No improvements, per say, but the module has been converted to
TypeScript so it supplies its own type definitions now, and we
can delete our hand-crafted typings from this repo.
* [now-cli] Use `xdg-app-paths` for `now dev` cache dir
For consistency, because #2877 uses this module.
No need for multiple modules that do the same thing.
* Update `@zeit/fun` to v0.9.3
* [now-cli] Fix `now certs ls` when the user or team has no certs
* Add tests and move to typescript
* Move index and add to typescript
* Fix reduce function in ls
* Added linebreak
* Update packages/now-cli/src/commands/certs/add.ts
Co-Authored-By: Naoyuki Kanezawa <naoyuki.kanezawa@gmail.com>
* [now-cli] Install dependencies before running `now dev` in tests
* Check install exit code
* Add more logging
* Add more logging
* More logging
* Include yarn.lock file
* Add lock files to dev fixtures
* Ignore test
* Ignore another test
* Ignore another test
* Whitespace
* Install deps for unit tests
* Whitespace
* add gatsby-plugin-now
* add test
* adjust with lerna
* fix test
* add tests to circleci
* add support for defaultRoutes functions
* add defaultRoutes to gatsby
* fix types
* add test case for gatsby redirects
* remove gatsby, react, react-dom from monorepo deps
* chmod +x build.sh
* add missing build script in fixtures
* do stuff during tests to avoid persistence issue
* move tests setup to build step
* copy gatsby plugin files in test case
* bring back ncc step
* prettier gatsby-plugin-now
* add missing semicolons
* remove eslint, prettier from plugin
* persist build step copied file
* fetch without following redirects
* add files in package.json
* remove force
* fix tests probes
* fetch location is not raw location
* fix test
* add readme
* fix type error
* adjust tests
* add support for `force`
* add tests for `force`
* adjust tests again
* gatsby-plugin-now@1.1.0
* `"` -> `'`
* tweak redirect names in test by precaution
* change file name and delete when consumed
* format files
* gatsby-plugin-now@1.2.0
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* tests -> test
* add --verbose
* adjust circleci to persist fixtures
* trigger tests
* add repository and homepage in package.json
* glob files after `defaultRoute` invocation
* Optimize zipping lambdas for now-next
* Update to use jszip to get around bug in yazl
* Add pseudo layer utils
* Apply suggestions from code review
Co-Authored-By: Joe Haddad <joe.haddad@zeit.co>
* Update sema concurrency from tests
* Update packages/now-next/src/index.ts
* Use custom types to fix broken @types package
* Add license header
* Revert "Use custom types to fix broken @types package"
This reverts commit 82441285155f6e0899c43dffdd5e000ecbd7b1b6.
* Fix CI Yarn installation
* TypeScript types should never be hoisted
* Fix all typechecking
* [now-go] Use `debug()` from build-utils (#923)
* Use `debug()` from build-utils
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* Print errors
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* Use XDG standard instead of writing to home directory
* Fix typos
* Use dependencies as dev dependencies
* Remove lodash dependency
* Use xdg-app-paths instead of xdg-portable
* use find instead of filter(...)[0]
Otherwise, JavaScript Object built-ins such as `hasOwnProperty` are
incorrectly considered a valid subcommand, but fail afterwards with
a `require()` error and confusing error message.
* [now-cli] Validate inputs for alias, list and remove
* Log test output
* Add more logging to test
* Change to execa
* Use `split`
* Only validate when it exists
* [now-cli] Change success message after login
* Linting
* Test now login
* Linting
* Revert "Test now login"
This reverts commit 690360db3f148552a456b4ee1bd2a59b8d09216c.
* Revert "Linting"
This reverts commit 3d5ebfaa76ecdcc2152c8344c8e1205b241abe09.
* Adjust test
* Remove binaryPath from args
* Fix loggin test
This enables https://github.com/zeit/now-cli/pull/2747 from @nkzawa again.
We had to revert the previous one, because we didn't want to include it in
the next stable release.
This further makes sure that we don't display `https://` in front of a
wildcard alias, since `https://*.mydomain.tld` is not a valid URL.
* [now-cli] Validate builds and routes for `now dev`
* Remove @ts-ignore
* Sort the matches such that `utils` modules are compiled first
Because other packages may rely on them
* Prettier
* Add `reject: false` to tests
* Prettier
* Make validation async
* Fix syntax
* Fix type
* Linting
* Fix error check
* [now dev] Update `yarn` to v1.17.3
* Wait longer for angular integration test
It keeps on failing
* Only run angular test on Node 10.x
* Revert "Wait longer for angular integration test"
This reverts commit 19d70d4ba9aee49a5114b65f00ef97e2a88dc7ef.
* Update links to `now-builders` repo to `now` repo
Also copies over the `.md` files from the now-builders' `errors`
directory so that the https://err.sh links work correctly.
Part of #2782.
* Update `err.sh` links that were formerly `now-cli`
* Empty commit for CI
* Make CircleCI `run.sh` script a bit better
Before it would fail with exit code 1 if there were no matching modified
files because of the `grep` call failing without any `packages` prefixed
files.
* [tests] Change run script from bash to node
* Fix loop for runScript
* Fix `all` script test
* Improve console.log() messages
* Use -l instead of -p
* Delete yarn.lock from now-python
* Move now-cli to /packages/now-cli
* Fix .gitignore paths
* Add now-client
* Add lerna to top level
* Add scripts
* Update codeowners
* Fix `/now-cli/build.ts` script
* Fix circleci path to artifacts
* Use relative paths
* Fix path to scripts
* Add test-lint script
* Add missing return type
* Fix typo in test-lint
* Fix string match in shell scripts
* Fix path to hugo
* Add package node_modules
* Delete lock files in packages, use root yarn.lock
* Add missing b.js file
* Add test-integration-now-dev script
* Add missing test files
* Add missing integration test script
* Add missing test files
* Delete travis.yml
* Fix ts-jest in now-client
* Add support for Node 8 (ES2015 target)
* Add support for Node 8
* Add polyfill for Node 8
* Fix polyfill for Node 8
* Only run coverage for now-cli
* Add packages from now-builders
* Run integration tests for builders
* Add node_modules to cache
* Add root readme.md
* Move readme to top level
* Add yarn bootstrap
* Add bootstrap step
* Add dist to `persist_to_workspace`
* Fix 08-yarn-npm integration test
* Remove duplicate path
* Change stdio to inherit
* Add back store_artifacts
* testing - remove bootstrap step
* Add back now-build-utils
* Remove bootstrap step
* Fix test again
* Add console.log()
* Fix lint
* Use local ncc version
* Install go
* Revert changes to stdio and console.log()
* Add missing now-go test
* Add missing integration tests
* Add --runInBand flag
* Fix now-node-bridge persistence
* Add missing symlinks
* Add codeowners
* Consolidate into single run.sh function
* Run uniq
* Fix typo
* Change now-routing-utils to test-unit
* Special case test for node 8
* Add docs from builders
* Only run script for modified packages
* Add test-integration-once which only runs once
* Fix set intersection
* [now deploy] Add `--production` and `--staging` flag
* Change message
* Fix tests
* Fix test
* Add another test
* Fix production test
* Update message and add `--prod`
* Update help
* Remove `--staging`
* Use only `--prod`
* Add test
* Add aliasError output
* Fix output
* [now rm] Use the proper `client` so that the process does not hang
The crux of this fix is that `getDeploymentByIdOrHost()` and
`getProjectByIdOrName()` were improperly being passed the `Now`
instance instead of the expected `Client` instance, and for some
reason that would cause the process to hang until the underlying
`http.Agent` timed out its connection to the API server.
Also ran `prettier` on this file.
Fixes#2760.
* Remove `console.error()`
* Add integration test
* Fix syntax error
* Add `now rm` 404 integration test
* Remove `.only`
* Use canary builders for the canary version
* Use the `getDistTag` function instead
* Fix function call
* Add tests
* Remove unused code
* Remove logging
* [now dev] Add `--bind` / `-b` flag
This changes the default network interface that `now dev` binds to, in
order to prevent operating system firewalls from showing a confirmation
prompt in order to run.
Fixes#2704.
* Change to `--listen`
* Default port 3000
* Fix unit
* Fix `--port`
* Use `-l` for integration tests
* Add unit tests
* [now update] Show correct global or local install command
* Remove `canRead` check
* Change bin to lib since the actual script will be there
* Use realpath
* Remove console.error
All of the APIs already support JSON by default, so this is a no-op for
our APIs, however the proxy layer _does_ respect the `Accept` header to
send JSON error responses, which is useful for more gracefully handling
outage responses (previously they were being returned as plain text,
which Now CLI blindfully tries to parse as JSON and fails with an
unhelpful error message).
Related to #2681.
For some reason, `ava` was silently skipping these tests on CI because
the process was crashing. According to sindre, this is a bug in `ava`,
but with some digging I was able to determine that the root cause of the
crash was that the `builders.tar.gz` file from the `assets` dir was not
being persisted from the previous `build` job in CI.
With the `assets` dir being persisted I now see the `dev-server` unit
tests being executed once again as expected.
Related to: https://twitter.com/sindresorhus/status/1157614353375551493
* [now deploy] Use the project when checking the platform version
* Update src/util/prefer-v2-deployment.ts
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* Update src/util/prefer-v2-deployment.ts
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* Adjust message
* Fallback for local config
* [now dev] Render warning upon empty `cwd` directory
The warning matches the one that `now deploy` prints, and only
prints the warning once (rather then upon every HTTP request).
Closes#2696.
* Fix eslint warning
* Add "pipe"
* Debugging…
* Fix integration test
* Debugging…
* Add `--verbose` to "test-integration-now-dev" script
* Ignore `yarn.lock` and `node_modules` in test dir
* Ignore `hugo` binary
* Ignore `public` dir in hugo test fixture
* Add `.gitignore` to `empty` test fixture
* Revert "Debugging…"
This reverts commit 27c6d2e06fe7eff12077a0e88915cf46b39b00ea.
* Ignore `public` / `dist` dirs in fixtures
This is to prevent false-positives like this from occurring,
and fixes the warning from `node`:
```
$ ts-node ./scripts/build.ts
Creating builders tarball with: @now/build-utils@canary, @now/go@canary, @now/next@canary, @now/node@canary, @now/php@canary, @now/static-build@canary
(node:156) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open '/home/circleci/repo/assets/builders.tar.gz'
at ReadStream.evt.error.err (/home/circleci/repo/node_modules/promisepipe/index.js:30:23)
at ReadStream.emit (events.js:198:13)
at ReadStream.EventEmitter.emit (domain.js:448:20)
at /home/circleci/repo/node_modules/graceful-fs/graceful-fs.js:207:14
at /home/circleci/repo/node_modules/graceful-fs/graceful-fs.js:258:16
at FSReqWrap.args [as oncomplete] (fs.js:140:20)
(node:156) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:156) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
```
* [now deploy] Check if builds are ready right away
* Adjust tests
* Remove test
* Log more while testing
* Remove check in tests
* Adjust all tests
* Log more
* [now dev] Support JSON and HTML redirect responses
Matches the production behavior.
* Set Now response headers during redirect
* Set `location` header
* Remove unused `matched_route` var
* [now dev] Allow custom 404 pages via `routes`
This matches the behavior in production, which allows a `dest` to be
provided when defining a `status: 404` in the routes configuration.
Related to #2638.
* Fix typo
* [preinstall/now update] Check if now is installed locally and adjust messages
* Adjust test
* Add tests
* Wait for deployment to be ready
* Removed log
* Adjust prefix in test
* Adjust path
* Only wait 4 minutes
* More logging
* Change binPrefix to prefix
* Remove all linting warnings
* Adjust env vars for test
* Don't test on node 8
* Log more error information and fail right after 500
* Move docker test up
* [now dev] Support JSON and HTML error responses
Closes#2609.
* Compile templates for unit tests in CircleCI
* Update `ts-node` to v8.3.0
* Convert doT.js compiled templates to TypeScript
* Compile templates for lint tests in CircleCI
* Print convert time
* Add 502 error template
* Remove `message` param from `sendError()`
* Prettier
* Add 404 tests
* Fix test
* [now deploy] Change link for legacy warning
* Remove trailing slash
Co-Authored-By: Steven <steven@ceriously.com>
* Simplify `link` function
Co-Authored-By: Nathan Rajlich <n@n8.io>
* Determine which link to show and add test
* Adjust link for configuration
Co-Authored-By: Steven <steven@ceriously.com>
* Adjust Package type
* [CircleCI] Add more tests for macos support
* Change xcode version since node 8.9.x is required
* Log stderr and stdout
* Add custom start script
* Make tests use custom start script
* Made start script executable
* Use correct node path
* Fix script path
* Handle status code
* Use latest Node.js version for macos tests
* Include yarn.lock for ember test
* Only use start script in tests
* Change start script for macos
* Change start script for linux
* Change start script for linux
* Update `NOW_BUILDER_DEBUG` base on `--debug` flag
* No need to reset `NOW_BUILDER_DEBUG`
* Add comment for `NOW_BUILDER_DEBUG`
* Apply suggestions from code review
Co-Authored-By: Andy <AndyBitz@users.noreply.github.com>
* [now dev] Bundle `canary` builders for Now CLI canary
Closes#2641.
* Add unit tests
* More unit tests
* Use `semver.parse()` in `getDistTag()`
* Convert build script to TypeScript, DRY the `getDistTag()` function
* Prettier
Run the `now dev` integration tests in parallel with the "standard"
integration tests, since they both take a long time. This should
cut the CI testing time in about half.
* Support Node 8
This changes the TypeScript compilation target to "es2015" so that
async generator functions are transpiled, which enables Node 8 to be
supported.
As a side-effect, any of the files that utilize `async function*` or
`for await` needed to be converted to TypeScript so that the
transpilation actually happens.
It was painful to do this process for `src/commands/deploy/legacy.ts`,
and since it is legacy code I did not want to make too many changes to
the code, so there's a log of `@ts-ignore` and `any` types being used.
But the behavior of the file should not have changed at all.
* Make `engines` field be ">= 8"
* Add Node 8 to CircleCI matrix
* Remove `console.error()`
* Remove `.ts` extension on import calls
* Use `Now` instead of `any`
* Use native `url` module instead of `whatwg-url`
* Debug integration test
* Skip `02-angular-node` test on Node 8
* Remove debugging
* Add "Downloading Hugo" step to Node 8 tests
* Skip `03-aurelia` test on Node 8
* Skip `03-aurelia` test for all
All node versions are failing with the same error:
https://circleci.com/gh/zeit/now-cli/29922
* Use `fs-extra` instead of `fs.promises` for Node 8
* [now deploy] Consider `--npm` and `--docker` for platform detection
* Change order
* Change prepare
* Await fixtures
* Remove check
* Revert "Remove check"
This reverts commit 7a5c1c901085d4e22c5a34cc48b5d929a9ee3b80.
* Use async-retry
* Fix fetch
* Log token
* Retry user creation
* Add async
* Add try-catch
* Decrease the retries
* Use original way to get context name
* Using `stdio` to resolve `now dev` Ready
* Update test/dev/integration.js
Co-Authored-By: Andy <AndyBitz@users.noreply.github.com>
* Improve `testFixtureStdio` and update aurelia fixture
* Remove duplicate test
* Update `create-react-app` and `gatsby` test fixture
* Update `gridsome` test fixture
* Update `hugo` test fixture
* Update `jekyll` test fixture
* Add `marko` test fixture
* Add `mithril` test fixture
* Add `riot` test fixture
* Add `charge` test fixture
* Add `brunch` test fixture
* Add `docusaurus` and `ember` test fixtures
* Install ruby for `jekyll`
* Update base on platform for `jekyll` and `hugo`
* Use `sudo` to when installing `gem`
* Remove `09-jekyll`
* Extract the right filename
* Remove `-L` flag from `curl` for macOS
* Use different version of `hugo`
* Remove `min_version` from `08-hugo` theme
* [CircleCI] Run integration tests on multiple versions of Node.js
* Test Node 10 and Node 12
* Remove `fs.promises` usage for Node 8
* More `fs.promises` removal
* Remove Node 8, it is unsupported due to `async` function usage
* [now update] Render the proper tag and improve `yarn` detection logic
Before this the suggested command would always have you install the
stable version of `now`.
With this change the `@canary` tag will be suggested if the version of
`now` is from the canary release channel.
Also updates the `isYarn` detection logic to not consider the cwd, and
instead check the installed version of now's `package.json` for clues.
* Move `getUpdateCommand` to util
* Add a unit test
* Use integration test instead
* Remove `pkg` bundling
* Remove `(dev)` from `--version`
* Remove `test/dev-builder.unit.js`
* Temporary disable `update now to canary test`
* Update `now update` command
* Removed useless jobs
* Removed useless code
* Removed more useless code
* Use update command
* Only run publish upon tag
* Removed code
* No need bin, use dist directly
* Update test, using the right file
* Reslove `iconv-lite@0.5.0` version
* Removed useless file
* Added scripts directory
* Removed useless stuff
* Fixed build script
* Fix `now dev` integration test
* Also block coverage on linting
While debugging #2606, I noticed that the `Client` instances for
`now deploy` were not being supplied the appropriate `debug` flag
based on the command line args.
PR #2562 caused an issue with blocking builds at bootup being built
twice, which is problematic when i.e. running `yarn` simultaneously
on the same directory causing cache corruption issues.
The `getNowConfig(false)` used to be within this `if` branch, so the
debug call made sense there at the time, but as of zero config it got
moved to always be invoked, so this `debug()` call doesn't make sense
anymore.
* [now dev] Wait for blocking builds to complete before handling requests
After the `now dev` server has already booted, if you delete a build
match that previously required a build at bootup time (i.e. `@now/next`)
from the `builds` array in `now.json` (i.e. change the builder to
`@now/static`), and then change it back to `@now/next`, then previously
the build would never execute.
With this change, the blocking build occurs as expected, and any HTTP
requests that occur are blocked until that build has completed.
* Prettier
* Better diff
* Add test
* [now dev] Add warning when there are no build matches
This matches the error in production, except it's just a non-fatal
warning when running in `now dev`. This is so that the user can fix
the warning without having to restart the `now dev` server.
* Add integration test
* [now update] Render the proper tag and improve `yarn` detection logic
Before this the suggested command would always have you install the
stable version of `now`.
With this change the `@canary` tag will be suggested if the version of
`now` is from the canary release channel.
Also updates the `isYarn` detection logic to not consider the cwd, and
instead check the installed version of now's `package.json` for clues.
* Move `getUpdateCommand` to util
* Add a unit test
* Use integration test instead
* [now dev] Print `Serving all files as static` only once
* Track the config state
* Revert "Track the config state"
This reverts commit 9766941ca8cd1ffeae5fb0729800f05f2547099c.
* Revert "[now dev] Print `Serving all files as static` only once"
This reverts commit 3e30c2440b6c4deed8a14f2359696e7bf8dcdcad.
* Add `isInitialLoad` param
* Add configuration and basic integration tests for `now dev`
* Add test fixtures from `now-examples`
* Add `include` to `tsconfig.json`
* Increase retries for 00-list-directory
* Increase retries for `03-aurelia-node`
* Enable test fixtures for hexo, hugo, next, polymer, preact, svelte, vue, and vuepress
* Increase retries for `08-hugo-node`
* Disable `08-hugo-node` fixture
* Enable `04-create-react-app-node` test
* Disable `04-create-react-app-node` test
* Better name for now dev test job
* [now init] Add suggestions for old examples
* Add support for selecting an old example
* Add message for selection
* Wait for user interaction
* Fix typo
* Use v2 api instead
* Move message label to first param
* Bump api url to latest, update download to v2
* Rename found to visible
The `getNowConfig()` function gets invoked frequently, and it is also
async and makes mutations to the cached now config object. This ends
up being a race condition when `getNowConfig()` is invoked concurrently,
since one of the invocations may end up with an incomplete `NowConfig`
object (namely, with missing `builds`/`routes` arrays due to the
zero-config processing).
This change makes it so that there's only one `getNowConfig()` invocation
being executed at a time, and other concurrent executions will await the
same promise that the original invocation is responsible for.
* Update deps of deps in `yarn.lock` file
To fix #lodashgate:
* Upgrade `lodash.merge` to version 4.6.2 or later.
* Upgrade `lodash` to version 4.17.13 or later.
* Regenerate `yarn.lock`
* [now dev] Wait for `updateBuilders()` to complete before `stop()` completes
Since #2477, the unit tests related to `now dev` have become flaky, and
need to be retried a couple of times before running successfully. My
theory is that this is related to having concurrent `yarn` processes
operating on the builders module directory, causing corruption with yarn's
cache. Waiting for the lazy updating `yarn` process to complete makes
sense to me, hopefully CircleCI agrees.
* Debugging "list the scopes" integration test
* Moar debug
* Use regular `require()` when not in a webpack build (ava tests)
* Remove debug
Fixes this error from the pkg'd binary:
```
Error: File or directory '/**/now-cli/dist/builders.tar.gz'
was not included into executable at compilation stage.
Please recompile adding it as asset or script.
```
* [now dev] Bundle the most popular core builders into CLI binary
Makes Now CLI bundle a tarball inside its snapshot filesystem that
includes the following builders:
* @now/go
* @now/next
* @now/node
* @now/php
* @now/static-build
The tarball is generated by the `build.js` script and ensures the
"latest" version of the builders are included into the tarball.
When `now dev` is run, the tarball will be extracted upon the first
run to make these builders "pre-installed" to avoid the "Installing
builders" phase during boot-up.
Overall, this should make booting up `now dev` a lot faster, and help
with offline support.
* Don't install builders if they are bundled
* Persist `assets` dir to CircleCI workspace
* Delete build assets
* Fix installing builders from URL
* Finish builder installation filtering logic
* Still install `@now/build-utils`
* Implement builders installation "stale-while-revalidate"
* Remove `console.time()`
* Fix unit test
* Add `Readonly<>` to `BuilderWithPackage` type props
* Add debug log stack trace upon builder update failure
* Disable automatic signup
* Use shorter error message
* Update tests
* Update tests with user info
* Create tmpDir before tests
* Tweak fixtures and assertions for new login
* Don't pre-create the test directory in CI
* Use `os.homedir` instead of `~` in tests
* Pre-create auth directory conditionally
* [now dev] Render directory listing for Now v2 projects
Before directory listings only worked for "all static" deployments since
`now dev` would shell out to `serve-handler` to do the rendering.
Now the directory listing rendering logic is moved into `now dev` which
allows projects with Lambdas to also serve the directory listing
(previously they would just 404).
This removes the special-casing of "all static" deployments so that
there's only one code path.
Fixes#2161.
Fixes#2417.
* Move `serve-handler/src/directory` types to root
* Set `Content-Length` header for dir listing
* Add unit tests for directory listing
* Fix unit test
* [now dev] Update @now/build-utils and handle warnings
* Display warnings from response headers for deployment creation
* Update src/util/dev/server.ts
Co-Authored-By: Nathan Rajlich <n@n8.io>
* Apply routes only when there are no builds
* Updated the build utils
* [now dev] Update `serve-handler` to v6.1.0 and enable `etag` option
Sending the `ETag` response header matches how Now in production works.
* Test file contents as well
* [now dev] Revert "Add `etag` response header for Lambda invocations"
This reverts commit f80f1f79a6 (#2502).
`ETag` header is only sent in production when the lambda function sets
the "stale-while-revalidate" cache-control header, which will be
implemented in a separate PR.
* Remove `etag` test assertion
* [now-dev] Add zero config
* Update @now/build-utils
* Update @now/build-utils
* Escape glob
* Fix windows and group globbing
* Made sure routes and builds get updated on file events
* Removed useless check
* Add unit tests
* Use fetch instead of get
Before this change, the `installBuilders()` function was only run at
bootup, so if you modify `now.json` during runtime and add a builder
that's not installed, then a `MODULE_NOT_FOUND` error occurs.
Now the `installBuilders()` function is run with the missing builder
so that the builder can be properly loaded.
`validateEnvConfig()` used to be invoked inside of `validateNowConfig()`,
but now it is invoked separately.
Explicitly exiting the process avoids reports going to Sentry.
* [now dev] Allow `cache-control` header to be overwritten
This matches the behavior in production.
* Add `now-dev-headers` unit test fixture
* Remove `console.error()` call
This matches the production router behavior, and prevents running `now
dev` on a different project from serving stale content from a different
project.
Also update the `x-now-id` header to match the production behavior (it
changed at some point).
* [now update] Add message saying that Windows is not supported
And direct the user back to the download page in order to re-install.
Closes#2492.
* Exit 1
Co-Authored-By: Steven <steven@ceriously.com>
* [now dev] Use system installed version of Node.js for builds
Rather than downloading the 8.10 Node.js binary, simply assume that the
user has their preferred version of `node` already installed onto the
system and use that version.
If there is no `node` binary in the $PATH, then `process.execPath` is
used instead, meaning that the pkg binary node version will be used.
* Simplify `getNodeBin()` using `nothrow` option
* Fix build
* ignore metrics with environment variable
* collect exception and exit code
* add deprecated warning for `now alias [id] [url]`
* add exception in util error
* consistent format
* ensure no duplicate warning
* using the right error message
* refactor metrics util
This error happens when Ctrl+C is pressed before the `http.Server`
instance is listening, meaning that the user attempted to quit very
quickly after starting `now dev`.
This change makes the process exit immediately instead of throwing,
which also causes the error to be sent to Sentry (which we do not want).
* More cert errors handling for deploy command
* Apply suggestions from code review
Co-Authored-By: Andy <AndyBitz@users.noreply.github.com>
* Revisions based on review
* Minor revision
* Adds get-deployment-by-id which uses latest v9 endpoint
* Refactor to use apiVersion
* Update now rm
* Fixed typo
* Don't use .flat() because of node 10
* Exit process
* Remove only the project instead of all deployments of it
* Changed output text
* Headlines for projects and deployments
* Typo and number prefix
1. Handle permissions errors in both update mechanisms
2. Handle `EBUSY` (Windows) as a file busy error
3. Update permissions error prompt to say "Administrator Command Prompt" on Windows
4. Add message about "unexpected end of file" error
Rather then throwing which causes the process to exit.
Better to give the developer a chance to fix the syntax
error without having to restart the dev server afterwards.
* Use v4 instead to prevent listing the same deployment multiple times
* Remove the latestDeployments since it is depracted and doesn't have the
`readyState` property and only get 35 projects instead of 50 to lower
the rate limit
* Fix tests
* [now dev] Strip prefixed `/` when doing routes matching
The prefixed `/` is implicit when matching routes, so strip them
so that they are optional. This matches the behavior in production.
* Fix unit tests
* More readable
* Add unit test
* integrate universal metrics
* Update src/index.js
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* Add default `collectMetrics` config
* Remove flag, only using global config to disable metrics
* Add GA tracking ID
* Move constant to file
* Rename constant to constants
* Rename `dsn` to `SENTRY_DSN`
* Apply suggestions from code review
Co-Authored-By: Leo Lamprecht <mindrun@icloud.com>
* Remove extra space
* Update event category and action
* Remove usagestate to use universal-analytics
* Chain timing and event function
* Make sure to user are unique
* Ensure unique User ID
* Add extra User-Agent and move metrics into its own file
* Use default export
People are often trying to store secrets starting with dashes such as
private keys. These dashes get interpreted as command line options which
effectively prevents a storage of private keys.
Fortunately, this is easily resolved by using bash -- convention to mark
an end of options, such as:
`now secret add google-secret-key -- "-----BEGIN PRIVATE KEY-----
abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVXYZ+/a
-----END PRIVATE KEY-----"
The problem is also discussed in following issues:
https://github.com/zeit/now-cli/issues/749https://github.com/zeit/now-cli/issues/80
* [now dev] Use `chokidar` for file watching
`nsfw` is not suitable for very large projects because it does not
have any "ignore" functionality implemented.
For macOS, the `useFsEvents` option is _disabled_, so that the
`fsevents.node` binary file does not need to be cached onto the
filesystem, which simplifies things for use with `pkg` binaries.
* Delete the `fsevents` module during build
* Add proper `.nowignore` logic to the chokidar watcher
Alpha versions of `now dev` that used npm instead of yarn were
installing the packages to `devDependencies` rather than `dependencies`,
so this fixes package name lookup when a legacy cache like that is on
the user's machine.
* [now dev] Use the dev server `cwd` as builder's `workPath`
Rather than copying the source files into a temporary directory,
simply use the existing source files in the `cwd`. This will make
subsequent boots of `now dev` be faster (i.e. because the `node_modules`
directory will already be in place), as well as use much less space on
the filesystem because temporary directory are no longer being used.
This will require some changes to the builders and `@now/build-utils`,
to ensure that the `download()` function is always installing into
`workPath`, and that the `meta` object passed to the `build()` function
is also passed into the `download()` function.
For example:
- https://github.com/zeit/now-builders/pull/474
- https://github.com/zeit/now-builders/pull/475
* Update `@now/build-utils` to v0.5.5-canary.1
This makes `download()` be a no-op when running in `now dev`.
* Add test case for `@now/next`
* Fix debug log formatting
* [now dev] Mix in routes query params when proxying to a URL
Fixes#2289.
* Refactor unit tests and add a unit test for proxy passing with query params
* Fix TypeScript compile error
* [DEBUG] Disable proxy pass unit test
* Run unit tests serially
* Remove `console.error()` in unit test
* Temporarily disable integration test "try to create a builds deployments with wrong config"
* Adjust `now init` and `now dev` to not require a login token
These two commands should not require a login token because
they do not interact with the Now API.
* Remove `config` from `subcommandsWithoutToken` array
It's not an existing command.
* [now dev] Inherit env vars from `now.json`
Before it was only using env vars defined in the `.env` and `.env.build`
dotenv files.
* Fix secrets validation
Some builders require access to the runtime env vars, i.e. `@now/next`
since it spawns a `next dev` subprocess and should be passing the
runtime env vars to that.
Before it was only respecting the status code for 301, 302 and 303
status codes. Now it handles any status code defined in the routes
config.
Fixes#2294.
* [now dev] Show build logs if a build fails during bootup
Before, the logs were never shown because `buildProcess` does not emit
an `error` event when the child process exits.
Also updates `ora` to the latest version.
* Remove `@types/ora`
`ora` includes its own TypeScript definitions now.
Which includes this fix: https://github.com/zeit/pkg/issues/671
Relevant to `now dev` invoking `yarn` when a package includes
a postinstall script that invokes `node`.
* [now dev] Install builders with `yarn` instead of `npm`
Also invokes via `process.execPath` so that the pkg'd node is used
instead of a global one.
Depends on #2270.
* Install `yarn` to the builder cache dir
Not the `node_modules/.bin` dir, because `yarn` cleans up that directory
when installing modules, so it deletes itself.
* Remove unnecessary unit test
* Always install `yarn`
* Pass in the `yarnPath` to `installBuilders()`
* Restore unit test
* Remove unused `delimiter` import
Co-Authored-By: TooTallNate <n@n8.io>
This is important for builders like `@now/next` and `@now/static-build`
which launch a child process dev server, and we want those logs to be
visible from the `now dev` console output.
* Do not report env errors to Sentry
* Added guide for missing env file in dev mode
* Update errors/missing-env-file.md
Co-Authored-By: leo <mindrun@icloud.com>
* Update errors/missing-env-file.md
Co-Authored-By: leo <mindrun@icloud.com>
* [now dev] Refactor builders installation logic
- Don't run `npm update`, only `npm install`, so no more "Checking for
builder updates".
- Don't save `package-lock.json`, to allow builders with newer versions
than already installed to be updated.
- Properly supports non-npm-registry builders (i.e. an HTTP URL,
`github:` syntax, etc.
* Use `Object.entries()`
- Have the builder exit if a rejection occurs
- Respawn the builder upon next rebuild after the builder has exited
- Log when builder is starting and completed with build time
- Render build error in the HTTP response
This forces all the files to be served as static assets using
`@now/static`, rather than having a special branch that dishes
out to `serve-static`. This is better because it keeps the logic
consistent with when a `now.json` is supplied vs. when it is not,
and allows the code to be simplified by removing checks for if
`getNowJson()` returned anything (previously it could return `null`,
but now that is not the case). Also allows us to remove the now-unused
`serveProjectAsStatic()` function.
* [now dev] Force `@now/static` to run in-memory
The logic for `@now/static` builder is bundled into the `pkg` binary,
and thus is not requireable, so it must instead be run in-memory.
* Also check for stdout TTY before doing the erase lines stuff
* Update `@zeit/fun` to v0.7.0
* Remove `builderCachePromise`
No longer used.
* Remove `intercept-stdout`
* WIP invoke the builder in a forked child process
* WIP Add `builder.js` file
* Remove `BuildResultV1 | BuildResultV2` distinction
Prefer normalizing the `build()` function result to `BuildResult` v2
shape so that we don't have to cast everywhere else.
* Apply build env vars to builder child process
* Copy the `builder.js` file from the pkg filesystem snapshot to the builder cache dir
* Map `FileFsRef` and `FileBlob` of the builder's output back into instances
* Fix `@now/next` :/
* Cleanup
* Print number of initial builds
* Add spinner for building process
* Refine logs
* Support none-tty
* Crop long lines
* Clean up imports
* Refine logs wording
The `entrypoint` should always be watched, since we know that it was used
to produce the build output. This is for builders that don't implement
a fully featured `watch` return value.
* [now dev] Don't include a file in both `filesChanged` and `filesRemoved` list
This makes it so that if a file is added to the "changed" array, then it
is also removed from the "deleted" array, and vice-versa.
* Only render the "files changed/remove" debug log if there are entries
This will be necessary for `@now/static-build` since it needs to watch
all files in the dir containing the entrypoint. For example:
```
watch: [ path.join(path.dirname(entrypoint), '**/*') ]
```
The file watcher logic expects that there is no `'./'` prefix on the
watched file paths/patterns, but `path.dirname('foo')` returns `'.'`
which turns into `'./foo'` with `path.join()`. So this allows those
file paths to be returned from the builder and `now dev` normalizes the
paths after the build has completed.
The dev server `cwd` is not correct working path of a build match, so
pass in the correct one. This property will be used by
`@now/static-build`'s dev mode.
* [now dev] Remove `requiresInitialBuild` and make `shouldServe()` optional for v2 Builders
`@now/next` will be removing `shouldServe()` in favor of returning
a `routes` config array upon bootup. This makes now dev's
`shouldServe()` wrapper function support matching a `routes` config
entry when `shouldServe()` is not defined.
* Remove `console.error()` debugging calls
* Remove `mergeRoutes()` logic
This was incorrect behavior, and more like what `continue: true` is
supposed to do.
* Remove invalid test case
* Remove from the `files` array when ENOENT occurs in file watcher
* Prettier
* Pass workPath to builder.shouldServe() (#2211)
* [now dev] Resolve built routes after matching builder
This removes the `combineRoutes()` function since it was problematic and
triggered rebuilds upon every HTTP request, which is not necessary and
makes development slower.
Now, when an HTTP request comes in, the `now.json` routes are resolved
first, and then the matched build is checked if it defines any `routes`
in the build output. If it does, and a matching route is found then the
route is handled accordingly.
* Fix dev router unit tests
* Only try to match build routes if `.length > 0`
* Remove `routes` config from `@now/static` build results
This would cause an infinite loop of resolving `entrypoint` to
`entrypoint`, and is not necessary for this builder.
* [now dev] Reuse the same `workPath` for subsequent builds
Reusing the same `workPath` for subsequent builds makes rebuilding
faster, as well as it's necessary for webpack's watcher to work
correctly as it relies on the full filesystem paths being intact.
`prepareCache()` also no longer needs to be invoked, since the
previous `workPath` directory will already contain the necessary files
that the cache would otherwise produce.
* Prettier
* [now dev] Don't trigger a rebuild if an asset was deleted
This handles the case where an asset was deleted and should no longer be
served after a filesystem watcher event. For example, if a Next.js page
was previously built and the files was deleted from the `pages`
directory, then the rebuild should not happen since it will fail in the
`build()` function anyways.
* Add `config` to `shouldServe()`
* Remove unused `builder` var
* Show a upgrade message if the build limit is exceeded
* Typo
* Update src/commands/deploy/latest.js
Co-Authored-By: AndyBitz <AndyBitz@users.noreply.github.com>
Editors like `vim` like to use temporary files in the file's working
directory and quickly rename / delete them. This makes `now dev` handle
that gracefully and not crash.
This matches the behavior in production, so it is more correct.
This new common `getMimeType()` function also centralizes a place where
we can overwrite the `mime-types` return value to other values to match
production for other future discrepancies.
* [now dev] Add `nsfw` file watcher
WIP for triggering background rebuilds. So far the `files` mapping is
now kept in sync via the events produced by `nsfw`.
* Add `now.json` caching and invalidation from nsfw events
* Add initial rebuilding logic from filesystem watching
* Remove previously built assets when a rebuild occurs
* Make `@now/static` not require a hard refresh
* Shut down the `nsfw` instance when stopping the DevServer
* Prettier and some minor tweaks
* Ship module
* Support private deps
* Fixed tests
* Fixed integration tests
* Revert "Support private deps"
This reverts commit 0b4991b87641d693fa61f81223e0efc2b7006f83.
* Support multiple platforms
* Typed
* Consider Alpine
* Bumped @zeit/nsfw to latest version
* Update src/commands/dev/lib/nsfw-module.ts
Co-Authored-By: leo <mindrun@icloud.com>
* Pass module path differently
* Bumped package
* Make binary executable
* Wait until piping is complete
* Added debug statements
If you run `yarn build-dev`, then now source maps are enabled, allowing
us to see the proper line of an error in the source code file instead of
the huge `dist/index.js` file.
Previously they were only enabled for production builds.
* Handle additional errors when issuing a certificate
* Rename errors
* Provide more context in CertsDNSError
* Fix CertsDNSError structure
* Display cns with join
* Fix CertsDNSError
* WIP refactor to Now Builders v2 API
* More WIP
* Finish up refactor
* Remove `BuiltAsset` type
These properties are on the the `BuildMatch` interface now.
* Fix `handle: filesystem` route post-refactor
* Prettier
* Update src/commands/dev/lib/builder-cache.ts
Co-Authored-By: leo <mindrun@icloud.com>
- Get `.ts` files covered 🎉
- Update eslint related dependencies
- Add typescript-eslint [recommended rules](3e26ab684a/packages/eslint-plugin/src/configs/recommended.json), but only enabled ones we already followed, commented ones causing errors.
Commented rules including:
```yaml
# '@typescript-eslint/no-unused-vars': 1
# '@typescript-eslint/indent': ['error', 2]
# '@typescript-eslint/array-type': error
# '@typescript-eslint/ban-types': error
# '@typescript-eslint/explicit-member-accessibility': error
# '@typescript-eslint/member-delimiter-style': error
# '@typescript-eslint/no-angle-bracket-type-assertion': error
# '@typescript-eslint/no-explicit-any': warn
# '@typescript-eslint/no-object-literal-type-assertion': error
# '@typescript-eslint/no-use-before-define': error
# '@typescript-eslint/no-var-requires': error
# '@typescript-eslint/prefer-interface': error
```
### TODO
Go through these commented rules one by one, enable & fix for it or confirm it's disabled. Since enabling some rules would cause massive code change (like `'@typescript-eslint/indent': ['error', 2]`), which might conflict with our ongoing development, we better do this in separated PRs.
* Revert "Stop indicating whether CDN is enabled (#2132)"
This reverts commit 3dda3e84bf.
* Add a note about the CDN always being enabled
* Removed useless flag
* Added correct table heading
This is the same de-duping logic that occurs when you hard refresh,
but the unbuilt case was still not being considered. This fixes clicking
on an unbuilt link more than once from triggering multiple builds of the
same asset.
* [now dev] Run `prepareCache()` asynchronous
And also wait a few seconds before running the actual logic,
since the `prepareCache()` function may be computationally expensive,
and its run in the same process as `now dev` (for now), so allow
some time for the current HTTP request to complete.
* Add symlinks support to `glob()`, instrument prepareCache time
If a builder defines the `prepareCache()` function, then it gets invoked
after `build()` has completed to set up the initial build state of the
next build for this same asset.
For example, the goal for `@now/node` if the package.json has not
changed is to have yarn produce the "Already up-to-date" message on the
next build, because installing dependencies ends up taking a long time
on bigger projects.
This is more inline with how a fresh Now deployment works, where
is has to download fresh files each time. This will also fix the issue
with `@now/next` that deleted the `.next` output dir and deleting static
files upon subsequent builds.
This is still a bit unoptimized because `prepareCache()` from the
builder is not yet being invoked, but it's still more correct than
reusing the `workPath`.
Because `now dev` uses these dotenv files to define the Now secrets to
use, it would be bad practice to include them in the deployment files
since they will be using development values instead of production values.
* [now dev] Clean up `dev-router` a bit
This is a follow up to #2095 to move the `resolveRouteParameters()`
funcrtion to the top-level and other slight optimizations like not
re-parsing the URL multiple times.
* Remove unused `qs` import
This test is very flaky causing us to constantly restart CircleCI jobs
in order to do releases of `now-cli`. Considering that it's testing the
1.0 pipeline, let's just remove this one to make life easier.
This passes in the resolved `assetKey` instead of `req.url` to the
builder `requestPath` when a hard-refresh is requested, allowing the
proper single-page rebuild to happen.
* [now dev] Fix subscription resolving logic
Strip the leading `/` since the builder outputs don't have one, match
index routes, and pass the resulting subscription key to the builder.
* Fix `index` matching
* Update `@now/build-utils` to v0.4.39-canary.0
* Update `@now/build-utils` to v0.4.39
In the case of a keep-alive connection from the web browser, and a page
continuing to send HTTP requests to the dev server, sometimes the server
never shuts down. So send a 404 response with `Connection: close` to
force the web browser to close the connection.
If the builder has a `subscribe()` function, then the initial
builds are not run and instead an array of "subscriptions" is
created. When an HTTP request comes in that matches one of the
subscription patterns, then this builder will be actually be
executed.
This introduces a new object called `meta` that gets passed to the
Now Builders' `build()` function. The `isDev` property is moved to
this object, and a new property `requestPath` is also introduced.
`requestPath` represents the URL that was requested to trigger the
`build()` to be called. It may be used by builders to do incremental
compilation and only re-build the assets related to the URL that was
requested. For example, `@now/next` may use this property to only build
the page that was requested.
For `now dev`, this fixes an edge case in named capture groups
in some `routes` definitions that would lead to an error being thrown:
```
Cannot read property '1' of null
```
Also ignoring "handler" routes for now.
* Group builds with similar paths together to reduce the output
* Style the new output
* Ensure space between state and time
* Update src/util/output/builds.js
Co-Authored-By: AndyBitz <AndyBitz@users.noreply.github.com>
* Add comma between ready states
* Tell what is hidden
* Change builds and items
* [now dev] Add support for `.env` file to define Now secrets
If a `now.json` files relies on secret env vars, then they must be
defined in the user's local `.env` file otherwise `now dev` exits with
an error.
* Prettier
* Fix multi-line error output
* Use `code()` to format the dotenv file name
* Add "file" to error message for clarity
* Use `hasOwnProperty()` instead of `in`
* Apply `build.env` vars during builder `build()` invocations
Fixes#2046.
Consider the scenario where an HTML asset is built and references other
files that were produced by the build (CSS/JS/img/etc. files). The build
will happen and then the HTML page will be served, and then the browser
will request the assets on the page also with the `no-cache` header,
which would cause a second build right after the first one completed,
which is bad DX and unnecessary.
This commit introduces "build deduping logic" so that this scenario is
avoided by doing two things:
1. Not allowing the same entrypoint to be built at the same time (so if
a concurrent request happens for an asset that was produced by the same
entrypoint, the subsequent requests will wait on the already running build
instead of triggering a new one in parallel.
2. Not allowing an asset to be rebuilt if the previous build completed
less than two seconds ago. This is to catch the scenario where the
HTML page is served and the browser quickly requests the assets on
the page to avoid triggering a second rebuild.
* [now dev] Set the Now proxy and response headers
* Add `X-Real-IP` proxy header
* Set any headers defined in the matched `route` config
* Apply @amio's suggestions
This is mostly to appease TypeScript since `fn` is an optional prop,
but this shouldn't really ever happen since we run the builds before
responding to HTTP requests.
This matches how the Now proxy invokes the lambdas, where the route
`dest` query params are mixed-in to the provided `req.url`, with the
dest query params taking precedence over any conflicting user-provided
query params.
* [now dev] Use `pcre-to-regexp` to match `routes`
The now.json `routes` support PCRE syntax like named captures,
so use the `pcre-to-regexp` module to match the routes.
Fixes#2023.
* Pass the resolved router `dest` and query params to the Lambda
This just DRYs up the code a bit and centralizes the error sending logic
so that we can more easily add the HTML and JSON versions of the
responses as well.
`.gitignore` is not respected anymore for Now v2, so this was a bug.
Also removes `ncc` and `user` from the ignore list, since that issue was
fixed a while back as well.
Fixes#2021.
* [WIP] now-dev
* try invoking lambda
* add error status to dev-server
* add basic routing
* add entry for custom @now/static builder
* honor .gitignore & .nowignore while collecting files
* add route for single static file
* add test fixtures for now-dev (nodejs)
* fix miss typed @now/statics
* import types from @now/build-utils
* fix typo @now/statics -> @now/static
* revamped router
* typescript-eslint-parser -> @typescript-eslint/parser
Eliminate error while running pre-commit hooks:
SUPPORTED TYPESCRIPT VERSIONS: ~3.1.1
YOUR TYPESCRIPT VERSION: 3.2.2
* send files from local @now/static builder
* use serve-handler when no now.json
* remove http-proxy
* add type def for serve-handler
* code cleanup
* move type declarations to types.ts
* dont rely on `this.cwd` while running builder
* more type definitions
* fix invoking error
* clean code
* better debug logging
* refined request handler logic
* handle /favicon.ico with serve-handler
* make builder-cache self contained
* move builder works to dev-builder.ts
* add proxy_pass handler
* support named groups in routes
* fix creating cache dir error
* add "--nodejs-preview" solely for nodejs
* clean require.cache after required user js
* fix router & header issue in nodejs preview
* [wip] add tests for dev-router
* add tests for dev-router
* lookup "/index.*" for indexes
* refine logging
* [WIP] `now dev` progress point
Actually invoking the `@zeit/fun` module at this point.
Still lots of work to be done…
* Update `@zeit/fun` to v0.0.4
* Remove `--nodejs-preview`
To be replaced by `@zeit/fun`.
* Remove `decache` and `import-fresh`
Leftover from the `--nodejs-preview`.
* Remove "declaration: true" from `tsconfig.json`
Otherwise the ncc `dist` dir ends up full of generated `.d.ts` files.
* Remove `ignore` dep, always use `@zeit/dockerignore`
* Use tarball URL for `@zeit/fun`
Because `@zeit/fun` is not yet public on npm.
* Regenerate `yarn.lock` to fix bad integrity check on fun tarball
* Upgrade to `@zeit/fun` v0.0.6
With re-written unzipping logic utilizing `yauzl`.
* Add lambda function handling logic for the HTTP response
* Match the lambda invoke shape that Now's proxy provides
* Move deps to devDependencies
* Update `@zeit/fun` to v0.0.8
* Update `@zeit/ncc` to v0.15.0
* Attempt to fix unit test for `wait()` helper function
* Add `build.sh` script to work around ncc issues
* Fix `build.sh` script for BSD's chmod
No `--changes` flag.
* Update `@zeit/fun` to v0.0.11
* Update `@zeit/fun` to v0.0.12
* Tweak some comments
* Update `@zeit/fun` to v0.0.13
* Add `now.json` env vars to lambda functions
* Finish removing `--nodejs-preview` flag
* Style tweaks
* Use `npm-package-arg` to parse the "use" builder
* Styling
* Use the parsed `pathname` when matching routes
The querystring portion needs to be removed to match properly.
* Update `@zeit/fun` to v0.1.1
* Support `-d` for debug flag
It was already listed as such in the `--help` output.
* List the `dist/runtimes` dir as pkg "assets"
* Update `@now/build-utils` to v0.4.37-canary.0
* Update `@zeit/fun` to v0.2.0
* Update `@zeit/fun` to v0.2.1
* Rewrite the `req.url` to fix serving FileFsRef assets
* Disable re-building, build all `builds` upon server bootup
* 404 is not a redirect
* warning on more than one argument
* Fix `index` without a file extension matching
* Update `@zeit/fun` to v0.2.2
* Use `async-listen`
* Add shutdown cleanup logic
* Rename `buildLambdas()` to `executeBuilds()`
* Rename `lambda` prop to `fn`
* Misc tweaks
* Pass `isDev: true` to the builder `build()` function
* Use `Object.assign()` instead of object spread
* Set `res.statusCode` instead of `writeHead()`
* Create Lambda functions during build-time
This way, the lambda instance is re-used for subsequent HTTP requests
* Wait for cleanup operations to complete in `stop()`
* Destructure `path` for join()
* Add some missing types
* Store the `buildConfig` on the assets for reverse lookup
* Remove `console.log()`
* Attempt to make globbing faster and ignore files more accurately
* Rewrite `installBuilders()` to be idempotent
So that npm is not executed for canary tags, for example.
This is done by comparing the contents of the package.json file rather
then the `node_modules` directory.
* Use `ignore` instead of `@zeit/dockerignore` for glob-gitignore
It seems that the object produced by `@zeit/dockerignore` is not
compatible with the `glob-gitignore` module, so use the vanilla
`ignore` module instead for now as a workaround.
* Implement a `GlobIgnore` class to replace `glob-gitignore`
This allows us to continue using `@zeit/dockerignore` for proper
consistency.
Closes#1899.
* Prettier
* Skip installing built-in builders (i.e. `@now/static`)
* Remove `console.error()` calls
* Use a deterministic `workPath` directory
So that the same one is re-used in-between subsequent boots of `now dev`
* Add `now.json` validation logic
* Fix serving static assets outside the project working directory
This fixes, for example, `@now/mdx-deck` which outputs static files
from its build process.
* Add comment
* Validate the `now.json` file before launching the dev server
* Respect `maxLambdaSize` config
Closes#1950.
* Add `@types/bytes` dependency
* Make `maxLambdaSize` be optional
Co-Authored-By: TooTallNate <n@n8.io>
* WIP force reload in browser = rebuild asset behavior
* Resolve the `asset` again after re-build
* Remove logging
* Update `@zeit/fun` to v0.3.0
* Update `@now/build-utils` to v0.4.37-canary.1
Sets `npm_config_target` to the proper Node.js version for native
modules.
* Update `@zeit/fun` to v0.3.1
* Fix "hard refresh to reload" after the first rebuild
The `buildConfig` and `buildEntry` proper were not being set on the
rebuilt assets, causing the rebuild to only work the first time.
Now fixed.
* Add logic for the `now dev cache clean` command (#1977)
* Added the cache-clean command
* censer code :)
* Fix non-route match `dest` param
This makes the `go-image-to-ascii` work, since the query param URL gets
properly routed to the `/` route.
* Add support for `FileBlob` outputs
Fixes `@now/optipng`, `@now/html-minifier` and `@now/md` builders.
* Remove `console.error()` call
* Add `now dev cache clean` command
* Use the `assetKey` to look up the Content-Type on FileBlobs
Instead of the `fsPath` of the entrypoint file.
This fixes `@now/md` to return `text/html` Content-Type instead of
`text/markdown` which does not render properly in the web browser.
* Update `@zeit/ncc` to v0.16.1
Co-Authored-By: TooTallNate <n@n8.io>
* Regenerate `yarn.lock` file
* Remove leading `/` on build `src` specifications
* Use `rsync` to copy over all of `fun`'s runtime files
* Update `@zeit/fun` to v0.5.0
* Update `@zeit/fun` to v0.5.1
* try/catch the lambda invoke and send 500 upon error
* Add `rsync` to CircleCI build
* Convert `errors.js` to TypeScript to fix compilation errors
* Also accept `Cache-Control: no-cache` for rebuilding
* Prettier
* Update `@now/build-utils` to v0.4.38-canary.1
* Update `@zeit/ncc` to v0.17.0 (#2017)
* Install `@zeit/fun` from npm
* Remove `console.error()` call
Co-Authored-By: TooTallNate <n@n8.io>
* Create `NowError` subclasses
* Add `LambdaSizeExceededError`
* Return early if there's no builds
* Fixed `GET /v3/now/certs`
- Limit the response size to 20 because the endpoint doesn't have a default limit
- If the id in `/v3/now/certs/{id}` isn't a valid id the endpoint responds with a set or certs instead
- The route `/v3/now/certs/{idOrCn}` isn't supported any more
* removed limit of 20, the endpoint was updated
Before this change, only if `user` or `team` could be read from
the scope would stdarg be reported to Sentry, however it's
completely unrelated to the existence of the former and is always
useful debugging information.
* Add support for the target flag
* Show the given alias at the end
* Use the proper naming for the alias properies and include arrays
* Use the correct output
* Make sure that aliasFinal has properties
* Add support for the target flag
* Show the given alias at the end
* Use the proper naming for the alias properies and include arrays
* Use the correct output
* Make sure that aliasFinal has properties
* Added basics for new --scope flag
* Fixed usage information
* Fixed integration test
* Fixed usage information about whoami
* Brought back missing whitespace
* Do not push scope property to API
* Ensure we're only reading local config in one place
* Fixed build
* Added test
* Made scope from config work
* Correctly handle error
* Handle Now errors too when loading local config
* Removed NowError
* Revert "Removed NowError"
This reverts commit cfeebc65251d3eb07f9aeb3e548af1d23c00a18e.
* Fixed CI
* Fixed final bug
* Do not consider switch command
* Made it work as expected
* Added test
* Added yet another test for the scope property
* Added space
* fix unexpected `payment_error`
* fix unexpected `deployment_not_found`
* fix unexpected `not_authorized` and `team_deleted`
* make id optional in DeploymentNotFound
* Display transfer renewal price for domain transfers
* Check domain transferable status immediately on transfer-in
* Transfer status endpoint change to .../registry
* spelling fix
* Enable transferable check
* Update dependencies
* Added default script that will run if now fails to install
* Don't overwrite the default now script before publishing
* Copy the default now binary on publish instead of keeping it inside the dist folder
* Removed download/dist/now
* Changed text
* Send project property to api-deployments.
* Allow to talk to local api-deployments temporarly.
* Introduce the getProjectName utility.
* Use getProjectName on both legacy and latest deploy commands.
* Add now projects ls support.
* Implement 'now project add' and 'now project rm'
* Show project id
* Add basic now ls support with projects.
* Add some cosmetics changes.
* Make the UI colorful.
* Set the name as project
* Notify the user about the project name
* Remove legacy list
* Make sure 'now projects xxx' possible
* Set the project name in the list header
* Remove unwanted package
* Use --project in tests
* Force --project instead of --name
* Force the use of project property inside now.json
* Update ncc to the latest
* Remove -w from ncc
* Deprecate --name and .name instead of throwing errors
* Use the built-in fetch client
* Fix tests
* Change the order of tests
* Reset integration tests
* Remove some debug logs
* Bumped `@zeit/ncc` to latest
* Reverted lockfile
* Make linking build for dev
* Cover line 21 in util/config/local-path.js
* Heavily improved unit test coverage
* Fixed space
* Got to 90% coverage
* Removed useless code
* Made builds work
* Fixed a few lines
* Fully covered read-metadata.js
* Brought coverage to 95.38
* Removed code that was never executed
* Track everything
* Don't show badge for now
* Add now-init
* fix ci error
* refactor: (now-init) js => ts, some improvements.
- now-init works like git-clone
(create new directory / complain about overwritten / can be forced)
- Better guess user intention
(use jaro-winkler algorithm with "-" awareness)
- Stricter on arguments
- Non-TTY frendly
* add now-init to main help message
* fix miss typed args in didYouMean
* clean console.log
* output a new-line after any response to promptBool
Fix the missing '\n' when promptBool get an negative input ("n"/"N"/Enter/Abort).
Before:
~/git » now init koa
> Did you mean nodejs-koa? [y|N] > No changes made.
After:
~/git » now init koa
> Did you mean nodejs-koa? [y|N]
> No changes made.
* refine now-init output messages
* prettier code format
* update tests for now-init
* put "init" before "help" in now-help message
* remove redundant semicolon
* More flexible response error
* Consider async domain purchases
* Jumpline for domains ls
* Jumpline in domains verify
* Remove not needed body performing verification
* Add orderedAt to domains inspect
If a domain is not found the DNS record arrays are aligned
incorrectly and finally some records are shown under wrong domains.
It happens because the length of the domains array differs from the
length of array of record arrays.
* Migrate getDomainDNSRecords to Typescript
* Migrate getDNSRecords to Typescript and fix it
* Migrate cert functions to Typescript and fix issues
* Migrate certs issue to Typescript
* Minor fixes
* Removed legacy dependencies
* Added @zeit/git-hooks
* Added scripts to run before commit
* Format only the modified files
* Revert "Format only the modified files"
This reverts commit 9f4a58d2b978fa286eb7fcf38186bd9d53a2cda1.
* Revert "Added scripts to run before commit"
This reverts commit 07636d945374e404161ad281feed4180801b3509.
* Revert "Added @zeit/git-hooks"
This reverts commit 3f44f401f36fa6965d36ef28b81907c137c08abc.
* Revert "Removed legacy dependencies"
This reverts commit bb02465c59d75bf6b32bd449a04832cf4e2f4bf4.
* Fixed setup
* Print important test parts
* Logged kind
* Added more logs
* No need to remove deployments, we will prune
* Update `now alias` error to mention potentially missing name config
Running `now alias` in a project that has no `package.json` and doesn't
have a `name` property defined in `now.json` fails with a cryptic
error currently. This, in combination with
https://github.com/zeit/docs/pull/378 tries to better guide the user.
* Add a link to the `name` config property
* Handle EPERM errors when creating config files
* Catch errors when retrieving scope
* Added validation for the API URL
* Removed useless whitespace
* Removed useless file
* Cleaned up `setRawMode` mess
* Removed tests that are erroring on non-TTY
* Set environment based on release channel
* Fixed syntax
* Configure releases and environment for Sentry
* Correctly send development errors away
* Report Sentry errors with metadata
* Report username and full name of user too
* Better release name
* Bumped `@zeit/ncc` to latest version
* Do not report user errors
* Do not report mistyped arguments to Sentry
* Do not report when user aborts action
* Removed all occurances of user errors
* Do not report arg errors
* Correctly report teams and billing errors
* Prevent `setRawMode` from causing an error
* Do not report errors while developing
* Revert "Prevent `setRawMode` from causing an error"
This reverts commit 323296f30bfcca70ea5bb736db98357212f86a0a.
* Fixed whitespace
* Added code coverage report
* Correctly include everything
* Ignored useless stuff
* Combine all the coverages
* Corrected requiring
* Persist only what is needed
* Send errors away for inspection
* Allow Sentry to send them away
* Fixed dependency
* Fix credit card input
* Do not test for something that requires TTY
* Track properly
* Make it extra safe
* Added back test
* Added tests for `-V` option
* Pushed for testing
* Correctly set it
* Revert "Correctly set it"
This reverts commit c76286082d90f091ecec4a317856e91b4558e781.
* Create a new deployment each time
Made `--build-env`, `--meta` and `--dotenv` work for v1
* Locked multi static file test to v1
* Correct fix
* Final fix
* Config also adds to count
* Fixed single file test
* legacy => old
* Correctly set it
* Removed external providers
* Renamed sh provider
* Removed serverless stuff
* Fixed paths
* Properly pass token
* Fixed paths
* Check for token correctly
* Remove useless properties
* Fixed unit tests
* Keep certain things
* Adjusted remaining parts
* Fixed login
* Remove user properties that are not needed
* Store `platformVersion` for teams
* Store `platformVersion` for users
* Delete team order when logging out
* Made team commands work with tiny config
* Load data dynamically
* Made billing command show correct context
* Fixed remaining occurences of context name
* Fixed remaining pieces
* Test CI
* Clean strings when testing
* Better error check
* Render correct information when asking for credit card
* Migrate from objects to strings
* Better migration message and keep tips
* Remove the old property
* Use note for migration message
* Don't show spinner for loading missing data
* Allow for current team or user to be deleted
* Two deploy files
* Consume context name correctly
* Removed deployment types from new deployer
* Also check for bigger than 1
* Better file names
* Added upgrade message for legacy deployer
* Make help work when logged out
* Error if sub command doesn't exist when requesting help
* Fixed wording
* Support for version property added
* Better handling
* Removed useless props from deploy help
* Don't show version warnings when rendering help
* Fixed wording in readme
* Migrate even if in the middleground
* Make `now whoami` work
* Deprecated support for deploying Git repo in latest deployer
* Added usage information
* Load config separately
* Don't need local config on root
* Correct status code for help test
* Show error only in correct case
* Properly error if path does not exist
* Fixed types
* Fixed remaining occurances of old config
* Don't show warning when rendering help
* Consider version when outputting help
* Only error if path does not exist if it's not help
* Remove testing logging
* Don't error for no-verify
* Stop logging
* Fixed last test
* Added missing semicolons
* Fix indent
* Fix indent again
* Ran prettier over everything
* Added missing types
* Brought test hashes back to normal
* Exit properly when deploying
* Show clipboard note in gray and remove Node.js version
* Completed usage information
* Ensure `now whoami` only outputs the user
* Don not save user data to config
* Removed last traces of `user` and `.api` and `--team` work
* Made `now upgrade` and `now downgrade` correctly render context
* Fixed upgrade/downgrade URL for teams
* Ability to load required data
* Better file name
* Corrected check for current scope
* Don't render version warning when showing help
* Keep polling for handlers
* Render handlers
* Removed useless file
* Much better transpilation setup
* Sweetened logging
* Shortened time it takes to render ready
* Support for error ready states
* Make sure table is not wobbling
* Show times for every handler
* Attach env and build env
* Don't pass useless stuff
* Re-structured pipeline
* Allow empty config
* Do not support package.json config for new pipeline
* Removed occurances of AWS
* Drop useless packages
* Removed useless file
* Ensure the legacy pipeline is working
* Test staging proxy with legacy pipeline
* Adjust test
* Stop testing staging proxy
* Allow for anything
* Pass `handlers` and `routes` to creation endpoint
* Fixed tests
* Revert "Fixed tests"
This reverts commit e0d18a61b9520728089cb2f9e6877c1b91016312.
* Running tests should not be optional
* Support for `-m` and `--meta` added
* Support reading `meta` in local config
* Allow reading `name` from local config
* The `public` prop in local config should be considered
* Handlers deployments should use `.nowignore` and nothing else
* Allow handlers deployments without `handlers` and `routes` in the config
* Locked legacy tests to legacy platform version
* Support aliasing handlers deployments
* Removed useless condition
* Don't allow scaling handlers deployments
* Don't show warning message when deploying single file
* Fixed tests
* Made `now inspect` work
* No type for handlers deployments in list
* Indicate whether a deployment is legacy in `now inspect`
* Made `--force` work for handlers deployments
* Do not document `--dotenv` for handlers (not supported)
* Do not strip `hdl_` from handler IDs
* Fixed for upgrading to latest platform
* Better error for when `version` property is missing
* Render platform version while deploying
* Strip `hdl_` from handler IDs
This reverts commit 750d38ba9074bdc3e63ad2dab8538e51dbba5f03.
* Removed `https://` from handler list
* Removed demo mock
* Cleaner errors
* Make times and erroring work properly
* Print final deployment error
* Removed useless promise
* Prettified code
* Put config utils into correct location
* Moved even more config files
* Removed useless directory
* Removed last useless file
* Fixed wrong paths
* Fixed unit tests
* Update deployment according to handler state, like the server-side loop
* More robust deployment mechanism
* Poll every 1.5 seconds
* Prevent many requests
* Show spinner while waiting for deployment to be ready
* Render how long the deployment took
* Avoid unnecessary repainting
* Automatically remove useless `user` property from config when migrating
* Fixed property names in `now inspect`
* Render platform version for legacy pipeline
* Shortened error messages
* Support `regions` in the local config
* Support for `--regions` added
* Add metadata support for legacy deployments (#2)
* Share handlers table between deploying and inspecting
* Make `now inspect` work nicely
* Renamed handlers to builds
* Stop sending away description
* Bare UI support for builds
* Simper logic for rendering builds
* Render output of builds
* Indicate lambdas in a better way
* Render size for build output
* Do not show type for version 2 deployments
* Fixed time output for `now inspect`
* Don't handle BUILDS type
* Allow for 100% non-config deployments
* Add metadata support for now ls (#3)
* Add metadata support for now ls
So, we can do things like this:
now ls -m key1=value1 -m key2=value2
* Better description
* Fix wording
* Added final newline
* Add sentry (#4)
* Revert "Add sentry (#4)"
This reverts commit 851d1bdb0e1bbc8f329a45388865b2c41395d8c2.
* Only render build output if it was not copied
* Made `now alias` work with latest staging proxy
* Revert "Made `now alias` work with latest staging proxy"
This reverts commit 16e8998435ef03c50d2737f3ef17fa5c0c2dd33f.
* Bumped deployments API to the latest version
* Made `now rm` work
* Do not print `version` warning for single files
* Removed useless `fs-extra` dependency
* Removed useless dependencies
* Default binaries to Node 10
* Bumped Node.js in Circle CI to latest
* Bumped Xcode to get latest Node.js for integration tests
* Enabled HTTP/2 support
* Removed useless code
* Added integration test for builds
* Bumped `fetch-h2` to the latest version
* Avoid performing network request for rendering help
* Render note when viewing latest help
* Return status code `2` when exiting with help
* Fixed test for usage information
* Removed wrong text in usage info for Now 2.0
* Removed support for `--links` from v2 pipeline
* migrated => upgraded
* Added default routing for single files
* Make `--token` work as expected
* Better message for build errors
* Prevent update notification
* Prevent update notifications from showing
* Only show migration message in debug output
* Prevent flickering of state
* Improved output
* Removed useless assignment
* Corrected padding
* Less padding before state
* Corrected links for global configuration
* Fixed integration tests
* Render region for Lambdas
* Join regions in a better way
* Ensure `now.json` and `.nowignore` (the latter worked anyways) are uploaded
* Fix `build.env` in new deployment API call (#6)
* JSON log the deployment body when debugging (#8)
Otherwise it's just `[object Object]` which is useless.
* Retry to fetch on error on follow mode (#5)
* retry fetch on error on follow mode
* improve logging
* Fixed `--env` and `--build-env` CLI args (#7)
* Fix `--env` and `--build-env` CLI args
* Fall back to `undefined`
* Ensure `now switch` lists active scope in the beginning
* Removed useless code
* Error if `env` or `build.env` have wrong types
* Made `now inspect` look great
* Fixed wrong protocol in URL
* Made `now --team` work with users
* Leave PHP out of integration test for now
* Do not select PHP build
* Fixed integration tests
* Revert "12.0.0-canary.93"
This reverts commit 70a0a594b4.
* Revert "Revert "Add support for top-level "sh" auth""
This reverts commit 4273d62460.
* Revert "12.0.0-canary.92"
This reverts commit 847c71ecf2.
* Revert "Add support for top-level "sh" auth"
This reverts commit c493d651db.
* Revert "12.0.0-canary.91"
This reverts commit 06c954f8fe.
* Revert "Added metadata support for `now inspect` (#1634)"
This reverts commit 9567656b45.
* Revert "12.0.0-canary.90"
This reverts commit 966737be23.
* Revert "Added support for deployment metadata (#1604)"
This reverts commit 6c1188a787.
* Allow to add metadata in the now deploy command.
Use can add multiple items of metadata with:
'-m key1=val1 -m key2=val2'
* Add a test case.
* Update to accept and send metadata as meta.
* Use correct fields in now.create
* Add now ls support.
* Add an integration tests for ls with metadata
* Added newline
* Removed semicolon
`slot` and `limits` are now rendered when it is a Cloud v2 deployment.
Also fixes an issue with static deployments always
rendering `affinity: undefined`.
* Move getDomainNameservers function
* Don't show an error as unexpected if there is a code in the error payload
* Add start and finish cert order functions
* Integrate add wildcard cert for external domains
* Use a different endpoint to get a cert by id
* Add new command to download a certificate
* If there are no pending challenges, try to generate the cert right away
* Remove cert download
* Move DNS table options to an object
* Bugfix: cancel spinner message when finish order fails
* Restore add to work only with cert add
* Refactor obtaining cns
* Add start and finish order commands
```
> Error! An unexpected error occurred in scale: Error: This region (gru1) only accepts Serverless Docker Deployments (400)
```
This is happening because `now-cli` is validating DC names and
expanding "all" locally. However not all DCs have same features but
the client can't be aware of that. Instead of making the client
aware of the differing capabilities of the available DCs we should
pass "all" as a special DC selector, and let the backend handle
scaling properly.
* Have returnify use generators and reinstantiate them upon error
* check for status not_ready instead of 412
* poll every 5s instead of 1s for ready state notification
* poll every 2s for scale verification
* checks it is a npm deployment before reading package.json
* checks if you have a config.type first
* checks if you have a config.type first
* fixed logic for config.type
* Use correct source when listing
* Use correct source when buying domains
* Replaced the rest too
* Make adding work nicely
* Make listing work for all scopes
* Don't require address
* Bumped lockfile
* Removed more useless code
* Renamed file
* Fixed weird zlib error
* Fixed output
* Added some tests
* Add `--build-env` to `now deploy` command
Build env vars are only visible during build-time, compared to
regular env vars which are only exposed during runtime.
This also removes the client-side validation of the deployment
schema, because it makes it difficult to keep the client and server
in sync, especially as new features are added. Instead `now-cli`
should be responsible for knowing how to render the server's error
message in an informative and future-proof way so that we can
update the server and even older clients would show the validation
error properly.
* Remove `only` dependency
* Add `--build-env` CLI flag integration test
* Add more integration tests related to static builds and env
Here we are adding a few more integration tests for static builds and for using env vars in the build step.
* Add build-env related test case.
* Do not allow adding domains with subdomains
* Do not ask for confirmation when the domain exists
* Improve message when the domain is under a different account
* Fix flow errors
* Revamp domains add command
* Remove setting dns records when setting up the domain
* Refactor DNS commands
* Hide fields in system dns records and show creator
* Better formatting for dns ls
* Remove exhaustive check of dns record type
* Remove domain ids from responses in domain commands
* Change all `domains` API references to use `v3`
* Update to domains API v3
* Remove NeedUpgrade error and use CDNNeedsUpgrade where it proceeds
* Update copies when adding domains
* Remove extra blank line
* Fix flow errors
* Change params order in createAlias
* Make setupDomain return domainInfo
* Do not try to get a wildcard cert for alias when domain is external
* Update setup-domain.js
* Revert "12.0.0-canary.51"
This reverts commit 5e17fe5ad6.
* Revert "Update `@zeit/schemas` to v1.6.0"
This reverts commit b216adadc0.
* Revert "Upload the Dockerfile if it's a static deployment. (#1437)"
This reverts commit 5078c95667.
* Revert "Upgrade to webpack 4 and latest Babel (#1436)"
This reverts commit 7612d77647.
* Upload the Dockerfile if it's a static deployment.
This allows us to build the Dockerfile and upload static assets
* Allow to upload package.json as well for static deployments.
* Try to purchase a domain only when there is no other choice
* Allow eventsStream to fail during deployment
* Allow to verify instantiation without events API
* Move domains command to its own folder
* Refactor domains commands
* Add cdn to domain ls
* Add function to patch domains
* Support toggling cdnEnabled
* Better messages
* Add new cdn options to help command in domains
* use push instead of read
* don't auto-clear
* single progress bar that hangs till last chink
* print symmary beofre link
* print smmary faster
* print more discreet timestamps
* fix tests
* fix flow error
* Allow to fallback to passed body parsing a response error
* Extract domain purchase from setup-domain
* Move getCertRequestSettings
* Add create method to Now interface
* Extract print dns table and zeit world table functions
* Add support to generate certificates during deploy
* Point to v5 in deploy endpoint
* Add feedback messages when creating a cert during deployment
* Remove hardcoded references to now.sh
* Dont bump create endpoint version
* Support empty reponses in fetch
* Strip quotes from Dockerfile labels
* remove console.log
* add test
* issue normal cert for nested subdomain (#1344)
* Prefer HTTP challenge for regular certs
* 12.0.0-canary.31
* Update non-existing team test
* 12.0.0-canary.32
* Bumped `update-check` to the latest version (#1354)
* 12.0.0-canary.33
* Strip quotes from Dockerfile labels
* remove console.log
* add test
* Load schema from package
* Send config to deployment endpoint
* Upgraded @zeit/schemas to the latest version
* Removed type for now
* Added config correctly
* Corrected license file name
* Corrected readme name
* Added editorconfig
* Account for npm being down
* Print full error
* Only show full error while debugging
* Initialize polling function from args
* Remove rule of having a mandatory dest field in path alias rules
* Wait 5 seconds after getting the deployment ready
* Ignore errors coming from events stream
* Migrate to arg@2.0.0
* Refactor scale command
* Move alias.js to alias/index.js
* Move alias set to its own file
* Move alias ls to its own file
* Move alias rm to its own file
* Remove old alias and scale files
* Update alias integration test
* Fix scaling to 0
* Read scale params from now.json on deploy
* Move deploy command to its own directory
* Do not show success on downscale message
* Move getDeploymentByIdOrHost to /util/deploy
* Remove unneeded parameter in getAppName
* Better types for copyToClipboard
* Update to babel 7
* Add generator utility functions
* Add function to get deployment events
* Finish getDeploymentEvents after getting one state-change event
* Refactor deploy events and reduce verification timeout
* Reduce verification timeout for scale and alias
* Use output.log for success message in scale
* Fix integration tests
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.
Please read our [code of conduct](CODE_OF_CONDUCT.md) and follow it in all your interactions with the project.
## Local development
This project is configured in a monorepo pattern where one repo contains multiple npm packages. Dependencies are installed and managed with `yarn`, not `npm` CLI.
To get started, execute the following:
```
git clone https://github.com/zeit/now
yarn install
yarn bootstrap
yarn build
yarn lint
yarn test
```
Make sure all the tests pass before making changes.
## Verifying your change
Once you are done with your changes (we even suggest doing it along the way ), make sure all the test still run by running
```
yarn build && yarn test
```
from the root of the project.
If any test fails, make sure to fix it along with your changes. See [Interpreting test errors](#Interpreting-test-errors) for more information about how the tests are executed, especially the integration tests.
## Pull Request Process
Once you are confident that your changes work properly, open a pull request on the main repository.
The pull request will be reviewed by the maintainers and the tests will be checked by our continuous integration platform.
## Interpreting test errors
There are 2 kinds of tests in this repository – Unit tests and Integration tests.
Unit tests are run locally with `jest` and execute quickly because they are testing the smallest units of code.
### 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:
```
[Error: Fetched page https://test-8ashcdlew.now.sh/root.js does not contain hello Root!. Instead it contains An error occurred with this application.
NO_STATUS_CODE_FRO Response headers:
cache-control=s-maxage=0
connection=close
content-type=text/plain; charset=utf-8
date=Wed, 19 Jun 2019 18:01:37 GMT
server=now
strict-transport-security=max-age=63072000
transfer-encoding=chunked
x-now-id=iad1:hgtzj-1560967297876-44ae12559f95
x-now-trace=iad1]
```
In such cases you can visit the URL of the failed deployment and append `/_logs` so see the build error. In the case above, that would be https://test-8ashcdlew.now.sh/_logs
The logs of this deployment will contain the actual error which may help you to understand what went wrong.
### @zeit/node-file-trace
Some of the Builders use `@zeit/node-file-trace` to tree-shake files before deployment. If you suspect an error with this tree-shaking mechanism, you can create the following script in your project:
```js
consttrace=require('@zeit/node-file-trace');
trace(['path/to/entrypoint.js'],{
ts:true,
mixedModules:true,
})
.then(o=>console.log(o.fileList))
.then(e=>console.error(e));
```
When you run this script, you'll see all imported files. If anything file is missing, the bug is in [@zeit/node-file-trace](https://github.com/zeit/node-file-trace) and not the Builder.
## Deploy a Builder with existing project
Sometimes you want to test changes to a Builder against an existing project, maybe with `now dev` or an actual deployment. You can avoid publishing every Builder change to npm by uploading the Builder as a tarball.
1. Change directory to the desired Builder `cd ./packages/now-node`
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
6. Run `now` or `now dev` to deploy with the experimental Builder
The following page is a reference for how to create a Builder using the available Builder's API.
A Builder is an npm module that exposes a `build` function and optionally an `analyze` function and `prepareCache` function.
Official Builders are published to [npmjs.com](https://npmjs.com) as a package and referenced in the `use` property of the `now.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 Builder.
See the [Builders Documentation](https://zeit.co/docs/v2/advanced/builders) to view example usage.
## Builder Exports
### `version`
A **required** exported constant that decides which version of the Builder API to use.
The latest and suggested version is `2`.
### `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.
```js
exportanalyze({
files:Files,
entrypoint:String,
workPath:String,
config:Object
}):Stringfingerprint
```
If you are using TypeScript, you should use the following types:
```ts
import{AnalyzeOptions}from'@now/build-utils'
exportanalyze(options: AnalyzeOptions){
return'fingerprint goes here'
}
```
### `build`
A **required** exported function that returns a [Files](#files) data structure that contains the Build outputs, which can be a [Static File](#file) or a [Serverless Function](#serverless-function).
What's a Serverless Function? Read about [Serverless Function concepts](https://zeit.co/docs/v2/deployments/concepts/lambdas) to learn more.
```js
build({
files:Files,
entrypoint:String,
workPath:String,
config:Object,
meta?:{
isDev?:Boolean,
requestPath?:String,
filesChanged?:Array<String>,
filesRemoved?:Array<String>
}
}):{
watch:Array<String>,
output:Filesoutput,
routes:Object
}
```
If you are using TypeScript, you should use the following types:
```ts
import{BuildOptions}from'@now/build-utils'
exportbuild(options: BuildOptions){
// Build the code here
return{
output:{
'path-to-file':File,
'path-to-lambda':Lambda
},
watch:[],
routes:{}
}
}
```
### `prepareCache`
An **optional** exported function that is equivalent to [`build`](#build), but it executes the instructions necessary to prepare a cache for the next run.
```js
prepareCache({
files:Files,
entrypoint:String,
workPath:String,
cachePath:String,
config:Object
}):FilescacheOutput
```
If you are using TypeScript, you can import the types for each of these functions by using the following:
```ts
import{PrepareCacheOptions}from'@now/build-utils'
exportprepareCache(options: PrepareCacheOptions){
return{'path-to-file':File}
}
```
### `shouldServe`
An **optional** exported function that is only used by `now dev` in [Now CLI](https:///download) and indicates whether a [Builder](https://zeit.co/docs/v2/advanced/builders) wants to be responsible for building a certain request path.
```js
shouldServe({
entrypoint:String,
files:Files,
config:Object,
requestPath:String,
workPath:String
}):Boolean
```
If you are using TypeScript, you can import the types for each of these functions by using the following:
```ts
import{ShouldServeOptions}from'@now/build-utils'
exportshouldServe(options: ShouldServeOptions){
returnBoolean
}
```
If this method is not defined, Now CLI will default to [this function](https://github.com/zeit/now/blob/52994bfe26c5f4f179bdb49783ee57ce19334631/packages/now-build-utils/src/should-serve.ts).
### Builder Options
The exported functions [`analyze`](#analyze), [`build`](#build), and [`prepareCache`](#preparecache) receive one argument with the following properties.
**Properties:**
-`files`: All source files of the project as a [Files](#files) data structure.
-`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`.
## Example: html-minifier
Let's walk through what it takes to create a simple builder that takes in a HTML source file and yields a minified HTML static file as its build output.
While this is a very simple builder, the approach demonstrated here can be used to return anything: one or more static files and/or one or more lambdas.
## Setting up the module
### Defining the analyze step
The `analyze` hook is optional. Its goal is to give the developer a tool to avoid wasting time _re-computing a build_ that has already occurred.
The return value of `analyze` is a _fingerprint_: a simple string that uniquely identifies the build process.
If `analyze` is not specified, its behavior is to use as the fingerprint the combined checksums of **all the files in the same directory level as the entrypoint**. This is a default that errs on making sure that we re-execute builds when files _other than the entrypoint_ (like dependencies, manifest files, etc) have changed.
For our `html-minify` example, we know that HTML files don't have dependencies. Therefore, our analyze step can just return the `digest` of the entrypoint.
Our `index.js` file looks as follows:
```js
exports.analyze=function({files,entrypoint}){
returnfiles[entrypoint].digest
}
```
This means that we will only re-minify and re-create the build output _only if the file contents (and therefore its digest) change._
### Defining the build step
Your module will need some utilities to manipulate the data structures we pass you, create new ones and alter the filesystem.
To that end, we expose our API as part of a `@now/build-utils` package. This package is always loaded on your behalf, so make sure it's only included as `peerDependencies` in your `package.json`.
Builders can include dependencies of their liking:
If our builder had performed work that could be re-used in the next build invocation, we could define a `prepareCache` step.
In this case, there are not intermediate artifacts that we can cache, and our `analyze` step already takes care of caching the full output based on the fingerprint of the input.
## Technical Details
### Execution Context
A [Serverless Function](https://zeit.co/docs/v2/advanced/concepts/lambdas) is created where the builder 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.
If you need to share state between those steps, use the filesystem.
### Directory and Cache Lifecycle
When a new build is created, we pre-populate the `workPath` supplied to `analyze` with the results of the `prepareCache` step of the previous build.
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/builders#technical-details).
### Accessing Environment and Secrets
The env and secrets specified by the user as `build.env` are passed to the builder process. This means you can access user env via `process.env` in Node.js.
### Utilities as peerDependencies
When you publish your builder to npm, make sure to not specify `@now/build-utils` (as seen below in the API definitions) as a dependency, but rather as part of `peerDependencies`.
## Types
### `Files`
```ts
import{File}from'@now/build-utils'
typeFiles={[filePath: string]:File}
```
This is an abstract type that is implemented as a plain [JavaScript Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object). It's helpful to think of it as a virtual filesystem representation.
When used as an input, the `Files` object will only contain `FileRefs`. When `Files` is an output, it may consist of `Lambda` (Serverless Functions) types as well as `FileRefs`.
An example of a valid output `Files` object is:
```json
{
"index.html":FileRef,
"api/index.js":Lambda
}
```
### `File`
This is an abstract type that can be imported if you are using TypeScript.
```ts
import{File}from'@now/build-utils'
```
Valid `File` types include:
- [`FileRef`](#fileref)
- [`FileFsRef`](#filefsref)
- [`FileBlob`](#fileblob)
### `FileRef`
```ts
import{FileRef}from'@now/build-utils'
```
This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents an abstract file instance stored in our platform, based on the file identifier string (its checksum). When a `Files` object is passed as an input to `analyze` or `build`, all its values will be instances of `FileRef`.
**Properties:**
-`mode : Number` file mode
-`digest : String` a checksum that represents the file
**Methods:**
-`toStream() : Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `FileFsRef`
```ts
import{FileFsRef}from'@now/build-utils'
```
This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents an abstract instance of a file present in the filesystem that the build process is executing in.
**Properties:**
-`mode : Number` file mode
-`fsPath : String` the absolute path of the file in file system
**Methods:**
-`static async fromStream({ mode : Number, stream : Stream, fsPath : String }) : FileFsRef` creates an instance of a [FileFsRef](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) from `Stream`, placing file at `fsPath` with `mode`
-`toStream() : Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `FileBlob`
```ts
import{FileBlob}from'@now/build-utils'
```
This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents an abstract instance of a file present in memory.
**Properties:**
-`mode : Number` file mode
-`data : String | Buffer` the body of the file
**Methods:**
-`static async fromStream({ mode : Number, stream : Stream }) :FileBlob` creates an instance of a [FileBlob](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) from [`Stream`](https://nodejs.org/api/stream.html) with `mode`
-`toStream() : Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `Lambda`
```ts
import{Lambda}from'@now/build-utils'
```
This is a [JavaScript class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), called a Serverless Function, that can be created by supplying `files`, `handler`, `runtime`, and `environment` as an object to the [`createLambda`](#createlambda) helper. The instances of this class should not be created directly. Instead use a call to [`createLambda`](#createlambda).
**Properties:**
-`files : Files` the internal filesystem of the lambda
-`handler : String` path to handler file and (optionally) a function name it exports
-`runtime : LambdaRuntime` the name of the lambda runtime
-`environment : Object` key-value map of handler-related (aside of those passed by user) environment variables
### `LambdaRuntime`
This is an abstract enumeration type that is implemented by one of the following possible `String` values:
-`nodejs10.x`
-`nodejs8.10`
-`go1.x`
-`java-1.8.0-openjdk`
-`python3.6`
-`python2.7`
-`dotnetcore2.1`
-`dotnetcore2.0`
-`dotnetcore1.0`
## JavaScript API
The following is exposed by `@now/build-utils` to simplify the process of writing Builders, manipulating the file system, using the above types, etc.
This utility allows you to download the contents of a [`Files`](#files) data structure, therefore creating the filesystem represented in it.
Since `Files` is an abstract way of representing files, you can think of `download` as a way of making that virtual filesystem _real_.
If the **optional**`meta` property is passed (the argument for [build](#build)), only the files that have changed are downloaded. This is decided using `filesRemoved` and `filesChanged` inside that object.
```js
awaitdownload(files,workPath,meta)
```
### `glob`
Signature: `glob() : Files`
```ts
import{glob}from'@now/build-utils'
```
This utility allows you to _scan_ the filesystem and return a [`Files`](#files) representation of the matched glob search string. It can be thought of as the reverse of [`download`](#download).
The following trivial example downloads everything to the filesystem, only to return it back (therefore just re-creating the passed-in [`Files`](#files)):
[](https://spectrum.chat/zeit)
**Note**: The [canary](https://github.com/zeit/now/tree/canary) branch is under heavy development – the stable release branch is [master](https://github.com/zeit/now/tree/master).
## Usage
To install the latest version of Now CLI, visit [zeit.co/download](https://zeit.co/download) or run this command:
```
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
```
## Documentation
For details on how to use Now CLI, check out our [documentation](https://zeit.co/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
As always, you should use `yarn test-unit` to run the tests and see if your changes have broken anything.
## How to Create a Release
If you have write access to this repository, you can read more about how to publish a release [here](https://github.com/zeit/now/wiki/Creating-a-Release).
All PRs are submitted to the `canary` branch. Once a PR is merged into the `canary` branch, it should be published to npm immediately using the Canary Channel.
## Version Selection
Since Builders are published to [npmjs.com](https://npmjs.com), this makes versioning works the same for Builders as it does for any npm package. The `use` statement in [now.json](https://zeit.co/docs/v2/advanced/configuration#builds) has a similar syntax to `npm install`.
The following are valid examples [@now/node](https://www.npmjs.com/package/@now/node?activeTab=versions):
-`@now/node`
-`@now/node@0.7.3`
-`@now/node@canary`
-`@now/node@0.7.2-canary.2`
We always recommend using the latest version by leaving off the dist-tag suffix, `@now/node` for example.
When generating a certificate, we have to prove ownership over the domain
for the Certificate Authority (CA) that issues it. This error means that
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,
it could be that:
- The domain was acquired recently, and it might not be ready for use yet.
- Required DNS records have not propagated yet.
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
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.
- 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.
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
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,
it could be that:
- The domain was acquired recently, and it might not be ready for use yet.
- Required DNS records have not propagated yet.
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
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.
The domain you supplied cannot be verified using either the intended set of nameservers of the given verification TXT record.
#### Possible Ways to Fix It
Apply the intended set of nameservers to your domain or add the given TXT verification record through your domain provider.
You can retrieve both the intended nameservers and TXT verification record for the domain you wish to verify by running `now domains inspect <domain>`.
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.
If you would not like to verify your domain, you can remove it from your account using `now domains rm <domain>`.
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).
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.
We require this to ensure your app works as you intend it to, in the Now Dev environment, and to provide you with a way to mirror or separate private environment variables within your applications, for example when connecting to a database.
Read below for how to address this error.
#### Possible Ways to Fix It
The error message will list environment variables that are required and which file they are required to be included in (either `.env` or `.env.build`).
If the file does not exist yet, please create the file that the error message mentions and insert the missing environment variable into it.
For example, if the error message shows that the environment variable `TEST` is missing from `.env`, then the `.env` file should look like this:
```
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/).
The `--scope` flag was specified, but there's no value for it available.
#### Possible Ways to Fix It
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`.
@@ -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 `--team` flag. This needs to be the slug of the team as which you'd like to act. As an example, if your team URL is `https://zeit.co/teams/zeit`, the slug is `zeit`.
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.
The `package.json` file of the used project invokes `now dev` as `dev` script. This would cause `now dev` to recursively invoke itself.
#### Possible Ways to Fix It
Adjust the `dev` script inside the `package.json` file to match what your framework uses to begin development mode, e.g. `next` for Next.js or `gatsby develop` for Gatsby.
`@now/next` has two modes: `legacy` and `serverless`. You will always want to use the `serverless` mode. `legacy` is to provide backwards compatibility with previous `@now/next` versions.
The differences:
Legacy:
- Minimal lambda size of `2.2Mb` (approximately)
- Forces `next@v7.0.2-canary.49` and `next-server@v7.0.2-canary.49`
- Forces all `dependencies` to be `devDependencies`
- Loads `next.config.js` on bootup, breaking sometimes when users didn't use `phases` to load files
- Used `next-server` which is the full Next.js server with routing etc.
- Runs `npm install`
- Runs `npm run now-build`
- Runs `npm install --production` after build
Serverless:
- Minimal lambda size of `49Kb` (approximately)
- Uses Next.js build targets (`target: 'serverless'`) in `next.config.js`. [documentation](https://github.com/zeit/next.js#summary)
- Does not make changes to your application dependencies
- Does not load `next.config.js` ([as per the serverless target documentation](https://github.com/zeit/next.js#summary))
- Runs `npm install`
- Runs `npm run now-build`
- Does not run `npm install --production` as the output from the build is all that's needed to bundle lambdas.
- No runtime dependencies, meaning smaller lambda functions
- Optimized for fast [cold start](https://zeit.co/blog/serverless-ssr#cold-start)
#### Possible Ways to Fix It
In order to create the smallest possible lambdas Next.js has to be configured to build for the `serverless` target.
1. Serverless Next.js requires Next.js 8 or later, to upgrade you can install the `latest` version:
```
npm install next --save
```
2. Add the `now-build` script to your `package.json`
```json
{
"scripts":{
"now-build":"next build"
}
}
```
3. Add `target: 'serverless'` to `next.config.js`
```js
module.exports={
target:'serverless',
// Other options are still valid
};
```
4. Optionally make sure the `"src"` in `"builds"` points to your application `package.json`
# `@now/static-build` Failed to detect a server running
#### Why This Warning Occurred
When running `now dev`, the `@now/static-build` builder proxies relevant HTTP
requests to the server that is created by the `now-dev` script in the
`package.json` file.
In order for `now dev` to know which port the server is running on, the builder
is provided a `$PORT` environment variable that the server _must_ bind to. The
error "Failed to detect a server running on port" is printed if the builder fails
to detect a server listening on that specific port within five minutes.
#### Possible Ways to Fix It
Please ensure that your `now-dev` script binds the spawned development server on
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:
```
{
...
"scripts": {
...
"now-dev": "gatsby develop -p $PORT"
}
}
```
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)
You specified the `--scope` flag and specified the ID or slug of a team that you're not a part of or a user whose account you don't own. This problem could also occur if your user credentials aren't valid anymore.
#### Possible Ways to Fix It
- Make sure commands like `now ls` work just fine. This will ensure that your user credentials are valid. If it's not working correctly, please log in again using `now login`.
- Ensure that the scope you specified using `--scope` shows up in the output of `now switch`. If it doesn't, you're either not part of the team (if you specified a team) or you logged into the wrong user account.
You specified the `--scope` flag and specified the ID or slug of a team that does not exist or that you're not a part of. Similarly you might have specified the ID or username of user whose account you don't own.
#### Possible Ways to Fix It
If you're sure the specified team exists, please make sure that you're a part of it (ask an owner of the team to invite you). If you specified the identifier of a user, make sure you are actually the owner of this account.
Otherwise, either create a team with the specified slug or ensure that the identifier is correct if you're sure that the scope exists.
You specified the `--team` flag and specified the slug of a team that you're not a part of. This problem could also occur if your user credentials aren't valid anymore.
#### Possible Ways to Fix It
- Make sure commands like `now ls` work just fine. This will ensure that your user credentials are valid. If it's not working correctly, please log in again using `now login`.
- Ensure that the team you specified using `--team` shows up in the output of `now switch`. If it doesn't, you're not part of it. In that case, please ask an owner of the team to invite you.
This plugin generates [Now Routes](https://zeit.co/docs/v2/advanced/routes) for [redirects](https://www.gatsbyjs.org/docs/actions/#createRedirect) you configured for to your Gatsby project.
### Usage
1. Install the plugin:
```
npm install gatsby-plugin-now --save-dev
```
2. Add it to the configuration file:
```
// gatsby-config.js
module.exports = {
plugins: [
'gatsby-plugin-now'
]
}
```
3. [Deploy your project to ZEIT Now](https://www.gatsbyjs.org/docs/deploying-to-zeit-now/)
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.