We were already using `http-proxy`'s WebSockets option, but we were missing a step! In addition to setting `{ws: true}`, you must also forward WebSocket upgrade events from the front-facing server to the proxy. [(See this example.)](https://github.com/http-party/node-http-proxy#proxying-websockets)
Previously, the proxy server and client _would_ mutually agree to "upgrade" their connection (because we set `{ws: true}`)… but then, when the client would start sending WebSocket data instead of HTTP data, our front-facing server would drop it, because we hadn't configured a place for it to go.
In this change, we configure `this.server` to forward its `upgrade` events to the proxy server.
We also refactor `proxyPass` to use the new shared `this.proxy` instance responsible for the `upgrade` events, instead of creating a new proxy instance for every request. This isn't strictly necessary, but a helpful simplification to clarify that there's no specific reason for the proxy instances to be _different_ than the instance that manages WebSocket upgrades!
This fixes#3451: CRA apps can now auto-refresh when the source code changes, and Firefox can now load the app without crashing on the 6th attempt.
Co-authored-by: Steven <steven@ceriously.com>
* Add initial changes for grouping lambdas
* Handle more cases and clean up some stuff
* Remove logs from debugging
* Remove changes from testing and add page layers
* Update output tests
* Move new behavior behind flag
* Add separate tests for new behavior
* Clean-up style diffs
* Update error
* Update to separate out new behavior more
* Apply suggestions from review
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
* Add test to frameworks
* Add example for Docusaurus v2
* Add example for ionic-angular
* Update READMEs
* Use existing versions
* Reset yarn.lock
* Add schema validation and add missing Scully.io logo
Write the generated `tsconfig.json` files that are required to do TypeScript type checking on a single file to the dev cache directory (`.vercel/cache`). This way, they are in a location that is gitignored by default, but still has `require()` access to the types that the project uses.
* `StartDevServerOptions` had to be updated to include `meta`, at which point it's identical to `BuildOptions`, so just make it a type alias instead.
* Vercel CLI is updated to pass in the `meta` object to `startDevServer`
* Vercel CLI is updated to create the `.vercel/cache` dir upon startup, if it does not already exist
* `@vercel/node` now creates the tsconfig files in the dev cache directory, using the `wx` write flags. This ensures that the file is only created once and then cached in the dev cache dir.
An example of a generated tsconfig file for endpoint `api/foo.ts`:
```json
{
"extends": "../../tsconfig.json",
"include": ["../../api/foo.ts"]
}
```
To keep the `lerna` monorepo version pinning intact.
It should have been updated in c23b9ccd1d, but was not because the commit was created manually instead of with `lerna`.
Starting with version 18.0.0, there was a regression from ##3980 causing the deploy command to hang indefinitely at the file tree building stage. I triaged the issue to be that the call of `recursive-readdir` was now walking through my `node_modules` folder. This is an issue in my environment since I have a very intricate monorepo with circular symlinks in my node_modules, which causes `recursive-readdir` to go into an infinite loop.
This PR fixes this in 2 commits:
1) The first commit refactors out the file tree building logic into separate utility functions and adds unit tests to verify the expected behavior of not walking through `node_modules` (this commit's unit test run should fail as seen in checks on this PR). This commit does not change any behavior.
2) The second commit fixes the actual issue (causing the unit tests to pass again). When I was bisecting the issue between the 17.0.0 and 18.0.0 tags I noticed that trailing slashes were added to the default ignore's directory entries in `getVercelIgnore()`. I removed them to bring it back to how it was done in v17.0.0 and it resolved the issue.
Hopefully with the added unit tests this shouldn't regress in the future.
Co-authored-by: Steven <steven@ceriously.com>
* [now-node-bridge] Catch invalid HTTP request headers
In some rare cases, the proxy layer passes what Node.js considers an
invalid HTTP request header causing the `http.request()` function to
throw an error, such as:
```
TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["cookie"]
```
So instead, use `req.setHeader()` API with try/catch to skip invalid
HTTP headers and print a message for the deployment logs with debugging
information. This way, the HTTP request will still go through, with
a missing header, rather than causing the whole function to 500.
* Add test
* Don't use `typeof`
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This PR improves the error message when a user provides an invalid pattern in package.json `engines` field.
## Before
```
TypeError: Invalid comparator: => 10
at Comparator.module.exports.Comparator.parse (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10262:11)
at new Comparator (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10245:8)
at Range.<anonymous> (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10439:12)
at Array.map (<anonymous>)
at Range.module.exports.Range.parseRange (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10438:13)
at Range.<anonymous> (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10381:17)
at Array.map (<anonymous>)
at new Range (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10380:40)
at Function.intersects (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10998:8)
at /zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:25847:29
```
## After
```
Found `engines` in `package.json` with an invalid Node.js version range: "=> 10".
Please set "engines": { "node": "12.x" } in your `package.json` file to upgrade to Node.js 12.
More details: https://vercel.com/docs/runtimes#official-runtimes/node-js/node-js-version
```
In this case, the `=>` operator is not valid so the user probably meant `>=` but we only suggest the `10.x` or `12.x` syntax because we can only guarantee a major version.
This PR fixes the scenario when a user adds an environment variable to a project but then deletes the secret associated with the environment variable.
For example:
```sh
echo 'foo' | vc env add FOO development
vc secrets rm foo-development-v1ln
vc env pull # would error with 404 every time
vc env rm FOO development # would error with 404 the first time
```
Now we'll warn for `vc env pull` and we will assume success for `vc env rm`.
Fixes https://sentry.io/organizations/zeithq/issues/1612188511/
Fixes https://sentry.io/organizations/zeithq/issues/1656997656/
* [client] Throw an error if both `.vercelignore` and `.nowignore` exist
* Remove `.`
* Add tests
* Update test
* [cli] Properly clear spinner if `createDeployment()` async generator throws an error
* Update packages/now-client/src/utils/index.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/now-client/tests/vercelignore.test.ts
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Steven <steven@ceriously.com>
This PR fixes an issue where old versions of the CLI would update to the latest builder, but not have a copy of `@vercel/build-utils` because they only shipped with `@now/build-utils`. So in this case, we can fallback to the other package. We must be careful to only import types from `@vercel/build-utils` and anything needed at runtime must be imported from `./build-utils` wrapper.
This PR fixes an issue when the error message assumed the config was `vercel.json` even when the user had `now.json`.
### Before
```
Error! The property `foo` is not allowed in vercel.json – please remove it.
```
### After
```
Error! The property `foo` is not allowed in now.json – please remove it.
```
Co-authored-by: Nathan Rajlich <n@n8.io>
This PR fixes a regression from PR #4084 where secrets were paginated so some v1 deployments that had more than 20 secrets were unable to deploy since CLI version 19.
This PR adds two functions:
* `getTitleName()` - used to get the uppercase Vercel or Now package name, for example `vercel --version`
* `getCommandName()` - used to get the `vercel` command followed by subcommands, for example in error suggestions
Unset the `npm_config_registry` env var which yarn overwrites to the
yarn registry, which we don't want since the `.npmrc` file that gets
created is configured to the npm registry.
This PR adds a test for a deployment as well as `now dev` to ensure both `vercel.json` and `.vercelignore` are applied.
I also fixed the remaining test helpers to work with `vercel.json`.
* [now-build-utils] Use `@now` runtimes for zero-config
This is a temporary change until the `@vercel` runtimes work in
production.
* Temporary fix to E2E
Fixes a bug where `isOfficialRuntime('static', '@now/static-build')` was returning `true` when it should have been `false`.
And use the function from `@vercel/build-utils` in Vercel CLI.
We want to make sure the bin matches the [installed package name](https://docs.npmjs.com/files/package.json#bin).
This means `npm i -g now` will remain `now` and `npm i -g vercel` will use `vercel` as the binary name.
This allows support for different versions on one machine such as `npm i -g now@17 vercel@19` for example.
In addition, we will also install a shorthand `vc` so you can do `vc env pull` for example.
Added the following env vars, most are undocumented but its good to be consistent:
- `VERCEL_REGION`
- `VERCEL_DEBUG`
- `VERCEL_BUILDER_DEBUG`
- `VERCEL_TOKEN`
- `__VERCEL_SKIP_DEV_CMD`
I also updated the error code prefixes to remove `NOW_`.
There `code` isn't used anywhere, this is just to make it unique and a little shorter.
We renamed `.now` to `.vercel` in #4234 but still fallback to `.now` if it exists. This is because we don't want users to have to re-link all their existing projects. So we need to make sure that the Runtimes know which directory to use for caching. This PR introduces the `devCacheDir` for this purpose.
As you can see in https://github.com/zeit/now/runs/647945621,
the final step for publishing the legacy `@now` packages failed
with a 401 error from npm.
This additional logging an to attempt to debug why that is happening.
https://vercel.com/blog/zeit-is-now-vercel
* Updates all org packages from `@now` to `@vercel`
* Updates Now CLI package name from `now` to `vercel`
* Packages contains `"bin"` entries for _both_ `vercel` and `now` in the package.json
* Updates `now-client` package name to `@vercel/client` (org scoped, for authenticity)
There is also a new `publish-legacy.sh` script which ensures that all the legacy package names (i.e. `now`, `now-client`, `@now/node`, etc.) will still be published as well.
We will remove this legacy publishing logic on Jan 1, 2021.
This PR renames the CLI and config files to `vercel`.
https://vercel.com/blog/zeit-is-now-vercel
### Complete
- [x] Help menus and error messages should print cli name from `package.json`
- [x] `now.json` => `vercel.json`
- [x] `.nowignore` => `.vercelignore`
- [x] `~/.now` => `~/.vercel`
- [x] `<project>/.now/project.json` => `<project>/.vercel/project.json`
### TODO
I'm going to do the remaining work in a follow-up PR:
- [ ] `<project>/.now/cache` => `<project>/.vercel/cache` (Runtimes sometimes use this)
- [ ] `NOW_*` special cased environment variables
- [ ] `*.now.sh` special cased url suffix
This PR fixed a corner case when the user defined both `cleanUrls: true` and `trailingSlash: true` and then visited `/index.html` which would attempt to redirect to the invalid `//` path.
This PR fixes a bug where the headers were not applied when exiting with a status code such as 204.
This is a common pattern for CORS where you want `OPTIONS` method respond with 204 status due to a preflight request.
I also updated the test suite to support the `method` property and ensured a body with empty string is asserted.
As discussed this updates to leverage the new named regexes and route keys output in the `routes-manifest.json` to pass the dyname page values in the query to ensure we're handling edge cases with the new custom routes support
Note: the `yarnPreferOffline` change is unrelated and was added to make debugging easier as the build can fail when using this option and the cache is invalid for some packages.
x-ref: https://github.com/zeit/next.js/pull/12250
In PR #3514, we added a `/api` directory for functions and a `/public` directory which was created at build time.
This moves the build script to be `now-build` so we don't don't need to build everything in the repo and also no longer need to special case the git env vars.
This PR makes sure that all the `now dev` tests have a corresponding deployment and each assert is also compared to the deployment.
If you want to opt-out of this behavior, for example a test that is meant for specific dev functionality, then there is an option `skipDeploy: true`.
This also fixes a bug where headers were not assigned during proxying to a dev server.
Using `ts-node`, with asynchronous type checking via `tsc --no-emit`.
This also removes `ncc` of `typescript` during the build in favor of
having typescript be a regular npm "dependency".
Noticed that we still say `Zeit` while using the now cli.
The inspect command still points to zeit.co when I tested it some hours ago but that seems to be fixed already 😄
This was switched to `npm` for debugging purposes in #4124, but at this
point we can switch it back to `yarn` so the tests don't take as long.
Co-authored-by: Leo Lamprecht <leo@zeit.co>
As a follow up to #4178, this fixes the final lint errors so we can run in CI.
Since lint is very quick, about 8 seconds, we can run it on the entire repo instead of only changed files.
I also disabled a couple rules that were leading to 500 warnings we would likely never change.
It's not useful information and distracts from whatever the actual error
message was from the dev server, which is what the user is actually
interested in.
This updates the error message shown when we fail to load the `routes-manifest` which appears to be happening most often when an incorrect output directory is configured for a Next.js application
Rather than creating a `builders.tar.gz` file with the core Runtimes and
bundling that tarball with Now CLI, simply have them be regular npm
dependencies so that they are installed into Now CLI's `node_modules`
directory.
When one of the core runtimes is specified for a build, the runtime will be
required as a regular module dependency of Now CLI, and the builders cache
will never touched.
Bundled runtimes are also no longer updated, making the runtime versions
pinned to the version of Now CLI.
Logic for the builders cache directory still remains, but will now only be
used when using a Community Runtime (or development tarball URL).
The previous file path for ncc isn't always reliable during development,
depending on which directory `yarn` is invoked in inside the monorepo.
Using `npx` ensures the version specified in the now-cli `package.json`
is used even if it's installed at the root of the monorepo.
When Now CLI 17 introduce the `.now` directory with project settings, it started assuming that the current project scope should be used for all commands. This made `now switch` do nothing unless you changed the current directory.
This PR is a _major_ semver change so that the only commands that inherit the project settings are:
- `now deploy`
- `now dev`
- `now env`
For example, `now ls` will not observe project settings and instead observe `now switch`.
`now dev` integration tests have been failing as of recently with failures to require Runtime builders from the builder cache. Upon investigation, it turns out that the `builders.tar.gz` file was not being completely extracted since the integration tests complete quickly and then kill the Now CLI process, which has not yet completed the extraction.
Fix is to ensure the tarball extraction promise is fully resolved before cleanly shutting down.
Also now applying the clean shutdown logic upon `SIGTERM` signal, which is what the integration tests send to shut down the Now CLI process.
After #4024 was merged, I tested and still got the same error. I searched around and found that the lines of code are in wrong order (ref: https://bugs.python.org/issue37521). So this is the proper fix.
Co-authored-by: Steven <steven@ceriously.com>
Stop downloading and caching `yarn` from GitHub Releases in `now dev`,
and instead simply rely on the user having `npm` installed. The user is
extremely likely to have `npm`, since Now CLI now requires `node` to be
installed (no longer using `pkg`) which comes with `npm` bundled by
default.
DRY and removes the `pid` from the set immediately so there's no race
condition if the server is shut down shortly after an HTTP request
(like in the tests).
Previously, when `package-lock.json` was detected, we would always use `npm install`.
This PR changes the behavior to the following:
- If only `package-lock.json` is detected, we use `npm install`.
- If both `package-lock.json` and `yarn.lock` are detected, use `yarn install`.
This will avoid npm bugs such as `npm ERR! Cannot read property 'match' of undefined`.
- Print an error instead of throwing when `destination` has segment not found in `source`
- Update docs to explain how to fix this error
- Add a couple tests
- Update uncaught `path-to-regexp` error message to print the full route that caused the error
This is an extension to the Runtime API, where a runtime can optionally define a `startDevServer()` function which is responsible for spawning a single-serve dev server for an individual HTTP request (the dev server is booted up upon receiving an HTTP request, and gets shut down by `now dev` after the HTTP request is completed). For runtimes that define this function, the `build()` function will never be executed, which avoids a lot of unnecessary processing for a dev environment.
Some things this accomplishes:
* Retains the proper stack trace for errors.
* Ensures that if a source code file is changed, and then an HTTP request is sent, it's guaranteed to be using the latest code (no file watching, or re-compilations).
* Avoids creating a Lambda zip file (just to immediately unpack it for dev).
* Avoids `@zeit/fun` completely, which loses some "correctness" (i.e. function is not frozen in between requests).
* Backwards compatible with older Now CLIs - versions that don't know about `startDevServer()` will just invoke `build()`, and there's no version change required in the Runtime.
The `runNpmInstall()` function is already a no-op when invoked via `now dev` (#2926), however the "Installing" message was still being printed, leading to confusion about whether or not they actually are (they're not).
This fixes the static 404 page not being used when deploying in a mono-repo structure. Before we weren't taking into account the `entryDirectory` where we needed to causing us to deploy `_error` when we didn't need to
x-ref: https://github.com/zeit/now/discussions/4077#discussioncomment-4625
The `public` directory was missing from the `ionic-react` example because we were ignoring all `public` directories.
This PR adds the public directory back (it is copied from now-static-build test fixtures). I also updated `.gitignore` and `.gitattributes` to be a little more friendly to our test fixtures so this doesn't happen again.
- Capitalize `Environment` in all outputs
- Fix stdin detection so there is no need for timeouts
- Dont throw if the error is bad user input, only throw for unexpected errors
- Fix tests so waiting for prompt will throw if expected output is never received
The latest `now env` subcommand no longer makes the distinction between build time and runtime environment variables so this PR updates `now dev` to no longer make the distinction either.
The only exception is that some builders such as `@now/next` might still rely on the separation so we must preserve the distinction for legacy builders.
This PR adds support for empty values when using `now env add|ls|rm|pull`.
This is necessary when using system environment variables such as `NOW_GITHUB_COMMIT_SHA` which will not receive a value from the user but will instead assign a value automatically during deployment.
Without this fix, Python app which uses [Pydantic](https://pydantic-docs.helpmanual.io/usage/postponed_annotations/) for data validation will crash with log like this:
```py
File "pydantic/main.py", line 175, in pydantic.main.ModelMetaclass.__new__
annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None))
File "pydantic/typing.py", line 136, in pydantic.typing.resolve_annotations
annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None))
File "pydantic/typing.py", line 136, in pydantic.typing.resolve_annotations
base_globals: Optional[Dict[str, Any]] = sys.modules[module_name].__dict__
KeyError: 'api.main'
```
The added code also follow Python official documentation: https://docs.python.org/3.6/library/importlib.html#importing-a-source-file-directly
This PR does a few things:
- Change `dev.unref()` when possible and use `testFixtureStdio` instead
- Replace `fetch()` with `fetchWithRetry()` when possible
- Remove commented-out tests
There was a bug preventing `continue: true` from working between (null => filesystem) phases.
This PR fixes that bug and adds a test to ensure users can rewrite to dynamic path segments.
This PR adds framework config for Ionic Angular and also updates a mistake found in the dev script of Ionic React, which mistakenly was using the same dev script as Stencil.
This PR adds a new command `now env` for managing environment variables for a given project. This will complement the changes in the Dashboard and will provide 3 possible environments: `production`, `preview`, and `development`.
- [x] Add `now env ls`
- [x] Add `now env add`
- [x] Add `now env rm`
- [x] Add `now env pull`
- [x] Add test for `now env ls`
- [x] Add test for `now env add`
- [x] Add test for `now env rm -y`
- [x] Add test for `now env pull -y`
- [x] Add test for `now env add FOO preview < secret.txt`
- [x] Add test deployment to verify env var is assigned to both build and runtime
- [x] Test on Windows
```
▲ now env [options] <command>
Commands:
ls [environment] List all variables for the specified environment
add [name] [environment] Add an environment variable (see examples below)
rm [name] [environment] Remove an environment variable (see examples below)
pull [filename] Read development environment from the cloud and write to a file [.env]
Options:
-h, --help Output usage information
-A FILE, --local-config=FILE Path to the local `now.json` file
-Q DIR, --global-config=DIR Path to the global `.now` directory
-d, --debug Debug mode [off]
-t TOKEN, --token=TOKEN Login token
Examples:
– Add a new variable to multiple environments
$ now env add <name>
$ now env add API_TOKEN
– Add a new variable for a specific environment
$ now env add <name> <production | preview | development>
$ now env add DB_CONNECTION production
– Add a new environment variable from stdin
$ cat <file> | now env add <name> <production | preview | development>
$ cat ~/.npmrc | now env add NPM_RC preview
$ now env add DB_PASS production < secret.txt
– Remove a variable from multiple environments
$ now env rm <name>
$ now env rm API_TOKEN
– Remove a variable from a specific environment
$ now env rm <name> <production | preview | development>
$ now env rm NPM_RC preview
```
Some inputs cause `compile()` to throw but its not clear which route caused it to fail.
> TypeError: Unexpected MODIFIER at 29, expected END [see source](https://sentry.io/organizations/zeithq/issues/1593291118/?project=1351065)
This PR adds logs so we can see the bad user input and correct accordingly.
Since enabling `CI` environment variable for cloud builds, this test fails because it is meant to emit a warning however that warning has turned into an error.
```
05:40:53.148 Treating warnings as errors because process.env.CI = true.
05:40:53.148 Most CI servers set it automatically.
05:40:53.148 Failed to compile.
05:40:53.149 ./src/App.js
05:40:53.149 Line 1: 'useState' is defined but never used no-unused-vars
05:40:53.172 error Command failed with exit code 1.
```
We can again treat lint errors as warnings by setting `CI=false`.
Example build output given a user's build script named `shouldfail.js`:
## Before
```
/zeit/4af70cdc/shouldfail.js:3
throw new Error('This is my failure')
^
Error: This is my failure
at Object.<anonymous> (/zeit/4af70cdc/shouldfail.js:3:7)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Exited with 1
at ChildProcess.<anonymous> (/zeit/687b1c64/.build-utils/node_modules/@now/build-utils/dist/index.js:31350:24)
at ChildProcess.emit (events.js:223:5)
at ChildProcess.EventEmitter.emit (domain.js:475:20)
at maybeClose (internal/child_process.js:1021:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
worker exited with code 20 and signal null
Done with "package.json"
```
## After
```
/zeit/255bfdd/shouldfail.js:3
throw new Error('This is my failure')
^
Error: This is my failure
at Object.<anonymous> (/zeit/255bfdd/shouldfail.js:3:7)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Command "yarn run build" exited with 1
worker exited with code 20 and signal null
Done with "package.json"
```
The current error message prints a link that is not clickable from the terminal.
This PR adds the missing `https://` protocol prefix, so that the link is clickable.
This fixes the error when attempting to add a secret with a hyphen and underscore such as the following:
```
$ now secret add name '-foo_bar'
Error! argv._.slice is not a function
```
As discussed this removes automatically adding path segments to redirect's destination query and only adds them if manually specified
x-ref: https://github.com/zeit/next.js/pull/11497
We already ignore specific files such as `node_modules` and `.env` during the upload phase so these never make it to the build. However, if those files are generated during the build, that are still emitted.
This PR will ignore these specific files even if they end up in the output directory (for example, when the user assigns `outputDirectory='.'` in project settings)
Somehow, PR #3973 broke Go since the bridge is imported from this repo's master branch.
Go has very strict file name constraints and the file `[...path].js` is not compatible.
Here's what a `@now/go` deployment error message looks like:
```
Error: Command failed: go mod tidy
go: finding github.com/zeit/now latest
go: downloading github.com/zeit/now v0.0.0-20200326223129-c91495338d5e
go: extracting github.com/zeit/now v0.0.0-20200326223129-c91495338d5e
-> unzip /tmp/5a0676f5/pkg/mod/cache/download/github.com/zeit/now/@v/v0.0.0-20200326223129-c91495338d5e.zip: malformed file path "packages/now-next/test/fixtures/22-ssg-v2-catchall/pages/[...path].js": double dot
handler imports
github.com/zeit/now/utils/go/bridge: unzip /tmp/5a0676f5/pkg/mod/cache/download/github.com/zeit/now/@v/v0.0.0-20200326223129-c91495338d5e.zip: malformed file path "packages/now-next/test/fixtures/22-ssg-v2-catchall/pages/[...path].js": double dot
```
The solution is to move Go Bridge into a separate repository: https://github.com/zeit/now-go-bridge
This will also have the side effect of speeding up Go imports because the repo will be much smaller.
@tootallnate's bug fix for `SIGHUB` on Windows has been merged and
published as `signal-exit@3.0.3`, so no more need for the "resolutions"
field in `package.json`.
The `yarn.lock` file has been updated accordingly.
When using a catch-all route at the base of the project it would cause it to be prioritized over any GS(S)P `/_next/data` routes. This fixes the order putting `/_next/data` routes first as they have higher specificity and adds tests to ensure we don't regress on this
Fixes an issue with a dependency that was bumped but typescript was pinned in `ionic-react`.
```
$ react-scripts build
Creating an optimized production build...
Failed to compile.
/zeit/333ecfab/node_modules/@types/testing-library__react/node_modules/pretty-format/build/index.d.ts
TypeScript error in /zeit/333ecfab/node_modules/@types/testing-library__react/node_modules/pretty-format/build/index.d.ts(7,13):
'=' expected. TS1005
5 | * LICENSE file in the root directory of this source tree.
6 | */
> 7 | import type * as PrettyFormat from './types';
| ^
8 | /**
9 | * Returns a presentation string of your `val` object
10 | * @param val any potential JavaScript object
error Command failed with exit code 1.
```
This PR does a few things:
- Separate tests into multiple workflows
- Rename a few package.json scripts to make naming consistent
- Rename workflows to be uppercase and jobs to be lowercase
The benefits here are:
- Restart a workflow if it fails, for example only restart `now dev` tests
- Easier to read when we need to understand a workflow or modify env vars
After merging, we'll need to modify the required checks in the repo settings.
We'll also need to update the cancel workflow (that will need to be a separate PR).
This updates the error message to offer action items when an ambiguous argument is provided.
## Before
```
Error! The supplied argument "secrets" is ambiguous. Both a directory and a subcommand are known
```
## After
```
Error! The supplied argument "secrets" is ambiguous.
If you wish to deploy the subdirectory "secrets", first run "cd secrets".
If you wish to use the subcommand "secrets", use "secret" instead.
```
- Change default version to Ruby `2.7.x` to match our static builds such as jekyll
- Detect ruby version in `Gemfile` in case the user wishes to downgrade to Ruby `2.5.x`
- Print nicer error message in `now dev`
cc @nathancahill @m5o
We recently updated the build image to add the necessary dependencies so that `puppeteer` can run during the build step.
This PR adds a test that takes a screenshot and prints metrics during a static build.
This is necessary to support `react-snap` (along with a few flags in `package.json`).
```json
{
"reactSnap": {
"puppeteerArgs": [
"--no-sandbox",
"--disable-setuid-sandbox"
]
}
}
```
- Fixes https://github.com/zeit/now-builders/issues/517
- Fixes#2357
https://zeit.atlassian.net/browse/PRODUCT-1380
This makes `now-next` consider the `node_modules/.bin` path if a custom build command was specified, which makes it work like `now-static-build`.
This PR updates API Errors to support the `error.link` property.
Unlike `error.slug` which is only a path to an error message, `error.link` contains the full URL.
### Example Output
```
$ now
Error! Serverless Functions.........etc
> More details: https://zeit.ink/...etc
```
This PR updates the way we run integration tests (the ones that create test deployments) so that it will be less likely to fail.
A couple side effects to this PR:
- To run the tests locally, you must set `NOW_TOKEN` env var (can be found in `~/.now/auth.json`).
- PRs from forked repos won't run tests because they now rely on a secret in GH Actions.
- A couple alias tests that require certs need to be disabled because they will fail.
[PRODUCT-2093]
[PRODUCT-2093]: https://zeit.atlassian.net/browse/PRODUCT-2093
"ESRCH" error means that the process is no longer running, and thus
already shut down. No need to throw in that case so just ignore the
error.
Fixes: https://sentry.io/organizations/zeithq/issues/1568104652
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Fixes test warnings from `jest-hast-map`:
```
[now-static-build] Running yarn test-integration-once
$ jest --env node --verbose --runInBand test/integration.test.js
jest-haste-map: Haste module naming collision: 12-create-react-app
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/12-create-react-app/package.json
* <rootDir>/test/fixtures/26-ejected-cra/package.json
jest-haste-map: Haste module naming collision: gatsby-starter-default
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/10-gatsby/package.json
* <rootDir>/test/fixtures/10-gatsby-without-build-script/package.json
jest-haste-map: Haste module naming collision: gohugo-default-theme
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/31-hugo/themes/ananke/package.json
* <rootDir>/test/fixtures/46-hugo-with-framework/themes/ananke/package.json
jest-haste-map: Haste module naming collision: gohugo-default-styles
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/31-hugo/themes/ananke/src/package.json
* <rootDir>/test/fixtures/46-hugo-with-framework/themes/ananke/src/package.json
jest-haste-map: Haste module naming collision: 47-nuxt-with-custom-output
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/47-nuxt-with-custom-output/package.json
* <rootDir>/test/fixtures/48-nuxt-without-framework/package.json
```
Also increased test retry to 5.
These examples were using an old version of Bundler which didn't match our tests and would fail with:
```
/ruby27/lib/ruby/2.7.0/rubygems.rb:275:in `find_spec_for_exe': Could not find 'bundler' (1.17.2) required by your /zeit/6f4b9e46/Gemfile.lock. (Gem::GemNotFoundException)
To update to the latest version installed on your system, run `bundle update --bundler`.
To install the missing version, run `gem install bundler:1.17.2`
from /ruby27/lib/ruby/2.7.0/rubygems.rb:294:in `activate_bin_path'
from /ruby27/bin/bundle:23:in `<main>'
```
I ran `bundle update --bundler` in each of these directories and it only updated the version in `Gemfile.lock` because 2.x is mostly backwards compatible.
This PR improves the error message and prevents "An unexpected error occurred" when the token is invalid during a project link step.
I also added the `--token` option to `now dev --help` .
Lastly, I updated `now logout` to work correctly when the token is invalid.
- Fixes#3772
- Fixes#3786
This implements the new handles from https://github.com/zeit/now/pull/3876 to allow us to ensure the proper order for `rewrites`, `redirects`, and `headers` in Next.js. I also added in the tests from the Next.js [custom-routes test suite](https://github.com/zeit/next.js/tree/canary/test/integration/custom-routes) to ensure we're matching behavior.
To help keep track of what each probe is testing I added support for parsing the `now.json` files in `testDeployment` as [JSON5](https://www.npmjs.com/package/json5) to allow adding comments before each probe. If this is undesired I can remove this specific change even though it makes managing the fixture tests much easier
When running a framework like Create React App or Gridsome, the console gets cleared. This prevented the user from seeing the message printed from `now dev` which is typically `http://localhost:3000`. Instead the user would see the framework's URL such as `http://localhost:54684`.
See #3497 for an example.
The solution is to change the child process to pipe stdout/stderr. Since most frameworks detect [`process.stdout.isTTY`](7e6d6cd05f/packages/react-scripts/scripts/start.js (L141-L143)) before clearing the console, this will solve the problem. I was also able to intercept stdout to replace the framework's port with the `now dev` port and I think this will also help prevent confusion.
I also had to set `FORCE_COLOR=1` to avoid losing ANSI colors.
- Related to https://github.com/facebook/create-react-app/issues/2495
- Fixes#3497
When we ask the question "In which directory is your code located?" we were displaying a prefix of `cwd/` which is confusing because it seems like you are supposed to type in the current directory. It also doesn't match what is displayed in the Project Settings after it is deployed.
This changes the prefix to `./` so that `rootDirectory` is set to the current directory and the user can type in a subdirectory if they wish such as `./packages/web` for example.
### Before
```
? Set up and deploy “~/Code/app”? [Y/n] y
? Which scope do you want to deploy to? Testing
? Link to existing project? [y/N] n
? What’s your project’s name? app
? In which directory is your code located? app/
```
### After
```
? Set up and deploy “~/Code/app”? [Y/n] y
? Which scope do you want to deploy to? Testing
? Link to existing project? [y/N] n
? What’s your project’s name? app
? In which directory is your code located? ./
```
In PR #3847 we fixed a bug that prevented installing `devDependencies` when `NODE_ENV=production` this is typically what users want, but there are some cases where a user may wish to skip installing `devDependencies`. For example, if you have more than 500 MB worth of dependencies.
This PR introduces `NPM_ONLY_PRODUCTION=1` which can be used to skip installing `devDependencies` in these rare cases. It is the equivalent of `npm install --production` or `yarn install --production`. There is also `npm install --only=production` for which this new env var gets its name.
#### References
- https://docs.npmjs.com/cli/install
- https://classic.yarnpkg.com/en/docs/cli/install/#toc-yarn-install-production-true-false
In Now CLI 17 when Next.js is detected, the `next dev` command is proxied from `now dev`.
This brings Next.js into alignment as other other frameworks such as Gatsby and CRA. But those other frameworks are building static websites, so we were only passing build time env vars. However, Next.js needs runtime env vars for APIs in `/pages/api`.
So the solution is to special case until Next.js can read these files directly. See https://github.com/zeit/next.js/pull/10525Fixes#3758
This adds support for the new internal `handle` types `error` and `rewrite` and also updates the error messages to be more verbose since additional keys are allowed when using `handle: 'error'`.
This is needed so that we can implement utilize the new handles in `@now/next` for the new custom-routes support
This PR adds issue templates for common cases:
- Bug Report - to be submitted through the ZEIT Now support form.
- Feature Request - to be handled as a discussion between the community and ZEIT staff.
- Ask a Question - to be posted in Discussions for all to answer.
In addition to this, the PR also removes the Spectrum link from the README.
Fixes a regression in #3847 which was preventing the user from assigning `NODE_ENV`.
The root cause was that the spread operator (`...`) performs a shallow clone, not a deep clone. So we must perform another spread to clone the user-provided `env` object before deleting `NODE_ENV` during `npm install`.
The code coverage report stopped uploading after we switched to GitHub Actions because its not a recognized CI provider.
This PR adds a secret with the code coverage token from [codecov.io](https://codecov.io/gh/zeit/now/settings).
This PR changes the behavior of error reporting and metrics so that developers who build and run Now CLI locally won't accidentally report any metrics. It also prevents errors during CI tests from being reported.
The env vars are only assigned during the publishing step so that the official Now CLI hosted on npm is the only way to report metrics.
* add ruby ActiveSupport test fixture
> ActiveSupport is a Ruby module & a stand-alone component of Rails that includes additional functionality to core Ruby classes, like Array, String & Numeric.
🔗https://guides.rubyonrails.org/active_support_core_extensions.html
* add `Date.current + 10.years` calculation example
This fixes a bug in our `@now/build-utils` tests that pair the current build-utils with a stable builder. Since ncc was bundling `@now/build-utils`, we weren't able to configure a different version and these tests were not actually testing the correct version of build-utils.
A nice side-effect is that each builder will be about 50% smaller (compared by measuring `dist`).
* [now-next] Add Support for Prerender v2
* Copy test suite
* Test that fallback doesn't work for fallback: false
* record omitted lambdas
* Improve test case
* improve omitted routes logic
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Some build utilities and SSG Frameworks instruct users to set `NODE_ENV=production` which typically means updating `now.json` to the following:
```json
{
"build": {
"env": {
"NODE_ENV": "production"
}
}
}
```
The problem is that this environment variable is assigned during `npm install` or `yarn install` which is the equivalent of running install with the `--production` flag. This flag prevents `devDependencies` from installing. This is almost never what the user intends so they have to remove `now.json` and instead updating their build script to `NODE_ENV=production yarn build`.
This PR improves the experience by deleting `NODE_ENV` during the install step.
This PR fixes `@now/routing-utils` when the input routes are null. It used to return the empty array but now it will still append.
I also added many more tests to `@now/build-utils` when `featureHandleMiss: true` and refactored the code a bit to make dynamic routes and api routes a little more clear.
This PR refactors the rewrites (the dynamic routes as well as the route that prevents directory listing for zero config deployments) so they are not in the `handle: miss` phase.
This is necessary because the behavior of `handle: miss` will change in an upcoming release.
The solution is to separate these into `rewriteRoutes` that can then be merged properly with the user's routes. They will be appended to the `handle: filesystem` phase (or add the phase if it doesn't exist).
* [now-cli] Remove v1 "static build" integration tests
These are the last remaining v1 static type deployments being created.
* Remove from `integration.js` as well
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
There was a bug in `now-client` when deploying a directory that ends with a slash, for example `/Users/styfle/Code/myapp/` instead of the usual `/Users/styfle/Code/myapp`.
This never affected `now-cli` until we added support for defining the `rootDirectory` which allows the user to type whatever they wish in the Project Settings.
The fix is to use `path.relative()` instead of substring.
The combination of file renaming and brackets doesn't work well for go build so we need to add the file extension back before building.
I also simplified the `.now/cache/folder` logic because it should be the same whether `builds` is defined or not (aka zero config).
The combination of file renaming and brackets doesn't work well for python imports so we need too add the file extension back before importing the python module.
I also simplified the `.now/cache/folder` logic because it should be the same whether `builds` is defined or not (aka zero config).
This updates to not pass segments already used in a redirect's destination query since these values are most likely unwanted and can still be manually added if desired. This change does not affect rewrites and we still pass through all segments in the query
This adds handling for treating `pages/404.js` as the custom error page in Next.js to allow for more flexible auto static optimization on the 404 page. This makes sure we handle `pages/404.js` being a lambda due to `_app` having `getInitialProps` and also makes sure that visiting `/404` doesn't respond with a 200 status code
~We can add tests for this behavior after the below PR has been released in a canary of Next.js~
x-ref: https://github.com/zeit/next.js/pull/10329
x-ref: https://github.com/zeit/next.js/pull/10593
Bumps [codecov](https://github.com/codecov/codecov-node) from 3.1.0 to 3.6.5.
<details>
<summary>Release notes</summary>
*Sourced from [codecov's releases](https://github.com/codecov/codecov-node/releases).*
> ## v3.6.4
> Fix for Cirrus CI
>
> ## v3.6.3
> AWS Codebuild fixes + package updates
>
> ## v3.6.2
> command line args sanitised
>
> ## v3.6.1
> Fix for Semaphore
>
> ## v3.6.0
> AWS CodeBuild
> Semaphore v2
>
> ## v3.3.0
> Added pipe `--pipe`, `-l`
</details>
<details>
<summary>Commits</summary>
- See full diff in [compare view](https://github.com/codecov/codecov-node/commits)
</details>
<details>
<summary>Maintainer changes</summary>
This version was pushed to npm by [drazisil](https://www.npmjs.com/~drazisil), a new releaser for codecov since your current version.
</details>
<br />
[](https://help.github.com/articles/configuring-automated-security-fixes)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/zeit/now/network/alerts).
</details>
When testing, you can set `NOW_BUILDER_DEBUG=1` to print verbose logs from builders.
However, this was causing some tests to fail that depended on a build environment variable.
This PR fixes the assignment so that it preserves the environment variables from the tests by adding `NOW_BUILDER_DEBUG` instead of replacing.
This handles an edge case where deeply nested dynamic routes were handling `_next` 404s that were cached forever since the immutable header we set isn't cleared after not matching on the filesystem.
I updated our cache-header fixture to check for this edge case also to make sure we don't regress on this
Some users wish to put all Go related code in the `/api` directory and the root is reserved for a frontend framework.
This PR adds support for `/api/go.mod` which will act the same as `/go.mod` by moving the file to the root.
This adds support for using the fallback file for dynamic (lazy) SSG pages to allow showing a loading state while the cache is populated with data. We can add tests for this behavior once the below referenced PR is shipped on canary
x-ref: https://github.com/zeit/next.js/pull/10424
~Update: added tests now that fallback support has landed in Next.js although it appears `now-proxy` might need to be updated to revalidate the fallback correctly since the initial fallback is always being shown for lazy SSG pages with these changes~
Looks like this is working properly in `now-proxy` and we were overriding the prerender output with the static page output, thanks @juancampa for helping investigate! 🙏
Previously, `@now/go` would fail when using [Path Segments](https://zeit.co/docs/v2/serverless-functions/introduction#path-segments) since `go build` [doesn't support](https://stackoverflow.com/q/60140859/266535) files that begin with square bracket.
This PR changes the build logic so that the entrypoint file is renamed if if begins with a square bracket.
The output file is not renamed because v3 builders can't rename outputs which works great for this feature.
This adds initial support for Windows in GitHub Actions CI tests.
There is still work to be done to prevent certain tests from hanging in CI so those are skipped for now.
We used to require a `package.json` but we have since introduced [Advanced Project Settings](https://zeit.co/blog/advanced-project-settings) which will ask the user for a build command during the first deploy.
Updates go to the latest version 1.13.7 (https://golang.org/doc/devel/release.html#go1.13). This allows users to use the new error functionality that was introduced in go 1.13 (https://blog.golang.org/go1.13-errors) and also includes a couple of security fixes.
Looking at the last PR that updated the version (https://github.com/zeit/now-builders/pull/247/files) this should be as simple as updating the version number.
P.S. I tried to follow the contribution guidelines, but `yarn lint` fails with `exit code 1`/`295 problems (33 errors, 262 warnings)` and `yarn test` returns `error Command "test" not found` on master. But `yarn test-unit` shows no errors.
* [now-cli] Consider root directory for now.json
* Adjust message check in test
* Fallback if config does not exist as well
* Assign localConfig later and add debug
* Prefere now.json from root directory
* Comment
* Adjust test and add warning
This fixes a regression from #3749 where the PORT env var was removed. This is necessary so frameworks like create-react-app and gatsby can proxy to `now dev`.
Fixes#3761
Previously, the changelog script was looking for the last "Publish Stable" commit, but it should really be looking for the last Stable release of Now CLI.
This PR updates the changelog script so that it fetches the latest GH Release (which should be Now CLI) and then compares that to the HEAD.
This PR changes the behavior of `trailingSlash: true` after we received feedback that files should not be redirected with a trailing slash. This matches the behavior of `serve` and `serve-handler`.
### Examples
* `/index.html` => serve
* `/assets/style.css` => serve
* `/assets` => redirect to `/assets/`
* `/assets/style` => redirect to `/assets/style/`
### Additional
In order to avoid duplicate content, this PR also adds redirects to files without a trailing slash.
* `/about.html/` => redirect to `/about.html`
* `/assets/style.css/` => redirect to `/assets/style.css`
Fixes#3731
* use npx when available
* add --no-install
* replace $PORT and %PORT% in devCommand
* remove PORT from env variables
* replace more than one $PORT or %PORT%
* fix regex
The Hugo theme was lost when transferring from `zeit/now-examples` to `zeit/now`.
This PR fixes the `.gitignore` file to include the `dist` directory and override our root `.gitignore`.
* do not prompt for root directory when linked
* run tests
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Leo Lamprecht <mindrun@icloud.com>
Typically, Go tests are side-by-side with their source files in a `_test.go`.
The Go documentation says the following:
> To write a new test suite, create a file whose name ends _test.go that contains the TestXxx functions as described here. Put the file in the same package as the one being tested. The file will be excluded from regular package builds but will be included when the “go test” command is run. [View Docs](https://golang.org/pkg/testing/)
This PR excludes the test files from being turned into Serverless Functions.
This PR is a follow up to #3703 which fixes file output renaming on initial boot but not when files are added or removed while `now dev` is running. This PR fixes that behavior.
Fixes GH pull request auto-lint:
> #### Check warning on line 2 in `packages/now-cli/src/util/input/input-root-directory.ts`:
>
> ## GitHub Actions / Unit Tests (ubuntu-latest, 12)
>
> `packages/now-cli/src/util/input/input-root-directory.ts#L2`
>
> ```
> 'fs' is defined but never used
> ```
This PR adds a `config.excludeFiles` pattern for `@now/python` that defaults to `node_modules/**` for users who are using a Node.js SSG frontend with Python APIs backend.
If the user chooses, they can override to any glob pattern such as `{.cache,node_modules}/**`.
Related to #2830
Related to #3416
There was a bug where python src files were being renamed when it really should be the output files only.
This is a tricky bug because production deployments build all files first and then perform routing. So we simply rename lambda outputs with prod deployments. But `now dev` matches a request URL to a build before performing the build lazily so we have to rename source files.
The solution is to add both the original file name and the renamed file name in the `files` map so that it matches correctly but `zeit/fun` will still copy the original source files in the output correctly.
Routing will match on the extensionless file, the builder will use the file with extension (it doesn't know about file renaming), then the build results in a lambda output which is renamed to extensionless.
I added a test for `@now/python` and updated the `@now/bash` test.
Fixes#3638
* [now-cli] Add support for the `rootDirectory` property
* Only check if rootDirectory exists
* Add test
* Support now dev
* Use defaults
* Comment
* Normalize the path input
* Adjust test
* Remove .only
* Adjust more tests
* Adjust test
* Fix test
* Remove unused import
* Update packages/now-cli/src/util/validate-paths.ts
Co-Authored-By: Luc <luc.leray@gmail.com>
* Run check on normalized path
* Add more checks
* Change error message
* Use basename as prefix
* Use correct path when linking
* Update packages/now-cli/src/util/input/input-root-directory.ts
Co-Authored-By: Luc <luc.leray@gmail.com>
Co-authored-by: Luc <luc.leray@gmail.com>
* [tests] Run unit tests on ubuntu and macos
* Add back Node 10 for Now CLI Tests
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This enables case sensitive rewrites and redirects. It also changes the delimiter to `/` to match Next.js.
Unlike `routes` which were case insensitive, `rewrites` and `redirects` are case sensitive.
In the future, we may wish to add an option to toggle the sensitivity.
* use .now scope for commands
* add cache to getUser
* add cache on getTeams
* add cache for link
* refactor
* add error if NOW_ORG_ID is missing
* remove link cache
* refactor
* fix whoami
* add tests
* move fetching scope/org after subcommand condition
* Update packages/now-cli/src/util/projects/link.ts
Co-Authored-By: Andy <AndyBitz@users.noreply.github.com>
* remove userId from global scope
* show team and user in whoami command
* reset whoami
* Revert "move fetching scope/org after subcommand condition"
This reverts commit d145e6164074fe2442178cd8fafbeb225c978b9c.
* remove `client` from main scope
* tests adjustments
* adjust tests
* adjust tests (bis)
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This PR changes the behavior so that `:segment` in the `source` is always added to the query string unless the `destination` query string already contains a key with the same name.
* deprecate uploading files instead of erroring
* fix misc bugs
* remove final `.`
* add test
* check .now folder does not exist in test
* clean up after test
Deployments no longer support Node 8 since reaching EOL so we can also drop all of the special casing used to support Node 8 in Now CLI and Now Client.
The `tsconfig.json` has been updated to ES2018 per [Node-Target-Mapping](https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping).
* Checkout master on master
* Check if checkout works
* Revert "Check if checkout works"
This reverts commit 66f712a43edfb938c551110c214661e4a920b492.
* Revert "Checkout master on master"
This reverts commit 41b6eab926474830629e758a51e7cfdd1947bdf2.
* Use --depth=10
* Add another fetch
* Initial Build step
* Typo
* Remove circleci config
* Fix command
* Change Node version
* Add unit tests
* Use artifact
* Fix workflow file
* Remove node_modules
* Remove .git
* Do not upload files
* Checkout master branch
* Use git fetch
* Add now-dev tests
* Fix workflow file
* Use node10 for building
* Use node12 for building
* Download Hugo before building
* Fetch master branch
* Do not cancel other jobs when one fails
* Add all tests
* Remove needs
* Add build step
* Move test up
* Use isCanary function and remove tests
* Update Publish workflow
* Update .github/workflows/continuous-integration.yml
Co-Authored-By: Steven <steven@ceriously.com>
* Specify more events
* Add publish.sh script
* Remove Node8
Co-authored-by: Steven <steven@ceriously.com>
* [now-client][now-cli] Remove builds check from now-client
* [now-client] Adjust README and change version
* Change events and adjust build error
* Use message from error
* Update packages/now-cli/src/util/deploy/process-deployment.ts
Co-Authored-By: Luc <luc.leray@gmail.com>
* [now-cli] Rename event
* Make types more consistent
* Fix type in process-legacy-deployment
* Adjust type in test
* Update type
* Make events type simpler
Co-authored-by: Max <8418866+rdev@users.noreply.github.com>
Co-authored-by: Luc <luc.leray@gmail.com>
This PR a regression when path segments are used in the query string.
Take a look at the following ASCII Table for why I had to delete certain parts of the parsed url before formatting again.
https://nodejs.org/api/url.html#url_url_strings_and_url_objects
Related to #3539
This adds support for `headers` in custom-routes which was landed in Next.js.
This also updates `@now/routing-utils` `convertHeaders` to call `sourceToRegex` to match behavior with Next.js and allow using `segments` to match in the header `source` as not being able to use the same syntax for a header `source` as a `redirect` source could get confusing
This is required to match custom-routes behavior in Next.js by checking dynamic routes after each rewrite although is currently blocked on `now dev` also supporting the feature
This reverts commit 0da98a7f5d.
- [x] Add tests from now-proxy for `handle: miss`
- [x] Add tests from now-proxy for `handle: hit`
- [x] Add file output renaming when `featHandleMiss` is true (also assign true for now dev)
This adds initial support for static 404 pages when enabled for Next.js applications > `9.2.1-canary.3` it also disables tracing/logging related to lambdas when there aren't any lambdas besides the `_error` when a static 404 is being used
Closes: #3368
I was getting errors when running `yarn build` locally because the public directory already exists.
This will make sure the public directory is deleted before generating it again.
This adds `permanent: boolean` to the redirects in the custom-routes tests for `@now/next` since this field is required for redirects in Next.js in the latest version
unblocks: https://github.com/zeit/now/pull/3613
This PR adds `NOW_PROJECT_ID` and `NOW_ORG_ID` environment variables as a way to specify a project to deploy to when running `now`.
eg.
```
NOW_ORG_ID=abc NOW_PROJECT_ID=123 now
```
When using these environment variables:
- the folder is not linked to the project (ie. no `.now` is created)
- we interrupt the process and show an error message if the project is not found:

Since v2 deployments are auto-assigned aliases, render as such to match more closely to the v2 pipeline when a static deployments was implicitly upgraded to the v2 platform.
* [api] Add Sentry
* Use function name
* Add test error
* Revert "Add test error"
This reverts commit 39cf8a61dad9fcdcb616e418a0deb6ffe9e04ea9.
* Revert "Revert "Add test error""
This reverts commit c718f201da9d80743319ac87e0d4560e718fff53.
* Add logging
* Revert "Add logging"
This reverts commit 39cd46c8bbeef9024e71fe70478068480a51545b.
* Revert "Revert "Revert "Add test error"""
This reverts commit e6f63ee21fabb4ac8fc065b74281dbcdf5811216.
* Ignore .env
* Use init function for Sentry inline
* Print warnings / notices from the API
* Print `v2` instead of `v1` when upgraded to v2
* Wait for "alias-assigned" event in v1 pipeline when upgraded to v2
This PR updates the framework auto-detection flow in `deploy` command to not show "overwrite project settings?" prompt when the API returns a `framework` property that is `null`.
In a previous release, we pinned the node version to the project so that we could upgrade new projects to a newer version of Node.js while maintaining backwards compatibility with existing projects.
This puts some burden on the user when they're deployment is a year old and their pinned version of Node reaches EOL. Because we currently force the user to add a package.json.
This PR changes the behavior so projects are no longer pinned. Instead, newer deployments get the latest Node unless they opt-in and pin via package.json.
* fix "in your organization"
* add feedback link to canary version prompt
* `Detecting framework` -> `Setting up project`
* "Auto-detect project settings (<framework>)"
* "What’s your project’s name?"
* ✅ -> ☑️
* "organizations" -> "scope"
* always show feedback prompt for `now dev`
* dim feedback prompt
* [now-build-utils] Error for unused `functions`
* Update packages/now-build-utils/src/detect-builders.ts
Co-Authored-By: Steven <steven@ceriously.com>
Co-authored-by: Steven <steven@ceriously.com>
This behavior is legacy from the very early days of `now dev`
(before the `files` array was returned from Runtimes) and adds
complexity. We can remove it at this point to simplify dev server.
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Co-authored-by: Leo Lamprecht <mindrun@icloud.com>
* Revert "[frameworks] Fix import in test (#3570)"
This reverts commit 9ee86df69d.
* Revert "[frameworks] Rename frameworks to now-frameworks (#3569)"
This reverts commit daa5cbdd4b.
This PR fixes an issue where certain patterns caused `path-to-regexp` to throw when it should be returning an error object. The fix is to make sure all inputs work properly with `path-to-regexp` before continuing.
While migrating redirects on `/docs` I noticed we don't update segments in the `hash` of the destination. This updates to also handle these segments and adds a test for this behavior
* Add API for frameworks and examples
* Adjust headers
* Update frameworks list
* Always use latest
* Add types
* Use now repo for downloading and listing
* Use .existsSync
* Remove unused packages
* Use 307 for redirect
* Add examples
* Update tsconfig.json
Co-Authored-By: Steven <steven@ceriously.com>
* Make examples unique
* Remove detectors from frameworks API
* Use /api instead of Next.js
* Install dependencies
* Rename project
* Change name
* Empty
* Change name
* Update api/tsconfig.json
Co-Authored-By: Steven <steven@ceriously.com>
* Update examples
Co-authored-by: Steven <steven@ceriously.com>
This PR will use the system installed version of Node.js and avoid printing a warning or error if a discontinued version is selected.
This optimization was already in `@now/node` but for some reason it was never add to `@now/next`.
The reason why its relevant today is because the warnings turned into errors due to Node 8 deprecation and we don't have the "Project" in `now dev` so we don't know which version of node to select.
So instead of determining the version, `now dev` will always use `node` in the PATH and avoid printing warnings or errors. This also results in less FS reads since we no longer need to read package.json.
There was a regression with framework detection that was preferring the frameworks output directory instead of the `distDir` defined in the `@now/static-build`.
The fix is to only run framework detection when `builds` is not defined (ie zero config).
Related to https://github.com/Ebury/chameleon/pull/63
This extends the behavior of `featHandleMiss: true` flag to do the following:
- Reduce zero config API routes so that only dynamic path segment files (`api/[id].js`) get a route.
- Remove zero config out directory route (`public/`)—the files will be renamed instead.
- Use redirects for API routes when `cleanUrls: true` and use rewrites when `cleanUrls: false` from extension to the extension-less file.
- Normalize existing routes to begin with `^` and end with `$`.
This PR does the following
- Add and export class, `NowBuildError`, that can be thrown to stop the build and print an error but it will not print a stack trace.
- Improve logic for discontinued node versions and add more tests
- Remove hack (#3425) for undefined TERM, fixed by updating dependencies
- Rename `silent` variable to `isAuto` which means the node version was automatically selected, not defined in `package.json`
- Rename `test` deployments to `test2020` so that a fresh project is created with latest Node.js 12.x
We want to take advantage of the better defaults and retry policies (among others).
This bumps `@zeit/fetch` and replaces `node-fetch` with `@zeit/fetch` in `now-client`.
Also update retry policy for "uploading" files to:
- base 10ms
- 5 retries
- factor 6
which means the timeouts are 10, 60, 360, 2160, 12960
This PR does a few things:
1. Add functions `getLatestNodeVersion()` and `getOldestNodeVersion()` for use in api-project.
2. Add property `config.nodeVersion` which has precedence over default Node 8.
We want new projects to use the latest node version without setting any configuration but we don't want to break old projects. So during project creation, the value of `getLatestNodeVersion()` will be saved and then each deployment of that project will assign that value to `config.nodeVersion`.
Implements [PRODUCT-837]
[PRODUCT-837]: https://zeit.atlassian.net/browse/PRODUCT-837
This implements `{ handle: 'miss' }` which will allow more efficiently checking dynamic routes after a matching rewrite. This is not fully available in production yet and the tests will fail for this PR until it is ready in Now
x-ref: https://github.com/zeit/next.js/pull/9568
This handles the new `routes-manifest` version in the latest canary of Next.js since we throw an error if the version isn't handled by `@now/next`
unblocks: https://github.com/zeit/now/pull/3481
Bumps [handlebars](https://github.com/wycats/handlebars.js) from 4.1.2 to 4.5.3.
<details>
<summary>Changelog</summary>
*Sourced from [handlebars's changelog](https://github.com/wycats/handlebars.js/blob/master/release-notes.md).*
> ## v4.5.3 - November 18th, 2019
> Bugfixes:
>
> - fix: add "no-prototype-builtins" eslint-rule and fix all occurences - f7f05d7
> - fix: add more properties required to be enumerable - 1988878
>
> Chores / Build:
> - fix: use !== 0 instead of != 0 - c02b05f
> - add chai and dirty-chai and sinon, for cleaner test-assertions and spies,
> deprecate old assertion-methods - 93e284e, 886ba86, 0817dad, 93516a0
>
> Security:
>
> - The properties `__proto__`, `__defineGetter__`, `__defineSetter__` and `__lookupGetter__`
> have been added to the list of "properties that must be enumerable".
> If a property by that name is found and not enumerable on its parent,
> it will silently evaluate to `undefined`. This is done in both the compiled template and the "lookup"-helper.
> This will prevent new Remote-Code-Execution exploits that have been
> published recently.
>
> Compatibility notes:
>
> - Due to the security-fixes. The semantics of the templates using
> `__proto__`, `__defineGetter__`, `__defineSetter__` and `__lookupGetter__` in the respect that those expression now return
> `undefined` rather than their actual value from the proto.
> - The semantics have not changed in cases where the properties are enumerable, as in:
>
> ```js
> {
> __proto__: 'some string'
> }
> ```
>
> - The change may be breaking in that respect, but we still only
> increase the patch-version, because the incompatible use-cases
> are not intended, undocumented and far less important than fixing
> Remote-Code-Execution exploits on existing systems.
>
>
>
> [Commits](https://github.com/wycats/handlebars.js/compare/v4.5.2...v4.5.3)
>
> ## v4.5.2 - November 13th, 2019
> # Bugfixes
>
> - fix: use String(field) in lookup when checking for "constructor" - d541378
> - test: add fluent API for testing Handlebars - c2ac79c
>
> Compatibility notes:
> - no incompatibility are to be expected
></tr></table> ... (truncated)
</details>
<details>
<summary>Commits</summary>
- [`c819c8b`](c819c8b533) v4.5.3
- [`827c9d0`](827c9d0747) Update release notes
- [`f7f05d7`](f7f05d7558) fix: add "no-prototype-builtins" eslint-rule and fix all occurences
- [`1988878`](1988878087) fix: add more properties required to be enumerable
- [`886ba86`](886ba86c2f) test/chore: add chai/expect and sinon to "runtime"-environment
- [`0817dad`](0817dad7e7) test: add sinon as global variable to eslint in the specs
- [`93516a0`](93516a0b07) test: add sinon.js for spies, deprecate current assertions
- [`93e284e`](93e284ed9b) chore: add chai and dirty-chai for better test assertions
- [`c02b05f`](c02b05fa81) fix: use !== 0 instead of != 0
- [`8de121d`](8de121d21c) v4.5.2
- Additional commits viewable in [compare view](https://github.com/wycats/handlebars.js/compare/v4.1.2...v4.5.3)
</details>
<br />
[](https://help.github.com/articles/configuring-automated-security-fixes)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot ignore this [patch|minor|major] version` will close this PR and stop Dependabot creating any more for this minor/major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/zeit/now/network/alerts).
</details>
There is an undocumented feature that adds a route when a single file is deployed, for example a single image or a zip file. This was causing the legacy routes to be added even when `rewrites` or `redirects` was defined. This PR fixes that case when the user has a single file, `now.json`, with redirects defined.
* [now-build-utils] Only add 404 route when there are no api routes
* Fix startWith
* Update packages/now-build-utils/src/detect-routes.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Import isHandler
Co-authored-by: Steven <steven@ceriously.com>
This PR adds the route `handle: miss` and a catch-all route for the api directory.
The plan is to rename files in `/api` and `/public` (in a future PR) to be extension-less and then the route is only used to rewrite the extension to the extension-less file (for example, `/api/user.go` => `/api/user`)
This reduces the routes needed for zero config (previously N routes for N files down to 1 route for N files).
This PR deletes the incorrect `Route` type defined in `@now/build-utils` and instead relies on the correct type defined in `@now/routing-utils`. There is no change to runtime code since this is strictly a change to the typescript types. The one exception to this is I had to change the sort order for our build script so that `@now/routing-utils` is built first.
This is necessary for PR #3403
This makes sure to replace multi-match characters used in `path-to-regexp` when converting redirects.
Fixes `/:path*/` being converted to `/$1*/` and now converts it to `/$1/`
As requested by @timneutkens after investigating we're disabling auto running `next export` for the user during a build since most users who want their app exported will define `next export` in their `build` script
* Adjust README
* Fix now-dev test
* Add hugo to the PATH
* Fix Hugo build
* Add more logging
* Resolve path
* Do not use the build script as dev command
* Update yarn.lock file
* fetch with retry
* Remove sh from README
* Use Set for Hugo config files
* Revert "Revert "[now-static-build] Add support `buildCommand`, `devCommand` and `outputDirectory` (#3422)" (#3428)"
This reverts commit f7b4dd4458.
* Handle generic node projects with /public
* Remove .only
* Ensure node_modules/.bin is also available during `now dev`
* Remove config log
* Adjust test
* Fix integration tests
* Fix public check
* Remove build + public
* Remove _scan
* Remove any casting
* Use `spawnCommand` for dev
* Remove unused import
* Remove cross-spawn
* Fix null config
* Fix build
* Only do a single Buffer.concat
Follow up to #3431 adding tests for this behavior
Tests to add:
- [x] custom routes: redirects
- [x] custom routes: rewrites
- [x] confirming each test is actually a `next export` deploy somehow
* [now-static-build] Handle `buildCommand`, `devCommand` and `outputDirectory`
* Adjust tests
* Swap order
* Add `node_modules/.bin` to PATH
* Remove @types/execa
* Append PATH only to spawn options
* Remove test check
* Only add when there is a command
This PR reduces the time running Circle CI tests.
Since creating the monorepo in #2812, the coverage broke and then was fixed in #2876 with a workaround which would run unit tests twice.
More recently, we enabled Now CLI to always run tests in #3305 so that means coverage data is always generated.
This PR is a final proper fix so that unit tests run once which saves approximately 2 minutes per push (CI workflow).
We used to have a default `maxLambdaSize` and allow the user to increase to 50 MB.
However, this is no longer true. Today, the `maxLambdaSize` for every function is 50 MB and is not configurable, it's a hard limit.
This PR removes the dead link to avoid confusion like in Issue #3416.
* [now-build-utils] Consider `yarn build` and `npm run build` as `buildCommand`
* [@now/build-utils] Update new detectors
* Update unit tests
* [@now/build-utils] Update detect-builder and detect-routes
* Update tests
* Run prettier
* Add more tests
* [now-cli] Use default detectors
* Add now-dev test
* Add a generic node project fallback
* Fix build
* Use public as default
* Ensure generic node project is last
* Update tests
* Update tests again
* Update packages/now-build-utils/src/detectors/filesystem.ts
Co-Authored-By: Nathan Rajlich <n@n8.io>
* Remove parentheses
* Revert "Remove parentheses"
This reverts commit 03f9aba07b0a6d4088719ca9afd602ce8fb1e9c1.
* Use getDependencyVersion instead of hasDependency
* [@now/build-utils] Add functions schema
* [now-cli] Use functions schema from build-utils
* Move buildsSchema to build-utils
* Add retries to test
* Add await
Follow up to #3408 .
```
> Error! Checking for updates failed
> Now CLI 16.6.3 dev (beta) — https://zeit.co/feedback/dev
> Error! Invalid `functions` property: ['api/test.js'] should NOT have additional properties
```
This PR adds a `discontinueDate` to Node 8 and prints a warning if the current deployment is using it.
```
┌──────────────────────────────────────────────────────────────────────────────────────────────┐
│ │
│ WARNING │
│ │
│ Node.js 8.10.x will be discontinued on 2020-01-06. │
│ Deployments created on or after 2020-01-06 will fail to build. │
│ Please use one of the following supported `engines` in `package.json`: ["12.x","10.x"] │
│ This change is a result of a decision made by an upstream infrastructure provider (AWS). │
│ Read more: https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html │
│ │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
```
Starting January 2020, Node 8 deployments will fail to build and print an error.
```
Found `engines` in `package.json` with an unsupported Node.js version range: 8.10.x
Please use one of the following supported ranges: ["12.x","10.x"]
```
[PRODUCT-796]
[PRODUCT-796]: https://zeit.atlassian.net/browse/PRODUCT-796
Before, the debug log message "Downloading user files..." was copy+pasted to all the builders.
This change centralizes that log message to be inside the `download()` function for consistency and DRY purposes.
Additionally, the wording has changed as per [INFRA-289], and a resulting timestamp message is also printed.
[INFRA-289]: https://zeit.atlassian.net/browse/INFRA-289
Before this change, in `@now/next` when running via `now dev`,
the runtime env vars get passed to the child `dev-server.js`
process via argv.
This is problematic because it causes the env vars to be visible in
the process listing, and also causes the command itself to be very
large.
In some cases, with a lot of env vars, we've seen the command be too
large and it will fail to spawn (https://serverfault.com/a/163390/294389).
This changes the start-up process such that the env vars are passed
in via Node.js `fork()` IPC, rather than via `argv`.
Saw my `pre-commit` hook wasn't being triggered after running `yarn` and noticed it was due to an un-used `pre-commit` dependency in `now-cli` overriding the changes to my `.git/hooks/pre-commit` file done by `husky`
**Note**: you will probably need to run `yarn install --force` after this is applied before the correct `pre-commit` changes are applied by `husky`
We've shut down our Typeform for feedback, so we can simply the feedback link. The old one will continue working, but we should start using the new one.
Pending on https://github.com/zeit/front/pull/5874.
Fixes#3377
2019-12-10 18:18:10 +00:00
2468 changed files with 142458 additions and 17479 deletions
When contributing to this repository, please first discuss the change you wish to make via [GitHub Issue](https://github.com/zeit/now/issues/new) or [Spectrum](https://spectrum.chat/zeit) with the owners of this repository before submitting a Pull Request.
When contributing to this repository, please first discuss the change you wish to make via [GitHub Discussions](https://github.com/zeit/now/discussions/new) with the owners of this repository before submitting a Pull Request.
Please read our [code of conduct](CODE_OF_CONDUCT.md) and follow it in all your interactions with the project.
@@ -47,7 +47,7 @@ Unit tests are run locally with `jest` and execute quickly because they are test
### Integration tests
Integration tests create deployments to your ZEIT account using the `test` project name. After each test is deployed, the `probes` key is used to check if the response is the expected value. If the value doesn't match, you'll see a message explaining the difference. If the deployment failed to build, you'll see a more generic message like the following:
Integration tests create deployments to your Vercel account using the `test` project name. After each test is deployed, the `probes` key is used to check if the response is the expected value. If the value doesn't match, you'll see a message explaining the difference. If the deployment failed to build, you'll see a more generic message like the following:
```
[Error: Fetched page https://test-8ashcdlew.now.sh/root.js does not contain hello Root!. Instead it contains An error occurred with this application.
@@ -92,5 +92,14 @@ Sometimes you want to test changes to a Builder against an existing project, may
2. Run `yarn build` to compile typescript and other build steps
3. Run `npm pack` to create a tarball file
4. Run `now *.tgz` to upload the tarball file and get a URL
5. Edit any existing `now.json` project and replace `use` with the URL
5. Edit any existing `vercel.json` project and replace `use` with the URL
6. Run `now` or `now dev` to deploy with the experimental Builder
## Add a New Framework
You can add support for a new Framework by creating a Pull Request for this repository and following the steps below:
1. Add the Framework to the `@now/frameworks` package: The file is located in `packages/frameworks/frameworks.json`. You can copy the structure of an existing one and adjust the required fields. Note that the `settings` property either contains a `value` or a `placeholder`. The `value` property is used when something is not configurable, the `placeholder` is used when something is configurable and can be changed with configuration. An example would be the Output Directory for Hugo, it's `public` by default but can be changed through its config file, so we use `placeholder` with an explanation of what can be used.
2. Add an example to the `examples/` directory: The name of the directory should equal the slug of the framework used in `@now/frameworks`. The `.github/EXAMPLE_README_TEMPLATE.md` file can be used to create a `README.md` file for the example.
3. Update the `@now/static-build` package: The file `packages/now-static-build/src/frameworks.ts` has to be extended. You can add default routes that will always be applied to projects that use this Framework or specify some paths that will be cached to speed up the build process.
4. After your Pull Request has been merged and released, other users can select the example on the Vercel dashboard and deploy it.
This directory is a brief example of a [Name](site-link) site that can be deployed with Vercel and zero configuration.
## Deploy Your Own
Deploy your own [Name] project with Vercel.
[](https://vercel.com/import/project?template=https://github.com/zeit/now-examples/tree/master/example-directory)
### How We Created This Example
To get started with [Name] on Vercel, you can use the [CLI Tool Used](CLI-link) to initialize the project:
```shell
$ now init charge
```
### Deploying From Your Terminal
Once initialized, you can deploy the [Name] example with just a single command:
The following page is a reference for how to create a Runtime using the available Runtime API.
A Runtime is an npm module that exposes a `build` function and optionally an `analyze` function and `prepareCache` function.
Official Runtimes are published to [npmjs.com](https://npmjs.com) as a package and referenced in the `use` property of the `now.json` configuration file.
Official Runtimes are published to [npmjs.com](https://npmjs.com) as a package and referenced in the `use` property of the `vercel.json` configuration file.
However, the `use` property will work with any [npm install argument](https://docs.npmjs.com/cli/install) such as a git repo url which is useful for testing your Runtime.
See the [Runtimes Documentation](https://zeit.co/docs/v2/advanced/runtimes) to view example usage.
See the [Runtimes Documentation](https://vercel.com/docs/runtimes) to view example usage.
## Runtime Exports
@@ -18,7 +18,7 @@ The latest and suggested version is `3`.
### `analyze`
An **optional** exported function that returns a unique fingerprint used for the purpose of [build de-duplication](https://zeit.co/docs/v2/advanced/concepts/immutability#deduplication-algorithm). If the `analyze` function is not supplied, a random fingerprint is assigned to each build.
An **optional** exported function that returns a unique fingerprint used for the purpose of [build de-duplication](https://vercel.com/docs/v2/platform/deployments#deduplication). If the `analyze` function is not supplied, a random fingerprint is assigned to each build.
An **optional** exported function that is only used by `now dev` in [Now CLI](https:///download) and indicates whether a [Runtime](https://zeit.co/docs/v2/advanced/runtimes) wants to be responsible for building a certain request path.
An **optional** exported function that is only used by `now dev` in [Now CLI](https:///download) and indicates whether a [Runtime](https://vercel.com/docs/runtimes) wants to be responsible for building a certain request path.
```js
shouldServe({
@@ -143,7 +143,7 @@ The exported functions [`analyze`](#analyze), [`build`](#build), and [`prepareCa
-`entrypoint`: Name of entrypoint file for this particular build job. Value `files[entrypoint]` is guaranteed to exist and be a valid [File](#files) reference. `entrypoint` is always a discrete file and never a glob, since globs are expanded into separate builds at deployment time.
-`workPath`: A writable temporary directory where you are encouraged to perform your build process. This directory will be populated with the restored cache from the previous run (if any) for [`analyze`](#analyze) and [`build`](#build).
-`cachePath`: A writable temporary directory where you can build a cache for the next run. This is only passed to `prepareCache`.
-`config`: An arbitrary object passed from by the user in the [Build definition](#defining-the-build-step) in `now.json`.
-`config`: An arbitrary object passed from by the user in the [Build definition](#defining-the-build-step) in `vercel.json`.
## Examples
@@ -153,7 +153,7 @@ Check out our [Node.js Runtime](https://github.com/zeit/now/tree/master/packages
### Execution Context
A [Serverless Function](https://zeit.co/docs/v2/advanced/concepts/lambdas) is created where the Runtime logic is executed. The lambda is run using the Node.js 8 runtime. A brand new sandbox is created for each deployment, for security reasons. The sandbox is cleaned up between executions to ensure no lingering temporary files are shared from build to build.
A [Serverless Function](https://vercel.com/docs/v2/serverless-functions/introduction) is created where the Runtime logic is executed. The lambda is run using the Node.js 8 runtime. A brand new sandbox is created for each deployment, for security reasons. The sandbox is cleaned up between executions to ensure no lingering temporary files are shared from build to build.
All the APIs you export ([`analyze`](#analyze), [`build`](#build) and [`prepareCache`](#preparecache)) are not guaranteed to be run in the same process, but the filesystem we expose (e.g.: `workPath` and the results of calling [`getWriteableDirectory`](#getWriteableDirectory) ) is retained.
@@ -165,8 +165,6 @@ When a new build is created, we pre-populate the `workPath` supplied to `analyze
The `analyze` step can modify that directory, and it will not be re-created when it's supplied to `build` and `prepareCache`.
To learn how the cache key is computed and invalidated, refer to the [overview](https://zeit.co/docs/v2/advanced/runtimes#technical-details).
### Accessing Environment and Secrets
The env and secrets specified by the user as `build.env` are passed to the Runtime process. This means you can access user env via `process.env` in Node.js.
[](https://github.com/zeit/now/discussions)
## Usage
To install the latest version of Now CLI, visit [zeit.co/download](https://zeit.co/download) or run this command:
Vercel is the optimal workflow for frontend teams. All-in-one: Static and Jamstack deployment, Serverless Functions, and Global CDN.
```
npm i -g now
```
To quickly start a new project, run the following commands:
```
now init # Pick an example project to clone
cd <PROJECT> # Change directory to the newly created project
now dev # Run locally during development
now # Deploy to the cloud
```
Get started by [Importing a Git Project](https://vercel.com/import) and use `git push` to deploy. Alternatively, you can [install Vercel CLI](https://vercel.com/download).
## Documentation
For details on how to use Now CLI, check out our [documentation](https://zeit.co/docs).
For details on how to use Vercel, check out our [documentation](https://vercel.com/docs).
## Caught a Bug?
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Install dependencies with `yarn install`
3. Compile the code: `yarn build`
4. Link the package to the global module directory: `yarn link`
5. You can now start using `now` anywhere inside the command line
4. Link the package to the global module directory: `cd ./packages/now-cli && yarn link`
5. You can start using `vercel` anywhere inside the command line
As always, you should use `yarn test-unit` to run the tests and see if your changes have broken anything.
@@ -8,7 +8,7 @@ the provider couldn’t solve the requested challenges.
## How to Fix It
If your domain is pointing to ZEIT World DNS and you’re getting this error,
If your domain is pointing to Vercel DNS and you’re getting this error,
it could be that:
- The domain was acquired recently, and it might not be ready for use yet.
@@ -17,11 +17,11 @@ it could be that:
When running into this, ensure that your nameservers are configured correctly. Also, if you bought the domain recently or have made changes, please be patient,
it might take a while for these to be ready.
If your domain is _not_ pointing to ZEIT World DNS and you’re getting this
If your domain is _not_ pointing to Vercel DNS and you’re getting this
error, the following methods could help:
- When solving challenges *manually*, ensure that the TXT
records required to solve the challenges exist and are propagated. You can do so by querying the nameservers with `nslookup -q=TXT _acme-challenge.domain.com` depending on the Common Names you want for your certificate.
- When solving challenges _manually_, ensure that the TXT
records required to solve the challenges exist and are propagated. You can do so by querying the nameservers with `nslookup -q=TXT _acme-challenge.domain.com` depending on the Common Names you want for your certificate.
- If you are not solving the challenges manually you must ensure that you have an
`ALIAS` and `CNAME` records in place. Ensure also that you have disabled automatic redirects to `https` and ensure all changes were propagated.
`ALIAS` and `CNAME` records in place. Ensure also that you have disabled automatic redirects to `https` and ensure all changes were propagated.
When generating a certificate, we have to prove ownership over the domain
for the Certificate Authority (CA) that issues it. We also run some pretests
to make sure the DNS is properly configured before submitting the request to
to make sure the DNS is properly configured before submitting the request to
the CA. This error means that these pretests did not succeed.
## How to Fix It
If your domain is pointing to ZEIT World DNS and you’re getting this error,
If your domain is pointing to Vercel DNS and you’re getting this error,
it could be that:
- The domain was acquired recently, and it might not be ready for use yet.
@@ -18,6 +18,6 @@ it could be that:
When running into this, ensure that your nameservers have configuration is correct. Also, if you bought the domain recently or have made changes, please be patient,
it might take a while for these to be ready.
If your domain is _not_ pointing to ZEIT World DNS and you’re getting this
If your domain is _not_ pointing to Vercel DNS and you’re getting this
error, you must ensure that you have an `ALIAS` and `CNAME` records in place.
Ensure also that you have disabled automatic redirects to `https` and ensure all changes were propagated.
@@ -12,10 +12,10 @@ You can retrieve both the intended nameservers and TXT verification record for t
When you have added either verification method to your domain, you can run `now domains verify <domain>` again to complete verification for your domain.
ZEIT will also automatically check periodically that your domain has been verified and automatically mark it as such if we detect either verification method on the domain.
Vercel will also automatically check periodically that your domain has been verified and automatically mark it as such if we detect either verification method on the domain.
If you would not like to verify your domain, you can remove it from your account using `now domains rm <domain>`.
When defining custom routes a route was added that causes an error during parsing. This can be due to trying to use normal `RegExp` syntax like negative lookaheads (`?!exclude`) without following `path-to-regexp`'s syntax for it.
#### Possible Ways to Fix It
Wrap the `RegExp` part of your `source` as an un-named parameter.
**Before**
```js
{
source:'/feedback/(?!general)',
destination:'/api/feedback/general'
}
```
**After**
```js
{
source:'/feedback/((?!general).*)',
destination:'/api/feedback/general'
}
```
Ensure any segments used in the `destination` property are also used in the `source` property.
@@ -8,4 +8,4 @@ The `--token` flag was specified, but its contents are invalid.
The `--token` flag must only contain numbers (0-9) and letters from the alphabet (a-z and A-Z). This needs to be the token of the user account as which you'd like to act.
You can either get the token from the `./now/auth.json` file located in your user directory or [from the dashboard](https://zeit.co/account/tokens).
You can either get the token from the `./vercel/auth.json` file located in your user directory or [from the dashboard](https://vercel.com/account/tokens).
You ran `now dev` inside a project that contains a `now.json` file with `env` or `build.env` properties that use [Now Secrets](https://zeit.co/docs/v2/deployments/environment-variables-and-secrets).
You ran `now dev` inside a project that contains a `vercel.json` file with `env` or `build.env` properties that use [Now Secrets](https://vercel.com/docs/v2/build-step#environment-variables).
In order to use environment variables in your project locally that have values defined using the Now Secrets format (e.g. `@my-secret-value`), you will need to provide the value as an environment variable using a `.env` or `.env.build` file.
@@ -23,4 +24,4 @@ TEST=value
In the above example, `TEST` represents the name of the environment variable and `value` its value.
For more information on Environment Variables in development, [see the documentation](https://zeit.co/docs/v2/development/environment-variables/).
For more information on Environment Variables in development, [see the documentation](https://vercel.com/docs/v2/build-step#environment-variables).
@@ -8,4 +8,4 @@ The `--scope` flag was specified, but there's no value for it available.
In order to make it work, you need to specify a value for the `--scope` flag. This needs to be the slug or ID of the team as which you'd like to act or the username or ID of a user you'd like to act as.
As an example, if your team URL is `https://zeit.co/teams/zeit`, you would set `--scope` to `zeit`.
As an example, if your team URL is `https://vercel.com/teams/zeit`, you would set `--scope` to `zeit`.
@@ -8,4 +8,4 @@ The `--token` flag was specified, but there's no value for it available.
In order to make it work, you need to specify a value for the `--token` flag. This needs to be the token of the user account as which you'd like to act.
You can either get the token from the `./now/auth.json` file located in your user directory or [from the dashboard](https://zeit.co/account/tokens).
You can either get the token from the `./vercel/auth.json` file located in your user directory or [from the dashboard](https://vercel.com/account/tokens).
@@ -6,5 +6,5 @@ You're running Now CLI in a non-terminal context and there are no credentials av
#### Possible Ways to Fix It
- Specify a value for the `--token` flag (this needs to be the token of the user account as which you'd like to act). You can either get the token from the `./now/auth.json` file located in your user directory or [from the dashboard](https://zeit.co/account/tokens).
- Ensure that both `~/now/auth.json` and `~/now/config.json` exist
- Specify a value for the `--token` flag (this needs to be the token of the user account as which you'd like to act). You can either get the token from the `./vercel/auth.json` file located in your user directory or [from the dashboard](https://vercel.com/account/tokens).
- Ensure that both `~/vercel/auth.json` and `~/vercel/config.json` exist
@@ -8,4 +8,4 @@ In turn, they would have to take the value of the `--token` flag into considerat
#### Possible Ways to Fix It
Specify a value for the `--scope` flag. This needs to be the slug or ID of the team as which you'd like to act (as an example, if your team URL is `https://zeit.co/teams/zeit`, the value can be `zeit`) or the username or ID of a user you'd like to act as.
Specify a value for the `--scope` flag. This needs to be the slug or ID of the team as which you'd like to act (as an example, if your team URL is `https://vercel.com/teams/zeit`, the value can be `zeit`) or the username or ID of a user you'd like to act as.
This could be caused by a misconfigured "Build Command" or "Output Directory" for your Next.js project.
#### Possible Ways to Fix It
In the Vercel dashboard, open your "Project Settings" and draw attention to "Build & Development Settings":
1. Ensure that the "Build Command" setting is not changed, or that it calls `next build`. If this command is not changed but you are seeing this error, double check that your `build` script in `package.json` calls `next build`.
2. Ensure that the "Output Directory" setting is not changed. This value almost never needs to be configured, and is only necessary if you override `distDir` in `next.config.js`.
3. For `next export` users: **do not override the "Output Directory"**. Next.js automatically detects what folder you outputted `next export` to.
In rare scenarios, this error message can also be caused by a Next.js build failure (if your "Build Command" accidentally returns an exit code that is not 0).
Double check for any error messages above the Routes Manifest error, which may provide additional details.
@@ -19,7 +19,7 @@ the provided `$PORT` that the builder expects the server to bind to.
For example, if you are using Gatsby, your `now-dev` script must use the `-p`
(port) option to bind to the `$PORT` specified from the builder:
> *In Windows environments, reference the `PORT` environment variable with `%PORT%`*
> _In Windows environments, reference the `PORT` environment variable with `%PORT%`_
```
{
@@ -34,7 +34,3 @@ For example, if you are using Gatsby, your `now-dev` script must use the `-p`
Consult your static builder program's `--help` or documentation to figure out what
the command line flag to bind to a specific port is (in many cases, it is one of:
`-p` / `-P` / `--port`).
### Useful Links
- [`@now/static-build` Local Development Documentation](https://zeit.co/docs/v2/deployments/official-builders/static-build-now-static-build#local-development)
This is the public list of examples for **Vercel**.
All of these ready to deploy examples feature a frontend framework or static site, created with zero configuration using the CLI tools they provide.
The `+functions` examples feature an `/api` directory as well, highlighting how to use serverless functions on top of a framework, again with zero configuration required.
## What is Vercel?
Vercel is a cloud platform for static frontends and serverless functions. It enables developers to host websites and web applications that deploy instantly, scale automatically, and require no supervision.
## What Does this Repository Contain?
This repository consists of multiple examples, created for use with the [Vercel](https://vercel.com) platform. In addition to this, it also contains:
- [Code of Conduct](https://github.com/zeit/now/blob/master/.github/CODE_OF_CONDUCT.md) - our Code of Conduct, adapted from the [Contributor Covenant](http://contributor-covenant.org)
- [Contributing Guidelines](https://github.com/zeit/now/blob/master/.github/CONTRIBUTING.md) - a guide on how to contribute to the Now Examples repository
- [License](https://github.com/zeit/now/blob/master/LICENSE) - the standard MIT license under which these examples are published
We recommend familiarizing yourself with the above sections, particularly if you are looking to make a contribution.
## Deploying Examples
To get started using any of these examples as your own project, [install Now](https://vercel.com/download) and use either of the following commands in your terminal:
```sh
now init # Pick an example in the CLI
now init <example> # Create a new project from a specific <example>
now init <example> <name> # Create a new project from a specific <example> with a different folder <name>
```
Deploying your project takes seconds and can be done with **just a single command**:
```sh
now # Deploys the project with Now
```
With the `now` command, your project will be built and served by Now, providing you with a URL that can be shared immediately.
## New Examples
We are continuously improving our examples based on best practices and feedback from the community. As a result, it is possible that example names will change and on occasion deprecated in favor of an improved implementation.
For example, the previous `nodejs` example showed a static frontend with a Node.js API. This is illustrated now in the `svelte` example. Below is a table that lists some of the most popular previous examples and the equivalent replacement:
If you have an existing project you would like to deploy with Vercel, we recommend reading our guide on [migrating to Vercel and zero configuration](https://vercel.com/guides/migrate-to-vercel). By combining the guide with this repository, you will quickly be able to understand how to deploy your application.
If you would like to upgrade a project to take advantage of zero configuration, you may find the [upgrade guide](https://vercel.com/guides/upgrade-to-zero-configuration) useful. The upgrade guide covers how to remove configuration from existing projects along with how to use the `/api` directory.
## How to Contribute
Contributing to Now Examples should be an enjoyable experience, as such we have created a set of [contributing guidelines](https://github.com/zeit/docs/blob/master/CONTRIBUTING.md) to help you do so.
The guidelines cover important information such as the requirements for new examples and where to get help if you have any questions.
We have tried to make contributing to Now Examples as easy as possible, especially for those new to Open Source. If anything is unclear or you have any questions then please reach out to us on [GitHub Discussions](https://github.com/zeit/now/discussions) where we will do our best to help you.
## Reporting Issues
We actively encourage our community to raise issues and provide feedback on areas of Now Examples that could be improved.
An issue can be raised by clicking the 'Issues' tab at the top of the repository, followed by the Green 'New issue' button.
When submitting an issue, please thoroughly and concisely describe the problem you are experiencing so that we may easily understand and resolve the issue in a timely manner.
## License
Now Examples is an open source project released under the [MIT License](https://github.com/zeit/docs/blob/master/LICENSE.md).
## Get In Touch
If you have any questions that are not covered by raising an issue then please get in touch with us on [GitHub Discussions](https://github.com/zeit/now/discussions). There you will find both members of the community and staff who are happy to help answer questions on anything Vercel related.
[](https://github.com/zeit/now/discussions)
This directory is a brief example of an [Angular](https://angular.io/) app that can be deployed with Vercel and zero configuration.
## Deploy Your Own
Deploy your own Angular project with Vercel.
[](https://vercel.com/import/project?template=https://github.com/zeit/now/tree/master/examples/angular)
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.