Adds support for bundling properly the dependencies used by the experimental instrumentation hook file, `instrumentation.js`, by adding the generated nft file to the list of server deps
fixes NEXT-631
There's [a PR](https://github.com/remix-run/remix/pull/5537) opened on
Remix to add an Edge compatible entrypoint to `@remix-run/vercel`. This
is only really needed specifically for projects that have a custom
server.js entrypoint file, which is not strictly necessary anymore, but
there are some edge cases where a project might still want to have one.
So this PR is necessary for those kinds of projects to be able to use
Edge runtime.
Even when they merge the PR, it would be good to leave this injection
code around for some time to continue support for older
`@remix-run/vercel` versions in existing projects.
Updates the `responseHeaders` probe checks to properly test for multiple headers with the same name.
Previously the probes were using `headers.get()` which concats multiple headers into a single string, which results in the test not really checking if there are in fact multiple headers with the same name. Using `headers.raw()` allows us to properly test for that.
A couple of Python tests that were already checking for multiple `set-cookie` headers needed to be updated to match the full value, since the check now properly validates the full string match of each header (before it was basically just doing a `string.includes()` check).
This is a precursor for https://github.com/vercel/vercel/pull/9533.
If for some reason the `get-latest-worker.js` fails to get the dist-tags, it doesn't check the status code and proceeds to `JSON.parse()` the response. If for example npm returns 401 Unauthorized, you get a cryptic JSON parse error message.
Fixes this error:
```
@vercel/node:test-unit: FAIL test/dev.test.ts (14.891 s)
@vercel/node:test-unit: × runs a mjs endpoint (5057 ms)
@vercel/node:test-unit: × runs a esm typescript endpoint (5122 ms)
@vercel/node:test-unit:
@vercel/node:test-unit: ● runs a mjs endpoint
@vercel/node:test-unit:
@vercel/node:test-unit: thrown: "Exceeded timeout of 5000 ms for a test.
@vercel/node:test-unit: Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
```
https://github.com/vercel/vercel/actions/runs/4247588973/jobs/7385801227#step:9:1039
In a Turborepo setup, there was this in the `remix.config.js` file:
```js
watchPaths: [require.resolve("ui")],
```
Since we attempt to `require()` the `remix.config.js` file in order to
determine whether or not it is using ESM syntax, this would fail since
the require happens before the Build Command is executed.
To fix, treat any non `ERR_REQUIRE_ESM` error as CJS, instead of
re-throwing the error. If there really is an issue with importing the
config, then that'll happen right after when `remix build` is doing it.
When the project defines a custom `server.js` file in `remix.config.js`,
then don't override that with the bundled
`server-node.mjs`/`server-edge.mjs` file. This allows for a custom
`getLoadContext()` function to remain supported.
In order for Edge runtime to be supported, a [companion
PR](https://github.com/remix-run/remix/pull/5537) for
`@remix-run/vercel` adapter has been created with a dedicated entrypoint
for when Edge runtime is being used. In order to support Edge on
previous versions of the adapter, we may end up patching the package to
enable support, but that will happen in a follow-up PR.
Related to https://github.com/orgs/vercel/discussions/1596.
---------
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
Make it so that the `export const config = { runtime }` value is "inherited" from a parent route, if it is defined.
For example, "edge" can be defined in `app/root.tsx`, and so all routes will use the Edge runtime by default, unless `"runtime": "nodejs"` is used more specifically in a route deeper in the route hierarchy.
`vc remove --safe <project>` has a unique code path that queries all deployments by project id. This function calls v4 deployments endpoint and returns the legacy deployment structure.
The problem is the `vc remove` command relies on the new `Deployment` structure defined by the v13 get deployment endpoint.
I've updated the `getDeploymentsByProjectId()` function to transform the legacy structure into the current one.
Fixes#9321
Linear: https://linear.app/vercel/issue/VCCLI-538/vc-rm-project-safe-is-not-working
After many hours of debugging, I tracked down that having an old Node
version (eg 14.x) listed in your Vercel project settings can result in
the build step failing with a confusing and unhelpful error message
"`@vercel/next` No Serverless Pages Built". Note that this is a case
where it "can" cause it to fail, including with NextJS 13.1.6 and Vercel
CLI 28.16.2, but it is not guaranteed to fail. I have six NextJS
projects. They have identical next.config.js, tsconfig.json,
eslintrc.js, and .gitignore files, and other than a few seemingly
non-critical dependencies they have identical package.json files. Four
of the six consistently built and deployed in the cloud without issue.
Two consistently failed to build in the cloud. All built successfully
locally including using vercel build locally, and all would vercel
deploy --prebuilt successfully. Switching all the vercel cloud project
settings from Node 14.x to Node 18.x enabled all the projects to build
and deploy successfully in the vercel cloud without needing local vercel
build and local vercel deploy --prebuilt steps.
---------
Co-authored-by: Steven <steven@ceriously.com>
This PR changes the fallback headers that relate to RSC to the defaults that Next.js currently uses. Also, it sets the initial `vary` header to all prerendered routes when RSC is enabled (`routesManifest?.rsc`), even for the pages directory.
That's because although the pages directory won't return any RSC payload, it can still be used in a project that contains app routes. When the app route requests a page route for RSC data, it's important for the browser to not accidentally cache that result hence we need the `vary` header to set there as well.
More related discussions can be found [here](https://linear.app/vercel/issue/NEXT-382/add-vary-rsc-etc-header-to-all-responses-to-ensure-browser-caching).
In order to have Next.js Lambdas show their operation types more specifically in the build output in the dashboard, the builder needs to return the Lambdas with `operationType` set to the appropriate value.
This PR adds those values. This allows the Richer Deployment Outputs to show the different types of serverless functions:
<img width="228" alt="Screenshot 2023-02-03 at 3 49 42 PM" src="https://user-images.githubusercontent.com/41545/216717479-d02fbd4a-fa62-479d-8b65-bd77fdcdb26c.png">
Missed this occurrence so it still prevents the upload of serverless
functions that have a mem value that is not dividable by 64.
Should be the last place before we can ship the documentation update.
#### Related PRs
- #9440
Co-authored-by: Steven <steven@ceriously.com>
When WEBrick receives `HEAD` requests it discards the body (i.e.
`req.body.nil? => true`), this causes Vercel to throw a
`BODY_NOT_A_STRING_FROM_FUNCTION` since it is expecting the serverless
function to respond with a string in the body.
---------
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Steven <steven@ceriously.com>
This PR changes the way cron jobs are being created in the build output
API. This is my first time contributing here. If you see something
unusual, let me know.
✅ Good for review
Our goal is to:
- Allow creating cron jobs via the `crons` property of `vercel.json` for
end users
- Allow framework authors to create cron jobs on Vercel via the `crons`
property of the Build Output API configuration
---
As you can see, we removed the previous implementation where cron jobs
could be configured at the function code level (export const cron = ""),
on top of vercel.json `functions` property. Here's why:
- All frameworks would have to implement the configure at the function
code level
- Not all frameworks can easily map a path to a specific function
(example: SvelteKit) and would have to bail on bundling functions inside
the same lambda
- Configuring a path + scheduler provides a better mapping of what cron
jobs are as of today: API routes on a schedule and not functions on a
schedule
- Dynamic routes Cron Jobs will be supported:
/api/crons/sync-slack-team/230
- Query parameters will be supported support:
/api/crons/sync-slack-team/230?secret=32k13l2k13lk21 (= securing cron
jobs v0)
- 100% frameworks compatibility from day one
Next.js and other frameworks may choose to implement their own cron jobs
feature that will then need to be configured through the `crons`
property of `config.json` (build output API).
cc @timneutkens @Rich-Harris
Internal thread:
https://vercel.slack.com/archives/C04DWF5HB6K/p1676366892714349
Adds framework to Lambda and edge build outputs so that we can distinguish which framework they originated from when certain features should be applied to specific frameworks.
This PR adds framework to the outputs. Part 1: https://github.com/vercel/vercel/pull/9448
ticket: ED-131
x-ref: [slack channel](https://vercel.slack.com/archives/C042LHPJ1NX)
`spawnSync()` does not throw if the command can't be found in the PATH or if an error occurs. If we use `execFileSync()`, it will throw and that was likely the desired behavior in this test utility function.
This adds a new package to the monorepo: `@vercel/remix-entry-server`
The purpose of this package is to provide most of the implementation of
the Remix `app/entry.server.tsx` file with proper support for the Vercel
Serverless and Edge runtimes, specifically in regards to React 18
streaming.
The reason that this package is necessary, as opposed to just updating
our Remix template, is due to the fact that Serverless and Edge runtimes
require a different implementation. This is because the
`react-dom/server` package exports different functions for the Node
(`renderToPipeableStream()`) vs. Edge (`renderToReadableStream()`)
bundles, and thus this package also has two different implementations
(by utilizing the `main` and `browser` fields in `package.json`).
Usage of this package in a Remix application's `app/entry.server.tsx`
file looks like:
```tsx
import handleRequest from "@vercel/remix-entry-server";
import { RemixServer } from "@remix-run/react";
import type { EntryContext } from "@remix-run/server-runtime";
export default function (
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
const remixServer = <RemixServer context={remixContext} url={request.url} />;
return handleRequest(request, responseStatusCode, responseHeaders, remixServer)
}
```
Once this package is published then we can update our own Remix template
to utilize it, enabling React 18 streaming for both Vercel runtimes.
We no longer require the memory to be provided in steps of 64mb for
serverless functions.
Instead the memory can now be chosen freely from `128mb` to `3008mb` in
`1mb increments`.
Updates the `vercel.json` schema to reflect that change.
Adds support for server-side rendered Remix using Edge Functions. This runtime can be enabled on a per-page basis, by adding the following to a page within the `app/routes` directory:
```js
export const config = {
runtime: 'edge'
};
```
Additionally, this PR further supersedes the `@remix-run/vercel` runtime adapter, because we will always inject our own server entrypoint. So the logic to ensure that package exists in the project's `package.json` has been removed (so this closes#9011). The only requirement is that the Remix project has `@remix-run/node` as a dependency, which is the case for the vanilla Remix template so I think that's a fair assumption.
To make Edge Functions work, we need to ensure that `remix build` is executed with a few specific configuration values in place, so this change wraps the existing `remix.config.js` file and adds our own to make sure those values are in place (and then cleans itself up after the build command is executed).
Finally, the reading of the Remix config logic was simplified by using the `readConfig()` function from the `@remix-run/dev` package, which also includes the routes manifest, so the hacky `vm` running logic to retrieve the manifest was able to be removed.
Closes#8784.
Closes#9011.
---
# To test this out:
1. Ensure that Remix dependencies are running _at least version `1.5.0`_ (which is when `writeReadableStreamToWritable()` was added to `@remix-run/node`).
2. Add the following line of code to any page in your Remix application’s `app/routes/*` directory:
```jsx
export const config = { runtime: 'edge' };
```
3. Set an Environment Variable on your Vercel Project:
- Name: `VERCEL_CLI_VERSION`
- Value: `https://vercel-git-update-remix-edge.vercel.sh/tarballs/vercel.tgz`
4. Make a deployment, either by running `vercel deploy` in the CLI, or by pushing a Git commit to your repository which has a Vercel Git integration enabled.
In an effort to speed up CI, we should update the lowest common
denominator to Node.js 16
Note: In April, Node.js 14 will reach EOL so we can update tsconfig
targets and ship a major semver at that time.
---------
Co-authored-by: JJ Kasper <jj@jjsweb.site>
This makes `react-dom` work as expected from within Edge Functions. Otherwise, NFT will only select the Node.js version of the files which do not work with react-dom within an Edge Function.
The error messages shown during `vc dev` when an Edge or Serverless functions returns a promise that ends up being rejected could be better.
Main changes:
- removed "socket hang up" error messages because they were not helpful to the user
- changed serverless function error handling to log explicitly and exit
- changed serverless function error message to include the request path
- changed edge function error message to include request path and a faked (but useful) stack trace
## Current
### In Production
**Serverless Function:** In production, for a serverless function rejected promise, you'll see this in the logs:
```
Unhandled Promise Rejection {
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "Error: intentional break!",
"reason": {
"errorType": "Error",
"errorMessage": "intentional break!",
"stack": [
"Error: intentional break!",
" at handler (/var/task/api/node.js:3:9)",
" at Server.<anonymous> (/var/task/___vc/__helpers.js:813:19)",
" at Server.emit (node:events:527:28)",
" at parserOnIncoming (node:_http_server:956:12)",
" at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)"
]
},
"promise": {},
"stack": [
"Runtime.UnhandledPromiseRejection: Error: intentional break!",
" at process.<anonymous> (file:///var/runtime/index.mjs:1194:17)",
" at process.emit (node:events:539:35)",
" at process.emit (/var/task/___vc/__sourcemap_support.js:559:21)",
" at emit (node:internal/process/promises:140:20)",
" at processPromiseRejections (node:internal/process/promises:274:27)",
" at processTicksAndRejections (node:internal/process/task_queues:97:32)"
]
}
Unknown application error occurred
Runtime.Unknown
```
**Edge Function:** In production, for an edge function rejected promise, you'll see this in the logs:
```
Error: intentional break!
at (api/edge.js:10:10)
```
In both cases, in the browser, you see the "This Serverless/Edge Function has crashed." template with no error message or stack trace.
### In `vc dev`
**Serverless Function:** In `vc dev`, for a serverless function rejected promise, you'll see this in the output:
```
Unhandled rejection: Error: intentional break!
at handler (/Users/smassa/source/demo/edge-errors/api/node.js:3:9)
at Server.<anonymous> (/Users/smassa/source/vercel/vercel/packages/node-bridge/helpers.js:813:19)
at Server.emit (node:events:513:28)
at Server.emit (node:domain:489:12)
at parserOnIncoming (node:_http_server:998:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Error: Failed to complete request to /api/node: Error: socket hang up
```
**Edge Function:** In `vc dev`, for an edge function rejected promise, you'll see this in the output:
```
Unhandled rejection: intentional break!
Error: Failed to complete request to /api/edge: Error: socket hang up
```
## After Changes
### In `vc dev`
**Serverless Function:** In `vc dev`, for a serverless function rejected promise, you'll see this in the output:
```
Rejected Promise returned from /api/node: Error: intentional break!
at handler (/Users/smassa/source/demo/edge-errors/api/node.js:3:9)
at Server.<anonymous> (/Users/smassa/source/vercel/vercel/packages/node-bridge/helpers.js:824:19)
at Server.emit (node:events:513:28)
at Server.emit (node:domain:489:12)
at parserOnIncoming (node:_http_server:998:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
```
**Edge Function:** In `vc dev`, for an edge function rejected promise, you'll see this in the output:
```
Rejected Promise returned from api/edge: intentional break!
at (api/edge.ts)
```
We can't show the real stack trace for Edge Functions because the bundling + VM execution mangles it. What's rendered here is a fake one, but it's still useful to the user.
If we currently showed the real stack trace for edge functions, it would look like:
```
Rejected Promise returned from api/edge: intentional break!
at edge (evalmachine.<anonymous>:35:9)
at FetchEvent.<anonymous> (evalmachine.<anonymous>:87:26)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async EdgeRuntime.dispatchFetch (evalmachine.<anonymous>:29:7)
at async Server.handler (/Users/smassa/source/vercel/vercel/node_modules/.pnpm/edge-runtime@2.0.0/node_modules/edge-runtime/src/server/create-handler.ts:46:26)
```
## Follow Up
We'll look into improving the Edge Function error stack traces later.
These tests will run if one of the conditions is met:
- any change to `./examples`
- any changes to `./packages/frameworks`
The test ensures that examples can build and deploy without errors.
In a future PR, we could improve these tests to make requests to the
test deployment (like we do for probes).
Since turbo and nx only consider `NEXT_PUBLIC_` prefixed env variables for the cache key this ensures we expose variables that affect the build in that format as well so that an incompatible build cache isn't attempted to be leveraged. No additional tests were added here as this related to build cache which can't be reliably tested here.
x-ref: [slack thread](https://vercel.slack.com/archives/C03S8ED1DKM/p1675821643786319)
If there is a monorepo that has one project at the root level we want to
return commands without the relative to root prefixes
---------
Co-authored-by: Chris Barber <chris.barber@vercel.com>
There are times when a request can arrive for a Python function with headers as a list. One of those examples is this header `x-vercel-proxied-for` which apparently is set twice. Example:
`[b'x-vercel-proxied-for', [b'207.81.134.243', b'172.71.147.74']]`
I took a quick scan through the other Python server implementations and I don't think any of them manipulate the value of the HTTP headers, the way the ASGI one does so I think we are good there.
To reproduce:
`curl https://..../ -H "foo: bar" -H "foo: bar"`
Will fail.
Fixes: https://github.com/vercel/vercel/issues/9132
Both `runtime: undefined` and `runtime: nodejs` have the same behavior
but we want to change that in the future.
The first step is to see if `runtime: nodejs` is currently used at all.
Instead of outputting a single SSR function at `/render` path, scan the
build manifest file to determine the proper paths to output the SSR
function at.
When Root Directory setting is used, and/or `vc build --output` is used,
do an intelligent "merge" (move) operation rather than copying the
contents of the build output directory to the destination. This should
overall be faster and avoid disk space issues for larger projects.
Instead of using `pathPrefix` from the Redux store, grab the value
directly from the "BuildArgs" passed to `onPostBuild()`. This value
seems to properly reflect whether or not `--prefix-path` mode was
enabled during the Gatsby build process.
We are getting reports of some larger Gatsby projects running out of
disk space during build which seem to be the result of copying the
static directory multiple times.
So move instead of copying, which doesn't fully solve the problem, but
it does kick the can down the road a bit. Very large projects would
probably still hit the disk limit at some point. Anyways, moving is
faster than copying so this is still a net positive.
The `.vercel/output` directory gets wiped away when `--output` is _not_ being used, but it should be deleted even when the flag is being used so that build scripts targeting Build Output API directly always start with a fresh slate.
1. `commandForIgnoringBuildStep` should be run at the project directory level not the monorepo root level
2. Simplifying the `installCommand` because doesn't need the relative root unless it is `npm`
Github Action for actions/cache has an issue that could cause it to take
1 hour and then timeout while trying to restore the cache.
Since `actions/setup-node` is no longer used to restore the pnpm cache,
the `timeout-minutes: 5` doesn't do anything for this action.
Instead we need to put an env variable on the `actions/cache` Github
Action to actually set the restore cache timeout.
```
env:
SEGMENT_DOWNLOAD_TIMEOUT_MINS: 5 # See https://github.com/actions/cache/issues/810
```
- See discussion here https://github.com/vercel/vercel/discussions/9340
- Related to actions/cache#810
- Follow up to #8639
Around 6 months ago, @styfle brought to my attention how `rename()` in build-utils used `reduce()` and could be written better. So, I rewrote it.
Before, the code would create a new `Files` object and copy the contents of the previous `Files` object. This caused heavy garbage collection and memory thrashing.
Instead, I created a single `Files` object, then add the files to it.
Results:
| # Files | Before | After |
|---|---|---|
| 1,000 | 75 ms | 1 ms |
| 10,000 | 10.6 s | 7 ms |
| 20,000 | 44.6 s | 16 ms |
| 30,000 | 105.5 s | 22 ms |
| 100,000 | Too long | 73 ms |
`.vercel/output` is already made fresh when running `vc build`, so the
plugin should not be doing this. In fact, it makes the `builds.json`
file be wiped away, which we don't want to happen.
Right now, static-build will add the necessary Gatsby plugins to the project's `package.json` at build-time, which has been bothersome for package managers when using a frozen lockfile.
Another issue with it is that we install `latest` version of the plugin, so the version used becomes disjointed from the CLI version itself, which leads to unpredictability when trying to debug issues or help users roll back to a previous behavior if something breaks.
So instead of patching `package.json` directly, include the plugins as deps of static-build itself, and create symlinks to those paths into the project's `node_modules` directory.
We currently don't make it obvious when `next export` is being leveraged which de-opts features like `middleware`, `rewrites`, `redirects`, etc. so this adds a notice to let users know when we are using `next export` output.
Adds some unit tests for the gatsby injection logic.
These are net new since we've heavily changed the injection logic. The tests and fixtures in `build-fixtures` and `builds.test.js` are seemingly not executed. We may delete those here too.
The `NODE_OPTIONS` env var value is wrong here and we shouldn't be overriding the user's setting to begin with.
Typically, it will be assigned in a build container or project settings.
We had Turborepo miscofigured. The `dependsOn: ["^build"]` means run all dependencies' build script, but it doesn't mean the package's build script will run first. For tests, it should always `dependsOn: ["build"]` (without the upcaret) instead to ensure its own build is complete before testing. I also learned that `outputs: []` can be dropped now since thats the default behavior.
We need to ensure that `@vercel/gatsby-plugin-vercel-builder` is executed as the very last plugin, which Gatsby itself doesn't really support in the plugins listing. So instead we'll patch the `gatsby-node` file to invoke the plugin in the project's own `onPostBuild()` hook, which does get executed last. The patching is similar to how is done with the `gatsby-config` file.
Astro v2 was released today. It includes [improved support for caching
all hashed build
assets](https://docs.astro.build/en/guides/upgrade-to/v2/#changed-_astro-folder-for-build-assets)
by gathering these all in a single `_astro` directory in build output
(previously these ended up in a number of different places).
This PR updates the Vercel frameworks config to provide out-of-the-box
immutable caching for these assets.
Co-authored-by: Steven <steven@ceriously.com>
Right now we create the SSR serverless function at path `_ssr`, and then symlink all the other pages to that function.
Instead just make the first page encountered be the "real" function, and symlink all the other pages to that endpoint.
Previously, the page-data Serverless Function and SSR Serverless Function were two distinct functions. They had almost identical file contents and just slightly different handler logic. So here we merge the handler logic into a single function and re-use the same Serverless Function for both page-data and SSR.
This simplifies the output quite a bit and deletes a good amount of code, and helps with build output size, cold boot times, etc.
So that the test runs get invalidated by Turbo when code changes within one of the plugin files. This is to avoid a PR breaking something in a plugin, but we don't notice it because the static-build tests still "pass" due to cache hit.
This function can sometimes give a TypeScript error if @types/node says 'code' should be a `number | null` and yet the code is returns as a `number`:
```
@vercel/build-utils:build: src/fs/run-user-scripts.ts(140,13): error TS2322: Type 'number \| null' is not assignable to type 'number'.
@vercel/build-utils:build: Type 'null' is not assignable to type 'number'.
```
I'm not sure if there are any other projects that depend on `@vercel/build-utils`, but it doesn't appear that the Vercel CLI nor the build container use this `execAsync()` function. If I'm mistaken, feel free to close this PR.
As this removal is a breaking change, setting the semver to major and not auto-merging unless others are in agreement.
Gridsome was not updated for [more than 2 years](https://www.npmjs.com/package/gridsome) and still relies on Webpack 4 what makes it incompatible with >= Node.js 17.
To make the example still deployable on Vercel, this adds an engine restriction to the `package.json` for that example.
Same as #9007.
* Sets a valid number of seconds for DSG expiration (10 minutes - do we want to make that configurable somehow?)
* Sets the `group` of DSG pages, so that the page-data and SSR pages are associated
* Outputs SSR/DSG pages with `/index.html` suffix so that those paths are accessible
* Updates SSR and page-data functions URL path parsing logic to handle querystrings and the `index.html` scenario
* Remove the unnecessary `rewrite` related to page-data URL paths
* Remove the page-data function static file fallback handling (they are accessible as just regular static files)
* Correct the path for the page-data endpoing when the root-level index page is SSR/DSG
Follow-up to https://github.com/vercel/vercel/pull/9258, even though that issue seemed to only happen when linked to the monorepo locally. In any case, this test will ensure those log messages are intact for any other change around that part of the codebase in the future.
This PR attempts to balance the tests so they run concurrently and therefore faster.
I also sorted the tests so they are deterministic when splitting/chunking.
Instead of always including empty directories in `glob()`, make it an
opt-in behavior because technically it's a breaking change to include
them by default.
These were missing from the compiled ncc build of `helpers.ts`, and thus causing an error at runtime because the deps are not available within the Serverless Function.
The previous delay of 1500ms was causing some users to hit the API rate limits. This doesn't normally happen with a single deployment, but it can happen with several concurrent deployments (for example a monorepo with many projects).
We don't need to be polling so often, so this PR changed the polling delay to the following:
- During 0s-15s: check every 1 second
- During 15s-60s: check every 5 seconds
- During 1m-5m: check every 15 seconds
- During 5m-10m: check every 30 seconds
Update `@vercel/client` to send empty directory entries to the `POST` create deployment endpoint. This makes it so that CLI deployments will have empty directories re-populated in the build-container when doing `vc deploy`.
Follow-up to #9103.
In [a different PR](https://github.com/vercel/vercel/pull/9009), detecting frameworks by package name will also provide framework version metadata to the build. Should we update these framework detectors to look up their respective packages or were they not doing that already for a reason?
I left the old detectors in place as fallbacks, which looks like:
```
some: [
{
path: 'package.json',
matchContent:
'"(dev)?(d|D)ependencies":\\s*{[^}]*"remix":\\s*".+?"[^}]*}',
},
{
path: 'remix.config.js',
},
],
```
Please review carefully.
This PR:
- updates `packages/frameworks` to have most supported frameworks specify which dependency version should reflect the overall framework version
- updates `packages/fs-detectors` to allow framework detection that returns the full `Framework` record instead of just the slug
- updates `packages/next` to return the detected Next.js version in the build result
- updates `packages/cli` to leverage these changes so that `vc build` can add `framework: { version: string; }` to `config.json` output
The result is that Build Output API and supported frameworks will return their framework version in the build result of `vc build` when possible, which is used by the build container when creating the deployment. The dashboard later retrieves this value to display in richer deployment outputs.
Supports:
- https://github.com/vercel/api/pull/15601
- https://github.com/vercel/front/pull/18319
---
With the related build container updates, we get to see Next.js version in the build output. You'll see this with BOA+Prebuilt or a normal deploy:
<img width="1228" alt="Screen Shot 2022-12-09 at 2 48 12 PM" src="https://user-images.githubusercontent.com/41545/206793639-f9cd3bdf-b822-45dd-9564-95b94994271d.png">
---
### The Path to this PR
I went through all the supported frameworks and figured out how to best determine their versions. For most of them, we can check a known dependency's installed version number.
We can get most of the way only checking npm. For a handful, we'd have to support Go/Ruby/Rust/Whatever dependencies.
I started with a more complex method signature to allow for later expansion without changing the signature. It looked like this, in practice:
```
async getVersion(dependencies: DependencyMap) => depedencies['next']
```
However, after checking all currently supported frameworks, I don't think this will end up being necessary. It also has the constraint that all dependencies have to be gathered and presented to the function even though it only needs to check for one or two. That's not a huge deal if we have them already where we need them, but we don't. We could use a variant here where this function does its own lookups, but this seemed unnecessary and would beg for duplication and small variances that could cause bugs.
Further, if we only look at `package.json`, we're going to either see a specific version of a version range. To be precise, we have to look at the installed version of the package. That means checking one of the various types of lockfiles that can exist or poking into node_modules.
If we poke into node_modules to detect the installed version, we introduce another point where Yarn 3 (default mode) will not be supported. If we read lockfiles, we have to potentially parse `npm`, `pnpm`, and `yarn` lockfiles.
If we use `npm ls <package-name>`, that also fails in Yarn 3 (default mode). We could accept that and go forward anyway, which would look like:
```
const args = `ls ${packageName} --depth=0 --json`.split(' ');
const { stdout } = await execa('npm', args, { cwd });
const regex = new RegExp(String.raw`${packageName}@([\.\d]+)`);
const matches = stdout.match(regex);
if (matches) {
return matches[1];
}
```
But it turns out there's a `--json` option! That's what I ended up using, for now.
We could explore the lockfile route more, but after some initial digging, it' non-trivial. There are 3 main lockfiles we'd want to check for (npm, pnpm, and yarn) and there are different lockfile versions that put necessary data in different places. I looked for existing tools that parse this, but I didn't find any. We could certainly go down this path, but the effort doesn't seem worth it when `npm ls` gets us really close.
---
### Follow-up Versioning
Now that we know how to determine version per framework, we can vary configuration by version. In a future PR, we could allow a given value to vary by version number:
```
name: (version) => {
if (semver.gt(version, '9.8.7')) {
return 'some-framework-2''
}
return 'some-framework';
}
```
However, it may still be easier to differentiate significant versions by adding multiple entries in the list.
Adds support for `remix.config.mjs` and `remix.config.cjs` and
also updates the example/fixtures to the latest version of Remix.
See: https://github.com/remix-run/remix/pull/3675
https://linear.app/vercel/issue/VCCLI-377/rollback-failing-for-enterprise-teams
When running `vc rollback` for a deployment belonging to another team, the command will fail requesting the rollback. Technically, the command should have failed trying to get the deployment. This PR checks that the current team matches the deployment being rolled back.

This PR also cleans up a bunch of deployment related things. There were 3 functions to get a deployment and now there's just one which uses the latest v13 API. Get deployment error handling now throws instead of returning an error. The `Deployment` type definition has been updated to match the v13 response and mock deployment data was also updated.
Updates the `static-build` injector to use the new plugin.
Still need to verify somehow that the newly published plugin is working as expected. It should be fine since it was a copy-paste from the previous plugin repo, but always good to verify before we break everything!
This PR also updates the README in `@vercel/gatsby-plugin-vercel-analytics`
This PR migrates https://github.com/vercel/gatsby-plugin-vercel to this
repo so that we can eventually integrate into our monorepo tooling.
Since it currently requires Node.js v12 to be built, I've manually
built, copied, and committed the package as it exists now so that we can
publish a stable v1 of `@vercel/gatsby-plugin-vercel-analytics`.
After work completes on adding support for Gatsby v4, I will come back
to this package and update it to Node.js v16 so that it can be
integrated properly into the repository's tooling.
🚨 DO NOT SQUASH MERGE 🚨
Adds support for auto injection into Gatsby's new ESM config format. Only injects if the `gatsby-config.mjs` is present, and continues to default generation of `gatsby-config.js`
This PR generates lockfiles for the various monorepo build tests and updates the package versions to their latest within the major. This should help make these tests less flaky.
Related issue: https://vercel.slack.com/archives/C017QMYC5FB/p1673025728939139
Updates the screenshot used for the Next.js template that shows up on the import/new project flow. The asset has been updated on Cloudinary (`/front/import/nextjs`) and this PR updates the version # of the url.
- Depends on https://github.com/vercel/nft/pull/297
- Fixes#7908
- Fixes#6194
This PR bumps `@vercel/nft` (for production) and `ts-node` (for
development) to fix ESM behavior.
Because Node.js cannot dynamically set [loader
hooks](https://nodejs.org/docs/latest-v18.x/api/esm.html#loaders) once a
process is started, I had to change the way `ts-node` is registered by
using environment variables such as `NODE_OPTIONS`. Most of the logic
for TS and ESM was pulled out of the child process and into the parent.
Co-authored-by: Ethan Arrowood <ethan.arrowood@vercel.com>
When you are on this page, creating a project the image here is the screenshot of an example project in the `Vercel Examples` enterprise. However that was not working:
<img width="1060" alt="Screen Shot 2023-01-03 at 2 26 58 PM" src="https://user-images.githubusercontent.com/74699/210451850-8208f42b-de43-4ac4-a1fe-b90d88fe86d8.png">
It does this by hitting the API. In this case the problem is that there is a trailing slash on the domain name, causing the API to fail:
<img width="477" alt="Screen Shot 2023-01-03 at 2 29 48 PM" src="https://user-images.githubusercontent.com/74699/210452032-2e32ae61-df29-48b4-b79f-93f5bcf299d3.png">
So this removes that trailing, but I'll see if I can tighten this up as well so in the future it doesn't matter if there is a `/` there.
FYI: this passes unit tests in framework, because it passes the URL in demo through to `URL` and grabs the hostname, which strips out the `protocol` and trailing `/`. Perhaps we should do the same on front.
In July 2022, VitePress changed (https://github.com/vuejs/vitepress/pull/931) the output directory from `.vitepress/dist` to `docs/.vitepress/dist`, however the framework detector was still referencing the old .vitepress/dist` output directory.
There are some edge-case situations where a dependency or build process is expecting an empty directory to exist, and this expectation would fail currently because `glob()` does not return directory entries.
So update `glob()` to return entries for empty directories, which are also re-created properly when passed to the `download()` function.
This adds a `link()` helper function to the `Output` class that is inspired by the `terminal-link` npm package.
The main difference with this version is that it's more tightly integrated with the `Output` class for the purposes of being able to toggle hyperlinks support on/off for [unit tests](4a54b19f46/packages/cli/test/unit/util/output/create-output.test.ts) by setting the `output.supportsHyperlink` boolean.
> **Note:** Since hyperlinks are still a relatively new feature, and users might not yet understand how to interact with them, we should only use this function for progressive enhancement scenarios at this time, and _not_ as part of a critical UX.
When adding an alias, the server can return a 400 Bad Request under these circumstances:
1. Invalid alias: no alias, empty string, null alias, alias domain is invalid, alias is not public, alias is not a subdomain (code: `'invalid_alias'`)
2. The deployment is indeed not ready (code `'deployment_not_ready'`)
3. The cert for the provided alias is not ready (code `'cert_missing'`)
4. There was an error assigning the alias (code varies)
`vc alias add` will treat all 4 of those bad request errors as the deployment "is not ready". Instead of treating all 400's as not ready, only return `DeploymentNotReady` if the `code` is set to `'deployment_not_ready'`.
The CODEOWNERS file had an error referencing the `@vercel/edge-function` team, which does not exist. I assume this is supposed to be `@vercel/edge-compute`, but please confirm.
There are a [few edge-related teams](https://github.com/orgs/vercel/teams?query=edge).
### 🔖 What's in there?
Because Typescript's `libdom` does not have [`static Response.json()`](https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1444) (which modern browsers and edge runtimes are supporting), Typescript users can't use easily use it.
This helper fills the gap.
### 🧪 How to test?
It's covered with unit tests
🎉 Kit is live! 🎉
Merge prior to #9030. Manually updates Kit to latest (will need to have
a commit pushed after 1.0 goes live on NPM).
Co-authored-by: Steven <steven@ceriously.com>
According to AWS Lambda official documentation:
> The Lambda documentation, log messages, and console use the abbreviation MB (rather than MiB) to refer to 1024 KB.
https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html
This is also a convenient thing for us since CF Limits are in base-2 (even they are printed as base-10).
Fixes flakey tests / CI:
- git metadata test for corrupted `.git` directory
- version identifier for `build-utils` being using in `fs-detectors`'s `devDependencies`
- bad import from `../dist/..`
### 📖 What's in there?
As part of Edge function GA, we're allowing `edge` as a runtime value.
This is adding to the allowed list, so we stay backward compatible.
[Linear ticket](https://linear.app/vercel/issue/EC-481/add-edge-to-the-list-of-allowed-runtimes)
I've kept one instance of `experimental-edge` in the test fixtures to ensure we still supports it.
### 📋 Checklist
#### 🧪 Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
### Related Issues
Allow the `ls` commands to have a `--limit` option that allows a user to fetch up to 100 records per page. Currently the default is 20, but the API allows up to 100. This keeps the default, if unspecified at 20.
Fixes: https://linear.app/vercel/issue/VCCLI-244/add-limit-option-all-the-ls-subcommands
This adds in `ls --limit` into:
- [x] `alias ls`
- [x] `certs ls`
- [x] `dns ls`
- [x] `domains ls`
I note that `env` has an `ls` command, but it doesn't have a pagination command and [looking at the API](https://vercel.com/docs/rest-api#endpoints/projects/retrieve-the-environment-variables-of-a-project-by-id-or-name) it doesn't support pagination or limit.
Wasn't sure if I should add in `-L` as a short cut to `--limit`, seems like a good idea.
~Couldn't find any tests that cover this API, but I could be looking in the wrong place, this is the first pull request, so my apologies if I've missed it. But I'll take another look tomorrow and leave it in the draft state for now.~
Added in unit tests for each of the commands and mocks for those unit tests, which is has caused this PR to get quite a bit larger, sorry about that.
Of note for reviewers, there were a few places where I changed `console.log` to `output.log` to get the output passed to the tests - as far as I can tell everything works on the command line and in tests.
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
The umi example currently uses `umi@2` which uses `webpack@4` under the hood to build.
Because of this issue https://github.com/webpack/webpack/issues/14532 Webpack@4 is no longer able to run on Node.js 17+.
Since we use [Node.js 18 as default](https://vercel.com/changelog/node-js-18-lts-is-now-available) for new projects, this example currently breaks when it gets deployed.
Temporary fix is here to ensure that a Node.js version below 17 is used in the meantime.
Augments the `BuildResultV2Typical` type to support `framework` and `frameworkVersion` for use in Richer Deployment Outputs.
I added this to a new `meta` object because it contains data about the result, not really part of the result.
---
Supports a related builder container update.
The `vc rollback` command provides the ability to redeploy a previous
deployment and check the status of a rollback request.
#### Requesting a rollback
vc rollback <id | url>
Upon requesting a rollback, the command will being a status polling loop
for 3 minutes. This timeout can be adjusted via the `--timeout <value>`
option which accepts time formats such as `30s` or `2m`. A timeout of
`0` (zero) will skip the status polling and immediately exit after
successfully requesting a rollback.
#### Querying rollback status
vc rollback
vc rollback status
The `status` action will return the most recent rollback info within the
last 3 minutes.
### Related Issues
>
https://linear.app/vercel/issue/HIT-117/cli-add-support-for-vc-rollback-deployid
>
https://linear.app/vercel/issue/HIT-118/cli-add-support-for-vc-rollback-[status]
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
The default routes for Astro are redirecting all non-existing files to
`index.html`, which means that the `404.html` page is not used, and
instead `index.html` is shown for all not found pages.
Astro outputs files for each page (ie. `about.html`, `blog.html`, ...)
so the `{handle: 'filesystem'}` route should be enough to route all
existing pages correctly.
The missing part to ship this fix is to answer the following question:
can we safely assume that Astro will always output a `404.html` file?
Internal ref: https://github.com/vercel/customer-issues/issues/638
Co-authored-by: Okiki Ojo <okikio.dev@gmail.com>
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Steven <steven@ceriously.com>
### Related Issues
Fixes: [slack
thread](https://vercel.slack.com/archives/C035J346QQL/p1669508061056179)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Fixes https://github.com/vercel/next.js/issues/43357
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Since introducing `vc build`, we no longer have isolated builds. This means we can share the cache across builds and improve TS compile across multiple builds.
For example, `api/foo.js` and `api/bar.js` are two different builds but they will likely share the same `tsconfig.json`. So this PR caches the initialization used before running the TS compiler so that it can be shared between builds of the same deployment.
In one customer build, we saw deployment time drop from 14 min to 7 min.
- Related to https://github.com/vercel/customer-issues/issues/925
### Related Issues
This fixes up a few links that had errors I found when scanning through
the code.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
`--cwd` is handled globally in the CLI entrypoint file, so if a relative path is used then it would be applied twice in `vc build` since it was _also_ handling `--cwd`. So remove `vc build`'s logic for it.
Fixes https://github.com/vercel/vercel/discussions/8948.
`json5` can be moved to a dev dependency since `ncc` bundles it into the output.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
A simple update to the framework array, updating the blitz properties to
match the legacy framework. This PR detects a `blitz.config.(ts|js)`
file which is specific to the legacy framework. With the blitz 2.0
update the framework detection should automatically be next.js.
`pnpm` is our package manager of choice. This repository contains
framework starter templates, which check-in lockfiles to speed up clone
& deploy time. This PR updates a few frameworks to use `pnpm` instead of
`yarn` or `npm`.
- Updates Gatsby to Gatsby 5 given Node.js 18 support
- Updates to latest Nuxt 3 template for stable version
- Updates Astro to latest stable version, previously on RC
- Updates Angular to v15, previously on v13
Remove `--forceExit` and wait for the child `vc dev` process to close
before continuing.
Listen to the `'close'` event instead of `'exit'` to ensure stdio has
been flushed and closed before continuing.
Some tests cause `vc dev` to spawn child processes that in turn spawn
nested child processes that do not exit when the parent exits, so a
`nukeProcessTree()` helper was added to ensure all spawned processes are
cleaned up. Furthermore, some of the nested child processes don't
respond well to `SIGTERM` and we need to use `SIGKILL` if `SIGTERM`
doesn't do the job.
I uncovered a larger issue exposed by removing the `--forceExit` flag.
The go builder uses `go run` to build and run the go-based serverless
function. Turns out that `go run` will build the executable, then spawn
it with a parent process id (ppid) of `1` (launchd) on macOS. This means
that the go serverless function executable is not detected as a child
process of `vc dev` and won't be cleaned up, yet has inherited `stdout`
and `stderr` keeping Jest alive. The solution is to explicitly `go
build` the serverless executable, then run it.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with
tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
### Related Issues
Includes a guard checking for `vercel-build` and a LD flag to control
rollout.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Adds support for package.json based turbo configuration.
Includes test.
Confirmed with Turbo that `turbo.json` takes precedence over
`package.json` based config so that is how it is processed here.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
No related issue, this is a drive-by fix
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
A customer issue was raised that web-vitals analytics were not working for their Gatsby application, even though this is meant to be zero config.
It turns out the issue is due to their `gatsby-config` file being declared as a `ts` file, rather than `js`. This is perfectly valid and supported in Gatsby.
However, the static-build modifications that are made to automatically add the `gatsby-plugin-vercel` only apply to existing `js` files.
This lead to their deployments containing both a `js` and `ts` version of `gatsby-config`. Luckily, the `ts` version has higher precedence, so _only_ web-vitals were affected.
Closes https://linear.app/vercel/issue/FLA-364/investigate-gatsby-and-nuxt-data-issues
#### Tests
- [X] The code changed/added as part of this PR has been covered with tests
- [X] All tests pass locally with `yarn test-unit`
#### Code Review
- [X] This PR has a concise title and thorough description useful to a reviewer
- [X] Issue from task tracker has a link to this PR
### Related Issues
Adds support for comments in JSON configs and skips operation when root directory is null or `'.'`
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
The `readOutputStream()` module was counting "data" events, not lines specifically, and was failing for me locally. So that was removed, and updated the tests that were using it to use the `line-async-iterator` module instead to be more explicit and be able to perform assertions on a per-line basis.
### Related Issues
Improves how `vc build` handles monorepos. In short, this introduces
monorepo manager detection logic and then some helpful defaults so users
don't have to manually specify a `buildCommand` or `installCommand` when
linking a project within a monorepo.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
`runDevCommand()` assumes the dev command is an npm package and thus uses `npx` or `yarn run` to execute it. In the case of a Hugo-based app, there is no npm package, so we want spawn to find Hugo in the `PATH`. Then for Node-based apps, instead of `npx`, spawn should find the command since `node_modules/.bin` has been added to the `PATH`.
### Related Issues
> https://github.com/vercel/customer-issues/issues/871
Note: This PR is a recreation of https://github.com/vercel/vercel/pull/8864 because prettier changed a bunch of Hugo files, which was bloating the original PR.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
On Windows, Python 3 is unable to listen on `0.0.0.0` and errors with:
```
[WinError 10049] The requested address is not valid in its context
```
The only solution I found is to bind to `127.0.0.1` or `localhost`. I've run into issues before with using `localhost`, so I chose to go with `127.0.0.1` and Windows (and macOS) seems to be happy.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
We have a link to an error page here:
https://github.com/vercel/vercel/blob/main/packages/cli/src/commands/deploy/index.ts#L873,
however that page is currently a 404.
This is an attempt to explain the error a bit more. Because there are
many possible causes of a deployment error, this mostly focuses on
explaining how to get to the logs.
### Related Issues
Fixes https://github.com/vercel/vercel/issues/1732.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Chris Barber <chris.barber@vercel.com>
### Related Issues
x-ref: [slack
thread](https://vercel.slack.com/archives/C01224Q5M99/p1667927545637489?thread_ts=1664536480.045539&cid=C01224Q5M99)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
This ensures we properly route dynamic routes with segments in the
middle of the path for rsc paths and also ensures we normalize the
header values from the routes-manifest correctly.
x-ref: https://github.com/vercel/next.js/issues/42364
x-ref:
https://github.com/vercel/next.js/actions/runs/3415662540/jobs/5685787894
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Required for https://github.com/vercel/next.js/pull/42482
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Updates @types/node to the latest version within the v14 major (based on `npm view @types/node`)
```
❯ npm view @types/node@'>=14.0.0 <15.0.0' version | tail -1
@types/node@14.18.33 '14.18.33'
```
This PR also fixes the various necessary type changes
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
https://github.com/vercel/api/pull/15009 broke one of our integration tests. This PR fixes it.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
While working on #8742 i found some useful error checking code buried in
the CLI. This PR adds a new private package `@vercel/errors` that moves
those helpful utilities into its own package so it can be used
throughout the monorepo.
For Next.js apps, a custom `basePath` in the `next.config.js` file was being prepended to all paths except edge functions of which this PR resolves.
### Related Issues
> Fixes [#853](https://github.com/vercel/customer-issues/issues/853)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Related - https://github.com/vercel/api/pull/15027
Removing setting the output directory placeholder - it is not extremely reliable https://vercel.slack.com/archives/C02HEJASXGD/p1667234137439189?thread_ts=1667232443.320769&cid=C02HEJASXGD
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Implements request headers override in middlewares.
#### New middleware headers
- `x-middleware-override-headers`: A comma separated list of *all* request header names. Headers not listed will be deleted.
- `x-middleware-request-<name>`: A new value for the header `<name>`.
### Related Issues
- #8724: Add helper functions for non-Next.js middlewares
- https://github.com/vercel/next.js/pull/41380: Next.js' implementation
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
x-ref: https://github.com/vercel/vercel/pull/8763
x-ref: [slack
thread](https://vercel.slack.com/archives/C035J346QQL/p1666645450798089)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
x-ref: https://github.com/vercel/vercel/pull/8757
Fixes: [slack thread](https://vercel.slack.com/archives/C035J346QQL/p1666278547705429)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Copes with `socket hang up` errors.
I tested with https://github.com/Shopify/toxiproxy and set up a proxy that generated a socket hangup error. With a test URL etc it looks like this:
<img width="935" alt="Screen Shot 2022-10-21 at 2 13 48 PM" src="https://user-images.githubusercontent.com/74699/197289788-9467ebef-d4dd-4fae-bf41-f635b7857d03.png">
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
### Related Issues
We introduced a new endpoint: `/env/pull/:projectId/:target?/:gitBranch?` which will return a complete list of key/value pairs (environment variables) for the proper target environment, using the same logic as we use for deployments.
This means that we don't need to fetch env variables from multiple sources (system, project, shared) and stitch them on the client anymore.
- removes unused logic for fetching & merging environment variables on the CLI client
- offloads env variables generation to the API
- new: shared env variables are now supported in vc env pull!
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
<!--
Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change that you're making:
-->
This PR adds a feature in middleware to add, modify, or delete request
headers. This feature is quite useful to pass data from middleware to
Serverless/Edge API routes.
### New APIs
Adds a new option `request.headers` to the `MiddlewareResponseInit`
parameter in `NextResponse.next()` and `NextResponse.rewrite()`. It's a
[`Header`](https://developer.mozilla.org/en-US/docs/Web/API/Headers)
object holding *all* request headers. Specifically:
```ts
interface ExtraResponseInit extends ResponseInit {
request?: {
headers?: Headers
}
}
```
### Example
```ts
// api/hello.ts
export default (req, res) => {
const valueFromMiddleware = req.headers['x-hello-from-middleware']
return res.send(valueFromMiddleware)
}
// middleware.ts
import { next } from '@vercel/edge'
export default function middleware(request: NextRequest) {
// Clone request headers
const headers = new Headers(request.headers);
// Add a new request header
headers.set('x-hello-from-middleware', 'foo');
// Delete a request header from the client
headers.delete('x-from-client');
return next({
request: {
headers
}
});
}
```
### New middleware headers
- `x-middleware-override-headers`: A comma separated list of *all*
request header names. Headers not listed will be deleted.
- `x-middleware-request-<name>`: A new value for the header `<name>`.
### Related Issues
- Next.js' implementation: https://github.com/vercel/next.js/pull/41380
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Co-authored-by: Gal Schlezinger <gal@spitfire.co.il>
### Related Issues
x-ref: https://github.com/vercel/vercel/pull/8743
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
This will allow a shorthand form of `export const config = { regions:
'iad1' }`
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Co-authored-by: Damien Simonin Feugas <damien@vercel.com>
The `link` and `pull` commands have essentially duplicate code from `ensureLink()`. This
Card: https://linear.app/vercel/issue/VCCLI-224/adopt-ensurelink-across-commands
The `dev` command should also be updated to use `ensureLink()`, however that may interfere with this in progress PR: https://github.com/vercel/vercel/pull/8666.
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
### Related Issues
This allows `initialHeaders` and `initialStatus` for Prender as has been discussed quite a bit so that the proper headers can be applied when serving the fallback.
x-ref: [slack thread](https://vercel.slack.com/archives/C035J346QQL/p1666130102396799?thread_ts=1666122861.189349&cid=C035J346QQL)
x-ref: follow-up to https://github.com/vercel/vercel/pull/8737
x-ref: dd94dcab32/packages/next/src/server-build.ts (L970)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
When deploying a project that uses typescript, but typescript is not a dependency, the default typescript is used. The message that's logged when this happens says:
> Using TypeScript 4.3.4 (no local tsconfig.json)
which is not necessarily true. You can have a `tsconfig.json` file with no typescript dependency.
This message leads to bad debugging paths.
This PR updates the message to be more specific. Now the message will say:
> Using TypeScript 4.3.4 (no local "typescript" package detected)
### Related Issues
This ensures we probably route the `/` rsc route properly and adds a regression test along with enabling some now patched tests that were skipped.
Fixes: [slack thread](https://vercel.slack.com/archives/C043ANYDB24/p1665746921485109)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
- `meta.isDev` is unconditionally read after the first check (even though it could technically still be `null`, ignoring typescript)
- `meta.isDev` is explicitly asserted to be falsy, since the first `if` will return early if it's truthy, so the later checks are all redundant
- added `?.` for the `packageJson?.engines?.node` read
The rest is auto formatting (and if my local eslint warnings are correct then I'm just gonna close this PR...)
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
### Related Issues
This ensures we properly normalize the optional catch-all data route correctly with middleware as currently the route is expecting a repeated slash in the regex `(?:/(?` which it should just be `(?:(?`. This also adds a regression test for this specific case.
Fixes: [slack thread](https://vercel.slack.com/archives/C045FKE5P51/p1665153317613089)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Otherwise you are not able to write a serverless function that returns a
Promise when using the ESLint rule
[@typescript-eslint/no-misused-promises](https://typescript-eslint.io/rules/no-misused-promises/)
Following function
```typescript
const handler: VercelApiHandler = async () => {};
```
will report a `Promise-returning function provided to variable where a
void return was expected`
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with
tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Add in placeholder settings for monorepos
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Fixes error:
```
ENOENT: no such file or directory, open 'querystring'
```
Unfortunately this issue would only manifest when installed externally. I.e. our tests didn't catch this since the `querystring` module is presumably present in the monorepo.
### Related Issues
This reduces the max length we check for when generating routes to ensure we stay under the 4096 limit after normalizing.
x-ref: https://github.com/vercel/customer-issues/issues/779
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
This ensures we handle the case were a lambda isn't present for `pages/404.js` with `getStaticProps` which can occur in older Next.js versions e.g. `v9.5.5`. This also adds a regression test for this specific version to ensure it is working as expected.
x-ref: https://github.com/vercel/vercel/pull/8663
Fixes: [slack thread](https://vercel.slack.com/archives/C03DQ3QFV7C/p1664945825621409)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
My IDE tells me `process` is unknown but mentions something about package.json so that may just be a superficial issue. I guess CI/CD will tell me soon enough.
This adds an env flag to override the file ref sema's so we can experiment with setting a higher sema.
One potential problem I'm seeing is that this is a generic sema for all the things that use this class. Not sure if that's going to work out as intended but in that case we'll have to find a different way :)
This removes the `styfle/cancel-workflow-action` in favor of native GitHub Actions `cancel-in-progress`.
The cancel key is workflow+branch but we don't want to cancel on the `main` branch.
https://docs.github.com/en/actions/using-jobs/using-concurrency
This moves an existing error from the build container to `vercel build`.
Its rare, but [Vercel Runtimes](https://vercel.com/docs/runtimes) might target a discontinued [AWS Lambda Runtime](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html) so we should fail fast when we know this has happened in `vercel build`.
A test has been added to demonstrate the failure using an old PHP version.
### Related Issues
Fixes: https://vercel.slack.com/archives/C03S8ED1DKM/p1664521958768189
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Here's the test for https://github.com/vercel/vercel/pull/8657.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
When running `vc build` for a Next.js app, the Next builder will execute the server build which performs several steps. One of the steps is to trace each serverless function for any referenced files, then the raw list of files is scrubbed and filtered. The filtering uses OS specific file path comparisons to see if a file is of interest. Since it's comparing OS specific paths, we need to use OS specific path separators.
During testing on Windows, the traced serverless functions file list was always empty.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
x-ref: https://github.com/vercel/next.js/pull/40979
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
When running `vc deploy` in a non-TTY context (i.e. CI), limit the number of progress updates to 25% increments (for a total of 5).
```
Uploading [--------------------] (0.0B/71.9MB)
Uploading [=====---------------] (18.0MB/71.9MB)
Uploading [==========----------] (36.0MB/71.9MB)
Uploading [===============-----] (54.0MB/71.9MB)
Uploading [====================] (71.9MB/71.9MB)
```
This avoids spamming the user logs with many progress updates.
### Related Issues
Parse `rush.json` files with `json5` because it is very common for these
to have comments in them
[Template for people to clone for
Rush](https://rushjs.io/pages/configs/rush_json/) which has comments in
it as a default which most people will clone
Docs of Rush showing to not use `JSON.parse`
https://rushjs.io/pages/help/faq/#why-do-rushs-json-config-files-contain--comments-that-github-shows-in-red
Added in tests with block comments and single line comments
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
There was a case where the npm version wasn't decided base on Node.js version but instead based on the lockfile.
This PR fixes the case when a newer npm version is detected base on the lockfile.
- Follow up to #8598
- Follow up to #8550
### Related Issues
- Needs https://github.com/vercel/next.js/pull/40881 for this to be
useful
- Resolves EC-238
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: JJ Kasper <jj@jjsweb.site>
This PR refactor `doBuild()` to return `void`.
This will prevent accidental bugs like #8623 where an exit code number was returned instead of throwing on error.
We were doing this validation in `vercel dev` but not `vercel build`.
This PR adds `vercel.json` validation to `vercel build` too.
Note I am calling this a patch because invalid `vercel.json` was already failing when passed to the API so this allows a nice error message earlier in the process.
Add strict mode to `vc dev` edge function handlers. This is behind a flag in production, but that flag has been at 100% for a while. So, it seems safe to include it here unconditionally.
Also remove legal comments.
These changes bring `vc dev` edge function support closer to production.
This PR will make sure that CI fails fast if there is a network issue when restoring the cache.
This has been a known issue for 3 months and no resolution:
- https://github.com/actions/cache/issues/810
### Related Issues
Seeing this while deploying appDir to production. The collecting path is
not correct for generated dist from appDir
```
Collected static files (public/, static/, .next/static): 18.834ms
Error: ENOENT: no such file or directory, open '/vercel/path0/.next/server/pages/route-groups/checkout.html'
Error: An unexpected error occurred!
Error: ENOENT: no such file or directory, open '/vercel/path0/.next/server/pages/route-groups/checkout.html'
Error: Command "vercel build" exited with 1
```
Fix the deployment of SSG, the output html/json paths should be prefixed
with `/app`
Adding a TODO now for how to determine the app path route, leveraging
`.rsc` suffix in data route. Better to use app paths manifest to
refactor it later.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with
tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Co-authored-by: JJ Kasper <jj@jjsweb.site>
The `create-git-meta` file contains a `isDirty()` function which calls `git status` and subsequently causes one of the test fixture's git index to be updated. Turns out that `git status` will update/optimize the index in the background when invoked: https://git-scm.com/docs/git-status#_background_refresh.
By disabling this using the `--no-optional-locks` flag, `isDirty()` will no longer update the index when checking the status.
From my testing, the `--no-optional-locks` flag must be set after `git` and before `status`.
This PR is likely a better alternative to https://github.com/vercel/vercel/pull/8568 as this PR eliminates the problem all together.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This is to fix the issue with processing new entries of `potentialFiles` when there was a `readdir` cache hit
### Related Issues
Related to https://linear.app/vercel/issue/HIT-57/monorepo-detection-api-prevent-rate-limits
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
The `disabledAt` and `enabledAt` properties need to be consulted in order to determine whether or not the Vercel Analytics feature has been enabled.
Related to https://github.com/vercel/vercel/discussions/8575.
Added a lock file to the normalize paths text fixture to speed up install dependencies.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Add in getting the package paths for Rush workspaces.
First get the contents of the `rush.json` file. If the `projects`
property is an array, map through that array and return the
`projectFolder` as the package path.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
In this PR, we try to detect when npm install fails due to invalid peer deps and retry with `--legacy-peer-deps`.
This is a follow up to PR #8550 that explains more.
Steps to reproduce the npm bug:
```sh
corepack enable npm
echo '{"packageManager":"npm@8.5.5","dependencies":{"swr":"1.3.0","react":"16.8.0"}}' > package.json
npm install --legacy-peer-deps
npm install # works fine now that a lockfile exists
echo '{"packageManager":"npm@8.6.0","dependencies":{"swr":"1.3.0","react":"16.8.0"}}' > package.json
npm install # fails with code ERESOLVE (Conflicting peer dependency)
```
Windows doesn't like it when the env has both a `PATH` and a `Path`, so `cloneEnv()` must remove `Path` after copying it to `PATH`.
Renamed the next builder `01-normalize-routes` test to `01-normalize-paths` as it's test normalization of output paths, then re-enabled the test for Windows.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This is a (further 😄) continuation of #8379 by @theMosaad, so that the tests can run.
I also added a change to make `images` _not_ be sent to the create deployment API endpoint, since it fails validation there.
### Related Issues
Add in Rush workspace
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Follow up to #7874 since the remote cache was not used on `main`.
We can unconditionally set these env vars with the latest turbo so it will work for contributors too.
### Related Issues
Fixes:
https://github.com/vercel/vercel/actions/runs/3086450305/jobs/4990850756
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Updates our test fixture for related changes in latest canary of
Next.js.
Fixes: https://vercel.slack.com/archives/CGU8HUTUH/p1663607276817069
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Use posix path separators for routes (static pages, lambdas, etc) instead of the native platform path separator (e.g. backslash on Windows).
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Prior to `npm@8.6.0`, running `npm install --legacy-peer-deps` to generate a lock file and then later running `npm install` would work fine.
After `npm@8.6.0`, running `npm install` with that same lock file will fail with `code ERESOLVE` and `Conflicting peer dependency`.
Steps to reproduce:
```sh
corepack enable npm
echo '{"packageManager":"npm@8.5.5","dependencies":{"next":"12.3.0","react":"16.8.0"}}' > package.json
npm install --legacy-peer-deps
npm install # works
echo '{"packageManager":"npm@8.6.0","dependencies":{"next":"12.3.0","react":"16.8.0"}}' > package.json
npm install # fails with code ERESOLVE
```
This PR introduces a flag so we can safely upgrade npm to a newer version without breaking thousands of deployments.
The [npm docs](https://docs.npmjs.com/cli/v8/using-npm/config#legacy-peer-deps) say the flag is not recommended so we also make sure that once we upgrade to Node.js 18, we stop flagging `--legacy-peer-deps` because its safe to introduce breaking changes.
On Windows 10 and 11 machines, environment variables are not case sensitive. The system PATH is actually defined as `process.env.Path`, however Node.js kindly handles the case sensitivity and will automatically return the system path when specifying `process.env.PATH`.
When we clone the environment variables via `{ ...process.env }`, we lose the automatic resolving of `Path` to `PATH`. To fix this, we need to explicitly copy the `PATH`.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
https://nx.dev/more-concepts/folder-structure#integrated-repo-folder-structure
Nx monorepo has an option to use Nx workspaces.
Nx workspace is defined within the root `workspace.json` file
Within this `workspace.json` file the workspace packages are under
projects
```{
"$schema": "./node_modules/nx/schemas/workspace-schema.json",
"version": 2,
"projects": {
"myblog": "apps/myblog",
"svelte-app": "apps/svelte-app",
}
}
```
Within `getNxWorkspacePackagePaths` get the projects object values for
the paths
Nx is listed as the last workspace manager within
`workspace-managers.ts` because other workspace managers could exist to
check for before Nx workspaces because the `workspace.json` could exist
but not be the correct workspace manager
Nx workspace file can exist when yarn/npm workspaces exist. When this
happens, the workspace.json file is empty with no projects so it will
not add any package paths to the list to look through for projects.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with
tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Path segment previously were not working when a `go.mod` file is present. This was fixed likely by https://github.com/vercel/vercel/pull/8291, so now this PR is just a test to ensure this case stays working.
Covers:
- Importing a built-in Builder with `@latest` should use the CLI's version
- Importing a built-in Builder with `@canary` should use the CLI's version
- Importing a built-in Builder with an explicit version should install to `.vercel/builders`
Update "typescript" and add a `yarn.lock` file.
It started failing without the lockfile with compilation issues:
```
$ react-scripts build
Creating an optimized production build...
Failed to compile.
/vercel/path1/node_modules/@types/react-router/index.d.ts
TypeScript error in /vercel/path1/node_modules/@types/react-router/index.d.ts(149,100):
Type expected. TS1110
147 | ): match<Params> | null;
148 |
> 149 | export type ExtractRouteOptionalParam<T extends string, U = string | number | boolean> = T extends `${infer Param}?`
| ^
150 | ? { [k in Param]?: U }
151 | : T extends `${infer Param}*`
152 | ? { [k in Param]?: U }
error Command failed with exit code 1.
```
This makes `vc dev` utilize the same Builder installing and importing logic that `vc build` uses. So now the Builders will be installed locally on a per-project basis, rather than being installed to a shared global installation directory.
Instead of replacing "127.0.0.1" in `vc dev`, replace "0.0.0.0" when rendering the URL to access the `vc dev` server.
The thought here is that the IPv6 form is replacing the catch-all host name (`::`), but the IPv4 version is only replacing the explicit "127.0.0.1" version, so there's an inconsistency.
Considering the catch-all host names are not usually intended to be routable anyways, we will fix the inconsistency by only replacing the catch-all versions instead of localhost.
Also, since Node.js will default to binding to the catch-all address when not explicitly specifying a host, this replacement will only happen in that case. If the user is explicitly specifing a host to bind to (i.e. `vc dev -l 127.0.0.1:8080` or `vc dev -l tcp://[::1]:8080`) then it makes more sense to print explicitly what the user specified.
This PR fixes an issue when the sha begins with `0` and causes [an error](https://vercel.com/vercel/vercel/EP7fVcXKsoodzWRy3fwG8AoeQcs6) when looking up the tarball:
> Error: ENOENT: no such file or directory,
> copyfile '/vercel/path0/packages/build-utils/vercel-build-utils-v5.4.2-0251253.tgz'
> -> '/vercel/path0/public/tarballs/@vercel/build-utils.tgz'
The fix is to no longer rely on the exact tarball name because we can't guarantee the name from `yarn pack` and instead rely on a pattern for the tarball name.
This removes the reliance on raw github hosting and instead relies on the Vercel deployment hosting the logo images.
Since we already have static files in each deployment (tarballs), it makes sense to start adding static images too.
### Related Issues
Adding in Nx and Rush as monorepo managers.
This will allow to help with starting zero config for both the above managers.
I have added in unit tests for both Nx and Rush.
### 📋 Checklist
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
When using a `rewrite` in middleware to a relative path that does not exist, the logic gets confused and falls back to the original path.
This was caused by two changes that, in combination, caused this behavior.
1. `prevUrl` was created to keep track of route results that point to other routes, but falls back to `req.url` (`prevUrl`'s initial value): [#4033](40e4b69267 (diff-142c93a61d03a1718eb765cd25e5f18d07a95358bb27ce5d5d4da314ee2fa286R1283-R1284))
2. `prevUrl` was reassigned when handling middleware: [#7973](ee1211416f (diff-00ef6e7b63ed4cae298afc2a8c84f49247855a2506270f748e4d3e41da97ad99R1538))
Because `prevUrl` was reset back to `req.url` after the first `phase` (null) was run, the updated `prevUrl` value from middleware was lost. This only matters if the second `phase` ("filesystem") was going to be hit.
Further confusing matters, this was partially fixed by https://github.com/vercel/vercel/pull/8457 because it either returned a proxy pass (which doesn't have this problem) or assigned `req.url` to include the `rewritePath`, which meant that later when `prevUrl` would default to `req.url`, it still had come from `rewritePath`. So, this is fixed for the absolute URL case, but not the relative path case.
Given all that, I think the fix we need is to keep `prevUrl` at its current value when it's not being updated based on the `routeResult`.
---
So, I made that change here. I added a test that exercises this specific behavior.
Adds a `writeFile` function to `DetectorFilesystem` that will be used to update the various file cache maps.
**Why is this needed?**
When detecting npm7+ monorepos, we identified a performance improvement where the service can inspect the `package-lock.json` file for workspaces, and reuse the package information for each workspace in framework-detection.
The pseudo code in `vercel/api` will look something like this
For a given lockfile
```json
{
...,
"packages": {
"": {
"name": "npm-workspaces",
"version": "1.0.0",
"license": "ISC",
"workspaces": {
"packages": [
"apps/*"
]
}
},
"apps/admin": {
"version": "0.1.0",
"dependencies": {
"next": "12.2.5",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"eslint": "8.23.0",
"eslint-config-next": "12.2.5"
}
},
...,
}
```
```ts
// for each projectPath we detect in package-lock.json
// switch the cwd of the fs to the project directory
const projectFs = fs.chdir(projectPath);
// gets the package info from the lockfile
const projectPackageInfo = lockFile.packages[projectPath];
// insert this content into fs cache
await projectFs.writeFile('package.json', projectPackageInfo)
// call detectFramework, which should now have a cached "package.json" file
const projectFramework = await detectFramework(projectFs);
```
### Related Issues
Related to https://linear.app/vercel/issue/HIT-57/monorepo-detection-api-prevent-rate-limits
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
This change will allow the downstream Dev Command server be able to listen on either of `127.0.0.1` for IPv4 or `[::1]` for IPv6.
- Fixes#6639
- Fixes#8511
- Fixes#8121
- Closes#8512
- Closes#8384
Found a few tests that won't run on Windows. The project settings override test runs `mkdir -p` which errors. The other two build tests fail because they try to create symlinks.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Adding the ability to explicitly set the `hasPath` and `isFile` caches via `readdir`
**Why is this needed?**
For framework detection, this allows us to fetch the contents of a directory (the root directory) of a git repo, and make assumptions about the existence of files,
```ts
import frameworks from "@vercel/frameworks";
// we can make the set of all file paths needed for framework detection like this
const setOfPaths = new Set(
frameworks.frameworks
.flatMap((f) => [
...(f.detectors?.every ?? []),
...(f.detectors?.some ?? []),
])
.map((d) => d.path)
);
// then we can read the contents of the root directory of a git repo via the `DetectorFilesystem`
fs.readdir('./', { potentialFiles: [...setOfPaths] });
// The filesystem has been fully primed - any network calls from here will only happen if needed.
// This works because the logic of `detectFramework` calls `hasPath` and then `isFile` before
// fetching file contents. Since the filesystem knows this information, it doesn't have to make
// any additional network calls 🙌
const framework = detectFramework(fs);
```
### Related Issues
Related to [HIT-57](https://linear.app/vercel/issue/HIT-57/monorepo-detection-api-prevent-rate-limits)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
When running tests locally that fail to make a fetch request, the retries add a lot of noise to debugging. This PR sets those retry counts to `0` locally, but keeps them at their current value for CI.
### Related Issues
Add handling for edge SSR in app dir, normalize the edge page routes
from app dir, like what we did for ones in `pages/`.
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with
tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a
reviewer
- [ ] Issue from task tracker has a link to this PR
Co-authored-by: JJ Kasper <jj@jjsweb.site>
### Related Issues
This ensures we properly normalize the `/` case from the `app-path-routes-manifest` as the outputs expect this to be normalized to `index`.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
We have code that tries to detect and highlight errors in the build logs, however it doesn't look for `Error!`, only `Error:`.
We could update that highlight code or we could update Vercel CLI to make it consistent.
This PR is the latter.
In Next.js 12, we introduce `outputFileTracing` as the default behavior. This moved `@vercel/nft` from `@vercel/next` into `next` itself so users can upgrade or downgrade Next.js if there is a bug in `@vercel/nft`.
Unfortunately, some users are setting `outputFileTracing: false` which deopts tracing back from `next` to `@vercel/next`. So we should pin `@vercel/nft` here and never upgrade in case of any bugs.
Adds a `writeFile` function to `DetectorFilesystem` that will be used to update the various file cache maps.
When detecting npm7+ monorepos, we identified a performance improvement where the service can inspect the `package-lock.json` file for workspaces, and reuse the package information for each workspace in framework-detection.
The pseudo code in `vercel/api` will look something like this
For a given lockfile
```json
{
...,
"packages": {
"": {
"name": "npm-workspaces",
"version": "1.0.0",
"license": "ISC",
"workspaces": {
"packages": [
"apps/*"
]
}
},
"apps/admin": {
"version": "0.1.0",
"dependencies": {
"next": "12.2.5",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"eslint": "8.23.0",
"eslint-config-next": "12.2.5"
}
},
...,
}
```
```ts
// for each projectPath we detect in package-lock.json
// switch the cwd of the fs to the project directory
const projectFs = fs.chdir(projectPath);
// gets the package info from the lockfile
const projectPackageInfo = lockFile.packages[projectPath];
// insert this content into fs cache
projectFs.writeFile('package.json', projectPackageInfo)
// call detectFramework, which should now have a cached "package.json" file
const projectFramework = await detectFramework(projectFs);
```
### Related Issues
Related to [HIT-57](https://linear.app/vercel/issue/HIT-57/monorepo-detection-api-prevent-rate-limits)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
When running `vc dev` for a project using `experimental-edge` runtime and a fetch-related error occurs, the message is a little vague:
```
Unhandled rejection: fetch failed
```
In this case, the fetch promise (defined in @edge-runtime/primitives) is being rejected with a `TypeError: fetch failed` that has a `cause` property containing the actual `response.error` message. The `response.error` is the actual error and is never reported to the user.
This PR simply appends the `cause` message, if exists, to the fetch failure message.
```
Unhandled rejection: fetch failed: Error: getaddrinfo ENOTFOUND undefined
```
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This fixes a few warnings when running Jest that look something like:
```
jest-haste-map: Haste module naming collision: nextjs
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/dev/fixtures/10-nextjs-node/package.json
* <rootDir>/test/dev/fixtures/25-nextjs-src-dir/package.json
```
We decided to change this to an explicit label and rely on a separate action to check for correct labels (see #8464).
This action likely won't work for PRs from forks, but that might be okay because our other actions don't work for forks either.
Changes:
- added @cb1kenobi @Ethan-Arrowood to sections owned by the Vercel CLI team
- removed outdated code owners: if this was you and you believe this was in error, let us know!
- removed no-op lines
### Related Issues
As the title, support a new version of middleware-manifest of next.js that is going to be added in https://github.com/vercel/next.js/pull/39257
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This function name can be anything, but the current one is confusing. This is what the function gets renamed to during compilation. Let's change it back to avoid confusion.
### Related Issues
Adds configuration override support to `vc build` and `vc dev` commands.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
When adding the `--yes` flag to the `vc git` command's help screen, the description was copy/pasted and not accurate, so this PR improves the description to be more accurate.
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
There were recently a few breaking changes introduced into SvelteKit. This PR clones that latest changes from a demo SvelteKit application, while retaining support for Vercel Analytics.
Deployed latest to https://sveltekit-template.vercel.app/ and confirmed analytics are sending.
This was broken since https://github.com/vercel/vercel/pull/8242, which accidentally pushed all WebAssembly modules to be nested under `global.wasmBindings` instead of being directly under the global scope.
### Related Issues
- This was broken since https://github.com/vercel/vercel/pull/8242
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This adds handling for the `app` outputs and adds initial tests to ensure it is working as expected.
### Related Issues
x-ref: https://github.com/vercel/next.js/pull/38420
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Related Issues
Previously we were only checking for a non-static version of pages/404 although this can also be the case for pages/500 so this ensures we match that handling and add a test case to prevent regression.
Fixes: slack thread
📋 Checklist
Tests
The code changed/added as part of this PR has been covered with tests
All tests pass locally with yarn test-unit
Code Review
This PR has a concise title and thorough description useful to a reviewer
Issue from task tracker has a link to this PR
Related Issues
This fixes caches for data routes with middleware due to search params not matching between the non-data variant and the data variant. Additional tests have been added to ensure this is working as expected.
Fixes: vercel/next.js#39595📋 Checklist
Tests
The code changed/added as part of this PR has been covered with tests
All tests pass locally with yarn test-unit
Code Review
This PR has a concise title and thorough description useful to a reviewer
Issue from task tracker has a link to this PR
As of 28.0.0, `vc link` stopped respecting `--yes` and would wait for prompt if it found a Git repository to connect. This PR passes `autoConfirm` through to the Git prompt, so that `vc link` continues to respect `--yes`.
Here's what `vc link` looks like after this PR if a user has a local Git repository:
<img width="513" alt="Screen Shot 2022-08-16 at 10 05 56 AM" src="https://user-images.githubusercontent.com/14811170/184899917-c3dc0603-370d-4c86-afb8-19758fbc051a.png">
Not sure if we want to remove the log messages to be consistent with the rest of `vc link`?
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
@leerob flagged that the language "Aborted" throughout the CLI should be changed to be more inclusive. This PR updates this throughout.
I didn't go as far as to update type names because I wanted to avoid potentially unintended consequences, but happy to also do that if we want.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
I ran `vc ls` for a project and I spotted a few small details that I felt compelled to make better.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Currently we are adding routes for edge function un-necessarily as static edge functions don't need routes added and dynamic edge functions already have their routes included in dynamicRoutes in the routes-manifest.
Related Issues
Fixes: slack thread
📋 Checklist
Tests
The code changed/added as part of this PR has been covered with tests
All tests pass locally with yarn test-unit
Code Review
This PR has a concise title and thorough description useful to a reviewer
Issue from task tracker has a link to this PR
This PR is a follow up to #8388. The tests were not running as expected because only the "vendored" test used `2.7.x` which was never failing `bundle install` to begin with. I had to add `2.7.x` to the non-vendored test to get `bundle install` to fail. The fix is to rename `2.7.x` to `2.7.0` before running `bundle install`.
#8170 shipped with a small bug: double quotes aren't stripped when pulling existing environment variables, but double quotes are stripped when reading `.env`, so if an environment variable uploaded to Vercel contained double quotes, it would always show as "Changed". This PR fixes the bug.
This error message was incorrectly telling user to use the `2.7.x` value even though it will fail `bundle install` with the following error:
```
Your Ruby patchlevel is 0, but your Gemfile specified -1
Command failed with exit code 18 (EXDEV)
```
The exact version, `2.7.0`, is necessary.
The `vc update` command is essentially a noop command that doesn't actually update the CLI. This command is not listed in the `--help` output, nor the CLI documentation. It should be safe to remove in the next major release.
### Before
Previously, the file upload progress bar would only get updated upon completion of uploading an individual file. This would cause the the progress bar to appear "chunky" when uploading large files. This problem is exasperated with #8356, since there is only a single (potentially large) file that gets uploaded, which would cause the progress bar to not render at all, making the deployment process seem "stuck".
https://user-images.githubusercontent.com/71256/184241009-ba6d1e63-a0fe-462f-804b-e58f56ec310c.mov
### After
Now, the progress bar gets updated incrementally as individual files get uploaded which makes the progress bar updates smoother and play nicely with large files. This is done by "chunking" the individual file into slices and creating a Readable stream from those chunks.
https://user-images.githubusercontent.com/71256/184241050-51832996-d42b-46fd-9a71-d8a1f87a026c.mov
#8100 added a new `vc git` command, which allows users to connect a Git provider repository, enabling them to set up a full Git workflow for their Vercel projects without having to leave the CLI.
This PR takes this functionality a step further by including it as part of the `vc link` flow. This way, users can set up a Vercel project and add a Git provider repository all in one step.
This PR is blocked by a PR to `front` which adds an option to the Git Settings page for a Project to re-enable the prompt if the user opted out (in review).
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Related to #8102 & #8151. This PR updates the look of `vc project ls`:
- Header names are cyan
- A new "Latest Production URL" section
### Before
<img width="583" alt="Screen Shot 2022-08-11 at 10 46 03 AM" src="https://user-images.githubusercontent.com/14811170/184199554-5b298f2c-7d62-4200-a580-ddb16765c20e.png">
### After
<img width="816" alt="Screen Shot 2022-08-11 at 10 45 54 AM" src="https://user-images.githubusercontent.com/14811170/184199502-34295b2f-be7f-4289-b426-372c58f37eb6.png">
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* Add functional but bad code
* Add docs
* Re-add thing just in case
* Fix some things
* Add a few tests
* Add test for multiple
* Add another test
* Small type fix
* Update packages/cli/src/commands/git/index.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/commands/git/index.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/commands/git/index.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/test/unit/commands/git.test.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/commands/git/index.ts
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
* Fix typo
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
* Update packages/cli/src/commands/git/connect.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/commands/git/connect.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/commands/git/connect.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/commands/git/connect.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/commands/git/connect.ts
Co-authored-by: Steven <steven@ceriously.com>
* return 0
* only return boolean in `promptConnectArg()`
* Remove err.meta check
* `parseRepoUrl()`: parse url without a scheme
* Remove todo
* Fix typo
* Small wording change
* Print each line instead of building buffer
* Make consistent quotes vs template literals
* Remove `multiple` variable
* Remove else
* Accept objects & rename some variables
* Move `connect-git-provider` to `git` folder
* Don't pass in `output`
* Fix small thing
* Add another test
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
Co-authored-by: Chris Barber <chris.barber@vercel.com>
This is just a small TypeScript cleanup to remove an `as Stats` cast for the "statsCache".
Also drops the `FsFiles` interface in favor of just using the built-in `Record` utility type.
Reverts vercel/vercel#8217
The previous PR had unresolved comments, but the kodiak bot automerged it. Let's revert for now, then we can continue to iterate on code in a new PR.
Right now, deployments via Vercel CLI are created by uploading every source file individually. This PR creates a tarball of the user's source files and sends the packed tarball instead. This speeds up deployment times, especially for large projects, and also bypasses the 15,000 file upload limit.
Currently, it requires a `--archive=tgz` flag. Perhaps we can enable this by default for prebuilt, but that may be for a separate PR.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This consolidates the logic to get the framework-specific prefixed System Environment Variables into a single shared function so each builder can reuse the same function.
- Related to #7009
- Related to #8306
In the future, this feature could be added to any other missing builders as well as `vc dev` but we'll save that for a new PR.
Previously `vc dev` would only set this env var for "create-react-app" Framework preset, but other frameworks do the "auto-open browser window" behavior as well, and respect this env var (Docusaurus, specifically).
So always set the `BROWSER=none` env var regardless of which framework preset is selected. Also simplifies the code since this was the only place `frameworkSlug` property was being used.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Fixes a regression from the the refactor in https://github.com/vercel/vercel/pull/8039 that was causing the following error:
```
Error! client.prompt is not a function
```
This PR consolidates all the `test` scripts to be the same and removes the `prepublishOnly` script since we always run `build` before publishing to npm.
Instead of copying symlinked files during a build, recreate the symlink.
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Follow-up to #8305.
The `expect().toOutput()` call was frequently timing out before the
command writes the error to the terminal, causing the test to fail.
So wait for the command to return the exit code before running assertion
on the printed output.
Review Notes: Turn off diff whitespace.
### Refactor
This PR refactors away the use of the result of `download` for a couple of reasons:
- Keeping `files` and `downloadedFiles` in sync with the file system (like when we rename a file that starts with a bracket) is easy to forget to do, causing bugs
- Nate says that `files` is something we've wanted to move away from using anyway
- It simplifies the code in a few places
- It was getting in the way of other fixes that need to be made
We do still call `download`, but it should be a no-op most of the time.
As a consequence of these changes, this PR also addresses:
- the builder no longer leaves build artifacts around, in many cases
- the builder can compile files that start with brackets again; routes don't seem to allow this to file to respond to a dynamic segments yet, though
### Next Steps
Upcoming PRs will resolve builder issues:
- bracket endpoints responding to dynamic segments
- exported function name conflict handling
- compilation targets should only apply to the source code build, not the analyze go utility
### Operating In-place
We also now have a cleanup step that clears out created files, created directories, and undoes file renames. This fixes an issue where multiple builds on the same directory would fail. It also cleans the user's project code when they are using `vc build`.
Ideally, we'd probably copy all of the code to a separate location, then freely do filesystem operations there. It's not clear to me if this is preferred for large projects because it would have to happen once per endpoint: 100 Go files would cause 10,000 (100 * 100) file copies (or symlinks).
It has to copy once per endpoint because we potentially need all of the files around in case any of them are imported. If we had nft-style tracing for Go, we could copy only what we needed.
This gets more complex in the next step where the exported function names will be renamed during compilation to fix the name conflict issue.
Previously, our test fixtures used to use a probes prop in `vercel.json` that was removed right before it was deployed.
This PR allows a separate `probes.json` file with the same content to separate the test fixture input from the test probes.
This allows us to test real "zero config" deployments without a `vercel.json` file.
Removes the legacy config file migration logic from back in the days when Zeit CLI supported multiple "providers". This was from a _very_ long time ago and we should expect that anyone who would have migrated at this point, has.
Right now, `vc inspect` fails to find a deployment if you include `http://` before it. But it works with no scheme and with `https://`.
Since it appears no scheme is what the API looks for anyway, and to avoid confusion, this PR strips any included scheme from the `deploymentIdOrHost` argument.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Ensures that errors that are serialized into `builds.json` are also printed to the terminal when running the `vc build` command.
Co-authored-by: Steven <steven@ceriously.com>
#8170 added a new message at the end of `vc env pull` which shows a delta of what was added, modified, and removed. Some people shared feedback that the yellow chalk color and `~` prefix to indicate modified variables was confusing. This PR instead keeps the prefix as `+` with a green color, but adds a `(Modified)` suffix at the end of every modified variable.
<img width="638" alt="Screen Shot 2022-08-03 at 10 18 28 AM" src="https://user-images.githubusercontent.com/14811170/182670327-5a3df6db-d84d-40a1-956b-9cf159501759.png">
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* Fix _next/data resolving priority for dynamic routes
* Apply suggestions from code review
* Ensure we match middleware for _next/data without header
* fix nested middleware case
* Update data routes generating
* Add version lock for non-nested middleware
* use path.posix
Middleware server setup wasn't logging errors the same way that dev server setup was. This meant that middleware instantiation errors (like invalid config) would cause requests to 500, but no errors to be logged to the console.
This PR updates the invalid config error, makes sure errors in this area are logged out, and adds a test for this behavior.
**It may be appropriate to fail the deploy (and crash `vc dev`) in this case instead, though. What do others think?**
---
During `vc dev` with middleware that has an invalid `config.matcher` value...
Before: You see a 500 response in the browser and no output in the terminal.
After: You see a 500 response in the browser and this output in the terminal:
```
Error! Middleware's `config.matcher` values must start with "/". Received: not-a-valid-matcher
```
---
Related Issue: https://github.com/vercel/edge-functions/issues/220
Some builders, such as `@vercel/next`, return both the symlinked directory and the resolved file.
When `vc build` iterates over the files to recreate them in `.vercel/output`, it fails with `EEXIST: file already exists` when creating the symlink because it first creates the file `node_modules/<symlink>/package.json` and then attempts to create the symlink `node_modules/<symlink>`.
This happened to work before `vc build` because yazl would accept the symlinked directory instead of the package.json file, so this PR is created to match that behavior.
Remove `meta.isDev` checks inside the `build` function because it's never set there. Instead, `startDevServer` would be used.
Also restored the Go tests in a partial form. Will fix the Go builder issues and make sure those features are tested completely in follow-up PRs.
* update edge-runtime to allow `instanceof` to work with primitives
* finishin upgrading edge-runtime
* update to latest
* fix merge
* remove dev only from test
The dev integration tests compare `vc dev` with a real deployment to make sure the results are the same. This PR ensures the deployment uses the same version of Vercel CLI as the local `vc dev` instance.
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
Since CI is already setup to run Build and then Test, we don't need to add it as an explicit turbo dependency so this PR removes `dependsOn: ['build']` from each test task.
In fact, the `test-unit` step doesn't need `build` in most cases now that jest is configured to run the TS sources directly.
This PR will also improve the time it takes to run the "Find Changes" job since it can ask jest for relevant files that changed without waiting for a build. This drops the time down from 2 minutes to 8 seconds.
For Edge Functions, we are now considering the `"browser"` and `"module"` fields of packages to find the proper entrypoint. This PR updates `@vercel/node` to consider those same fields when using the node-file-trace tracing, so that the proper files get included in the output Edge Function.
The `alias` command has been added to the `vercel --help` screen.
### Related Issues
> https://linear.app/vercel/issue/VCCLI-221/alias-command-missing-on-vc-h-help-screen
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This PR update the tests suite to wait for Vercel CLI tarball and then use that tarball to run E2E tests.
This is valuable because it will package all the packages in this monorepo to make the tests follow more closely what will happen in production once merged.
Since the current "Find Changes" step takes about 2 minutes, we run that first (it happens concurrently with the tarball preparation). Then once we complete "Find Changes" we wait for the tarball but it will likely be ready by that point since it also takes about 2 minutes. After both of those steps, the E2E tests continue as usual but with the `VERCEL_CLI_VERSION` set to the tarball.
- Related to #7967
- Closes#8245
- Closes#8227
The edge runtime context we were providing was necessary to have `ncc`-bundled code run, but after switching to `esbuild`, we didn't update this list.
This PR trims the values down to only what's necessary for `esbuild`-bundled code to run. It also adds comments about why these values are necessary.
This updates the API that generates tarballs so that it doesn't need to generate tarballs for every Serverless Function and instead generates it one time. This cuts the time in half.
* [node] Add WebAssembly importing support for the @vercel/node builder
* add comment about the original source
* trim down values to only what is required for esbuild wrapping logic
* Revert "trim down values to only what is required for esbuild wrapping logic"
This reverts commit c04dacad99f25156938dccdf2f29aac6e8282564.
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
### Related Issues
Adds `.vercel` path to the ignore list regardless if `zeroConfig` is enabled. This fixes a bug where the `.vercel` folder was being copied into the resulting `.vercel/output/static` directory after running `vc build` with `distDir: "."` configured for static-build.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Featuring:
- Aliases are now shown
- `readyState` –> `status` in "General" section
- `createdAt` –> `created` in "General" section
- Update `stateString` to support more states & be more visually appealing
### Before
<img width="754" alt="Screen Shot 2022-07-14 at 3 10 40 PM" src="https://user-images.githubusercontent.com/14811170/179097164-df7acd8a-d677-4e75-b7d5-b8ec6cf9bb12.png">
### After
<img width="748" alt="Screen Shot 2022-07-14 at 3 10 29 PM" src="https://user-images.githubusercontent.com/14811170/179097170-137d8977-60d6-402d-825e-8b0fb3025969.png">
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
The version of `@vercel/ncc` that was being used in this repo is rather old. Let's update to the latest version. Specifically, this is a baby step towards allowing CLI to become ESM format.
This applies the same chunking algorithm from `@vercel/static-build` tests to `@vercel/node` tests that we can run up to 5 integration tests concurrently.
### Related Issues
Adds a `isZeroConfig` check to static-build so that when `"zeroConfig": true` is enabled the correct settings are resolved.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This PR fixes a couple issues where `vercel build` was not correctly detecting the package.json files
```
Error: @vercel/node:test: ERROR: frontend/index.ts(1,12): error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
```
It also fixes an issue where all deployments were incorrectly detecting the lock file because the lock file doesn't always live in the same directory as the package.json file. So we need to do 2 passes: one to find the nearest package.json and one to find the nearest lock file.
Only consider the `.vercel/.env.${target}.local` file when loading env vars at the beginning of `vercel build`.
If a project-level `.env` (or `.env.production` or whatever) file needs to be loaded then it is the responsibility of the frontend framework's build command to consider those files (i.e. CRA build, `next build`, etc.)
I don't think anyone is using this command anymore in the world of M1.
Anyways, we should be using `ts-node` to execute the CLI from source code instead of skipping steps at build-time to iterate quickly.
This PR adds a new message to the end of `vc env pull` which shows delta of what was added, changed, and removed.
Example: you have a local `.env` file in a directory linked to a Vercel project. You change `TEST_1`, remove `TEST_2` via `vc env rm TEST_2`, and add `TEST_3` via `vc env add`. Then you run `vc env pull`. Here's what you will see:
```
> Updating existing .env file
> Downloading `development` Environment Variables for Project name
✅ Updated .env file
+ TEST_3
~ TEST_1
- TEST_2
```
<img width="562" alt="Screen Shot 2022-07-20 at 11 09 56 AM" src="https://user-images.githubusercontent.com/14811170/180064534-2ff5facb-95cb-4712-aaad-cbb47490cebe.png">
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
`ts-eager` isn't really maintained anymore and doesn't support ESM packages.
`ts-node` with SWC is more or less just as fast, so let's use that instead since it's well maintained any we can dogfood SWC more.
Pull the Vercel Analytics ID in the `vercel pull` command, so that `vercel build` can set the `VERCEL_ANALYTICS_ID` environment variable at build-time for the frontend framework to utilize.
This test sometimes times out on Windows. When it succeeds, it takes ~6 seconds. When it fails, we don't know how long it would have taken, but the current timeout is 7 seconds. Let's try 10 seconds and see if that's better.
If you run `yarn changelog` when your IP is already rate limited by github, you'll get an error. This allows you to set a [Github PAT](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) to get past the generic rate limit.
Given a PAT with value `MY_PAT_TOKEN`, you can run:
```
$ GITHUB_TOKEN=MY_PAT_TOKEN yarn changelog
```
If you do get an error, it now actually shows up in the output:
```
$ yarn changelog
yarn run v1.22.18
$ node utils/changelog.js
Error: Failed to fetch releases from github: API rate limit exceeded for 98.139.180.149. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)
```
Jest was saying that there's an open handle in the unit tests due to the `crypto.pbkdf2Sync()` call in this metrics file, so lazy-load that object in the case when metrics should not be collected.
### Related Issues
Updates to the latest version of `@vercel/nft` which adds fs concurrency limits to help alleviate memory usage.
x-ref: https://github.com/vercel/nft/pull/301
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
The logic that determines if a builder needs to be installed has a check to see if the builder should already be bundled: `isBundledBuilder`. This was looking for specific conditions that made it (1) a bit hard to follow and (2) very sensitive to `canary` tags (and having "canary" in the version specifier).
This causes general development problems because local changes weren't always used by local CLI builds. Depedendant packages (like `@vercel/node`) would be installed from the latest `canary` release instead.
This caused problems in CI and released CLI versions where the latest `canary` of dependant packages might be rather old, causing that old code to be used instead of the latest non-canary releases.
The issue was mitigated for now by publishing canary releases for all packages.
---
Paired with @styfle @MatthewStanciu.
@TooTallNate: Is this change too broad? Are there cases where we wouldn't want to do this?
### Related Issues
This updates to filter the `routes-manifest` and `pages-manifest` to only include entries for the pages that are being included in the specific serverless function. This fixes the case where multiple dynamic routes could match a path but one is configured with `fallback: false` so shouldn't match when executing for a different dynamic route.
A regression test for this specific scenario has been added in the `00-mixed-dynamic-routes` fixture.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
When an edge function has no response during `vc dev`, we were seeing an unhelpful error message:
> The event listener did not respond.
Now, we'll see a much more specific error message:
> Unhandled rejection: Edge Function "api/edge-no-response.ts" did not return a response.
> Error! Failed to complete request to /api/edge-no-response: Error: socket hang up
### Related Issues
1. exception from python 3.10:
```
TypeError: As of 3.10, the *loop* parameter was removed from Queue() since it is no longer necessary`
```
Remove the deprecated argument `loop` from `Queue`, which can also be omitted in python version < 3.10
2. exception from Sanic > 21.3:
```
File "C:\Users\Kevin\AppData\Local\Temp\zeit-fun-03f18b2d2c7d7\sanic\signals.py", line 93, in get
group, param_basket = self.find_route(
TypeError: 'NoneType' object is not callable
```
As of Sanic > 21.3, it cannot serve requests immediately after initializing, instead, we need implement the [ASGI lifespan protocol](https://asgi.readthedocs.io/en/latest/specs/lifespan.html) and wait for the startup event completed.
here I complemented the protocol copied from (same source of the previous HTTP procotol): <https://github.com/jordaneremieff/mangum/blob/main/mangum/protocols/lifespan.py>
### Related link:
https://github.com/encode/uvicorn/pull/498
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Co-authored-by: Steven <steven@ceriously.com>
Two features that handle a user's local Git config have been shipped:
- #8100
- #7910
Both of these features currently pull only from the user's remote origin URL. This covers 90% of cases, but there are cases in which the user has more than one remote URL, and may want to use one other than the origin URL, especially in `vc git connect`. This PR:
- Adds support for multiple remote URLs in a user's Git config
- Updates `vc git connect` to prompt the user to select a URL if they have multiple remote URLs
- Updates `createGitMeta` to send the connected Git repository url by default, origin url otherwise
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Update `node-fetch 2.6.1 -> 2.6.7` to fix high severity security vulnerability: Exposure of Sensitive Information to an Unauthorized Actor (https://github.com/advisories/GHSA-r683-j2x4-v87g).
`node-fetch` was updated in the root, `api`, `build-utils`, `cli`, `client`, `node`, and `static-build`.
### Related Issues
> https://linear.app/vercel/issue/VCCLI-196/update-vercelnode-dep-node-fetch-261-267
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Right now, `vc env pull` only pulls development environment variables. This PR adds a new flag, `--environment,` which allows users to specify which environment to pull from.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
If an error happens outside of a Builder (i.e. `detectBuilders()` function fails), then write the serialized error into the `builds.json` file at the top-level of the file (there is no `builds[]` when an error happens at the top-level).
This matches the behavior in production and prevents the error:
```
> Error! Your `package.json` file is missing a `build` property inside the `scripts` property.
```
If we don’t know the error, we should not assume it has a stack prop and instead print the whole thing to avoid accidentally printing `undefined`.
- related to https://github.com/vercel/vercel/discussions/8043
This is a semver major change to the public API for `@vercel/routing-utils` which includes the following breaking changes.
1. `getTransformedRoutes({ nowConfig })` props changed to `getTransformedRoutes(nowConfig)`
2. `type Source` renamed `type RouteWithSrc`
3. `type Handler` renamed `type RouteWithHandle`
4. `interface VercelConfig` removed
5. `type NowConfig` removed
6. `type NowRewrite` removed
7. `type NowRedirect` removed
8. `type NowHeader` removed
9. `type NowHeaderKeyValue` removed
This updates our `allowQuery` generating to ignore all query values for build-time prerender paths as these will match before dynamic routes since they are filesystem routes and the query values will not be overridden properly like they are for fallback prerender paths. This also adds testing for both prerender path types with on-demand ISR to ensure the cache is updated as expected regardless of the query.
Deployment with patch can be seen here https://nextjs-issue-odr-simple-hrjt2dagm-ijjk-testing.vercel.app/
### Related Issues
x-ref: https://github.com/vercel/next.js/issues/38306
x-ref: https://github.com/vercel/next.js/issues/38653
### Related Issues
Noticed this log was not being converted to a string so we're losing some context so this corrects in case we have a failure on this step in the future.
Fixes: https://github.com/vercel/vercel/runs/7344626478?check_suite_focus=true#step:8:258
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Updates to latest turbo which includes patches for cached files.
x-ref: [slack thread](https://vercel.slack.com/archives/C02CDC2ALJH/p1657767763630359?thread_ts=1657757803.039099&cid=C02CDC2ALJH)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
When a Builder returns an output asset that contains irregular slashes (multiple slashes or leading/trailing slashes), then have them be removed from the file path before creating the output asset.
This fixes an edge case where `@vercel/next` could end up outputting a Serverless Function with a trailing slash (i.e. `en-US/`). Before this PR, that would be serialized to the filesystem at `en-US/.func`, but after this fix it's saved in the correct `en-US.func` directory.
When a build fails, store the serialized Error in the "builds.json" file under the "build" object of the Builder that failed.
Example:
```json
{
"//": "This file was generated by the `vercel build` command. It is not part of the Build Output API.",
"target": "preview",
"argv": [
"/usr/local/bin/node",
"/Users/nrajlich/Code/vercel/vercel/packages/cli/src/index.ts",
"build",
"--cwd",
"/Users/nrajlich/Downloads/vc-build-next-repro/"
],
"builds": [
{
"require": "@vercel/next",
"requirePath": "/Users/nrajlich/Code/vercel/vercel/packages/next/dist/index",
"apiVersion": 2,
"src": "package.json",
"use": "@vercel/next",
"config": {
"zeroConfig": true,
"framework": "nextjs"
},
"error": {
"name": "Error",
"message": "Command \"pnpm run build\" exited with 1",
"stack": "Error: Command \"pnpm run build\" exited with 1\n at ChildProcess.<anonymous> (/Users/nrajlich/Code/vercel/vercel/packages/build-utils/dist/index.js:20591:20)\n at ChildProcess.emit (node:events:527:28)\n at ChildProcess.emit (node:domain:475:12)\n at maybeClose (node:internal/child_process:1092:16)\n at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5)",
"hideStackTrace": true,
"code": "BUILD_UTILS_SPAWN_1"
}
}
]
}
```
#8085 removed the clipboard copy feature in `vc deploy`, along with the `--no-clipboard` flag. Right now, the CLI exits and returns an error when someone includes the `--no-clipboard` flag. This PR instead consumes the flag and warns the user that the flag is deprecated.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
A function `formatProvider` wasn't imported in the `Project` mock endpoint. This wasn't caught before #8100 was merged, and dodged CI.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
`config.projectSettings` is not available when running `@vercel/remix` directly (i.e. when not using `vc build`), so calculate the correct root directory value based on the `workPath` relative to the `repoRootPath` value.
This PR adds a new subcommand `vc git`, which allows you to create a Git provider repository from your local `.git` config to your Vercel project.
Usage:
- `vc git connect` – connects a Git provider repository
- `vc git disconnect` – disconnects a Git provider repository
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
"solidstart" framework doesn't need to use the FS API v2 Builder anymore since:
1) Newer versions output Build Output API v3
2) Older versions that output FS API v2 will be handled by the compatbility shim that was added in https://github.com/vercel/vercel/pull/7690
This will enable Next.js to compile and set `vercel` as the edge runtime provider (`EdgeRuntime` global),
which can allow different libraries/customers to have different code running depends on the runtime environment (`edge-runtime` vs `vercel`).
### Related Issues
- https://github.com/vercel/next.js/pull/38331
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
The Next.js feature was not merged yet, so it still can't be tested.
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
There's a [Next.js PR](https://github.com/vercel/next.js/pull/38492) to include binary assets in Edge Functions. This PR enables to declare assets in the `EdgeFunction` constructor.
This is a configuration level setting, compared to WebAssembly modules which the `middleware-manifest.json` converts into `import` statements. This is because the asset generation is done in Webpack and it is not dynamic, it's a static string. We can use AST to replace it but we're risking in:
* worse performance
* accidentally replacing a string that isn't an asset
A test I wrote for a previous PR (https://github.com/vercel/vercel/pull/8112) was failing once in ~every 5 runs. This PR makes the test reliable.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
The Vercel API's `detect-framework` API contacts GitHub's API using its own file adapter.
However, currently the `detectFramework` function in the Vercel CLI (on which the API depends) calls the file system adapter in series using a `for` loop. This results in large amounts of lag when in a networked situation such as calling GitHub's API as each API call takes a couple hundred milliseconds.
I propose changing `detectFramework` to process the directories it scans in parallel.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
This debug log was originally added in #7871 because corepack has no output by default. In particular, it was nice to see the first deployment was not stalled when the package manager is being installed.
That being said, this gets noisy really fast because cache detections also print a log line.
For example, here's a deployment that prints 3 times:
```
Detected ENABLE_EXPERIMENTAL_COREPACK=1 and "npm@8.10.0" in package.json
Running "install" command: `npm install --prefix=.. --no-audit --engine-strict=false`...
2022-07-11T18:27:00.696Z corepack Reusing npm@8.10.0
356 packages are looking for funding
Running "npm run vercel-build"
2022-07-11T18:27:06.664Z corepack Reusing npm@8.10.0
> front@0.0.0 vercel-build
> npm run buildonly && npm run build:rss
2022-07-11T18:27:07.088Z corepack Reusing npm@8.10.0
> front@0.0.0 buildonly
> next build
```
I think its best to let users add this env var themselves if they want to debug what corepack is doing, so this PR removes that environment variable.
This is a follow-up to #8094 which debug logs errors.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This is a follow-up to #8091 which:
- Makes `vc project` the default command, with `vc projects` aliased to `vc project` (previously it was not clear in the code which one was the "real" command)
- Makes some helper names for `ls` more specific
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Since the `vc project` command is about to be expanded with 2 new subcommands, I think it makes sense to do a little bit of refactoring. The current `vc project` command is all in one file, with the logic for subcommands nested within if statements. I think the structure of `vc project` should look more like `vc env`, which is consistent with how commands with subcommands look throughout the rest of the codebase.
This PR moves the logic for the `project` subcommands into their own files.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
- Fixes https://github.com/vercel/customer-issues/issues/597
`vc deploy` currently fails with a confusing error if the user has a corrupt `.git` directory. This is caused by `create-git-meta` improperly handling the scenario where it detects a `.git` directory but cannot find git information. This PR handles this error.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
The `middlewarePath` property was not correctly stripping
the root directory setting from the value, causing Middleware
to not work correctly with Root Directory.
`vercel-sapper` is a case of a 3rd party Builder that does not export a `version` property. In this case, we should treat it the same as a `version: 2` Builder since its return value is compatible.
Adds a new `@vercel/hydrogen` Builder package so that Vercel can support Shopify Hydrogen projects with zero config. It outputs an Edge Function for the server-side render code and includes a catch-all route to invoke that function after a `handle: "filesystem"` to serve static files that were generated by the build command.
**Examples:**
* [`hello-world-ts` template](https://hydrogen-hello-world-otm2vmw6w-tootallnate.vercel.app/)
* [`demo-store-ts` template](https://hydrogen-demo-store-1gko2fst3-tootallnate.vercel.app/)
This PR adds a new subcommand, `vc project connect`, which connects a Git provider repository to the current project. Previously, this could only be done via the Dashboard.
This is the first part of a larger project—the goal is to include this functionality within `vc link`, so that you never have to leave the CLI if you want to set up a new Vercel project that's connected to Git.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
- https://github.com/vercel/vercel/pull/8053
While writing tests for this PR, I added a mock project endpoint that always returned a default project. This was probably incorrect and no longer needed (tests pass without it). I should have removed it before merging #8053, but I didn't catch this before merging.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Currently, `vc ls` is scoped to your team, and you have to type out a project name if you want to see deployments for a project. This PR instead scopes it to the linked project.
Under these changes, `vc ls` still works similarly to how it currently works: users can still specify a project name to get the deployments for a project. The difference is that:
1. The selected team is the one that the linked project belongs to, instead of the one that the user has selected.
2. `vc ls` with no arguments displays the latest deployments for the linked project.
This is the first part of a larger effort to change the behavior of `vc ls`, plucked from https://github.com/vercel/vercel/pull/7993. More PRs to follow.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
https://vercel.slack.com/archives/C03F2CMNGKG/p1656971502881949
Right now, `vc deploy` automatically copies the deploy url to your clipboard after the deployment has finished. You can opt out via the `--no-clipboard` flag, but the feature is enabled by default.
This is strange behavior—there's no indication that the CLI will hijack your clipboard, and you don't know it's been hijacked until after it happens.
This PR removes the clipboard copying feature as well as the `--no-clipboard` flag.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This ensures we update the canary dist-tag when publishing stable releases as we no longer need to do separate canary publishes.
### Related Issues
x-ref: [slack thread](https://vercel.slack.com/archives/C65QW9PN1/p1657049930618119?thread_ts=1656362480.574099&cid=C65QW9PN1)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This PR fixes a bug where corepack (#7871) was not correctly setup because the lockfile autodetection and node version autodetection was overriding the PATH.
It also fixes a bug where the log output was printed twice because we incorrectly prepended the PATH twice.
The Saber example had a lock file but the test did not.
This PR copies the lock file since the latest version of Saber doesn't work with the latest Vue.
```
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './package' is not defined by "exports" in /vercel/path0/node_modules/vue/package.json
at new NodeError (node:internal/errors:372:5)
at throwExportsNotFound (node:internal/modules/esm/resolve:472:9)
at packageExportsResolve (node:internal/modules/esm/resolve:753:3)
at resolveExports (node:internal/modules/cjs/loader:482:36)
at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
at Function.resolve (node:internal/modules/cjs/helpers:108:19)
at module.exports (/vercel/path0/node_modules/saber/dist/webpack/webpack.config.js:30:58)
at Saber.getWebpackConfig (/vercel/path0/node_modules/saber/dist/index.js:195:58)
at VueRenderer.build (/vercel/path0/node_modules/saber/dist/vue-renderer/index.js:232:39)
```
The `@vercel/build-utils` package was meant be shared functions necessary for writing a Vercel Builder (aka Runtime).
This package has since bloated into the catch-all package for anything that wasn't a Builder.
This PR removes the bloat in favor of a new package, `@vercel/fs-detectors`. It also removes the need for `@vercel/build-utils` to have a dependency on `@vercel/frameworks`.
- Related to #7951
This PR is a follow-up to #8039, which provides an intuitive syntax for writing unit tests for interactive CLI commands.
The heart of this is the new `await expect(stream).toOutput(test)` custom Jest matcher, which is intended for use with the mock Client `stdout` and `stderr` stream properties. The `test` is a string that will wait for the stream to output via "data" events until a match is found, or it will timeout (after 3 seconds by default). The timeout error has nice Jest-style formatting so that you can easily identify what was output:
<img width="553" alt="Screen Shot 2022-06-29 at 10 33 06 PM" src="https://user-images.githubusercontent.com/71256/176600324-cb1ebecb-e891-42d9-bdc9-4864d3594a8c.png">
Below is an example of a unit test that was added for an interactive `vc login` session:
```typescript
it('should allow login via email', async () => {
const user = useUser();
const exitCodePromise = login(client);
// Wait for login interactive prompt
await expect(client.stderr).toOutput(`> Log in to Vercel`);
// Move down to "Email" option
client.stdin.write('\x1B[B'); // Down arrow
client.stdin.write('\x1B[B'); // Down arrow
client.stdin.write('\x1B[B'); // Down arrow
client.stdin.write('\r'); // Return key
// Wait for email input prompt
await expect(client.stderr).toOutput('> Enter your email address:');
// Write user email address into prompt
client.stdin.write(`${user.email}\n`);
// Wait for login success message
await expect(client.stderr).toOutput(
`Success! Email authentication complete for ${user.email}`
);
// Assert that the `login()` command returned 0 exit code
await expect(exitCodePromise).resolves.toEqual(0);
});
```
**Note:** as a consequence of this PR, prompts are now written to stderr instead of stdout, so this change _may_ be considered a breaking change, in which case we should tag it for major release.
In some rare cases, `npm bin` exits with code 7, but still outputs the right bin path.
To reproduce, try:
```
npm init -y
echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" > .npmrc
vc
# enter "echo build" for the build command, leave the other configuration as default
```
The build will fail with `Error: Command exited with 7` because `npm bin` fails with code 7, for some reason.
In this PR, we do 2 things:
(1) Ignore exit codes from `npm bin`. It still outputs the right path when it exits with code 7 so we just read the output and check if it's a valid path.
(2) Throw a more specific error message when `npm bin` fails to give us the bin path. The current error was hard to debug because it looked like it was coming from the install commmand. We can do better by emitting a custom error.
Alternative considered for (2): Do not throw errors. If `npm bin` fails, emit a warning and let the build continue.
Related Issues:
- https://github.com/vercel/customer-issues/issues/585 (internal)
There's some cleanup directory walking logic that was choking when
a Lambda outputs a file with a broken symlink. We shouldn't need to
traverse into those directories in the case of a symlink anyways, so use
`lstat()` instead of `stat()` to prevent that filesystem call from
throwing an error.
If there is no `api` directory, then you run `vc dev`, then you create a new function `api/some-func.js`, then this file would not be served as a new function.
This was being caused by incomplete "new file" handling logic. This PR ensures that the proper detection is done in each new file (`getVercelConfig`) that populates key properties (`apiDir`, `apiExtensions`, and extensionless `files`) for determining when a file is used to serve a request.
When edge functions error, they were showing a basic text response instead of the error template. They were also sending a 502 status code instead of a 500.
This PR makes the error handling of Edge Functions consistent with Serverless Functions when executed through `vc dev`. If we want to update the error templates themselves, we can do that in a separate PR.
**Note:** Production currently treats Edge Function errors differently from Serverless Function errors, but that's a known issue that will be resolved.
---
*I deleted the original outputs (terminal and browser screenshots) because they are out of date and added a lot of content to this page. See my latest comment for updated examples.*
`vc bisect` currently prepends `https://` to a passed-in url if it doesn't begin with https—which means that if someone passes in a url that begins with `http://`, it'll turn the url into `https://http://url.com`. This PR fixes this.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Adds initial support for a root-level `middleware.js` / `middleware.ts` file in the `vercel dev` CLI command. This leverages the existing Edge Function invoking logic in `@vercel/node`'s `startDevServer()` function and applies the necessary response / rewrites / mutations to the HTTP request based on the result of the middleware invocation.
Allows to specify a string or array of paths/globs for when a root-level
Middleware should be invoked.
```javascript
export const config = {
matcher: ['/about/:path*', '/dashboard/:path*'],
}
```
This ensures we correctly match `basePath` for the `_next/data` resolving routes. The tests in the below referenced PR already cover this change so no new fixtures have been added here as they would rely on those changes landing first.
### Related Issues
x-ref: https://github.com/vercel/next.js/pull/37854
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This is the last missing piece in the size validation of edge functions. Since WASM binaries are not bundled in the user JavaScript file, we also need to count their sizes in the validation.
### Related Issues
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Include a `requirePath` property to each "build" in the `builds.json` file which is the absolute path to the Builder entrypoint that was executed.
This gives context as to which Builder was invoked by `vc build` which helps with introspection / debugging.
Some new imports were introduced recently but are missing from the `"dependencies"` object, so they were missing when the package was installed from the npm registry.
The `probes` in the vercel.json files in tests fixtures weren't allowing both `mustContain` _and_ `responseHeaders` probes due to an `else` block. This PR allows to combine those checks into the same probe test.
Gets rid of the annoying ts-jest update warning:
```
ts-jest[ts-jest-transformer] (WARN) Use 'ts-jest' entry point in v28 will resolve in refactored transformer. If you wish to use legacy transformer, please adjust your Jest 'transform' config. For example:
module.exports = {
transform: {
'^.+\\.tsx?$': 'ts-jest/legacy'
}
}
```
Add support for Edge Functions when using `vercel dev`. This uses the [`edge-runtime`](https://edge-runtime.vercel.app/) to emulate the proper environment, [`ncc`](https://github.com/vercel/ncc) to parse the entrypoint (supporting TypeScript and importing node modules), and some custom marshaling to pass the request/response values through.
In a previous PR, the entrypoint path extension was stripped in `vc dev` to match the behavior of production deployments (`/api/user.js` => `/api/user`). However, it was supposed to map back to the original file extension before invoking the matching builder. This PR fixes the mapping for dynamic paths with ESM, such as `/api/[id].mjs` => `/api/[id]`.
Currently, git metadata is not included on the Vercel dashboard when a project is deployed via the CLI. This PR populates the git metadata.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
This PR adds vercel.json configuration overrides support for both new and existing project flows through the CLI. It includes integration and unit tests.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Adds support for `config.middleware` property in `@vercel/node` to output an Edge Middleware (by including a catch-all route in the output).
Also updates the zero-config detection logic to schedule a build of root-level `middleware.js`/`middleware.ts` files with `@vercel/node` with this middleware option enabled.
<img width="1174" alt="Screen Shot 2022-05-19 at 3 53 55 PM" src="https://user-images.githubusercontent.com/35947020/169402845-4eb70a24-9954-44ac-8726-a6b56161d58c.png">
If there is no workspace detected, we still want to check if there are potential projects in the monorepo. An example of this case would be:
<img width="202" alt="Screen Shot 2022-05-19 at 10 29 12 AM" src="https://user-images.githubusercontent.com/35947020/169336400-e69845e3-616e-4857-80fe-c2614a65352a.png">
The directories `backend/app-three`, `frontend/app-one`, `frontend/app-two` all have definitions within their `package.json` files that define a framework assosiated with the project. This is what distinguishes them from the `package.json` files within `backend` and `frontend`
`getProjectPaths` loops through a depth of 3 (this can be changed but in most cases of this it won't be more than 3). For each directory it recursively calls itself until it finds a `package.json` file. It then checks if the directory has a framework defined and if so it adds the path to the final return value of all projects.
If any `skipPaths` are sent into the function, no projects will be looked for within those path(s). This would include the case for a hybrid monorepo where a workspace has already been detected
### Related Issues
> Fixes#1
> Related to #2
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
`vc build` runs `vc pull` if no project settings are found locally. By default, `vc pull` pulls development environment variables, but we want either preview or production environment variables in the context of `vc build`. This PR adds a flag to the internal `vc pull` call to pull the correct environment variables.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Fixes an issue brought up in https://github.com/vercel/og-image/issues/207
The problem is that we allow a corner case with `vc dev` to run the build script, but this can break if the user ran `vc build` first due to the BOA V3 detection.
The workaround is to delete the BOA V3 directory when there is no Development Command provided since that will run the Build Command during development.
We also add a nicer error in the case when someone actually intended to emit BOA V3.
* Add regression test for nested middleware
* [next] Allow edge api endpoints in Next.js
This reverts commit d4cef69cc9 (#7898)
* delete `functions`, not `middleware`
* Add an assertion
Co-authored-by: JJ Kasper <jj@jjsweb.site>
Gets the package paths from the workspace definition for a given git repository
```ts
/**
* Gets the list of workspace package paths based on the configuration
*
* @example
*
* my-repo
* |-- packages
* | |-- api-1
* | |-- api-2
* |-- package.json
* |-- pnpm-workspaces.yaml // packages: ["packages/*"]
*
* const fs = new ... // based on 'my-repo'
* const workspace = { ..., type: "pnpm" }
* getWorkspacePackagePaths({ fs, workspace }) => [
* "my-repo/packages/api-1",
* "my-repo/packages/api-2"
* ]
*/
function getWorkspacePackagePaths(fs: DetectorFilesystem, workspace: Workspace): string[]
```
### Related Issues
Closes https://github.com/vercel/vercel/issues/7749
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Adds support for `@vercel/node` to return an `EdgeFunction` output when it detects `runtime: 'experimental-edge'` from the static `config` object. This is implemented in `@vercel/node` so that it can share the same file extension (`.js`/`.ts`) as Node.js Serverless Functions without modifying the zero-config detection logic.
**Example:**
```js
export const config = {
runtime: 'experimental-edge',
};
export default req => {
return new Response(`Hi, from an Edge Function!`);
};
```
* Ensure middleware route comes before beforeFiles rewrites
* update test
* add version lock and more tests
* update nested middleware test for version lock
Node 12 is EOL and we're starting to reference packages that don't install on node lower than 14, such as nuxt@3 and remix. Let's update to 14 for now.
---
Reimplements: https://github.com/vercel/vercel/pull/7819
This PR adds support for experimental [corepack](https://nodejs.org/api/corepack.html) to `vc build`.
Since this is still experimental, we only enable if the env var `ENABLE_EXPERIMENTAL_COREPACK=1` is set.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
This PR updates the way we handle warning for engines.node in `package.json`.
- should not warn when the engines version satisfies the project settings (previously it was an exact match)
- should warn when engines version is exact instead of range since it cannot be satisfied exactly
- should warn when engines version is greater than since it might introduce breaking changes for a future node.js version
This PR adds support for extracting `config` from swc's AST. `static-config` supports parsing from the source program but in some cases we already have parsed an AST to do other static code analysis.
### Related Issues
None
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
[cli] Add `vc build` integration test
Adds a `vc build` integration test to ensure the ncc'd CLI works as
expected to supplement the unit tests from #7869.
Co-authored-by: Steven <steven@ceriously.com>
These tests are asynchronous and would sometimes fail if the second call started before the first call finished. This PR fixes the usage since the function returns a promise.
This fixes an issue when an external contributor submits a PR and the remote cache is not accessible
```
$ turbo run build
ERROR No caches are enabled. You can try "turbo login", "turbo link", or ensuring you are not passing --remote-only to enable caching: <nil>
• Packages in scope: @vercel/build-utils, @vercel/client, @vercel/frameworks, @vercel/go, @vercel/next, @vercel/node, @vercel/node-bridge, @vercel/python, @vercel/redwood, @vercel/remix, @vercel/routing-utils, @vercel/ruby, @vercel/static-build, @vercel/static-config, vercel
```
```ts
/*
Example 1:
my-repo
|-- packages
| |-- api-1
| |-- api-2
|-- package.json
|-- pnpm-workspaces.yaml // packages: ["packages/*"]
getWorkspaces("my-repo") => [
{
implementation: "pnpm",
rootPath: "https://github.com/.../my-repo"
}
]
Example 2:
my-repo
|-- backend
| |-- api-1
| |-- api-2
| |-- package.json // workspaces: ["api-1", "api-2"]
|-- frontend
| |-- nextjs-app
| |-- gatsby-app
| |-- package.json
| |-- pnpm-workspaces.yaml // packages: ["nextjs-app", "gatsby-app"]
getWorkspaces("my-repo") => [
{
implementation: "yarn",
rootPath: "https://github.com/.../my-repo/backend"
},
{
implementation: "pnpm",
rootPath: "https://github.com/.../my-repo/frontend"
}
]
*/
type Workspace = {
implementation: "yarn" | "npm" | "pnpm"
rootPath: string // the path to the root of the workspace
}
function getWorkspaces(fs: DetectorFilesystem): Workspace[]
```
### Related Issues
> Closes https://github.com/vercel/vercel/issues/7730
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
To support legacy Builders like `@frontity/now` which still depends on the old `@now/build-utils` package name, create a symlink to `@vercel/build-utils` to make import the package work transparently.
Depends on #7842 being merged first.
The `DevServer` class as it's currently implement is not really suitable for unit testing, since it calls `process.exit()` when shutting down the server. This causes Jest to exit prematurely, and prevents tests after these one from running. This was in fact hiding some failing tests. So these tests were ported over to be "Dev" suite tests which spawn a child process of `vc dev` rather than running them in-process, so that the `process.exit()` doesn't exit Jest.
### Related Issues
We were previously using a custom type in Next.js for the build result although there is an existing type for this in the build-utils package which we can centralize around.
x-ref: https://github.com/vercel/vercel/pull/7854#issuecomment-1133934764
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Node 12 is EOL and we're starting to reference packages that don't install on node lower than 14, such as nuxt@3 and remix. Let's update to 14 for now.
This will prevent the possibility of an infinite loop occurring when importing builders that throw a `MODULE_NOT_FOUND` error. Instead, we'll just try to import the builders, then run yarn if necessary, and then try to import the builders a second time when needed. If that fails then we'll throw the original error.
* Revert "Revert "[static-build] Support subset of Build Output API v2" (#7803)"
This reverts commit dfb6ef949b.
* more specific v2 detection
* use nuxt@3.0.0-rc.3 to make sure the incident is resolved
* set test timeout to see if this works in CI
* update CI node version to 14
* add node_modules because it was taking too long to install in CI
* remove timeout
* remove node modules
* remove the nuxt@3 dependency
* finish update to node 14
* blank yarn.lock
* revert node version update
* fix revert
* remove newline
This env var should normally come from the `.env` file that is created from `vc pull`, but let's just be extra sure and hard-code it directly in to `vc build` command as well.
SvelteKit `adapter-vercel` depends on this env var being set for its detection logic.
Specify the `useRuntimes` property for the "remix" framework
to use the `@vercel/remix` Builder.
The `ENABLE_FILE_SYSTEM_API` env var is no longer necessary so the
`vercel.json` file from the Remix template has also been deleted.
This file will mimic the structure of `vercel/frameworks/frameworks.ts` in the sense that it defines the list of supported monorepo managers. These are the ones were targeting for the initial launch,
- Turborepo
```ts
export const monorepoManagers = [
{
name: "Turborepo",
slug: "turbo",
detectors: {
every: [
{
path: 'turbo.json'
},
],
},
},
]
```
### Related Issues
> Closes https://github.com/vercel/vercel/issues/7757
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Adds a new Builder for the Remix framework. This Builder has support for a few different configurations of Remix including the "just the basics" Remix server as well as the "vercel" server build target configuration. If the project does not have the `@remix-run/vercel` runtime adapter as a dependency in package.json then this Builder will implicitly add it when generating the SSR serverless function.
In a follow-up PR, we can make this Builder be used in the frameworks configuration so that it is executed when `remix` framework is selected for the project, and we can update the remix example template in this repo to no longer require the `ENABLE_FILE_SYSTEM_API` env var.
This PR adds the latest iteration of the `vc build` command which invokes the Builders that a Project depends on locally and serializes the output into the `.vercel/output` directory.
### Related Issues
x-ref: https://github.com/vercel/nft/releases/tag/0.19.0
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Currently if you have a `package.json` with `type: 'module'` the launcher will fail to load as it is not using ESM and isn't using the `.cjs` extension. This corrects the extension per the below error message.
```sh
ReferenceError: exports is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
```
x-ref: https://github.com/vercel/next.js/issues/36903
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* Migrate ava cli dev tests to jest
* remove outdated test
* update tests
* Update utils
* update stdio to fix stalling
* test stdio tests
* add debug logs
* more logs
* use strip ansi
* update
* add exit flag and fix next dev test
* update timeout for mac ci
* update cancel
* update cancel tests.yml -> test.yml
* update other ids -> names
* remove outdated test
* de-dupe scripts
* remove redwood dev test due to size
These two tests have been problematic on MacOS for a long time,
but now that we've re-introduced `@vercel/next` into this repo,
they've started to fail on Linux/Windows as well.
So the idea is to use the `devCommand` property so that
`@vercel/next` Builder doesn't get invoked at all.
Since the `devCommand` property was not yet being unit tested,
some logic in `vc build` needed to be adjusted in order to properly
shut down the dev command (via `tree-kill` module) when the
process was being stopped in order to cleanly shut down.
The `symlink` symlink wasn't being persisted through Turbo's cache,
so this test was failing. So move the symlink directly into the git repo
since there's no need to create it at build-time (git can store symlinks
just fine).
Additionally, the test itself was not testing that the symlink was indeed
re-created as a symlink from within the lambda environment (it actually
wasn't, due to the upload code not considering symlinks), so the test
has been updated to test for that as well.
When running `nuxi build` locally, you'll end up with a `.output` directory. This is not used to produce a vercel deployment and can cause confusion with Build Output API v2 (which also expects a `.output` directory). It's better to leave this ignored.
### Related Issues
This removes the secret for turbo team as it filters anywhere vercel is printed in the logs and it doesn't really need to be secret.
x-ref: https://github.com/vercel/vercel/runs/6496893033?check_suite_focus=true
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* [tests] Use `turbo` for unit tests
* .
* .
* Revert "."
This reverts commit 3d6204fef3fda3c7b4bf08955a186fe806d7c597.
* Add "src/util/constants.ts" to outputs
* .
* Add `@vercel/node-bridge` outputs
* .
* Mac and Windows
* .
* Node 14
* .
* .
* Add templates to CLI output
* Run only selected test files
* Add cross platform testing
* make test paths relative and have minimum per chunk
* add install arg
* update shell
* bump cache key
* use backslashes on windows
* pass tests as arg
* update script name
* update turbo config
* forward turbo args correctly
* dont use backslashes
* chunk integration tests instead
* update env
* separate static-build tests
* ensure unit test turbo cache is saved
* ensure turbo cache is saved for dev/cli
* fix cache key and update timeout
* Increase static-build unit test timeout
* Leverage turbo remote caching instead of actions/cache
* apply suggestions and test chunking itself
* update other ci jobs
* fix test collecting
Co-authored-by: Nathan Rajlich <n@n8.io>
This test was added several years ago, before the monorepo in https://github.com/vercel/vercel/pull/2812 but it was never working correctly due to the way zero config behaves differently than the test with `builds` in vercel.json
We can fix it in a follow up PR
Node.js 12 reached EOL April 2022 so its time to notify customers.
This PR will warn starting today and then error once the discontinue date is reached in a couple months.
### Related Issues
Fixes pnpm 7 support. Now uses a yarn installed version and drops an unnecessary check for node version.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
These frameworks (remix and solidstart) use the legacy file system api (v2) so they can't support Node.js 16.x so we change engines to pin to Node.js 14.x
I also added the missing `ENABLE_FILE_SYSTEM_API=1` env var to solidstart to match remix.
https://vercel.com/docs/file-system-api/v2
* Track source of getting decrypted environment variables
* Add source as a query param
* Revert lock file changes
* Change source from strings to type
* Differential between pull and env pull
In order to support various `fs` operations for monorepo detection, the team needs to add two new abstract functions to `DetectorFilesystem` in order to traverse down into children directories
* readdir
* chdir
```ts
interface Stat {
name: string
path: string
type: "file" | "dir"
}
export abstract class DetectorFilesystem {
...
/**
* Returns a list of Stat objects from the current working directory.
*
* @example
*
* const url = "https://github.com/vercel/front"
* const fs = new GitDetectorFilesystem(...) // based on url
*
* // calls "https://api.github.com/repos/vercel/front/contents" behind the scenes
* await fs.readdir() => [
* { name: "docs", path: "docs", type: "dir" },
* { name: "front", path: "front", type: "dir" },
* ...,
* { name: "package.json", path: "package.json", type: "file" },
* ]
*/
protected abstract _readdir(name: string): Promise<Stat[]>;
/**
* Changes the current directory to the specified path and returns a new instance of DetectorFilesystem.
*
* @example
*
* my-repo
* |-- backend
* | |-- api-1
* | |-- api-2
* | |-- package.json // workspaces: ["api-1", "api-2"]
* | |-- yarn.lock
* |-- frontend
* | |-- nextjs-app
* | |-- gatsby-app
* | |-- package.json
* | |-- pnpm-workspaces.yaml // packages: ["nextjs-app", "gatsby-app"]
*
* const fs = new (...) // based on "my-repo" as the root
* const backendFs = fs.chdir("backend")
* const frontendFs = fs.chdir("frontend")
*
* const backendWorkspaceManager = detectFramework({ fs: backendFs, frameworkList: workspaceManagers }) // "yarn"
* const frontendWorkspaceManager = detectFramework({ fs: frontendFs, frameworkList: workspaceManagers }) // "pnpm"
*/
protected abstract _chdir(name: string): DetectorFilesystem
...
}
```
### Related Issues
> Related to https://github.com/vercel/vercel/issues/7750
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
### Related Issues
Adds support for `pnpm@7` using a similar lock file detection and path setting method that `npm@7` uses
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This check prevents a user from creating a build output targeting one environment (like `preview`) and deploying targeting another environment (like `production`). It checks `.vercel/output/builds.json` for the `target` property to decide this. If that file is missing, the check is not run.
The "remix" magic package is no longer preferred by Remix,
so anyone who is using a modern template won't have it installed.
Checking for `remix.config.js` is safer detection logic.
Checks for `TTY` input to decide to handle the command or not. If the input is not TTY and the user did not pass the `--yes` option, the CLi will exit with the message:
> Command `vercel pull` requires confirmation. Use option "--yes" to confirm.
In order to support monorepo detection, we need to build out the list of supported workspace managers so that our helper functions and API endpoints can utilize the same `detectFramework` function / logic to detect a workspace manager for a given git repository.
### Related Issues
- Closes https://github.com/vercel/vercel/issues/7731
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
### Related Issues
improves package manager auto detection so that when multiple lock files are found, the highest priority one is selected rather than defaulting to yarn.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This PR does a few things:
- Changes the existing warning message for Python 3.6 to print a discontinue date
- Will automatically fail new Python 3.6 deployments created after that date
- Consolidates logic to make Python version selection work in a similar manner to Node.js version selection
- Changes tests from JS to TS
Supply light mode logos over the frameworks API to be consumed by front
### Related Issues
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
When a framework that outputs Build Output API v3 specifies the `cache`
property in the `config.json` file then static-build will include those
files in the `prepareCache()` function result.
When using `vc deploy --prebuilt`, we need to check for an actual ".vercel/output" before attempting to deploy. This PR adds a a check for that. Now...
In a directory without `.vercel/output`:
```
$ vc deploy --prebuilt
Error! Option `--prebuilt` was used, but no prebuilt deploy found in ".vercel/output"
```
In a direcotry with `.vercel/output` (where I've not linked it yet):
```
$ vc deploy --prebuilt
? Set up and deploy “~/source/vercel/examples/build-output-api/serverless-function”? [Y/n]
```
When the `.vercel` directory does not exist and the env vars
(`VERCEL_PROJECT_ID`/`VERCEL_ORG_ID`) are used for project
linking, the `vercel pull` command was throwing an error:
```
$ VERCEL_PROJECT_ID=xxxxxxxx VERCEL_ORG_ID=xxxxxxxxxx vercel pull
Vercel CLI 24.1.1-canary.3 — https://vercel.com/feedback
Downloading "development" Environment Variables for Project t
Error! ENOENT: no such file or directory, open '/Code/t/.vercel/.env.development.local'
```
This PR adds the required changes to the CLI to support overridable `vercel.json` `projectSettings` values. This PR is linked with changes on the API side too.
- The core changes are in `packages/cli/src/commands/deploy/index.ts`
- An unused code path was removed from `packages/client/src/create-deployment.ts`, `packages/cli/src/util/deploy/process-deployment.ts` and `packages/cli/src/util/index.ts`.
This will only work for *existing* deployment (not *new* ones). This is implemented by checking the `status` of the deployment (is it linked or not). An error is thrown if the user attempts to send overrided settings to a new project.
A warning is outputted when overrided settings are discovered and shares what settings are being overridden.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This PR sets environment properly in `vc pull`. The system env vars were not respecting the target `--environment`.
Adds tests for related `vc env` logic.
Go 1.18 has been released, but I find that I can't deploy my project on Vercel when `go.mod` has `go 1.18` in it.
1.18 adds some very useful features. It would be very valuable for developers to have Vercel support 1.18.
### Related Issues
This ensures a content-type is always set inside of each part of the multi-part payload as it's needed for proper parsing. This also ensures non-200 status codes/headers are passed back separate when they differ so that they can be handled independently without assuming they all match.
x-ref: https://vercel.slack.com/archives/C03AYHB6MA9
x-ref: https://github.com/vercel/vercel/pull/7507
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* Add `turbo.json`
Ran `npx @turbo/codemod create-turbo-config` like the warnings have been telling us to.
* [tests] Bump `turbo` and allow `turbo.json` in `.vercelignore` (#7623)
Co-authored-by: Jared Palmer <jared@jaredpalmer.com>
Co-authored-by: Steven <steven@ceriously.com>
Follow-up to #7671. Since `runNpmInstall()` might now be de-duped, only
print "Installing dependencies..." when the dependencies are actually
being installed. This avoids printing the log message unnecessarily when
the command won't actually be run, and also removes some duplication in
the Builders' code.
Adds detection logic for a framework / build script outputting Build Output v3
format to the filesystem. In this case, `static-build` will simply stop processing
after the Build Command since deserialization happens in the build-container side
of things (this is different compared to the v1 output which gets handled in this
Builder. The reason for that is because the v3 output matches what `vc build`
outputs vs. v1 which is a different format).
Adds a best-effort optimization to only run `npm install` once per
`pacakge.json` file. This will save a lot of time in the single-sandbox
build world (i.e. `vc build`).
### Related Issues
Updates the @vercel/nft dependency across the repo to v0.18.1.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
The `prepareCache()` function was throwing an error when doing `vc deploy --prebuilt` because the `package.json` file is not present.
Also just cleaned up the logic a bit.
`repoRootPath` is provided to the `prepareCache()` function and is the same value as provided to the `build()` function.
Also remove `cachePath` since it's no longer used.
* refactor in prep for changes
* pull all target env files
* update `pull` usage
* move .env files into /.vercel
* tighten types in helper functions
* add return type
* remove "any" type
* keep original behavior
* only use --env for root-level env file name
* add --target flag
* deprecate --env for --env-file
* rename --target to --environment
* more renaming
* pr feedback
* update `vc pull --help`
* Update pull.ts
* remove env-file logic from `vc pull`
Co-authored-by: Steven <steven@ceriously.com>
`vc`'s default command is `deploy`, which can lead to ambiguous cli invocations when running `vc dir-or-command` like:
```
$ vc list
Vercel CLI 23.1.2
Error! The supplied argument "list" is ambiguous.
If you wish to deploy the subdirectory "list", first run "cd list".
```
when run in a directory that contains a subdirectory "list". This conflict will happen with any current and future commands, like `vc build`.
In order to make sure the CLI can be invoked either way, this PR deprecates the default behavior. Going forward, a user would see the following.
**Conflicting Command, Run Command**
```bash
$ vc list
# warning: Did you mean to deploy the subdirectory "list"? Use `vc --cwd list` instead.
# ... runs the `list` command
```
**Conflicting Command, Deploy Directory**
```bash
$ vc --cwd list
# ... deploy as normal
```
---
Card: https://linear.app/vercel/issue/BUI-33/prevent-ambiguous-vc-command-oror-dir
Working with @TooTallNate to update the Vercel Redwood builder,
in preparation for the Redwood 1.0 launch.
- Support for nested api functions in dist folder:
This is essentially a change to the glob to pick up functions 1 level deep in the dist folder. In prior version of Redwood, we had a workaround specific to Vercel that we would like to take out. See redwoodjs/redwood#4813.
- ZeroConfig redirects:
Redwood now generates a 200.html file on every build, which is the "fallback" page for when a html file cannot be matched with the path. This PR adds support for using this 200.html file, out of the box for Redwood projects on Vercel.
This is to make it easy for users to deploy a partly prerendered project - without having to mess with the vercel.json file.
Closes#7592.
Closes#7630.
`vc build` outputs to the root-level `.vercel` directory, so no need to consider `rootDirectory` of the Project Settings when collecting this file list.
.substr() is deprecated so we replace it with .slice() or substring() which aren't deprecated
Signed-off-by: Tobias Speicher <rootcommander@gmail.com>
Co-authored-by: Steven <steven@ceriously.com>
Add `pnpm` commands to framework `installCommand.placeholders` so that it appears in the UI.
Additionally, adds the `pnpm-lock.yaml` file to an ignore list like the other lock files.
`vc build` is going to re-use the `meta` object between Builder
invocations, to allow arbitrary state to be shared between them. So
allow for additional properties to be specified on `Meta` with an
`unknown` type.
* fix test 24 and add test 25
* move pnp/symlink test to cli and complete hoisted test
* fix execa
* remove unnecessary gitignore
* Update packages/cli/test/integration.js
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/test/integration.js
Co-authored-by: Steven <steven@ceriously.com>
* complete cherry-pick
* remove package.json edit
* use fs-extra remove
* use fs-extra.remove correctly
Co-authored-by: Steven <steven@ceriously.com>
In a previous PR (#4254), the behavior of `vercel dev` was added separately without matching how deployments work.
This PR consolidates the `tsconfig.json` options for `vercel` deployments as well as `vercel dev` so they work the same.
Fixes https://github.com/vercel/customer-issues/issues/349
* temp commit
* update test case
* check for build cache hit
* Update packages/build-utils/test/integration.test.ts
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Steven <steven@ceriously.com>
When running this example using `pnpm`, the filesystem environment variable was causing issues.
This change removes the variable and the file since it no longer serves a purpose.
Deployment was tested using `pnpm`, `npm`, and `yarn` and all seem to run successfully now
### Related Issues
x-ref: https://github.com/vercel/next.js/pull/34935
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Fixes issue introduced by #7436 when using `vc dev`. Since the dev-server script now imports `@vercel/node-bridge` directly, instead of copying the relevant files into the package, the bridge needs to be a regular dependency otherwise the import will fail.
```
Error: Cannot find module '@vercel/node-bridge/launcher.js'
Require stack:
- /usr/local/lib/node_modules/vercel/node_modules/@vercel/node/dist/dev-server.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:902:15)
at Function.Module._load (internal/modules/cjs/loader.js:746:27)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at Object.<anonymous> (/usr/local/lib/node_modules/vercel/node_modules/@vercel/node/dist/dev-server.js:79:23)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
Error! `node api/hello.js` failed with exit code 1
```
* refactor and add test to changelog
* group changelog into areas
* remove revert and reverted commits from changelog
* make sure Revert commits that revert a commit in a previous changelog are not filtered
* run "yarn test" as part of "yarn test-unit"
* remove advanced syntax
* remove advanced syntax
* temp changelog
* remove temp changelog
* remove global jest config
* Delete symlink
* scope jest dir to just the test files we care about
Add support for `pnpm` as well as new fixtures for `pnpm` with and without workspaces
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit && yarn test-integration-once`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
* docs: use meaningful word in contributing
I have changed the word `run` to `pass` in the Contributing Guidelines file inside `Verifying your change` documentation.
This provides a better understanding of how to run tests after every change.
* docs: remove `test` command run in local development
Remove guideline to test the code using `yarn test`, the test command does not exist in the project root but the build command automatically runs the tests.
* docs: add info about how tests are run
Add information about tests are run in this repo
* docs: fix testing scripts reference
Fixed some mistakes in the contributing readme
- Added `yarn test-unit` instead of `yarn test`
Co-authored-by: Steven <steven@ceriously.com>
Updates `@vercel/node` to utilize the `NodejsLambda` class so that it doesn't need to explicitly bundle in the launcher/bridge files into the build result. This reduces the complexity of the Builder and is a cleaner separation of concerns. The `helpers.test.ts` file has been moved to `@vercel/node-bridge` so it's being removed in this PR as well.
Adds formal type interfaces for Builders into `@vercel/build-utils`, and
updates the serverless functions runtimes to utilize them. This provides
type safety for the args/return values in i.e. the `build()` functions,
where previously they were not using any explicit return type.
When an instance of this class is returned in a Builder's `output`, it is a signal to the build system that it needs to add additional files to the final Lambda before creating the zip file.
* [cli] Remove initial iteration of `vc build` and Plugins
The `vercel build` command is being restructured, so we'll remove it for
now so that this initial iteration isn't included as part of the stable
CLI release.
* Update packages/cli/src/commands/init/init.ts
Co-authored-by: Steven <steven@ceriously.com>
* Remove more `.output` references
* Remove unnecessary space
* Fix test
* Remove vc dev middleware tests for now
Co-authored-by: Steven <steven@ceriously.com>
Makes the `Lambda` class itself just a reference of the files that are
needed to produce a zip file, and adds a `createZip()` function that
does the actual zip file creation. This will allow the zip file creation
to be done in the Vercel build container instead of directly in the
Builder itself.
* Adds `files` property to `Lambda` class
* Adds `createZip()` function to `Lambda` class
* Deprecates the `createLambda()` function
* Deprecates the `zipBuffer` property (only populated when `createLambda()` is used)
* Removes the private `FILES_SYMBOL` symbol, since `files` is the same thing
This PR adds a new `vercel bisect` command which is inspired by `git bisect`. This command takes two deployment URLs as its input (one "bad" deployment that exhibits a bug, and one "good" deployment where the bug does not occur) and steps through the deployments using a binary search. The command is useful for finding a deployment (and commit if the project is connected to a Git repo) where a bug has been introduced.
<img width="582" alt="Screen Shot 2022-01-26 at 12 46 29 PM" src="https://user-images.githubusercontent.com/71256/151244295-8e90c493-c45f-40b4-8e43-f39e7fcac262.png">
These integration tests have started consistently failing with
`ECONNRESET` errors and after some debugging it's been
difficult to point the finger at anything related to Vercel
infrastructure. So possibly it's related to GitHub actions infra
changes, but either way retrying seems to help.
* [ci] Add turborepo for faster builds
* Replace yarn run with turbo run
* Fix typo
* Add `@vercel/build-utils` as explicit dev dep
* Remove unused --clean argument
* Only turbo the "build" script, leave tests as-is
* Bump turbo to 1.0.13
* Add back test-unit
* Revert "Add back test-unit"
This reverts commit 469868c5c06f6c6f15da7ef0a440587d41419fd8.
This is following a similar pattern to Next.js workflows so that the publish step is skipped and reduces the time it takes GH Actions to run since we don't need to build to know that it should be skipped.
This ensures that using `vc deploy --prebuilt` will also upload any files that `.output/**/.nft.json` points to and also handle the Root Directory correctly since `vc build` emits `rootdir/.output`.
- Related to https://github.com/vercel/runtimes/issues/304.
### Related Issues
> Fixes#7086
> Related to #7086
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
We have identified that the `handler` for Lambdas does not support a dot-preceded path for Ruby, Python, and probably other languages, so we're adjusting the File System API to change `.output` inside the Lambda to something else, which requires version `2` of `functions-manifest.json`.
Furthermore, we're also bumping the `.nft.json` files to version `2`, which allows `output` to be relative to the NFT file itself, so that, inside the Lambda, the behavior mentioned at the top can be applied by the File System API.
As a nice side effect, this will also support nested API Routes, because it'll place all the dependencies next to every API Route, meaning that the launcher will have access to all of them (bundling multiple API Routes or Pages into the same Lambda currently doesn't work for non-Next.js anyways, because of https://github.com/vercel/runtimes/issues/305).
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Previously, CLI Plugins would try to mount the user-provided request handler (e.g. `api/test.rb`) at the same position inside the Lambda at which the launcher was located (e.g. `api/test.rb`), which would cause the launcher to be overwritten.
With this change, all the destination mounting points for NFT input files are becoming relative to the `.output/server/pages/api` directory instead of `.output/server/pages`, so they should no longer overwrite the launcher, and instead be loaded from the launcher, like normal.
This PR might have two problems:
- If imports in Ruby/Python/etc are relative to `cwd` and not the file from which the import is executed (which I doubt), this would fail.
- We might have to replace `api` with the exact sub folder of the API Route within `.output/server/pages/api` if the current change doesn't yet work for nested paths. Although that also means repeating all of the other dependencies (not just the user-provided request handler) in a different location for every single API Route.
The two above will be tested after this PR was merged, as there currently isn't a way to test `vercel-plugin-go`, `vercel-plugin-python`, and `vercel-plugin-ruby` without publishing a canary, because they don't bundle `@vercel/build-utils`, which was the package that was just updated.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
* Use correct Lambda handler for compiled languages
* Use the correct entrypoint
* Fixed the logic
* Perfected it
* Simpler code
* Update packages/build-utils/src/convert-runtime-to-plugin.ts
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
* Handle edge cases and simplify logic
* Fixed the logic yet again to work perfectly
* Normalize Page path
* Simplified everything
* Fixed the tests
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
* Corrected CLI Plugin output creation
* Wait for the linking to be done before removing anything
* Make it work
* Renamed variables
* Made everything work
* Removed debugging
* Fixed comment typos
* [cli] Support `next export` in `vercel build`
* Add debug line
* Remove unused import
* Ensure file is copied
* Return in `getNextExportStatus`
* Include dotNextDir
Co-authored-by: Steven <steven@ceriously.com>
### Related Issues
This fixes https://github.com/vercel/runtimes/issues/299.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
* Fixed error with API directory
* Made output work
* Use handler as API Route
* Correctly find the handler
* Fixed a missing instance
* Made handler logic work
* Made it work as expected
* Exclude unnecessary files
* Use a method that always works
* Additional comment
* Made everything work
* Cleaner tests
* Clean up all the useless files
* Fixed missing instance
* Speed up the code
* Removed useless lines
* Update packages/build-utils/src/convert-runtime-to-plugin.ts
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
* Clarified comment
* Use relative logic again
* Fixed tests
* Deleted useless file
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
### Related Issues
This applies what was mentioned in https://github.com/vercel/runtimes/issues/288#issuecomment-984101750.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
After https://github.com/vercel/vercel/pull/7088, `dist` now contains `package.json`, which made `tsc` move `index.js` a level deeper, effectively breaking the `main` property of all of the affected CLI Plugins.
This change makes them work again.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
* Avoid unnecessary Gemfile installations
* Do not bundle `.output` or `.vercel` into Lambdas
* Use the same input hash format for all CLI Plugins and `vercel build`
* Fixed unit tests
* Fixed the unit tests again
* Fixed the unit tests
* Fixed all the tests
* Exclude useless files
* Consider `.vercelignore` and `.nowignore`
* Fixed error
* Reverted changes
* Deleted useless file
* Fixed tests
* Share input hash format with `vercel-plugin-node`
* Make output inspectable
* Fixed build error
* Extended comment
* Bump Ruby version
* Update Gemfiles
* Update bundles
* Fixed tests
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
* Stop passing `functions` and `regions` to Runtimes
* Added required types back
* Removed `vercelConfig` from `vercel-plugin-node`
* Fixed unit test
* Fixed test
* [cli] Consider `envPrefix` for the framework
* Fix env
* Remove type
* Resolve .nft.json files correctly
* Fix public and static directory handling
* Do not use .replace
* Consider the output directory
* Added Remix to the list of frameworks
* Replaced Development Command
* Polished config
* Added headers
* Added example
* Fixed logo
* Trigger a Deployment
* Added vercel.json
* Port is automatically parsed through remix.config.js
* Fixed sorting
* Moved it down a bit
* Trigger a Deployment
* Removed useless property
* Reverted readme
* Fully reverted readme
* [plugin-node][node] Fix dependency installation, handler path, and build script
* Use smaller library for testing
* Make test work on windows
* Remove .output before fixture runs and update routes update
* Apply suggestions from code review
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Steven <steven@ceriously.com>
### Related Issues
The Parcel template via the Project Creating Flow returns a build error because the default output directory for the Parcel **Framework Preset** is searching for `public` instead of `dist`. The default behavior of Parcel's CLI I believe is `dist`.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* [python] Upgrade python 3.9
* Fix python path
* Improve testing
* Add support for version selection via Pipfile
* Parse the "Pipfile.lock" instead
* Fix support for Node.js 12
* Switch from hardlinks to symlinks in vc build
* Remove error handling that fs-extra already takes care of
* Add comment
* Put back symlink error handling
Seems like macOS sometimes exceeds 60 min so this bumps the timeout.
The build can be between 3 minutes and 5 minutes. The tests can be between 45 minutes and 55 minutes.
* Prevent infinite recursion of vercel build and dev
* Improved text
* Improved the text further
* Add tests
* Debug test
* Add debug log
* Debug test
* debug test
* Debug test
* Fix test
* Debug tests
* Debug test
* Remove only from tests
* Add error documentation
* Improved docs
* Fix other test
* Fixed links to error docs
* Remove legacy error page
* Use nicer error links
Co-authored-by: Leo Lamprecht <leo@vercel.com>
* Fix middleware build result. Return middleware next when invalid result.
* Add a unit test that would have failed before previous commit.
* Copy next.js behavior.
* Add a test for invalid responses from middleware.
Co-authored-by: Leo Lamprecht <leo@vercel.com>
### Related Issues
x-ref: https://github.com/vercel/customer-issues/issues/34
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* Move loadPlugins to a utils file to be shared w/ dev server.
* Update loadCliPlugins to also return startDevServer and runDevMiddleware based plugins.
* Move plugins back to dependencies.
These can't be bundled as it interferes with plugin resolution.
* Hook up middleware plugins to dev server.
* Pass output object to loadCliPlugins instead of a logging function.
* Allow more than one runDevMiddleware defining plugins.
* Bundle esbuild w/ middleware plugin.
* Keep esbuild as an external
* Update middleware's esbuild.
* set old space size
* Revert "set old space size"
This reverts commit b579194a862949a11769e9087f01c31f2e1f3b60.
* Use --max-old-space-size for CLI unit tests
* Increase memory
* Use `run.js` to set the memory
* Make NODE_OPTIONS optional
Co-authored-by: Leo Lamprecht <leo@vercel.com>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
* [node] Refactor to Vercel CLI Plugin
* Enforce "index" suffix on output Serverless Functions
So that nesting works properly
* Some cleanup
* Add version
* Use `@vercel/static-config`
* .
* Add support for wildcard routes
* Don't compile dotfiles, underscore prefixed files, files within `node_modules`, nor TypeScript definition files
Matches the logic from `maybeGetBuilder()` in `@vercel/build-utils`.
* Bump version
* Introduce testing framework
* Debug
* Add test without any deps
* Longer timeout to install Node.js for vercel/fun
* Install deps
* Add legacy Node.js server interface test
* More tests
* Test "assets" fixture
* Test "helpers" fixture
* fix
* Support AWS native API
* Remove debugging `console.log()` calls
* Use plugin-node for new plugin instead
* Revert "Use plugin-node for new plugin instead"
This reverts commit f317b8c6ecdc67a74d5f2b12a2e7567a27d4b6b8.
* Move to `plugin-node` directory
* Update plugin-node version in package.json
* Checkout node from main
* Add yarn.lock files for tests
* Update node-bridge
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
### Related Issues
> Fixes https://github.com/vercel/runtimes/issues/219
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* Use ncc to bundle middleware plugin, move dependencies to devDependencies, remove querystring
* Switch from globby (deprecated dependencies) to glob in middleware plugin.
* Bundle the node-plugin and middleware-plugin into cli.
* Add initial `vercel-plugin-middleware`
* Ignore `entries.js` from ESLint
* Add `runDevMiddleware()` stub
* Add test
* Add support for "_middleware.{js,ts}" to `vercel dev` (#6880)
* Add websandbox from next.js codebase.
* Use node-fetch instead of next's polyfilled fetch.
* Handle middleware rewrites.
* Add response, headers, and request to websandbox context.
* Move websandbox dependency to middleware plugin.
* Add integration tests, update websandbox to support ts files and json imports.
* commit yarn.lock changes after rebasing
* Clean up left over console.logs, fix some tsc issues, and rebase issue.
* Fix failing test and eslint.
* Fix middleware test on windows.
* [examples] Update Vercel Next.js example template to 12.0.1 (#6905)
* Mark the Plugins as external to CLI's ncc build
* [cli] Improve tracing in vc build (#6898)
* [cli] Fix tracing for `vc build`
* Ignore object when there are no changes
* Make Next < 12 work with FS API w/ nft
* Update packages/cli/src/commands/build.ts
Co-authored-by: Nathan Rajlich <n@n8.io>
* Document how Next.js processing works in build
* [cli] Fix static assets (#6906)
* Make sure output path is .next
* Fix up require-server-files for processing
* Fix typo
* Move static
* Update static rename
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
* Publish Canary
- vercel@23.1.3-canary.17
- @vercel/client@10.2.3-canary.15
- @vercel/static-config@0.0.1-canary.0
* [cli] Ignore `.env` and `.gitignore` in "vc build" (#6910)
* Publish Canary
- vercel@23.1.3-canary.18
* Pass workPath to plugins.
The new plugin architecture doesn't pass a full BuildOptions object, previous
to this commit it wasn't passing any options at all. I've added workingPath to
support running dev/build from directories other than the project root.
* Remove error state when package.json exists, but no build script
This allows vercel build to continue working for projects that are not using
frameworks, but use package.json to manage dependencies.
* Fix types, pull in middleware header fix from next.js
Next js PR w/ the header fix:
https://github.com/vercel/next.js/pull/30560
* Fix missing entries file for vc build.
* Update call signature of middleware when using vc build.
Co-authored-by: Drew Bredvick <dbredvick@gmail.com>
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Jared Palmer <jared@jaredpalmer.com>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Co-authored-by: Gary Borton <gdborton@gmail.com>
Co-authored-by: Drew Bredvick <dbredvick@gmail.com>
Co-authored-by: Jared Palmer <jared@jaredpalmer.com>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
* [cli] Fix tracing for `vc build`
* Ignore object when there are no changes
* Make Next < 12 work with FS API w/ nft
* Update packages/cli/src/commands/build.ts
Co-authored-by: Nathan Rajlich <n@n8.io>
* Document how Next.js processing works in build
* [cli] Fix static assets (#6906)
* Make sure output path is .next
* Fix up require-server-files for processing
* Fix typo
* Move static
* Update static rename
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
* Add PoC pull command
* Improve pull's linking logic
* Remove `__VERCEL_SKIP_PULL_CMD` env var and unneeded type narrowing
* Improve pull's link logic
* Fix team mock
* Add smoke test for vc pull
* Add setupFixture helper
* Remove debug duplicate
* Use a fixture in pull test
* Put back debug
* Fix unit test
* Fix test on windows
* Remove mock-stdin
* Pass cwd to link and pull
* Add help command for `vc pull`
* Organize imports
* Update packages/cli/src/commands/deploy/args.ts
Co-authored-by: Steven <steven@ceriously.com>
* Use tmp-promise instead of tmp
* Update packages/cli/src/commands/pull.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/commands/pull.ts
Co-authored-by: Steven <steven@ceriously.com>
* Clean up pull comments and variable declarations
* Remove graceful tmp directory cleanup
* Put back graceful cleanup
* Print output for debugging
* Moar debug
* Set 10s timeout for `vc pull` test
* Change fixture to now-pull-next
* Fix pull test name
* Switch project mock to use encrypted env
* Add --env flag
* Update fixtures
* Remove now- from everywhere
* Remove instrumentation
* Rename setupFixture to setup-fixture
* Add deprecation warning to `vc env pull`
* Update packages/cli/src/commands/deploy/args.ts
Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>
* Update packages/cli/src/commands/env/pull.ts
Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>
* Fix pull and update imports
* Revamped build command
* printConfig -> renderConfig
* Remove frameworks
* Add build state unit test for gatsby
* Update packages/cli/src/commands/pull.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/commands/env/index.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/cli/src/util/projects/write-project-settings.ts
Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>
* Update packages/cli/src/commands/pull.ts
Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>
* Don't writeProjectSettings in env pull
* Cleanup fixtures once afterAll
* Add help text for --env and -y
* Add output for pull
* Write project settings output after env output
* Pushing for Nate
* Add todo about handling Other's build output directory
* Add support for plugins
* Improve prompt logic loop
* Pluralize plugin output
* Better plugin failure handling
* Refactor away from BuildState class
* Remove unused file
* Correct framework detection logic, smart copy w/hardlinks
* Generate build manifest
* Generate routes-manifest.json
* Remove ambiguity when calling vc build
* Make sure manifests have all keys
* Ensure that .output is added to .gitignore in vc link
* Remove directoryListing from project settings
* Add support for default cli plugins
* Remove directory listing
* Install vercel-plugin-node
* Patch console.log and console.error for plugins
* Improve build output
* Remove unused unit tests
* Allow build without token
* Add vercel plugin middleware
* Bump vercel-plugin-middleware
* Bump middleware plugin
* Tweak require.resolve
* Tweak require.resolve to __dirname
* Update `vercel-plugin-node`
* Fix prefixed logs when using formatters i.e. `%j`
* Pretty print the manifest files
* Get unique CLI deps
For the case where the local project has one of the CLI default plugins
specified.
* Update packages/cli/package.json
Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>
* Add help output
* Remove p-limit properly
* Confirm before pull in build
* Bump `vercel-plugin-node`
* [cli] Make Next.js move files into .output (#6885)
* Use OUTPUT_DIR
* Return properly if no package.json exists and no build command
* Invert logic for runPackageJsonScript
* Bump `vercel-plugin-middleware`
* Fix defaultHeaders in frameworks
* Fix build when nft files is object
* Update `yarn.lock`
* 2nd attempt at --prebuilt (#6888)
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
* Add beta and feedback to vc build
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Nathan Rajlich <nathan@tootallnate.net>
Co-authored-by: Andy Bitz <artzbitz@gmail.com>
Add `vercel pull` command. Closes https://github.com/vercel/runtimes/issues/142.

It does the following:
- Pull the `.env` file (it calls `pull` internally)
- Adds the following to `.vercel/project.json` (which will then be used by `vercel build`):
```tsx
interface ProjectLink {
projectId: string
orgId: string
settings: {
buildCommand: string | null,
devCommand: string | null,
directoryListing: string | null,
outputDirectory: string | null,
rootDirectory: string | null,
framework: string | null,
}
}
```
This PR also deprecates `vc env pull` with a warning:

### 📋 Checklist
- [x] Help output
- [x] Flags (need to combine flags from `env pull`)
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Adds an additional property for the `routes` schema.
### Related Issues
N/A
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This will prevent any issues where the `Now` instance is out-of-sync with the `Client` instance, for example, during a re-auth where a new auth token is issued. Also reduces a bit of code which is nice.
Fixes an issue where the token would not be properly upgraded while
a Team scope was currently active, causing a new auth token to be issued
and lose the previous access scope(s).
These changes originally from #6652, but pulled out to be merged
separately.
`outputBuffer` is a simpler way of asserting tests against the CLI
output instead of working directly withe Jest mock function.
`output.isTTY` is also now mutable, so that we can write tests for both
cases when the output is different based on TTY-ness (for example,
see the updated `vc whoami` tests in this PR).
This adds an argument to allow passing internal param names that should be ignored when considering whether params should be auto-added to a rewrite's destination query. After adding this we should be able to resolve https://github.com/vercel/next.js/issues/27563 in the runtime where `convertRewrites` is called.
This matches Next.js' handling for internal params which can be seen [here](e90825ad88/packages/next/shared/lib/router/utils/prepare-destination.ts (L203))
### Related Issues
x-ref: https://github.com/vercel/next.js/issues/27563
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This ensures we replace header values correctly when no named segments are used and only has items are used.
### Related Issues
Fixes: https://vercel.slack.com/archives/CHTTGQYQ4/p1631023974185700
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* Rewrites the CLI unit tests to be TypeScript and use Jest (consistent with the unit tests in the other packages in this repo).
* The file structure of the new test files mirrors that of the `src` directory, so that it's easy to find the relevant tests.
* Code coverage is also properly set up through Jest - you can already see a big increase in coverage from this PR.
* Adds a mock API server framework, with the intention of making it possible to write granular tests of the CLI commands. Using mocks also has the benefit of not requiring `VERCEL_TOKEN` env var to be set, so 3rd party PRs will be able to have their tests run. Ultimately this will also help with test coverage, since we will be writing unit tests that test the commands' code directly.
* Converts `Output` into a proper class (which is subclassed for the mocks).
To make setting up local dev README instructions easier for new users being introduced to a Vercel project, support flags to make the `vc link` command be non-interactive, in the case where the project name does not match the name of the directory where the code is located:
```
$ vc link --scope acme --project docs
```
Related to https://github.com/vercel/front/pull/10732.
Before:
```
Error! Unexpected error. Please try again later. ()
```
After:
```
Error! An unexpected error happened when running this build. We have been notified of the problem. If you have any questions, please contact support@vercel.com.
```
### Related Issues
Check the project's nodeVersion setting for when we release Node 16 and later
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Currently, when `scanParentDirs()` finds the closest `package.json` file, it stops iteration regardless of whether or not a lockfile was found. For npm Workspaces, this is problematic because if you are deploying a subdirectory of a monorepo, then there will be no lockfile in the subdirectory (the `package-lock.json` file is at the root of the project). So instead of stopping once the `package.json` file is found, instead stop when the first lockfile is found.
And remove `jest`/`ts-jest` from the individual packages. It is important to have a consistent version of `jest` being used throughout the monorepo, otherwise bizarre errors surface that cause jest to crash, such as [here](https://github.com/vercel/vercel/runs/3255999061?check_suite_focus=true):
```
TypeError: this._environment.runScript is not a function
at Runtime._execModule (../../node_modules/jest-runner/node_modules/jest-runtime/build/index.js:856:41)
```
As the title suggests, this PR makes it such that npm 7 will be invoked when there is a `package-lock.json` file with `lockfileVersion` 2 or greater, by prepending the the `$PATH` a directory within the build container where npm 7 is located.
The test fixture `20-npm-7` is also enabled for E2E testing, to ensure that the proper npm version is enabled in the production build.
Makes the `test/unit.test.ts` file be TypeScript, and import from the source TypeScript code. This way, we don't need to run `yarn build` to test local changes when testing.
Also, VS Code was complaining about the types for jest `describe()`/`it()` not being installed, even though they are. After some digging, I found that TypeScript has a peculiar behavior with types in monorepo setups. [This solution](https://github.com/microsoft/TypeScript-Node-Starter/issues/196#issuecomment-771988960) describing adding a `tsconfig.json` inside of the `tests` dir seems to do the trick.
Like this, we can avoid that the dashboard will ask people to pass `--port` when running SvelteKit's Development Command.
Only `vercel dev` will make use of it.
This ensures we validate segments being used from `has` in the `destination` correctly
### Related Issues
x-ref: https://vercel.slack.com/archives/CLDDX2Y0G/p1627285500281300
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Follow up to #6508. Adds a request "counter" that increments for every API request, matching how `front` does it.
Also tweaks the `output.time()` output a bit by rendering the timestamp in gray, and with `[]` brackets. If the time diff is < 1000ms then the full milliseconds will be printed intstead of the seconds.
<img width="710" alt="Screen Shot 2021-07-22 at 2 45 39 PM" src="https://user-images.githubusercontent.com/71256/126713843-db70ed9c-4752-4ca9-8f54-313c4cb44914.png">
Updates the `output.time()` function to accept a function as the "label" parameter. When a function is passed, it will be invoked twice, once at the beginning of the promise being executed, and a second time after the promise has resolved. The second time, the return value of the promise is passed to the label function, so that the resolved value may be used to create the label.
Drops usage of Node's `console.time()` and `console.timeEnd()` since we were using it in a hacky and unnecessary way.
Adds an "out-of-band" login mode to the `vc login` command, for use in headless environments like inside a Docker container or an SSH session. In these situations, spawning a localhost HTTP server won't work, because the HTTP server will not be accessible to the web browser that is doing the authentication.
In "out-of-band" mode, the login URL is simply presented to the user, and they must visit the login URL in their web browser and complete the authentication. The callback URL is a page on front that shows the verification token to the user and instructs them to copy + paste the token back into the CLI, at which point the login can complete.
Docker/SSH sessions are attempted to be automatically detected, and "out-of-band" mode is enabled implicitly. But there is also an `--oob` flag in case that detection logic were to fail (or if you'd like to run OOB mode locally).
This PR also adds shortcut flags for the Git provider login mechanisms, i.e. `vc login --github`.
https://user-images.githubusercontent.com/71256/125129304-1f5f3380-e0b4-11eb-8139-d1109811bd86.mov
This is a continuation of https://github.com/vercel/vercel/pull/6382 (thank you @markozxuu!) with merge conflicts addressed and pushed to a local branch, so that CI tests run.
Currently the `06-rails` test is failing at build time with:
```
16:27:09.550 'Your bundle is locked to mimemagic (0.3.3) from rubygems repository\n' +
16:27:09.550 'https://rubygems.org/ or installed locally, but that version can no longer be\n' +
16:27:09.550 'found in that source. That means the author of mimemagic (0.3.3) has removed it.\n' +
16:27:09.550 "You'll need to update your bundle to a version other than mimemagic (0.3.3) that\n" +
16:27:09.550 "hasn't been removed in order to install.",
```
So I ran `bundler update` in the "06-rails" Ruby test fixture to update the deps in the Gemfile.lock file.
Fixes an edge case bug when the user has a current scope that is
different than the owner of the project that is being deployed.
When this was the case, the API call to get the certs for a domain at
the end of the `vc deploy` command was using the incorrect `teamId`,
potentially causing a 403 error (when the current auth token does not
have access to the selected scope).
`vc deploy` doesn't care about the current "scope" that the CLI has selected, since it uses the `.vercel` directory to determine the ownerId and projectId.
Therefore, it should not be fetching the team details of the selected scope during `vc deploy`, since it's possible that the token might not have access to the current scope and returns a 403, even though that API call is unnecessary for the `vc deploy` command to complete.
Closing keep-alive HTTP connections was causing the `server.close()` call
to take a few seconds before completing, so set the `Connection: close`
response header in order to make the connections close immediately,
so that `server.close()` is fast.
Considering that it's a development environment, it's not important to wait for ongoing HTTP request connections to complete. Sometimes it takes a long time for all the shutdown operations to complete, which makes the command feel sluggish. So let's just `process.exit()` and exit quickly.
This Runtime is very old, outdated, unmaintained, and has never been documented.
Additionally, it no longer compiles with the latest version of Go. So
rather than fixing it, let's just remove it since we don't want to
invest any more time into it.
In some cases (i.e. when SSH'd to a remote machine) the `open` command will not work reliably. So we need to print the URL to the user as a fallback for those cases when the web browser is not automatically opened.
This also moves where `tokenName` is specified to be in the "verify" endpoint, so that it does not need to be part of the URL that gets printed to the user.
<img width="738" alt="Screen Shot 2021-06-07 at 2 12 47 PM" src="https://user-images.githubusercontent.com/71256/121089239-b5452d00-c79b-11eb-85b2-0e45b817dff0.png">
* refactor: Remove unncessary file
* feat(cli/alias): Migration to TS
* refactor(cli/alias): Add a line break
* refactor(cli/alias): Remove unnecesary code
* feat(cli): Add `Paginationoptions` type to `pagination`
* feat(cli/commands): Rewrite th `alias ls` command to TS
* refactor: Remove unncessary code
* feat: Create helper function for `getSafeAlias`
* refactor: Remove unnecessary code
* feat: Remove parameter generic, "null" for the fetch
* feat(cli/alias): Rewritten in full TS
* feat: Add Partial to opts
* refactor: Remove comment @ts-ignore
* feat: Add Partial to opts
* feat: Only should be return `alias.uid`
* refactor: Remove `Alias` type from of the parameter `id`
* refactor: Remove destructuring from alias object
* refactor: Remove unnecessary code
* feat: Rename `created` property to `createdAt` of number type
* refactor: Move getSafeAlias function in the same file
* refactor: Simplifying code
* refactor: Intentation did not affect diff on git
* Add null back to type
Co-authored-by: Steven <steven@ceriously.com>
The call to `GET /projects/info` is used to check existence but it can cause a race condition if the project was removed before the `DELETE /v2/projects` is called.
Instead, we rely on the response from `DELETE /v2/projects` to determine if the project exists or not.
This will also allow us to remove a legacy API endpoint in the future (see related API PR)
This ensures we normalize header `key` values in `has` items to be lower-case as the proxy currently only matches against the lower-case variant. Updated superstatic tests to ensure the header key is normalized correctly.
### Related Issues
[related thread](https://vercel.slack.com/archives/C01N3RWTE5V/p1621937306006400)
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
In the `vc switch` command, if your current access token results in
"limited" Team information being returned, then show a lock emoji
next to the team/user name in the select input.
When a locked scope is selected, then pre-emptively prompt the
user to re-authenticate using a valid login method in relation to
the desired scope.
https://user-images.githubusercontent.com/71256/119441172-87abae80-bcda-11eb-801a-cb6837bae353.mov
[ch21964]
We're not currently setting the `tokenName` when logging in via a
Git provider, so the name becomes the default "Website" one which
is confusing / incorrect.
Refactors the `vc switch` command to more closely match how the team picker works on the Vercel dashboard:
* Converts to TypeScript
* Adds separator between user scope and team scopes
* Sorts teams by name
* No longer places the current scope at the top of the list (but the current scope is still selected by default)
It's failing during runtime, like here: https://github.com/vercel/vercel/runs/2520732314
With an error like so:
```
[GET] / 2021-05-06T20:02:55.411Z undefined ERROR The gRPC
binary module was not installed. This may be fixed by running "npm rebuild"
Original error: Cannot find module
'/var/task/node_modules/grpc/src/node/extension_binary/node-v83-linux-x64-glibc/grpc_node.node'
Require stack:
- /var/task/node_modules/grpc/src/grpc_extension.js
- /var/task/node_modules/grpc/src/client_interceptors.js
- /var/task/node_modules/grpc/src/client.js
- /var/task/node_modules/grpc/index.js
- /var/task/node_modules/google-gax/build/src/grpc.js
- /var/task/node_modules/google-gax/build/src/index.js
-
/var/task/node_modules/@google-cloud/scheduler/src/v1beta1/cloud_scheduler_client.js
- /var/task/node_modules/@google-cloud/scheduler/src/v1beta1/index.js
- /var/task/node_modules/@google-cloud/scheduler/src/index.js
- /var/task/index.js
- /var/task/___vc_launcher.js
- /var/runtime/UserFunction.js
- /var/runtime/index.js 2021-05-06T20:02:55.411Z undefined ERROR
Did you forget to add it to "dependencies" in `package.json`? RequestId:
2cdba37e-4bf4-4a2f-b443-4ebcc99fe308 Error: Runtime exited with error: exit
status 1 Runtime.ExitError
```
Because grpc is failing with NFT.
But also, the test is no longer necessary because we no longer support Node 8 which was what the original test intended https://github.com/vercel/now-builders/pull/463
Refactors the CLI `vc login` command with the following features:
* Adds GitHub, GitLab and Bitbucket as login options
* Uses a "list" input to select which login method to use (same list as `vc init`)
* Support connecting SAML Profile to Vercel user during login
This ensures that when segments are coming from only `has` items we still replace them correctly as they currently don't get replaced if the `source` doesn't have any segments as well.
### Related Issues
x-ref: https://vercel.slack.com/archives/CLDDX2Y0G/p1619061783470000
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
* Ensure has segments are replaced in destination
* update type
* Use regex lexar for gathering named groups from has
* Update to use shared repo for regex lexer
* apply suggestions
* remove regexr from .eslintignore
Node.js 10 is about to reach EOL so we can drop CLI support in the next major release. We'll support 12+ going forward.
Node.js 12 needs `es2019` because it doesn't support the `es2020` features of optional chaining and nullish coalescing as seen from the [compatibility table](https://kangax.github.io/compat-table/es2016plus/#node12_11).
### Changes
- Add support for Git Branch
- Use a single env type: "encrypted"
- Remove unnecessary questions during `vc env add`
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
If the user is signed in to a team with SAML enforced, but the
current token is not a SAML token, then `getScope()` will fail.
So add the option to opt-out of team information in `getScope()`
and use that new option in `vc whoami` since it doesn't require
team information.
When the API returns a `saml: true` error, CLI will re-trigger the SSO
auth browser window so that the user can sign into their identity
provider again. Once the new token is received, it is saved to the
`auth.json` file (unless the token was specified via `--token`) for
future use.
This is a rather large refactor of the CLI codebase that merges the
`NowContext` object into the `Client` class.
There's a few reasons to do this:
1. Nearly every sub-command was creating its own `Client` instance, leading to a lot of duplicated code. It makes more sense to create one instance and pass it to every sub-command, which deletes a lot of code as well.
2. There's a lot of overlap between `NowContext` and the props on the `Client` class, so it was a relatively easy transition.
3. The main reason is so the same `authConfig` is used throughout the program lifecycle. This paves the way for updating the token mid-flight when i.e. a SAML token has expired. In a follow-up PR, CLI will handle that scenario gracefully by re-triggering the SAML auth flow.
* Add yarn.lock to all examples
* Add missing yarn lock
* Deploy all examples after yarn.lock changes
* Remove package-lock
* Update ionic angular to working version
* Skip libCheck to make ionic-angular build
* Rename nowignore to vercelignore, remove yarn.lock from ignore
* Revert zola changes
Our automated documentation requires descriptions in the schema
#### Tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
We need to support `{ "source": "/", "has": { "type", "host", "value": "vercel.com" }, "destination": "/prod" }`
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
CH-19565
Since CRA is an SPA (all routes fallback to index.html), we can't do a proper custom 404.
But we can do a custom 404 when accessing the static directory, for example `/static/foo.html`.
To handle something like `/foo`, the user needs to do a client-side routing 404 like this example: https://reactrouter.com/web/example/no-match
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
x-ref: https://github.com/vercel/next.js/pull/22341
x-ref: https://github.com/vercel/next.js/issues/22345
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
This PR fixes an error that happens when `includeFiles` has `.ts` files:
```
ReferenceError: Cannot access 'tsCompile' before initialization
```
~~However its not clear what the expected behavior is. Should the `.ts` files be compiled to `.js` or should they be considered assets and included as-is?~~
We will assume that `includeFiles` is only for assets and thus `.ts` files should not be compiled, they're included as-is.
[ch20529]
* remove prefix from codeowners
* remove references from ignore files
* Remove prefix from package json and tests
* Add run js without prefixes
* Rename package folders
* Delete auto generated test files
* Remove now-node in integration test
* Put back deleted vercel json files
* Remove eol
* Add styfle suggestion to comment in utils/run.js
Co-authored-by: Steven <steven@ceriously.com>
We need to make CI explicit about the lowest common denominator for Go Version like we do with the Node.js Version.
This will add about 10 seconds to CI which is negligible to the 8 min+ CI currently.
A regression was introduced in #5873 that caused the analyze step to parse Go's internal source files (eg `golang/test/bombad.go`) instead of only parsing the user's source code (eg `api/users.go`).
This resulted in the error:
```
Failed to parse AST for "api/users.go"
Error: Command failed: /vercel/1ab928d537d26157/.build-utils/.builder/node_modules/@vercel/go/dist/analyze -modpath=/vercel/workpath1 /vercel/workpath1/api/users.go
2021/02/26 14:26:42 Could not parse Go file "/vercel/workpath1/.vercel/cache/golang/test/bombad.go"
```
Uses inspector url from api rather than generating one locally.
### 📋 Checklist
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
### Related Issues
Follow up to #5888
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
This PR updates the warning for `api` + `pages/api` to only be printed when Next.js is mixed with `@vercel/node` functions. It should not print the warning with `@vercel/go` functions for example.
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
`@babel/preset-env` shipped a change that broke Nuxt.js usage of the
module, so here we add a `yarn.lock` file that pins the preset-env
version to 7.12.17.
See: https://github.com/nuxt/nuxt.js/issues/8882
We now return a 504 for lambda timeouts
### Related Issues
Related to https://github.com/vercel/now-proxy/pull/1970
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
This PR removes the flags from `bundle install` which fixes the deprecated warnings such as
```
[DEPRECATED] The `--no-prune` flag is deprecated because it relies on being remembered across bundler invocations, which bundler will no longer do in future versions. Instead please use `bundle config set --local no_prune 'true'`, and stop using this flag
```
These flags already represent the defaults for `bundle install` anyway and we can pass environment variables in the spawn options instead.
https://app.clubhouse.io/vercel/story/16876
This will fix the issue that symlinks pointing to a directory is not returned on `prepareCache` and node modules linked to local files don't work.
### Related Issues
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Co-authored-by: Steven <steven@ceriously.com>
Animated gif should bypass (serve as-is).
This is to avoid the time it takes to optimize animated images which can sometimes take minutes.
It also matches how `next dev` works so we want to stay consistent (this tests both dev and a deployment).
Fixes TypeScript error:
```
test/unit.framework-detector.test.ts:52:40 - error TS4104: The type 'readonly Framework[]' is 'readonly' and cannot be assigned to the mutable type 'Framework[]'.
52 expect(await detectFramework({ fs, frameworkList })).toBe(null);
~~~~~~~~~~~~~
```
This PR improves the CLI in a way that if the API from any request returns a response which contains a header with the prefix `x-vercel-warning-*`, `x-vercel-notice-*` or `x-vercel-tip-*`, it will print out the message to the output to let the user know.
This new feature also supports additional headers which improve the message, so that a link can be printed out for more information. Those are `x-vercel-link-*`, where we specify a link, and `x-vercel-action`, where we specify the text before the link.
Here's an example for a warning message which warns the user if they add a DNS record for a domain which does not use Vercel Nameservers:
<img width="719" alt="Screenshot 2021-01-18 at 17 49 14" src="https://user-images.githubusercontent.com/35507539/104943788-8da12400-59b6-11eb-8e54-77a3c517e56d.png">
The API request from above which creates a DNS record has the following HTTP response headers set:
```
x-vercel-warning-create-domain-record: Your Domain isn't using Vercel nameservers. In order for the changes to your DNS Records to get applied, however, it needs to.
x-vercel-link-create-domain-record: https://vercel.link/configure-vercel-nameservers
```
If `x-vercel-action` is not specified, it defaults to `Learn More`.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
* [frameworks] Add type annotations
This will be necessary for static type analysis in our API docs generator.
* Apply suggestions from code review
Co-authored-by: Steven <steven@ceriously.com>
* Add quotes to @examples
Co-authored-by: Steven <steven@ceriously.com>
This will be necessary for static type analysis in our API docs generator.
The default export is still typed as `Framework[]` for backwards-compat purposes, but the `frameworks` export is the statically typed array.
This PR converts the `frameworks.json` file to TypeScript, and extends the values with the detection logic from `@vercel/static-build`, so that it's publicly editable. You also don't need to do the type casting downstream anymore.
As a consequence, it also makes Zola a 1st-class framework, as it was previously missing from the `frameworks.json` file, but present in the static-build frameworks. An example has been included based on their "Getting Started" tutorial.
CH-3808
CH-18771
### Related
Related to #4754
### Upstream
https://aws.amazon.com/blogs/compute/node-js-14-x-runtime-now-available-in-aws-lambda/
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Both `vc` and `vc dev` already ask to link/setup when the project is not found, so this will update the error message to mention the possible reasons why a project was not found.
### Before
```
$ vc
Vercel CLI 21.2.1
❗️ Your project was either removed from Vercel or you’re not a member of it anymore.
? Set up and deploy “~/Code/myproject”? [Y/n]
```
### After
```
$ vc
Vercel CLI 21.2.1
❗️ Your Project was either deleted, transferred to a new Team, or you don’t have access to it anymore.
? Set up and deploy “~/Code/myproject”? [Y/n]
```
### 📋 Checklist
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
There was an issue with `output.spinner()` spinner if the old-style
interface was used (invoking the return value to stop the spinner),
which caused the internal spinner instance in `output` to be defined,
but in a "stopped" state. Then later the `text` gets updated to a
different value but the spinner is still stopped and nothing gets
rendered.
The fix is to ensure that `output.stopSpinner()` is called rather
than directly invoking the cancel function. In fact, the return
value of `output.spinner()` has been removed completely.
`@vercel/python` has been incorrectly "unquoting" the incoming request
URL for all Python interfaces (basic, WSGI, ASGI). The proper behavior is
to pass along the request URL to the serverless function handler unmodified.
This is proven by the additional test that is added in this PR, which actually
fires up the corresponding Python server via i.e. `python3 api/asgi.py`,
and executes the test probes defined in the
`test/fixtures/00-request-path/vercel.json` file. Adding this test ensures
that the request URL behavior of `@vercel/python` matches the behavior
as compared to executing via `python` directly.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Previously every command implementation was invoking `createOutput()` individually, causing multiple instances of `Output` to be created, which was unnecessary, and causes issues with the shared `spinner` instance introduced by #5717.
Now, the `Output` instance created in `src/index.js` is passed down to the sub-command being executed and therefore re-used.
This is a refactor of the `ora` Spinner usage to make the preferred usage be via the `output.spinner()` and `output.stopSpinner()` functions.
* The `Output` instance has a local spinner instance that can be updated via multiple calls to `output.spinner()`.
* `output.print()` and friends call `output.stopSpinner()` implicitly, so `output.stopSpinner()` doesn't need to be called unless it is desired to immediately remove the spinner before rendering the next text.
* Because there's meant to be a shared `spinner` for the `output` instance, it means that the same `output` instance needs to be used throughout the CLI lifecycle. Therefore, the `createOutput()` function now returns a singleton so that it's guaranteed to be the same instance.
https://user-images.githubusercontent.com/71256/105009979-0670a200-59f0-11eb-9853-232f92eae536.movhttps://user-images.githubusercontent.com/71256/105010034-17211800-59f0-11eb-918d-b15f457e9640.mov
In the "before" video above, note how there's a brief second where the spinner is cleared, but the deployment URL has not yet been printed. In the "after" video, this is fixed and the spinner is only cleared once the CLI is ready to render the deployment URL.
This is essentially a refactor of the `@vercel/static` builder that
simplifies the code a lot and fixes a bug where `cleanUrls: true`
was not working correctly when using an `outputDirectory`.
Add auto renew prompt to `domains buy`
```diff
> The domain "example.com" is available to buy under <username>!
> Buy now for $20 (1yr)? [y|N]
+ > Auto renew yearly for $20? [Y|n]
```
### 📋 Checklist
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
Implements the ["Directory Listing" Project setting](https://vercel.com/changelog/listing-the-content-of-directories-can-now-be-toggled) in `vercel dev`.
The Dev integration test file has been updated to allow specifying custom Project settings that will be `PATCH`'d to the project document before running `vc deploy` / `vc dev`.
When `spawn()` emits an "ENOENT" error, meaning that the command was not
found, the error would only be visible if `--debug` was enabled for vc
dev.
Now we will always render any error from `startDevServer()`, as well as
special-case the "ENOENT" error informing the user to double check their
installation of the command.
These `@now` scoped packages have been published and deprecated with the following warning since May 2020:
```
DEPRECATED ⚠️ - "@now/node" is deprecated and will stop receiving updates on December 31, 2020. Please use "@vercel/node" instead.
```
Since it is now 2021, the time has come to stop publishing.
### Related Issues
[[ch3378]]
This adds tests for optional catch-all `fallback: true` pages to ensure the params are normalized correctly. These should be failing initially until the PR with the normalizing fix in Next.js is released to canary.
x-ref: https://github.com/vercel/next.js/issues/17220
This is a follow-up to https://github.com/vercel/vercel/pull/5618 ensuring the 404 route is pointing to the static 404 output correctly when `_app.gip` and getStaticProps in `/404.js` is used
### Related Issues
Fixes: https://github.com/vercel/next.js/issues/19849
#### Tests
- [ ] The code changed/added as part of this PR has been covered with tests
- [ ] All tests pass locally with `yarn test-unit`
#### Code Review
- [ ] This PR has a concise title and thorough description useful to a reviewer
- [ ] Issue from task tracker has a link to this PR
There are events (i.e. with `type: "deployment-event"`) that do not
contain a `text` property, so check that it's a string before invoking
`.replace()` on it.
Fixes this stack trace:
```
Error! An unexpected error occurred in logs: TypeError: Cannot read property 'replace' of undefined
at Object.printLogRaw [as raw] (/home/me/nextjs-site/node_modules/vercel/dist/index.js:203803:10)
at printEvent (/home/me/nextjs-site/node_modules/vercel/dist/index.js:203688:35)
at Array.forEach (<anonymous>)
at main (/home/me/nextjs-site/node_modules/vercel/dist/index.js:203690:31)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at main (/home/me/nextjs-site/node_modules/vercel/dist/index.js:207173:16)
```
The `Now` prefixed types remain as aliases for backwards-compat purposes.
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
Bumps [ini](https://github.com/isaacs/ini) from 1.3.5 to 1.3.7.
<details>
<summary>Commits</summary>
<ul>
<li><a href="c74c8af35f"><code>c74c8af</code></a> 1.3.7</li>
<li><a href="024b8b55ac"><code>024b8b5</code></a> update deps, add linting</li>
<li><a href="032fbaf5f0"><code>032fbaf</code></a> Use Object.create(null) to avoid default object property hazards</li>
<li><a href="2da90391ef"><code>2da9039</code></a> 1.3.6</li>
<li><a href="cfea636f53"><code>cfea636</code></a> better git push script, before publish instead of after</li>
<li><a href="56d2805e07"><code>56d2805</code></a> do not allow invalid hazardous string as section name</li>
<li>See full diff in <a href="https://github.com/isaacs/ini/compare/v1.3.5...v1.3.7">compare view</a></li>
</ul>
</details>
<details>
<summary>Maintainer changes</summary>
<p>This version was pushed to npm by <a href="https://www.npmjs.com/~isaacs">isaacs</a>, a new releaser for ini since your current version.</p>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/vercel/vercel/network/alerts).
</details>
This PR completes the routes schema to be more accurate for the provided type.
This will allow us to generate the type dynamically from the JSON Schema
* [routing-utils] Handle `null` phase at the beginning
* Add fixed list
* Add tests
* Change hit and miss order
* Put null at the start
* Undo order changes
Co-authored-by: Steven <steven@ceriously.com>
* fix VERCEL_REGION and NOW_REGION
* remove VERCEL_REGION from exposeSystemEnvs
* refactor exposeSystemEnvs
* refactor getDecryptedEnvRecords
* consider project envs in exposeSystemEnvs
* simplify exposeSystemEnvs
* correctly set value of VERCEL_URL system envs
* make exposeSystemEnvs return all envs object
* parse url in server
* simplify
* refactor getDecryptedEnvRecords
* add comment
* remove unnecessary code
* add test
* fix test
* fix dev server unit tests
* always expose NOW_REGION
* fix dev test
* fix dev test
* only retrieve system env values when autoExposeSystemEnvs is true
Ref: https://app.clubhouse.io/vercel/story/15112
We added a property called `autoExposeSystemEnvs` to projects. If that property is `true`, we automatically expose system env variables such as `VERCEL=1`, `VERCEL_ENV=<production | preview>`, ... to the runtime and build time.
This PR makes sure we mirror this behavior when running `vc dev` locally.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
Add E2E test for to test image optimization against `vc dev` as well as a prod deployment.
### 📋 Checklist
<!--
Please keep your PR as a Draft until the checklist is complete
-->
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR (CH13104)
`/.well-known` files shouldn't have trailing slashes added as these clients likely do not follow redirects
Specifically, `/.well-known/apple-developer-merchantid-domain-association` cannot have trailing slash.
### Related Issues
https://vercel.slack.com/archives/CLDDX2Y0G/p1605127589058800
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR
If a builder wants to set a header that isn't allowed to be overridden by users, it should use `important: true`
#### Tests
- [x] The code changed/added as part of this PR has been covered with tests
- [x] All tests pass locally with `yarn test-unit`
#### Code Review
- [x] This PR has a concise title and thorough description useful to a reviewer
- [x] Issue from task tracker has a link to this PR: CH-14921
* [build-utils] Include `installCommand` when empty string
An empty string for the Project's `installCommand` setting has different
behavior than `null`, so properly provide the empty string to the
Runtime.
* Move tests to proper section
* [@vercel/static-build] Add directory for Serverless Functions
* Update tests and only consider index.js files
* Import only once
* Only change for zeroConfig
* Update packages/now-static-build/src/utils/_shared.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/now-static-build/test/fixtures/62-function-output-directory-with-static/now.json
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/now-static-build/test/fixtures/61-function-output-directory/now.json
Co-authored-by: Steven <steven@ceriously.com>
* Update build
* Fix type
* Remove line
* Add to .vercelignore
* Fix paths in test
* Move more files
* Remove special case for test
Co-authored-by: Steven <steven@ceriously.com>
* prompt to select env type
* improve copy
* create env variable with type
* remove nanoid dependency
* use encodeURIComponent
* refactor envType -> type
* refactor envName -> key
* do not hide value input
* adjust value prompt depending on type
* handle std input for plaintext env variables
* show custom error when secret is not found
* handle secret name input starting with `@`
* fix system env value question
* improve ui of prompts
* expand env list in vc rm
* adjust tests
* environment -> environments
* list multiple targets in vc env ls
* show value for system env vars
* adjust tests
* capitalize targets
* add <type> to arguments
* always use stdInput for envValue
* fix number of arguments error
* adjust tests
* refactor ProjectEnvType
* refactor SYSTEM_ENV_VALUES
* fix typo for typePlaceholder
* use getCommandName
* use title
* remove @ts-ignore
* improve types
* show key controls for checkbox prompt
* fix plain envs can not be retrieved
* add test
* add test for `vc dev`
* use v6 to retrieve env variables
* fix v6 return type
* use v6 to display env vars
* add test for vc env ls
* expand env vars with multiple targets
* minor type fixes
* always use v6 for getEnvVariables
Co-authored-by: luc <luc.leray@gmail.com>
We currently pass through `images` whenever its defined, but this is enabling Image Optimization in the Proxy for every Next.js project.
Instead, we should check to see if the default loader is used (the same use for `next dev`) as a signal to enable this feature in the deployment.
Related to https://github.com/vercel/next.js/issues/18122
Bumps [next](https://github.com/vercel/next.js) from 9.5.1 to 9.5.4.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/vercel/next.js/releases">next's releases</a>.</em></p>
<blockquote>
<h2>v9.5.4</h2>
<p><strong>This upgrade is <em>completely backwards compatible and recommended for all users on versions below 9.5.4.</em> For future security related communications of our OSS projects, please <a href="https://vercel.com/security">join this mailing list</a>.</strong></p>
<p>A security team from one of our partners noticed an issue in Next.js that allowed for open redirects to occur.</p>
<p>Specially encoded paths could be used with the trailing slash redirect to allow an open redirect to occur to an external site.</p>
<p>In general, this redirect does not directly harm users although can allow for phishing attacks by redirecting to an attackers domain from a trusted domain.</p>
<p>We recommend upgrading to the latest version of Next.js to improve the overall security of your application.</p>
<h2>How to Upgrade</h2>
<ul>
<li>We have released patch versions for both the stable and canary channels of Next.js.</li>
<li>To upgrade run <code>npm install next@latest --save</code></li>
</ul>
<h2>Impact</h2>
<ul>
<li><strong>Affected</strong>: Users of Next.js between 9.5.0 and 9.5.3</li>
<li><strong>Not affected</strong>: Deployments on Vercel (<a href="https://vercel.com">https://vercel.com</a>) are not affected</li>
<li><strong>Not affected</strong>: Deployments using <code>next export</code></li>
</ul>
<p>We recommend everyone to upgrade regardless of whether you can reproduce the issue or not.</p>
<h3>How to Assess Impact</h3>
<p>If you think users could have been affected, you can filter logs of affected sites by <code>%2F</code> with a 308 response.</p>
<h2>What is Being Done</h2>
<p>As Next.js has grown in popularity, it has received the attention of security teams and auditors. We are thankful to those that reached out for their investigation and discovery of the original bug and subsequent responsible disclosure.</p>
<p>We've landed a patch that ensures encoding is handled properly for these types of redirects so the open redirect can no longer occur.</p>
<p>Regression tests for this attack were added to the <a href="https://github.com/vercel/next.js/blob/canary/test/integration/production/test/security.js">security</a> integration test suite.</p>
<ul>
<li>We have notified known Next.js users in advance of this publication.</li>
<li>A public CVE was released.</li>
<li>If you want to stay on top of our security related news impacting Next.js or other Vercel projects, please <a href="https://zeit.co/security">join this mailing list</a>.</li>
<li>We encourage responsible disclosure of future issues. Please email us at <strong><a href="https://github.com/vercel/next.js/blob/HEAD/mailto:security@zeit.co">security@vercel.com</a>.</strong> We are actively monitoring this mailbox.</li>
</ul>
<hr />
<h3>Core Changes</h3>
<ul>
<li>Make the image post-processor ignore SVG images: <a href="https://github-redirect.dependabot.com/vercel/next.js/issues/16732">#16732</a></li>
<li>Only update lookups for dev overlay if mounted: <a href="https://github-redirect.dependabot.com/vercel/next.js/issues/16776">#16776</a></li>
<li>Ensure interpolating dynamic href values works correctly: <a href="https://github-redirect.dependabot.com/vercel/next.js/issues/16774">#16774</a></li>
<li>Add automatic reloading when editing GS(S)P methods: <a href="https://github-redirect.dependabot.com/vercel/next.js/issues/16744">#16744</a></li>
<li>Update to show build indicator while re-fetching GS(S)P data in dev: <a href="https://github-redirect.dependabot.com/vercel/next.js/issues/16789">#16789</a></li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="6588108150"><code>6588108</code></a> v9.5.4</li>
<li><a href="7108567b06"><code>7108567</code></a> v9.5.4-canary.25</li>
<li><a href="5d79a8c0c4"><code>5d79a8c</code></a> Update workflow step to restore cache (<a href="https://github-redirect.dependabot.com/vercel/next.js/issues/17656">#17656</a>)</li>
<li><a href="4c38e3ed8e"><code>4c38e3e</code></a> fix typo (<a href="https://github-redirect.dependabot.com/vercel/next.js/issues/17653">#17653</a>)</li>
<li><a href="241f38eaa8"><code>241f38e</code></a> v9.5.4-canary.24</li>
<li><a href="7dec91175c"><code>7dec911</code></a> change anonymous functions to named in docs examples (<a href="https://github-redirect.dependabot.com/vercel/next.js/issues/17510">#17510</a>)</li>
<li><a href="1659e4da61"><code>1659e4d</code></a> Update migrating from Gatsby docs. (<a href="https://github-redirect.dependabot.com/vercel/next.js/issues/17636">#17636</a>)</li>
<li><a href="06a8b1ad67"><code>06a8b1a</code></a> Add docs on how to migrate from Gatsby. (<a href="https://github-redirect.dependabot.com/vercel/next.js/issues/17491">#17491</a>)</li>
<li><a href="04234cc312"><code>04234cc</code></a> Update to use hasNextSupport for custom-routes in next export check (<a href="https://github-redirect.dependabot.com/vercel/next.js/issues/17630">#17630</a>)</li>
<li><a href="742f5d9a46"><code>742f5d9</code></a> test(create-next-app): increase coverage (<a href="https://github-redirect.dependabot.com/vercel/next.js/issues/17507">#17507</a>)</li>
<li>Additional commits viewable in <a href="https://github.com/vercel/next.js/compare/v9.5.1...v9.5.4">compare view</a></li>
</ul>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/configuring-github-dependabot-security-updates)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/vercel/vercel/network/alerts).
</details>
In some rare cases, the progress bar will still be in progress when the deployment completes, which causes the "Inspect" URL to print on the same line as the progress bar instead of a new line.
This PR fixes that corner case.
We don't support routing path aliases anymore, now that we've completely shut down the ZEIT Now 1.0 infrastructure. This PR removes path alias rules from Vercel CLI.
There was a regression when introducing multiple phases such as `hit` and `miss` which caused `routes` to stop working because the transition from `null` phase to the `filesystem` phase resets any dest rewrites.
The workaround is to detect when we don't have a `filesystem` phase and exit early.
Follow up to #5158 to add longer delay.
There is an issue with npm consistency after publishing so we wait longer before deprecating the `now` package because its a little larger than the others.
We have started migrating our projects to use Vue CLI with the Vercel zero-config builders. One particularly bug we ran into was due to the `Cache-Control` headers automatically applied on these resources that [differ from the documentation](https://vercel.com/docs/edge-network/caching#static-files):
> By default we return a `Cache-Control` header containing `public, max-age=0, must-revalidate` to prevent clients (e.g. browsers) from caching the file locally.
Instead of these headers, we were seeing `immutable` on all our resources. This is a good assumption for a vanilla Vue CLI setup because by default a content hash is used on every chunk, even the entry, which will change as soon as the file contents change. However, this may not always be the case, particularly on Vue CLI projects with any modifications to the build process, custom plugins, etc. that may exclude one or more files from the hash.
In our case this was breaking things in dramatic ways every time we deployed (and we deploy quite often!). Since the resources were being sent with the `immutable` header, the client browser was persisting these in cache and subsequent deployments with potentially breaking changes caused errors that were only resolved by clearing the client browser cache.
Example:
```
dist
├── css
│ ├── app.db598b39.css
│ └── common.css
├── js
│ ├── app.ac201ece.js
│ ├── chunk-587c608b.7d4361a1.js
│ ├── chunk-vendors.00676d62.js
│ └── common.js
└── index.html
```
In the above example, `common.css` and `common.js` are not hashed, but still have an `immutable` header preventing them from being re-validated by the client browser when a new deployment modifies their content.
To solve for this, I've updated the RegExp for Vue CLI to only apply the `immutable` caching header on files which have a content hash. This should solve for both vanilla Vue CLI setups and more advanced ones in which there may exist both files with and without a content hash.
Co-authored-by: Steven <steven@ceriously.com>
This PR solves an issue where tests would sometimes be rate limited when generating a token. This can be solved by caching the token like we do for E2E tests.
Example failure: https://github.com/vercel/vercel/runs/1098030228#step:11:9376
I also update the `@vercel/node` tests to compare the error message, exactly like how we do it with `@vercel/static-build`.
TypeScript supports comments in the `tsconfig.json` file, which is not
compatible with `JSON.parse()` so we have to use the built-in function
to parse the config file.
Fixes#4835.
Bumps [node-fetch](https://github.com/bitinn/node-fetch) from 2.6.0 to 2.6.1.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/bitinn/node-fetch/releases">node-fetch's releases</a>.</em></p>
<blockquote>
<h2>v2.6.1</h2>
<p><strong>This is an important security release. It is strongly recommended to update as soon as possible.</strong></p>
<p>See <a href="https://github.com/node-fetch/node-fetch/blob/master/docs/CHANGELOG.md#v261">CHANGELOG</a> for details.</p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a href="https://github.com/node-fetch/node-fetch/blob/master/docs/CHANGELOG.md">node-fetch's changelog</a>.</em></p>
<blockquote>
<h2>v2.6.1</h2>
<p><strong>This is an important security release. It is strongly recommended to update as soon as possible.</strong></p>
<ul>
<li>Fix: honor the <code>size</code> option after following a redirect.</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="b5e2e41b2b"><code>b5e2e41</code></a> update version number</li>
<li><a href="2358a6c256"><code>2358a6c</code></a> Honor the <code>size</code> option after following a redirect and revert data uri support</li>
<li><a href="8c197f8982"><code>8c197f8</code></a> docs: Fix typos and grammatical errors in README.md (<a href="https://github-redirect.dependabot.com/bitinn/node-fetch/issues/686">#686</a>)</li>
<li><a href="1e99050f94"><code>1e99050</code></a> fix: Change error message thrown with redirect mode set to error (<a href="https://github-redirect.dependabot.com/bitinn/node-fetch/issues/653">#653</a>)</li>
<li><a href="244e6f63d4"><code>244e6f6</code></a> docs: Show backers in README</li>
<li><a href="6a5d192034"><code>6a5d192</code></a> fix: Properly parse meta tag when parameters are reversed (<a href="https://github-redirect.dependabot.com/bitinn/node-fetch/issues/682">#682</a>)</li>
<li><a href="47a24a03eb"><code>47a24a0</code></a> chore: Add opencollective badge</li>
<li><a href="7b136627c5"><code>7b13662</code></a> chore: Add funding link</li>
<li><a href="5535c2ed47"><code>5535c2e</code></a> fix: Check for global.fetch before binding it (<a href="https://github-redirect.dependabot.com/bitinn/node-fetch/issues/674">#674</a>)</li>
<li><a href="1d5778ad0d"><code>1d5778a</code></a> docs: Add Discord badge</li>
<li>Additional commits viewable in <a href="https://github.com/bitinn/node-fetch/compare/v2.6.0...v2.6.1">compare view</a></li>
</ul>
</details>
<details>
<summary>Maintainer changes</summary>
<p>This version was pushed to npm by <a href="https://www.npmjs.com/~akepinski">akepinski</a>, a new releaser for node-fetch since your current version.</p>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/configuring-github-dependabot-security-updates)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/vercel/vercel/network/alerts).
</details>
The [functions](https://vercel.com/docs/configuration#project/functions) property matches source files and it wasn't working for `index.js` or `.ts` files because `next build` converts the source file `pages/api/index.js` to the output `.next/server/pages/api.js`. So this PR fixes the logic to reverse the output page to source file.
This PR is a follow up to #5157 which was unable to deprecate a package immediately after publishing and failed with E405. So this PR adds a delay between publish and deprecate. It also uses the `-f` flag suggested in the error message. https://github.com/vercel/vercel/runs/1076007594#step:6:649
This PR is a follow up to #5119 which had the names backwards.
I fixed the variable names to avoid the confusion since "new" and "old" were ambiguous.
I also removed the incorrect deprecation message from packages published during commit c9597dc199.
We deprecated all the `now` scoped packages in favor of the `vercel` equivalents, however the deprecation message disappears after each publish, so we must to run `npm deprecate` after `npm publish` for legacy packages.
Currently on my machine, vercel --version takes 850ms to run. With this change, that execution time is reduced to ~550ms.
The reason is that source maps seem to significantly slow down Node.js execution, compounded by the size of the source map, even if it is not used.
I believe the benefits of this perf improvement outweigh the direct source maps and minification benefits.
If it is felt that direct per-file source maps are necessary for internal errors, then reducing the source map size should be investigated further to improve the runtime performance here.
This PR updates the `README.md` files with the following changes:
- Removal of CLI deployment.
- Amends Blitz.js to be in line with other `README.md` formats.
* Revert "[build-utils] Use `handle: error` for api 404 (#5064)"
This reverts commit 02e1c921ac.
* Re-enable cli changes
* Re-enable redwood changes
* Minor cleanup
Since released PR #5009, we had some users that depend on the broken behavior. This adds an arbitrary date so that old projects will use the old broken behavior, and new projects will use the new behavior from #5009.
The reason for the date is that we don't want to force users to create new projects who noticed this broken behavior months ago like this discussion: https://github.com/vercel/vercel/discussions/4138
Its better to be a bit aggressive and set the date far back because users with that want the old behavior have a workaround: select Next.js in the framework dropdown. However, users that want the new behavior with an old project will be stuck without a solution.
This PR does a few things:
- Consolidates build-utils to use both 404 routes in `handle: error` phase
- Fixes `vc dev` to process `handle: error` phase after the `handle: filesystem` phase
- Updates `/api` 404 route to be excluded for frameworks like RedwoodJS which use their own functions
The deployment API might return a learn more link to address warnings, tips, or notices
CH-568
```
HTTP/2 200
...
x-vercel-warning-bad-error: Something went wrong
x-vercel-link-bad-error: https://vercel.link/bad-error
x-vercel-notice-low-funds: You are low on funds
x-vercel-link-low-funds: https://vercel.link/increase-funds
...
```
Should output as:
```
Warning: Something went wrong
Learn More: https://vercel.link/bad-error
Notice: You are low on funds
Learn More: https://vercel.link/increase-funds
```
This pull request adds a method redirect, the behavior will be the same as that of Next.js with `pages/api`. This PR takes into account the change that is being made in Next.js with redirect due to the [error that was reported](https://github.com/vercel/next.js/issues/15594) a few hours ago.
Co-authored-by: Steven <steven@ceriously.com>
This corrects behavior that was changed when switching to use `safelyCompile` which caused some `path-to-regexp` replacing behavior to be changed like not removing brackets `{}` around params which are removed in Next.js. This updates to first attempt to use the normal replacing behavior from `path-to-regexp` falling back to the safe compiling logic added when that fails.
Additional tests have been added to ensure the brackets are stripped as expected when compiling with `path-to-regexp`
The update message was sometimes printed when there was no update.
This PR fixes the update check to ensure the that it is only printed when the latest version differs from the current version.
This fixes the case where `trailingSlash: true` is used with `next export` causing the `404` page to be output as `404/index.html` and we were previously only checking for the 404 output at `404`. This also adds a regression test for this behavior.
Closes: https://github.com/vercel/next.js/issues/16218
The CLI doesn't depend on `@vercel/redwood` for `vc dev` since PR #5036 so we can remove it.
Similarly, zero config does not install `@vercel/next` or `@vercel/static-build` during `vc dev` so these can be removed too.
In the case where the user defines `builds` in vercel.json, the runtimes will be installed during the first run of `vc dev`.
This updates to not automatically append params to the query for rewrites if one or more of the params are already used in the destination's path. No other behavior is being changed and if the user still wants the params in the query after using them in the destination's path they can manually add them like with redirects.
x-ref: https://github.com/vercel/next.js/pull/16189
This PR uses the the new property added in PR #5034 to determine if a framework has a frontend runtime defined.
It also reverts a couple workarounds add in PR #4937 which was added for RedwoodJS which is no longer necessary since RedwoodJS defines a frontend framework the same way Next.js does.
This PR adds two properties to `frameworks.json`:
1. `useRuntime` - this moves the special case for non `@vercel/static-build` frontends, so that any framework can do the same as Next.js and RedwoodJS
2. `ignoreRuntimes` - this allows a framework to opt out of api detection such as RedwoodJS which handle's its own `.js` extensions
This also fixes 2 bugs discovered during implementing the feature:
1. `test-unit.yml` was not testing Node 12, it was testing 10 for both runs
2. `sortFilesBySegmentCount()` was non-deterministic causing node 10 and 12 to sort differently
This PR updates the default build command per @thedavidprice
It also uses `@vercel/frameworks` as a source of truth for the build command.
If the user has a `build` script in `package.json`, that will take precedence over the default.
Some files require execution privileges, such as Prisma, so we must preserve the file mode.
We also want redwood to behave the same as other frameworks and use `yarn build` if available.
CH Story:
https://app.clubhouse.io/vercel/story/5291/cli-connection-pooling
(Mac) script for watching count of active connections to API:
`watch -n 0.1 'netstat -a -n | grep -E \'(13.52.46.156|52.9.164.177)\' | wc -l'`
Limiting the active connections to 50 greatly decreased the amount of active connections but did not noticeably increase the time to upload files.
For each semaphore size below, I tested uploading 200 files of random size (between 50kb and 100kb) 5 times. More tests on varying file sizes / amounts showed similar results.
Results:
```
Size: Average time in ms
50 : 25740 ms
700 : 28763 ms
10 : 29339 ms
```
I also moved the the agent creation outside of the forEach loop when uploading. This is functionally the same (as node would use the same socket for the same hostname) but makes it easier to access the agent object if we need to debug in the future, and it seems unnecessary to create a new object each call.
This fixes the scenario where 1) is Windows and 2) there is no
`.gitignore` file in the project, so `vc link` creates one. Before, it was
defaulting to `\n`. Updated to use `os.EOL` so that `\r\n` is used on
Windows.
Also removed `encoding` option to `writeFile()` since `utf8` is already the
default.
Related to #4965.
We don't need to report these errors to Sentry because the user attempted a command that requires them to login.
https://sentry.io/organizations/vercel/issues/1498276418/?project=1323225
This will print:
- `NOT_AUTHORIZED`: "The specified token is not valid. Use vc login to generate a new token."
- `TEAM_DELETED`: "Your team was deleted. You can switch to a different one using vc switch"
### Related
- Related to #4082
- Related to #3857
* [cli] Adjust output for recently changed domain commands
* Update the inspect and list page
* Remove test
* Update packages/now-cli/src/commands/domains/inspect.ts
Co-authored-by: Steven <steven@ceriously.com>
* Change output
* Remove workaround
* Update error
* Include contextName
Co-authored-by: Steven <steven@ceriously.com>
This makes sure the routes mapping to the serverless functions handle the trailing slash being present or not. This also adds additional test cases to ensure it is functioning correctly
This adds handling for more cases while updating header values to make sure to escape any characters that could break compiling with `path-to-regexp`
x-ref: https://github.com/vercel/next.js/pull/15592
This makes sure we detect a fully static `/index` page correctly since the `prerender-manifest` lists it as `/` and we were expecting `/index` during the lambda building opt-out check
x-ref: https://github.com/vercel/next.js/discussions/15619
This PR fixes a bug when running `vercel link` command in a directory with `vercel.json` that contains `builds` property. The problem is that framework auto-detection doesn't run when `builds` is used, only for zero config. So we skip the API and instead create the project without auto-detection during `vc link`.
This updates our Next.js test fixtures to run against canary.
It looks like the mono-repo fixtures will need to be updated to run against canary separately since there may be a conflict with legacy routes and the trailing slash redirect
* [client] Export `buildFileTree()` and return the ignore list
The ignore list from this function will be used in production to
render a warning if there are files listed in the `.vercelignore` file
that are being comitted to the project's git repo.
* Tests for `ignoreList`
* Update packages/now-client/src/utils/index.ts
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Steven <steven@ceriously.com>
Previously, the zero detection would see js files in the `/api` directory and attempt to use `@vercel/node`. However, this doesn't work with RedwoodJS which uses a different format for [`/api`](https://github.com/vercel/vercel/tree/master/examples/redwoodjs/api) so we must only use `@vercel/redwood` when RedwoodJS is detected.
## Problem
`api-frameworks` is not being cached by our edge when used via the fallback-to-front mechanism. That's because the headers are only applied to `/api/frameworks` but not `/api/v1/frameworks` which is the actual path being used.
## Solution
Also apply the caching headers to `/api/<version>/frameworks`
* [now-cli] Change `now domains add` workflow to match dashboard
* Fix error throwing and add --force
* Remove `now domains verify`
* Count projects when removing a domain
* Include projects for `now inspect`
* Updated `now domains ls`
* Fix `now domains ls`
* Use Finally
* Add tests
* Use --force for domain tests
* Adjust tests
* Adjust test and fix output
* Fix padding
* Adjust more tests
* Ensure the project exists
* Log the deployment
* Fix tests again
* Remove project after test
* Fix command
* Fix test
* Change user after a couple of tests
* Add check
* Use random name for domain
* More logging
* Add more logging
* Remove logging
* Remove .now/project.json every time
* Skip test
* Add test to change user
* More logging
* Use now login
* Remove duplicated test
* Consider linked project for `domains add`
* Fix linting
* Remove unused docs
* Undo changes
* Undo more changes
* Fix typo
* Do not sort projects when there is only one record
* Fix loop
* Deploy with `-V 2`
* Remove verification
* Remove outdated link
* Update packages/now-cli/src/commands/domains/add.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/now-cli/src/commands/domains/add.ts
Co-authored-by: Steven <steven@ceriously.com>
* Use utils for public suffix and service type
* Update packages/now-cli/src/commands/domains/ls.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/now-cli/src/commands/domains/add.ts
Co-authored-by: Steven <steven@ceriously.com>
* Change link
* Undo test changes
* Fix type issues
* Update packages/now-cli/src/commands/domains/add.ts
Co-authored-by: Steven <steven@ceriously.com>
* Use domain config to print info
* Check apex domain when removing a domain
* Remove psl
* List projects when removing a domain
* Do not list projects
* Change user earlier
* Update packages/now-cli/src/commands/domains/inspect.ts
Co-authored-by: Steven <steven@ceriously.com>
* Apply suggestions from code review
Co-authored-by: Steven <steven@ceriously.com>
* Apply suggestions from code review
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Mark Glagola <mark.glagola@gmail.com>
Co-authored-by: Steven <steven@ceriously.com>
Follow up to #4897
* `vc link` - Update message to say `Set up ~/proj`
* `vc dev` - Update message to say `Set up and develop ~/proj`
* `vc link --help` - Updated example message to include `vc link ~/proj` usage
When pages are fully static and don't leverage preview mode or revalidation we can skip tracing the pages for generating the lambdas since lambdas aren't needed in this case
* [build-utils] Make `runPackageJsonScript()` run the `vercel-` or `now-` if defined in `package.json`
* [build-utils] Export `getScriptName()`
* [next] Use `getScriptName()` and `remove()`
* [node] Update for `vercel-`
* [static-build] Update for `vercel-`
* Remove debug
* Add `getScriptName()` unit tests
* Test for `vercel-build` in e2e
* Make platform name behavior be opt-in
So that it's not a breaking behavior change.
* Check for only "vercel-build" or "now-build", but not "build"
* Simplify `getScriptName()` to return the first existing script in a possible set
* Revert change
* Fix test
Co-authored-by: Joe Haddad <joe.haddad@zeit.co>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Bumps [codecov](https://github.com/codecov/codecov-node) from 3.6.5 to 3.7.1.
<details>
<summary>Commits</summary>
<ul>
<li><a href="29dd5b6b03"><code>29dd5b6</code></a> 3.7.1</li>
<li><a href="c0711c6566"><code>c0711c6</code></a> Switch from execSync to execFileSync (<a href="https://github-redirect.dependabot.com/codecov/codecov-node/issues/180">#180</a>)</li>
<li><a href="5f6cc62d4f"><code>5f6cc62</code></a> Bump lodash from 4.17.15 to 4.17.19 (<a href="https://github-redirect.dependabot.com/codecov/codecov-node/issues/183">#183</a>)</li>
<li><a href="0c4d7f3c6f"><code>0c4d7f3</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/codecov/codecov-node/issues/182">#182</a> from codecov/update-readme-badges</li>
<li><a href="cc5e121842"><code>cc5e121</code></a> Update depstat image and urls</li>
<li><a href="b44b44e1f8"><code>b44b44e</code></a> Update readme with 400 error info (<a href="https://github-redirect.dependabot.com/codecov/codecov-node/issues/181">#181</a>)</li>
<li><a href="bb79335719"><code>bb79335</code></a> V3.7.0 (<a href="https://github-redirect.dependabot.com/codecov/codecov-node/issues/179">#179</a>)</li>
<li><a href="0d7b9b01cb"><code>0d7b9b0</code></a> Remove <code>'x-amz-acl': 'public-read'</code> header (<a href="https://github-redirect.dependabot.com/codecov/codecov-node/issues/178">#178</a>)</li>
<li><a href="eeff4e1953"><code>eeff4e1</code></a> Bump acorn from 5.7.3 to 5.7.4 (<a href="https://github-redirect.dependabot.com/codecov/codecov-node/issues/174">#174</a>)</li>
<li><a href="eb8a527470"><code>eb8a527</code></a> Merge pull request <a href="https://github-redirect.dependabot.com/codecov/codecov-node/issues/172">#172</a> from RoboCafaz/bugfix/codebuild-pr-parser</li>
<li>Additional commits viewable in <a href="https://github.com/codecov/codecov-node/compare/v3.6.5...v3.7.1">compare view</a></li>
</ul>
</details>
<br />
[](https://help.github.com/articles/configuring-automated-security-fixes)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/vercel/vercel/network/alerts).
</details>
Previously, users would have to run `vc env pull` to fetch cloud environment
variables into `.env`. After this PR, if no `.env` or `.build.env` file is present,
environment variables will be pulled by `vc dev` from your Vercel Environment
Variables settings, no file necessary.
This makes the updating logic be asynchronous instead of synchronous, and as such will make boot-up of CLI be faster.
The actual update notification display is identical to previous, we are not using `update-notifier`'s default boxen rendering.
Now that `@vercel/static-build` is being symlinked to CLI due to the
yarn workspace, `vc dev` will always use the latest code for
zero-config, so this "npm pack" logic is no longer necessary.
The `vercel.json` also no longer gets created in this test so that
zero-config is used.
Ensures that `VERCEL_REGION` is set for API calls when the runtime
implements `startDevServer()`.
Also adds `VERCEL_URL` which was previously not defined.
The Vercel proxy request headers (`x-vercel-deployment-url` for example)
were not being sent to the dev server when the Runtime defines
`startDevServer()`. This is now fixed.
Also updates the header names to match production:
- `now` -> `vercel`
- 'x-now-trace', 'x-now-id', and 'x-now-log-id' are removed
Fixes#4729.
CH-3242
When a user has project configuration in `.vercel` that corresponds to a team that they are not a part of, we currently throw a 403 error. This adds special handling so that we can show a specific message when this happens.
I didn't want to update the return type of `getProjectByIdOrName` because we only want to handle this 403 in a special case, so I `throw` it instead.
Other changes are linter.
This is for `@vercel/go` to work on Windows, which currently fails with
this error:
```
panic: write pipe: The handle is invalid.
goroutine 1 [running]:
main.main()
C:/Users/Nathan/Code/casca/vercel-go-test/.vercel/cache/go/2flefmhra8o/api/vercel-dev-server-main.go:25 +0x1ec
exit status 2
```
So this fallback writes the port number to a temp file that
`startDevServer()` polls for in order to figure out the port number.
This PR adds an optional property called `sort` to each framework so that we can change the order returned in the API.
The reason this is necessary is because the order of the original array determines the precedence of framework detection. So we need another way to indicate the order of templates/examples returned from the API.
In particular, we need "Next.js" to be first and "Other" to be last.
I also updated the deprecated `@now/node` usage to `@vercel/node` in the API.
* [@vercel/build-utils] Improve Nuxt build
Need review from @pi0 and @danielroe
* Update packages/now-static-build/src/frameworks.ts
Co-authored-by: Daniel Roe <daniel@roe.dev>
Co-authored-by: Daniel Roe <daniel@roe.dev>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
This fixes dynamic routes missing inside of shared lambdas for non-revalidate pages that leverage preview mode which causes them to not be able to render. Additional tests have also been added to ensure preview mode is working properly
This adds failing page names to our tests which should be resolved once the correct regexes is being generated for the routes-manifest in Next.js
Co-authored-by: Joe Haddad <joe.haddad@zeit.co>
Co-authored-by: Steven <steven@ceriously.com>
When a user performs an action such as trying to add a domain they don't own, the API returns a 400-499 response code.
Previously, we would save this error in Sentry but this PR changes the behavior so that the error is printed locally for the user but not saved in Sentry.
This reverts commit f11eb32b2c.
Reverts PR #4816
This PR adds back the Blitz.js demo now that we confirmed the example works and is deployed to the correct account.
This is a re-introduction of #4697, which was reverted for performance
resons. But now that #4760 and #4793 have landed, we can enable this
behavior again.
The first version of `routeKeys` which was Array based could contain invalid named regexes which would break the build during route validation so this disables using them in that version of the manifest instead of trying to leverage them still. It also adds an additional test fixture with this version of the manifest to ensure it is still working properly
This adds [Blitz.js](https://github.com/blitz-js/blitz) to the zero-config frameworks.
Blitz compiles to a Next.js app, so it uses the same `@vercel/next` builder.
The change in `packages/now-build-utils/src/detect-builders.ts` was made according to @styfle's suggestion in Slack.
---
**This is a rerun of #4219 which had to be reverted because of this:**
> It looks like the @vercel/next package still requires next in the dependencies.
>
> When I've deployed the example I've got only a file listing, but when I added next to the dependencies it worked. I'll revert for now.
This new PR fixes that problem with a small refactor to `@vercel/next`.
`@vercel/next` was getting the Next version two different ways:
1. By checking project root package.json for `next` in deps or devDeps
2. By trying to resolve the installed next version and get `version` from its package.json
My refactor consolidates those two approaches by changing the existing `getNextVersion()` function to first try and resolve the real next version. If that fails, fall back to checking the project root.
Blitz bundles Next, so the real next package version should always be resolved.
The current code uses `getAllProjectFiles()` which globs for every file
in the project, not considering the `.vercelignore` file and default
ignore list. For example, every file in the `node_modules` directory is
selected, just for `vercel dev` to manually ignore them afterwards,
which is very slow and wasteful. For a simple Next.js project, this
globbing was taking over 3 seconds on my machine 🤯!
Solution is to use the `staticFiles()` function which is the same as
`vercel dev` uses at boot-up time. This function properly considers the
ignore list and thus is much faster, and the manual filtering is no
longer necessary by `vercel dev`. For the same simple Next.js project,
this function takes on average 10 milliseconds.
Also did a bit of cleanup and removed the `getAllProjectFiles()`
function since it is no longer used anywhere.
For `getServerSideProps` routes the non-named data route was being used for routes causing dynamic route params that were being trusted from the proxy to be incorrect. Our tests weren't failing after trusting the values from the proxy was landed in Next.js on canary due to the `21-server-props` test suite not running against the latest canary which is updated in this PR.
Note: the below Next.js PR is not needed or can be reverted if this PR is landed
x-ref: https://github.com/vercel/next.js/pull/14829
* [cli] Reduce number of times `getNowConfig()` is invoked in `vercel dev`
When using the `vercel dev` command, the `getNowConfig()` function was
being invoked many times per HTTP-request. It should only be read _once_
per HTTP request as it may be an expensive function depending on the
project size.
This change reduces the number of times the function is called to once
per HTTP request, and passes around the resulting `nowConfig` object to
the functions that require it.
* Fix default values
* Remove unnecessary type narrowing
* Remove one more `getNowConfig()` invocation
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This adds the Lockfile from Gatsby's official starter to fix deployments.
```
❯ npx gatsby-cli new ~/Desktop/scratch/test-default
❯ cp ~/Desktop/scratch/test-default/yarn.lock examples/gatsby
❯ cd examples/gatsby
❯ yarn
❯ git add examples/gatsby/yarn.lock
```
This fixes mapping dynamic routes to their shared lambdas failing from the `dynamicPageLambdaRoute` not being injected directly after the dynamic route due to dynamic routes now containing a `query` which caused the route lookup to fail.
This is resolved by making sure to parse the pathname while injecting the `dynamicPageLambdaRoute` so the route can be looked up correctly. This also adds additional test cases to prevent regressing on this along with updating existing fixtures for custom routes being de-experimentalized
This reverts commit ffb98781f1 (#4697),
because it was realized that `vc dev` reads this configuration file many
times per HTTP request, causing the server to feel extremely slow.
Reverting this optimization for now until the over-reading issue is
addressed.
This PR improves the error handling when a zero config framework has an unexpected output directory.
Previously, setting a Docusaurus 2.0 build command to `docusaurus build && mv build foo` would fail with the following:
```
Error: ENOENT: no such file or directory, scandir '/vercel/514ce14b/build'
```
With this PR, the error message will show the expected:
```
Error: No Output Directory named "build" found after the Build completed. You can configure the Output Directory in your project settings. Learn more: https://vercel.com/docs/v2/platform/frequently-asked-questions#missing-public-directory
```
I also changed the usage of [`promisify(fs)`](https://nodejs.org/docs/latest-v10.x/api/util.html#util_util_promisify_original) to [`fs.promises`](https://nodejs.org/docs/latest-v10.x/api/fs.html#fs_fs_promises_api) which is available in Node 10 or newer.
Lastly, I updated the test suite to check if the correct error message is returned for builds we expect to fail.
Previously, when a project has a specific "Output Directory" configured
in the project settings page, it was not being correctly considered when
using `vercel dev`.
The main fix here is passing in the full project settings object
(including the `outputDirectory`) to the `detectBuilders()` function.
Also cleaned up a few types and updated the error message that was
previously being rendered to use a short link.
Due to Go's peculiar package importing structure, there's unfortunately no way to _directly_ invoke a Go serverless file, so the approach for this `startDevServer()` function is:
* Create a temp directory in `.vercel/cache`
* Run the `analyze` Go program on the entrypoint file to determine the `functionName`
* Copy the entrypoint file into the temp directory, while modifying it to use `package main`
* Copy the `dev-server.go` file into the temp directory, replacing the placeholder function name with the `functionName` retrieved from the analysis step from before
* Execute `go run $tmp_dir` to spawn the Go HTTP server on an ephemeral port
* Return the Go process id and port number for `vercel dev` to proxy to
* After the Go process has exited, delete the temp directory
This adds more fine grained tests for our revalidate behavior to ensure pages are actually being updated instead of only checking the headers, it also corrects page lookups failing with shared lambdas enabled for dynamic pages using revalidate.
Closes: https://github.com/vercel/next.js/issues/14497
Since the filesystem watcher may be slow, it's actually faster and more
reliable to simply re-read the `vercel.json` configuration for every
HTTP request. This also simplifies the logic as an added benefit.
Some `sleep()` calls are removed from relevant tests that were
previously necessary due to the lag in the filesystem watcher.
This PR improves the validation error message when the user has an invalid `vercel.json` file.
Previously, the error message did not account for nested properties so `{"foo": "will error"}` looked fine because it would mention there is an additional property `foo`. However, the error message for `{ "routes": [{ "foo": "will error" }] }` did not mention anything about `routes` when it explaining there was an additional property `foo`. This became more apparent as we added nested properties for `rewrites` and `redirects` (see tests in this PR).
This PR also adds suggestions for common mistakes such as `src` vs `source`.
In the latest canary of Next.js pages are no longer nested under the `BUILD_ID` folder and instead are nested under a hash for the page bundle content. To prevent these tests from breaking too often from changes in canary this updates to locate the page bundle using the `buildManifest`. This also updates our latest SSG fixture to test against the latest canary to help ensure the feature doesn't break with a new canary release
Append `# Created by Vercel CLI` to the head of `.env` file and automatically overwrite the file if it's there next time without confirmation.
https://app.clubhouse.io/vercel/story/316
This PR fixes the error message when the client does not have internet connectivity or perhaps DNS is misconfigured such that the hostname cannot be resolved.
This PR fixes#4239 where using `vercel dev` to work on monorepos where
the Next.js app is not in the topmost directory fails to correctly route
to dynamic pages.
After investigating the devServer router, @styfle prompted me to
investigate the @vercel/next builder. He also suggested restricting
`check` to be false only when running in `now dev`.
Co-authored-by: Steven <steven@ceriously.com>
Bump node-file-trace to fix a webpack tracing bug that looks like the following:
```
TypeError: Cannot read property 'type' of null
at handleWrappers (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:12763:58)
at module.exports.447.module.exports (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:14674:3)
at Job.emitDependency (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:11730:40)
at /vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:11755:20
at async Promise.all (index 9)
at async Job.emitDependency (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:11736:5)
at async Promise.all (index 1)
at async Object.module.exports.328.module.exports [as default] (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:11514:3)
at async Object.module.exports.178.exports.build (/vercel/e77875438c1cd74b/.build-utils/.builder/node_modules/@vercel/next/dist/index.js:6076:69)
at async buildStep (/var/task/sandbox-worker.js:20407:20)
```
- [0.6.2](https://github.com/vercel/node-file-trace/releases/tag/0.6.2)
- [0.6.3](https://github.com/vercel/node-file-trace/releases/tag/0.6.3)
- [0.6.4](https://github.com/vercel/node-file-trace/releases/tag/0.6.4)
Depends on #4355
As mentioned by @dav-is we can prefix the outputs with the `basePath` instead of using a rewrite so that we make sure to 404 when the basePath isn't prefixed on the output. This behavior is also matched in Next.js with [this PR](https://github.com/zeit/next.js/pull/9988).
x-ref: https://github.com/zeit/now/pull/3478
This updates to leverage changes from https://github.com/zeit/next.js/pull/12801 which resolves invalid named regexes being used when the segments contain non-word characters e.g. `/[hello-world]`.
Failing page names have also been added to the `23-custom-routes-verbose` fixture. Since the routeKeys aren't applied for dynamic routes in this PR until the routes-manifest version is bumped in the latest canary of Next.js the added test cases will be passing now and should be re-run to ensure passing after a new canary of Next.js is released with the routes-manifest version bump
On Node 10, the `require.resolve()` with "paths" does not return the
proper value relative to the `node_modules` directory. To wit:
```
$ node -v
v10.16.3
$ node -p "require.resolve('typescript', { paths: [process.cwd()] })"
/Users/nrajlich/Code/vercel/vercel/packages/now-node/dist/typescript.js
$ node -v
v14.4.0
$ node -p "require.resolve('typescript', { paths: [process.cwd()] })"
/Users/nrajlich/Code/vercel/vercel/node_modules/typescript/lib/typescript.js
```
(**Note:** cwd when running these commands is the `dist` dir of `@vercel/node`)
So the solution is to just let `require.resolve()` throw an error so the
default string "typescript" is used instead of a resolved absolute path.
This PR adds a E2E CLI test to ensure that the Gatsby example deploys correctly and that the second deployment has the proper cached directories.
Co-authored-by: Nathan Rajlich <n@n8.io>
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Before this, if the `vercel.json` file gets deleted while the dev server
is running, then it would still act like the file exists since it would
use the cached version.
Now it properly invalidates to an empty configuration if the
`vercel.json` file does not exist.
This is a follow up to #4514 to handle the case where there is no
`tsconfig.json` closer to the entrypoint. This is likely the case when
`.js` files with ES Modules syntax are being used instead of `.ts`.
* [cli] Better errors for conflicting configuration files
Renders the link https://vercel.link/combining-old-and-new-config
for all conflicting config errors.
* Fix unit test
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
* Fixes changing a `config` value in the `builds` array (such as `helpers: false` for `@vercel/node`) and having it be reflected in `vc dev` without restarting the dev server.
* Re-validates the env vars configuration when a `.env` file changes or the `env` object is changed in `vercel.json` (same for the builds equivalents).
* Ensures that the `NODEJS_HELPERS` build env var is being properly checked in `startDevServer()`.
* Regenerated the `yarn.lock` file because yarn was erroring when trying to add the `fast-deep-equal` dependency.
As noticed, `now.json` and `vercel.json` files aren't available during the build currently which makes feature detecting and opting out when `routes` are used not work currently so this re-disables the shared lambdas optimization by default while we investigate detecting this
* Ensures that `vc --debug projects ls` properly prints the Projects listing, rather than the usage help info.
* `vc projects` (without a subcommand) shows the Projects listing (this is consistent with i.e. `vc domains`).
* Returns with exit code `2` when the usage help info is printed (standard Unix convention).
As discussed this adds opting out of the shared lambdas optimization when a user adds a functions config in `now.json` or `vercel.json` since this could potentially be a breaking change. We plan to add new handling to still allow customizing this config for the combined lambdas that are created
This happens, for example, with a `startDevServer()` process that
crashes (i.e. a syntax error in a Node.js API endpoint) before
responding to the HTTP request.
* Fix the "Developer Documentation" link.
* Remove the "If you're a visitor" section - doesn't make sense for `vc dev` since there are no "visitors".
* Don't link to `_logs` since it's not supported in `vc dev`. Instead direct the user to look at their terminal window to see error logs.
* Link to new GH issue for non-app error 502 (I don't think this code path ever happens in `vc dev`, but might as well make it correct in case we do in the future).
<img width="1077" alt="Screen Shot 2020-06-05 at 4 15 16 PM" src="https://user-images.githubusercontent.com/71256/83929319-c7832a00-a747-11ea-9cae-b0adac97dfa5.png">
As discussed this de-experimentalizes the shared lambdas optimization now that we have tested it, it also bails out of the optimization when a `now.json` or `vercel.json` is detected that contains legacy routes
Next.js already has support for [customizing the 404 page](https://nextjs.org/docs/advanced-features/custom-error-page#customizing-the-404-page), but many other frameworks do not or they expect a 404.html in the output directory.
This PR adds support for rendering the a `404.html` page for all zero config deployments.
- Implements ch337
- Related to #3491
* [client] Throw an error if both `vercel.json` and `now.json` exist
* Update packages/now-client/src/create-deployment.ts
Co-authored-by: Steven <steven@ceriously.com>
* Check in CLI as well
* Add integration test
* Add logic to `getLocalPathConfig()` as well
* Fix import path
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
So that if a `tsconfig.json` exists closer to the entrypoint file,
then that config file will be correctly used (rather than say, the
root-level `tsconfig.json` file, which may be specific to the frontend
configuration in Next.js for example).
Upon investigation into the `dist` dir, it appears that `ncc` is bundling some assets that don't need to be there. This change is a quick band-aid fix to remove those assets, without addressing the underlying cause of _why_ they're being bundled, which requires further investigation.
Overall about 1mb of disk space is saved.
Fixes a case when the header value contains a URL which was mistaken for a named segment.
https://sentry.io/organizations/zeithq/issues/1702692084/?project=1351065
The regression was introduced in PR #4484 where unnamed segments were implemented for `redirects` and `rewrites` but not handled properly in `headers`.
In PR #4498, the type of the routing error was changed from first error and then the remaining errors. This PR changes the type back such that `error.errors` returns all errors. This will avoid any breaking change.
This PR improves the way we handle routing errors in a few ways:
- The error response is a single error (the first) instead of an array of errors when mixing routing properties
- The error message says which route index has the error
- The error includes `link` and `action` properties to match our API
- The error message for mixed routes with new routing properties has been updated per [ch341](https://app.clubhouse.io/vercel/story/341)
Related to #3491
We renamed the GitHub repository from `zeit/now` to `vercel/vercel` so this PR updates all references to the repo URL.
There were also a few remaining references to Now CLI that have been updated to Vercel CLI.
Follow up to #4463 to fix failing windows unit tests in `now-client`.
This also fixes `now-cli` tests that started failing after renaming the repo to `vercel/vercel`.
Follow up to #4444 that makes sure we run Next.js tests.
This `--ignore-engines` flag was originally added in https://github.com/vercel/now-builders/pull/463 as a workaround. We can remove it to make sure the version of Node selected will work with the dependencies.
Removing the flag also makes sure that Yarn 2 will work properly, see #4444.
This adds a failing test for the regex from https://github.com/zeit/next.js/discussions/13347#discussion-4546
It appears the reason the regex does not work when deployed on Vercel is due to us not indexing the un-named segments and instead we filter them out as noticed by @dav-is.
This PR adds one approach to resolve this by accounting for the un-named indexes while not allowing them to be used in the destination still.
Similar to #4427 but instead of an option to turn on or off, we delay the background task that updates the Runtimes during development. The idea is that the initial install runs immediately using the bundled Runtimes from the CLI. Then if the user plans to keep developing, we'll check to see if we should update to the latest Runtime version after 30 seconds.
When debugging the CLI with `--inspect`, the flag was being passed to the child process as well since #4254.
This PR prevents any arguments from being passed to the child process.
For some reason, the glob selector was causing problems on Windows:
```
[frameworks] Running yarn test-unit
$ jest --env node --verbose --runInBand --bail test/*unit.*test.*
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
In D:\a\now\now\packages\frameworks
6 files checked.
testMatch: **/__tests__/**/*.[jt]s?(x), **/?(*.)+(spec|test).[tj]s?(x) - 1 match
testPathIgnorePatterns: \\node_modules\\ - 6 matches
testRegex: - 0 matches
Pattern: test\\*unit.*test.* - 0 matches
error Command failed with exit code 1.
```
Remove the glob pattern fixes the issue, though it's not clear why it
causes an issue in the first place.
See: https://github.com/zeit/now/runs/701043212
* Update routes order for shared lambdas
* Add test case
* update test path
* Update packages/now-next/test/fixtures/23-custom-routes-verbose-shared-lambdas/now.json
* Update headers in probes
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Co-authored-by: Joe Haddad <joe.haddad@zeit.co>
This code was contributed by @nathancahill under MIT license but it is likely from the Mangum project, so we'll link to the relevant code as the original source, also MIT License.
Currently, CI is printing this:
```
Running "test-unit" on branch "(HEAD" with the following packages:
now-cli\test\dev-server.unit.js
now-cli\test\fixtures\unit\now-dev-request-body\api\data-events.js
now-cli\test\fixtures\unit\now-dev-request-body\api\req-body.js
now-node-bridge\src\bridge.ts
now-node\src\dev-server.ts
now-node\src\helpers.ts
now-node\src\launcher.ts
now-cli
[now-cli\test\dev-server.unit.js] Skipping since script "test-unit" is missing from package.json
[now-cli\test\fixtures\unit\now-dev-request-body\api\data-events.js] Skipping since script "test-unit" is missing from package.json
[now-cli\test\fixtures\unit\now-dev-request-body\api\req-body.js] Skipping since script "test-unit" is missing from package.json
[now-node-bridge\src\bridge.ts] Skipping since script "test-unit" is missing from package.json
[now-node\src\dev-server.ts] Skipping since script "test-unit" is missing from package.json
[now-node\src\helpers.ts] Skipping since script "test-unit" is missing from package.json
[now-node\src\launcher.ts] Skipping since script "test-unit" is missing from package.json
```
So, other than `now-cli` which is hard-coded to always run, no other tests were being selected on Windows. This change uses the proper path separator for the OS to fix this.
Also, the branch name detection command is changed to fix the `"(HEAD"` name that is being detected in CI.
With this change, it looks like:
```
Running "test-unit" on branch "fix/tests-windows" with the following packages:
- now-node
- now-cli
[now-node] Running yarn test-unit
…
[now-cli] Running yarn test-unit
…
```
This PR adds two additional flags to `npm install` when updating Runtimes:
- `--no-audit`: disable sending of audit reports to the configured registries
- `--no-progress`: disable the progress bar
* Removes the `get-bundled-builders.ts` file, which is no longer relevant, and was causing a false-positive for `@now/build-utils`.
* Makes the installing of `@vercel/build-utils` and `@now/build-utils` only happen if there is another Runtime to install.
* `@vercel/build-utils` and `@now/build-utils` will now be properly checked for updates (but again, only if there is another Runtime to update).
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
Fixes an issue from discussion #4391 so that quotes are no longer escaped per dotenv conventions.
I tested the behavior and it works correctly with Next.js and Create React App.
`now-bash@3.0.0` is broken in production because AWS decided to remove
the `which` command from the Lambda environment for some reason. Fixed
in the latest version which uses the updated Vercel name.
Also removes the `skipDeploy: true` flag for this test, and updates the
test names to include "vercel dev" intstead of "now dev".
This is a follow-up to #4241, which apparently caused the `vc dev` unit
tests to start timing out. After some digging, it seems the root cause
is that `proxy.close()` callback is never invoked. This makes sense
because we never call `proxy.listen()` or have the `httpProxy` actually
bind to a port.
We were already using `http-proxy`'s WebSockets option, but we were missing a step! In addition to setting `{ws: true}`, you must also forward WebSocket upgrade events from the front-facing server to the proxy. [(See this example.)](https://github.com/http-party/node-http-proxy#proxying-websockets)
Previously, the proxy server and client _would_ mutually agree to "upgrade" their connection (because we set `{ws: true}`)… but then, when the client would start sending WebSocket data instead of HTTP data, our front-facing server would drop it, because we hadn't configured a place for it to go.
In this change, we configure `this.server` to forward its `upgrade` events to the proxy server.
We also refactor `proxyPass` to use the new shared `this.proxy` instance responsible for the `upgrade` events, instead of creating a new proxy instance for every request. This isn't strictly necessary, but a helpful simplification to clarify that there's no specific reason for the proxy instances to be _different_ than the instance that manages WebSocket upgrades!
This fixes#3451: CRA apps can now auto-refresh when the source code changes, and Firefox can now load the app without crashing on the 6th attempt.
Co-authored-by: Steven <steven@ceriously.com>
* Add initial changes for grouping lambdas
* Handle more cases and clean up some stuff
* Remove logs from debugging
* Remove changes from testing and add page layers
* Update output tests
* Move new behavior behind flag
* Add separate tests for new behavior
* Clean-up style diffs
* Update error
* Update to separate out new behavior more
* Apply suggestions from review
Co-authored-by: Tim Neutkens <tim@timneutkens.nl>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
* Add test to frameworks
* Add example for Docusaurus v2
* Add example for ionic-angular
* Update READMEs
* Use existing versions
* Reset yarn.lock
* Add schema validation and add missing Scully.io logo
Write the generated `tsconfig.json` files that are required to do TypeScript type checking on a single file to the dev cache directory (`.vercel/cache`). This way, they are in a location that is gitignored by default, but still has `require()` access to the types that the project uses.
* `StartDevServerOptions` had to be updated to include `meta`, at which point it's identical to `BuildOptions`, so just make it a type alias instead.
* Vercel CLI is updated to pass in the `meta` object to `startDevServer`
* Vercel CLI is updated to create the `.vercel/cache` dir upon startup, if it does not already exist
* `@vercel/node` now creates the tsconfig files in the dev cache directory, using the `wx` write flags. This ensures that the file is only created once and then cached in the dev cache dir.
An example of a generated tsconfig file for endpoint `api/foo.ts`:
```json
{
"extends": "../../tsconfig.json",
"include": ["../../api/foo.ts"]
}
```
To keep the `lerna` monorepo version pinning intact.
It should have been updated in c23b9ccd1d, but was not because the commit was created manually instead of with `lerna`.
Starting with version 18.0.0, there was a regression from ##3980 causing the deploy command to hang indefinitely at the file tree building stage. I triaged the issue to be that the call of `recursive-readdir` was now walking through my `node_modules` folder. This is an issue in my environment since I have a very intricate monorepo with circular symlinks in my node_modules, which causes `recursive-readdir` to go into an infinite loop.
This PR fixes this in 2 commits:
1) The first commit refactors out the file tree building logic into separate utility functions and adds unit tests to verify the expected behavior of not walking through `node_modules` (this commit's unit test run should fail as seen in checks on this PR). This commit does not change any behavior.
2) The second commit fixes the actual issue (causing the unit tests to pass again). When I was bisecting the issue between the 17.0.0 and 18.0.0 tags I noticed that trailing slashes were added to the default ignore's directory entries in `getVercelIgnore()`. I removed them to bring it back to how it was done in v17.0.0 and it resolved the issue.
Hopefully with the added unit tests this shouldn't regress in the future.
Co-authored-by: Steven <steven@ceriously.com>
* [now-node-bridge] Catch invalid HTTP request headers
In some rare cases, the proxy layer passes what Node.js considers an
invalid HTTP request header causing the `http.request()` function to
throw an error, such as:
```
TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["cookie"]
```
So instead, use `req.setHeader()` API with try/catch to skip invalid
HTTP headers and print a message for the deployment logs with debugging
information. This way, the HTTP request will still go through, with
a missing header, rather than causing the whole function to 500.
* Add test
* Don't use `typeof`
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This PR improves the error message when a user provides an invalid pattern in package.json `engines` field.
## Before
```
TypeError: Invalid comparator: => 10
at Comparator.module.exports.Comparator.parse (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10262:11)
at new Comparator (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10245:8)
at Range.<anonymous> (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10439:12)
at Array.map (<anonymous>)
at Range.module.exports.Range.parseRange (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10438:13)
at Range.<anonymous> (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10381:17)
at Array.map (<anonymous>)
at new Range (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10380:40)
at Function.intersects (/zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:10998:8)
at /zeit/9cd49d8c66a9bd43/.build-utils/node_modules/@vercel/build-utils/dist/index.js:25847:29
```
## After
```
Found `engines` in `package.json` with an invalid Node.js version range: "=> 10".
Please set "engines": { "node": "12.x" } in your `package.json` file to upgrade to Node.js 12.
More details: https://vercel.com/docs/runtimes#official-runtimes/node-js/node-js-version
```
In this case, the `=>` operator is not valid so the user probably meant `>=` but we only suggest the `10.x` or `12.x` syntax because we can only guarantee a major version.
This PR fixes the scenario when a user adds an environment variable to a project but then deletes the secret associated with the environment variable.
For example:
```sh
echo 'foo' | vc env add FOO development
vc secrets rm foo-development-v1ln
vc env pull # would error with 404 every time
vc env rm FOO development # would error with 404 the first time
```
Now we'll warn for `vc env pull` and we will assume success for `vc env rm`.
Fixes https://sentry.io/organizations/zeithq/issues/1612188511/
Fixes https://sentry.io/organizations/zeithq/issues/1656997656/
* [client] Throw an error if both `.vercelignore` and `.nowignore` exist
* Remove `.`
* Add tests
* Update test
* [cli] Properly clear spinner if `createDeployment()` async generator throws an error
* Update packages/now-client/src/utils/index.ts
Co-authored-by: Steven <steven@ceriously.com>
* Update packages/now-client/tests/vercelignore.test.ts
Co-authored-by: Steven <steven@ceriously.com>
Co-authored-by: Steven <steven@ceriously.com>
This PR fixes an issue where old versions of the CLI would update to the latest builder, but not have a copy of `@vercel/build-utils` because they only shipped with `@now/build-utils`. So in this case, we can fallback to the other package. We must be careful to only import types from `@vercel/build-utils` and anything needed at runtime must be imported from `./build-utils` wrapper.
This PR fixes an issue when the error message assumed the config was `vercel.json` even when the user had `now.json`.
### Before
```
Error! The property `foo` is not allowed in vercel.json – please remove it.
```
### After
```
Error! The property `foo` is not allowed in now.json – please remove it.
```
Co-authored-by: Nathan Rajlich <n@n8.io>
This PR fixes a regression from PR #4084 where secrets were paginated so some v1 deployments that had more than 20 secrets were unable to deploy since CLI version 19.
This PR adds two functions:
* `getTitleName()` - used to get the uppercase Vercel or Now package name, for example `vercel --version`
* `getCommandName()` - used to get the `vercel` command followed by subcommands, for example in error suggestions
Unset the `npm_config_registry` env var which yarn overwrites to the
yarn registry, which we don't want since the `.npmrc` file that gets
created is configured to the npm registry.
This PR adds a test for a deployment as well as `now dev` to ensure both `vercel.json` and `.vercelignore` are applied.
I also fixed the remaining test helpers to work with `vercel.json`.
* [now-build-utils] Use `@now` runtimes for zero-config
This is a temporary change until the `@vercel` runtimes work in
production.
* Temporary fix to E2E
Fixes a bug where `isOfficialRuntime('static', '@now/static-build')` was returning `true` when it should have been `false`.
And use the function from `@vercel/build-utils` in Vercel CLI.
We want to make sure the bin matches the [installed package name](https://docs.npmjs.com/files/package.json#bin).
This means `npm i -g now` will remain `now` and `npm i -g vercel` will use `vercel` as the binary name.
This allows support for different versions on one machine such as `npm i -g now@17 vercel@19` for example.
In addition, we will also install a shorthand `vc` so you can do `vc env pull` for example.
Added the following env vars, most are undocumented but its good to be consistent:
- `VERCEL_REGION`
- `VERCEL_DEBUG`
- `VERCEL_BUILDER_DEBUG`
- `VERCEL_TOKEN`
- `__VERCEL_SKIP_DEV_CMD`
I also updated the error code prefixes to remove `NOW_`.
There `code` isn't used anywhere, this is just to make it unique and a little shorter.
We renamed `.now` to `.vercel` in #4234 but still fallback to `.now` if it exists. This is because we don't want users to have to re-link all their existing projects. So we need to make sure that the Runtimes know which directory to use for caching. This PR introduces the `devCacheDir` for this purpose.
As you can see in https://github.com/zeit/now/runs/647945621,
the final step for publishing the legacy `@now` packages failed
with a 401 error from npm.
This additional logging an to attempt to debug why that is happening.
https://vercel.com/blog/zeit-is-now-vercel
* Updates all org packages from `@now` to `@vercel`
* Updates Now CLI package name from `now` to `vercel`
* Packages contains `"bin"` entries for _both_ `vercel` and `now` in the package.json
* Updates `now-client` package name to `@vercel/client` (org scoped, for authenticity)
There is also a new `publish-legacy.sh` script which ensures that all the legacy package names (i.e. `now`, `now-client`, `@now/node`, etc.) will still be published as well.
We will remove this legacy publishing logic on Jan 1, 2021.
This PR renames the CLI and config files to `vercel`.
https://vercel.com/blog/zeit-is-now-vercel
### Complete
- [x] Help menus and error messages should print cli name from `package.json`
- [x] `now.json` => `vercel.json`
- [x] `.nowignore` => `.vercelignore`
- [x] `~/.now` => `~/.vercel`
- [x] `<project>/.now/project.json` => `<project>/.vercel/project.json`
### TODO
I'm going to do the remaining work in a follow-up PR:
- [ ] `<project>/.now/cache` => `<project>/.vercel/cache` (Runtimes sometimes use this)
- [ ] `NOW_*` special cased environment variables
- [ ] `*.now.sh` special cased url suffix
This PR fixed a corner case when the user defined both `cleanUrls: true` and `trailingSlash: true` and then visited `/index.html` which would attempt to redirect to the invalid `//` path.
This PR fixes a bug where the headers were not applied when exiting with a status code such as 204.
This is a common pattern for CORS where you want `OPTIONS` method respond with 204 status due to a preflight request.
I also updated the test suite to support the `method` property and ensured a body with empty string is asserted.
As discussed this updates to leverage the new named regexes and route keys output in the `routes-manifest.json` to pass the dyname page values in the query to ensure we're handling edge cases with the new custom routes support
Note: the `yarnPreferOffline` change is unrelated and was added to make debugging easier as the build can fail when using this option and the cache is invalid for some packages.
x-ref: https://github.com/zeit/next.js/pull/12250
In PR #3514, we added a `/api` directory for functions and a `/public` directory which was created at build time.
This moves the build script to be `now-build` so we don't don't need to build everything in the repo and also no longer need to special case the git env vars.
This PR makes sure that all the `now dev` tests have a corresponding deployment and each assert is also compared to the deployment.
If you want to opt-out of this behavior, for example a test that is meant for specific dev functionality, then there is an option `skipDeploy: true`.
This also fixes a bug where headers were not assigned during proxying to a dev server.
Using `ts-node`, with asynchronous type checking via `tsc --no-emit`.
This also removes `ncc` of `typescript` during the build in favor of
having typescript be a regular npm "dependency".
Noticed that we still say `Zeit` while using the now cli.
The inspect command still points to zeit.co when I tested it some hours ago but that seems to be fixed already 😄
This was switched to `npm` for debugging purposes in #4124, but at this
point we can switch it back to `yarn` so the tests don't take as long.
Co-authored-by: Leo Lamprecht <leo@zeit.co>
As a follow up to #4178, this fixes the final lint errors so we can run in CI.
Since lint is very quick, about 8 seconds, we can run it on the entire repo instead of only changed files.
I also disabled a couple rules that were leading to 500 warnings we would likely never change.
It's not useful information and distracts from whatever the actual error
message was from the dev server, which is what the user is actually
interested in.
This updates the error message shown when we fail to load the `routes-manifest` which appears to be happening most often when an incorrect output directory is configured for a Next.js application
Rather than creating a `builders.tar.gz` file with the core Runtimes and
bundling that tarball with Now CLI, simply have them be regular npm
dependencies so that they are installed into Now CLI's `node_modules`
directory.
When one of the core runtimes is specified for a build, the runtime will be
required as a regular module dependency of Now CLI, and the builders cache
will never touched.
Bundled runtimes are also no longer updated, making the runtime versions
pinned to the version of Now CLI.
Logic for the builders cache directory still remains, but will now only be
used when using a Community Runtime (or development tarball URL).
The previous file path for ncc isn't always reliable during development,
depending on which directory `yarn` is invoked in inside the monorepo.
Using `npx` ensures the version specified in the now-cli `package.json`
is used even if it's installed at the root of the monorepo.
When Now CLI 17 introduce the `.now` directory with project settings, it started assuming that the current project scope should be used for all commands. This made `now switch` do nothing unless you changed the current directory.
This PR is a _major_ semver change so that the only commands that inherit the project settings are:
- `now deploy`
- `now dev`
- `now env`
For example, `now ls` will not observe project settings and instead observe `now switch`.
`now dev` integration tests have been failing as of recently with failures to require Runtime builders from the builder cache. Upon investigation, it turns out that the `builders.tar.gz` file was not being completely extracted since the integration tests complete quickly and then kill the Now CLI process, which has not yet completed the extraction.
Fix is to ensure the tarball extraction promise is fully resolved before cleanly shutting down.
Also now applying the clean shutdown logic upon `SIGTERM` signal, which is what the integration tests send to shut down the Now CLI process.
After #4024 was merged, I tested and still got the same error. I searched around and found that the lines of code are in wrong order (ref: https://bugs.python.org/issue37521). So this is the proper fix.
Co-authored-by: Steven <steven@ceriously.com>
Stop downloading and caching `yarn` from GitHub Releases in `now dev`,
and instead simply rely on the user having `npm` installed. The user is
extremely likely to have `npm`, since Now CLI now requires `node` to be
installed (no longer using `pkg`) which comes with `npm` bundled by
default.
DRY and removes the `pid` from the set immediately so there's no race
condition if the server is shut down shortly after an HTTP request
(like in the tests).
Previously, when `package-lock.json` was detected, we would always use `npm install`.
This PR changes the behavior to the following:
- If only `package-lock.json` is detected, we use `npm install`.
- If both `package-lock.json` and `yarn.lock` are detected, use `yarn install`.
This will avoid npm bugs such as `npm ERR! Cannot read property 'match' of undefined`.
- Print an error instead of throwing when `destination` has segment not found in `source`
- Update docs to explain how to fix this error
- Add a couple tests
- Update uncaught `path-to-regexp` error message to print the full route that caused the error
This is an extension to the Runtime API, where a runtime can optionally define a `startDevServer()` function which is responsible for spawning a single-serve dev server for an individual HTTP request (the dev server is booted up upon receiving an HTTP request, and gets shut down by `now dev` after the HTTP request is completed). For runtimes that define this function, the `build()` function will never be executed, which avoids a lot of unnecessary processing for a dev environment.
Some things this accomplishes:
* Retains the proper stack trace for errors.
* Ensures that if a source code file is changed, and then an HTTP request is sent, it's guaranteed to be using the latest code (no file watching, or re-compilations).
* Avoids creating a Lambda zip file (just to immediately unpack it for dev).
* Avoids `@zeit/fun` completely, which loses some "correctness" (i.e. function is not frozen in between requests).
* Backwards compatible with older Now CLIs - versions that don't know about `startDevServer()` will just invoke `build()`, and there's no version change required in the Runtime.
The `runNpmInstall()` function is already a no-op when invoked via `now dev` (#2926), however the "Installing" message was still being printed, leading to confusion about whether or not they actually are (they're not).
This fixes the static 404 page not being used when deploying in a mono-repo structure. Before we weren't taking into account the `entryDirectory` where we needed to causing us to deploy `_error` when we didn't need to
x-ref: https://github.com/zeit/now/discussions/4077#discussioncomment-4625
The `public` directory was missing from the `ionic-react` example because we were ignoring all `public` directories.
This PR adds the public directory back (it is copied from now-static-build test fixtures). I also updated `.gitignore` and `.gitattributes` to be a little more friendly to our test fixtures so this doesn't happen again.
- Capitalize `Environment` in all outputs
- Fix stdin detection so there is no need for timeouts
- Dont throw if the error is bad user input, only throw for unexpected errors
- Fix tests so waiting for prompt will throw if expected output is never received
The latest `now env` subcommand no longer makes the distinction between build time and runtime environment variables so this PR updates `now dev` to no longer make the distinction either.
The only exception is that some builders such as `@now/next` might still rely on the separation so we must preserve the distinction for legacy builders.
This PR adds support for empty values when using `now env add|ls|rm|pull`.
This is necessary when using system environment variables such as `NOW_GITHUB_COMMIT_SHA` which will not receive a value from the user but will instead assign a value automatically during deployment.
Without this fix, Python app which uses [Pydantic](https://pydantic-docs.helpmanual.io/usage/postponed_annotations/) for data validation will crash with log like this:
```py
File "pydantic/main.py", line 175, in pydantic.main.ModelMetaclass.__new__
annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None))
File "pydantic/typing.py", line 136, in pydantic.typing.resolve_annotations
annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None))
File "pydantic/typing.py", line 136, in pydantic.typing.resolve_annotations
base_globals: Optional[Dict[str, Any]] = sys.modules[module_name].__dict__
KeyError: 'api.main'
```
The added code also follow Python official documentation: https://docs.python.org/3.6/library/importlib.html#importing-a-source-file-directly
This PR does a few things:
- Change `dev.unref()` when possible and use `testFixtureStdio` instead
- Replace `fetch()` with `fetchWithRetry()` when possible
- Remove commented-out tests
There was a bug preventing `continue: true` from working between (null => filesystem) phases.
This PR fixes that bug and adds a test to ensure users can rewrite to dynamic path segments.
This PR adds framework config for Ionic Angular and also updates a mistake found in the dev script of Ionic React, which mistakenly was using the same dev script as Stencil.
This PR adds a new command `now env` for managing environment variables for a given project. This will complement the changes in the Dashboard and will provide 3 possible environments: `production`, `preview`, and `development`.
- [x] Add `now env ls`
- [x] Add `now env add`
- [x] Add `now env rm`
- [x] Add `now env pull`
- [x] Add test for `now env ls`
- [x] Add test for `now env add`
- [x] Add test for `now env rm -y`
- [x] Add test for `now env pull -y`
- [x] Add test for `now env add FOO preview < secret.txt`
- [x] Add test deployment to verify env var is assigned to both build and runtime
- [x] Test on Windows
```
▲ now env [options] <command>
Commands:
ls [environment] List all variables for the specified environment
add [name] [environment] Add an environment variable (see examples below)
rm [name] [environment] Remove an environment variable (see examples below)
pull [filename] Read development environment from the cloud and write to a file [.env]
Options:
-h, --help Output usage information
-A FILE, --local-config=FILE Path to the local `now.json` file
-Q DIR, --global-config=DIR Path to the global `.now` directory
-d, --debug Debug mode [off]
-t TOKEN, --token=TOKEN Login token
Examples:
– Add a new variable to multiple environments
$ now env add <name>
$ now env add API_TOKEN
– Add a new variable for a specific environment
$ now env add <name> <production | preview | development>
$ now env add DB_CONNECTION production
– Add a new environment variable from stdin
$ cat <file> | now env add <name> <production | preview | development>
$ cat ~/.npmrc | now env add NPM_RC preview
$ now env add DB_PASS production < secret.txt
– Remove a variable from multiple environments
$ now env rm <name>
$ now env rm API_TOKEN
– Remove a variable from a specific environment
$ now env rm <name> <production | preview | development>
$ now env rm NPM_RC preview
```
Some inputs cause `compile()` to throw but its not clear which route caused it to fail.
> TypeError: Unexpected MODIFIER at 29, expected END [see source](https://sentry.io/organizations/zeithq/issues/1593291118/?project=1351065)
This PR adds logs so we can see the bad user input and correct accordingly.
Since enabling `CI` environment variable for cloud builds, this test fails because it is meant to emit a warning however that warning has turned into an error.
```
05:40:53.148 Treating warnings as errors because process.env.CI = true.
05:40:53.148 Most CI servers set it automatically.
05:40:53.148 Failed to compile.
05:40:53.149 ./src/App.js
05:40:53.149 Line 1: 'useState' is defined but never used no-unused-vars
05:40:53.172 error Command failed with exit code 1.
```
We can again treat lint errors as warnings by setting `CI=false`.
Example build output given a user's build script named `shouldfail.js`:
## Before
```
/zeit/4af70cdc/shouldfail.js:3
throw new Error('This is my failure')
^
Error: This is my failure
at Object.<anonymous> (/zeit/4af70cdc/shouldfail.js:3:7)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Exited with 1
at ChildProcess.<anonymous> (/zeit/687b1c64/.build-utils/node_modules/@now/build-utils/dist/index.js:31350:24)
at ChildProcess.emit (events.js:223:5)
at ChildProcess.EventEmitter.emit (domain.js:475:20)
at maybeClose (internal/child_process.js:1021:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)
worker exited with code 20 and signal null
Done with "package.json"
```
## After
```
/zeit/255bfdd/shouldfail.js:3
throw new Error('This is my failure')
^
Error: This is my failure
at Object.<anonymous> (/zeit/255bfdd/shouldfail.js:3:7)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Command "yarn run build" exited with 1
worker exited with code 20 and signal null
Done with "package.json"
```
The current error message prints a link that is not clickable from the terminal.
This PR adds the missing `https://` protocol prefix, so that the link is clickable.
This fixes the error when attempting to add a secret with a hyphen and underscore such as the following:
```
$ now secret add name '-foo_bar'
Error! argv._.slice is not a function
```
As discussed this removes automatically adding path segments to redirect's destination query and only adds them if manually specified
x-ref: https://github.com/zeit/next.js/pull/11497
We already ignore specific files such as `node_modules` and `.env` during the upload phase so these never make it to the build. However, if those files are generated during the build, that are still emitted.
This PR will ignore these specific files even if they end up in the output directory (for example, when the user assigns `outputDirectory='.'` in project settings)
Somehow, PR #3973 broke Go since the bridge is imported from this repo's master branch.
Go has very strict file name constraints and the file `[...path].js` is not compatible.
Here's what a `@now/go` deployment error message looks like:
```
Error: Command failed: go mod tidy
go: finding github.com/zeit/now latest
go: downloading github.com/zeit/now v0.0.0-20200326223129-c91495338d5e
go: extracting github.com/zeit/now v0.0.0-20200326223129-c91495338d5e
-> unzip /tmp/5a0676f5/pkg/mod/cache/download/github.com/zeit/now/@v/v0.0.0-20200326223129-c91495338d5e.zip: malformed file path "packages/now-next/test/fixtures/22-ssg-v2-catchall/pages/[...path].js": double dot
handler imports
github.com/zeit/now/utils/go/bridge: unzip /tmp/5a0676f5/pkg/mod/cache/download/github.com/zeit/now/@v/v0.0.0-20200326223129-c91495338d5e.zip: malformed file path "packages/now-next/test/fixtures/22-ssg-v2-catchall/pages/[...path].js": double dot
```
The solution is to move Go Bridge into a separate repository: https://github.com/zeit/now-go-bridge
This will also have the side effect of speeding up Go imports because the repo will be much smaller.
@tootallnate's bug fix for `SIGHUB` on Windows has been merged and
published as `signal-exit@3.0.3`, so no more need for the "resolutions"
field in `package.json`.
The `yarn.lock` file has been updated accordingly.
When using a catch-all route at the base of the project it would cause it to be prioritized over any GS(S)P `/_next/data` routes. This fixes the order putting `/_next/data` routes first as they have higher specificity and adds tests to ensure we don't regress on this
Fixes an issue with a dependency that was bumped but typescript was pinned in `ionic-react`.
```
$ react-scripts build
Creating an optimized production build...
Failed to compile.
/zeit/333ecfab/node_modules/@types/testing-library__react/node_modules/pretty-format/build/index.d.ts
TypeScript error in /zeit/333ecfab/node_modules/@types/testing-library__react/node_modules/pretty-format/build/index.d.ts(7,13):
'=' expected. TS1005
5 | * LICENSE file in the root directory of this source tree.
6 | */
> 7 | import type * as PrettyFormat from './types';
| ^
8 | /**
9 | * Returns a presentation string of your `val` object
10 | * @param val any potential JavaScript object
error Command failed with exit code 1.
```
This PR does a few things:
- Separate tests into multiple workflows
- Rename a few package.json scripts to make naming consistent
- Rename workflows to be uppercase and jobs to be lowercase
The benefits here are:
- Restart a workflow if it fails, for example only restart `now dev` tests
- Easier to read when we need to understand a workflow or modify env vars
After merging, we'll need to modify the required checks in the repo settings.
We'll also need to update the cancel workflow (that will need to be a separate PR).
This updates the error message to offer action items when an ambiguous argument is provided.
## Before
```
Error! The supplied argument "secrets" is ambiguous. Both a directory and a subcommand are known
```
## After
```
Error! The supplied argument "secrets" is ambiguous.
If you wish to deploy the subdirectory "secrets", first run "cd secrets".
If you wish to use the subcommand "secrets", use "secret" instead.
```
- Change default version to Ruby `2.7.x` to match our static builds such as jekyll
- Detect ruby version in `Gemfile` in case the user wishes to downgrade to Ruby `2.5.x`
- Print nicer error message in `now dev`
cc @nathancahill @m5o
We recently updated the build image to add the necessary dependencies so that `puppeteer` can run during the build step.
This PR adds a test that takes a screenshot and prints metrics during a static build.
This is necessary to support `react-snap` (along with a few flags in `package.json`).
```json
{
"reactSnap": {
"puppeteerArgs": [
"--no-sandbox",
"--disable-setuid-sandbox"
]
}
}
```
- Fixes https://github.com/zeit/now-builders/issues/517
- Fixes#2357
https://zeit.atlassian.net/browse/PRODUCT-1380
This makes `now-next` consider the `node_modules/.bin` path if a custom build command was specified, which makes it work like `now-static-build`.
This PR updates API Errors to support the `error.link` property.
Unlike `error.slug` which is only a path to an error message, `error.link` contains the full URL.
### Example Output
```
$ now
Error! Serverless Functions.........etc
> More details: https://zeit.ink/...etc
```
This PR updates the way we run integration tests (the ones that create test deployments) so that it will be less likely to fail.
A couple side effects to this PR:
- To run the tests locally, you must set `NOW_TOKEN` env var (can be found in `~/.now/auth.json`).
- PRs from forked repos won't run tests because they now rely on a secret in GH Actions.
- A couple alias tests that require certs need to be disabled because they will fail.
[PRODUCT-2093]
[PRODUCT-2093]: https://zeit.atlassian.net/browse/PRODUCT-2093
"ESRCH" error means that the process is no longer running, and thus
already shut down. No need to throw in that case so just ignore the
error.
Fixes: https://sentry.io/organizations/zeithq/issues/1568104652
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Fixes test warnings from `jest-hast-map`:
```
[now-static-build] Running yarn test-integration-once
$ jest --env node --verbose --runInBand test/integration.test.js
jest-haste-map: Haste module naming collision: 12-create-react-app
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/12-create-react-app/package.json
* <rootDir>/test/fixtures/26-ejected-cra/package.json
jest-haste-map: Haste module naming collision: gatsby-starter-default
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/10-gatsby/package.json
* <rootDir>/test/fixtures/10-gatsby-without-build-script/package.json
jest-haste-map: Haste module naming collision: gohugo-default-theme
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/31-hugo/themes/ananke/package.json
* <rootDir>/test/fixtures/46-hugo-with-framework/themes/ananke/package.json
jest-haste-map: Haste module naming collision: gohugo-default-styles
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/31-hugo/themes/ananke/src/package.json
* <rootDir>/test/fixtures/46-hugo-with-framework/themes/ananke/src/package.json
jest-haste-map: Haste module naming collision: 47-nuxt-with-custom-output
The following files share their name; please adjust your hasteImpl:
* <rootDir>/test/fixtures/47-nuxt-with-custom-output/package.json
* <rootDir>/test/fixtures/48-nuxt-without-framework/package.json
```
Also increased test retry to 5.
These examples were using an old version of Bundler which didn't match our tests and would fail with:
```
/ruby27/lib/ruby/2.7.0/rubygems.rb:275:in `find_spec_for_exe': Could not find 'bundler' (1.17.2) required by your /zeit/6f4b9e46/Gemfile.lock. (Gem::GemNotFoundException)
To update to the latest version installed on your system, run `bundle update --bundler`.
To install the missing version, run `gem install bundler:1.17.2`
from /ruby27/lib/ruby/2.7.0/rubygems.rb:294:in `activate_bin_path'
from /ruby27/bin/bundle:23:in `<main>'
```
I ran `bundle update --bundler` in each of these directories and it only updated the version in `Gemfile.lock` because 2.x is mostly backwards compatible.
This PR improves the error message and prevents "An unexpected error occurred" when the token is invalid during a project link step.
I also added the `--token` option to `now dev --help` .
Lastly, I updated `now logout` to work correctly when the token is invalid.
- Fixes#3772
- Fixes#3786
This implements the new handles from https://github.com/zeit/now/pull/3876 to allow us to ensure the proper order for `rewrites`, `redirects`, and `headers` in Next.js. I also added in the tests from the Next.js [custom-routes test suite](https://github.com/zeit/next.js/tree/canary/test/integration/custom-routes) to ensure we're matching behavior.
To help keep track of what each probe is testing I added support for parsing the `now.json` files in `testDeployment` as [JSON5](https://www.npmjs.com/package/json5) to allow adding comments before each probe. If this is undesired I can remove this specific change even though it makes managing the fixture tests much easier
When running a framework like Create React App or Gridsome, the console gets cleared. This prevented the user from seeing the message printed from `now dev` which is typically `http://localhost:3000`. Instead the user would see the framework's URL such as `http://localhost:54684`.
See #3497 for an example.
The solution is to change the child process to pipe stdout/stderr. Since most frameworks detect [`process.stdout.isTTY`](7e6d6cd05f/packages/react-scripts/scripts/start.js (L141-L143)) before clearing the console, this will solve the problem. I was also able to intercept stdout to replace the framework's port with the `now dev` port and I think this will also help prevent confusion.
I also had to set `FORCE_COLOR=1` to avoid losing ANSI colors.
- Related to https://github.com/facebook/create-react-app/issues/2495
- Fixes#3497
When we ask the question "In which directory is your code located?" we were displaying a prefix of `cwd/` which is confusing because it seems like you are supposed to type in the current directory. It also doesn't match what is displayed in the Project Settings after it is deployed.
This changes the prefix to `./` so that `rootDirectory` is set to the current directory and the user can type in a subdirectory if they wish such as `./packages/web` for example.
### Before
```
? Set up and deploy “~/Code/app”? [Y/n] y
? Which scope do you want to deploy to? Testing
? Link to existing project? [y/N] n
? What’s your project’s name? app
? In which directory is your code located? app/
```
### After
```
? Set up and deploy “~/Code/app”? [Y/n] y
? Which scope do you want to deploy to? Testing
? Link to existing project? [y/N] n
? What’s your project’s name? app
? In which directory is your code located? ./
```
In PR #3847 we fixed a bug that prevented installing `devDependencies` when `NODE_ENV=production` this is typically what users want, but there are some cases where a user may wish to skip installing `devDependencies`. For example, if you have more than 500 MB worth of dependencies.
This PR introduces `NPM_ONLY_PRODUCTION=1` which can be used to skip installing `devDependencies` in these rare cases. It is the equivalent of `npm install --production` or `yarn install --production`. There is also `npm install --only=production` for which this new env var gets its name.
#### References
- https://docs.npmjs.com/cli/install
- https://classic.yarnpkg.com/en/docs/cli/install/#toc-yarn-install-production-true-false
In Now CLI 17 when Next.js is detected, the `next dev` command is proxied from `now dev`.
This brings Next.js into alignment as other other frameworks such as Gatsby and CRA. But those other frameworks are building static websites, so we were only passing build time env vars. However, Next.js needs runtime env vars for APIs in `/pages/api`.
So the solution is to special case until Next.js can read these files directly. See https://github.com/zeit/next.js/pull/10525Fixes#3758
This adds support for the new internal `handle` types `error` and `rewrite` and also updates the error messages to be more verbose since additional keys are allowed when using `handle: 'error'`.
This is needed so that we can implement utilize the new handles in `@now/next` for the new custom-routes support
This PR adds issue templates for common cases:
- Bug Report - to be submitted through the ZEIT Now support form.
- Feature Request - to be handled as a discussion between the community and ZEIT staff.
- Ask a Question - to be posted in Discussions for all to answer.
In addition to this, the PR also removes the Spectrum link from the README.
Fixes a regression in #3847 which was preventing the user from assigning `NODE_ENV`.
The root cause was that the spread operator (`...`) performs a shallow clone, not a deep clone. So we must perform another spread to clone the user-provided `env` object before deleting `NODE_ENV` during `npm install`.
The code coverage report stopped uploading after we switched to GitHub Actions because its not a recognized CI provider.
This PR adds a secret with the code coverage token from [codecov.io](https://codecov.io/gh/zeit/now/settings).
This PR changes the behavior of error reporting and metrics so that developers who build and run Now CLI locally won't accidentally report any metrics. It also prevents errors during CI tests from being reported.
The env vars are only assigned during the publishing step so that the official Now CLI hosted on npm is the only way to report metrics.
* add ruby ActiveSupport test fixture
> ActiveSupport is a Ruby module & a stand-alone component of Rails that includes additional functionality to core Ruby classes, like Array, String & Numeric.
🔗https://guides.rubyonrails.org/active_support_core_extensions.html
* add `Date.current + 10.years` calculation example
This fixes a bug in our `@now/build-utils` tests that pair the current build-utils with a stable builder. Since ncc was bundling `@now/build-utils`, we weren't able to configure a different version and these tests were not actually testing the correct version of build-utils.
A nice side-effect is that each builder will be about 50% smaller (compared by measuring `dist`).
* [now-next] Add Support for Prerender v2
* Copy test suite
* Test that fallback doesn't work for fallback: false
* record omitted lambdas
* Improve test case
* improve omitted routes logic
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Some build utilities and SSG Frameworks instruct users to set `NODE_ENV=production` which typically means updating `now.json` to the following:
```json
{
"build": {
"env": {
"NODE_ENV": "production"
}
}
}
```
The problem is that this environment variable is assigned during `npm install` or `yarn install` which is the equivalent of running install with the `--production` flag. This flag prevents `devDependencies` from installing. This is almost never what the user intends so they have to remove `now.json` and instead updating their build script to `NODE_ENV=production yarn build`.
This PR improves the experience by deleting `NODE_ENV` during the install step.
This PR fixes `@now/routing-utils` when the input routes are null. It used to return the empty array but now it will still append.
I also added many more tests to `@now/build-utils` when `featureHandleMiss: true` and refactored the code a bit to make dynamic routes and api routes a little more clear.
This PR refactors the rewrites (the dynamic routes as well as the route that prevents directory listing for zero config deployments) so they are not in the `handle: miss` phase.
This is necessary because the behavior of `handle: miss` will change in an upcoming release.
The solution is to separate these into `rewriteRoutes` that can then be merged properly with the user's routes. They will be appended to the `handle: filesystem` phase (or add the phase if it doesn't exist).
* [now-cli] Remove v1 "static build" integration tests
These are the last remaining v1 static type deployments being created.
* Remove from `integration.js` as well
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
There was a bug in `now-client` when deploying a directory that ends with a slash, for example `/Users/styfle/Code/myapp/` instead of the usual `/Users/styfle/Code/myapp`.
This never affected `now-cli` until we added support for defining the `rootDirectory` which allows the user to type whatever they wish in the Project Settings.
The fix is to use `path.relative()` instead of substring.
The combination of file renaming and brackets doesn't work well for go build so we need to add the file extension back before building.
I also simplified the `.now/cache/folder` logic because it should be the same whether `builds` is defined or not (aka zero config).
The combination of file renaming and brackets doesn't work well for python imports so we need too add the file extension back before importing the python module.
I also simplified the `.now/cache/folder` logic because it should be the same whether `builds` is defined or not (aka zero config).
This updates to not pass segments already used in a redirect's destination query since these values are most likely unwanted and can still be manually added if desired. This change does not affect rewrites and we still pass through all segments in the query
This adds handling for treating `pages/404.js` as the custom error page in Next.js to allow for more flexible auto static optimization on the 404 page. This makes sure we handle `pages/404.js` being a lambda due to `_app` having `getInitialProps` and also makes sure that visiting `/404` doesn't respond with a 200 status code
~We can add tests for this behavior after the below PR has been released in a canary of Next.js~
x-ref: https://github.com/zeit/next.js/pull/10329
x-ref: https://github.com/zeit/next.js/pull/10593
Bumps [codecov](https://github.com/codecov/codecov-node) from 3.1.0 to 3.6.5.
<details>
<summary>Release notes</summary>
*Sourced from [codecov's releases](https://github.com/codecov/codecov-node/releases).*
> ## v3.6.4
> Fix for Cirrus CI
>
> ## v3.6.3
> AWS Codebuild fixes + package updates
>
> ## v3.6.2
> command line args sanitised
>
> ## v3.6.1
> Fix for Semaphore
>
> ## v3.6.0
> AWS CodeBuild
> Semaphore v2
>
> ## v3.3.0
> Added pipe `--pipe`, `-l`
</details>
<details>
<summary>Commits</summary>
- See full diff in [compare view](https://github.com/codecov/codecov-node/commits)
</details>
<details>
<summary>Maintainer changes</summary>
This version was pushed to npm by [drazisil](https://www.npmjs.com/~drazisil), a new releaser for codecov since your current version.
</details>
<br />
[](https://help.github.com/articles/configuring-automated-security-fixes)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `@dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/zeit/now/network/alerts).
</details>
When testing, you can set `NOW_BUILDER_DEBUG=1` to print verbose logs from builders.
However, this was causing some tests to fail that depended on a build environment variable.
This PR fixes the assignment so that it preserves the environment variables from the tests by adding `NOW_BUILDER_DEBUG` instead of replacing.
This handles an edge case where deeply nested dynamic routes were handling `_next` 404s that were cached forever since the immutable header we set isn't cleared after not matching on the filesystem.
I updated our cache-header fixture to check for this edge case also to make sure we don't regress on this
Some users wish to put all Go related code in the `/api` directory and the root is reserved for a frontend framework.
This PR adds support for `/api/go.mod` which will act the same as `/go.mod` by moving the file to the root.
This adds support for using the fallback file for dynamic (lazy) SSG pages to allow showing a loading state while the cache is populated with data. We can add tests for this behavior once the below referenced PR is shipped on canary
x-ref: https://github.com/zeit/next.js/pull/10424
~Update: added tests now that fallback support has landed in Next.js although it appears `now-proxy` might need to be updated to revalidate the fallback correctly since the initial fallback is always being shown for lazy SSG pages with these changes~
Looks like this is working properly in `now-proxy` and we were overriding the prerender output with the static page output, thanks @juancampa for helping investigate! 🙏
Previously, `@now/go` would fail when using [Path Segments](https://zeit.co/docs/v2/serverless-functions/introduction#path-segments) since `go build` [doesn't support](https://stackoverflow.com/q/60140859/266535) files that begin with square bracket.
This PR changes the build logic so that the entrypoint file is renamed if if begins with a square bracket.
The output file is not renamed because v3 builders can't rename outputs which works great for this feature.
This adds initial support for Windows in GitHub Actions CI tests.
There is still work to be done to prevent certain tests from hanging in CI so those are skipped for now.
We used to require a `package.json` but we have since introduced [Advanced Project Settings](https://zeit.co/blog/advanced-project-settings) which will ask the user for a build command during the first deploy.
Updates go to the latest version 1.13.7 (https://golang.org/doc/devel/release.html#go1.13). This allows users to use the new error functionality that was introduced in go 1.13 (https://blog.golang.org/go1.13-errors) and also includes a couple of security fixes.
Looking at the last PR that updated the version (https://github.com/zeit/now-builders/pull/247/files) this should be as simple as updating the version number.
P.S. I tried to follow the contribution guidelines, but `yarn lint` fails with `exit code 1`/`295 problems (33 errors, 262 warnings)` and `yarn test` returns `error Command "test" not found` on master. But `yarn test-unit` shows no errors.
* [now-cli] Consider root directory for now.json
* Adjust message check in test
* Fallback if config does not exist as well
* Assign localConfig later and add debug
* Prefere now.json from root directory
* Comment
* Adjust test and add warning
This fixes a regression from #3749 where the PORT env var was removed. This is necessary so frameworks like create-react-app and gatsby can proxy to `now dev`.
Fixes#3761
Previously, the changelog script was looking for the last "Publish Stable" commit, but it should really be looking for the last Stable release of Now CLI.
This PR updates the changelog script so that it fetches the latest GH Release (which should be Now CLI) and then compares that to the HEAD.
This PR changes the behavior of `trailingSlash: true` after we received feedback that files should not be redirected with a trailing slash. This matches the behavior of `serve` and `serve-handler`.
### Examples
* `/index.html` => serve
* `/assets/style.css` => serve
* `/assets` => redirect to `/assets/`
* `/assets/style` => redirect to `/assets/style/`
### Additional
In order to avoid duplicate content, this PR also adds redirects to files without a trailing slash.
* `/about.html/` => redirect to `/about.html`
* `/assets/style.css/` => redirect to `/assets/style.css`
Fixes#3731
* use npx when available
* add --no-install
* replace $PORT and %PORT% in devCommand
* remove PORT from env variables
* replace more than one $PORT or %PORT%
* fix regex
The Hugo theme was lost when transferring from `zeit/now-examples` to `zeit/now`.
This PR fixes the `.gitignore` file to include the `dist` directory and override our root `.gitignore`.
* do not prompt for root directory when linked
* run tests
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Leo Lamprecht <mindrun@icloud.com>
Typically, Go tests are side-by-side with their source files in a `_test.go`.
The Go documentation says the following:
> To write a new test suite, create a file whose name ends _test.go that contains the TestXxx functions as described here. Put the file in the same package as the one being tested. The file will be excluded from regular package builds but will be included when the “go test” command is run. [View Docs](https://golang.org/pkg/testing/)
This PR excludes the test files from being turned into Serverless Functions.
This PR is a follow up to #3703 which fixes file output renaming on initial boot but not when files are added or removed while `now dev` is running. This PR fixes that behavior.
Fixes GH pull request auto-lint:
> #### Check warning on line 2 in `packages/now-cli/src/util/input/input-root-directory.ts`:
>
> ## GitHub Actions / Unit Tests (ubuntu-latest, 12)
>
> `packages/now-cli/src/util/input/input-root-directory.ts#L2`
>
> ```
> 'fs' is defined but never used
> ```
This PR adds a `config.excludeFiles` pattern for `@now/python` that defaults to `node_modules/**` for users who are using a Node.js SSG frontend with Python APIs backend.
If the user chooses, they can override to any glob pattern such as `{.cache,node_modules}/**`.
Related to #2830
Related to #3416
There was a bug where python src files were being renamed when it really should be the output files only.
This is a tricky bug because production deployments build all files first and then perform routing. So we simply rename lambda outputs with prod deployments. But `now dev` matches a request URL to a build before performing the build lazily so we have to rename source files.
The solution is to add both the original file name and the renamed file name in the `files` map so that it matches correctly but `zeit/fun` will still copy the original source files in the output correctly.
Routing will match on the extensionless file, the builder will use the file with extension (it doesn't know about file renaming), then the build results in a lambda output which is renamed to extensionless.
I added a test for `@now/python` and updated the `@now/bash` test.
Fixes#3638
* [now-cli] Add support for the `rootDirectory` property
* Only check if rootDirectory exists
* Add test
* Support now dev
* Use defaults
* Comment
* Normalize the path input
* Adjust test
* Remove .only
* Adjust more tests
* Adjust test
* Fix test
* Remove unused import
* Update packages/now-cli/src/util/validate-paths.ts
Co-Authored-By: Luc <luc.leray@gmail.com>
* Run check on normalized path
* Add more checks
* Change error message
* Use basename as prefix
* Use correct path when linking
* Update packages/now-cli/src/util/input/input-root-directory.ts
Co-Authored-By: Luc <luc.leray@gmail.com>
Co-authored-by: Luc <luc.leray@gmail.com>
* [tests] Run unit tests on ubuntu and macos
* Add back Node 10 for Now CLI Tests
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This enables case sensitive rewrites and redirects. It also changes the delimiter to `/` to match Next.js.
Unlike `routes` which were case insensitive, `rewrites` and `redirects` are case sensitive.
In the future, we may wish to add an option to toggle the sensitivity.
* use .now scope for commands
* add cache to getUser
* add cache on getTeams
* add cache for link
* refactor
* add error if NOW_ORG_ID is missing
* remove link cache
* refactor
* fix whoami
* add tests
* move fetching scope/org after subcommand condition
* Update packages/now-cli/src/util/projects/link.ts
Co-Authored-By: Andy <AndyBitz@users.noreply.github.com>
* remove userId from global scope
* show team and user in whoami command
* reset whoami
* Revert "move fetching scope/org after subcommand condition"
This reverts commit d145e6164074fe2442178cd8fafbeb225c978b9c.
* remove `client` from main scope
* tests adjustments
* adjust tests
* adjust tests (bis)
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This PR changes the behavior so that `:segment` in the `source` is always added to the query string unless the `destination` query string already contains a key with the same name.
* deprecate uploading files instead of erroring
* fix misc bugs
* remove final `.`
* add test
* check .now folder does not exist in test
* clean up after test
Deployments no longer support Node 8 since reaching EOL so we can also drop all of the special casing used to support Node 8 in Now CLI and Now Client.
The `tsconfig.json` has been updated to ES2018 per [Node-Target-Mapping](https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping).
* Checkout master on master
* Check if checkout works
* Revert "Check if checkout works"
This reverts commit 66f712a43edfb938c551110c214661e4a920b492.
* Revert "Checkout master on master"
This reverts commit 41b6eab926474830629e758a51e7cfdd1947bdf2.
* Use --depth=10
* Add another fetch
* Initial Build step
* Typo
* Remove circleci config
* Fix command
* Change Node version
* Add unit tests
* Use artifact
* Fix workflow file
* Remove node_modules
* Remove .git
* Do not upload files
* Checkout master branch
* Use git fetch
* Add now-dev tests
* Fix workflow file
* Use node10 for building
* Use node12 for building
* Download Hugo before building
* Fetch master branch
* Do not cancel other jobs when one fails
* Add all tests
* Remove needs
* Add build step
* Move test up
* Use isCanary function and remove tests
* Update Publish workflow
* Update .github/workflows/continuous-integration.yml
Co-Authored-By: Steven <steven@ceriously.com>
* Specify more events
* Add publish.sh script
* Remove Node8
Co-authored-by: Steven <steven@ceriously.com>
* [now-client][now-cli] Remove builds check from now-client
* [now-client] Adjust README and change version
* Change events and adjust build error
* Use message from error
* Update packages/now-cli/src/util/deploy/process-deployment.ts
Co-Authored-By: Luc <luc.leray@gmail.com>
* [now-cli] Rename event
* Make types more consistent
* Fix type in process-legacy-deployment
* Adjust type in test
* Update type
* Make events type simpler
Co-authored-by: Max <8418866+rdev@users.noreply.github.com>
Co-authored-by: Luc <luc.leray@gmail.com>
This PR a regression when path segments are used in the query string.
Take a look at the following ASCII Table for why I had to delete certain parts of the parsed url before formatting again.
https://nodejs.org/api/url.html#url_url_strings_and_url_objects
Related to #3539
This adds support for `headers` in custom-routes which was landed in Next.js.
This also updates `@now/routing-utils` `convertHeaders` to call `sourceToRegex` to match behavior with Next.js and allow using `segments` to match in the header `source` as not being able to use the same syntax for a header `source` as a `redirect` source could get confusing
This is required to match custom-routes behavior in Next.js by checking dynamic routes after each rewrite although is currently blocked on `now dev` also supporting the feature
This reverts commit 0da98a7f5d.
- [x] Add tests from now-proxy for `handle: miss`
- [x] Add tests from now-proxy for `handle: hit`
- [x] Add file output renaming when `featHandleMiss` is true (also assign true for now dev)
This adds initial support for static 404 pages when enabled for Next.js applications > `9.2.1-canary.3` it also disables tracing/logging related to lambdas when there aren't any lambdas besides the `_error` when a static 404 is being used
Closes: #3368
I was getting errors when running `yarn build` locally because the public directory already exists.
This will make sure the public directory is deleted before generating it again.
This adds `permanent: boolean` to the redirects in the custom-routes tests for `@now/next` since this field is required for redirects in Next.js in the latest version
unblocks: https://github.com/zeit/now/pull/3613
This PR adds `NOW_PROJECT_ID` and `NOW_ORG_ID` environment variables as a way to specify a project to deploy to when running `now`.
eg.
```
NOW_ORG_ID=abc NOW_PROJECT_ID=123 now
```
When using these environment variables:
- the folder is not linked to the project (ie. no `.now` is created)
- we interrupt the process and show an error message if the project is not found:

Since v2 deployments are auto-assigned aliases, render as such to match more closely to the v2 pipeline when a static deployments was implicitly upgraded to the v2 platform.
* [api] Add Sentry
* Use function name
* Add test error
* Revert "Add test error"
This reverts commit 39cf8a61dad9fcdcb616e418a0deb6ffe9e04ea9.
* Revert "Revert "Add test error""
This reverts commit c718f201da9d80743319ac87e0d4560e718fff53.
* Add logging
* Revert "Add logging"
This reverts commit 39cd46c8bbeef9024e71fe70478068480a51545b.
* Revert "Revert "Revert "Add test error"""
This reverts commit e6f63ee21fabb4ac8fc065b74281dbcdf5811216.
* Ignore .env
* Use init function for Sentry inline
* Print warnings / notices from the API
* Print `v2` instead of `v1` when upgraded to v2
* Wait for "alias-assigned" event in v1 pipeline when upgraded to v2
This PR updates the framework auto-detection flow in `deploy` command to not show "overwrite project settings?" prompt when the API returns a `framework` property that is `null`.
In a previous release, we pinned the node version to the project so that we could upgrade new projects to a newer version of Node.js while maintaining backwards compatibility with existing projects.
This puts some burden on the user when they're deployment is a year old and their pinned version of Node reaches EOL. Because we currently force the user to add a package.json.
This PR changes the behavior so projects are no longer pinned. Instead, newer deployments get the latest Node unless they opt-in and pin via package.json.
* fix "in your organization"
* add feedback link to canary version prompt
* `Detecting framework` -> `Setting up project`
* "Auto-detect project settings (<framework>)"
* "What’s your project’s name?"
* ✅ -> ☑️
* "organizations" -> "scope"
* always show feedback prompt for `now dev`
* dim feedback prompt
* [now-build-utils] Error for unused `functions`
* Update packages/now-build-utils/src/detect-builders.ts
Co-Authored-By: Steven <steven@ceriously.com>
Co-authored-by: Steven <steven@ceriously.com>
This behavior is legacy from the very early days of `now dev`
(before the `files` array was returned from Runtimes) and adds
complexity. We can remove it at this point to simplify dev server.
Co-authored-by: Andy <AndyBitz@users.noreply.github.com>
Co-authored-by: Leo Lamprecht <mindrun@icloud.com>
* Revert "[frameworks] Fix import in test (#3570)"
This reverts commit 9ee86df69d.
* Revert "[frameworks] Rename frameworks to now-frameworks (#3569)"
This reverts commit daa5cbdd4b.
This PR fixes an issue where certain patterns caused `path-to-regexp` to throw when it should be returning an error object. The fix is to make sure all inputs work properly with `path-to-regexp` before continuing.
While migrating redirects on `/docs` I noticed we don't update segments in the `hash` of the destination. This updates to also handle these segments and adds a test for this behavior
* Add API for frameworks and examples
* Adjust headers
* Update frameworks list
* Always use latest
* Add types
* Use now repo for downloading and listing
* Use .existsSync
* Remove unused packages
* Use 307 for redirect
* Add examples
* Update tsconfig.json
Co-Authored-By: Steven <steven@ceriously.com>
* Make examples unique
* Remove detectors from frameworks API
* Use /api instead of Next.js
* Install dependencies
* Rename project
* Change name
* Empty
* Change name
* Update api/tsconfig.json
Co-Authored-By: Steven <steven@ceriously.com>
* Update examples
Co-authored-by: Steven <steven@ceriously.com>
This PR will use the system installed version of Node.js and avoid printing a warning or error if a discontinued version is selected.
This optimization was already in `@now/node` but for some reason it was never add to `@now/next`.
The reason why its relevant today is because the warnings turned into errors due to Node 8 deprecation and we don't have the "Project" in `now dev` so we don't know which version of node to select.
So instead of determining the version, `now dev` will always use `node` in the PATH and avoid printing warnings or errors. This also results in less FS reads since we no longer need to read package.json.
There was a regression with framework detection that was preferring the frameworks output directory instead of the `distDir` defined in the `@now/static-build`.
The fix is to only run framework detection when `builds` is not defined (ie zero config).
Related to https://github.com/Ebury/chameleon/pull/63
This extends the behavior of `featHandleMiss: true` flag to do the following:
- Reduce zero config API routes so that only dynamic path segment files (`api/[id].js`) get a route.
- Remove zero config out directory route (`public/`)—the files will be renamed instead.
- Use redirects for API routes when `cleanUrls: true` and use rewrites when `cleanUrls: false` from extension to the extension-less file.
- Normalize existing routes to begin with `^` and end with `$`.
This PR does the following
- Add and export class, `NowBuildError`, that can be thrown to stop the build and print an error but it will not print a stack trace.
- Improve logic for discontinued node versions and add more tests
- Remove hack (#3425) for undefined TERM, fixed by updating dependencies
- Rename `silent` variable to `isAuto` which means the node version was automatically selected, not defined in `package.json`
- Rename `test` deployments to `test2020` so that a fresh project is created with latest Node.js 12.x
We want to take advantage of the better defaults and retry policies (among others).
This bumps `@zeit/fetch` and replaces `node-fetch` with `@zeit/fetch` in `now-client`.
Also update retry policy for "uploading" files to:
- base 10ms
- 5 retries
- factor 6
which means the timeouts are 10, 60, 360, 2160, 12960
This PR does a few things:
1. Add functions `getLatestNodeVersion()` and `getOldestNodeVersion()` for use in api-project.
2. Add property `config.nodeVersion` which has precedence over default Node 8.
We want new projects to use the latest node version without setting any configuration but we don't want to break old projects. So during project creation, the value of `getLatestNodeVersion()` will be saved and then each deployment of that project will assign that value to `config.nodeVersion`.
Implements [PRODUCT-837]
[PRODUCT-837]: https://zeit.atlassian.net/browse/PRODUCT-837
This implements `{ handle: 'miss' }` which will allow more efficiently checking dynamic routes after a matching rewrite. This is not fully available in production yet and the tests will fail for this PR until it is ready in Now
x-ref: https://github.com/zeit/next.js/pull/9568
This handles the new `routes-manifest` version in the latest canary of Next.js since we throw an error if the version isn't handled by `@now/next`
unblocks: https://github.com/zeit/now/pull/3481
Bumps [handlebars](https://github.com/wycats/handlebars.js) from 4.1.2 to 4.5.3.
<details>
<summary>Changelog</summary>
*Sourced from [handlebars's changelog](https://github.com/wycats/handlebars.js/blob/master/release-notes.md).*
> ## v4.5.3 - November 18th, 2019
> Bugfixes:
>
> - fix: add "no-prototype-builtins" eslint-rule and fix all occurences - f7f05d7
> - fix: add more properties required to be enumerable - 1988878
>
> Chores / Build:
> - fix: use !== 0 instead of != 0 - c02b05f
> - add chai and dirty-chai and sinon, for cleaner test-assertions and spies,
> deprecate old assertion-methods - 93e284e, 886ba86, 0817dad, 93516a0
>
> Security:
>
> - The properties `__proto__`, `__defineGetter__`, `__defineSetter__` and `__lookupGetter__`
> have been added to the list of "properties that must be enumerable".
> If a property by that name is found and not enumerable on its parent,
> it will silently evaluate to `undefined`. This is done in both the compiled template and the "lookup"-helper.
> This will prevent new Remote-Code-Execution exploits that have been
> published recently.
>
> Compatibility notes:
>
> - Due to the security-fixes. The semantics of the templates using
> `__proto__`, `__defineGetter__`, `__defineSetter__` and `__lookupGetter__` in the respect that those expression now return
> `undefined` rather than their actual value from the proto.
> - The semantics have not changed in cases where the properties are enumerable, as in:
>
> ```js
> {
> __proto__: 'some string'
> }
> ```
>
> - The change may be breaking in that respect, but we still only
> increase the patch-version, because the incompatible use-cases
> are not intended, undocumented and far less important than fixing
> Remote-Code-Execution exploits on existing systems.
>
>
>
> [Commits](https://github.com/wycats/handlebars.js/compare/v4.5.2...v4.5.3)
>
> ## v4.5.2 - November 13th, 2019
> # Bugfixes
>
> - fix: use String(field) in lookup when checking for "constructor" - d541378
> - test: add fluent API for testing Handlebars - c2ac79c
>
> Compatibility notes:
> - no incompatibility are to be expected
></tr></table> ... (truncated)
</details>
<details>
<summary>Commits</summary>
- [`c819c8b`](c819c8b533) v4.5.3
- [`827c9d0`](827c9d0747) Update release notes
- [`f7f05d7`](f7f05d7558) fix: add "no-prototype-builtins" eslint-rule and fix all occurences
- [`1988878`](1988878087) fix: add more properties required to be enumerable
- [`886ba86`](886ba86c2f) test/chore: add chai/expect and sinon to "runtime"-environment
- [`0817dad`](0817dad7e7) test: add sinon as global variable to eslint in the specs
- [`93516a0`](93516a0b07) test: add sinon.js for spies, deprecate current assertions
- [`93e284e`](93e284ed9b) chore: add chai and dirty-chai for better test assertions
- [`c02b05f`](c02b05fa81) fix: use !== 0 instead of != 0
- [`8de121d`](8de121d21c) v4.5.2
- Additional commits viewable in [compare view](https://github.com/wycats/handlebars.js/compare/v4.1.2...v4.5.3)
</details>
<br />
[](https://help.github.com/articles/configuring-automated-security-fixes)
Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `@dependabot merge` will merge this PR after your CI passes on it
- `@dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `@dependabot cancel merge` will cancel a previously requested merge and block automerging
- `@dependabot reopen` will reopen this PR if it is closed
- `@dependabot ignore this [patch|minor|major] version` will close this PR and stop Dependabot creating any more for this minor/major version (unless you reopen the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
- `@dependabot use these labels` will set the current labels as the default for future PRs for this repo and language
- `@dependabot use these reviewers` will set the current reviewers as the default for future PRs for this repo and language
- `@dependabot use these assignees` will set the current assignees as the default for future PRs for this repo and language
- `@dependabot use this milestone` will set the current milestone as the default for future PRs for this repo and language
You can disable automated security fix PRs for this repo from the [Security Alerts page](https://github.com/zeit/now/network/alerts).
</details>
There is an undocumented feature that adds a route when a single file is deployed, for example a single image or a zip file. This was causing the legacy routes to be added even when `rewrites` or `redirects` was defined. This PR fixes that case when the user has a single file, `now.json`, with redirects defined.
* [now-build-utils] Only add 404 route when there are no api routes
* Fix startWith
* Update packages/now-build-utils/src/detect-routes.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Import isHandler
Co-authored-by: Steven <steven@ceriously.com>
This PR adds the route `handle: miss` and a catch-all route for the api directory.
The plan is to rename files in `/api` and `/public` (in a future PR) to be extension-less and then the route is only used to rewrite the extension to the extension-less file (for example, `/api/user.go` => `/api/user`)
This reduces the routes needed for zero config (previously N routes for N files down to 1 route for N files).
This PR deletes the incorrect `Route` type defined in `@now/build-utils` and instead relies on the correct type defined in `@now/routing-utils`. There is no change to runtime code since this is strictly a change to the typescript types. The one exception to this is I had to change the sort order for our build script so that `@now/routing-utils` is built first.
This is necessary for PR #3403
This makes sure to replace multi-match characters used in `path-to-regexp` when converting redirects.
Fixes `/:path*/` being converted to `/$1*/` and now converts it to `/$1/`
As requested by @timneutkens after investigating we're disabling auto running `next export` for the user during a build since most users who want their app exported will define `next export` in their `build` script
* Adjust README
* Fix now-dev test
* Add hugo to the PATH
* Fix Hugo build
* Add more logging
* Resolve path
* Do not use the build script as dev command
* Update yarn.lock file
* fetch with retry
* Remove sh from README
* Use Set for Hugo config files
* Revert "Revert "[now-static-build] Add support `buildCommand`, `devCommand` and `outputDirectory` (#3422)" (#3428)"
This reverts commit f7b4dd4458.
* Handle generic node projects with /public
* Remove .only
* Ensure node_modules/.bin is also available during `now dev`
* Remove config log
* Adjust test
* Fix integration tests
* Fix public check
* Remove build + public
* Remove _scan
* Remove any casting
* Use `spawnCommand` for dev
* Remove unused import
* Remove cross-spawn
* Fix null config
* Fix build
* Only do a single Buffer.concat
Follow up to #3431 adding tests for this behavior
Tests to add:
- [x] custom routes: redirects
- [x] custom routes: rewrites
- [x] confirming each test is actually a `next export` deploy somehow
* [now-static-build] Handle `buildCommand`, `devCommand` and `outputDirectory`
* Adjust tests
* Swap order
* Add `node_modules/.bin` to PATH
* Remove @types/execa
* Append PATH only to spawn options
* Remove test check
* Only add when there is a command
This PR reduces the time running Circle CI tests.
Since creating the monorepo in #2812, the coverage broke and then was fixed in #2876 with a workaround which would run unit tests twice.
More recently, we enabled Now CLI to always run tests in #3305 so that means coverage data is always generated.
This PR is a final proper fix so that unit tests run once which saves approximately 2 minutes per push (CI workflow).
We used to have a default `maxLambdaSize` and allow the user to increase to 50 MB.
However, this is no longer true. Today, the `maxLambdaSize` for every function is 50 MB and is not configurable, it's a hard limit.
This PR removes the dead link to avoid confusion like in Issue #3416.
* [now-build-utils] Consider `yarn build` and `npm run build` as `buildCommand`
* [@now/build-utils] Update new detectors
* Update unit tests
* [@now/build-utils] Update detect-builder and detect-routes
* Update tests
* Run prettier
* Add more tests
* [now-cli] Use default detectors
* Add now-dev test
* Add a generic node project fallback
* Fix build
* Use public as default
* Ensure generic node project is last
* Update tests
* Update tests again
* Update packages/now-build-utils/src/detectors/filesystem.ts
Co-Authored-By: Nathan Rajlich <n@n8.io>
* Remove parentheses
* Revert "Remove parentheses"
This reverts commit 03f9aba07b0a6d4088719ca9afd602ce8fb1e9c1.
* Use getDependencyVersion instead of hasDependency
* [@now/build-utils] Add functions schema
* [now-cli] Use functions schema from build-utils
* Move buildsSchema to build-utils
* Add retries to test
* Add await
Follow up to #3408 .
```
> Error! Checking for updates failed
> Now CLI 16.6.3 dev (beta) — https://zeit.co/feedback/dev
> Error! Invalid `functions` property: ['api/test.js'] should NOT have additional properties
```
This PR adds a `discontinueDate` to Node 8 and prints a warning if the current deployment is using it.
```
┌──────────────────────────────────────────────────────────────────────────────────────────────┐
│ │
│ WARNING │
│ │
│ Node.js 8.10.x will be discontinued on 2020-01-06. │
│ Deployments created on or after 2020-01-06 will fail to build. │
│ Please use one of the following supported `engines` in `package.json`: ["12.x","10.x"] │
│ This change is a result of a decision made by an upstream infrastructure provider (AWS). │
│ Read more: https://docs.aws.amazon.com/lambda/latest/dg/runtime-support-policy.html │
│ │
└──────────────────────────────────────────────────────────────────────────────────────────────┘
```
Starting January 2020, Node 8 deployments will fail to build and print an error.
```
Found `engines` in `package.json` with an unsupported Node.js version range: 8.10.x
Please use one of the following supported ranges: ["12.x","10.x"]
```
[PRODUCT-796]
[PRODUCT-796]: https://zeit.atlassian.net/browse/PRODUCT-796
Before, the debug log message "Downloading user files..." was copy+pasted to all the builders.
This change centralizes that log message to be inside the `download()` function for consistency and DRY purposes.
Additionally, the wording has changed as per [INFRA-289], and a resulting timestamp message is also printed.
[INFRA-289]: https://zeit.atlassian.net/browse/INFRA-289
Before this change, in `@now/next` when running via `now dev`,
the runtime env vars get passed to the child `dev-server.js`
process via argv.
This is problematic because it causes the env vars to be visible in
the process listing, and also causes the command itself to be very
large.
In some cases, with a lot of env vars, we've seen the command be too
large and it will fail to spawn (https://serverfault.com/a/163390/294389).
This changes the start-up process such that the env vars are passed
in via Node.js `fork()` IPC, rather than via `argv`.
Saw my `pre-commit` hook wasn't being triggered after running `yarn` and noticed it was due to an un-used `pre-commit` dependency in `now-cli` overriding the changes to my `.git/hooks/pre-commit` file done by `husky`
**Note**: you will probably need to run `yarn install --force` after this is applied before the correct `pre-commit` changes are applied by `husky`
We've shut down our Typeform for feedback, so we can simply the feedback link. The old one will continue working, but we should start using the new one.
Pending on https://github.com/zeit/front/pull/5874.
Fixes#3377
The lock files should not be cached because the user may wish to make a new deployment without a `yarn.lock` or `package-lock.json`.
This recently started causing problems because of the order of downloading cache changed from before user files to after user files.
So we need to be extra careful to only cache outputs and not source files.
This PR will reduce deployment time when a `package-lock.json` file is found by avoiding the audit step which usually [sends audit reports](https://docs.npmjs.com/cli/audit#description) to the registry.
The [--no-audit](https://docs.npmjs.com/cli/install) flag was introduced in [npm@6](
https://medium.com/npm-inc/announcing-npm-6-5d0b1799a905) which shipped with Node 10. However, using the flag with npm@5 does not do anything which is great because npm@5 doesn't audit. So this PR is backwards compatible.
### Performance
I tried `npm install` and `npm install --no-audit` with a large project, [StateOfJS](a9fa6d47f9/homepages/stateofjs), which has 2206 packages (audited 21778 packages).
I made sure to `rm -rf node_modules` each time and ran both commands 5 times to make sure it was always faster with `--no-audit`.
- Before: 61 seconds
- After: 49 seconds
Since we switched to a single branch (instead of master/canary), lerna gets confused about which packages to publish because stable and canary releases are in the same branch.
This PR fixes the confusion by looking at the git history and using [--force-publish](https://github.com/lerna/lerna/tree/master/commands/version#--force-publish) on the changed packages.
In order to avoid confusion for the person publishing, I removed the `yarn publish-stable` script in favor of `yarn changelog` which will print the change log and emit a script that can be used to publish stable.
<details><summary>View Example Output</summary>
<p>
```
$ yarn changelog
yarn run v1.19.1
$ node changelog.js
Changes since the last Stable release (21fe0a2):
- [now-cli] Change `--debug` to avoid debugging builders (#3386) [Steven]
- [now-next] Update routes for new check: true behavior (#3383) [JJ Kasper]
- [now-build-utils] Update Detectors API (#3384) [Nathan Rajlich]
- [now-client] Bump version (#3385) [Andy]
- [now-client] (Major) Split `now-client` options (#3382) [Andy]
- [now-cli][now-client] Fix user agent (#3381) [Steven]
- [now-client] Fix `main` in package.json (#3344) [Max]
- [now-build-utils] Change `script` to `scripts` in error message (#3376) [Andy]
- [now-cli] Add support for `check: true` routes in `now dev` (#3364) [Steven]
- [now-cli] Fix preinstall script on windows when `LOCALAPPDATA` is missing (#3365) [Steven]
- [now dev] skip installing already installed versioned runtimes (#3354) [Tommaso De Rossi]
- [now-routing-utils] Update `path-to-regexp` to v6.1.0 (#3361) [Steven]
- [now-routing-utils] Add mergeRoutes function (#3358) [Steven]
- [docs] Remove deprecated LambdaRuntimes (#3346) [Steven]
- [now-routing-utils] Add support for `check: true` (#3343) [Steven]
- [now-static-build] Cache `.cache` folder for gatsby deployments (#3260) (#3342) [Luc]
To publish a stable release, execute the following:
git pull && lerna version --message 'Publish Stable' --exact --force-publish=@now/build-utils,now,now-client,@now/next,@now/routing-utils,@now/static-build
```
</p>
</details>
* [now-cli] Remove `github` property from payload before sending it
* Add test and remove unused one
* Remove .only
* Remove unused fixture
* Use correct github properties
Since switching to a single branch, each package in the monorepo can be independently versioned so that some packages are using a canary version and others using a stable version.
This PR fixes an issue where a canary version of `now-cli` is bundling a stable version of `now-client` and thus does does not deploy zero config using canary builders.
The solution is to pass the User Agent from `now-cli` to `now-client` in a new option.
A nice side-effect of this PR is that we will switch the User Agent back to what it used to be pre-now-client days. It will look something like `now 16.6.1-canary.0 node-v10.17.0 darwin (x64)`.
This PR adds `now dev` support for routes that define `check: true`.
The algorithm is as follows:
- If a matching `dest` file is found, then serve it
- If a matching `src` file is found, then serve it
- Otherwise, behave the same as `continue: true` and continue processing routes
Fixes#3353
The current solution might break if a user interrupts `now dev` while yarn wrote the package in the cache package.json but has not yet added to node_modules.
This happens in like 20 ms but is possible, so we could execute `yarn` every time to be sure.
Tell me if the above is a problem or not
This moves the merging logic to `@now/routing-utils` and adds support for `check: true`.
- Builder before filesystem, continue: true
- User before filesystem
- Builder before filesystem, check: true
- Builder before filesystem, continue: false
- Handle filesystem
- Builder after filesystem, continue: true
- User after filesystem
- Builder after filesystem, check: true
- Builder after filesystem, continue: false
Apply 77348ea71e again.
> Adds `.cache` folder to the Now cache for Gatsby deployments.
> Also adds a generic optional `cachePattern` property to the frameworks array so we can optimize cache paths for other frameworks in the future.
Fixes a confusing error message.
<details>
<summary>Click to view error message</summary>
<pre>> Ready! Available at http://localhost:3000
> Building @now/node:index.js
Installing dependencies...
Running "yarn run now-build"
yarn run v1.17.3
error @: The engine "node" is incompatible with this module. Expected version "10.x". Got "12.13.1"
error Commands cannot run with an incompatible environment.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
Error: Exited with 1
at ChildProcess.<anonymous> (/Users/styfle/Library/Caches/co.zeit.now/dev/builders/node_modules/@now/node/dist/index.js:78518:24)
at ChildProcess.emit (events.js:210:5)
at ChildProcess.EventEmitter.emit (domain.js:475:20)
at maybeClose (internal/child_process.js:1021:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5) {
message: 'Exited with 1'
}</pre>
</details>
The `--ignore-engines` flag was added to `yarn install` many months ago but not `yarn run`.
This PR adds the flag to `yarn run`.
This is useful in `now dev` when the user might have a different Node version installed than what is specified by `engines` in `package.json`.
Reverts #3311
Previously, we thought we were going to use version 4 to support builder rewrites/redirects => routes. But that is no longer necessary. So instead version 4 will be builders that accept multiple file entrypoints.
Until v4 can be implemented, this reverts v4 changes.
Additionally, I added a helpful error message when the CLI does not support the builder version. In a future PR, we will add better version locking to avoid this type of version mismatch.
We expect `now@canary` to use canary builders. This PR fixes a bug where a zero config deployment was selecting `@now/static-build` instead of `@now/static-build@canary`.
Fixes#3334.
```
$ node ~/now-cli/dist/index.js --token $'he˚ll,o\n'
> Error! You defined "--token", but its contents are invalid. Must not contain: "\n", ",", "˚"
> More details: https://err.sh/now/invalid-token-value
```
Renames `test/unit.test.detectors.ts` -> `test/unit.detectors.test.ts`
and adjusts npm `test-unit` command.
Jest only runs tests for files that end in `*.test.ts` or `*.test.js`.
* [now-build-utils] Add framework detector functions
As described in [PRODUCT-399]. This is similar in nature to the
current framework detection logic in static-build, however the detectors
are now functions which allow for detection of frameworks without
a `package.json` file (i.e. jekyll), and also includes detection of
build and dev commands for use in project settings.
* Dedup `aggregate-error` dep in yarn.lock
* Simplify `hasDependency()`
* Adjust hugo detect logic
* Add "jekyll" detector
* Add "next" detector
* Optimize "gatsby" detector
Check the `package.json` first
* Add optimization to check "package.json" based detectors first
They're by far the most common and only rely on checking the single
`package.json` file. If no pkg-based detector succeeds then the non-pkg
detectors are consulted afterwards.
* Add "vue" detector
* Add "angular" detector
* Add "polymer" detector
* Add "svelte" detector
* Add "create-react-app-ejected" detector
* Add "gridsome" detector
* Add "umi" detector
* Add "sapper" detector
* Add "saber" detector
* Add "stencil" detector
* Add CRA ejected commands
* Add "brunch" detector
* Add "middleman" detector
* Add missing commands
* `buildCommand` is required
* Add initial unit tests
* Fix unit tests on Circle
* Move "jest" and "ts-jest" to the root of the monorepo
* Fix integration tests
* Fix test again
* Update packages/now-build-utils/src/detectors/middleman.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Move `@types/jest` to root level package.json
* Update packages/now-build-utils/src/detectors/ember.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Add `cachePattern`
* Address PR comments
* Add missing `$PORT` entries for devCommands
* Add `firstTruthy()` tests
* Revert some changes
Maybe it fixes CI build?
* Test remove `yaml` module
* Update packages/now-build-utils/src/detectors/next.ts
* Remove `toml`
* Test out "@iarna/toml" module
* Fix build
* Test out "js-yaml" module
* Add new routing properties
* Rename `test/unit.test.ts` to `test/unit.test.detectors.ts`
* Remove `@types/yaml`
Converts `reportError()` to typescript and adds an ignore list.
In particular, `uv_cwd` comes from `process.cwd()` so we don't need to track these errors in the case the user deletes their current working directory.
This is a follow up to #3194 which handled only one scenario.
* [now-build-utils] Ensure function paths are relative to the project and improve the error message
* Update packages/now-build-utils/src/detect-builders.ts
Co-Authored-By: Steven <steven@ceriously.com>
* Update packages/now-build-utils/src/detect-builders.ts
Co-Authored-By: Steven <steven@ceriously.com>
- Add now dev `BuildResultV4` type similar to V3 but no routes, only superstatic keys
- Add validation to `@now/routing-utils` to ensure V4 Builders do not return `routes`
Note, no builders have been changed yet because this needs to be shipped first so we can bump build-utils and then builders will work in production. Then in a separate PR, we can update builders to V4.
Fixes#3310
The root `package.json` file is copied to `dist` by tsc because of a relative import. This causes npm `files` property to be nested and therefore skip publishing most of the files.
```ts
import pkg from '../../package.json';
```
Disabling `resolveJsonModule` and using `require()` instead fixed it.
However, this change caused `now-cli` build to fail so I had to change the way `now-client` gets imported.
Previously, the `typescript` dependency resolution was using the package.json beside the `now.json` base directory.
This PR changes the behavior to start looking for package.json in the entrypoint directory.
Fixes#3258
This test was failing for the last week.
The issue was fixed in the build environment. The root cause was [ruby-build](https://github.com/rbenv/ruby-build) which is used to install the version of Ruby used in `@now/ruby`. It started using an older (possible broken) version of `bundler`. I pinned `ruby-build` to a previous version so that deployments continue working.
So now we can enable the Rails test again (which uses nokogiri).
Fixes#3246Closes#3274
This PR is an attempt to automatically inject `gatsby-plugin-now` in Gatsby projects, as an optimisation.
- [x] avoid conflicts with existing files
- [x] refactor
* [now-node] Use builder version 3
* [now-cgi] Use builder version 3
* [now-go] Use builder version 3
* [now-python] Use builder version 3
* [now-ruby] Use builder version 3
* Adjust docs
* [now-ruby] Remove unused import
* Temp. test in iad1
* Revert "Temp. test in iad1"
This reverts commit 4c495baa5888dda5ae8f184f679613e91ab7268c.
* [now-cli] Adjust `now dev` for builder version 3
* [now-build-utils] Do not allow non Community Runtimes
* Temp. Force Build in iad1
* Update DEVELOPING_A_RUNTIME.md
Co-Authored-By: Steven <steven@ceriously.com>
* Update docs
* Update test/lib/deployment/now-deploy.js
Co-Authored-By: Steven <steven@ceriously.com>
* Remove temp. iad1 check
* Check memory and maxDuration
* Use memory for Lambda
* Only cast once
* Skip tests
* Allow functions + next.js
* Don't allow empty or invalid functions
* Make sure runtimes match a source
* Update now-dev to use the functions property
* Functions must match a source file
* Split up functions
* Make sure @now/next does not receive any unused functions
* Allow memory and maxDuration properties on Lambdas
* Add lambda options to @now/node
* Add lambda options to @now/go
* Add lambda options to @now/python
* Add lambda options to @now/ruby
* Update lambda options on @now/node
* Add lambda optiosn to @now/cgi
* Make options optional
* Add lambda options to @now/next
* Fix assertion
* Add test
* Fix tests
* Skip 06-ruby test
* Skip correct tests
* Fix options and cache src check
* Adjust memory test
Fix https://github.com/zeit/now/issues/3247.
Adds `.cache` folder to the Now cache for Gatsby deployments.
Also adds a generic optional `cachePattern` property to the frameworks array so we can optimize cache paths for other frameworks in the future.
This PR implements `cleanUrls` for now dev which is similar to the implementation in fmeta-util.
I also added an integration test to ensure correctness.
This PR fixes a regression introduced in #3174 when removing the `^` and `$` normalization.
The previous PR was normalizing user-defined routes but forgot to normalize builder routes.
This PR normalizes builder routes 👍
This PR does 3 things:
- add default caching headers
- redirect all missed requests to Gatsby's own 404.html page
- add deprecation message to `gatsby-plugin-now` since we're auto injecting it and it's not needed anymore
Fixes#2859
This allows us to start de-coupling the builder from relying on inner utils of Next.js to generate dynamic routes for Now by leveraging a `routes-manifest` output during the build
Relies on: https://github.com/zeit/next.js/pull/9347
There was a regression since 16.3.0 (now-client refactor) causing file permissions for source files to be not be preserved.
The solution was to add the FS `mode` to each file.
Fixes#3172
This PR updates the link to the missing build script FAQ, pending a change to the structure of the documentation.
This PR should be merged only when the documentation PR has been - https://github.com/zeit/docs/pull/1423
If someone uses a wildcard in the root of pages, it could collide with internal `_next` files:
```
pages/
[slug]/
[slug]/
[slug]/
[slug].js
```
For example:
`/_next/static/runtime/webpack-hash.js` exists and has no problem routing
`/_next/static/runtime/webpack-old-hash.js` doesn't exist on the server any more but would route to `/[slug].js` with status 200
This could cause strange edge cases related to loading a new version of a Next.js site along with the possible cost of execution if it's a lambda plus the cost of however large the response is.
# Side Notes
Should this:
92d9f2d809/packages/now-next/src/index.ts (L839)
Instead be this?
```
src: path.join('/', entryDirectory, '_next/static/(?:[^/]+/pages|chunks|runtime|css|media)/.+'),
```
If this is the case, I need to adjust my PR to do the same
* [now-cli][now-client] Add support for `functions` property
* Fix typo
* Update yarn.lock for test
* Update all yarn.lock files for now dev
* Log fixture that failed
* Use catch instead
* Run dev tests not serial
* Revert "Run dev tests not serial"
This reverts commit bfcd83642bcd2275daaac129b2c8b233f582eaae.
* Do not throw
* Skip nextjs tests on node 8
* Remove only flag
* Ignore 19-mithril
* Revert "Ignore 19-mithril"
This reverts commit d438c40c26a8ef2227a0a0dd7caba8600503d585.
* Revert "Remove only flag"
This reverts commit caff05ad82a184706eb48b6b39df550f8d17bb1d.
* Revert "Skip nextjs tests on node 8"
This reverts commit 3b45ca33b969a56da0bccce4c95cae3b34af98e0.
* Revert "Do not throw"
This reverts commit 55624b9193d7751e1dc16cbee9005fe23ff19662.
* Revert "Revert "Run dev tests not serial""
This reverts commit cd5260a205b6478cb7a44c9ea982b99f26f2f2e9.
* Revert "Run dev tests not serial"
This reverts commit bfcd83642bcd2275daaac129b2c8b233f582eaae.
* Revert "Use catch instead"
This reverts commit fe652995c08e1e8b2ba581aaf7304b5432718161.
* Revert "Log fixture that failed"
This reverts commit feb0e7b393626ce1c117ef95f9e95f7a148e3dab.
* Revert "Update all yarn.lock files for now dev"
This reverts commit 36be4dd98ca6d65850843dc958727952dd7461ee.
* Update yarn.lock for 14-svelte-node
* Update es-abstract in all yarn.lock files
* Skip node test
* Revert "Skip node test"
This reverts commit c9c45ec8d6fcef13cbd300db410699b167d76ed2.
* Remove test.only
* Only execute node test in now-dev
* Revert "Only execute node test in now-dev"
This reverts commit 8ab7a88d696c1faa5fe0fbcca9dcfb0dd375925f.
* Clean cache on macos node8
* Fix query
* Use --skip-integrity-check
* Add --skip-integrity-check to different yarn call
* Add --network-concurrency 1
* Add retry
This fixes the scenario where the user defines `trailingSlash: true` and creates a file `/api/users.js`. They would expect to be able to visit `/api/users/` and it should run that function.
This PR removes the individual lambda zip prints since they're not very useful. We've already printed this information above and will time them as a group!
This fixes the scenario when both `{ cleanUrls: true, and trailingSlash: true }` so that only one redirect occurs when visiting `/file.html`.
Previously, this would have redirected twice from `/file.html` => `/file` => `/file/`.
Now it will redirect once from `/file.html` => `/file/`.
This PR refactors a few things:
- enhance validation so that invalid regex is caught before transforming to routes
- remove `filePaths` input parameter since it is no longer used
After this PR is merged and released, we'll be able to perform validation earlier in the build pipeline and report the errors to the user.
* [now-build-utils] Validate functions and allow them as config
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* Change memory check
* Adjust test
We used to read the output files and create a route for each redirect when `cleanUrls: true`.
Instead, this PR will add 2 redirects for `cleanUrls: true` no matter how many files are in the outputs.
This updates `@now/build-utils` to add support for the function property including types and tests.
Related: [PRODUCT-27]
[PRODUCT-27]: https://zeit.atlassian.net/browse/PRODUCT-27
This allows us to start de-coupling the builder from relying on inner utils of Next.js to generate dynamic routes for Now by leveraging a `routes-manifest` output during the build
Relies on: https://github.com/zeit/next.js/pull/9347
* [now-node] Use builder version 3
* [now-cgi] Use builder version 3
* [now-go] Use builder version 3
* [now-python] Use builder version 3
* [now-ruby] Use builder version 3
* Adjust docs
* [now-ruby] Remove unused import
* Temp. test in iad1
* Revert "Temp. test in iad1"
This reverts commit 4c495baa5888dda5ae8f184f679613e91ab7268c.
* [now-cli] Adjust `now dev` for builder version 3
* [now-build-utils] Do not allow non Community Runtimes
* Temp. Force Build in iad1
* Update DEVELOPING_A_RUNTIME.md
Co-Authored-By: Steven <steven@ceriously.com>
* Update docs
* Update test/lib/deployment/now-deploy.js
Co-Authored-By: Steven <steven@ceriously.com>
* Remove temp. iad1 check
* Check memory and maxDuration
* Use memory for Lambda
* Only cast once
* Skip tests
There was a regression since 16.3.0 (now-client refactor) causing file permissions for source files to be not be preserved.
The solution was to add the FS `mode` to each file.
Fixes#3172
Fix https://github.com/zeit/now/issues/3247.
Adds `.cache` folder to the Now cache for Gatsby deployments.
Also adds a generic optional `cachePattern` property to the frameworks array so we can optimize cache paths for other frameworks in the future.
After upgrading to macOS Catalina I get this error on some now-deploys:
```
> Error! ENOENT: no such file or directory, stat '<file that not exist>'
```
and the file is below a folder that should be ignored by `.nowignore`, think this is due to some fs-bug in my node version, but did also discover that the ignore-array returned from `getNowIgnore` did not include the ignores from my `.nowignore`, but only the default defined in the top of the function.
Is this a bug?
* Allow functions + next.js
* Don't allow empty or invalid functions
* Make sure runtimes match a source
* Update now-dev to use the functions property
* Functions must match a source file
* Split up functions
* Make sure @now/next does not receive any unused functions
* Allow memory and maxDuration properties on Lambdas
* Add lambda options to @now/node
* Add lambda options to @now/go
* Add lambda options to @now/python
* Add lambda options to @now/ruby
* Update lambda options on @now/node
* Add lambda optiosn to @now/cgi
* Make options optional
* Add lambda options to @now/next
* Fix assertion
* Add test
* Fix tests
* Skip 06-ruby test
* Skip correct tests
* Fix options and cache src check
* Adjust memory test
This PR updates the link to the missing build script FAQ, pending a change to the structure of the documentation.
This PR should be merged only when the documentation PR has been - https://github.com/zeit/docs/pull/1423
If someone uses a wildcard in the root of pages, it could collide with internal `_next` files:
```
pages/
[slug]/
[slug]/
[slug]/
[slug].js
```
For example:
`/_next/static/runtime/webpack-hash.js` exists and has no problem routing
`/_next/static/runtime/webpack-old-hash.js` doesn't exist on the server any more but would route to `/[slug].js` with status 200
This could cause strange edge cases related to loading a new version of a Next.js site along with the possible cost of execution if it's a lambda plus the cost of however large the response is.
# Side Notes
Should this:
92d9f2d809/packages/now-next/src/index.ts (L839)
Instead be this?
```
src: path.join('/', entryDirectory, '_next/static/(?:[^/]+/pages|chunks|runtime|css|media)/.+'),
```
If this is the case, I need to adjust my PR to do the same
This PR implements `cleanUrls` for now dev which is similar to the implementation in fmeta-util.
I also added an integration test to ensure correctness.
This PR fixes a regression introduced in #3174 when removing the `^` and `$` normalization.
The previous PR was normalizing user-defined routes but forgot to normalize builder routes.
This PR normalizes builder routes 👍
* [now-cli][now-client] Add support for `functions` property
* Fix typo
* Update yarn.lock for test
* Update all yarn.lock files for now dev
* Log fixture that failed
* Use catch instead
* Run dev tests not serial
* Revert "Run dev tests not serial"
This reverts commit bfcd83642bcd2275daaac129b2c8b233f582eaae.
* Do not throw
* Skip nextjs tests on node 8
* Remove only flag
* Ignore 19-mithril
* Revert "Ignore 19-mithril"
This reverts commit d438c40c26a8ef2227a0a0dd7caba8600503d585.
* Revert "Remove only flag"
This reverts commit caff05ad82a184706eb48b6b39df550f8d17bb1d.
* Revert "Skip nextjs tests on node 8"
This reverts commit 3b45ca33b969a56da0bccce4c95cae3b34af98e0.
* Revert "Do not throw"
This reverts commit 55624b9193d7751e1dc16cbee9005fe23ff19662.
* Revert "Revert "Run dev tests not serial""
This reverts commit cd5260a205b6478cb7a44c9ea982b99f26f2f2e9.
* Revert "Run dev tests not serial"
This reverts commit bfcd83642bcd2275daaac129b2c8b233f582eaae.
* Revert "Use catch instead"
This reverts commit fe652995c08e1e8b2ba581aaf7304b5432718161.
* Revert "Log fixture that failed"
This reverts commit feb0e7b393626ce1c117ef95f9e95f7a148e3dab.
* Revert "Update all yarn.lock files for now dev"
This reverts commit 36be4dd98ca6d65850843dc958727952dd7461ee.
* Update yarn.lock for 14-svelte-node
* Update es-abstract in all yarn.lock files
* Skip node test
* Revert "Skip node test"
This reverts commit c9c45ec8d6fcef13cbd300db410699b167d76ed2.
* Remove test.only
* Only execute node test in now-dev
* Revert "Only execute node test in now-dev"
This reverts commit 8ab7a88d696c1faa5fe0fbcca9dcfb0dd375925f.
* Clean cache on macos node8
* Fix query
* Use --skip-integrity-check
* Add --skip-integrity-check to different yarn call
* Add --network-concurrency 1
* Add retry
This fixes the scenario where the user defines `trailingSlash: true` and creates a file `/api/users.js`. They would expect to be able to visit `/api/users/` and it should run that function.
This PR removes the individual lambda zip prints since they're not very useful. We've already printed this information above and will time them as a group!
This fixes the scenario when both `{ cleanUrls: true, and trailingSlash: true }` so that only one redirect occurs when visiting `/file.html`.
Previously, this would have redirected twice from `/file.html` => `/file` => `/file/`.
Now it will redirect once from `/file.html` => `/file/`.
This PR does 3 things:
- add default caching headers
- redirect all missed requests to Gatsby's own 404.html page
- add deprecation message to `gatsby-plugin-now` since we're auto injecting it and it's not needed anymore
Fixes#2859
This PR refactors a few things:
- enhance validation so that invalid regex is caught before transforming to routes
- remove `filePaths` input parameter since it is no longer used
After this PR is merged and released, we'll be able to perform validation earlier in the build pipeline and report the errors to the user.
* [now-build-utils] Validate functions and allow them as config
* Apply suggestions from code review
Co-Authored-By: Steven <steven@ceriously.com>
* Change memory check
* Adjust test
We used to read the output files and create a route for each redirect when `cleanUrls: true`.
Instead, this PR will add 2 redirects for `cleanUrls: true` no matter how many files are in the outputs.
This updates `@now/build-utils` to add support for the function property including types and tests.
Related: [PRODUCT-27]
[PRODUCT-27]: https://zeit.atlassian.net/browse/PRODUCT-27
This PR is an attempt to automatically inject `gatsby-plugin-now` in Gatsby projects, as an optimisation.
- [x] avoid conflicts with existing files
- [x] refactor
There have been Sentry errors where `process.cwd()` fails and throws an error. This patch handles that scenario gracefully by printing a more clear error message to the user and avoids sending a report to Sentry.
Fixes#3193.
* Update version of deployment API
* Add `alias-assigned` event and handling
* Replace v9 api with v10
* Don't return on immediate ready
* Handle alias-assigned for v1 deployments
* Improve event ordering
* Detect upload deployment readiness by `alias-assigned`
* rebuild
* Fix upload readiness event type
* Check for aliases before running status checks
* Improve event flow and wait for `ready` in v1 deployments
* Remove console.log
Disables `--user` parameter of the `pip` utility, which is forcibly set under the hood on Debian systems and causes an error in the `pipInstall` function:
`distutils.errors.DistutilsOptionError: can't combine user with prefix, exec_prefix/home, or install_(plat)base`
Fixes#3089
This PR disables Now 1.0 production deployments with the following error message:
> Option --prod is not supported for Now 1.0 deployments. To manually alias a deployment, use `now alias` instead.
It looks like this:
<img width="835" alt="Capture d’écran 2019-10-23 à 19 42 09" src="https://user-images.githubusercontent.com/6616955/67419574-3e125380-f5cd-11e9-81ff-63bde292539b.png">
Also disables `--target` for Now 1.0 deployments.
* Update version of deployment API
* Add `alias-assigned` event and handling
* Replace v9 api with v10
* Don't return on immediate ready
* Handle alias-assigned for v1 deployments
* Improve event ordering
* Detect upload deployment readiness by `alias-assigned`
* rebuild
* Fix upload readiness event type
* Check for aliases before running status checks
* Improve event flow and wait for `ready` in v1 deployments
* Remove console.log
When `cleanUrls` is true, the redirects will be applied to the routes however there are no longer any rewrites. Instead (through a different PR to fmeta-util) we will rename the file output to remove the `.html` extension.
When `cleanUrls` is true, the redirects will be applied to the routes however there are no longer any rewrites. Instead (through a different PR to fmeta-util) we will rename the file output to remove the `.html` extension.
There have been Sentry errors where `process.cwd()` fails and throws an error. This patch handles that scenario gracefully by printing a more clear error message to the user and avoids sending a report to Sentry.
Fixes#3193.
This PR disables Now 1.0 production deployments with the following error message:
> Option --prod is not supported for Now 1.0 deployments. To manually alias a deployment, use `now alias` instead.
It looks like this:
<img width="835" alt="Capture d’écran 2019-10-23 à 19 42 09" src="https://user-images.githubusercontent.com/6616955/67419574-3e125380-f5cd-11e9-81ff-63bde292539b.png">
Also disables `--target` for Now 1.0 deployments.
Disables `--user` parameter of the `pip` utility, which is forcibly set under the hood on Debian systems and causes an error in the `pipInstall` function:
`distutils.errors.DistutilsOptionError: can't combine user with prefix, exec_prefix/home, or install_(plat)base`
Fixes#3089
This PR adds a `contentType` to the File interface.
This is necessary for [PRODUCT-341] to work properly with `cleanUrls` which will strip the file name but we will still need specify `contentType: 'text/html'`.
This is required for @dav-is `api-builds` PR 633 to work properly.
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
The `@now/node` helpers json parsing is too strict and doesn't match the behavior of Express when an incoming request has `{ method: 'POST', Content-Type: 'application/json', body: '' }`.
Instead of returning 400, this PR will continue with `body = {}` to match Express.
Fixes https://spectrum.chat/zeit/now/klarna-with-zeit-now~60852003-4db6-4ec4-a611-83b2349ece08
This PR does a few things
- Separate tests into `integration.test.js` and `unit.test.js`
- Use one static build instead of many to avoid `should NOT have more than 128 items` error
- Add a new unit test so we don't regress
Fixes#3159
This implements a new function `getTransformedRoutes()` which transforms some [superstatic](https://github.com/firebase/superstatic#configuration) configuration keys to Now routes so we can eventually use this new keys in `now.json`.
In particular, the following new keys are transformed to `routes`.
- cleanUrls
- rewrites
- redirects
- headers
- trailingSlash
[PRODUCT-341] #close
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
Our tests periodically fail because we're creating too many v1 deployments on a free plan and it times out.
This limits the number of deployments by running v1 exclusively under Node 12.
It also adds a missing waitForDeployment().
This makes it so that a programatically created `DevServer` instance that has `debug` mode enabled also gets set on the builder child processes as expected, rather than only when invoked via CLI.
For example, the `dev-server.unit.js` tests can set `debug: true` and with this change the builder child processes will also have debug logs enabled. See [here](https://git.io/JeW0O).
Explicitly send the SIGINT / SIGTERM signal to `now dev` server child processes, so that they are not left running when running the now-dev unit tests.
Related to #3113 which has hanging unit tests that never "complete".
This PR should fixes `ENOENT` related errors
```
> Error! ENOENT: no such file or directory, stat '.../node_modules/.bin/...'
```
Related: https://github.com/zeit/now/issues/3104
As of https://github.com/zeit/now-builders/pull/679, this logic is unnecessary because the `@now/static-build` builder will never end up executing the `dev` script when there is a `now.json` file present (and thus, no builds present, aka zero config mode).
Also, statically detecting the `now dev` command from the script command is brittle, as the command could execute a separate shell script that ends up executing `now dev` (and this detection logic would be a false negative).
This PR is a followup to #3138 so that `now dev` will validate and transform the following `now.json` config keys to routes:
- cleanUrls
- rewrites
- redirects
- headers
- trailingSlash
[PRODUCT-341] #close
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
This PR adds a `contentType` to the File interface.
This is necessary for [PRODUCT-341] to work properly with `cleanUrls` which will strip the file name but we will still need specify `contentType: 'text/html'`.
This is required for @dav-is `api-builds` PR 633 to work properly.
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
The `@now/node` helpers json parsing is too strict and doesn't match the behavior of Express when an incoming request has `{ method: 'POST', Content-Type: 'application/json', body: '' }`.
Instead of returning 400, this PR will continue with `body = {}` to match Express.
Fixes https://spectrum.chat/zeit/now/klarna-with-zeit-now~60852003-4db6-4ec4-a611-83b2349ece08
Explicitly send the SIGINT / SIGTERM signal to `now dev` server child processes, so that they are not left running when running the now-dev unit tests.
Related to #3113 which has hanging unit tests that never "complete".
This PR does a few things
- Separate tests into `integration.test.js` and `unit.test.js`
- Use one static build instead of many to avoid `should NOT have more than 128 items` error
- Add a new unit test so we don't regress
Fixes#3159
This implements a new function `getTransformedRoutes()` which transforms some [superstatic](https://github.com/firebase/superstatic#configuration) configuration keys to Now routes so we can eventually use this new keys in `now.json`.
In particular, the following new keys are transformed to `routes`.
- cleanUrls
- rewrites
- redirects
- headers
- trailingSlash
[PRODUCT-341] #close
[PRODUCT-341]: https://zeit.atlassian.net/browse/PRODUCT-341
Our tests periodically fail because we're creating too many v1 deployments on a free plan and it times out.
This limits the number of deployments by running v1 exclusively under Node 12.
It also adds a missing waitForDeployment().
This makes it so that a programatically created `DevServer` instance that has `debug` mode enabled also gets set on the builder child processes as expected, rather than only when invoked via CLI.
For example, the `dev-server.unit.js` tests can set `debug: true` and with this change the builder child processes will also have debug logs enabled. See [here](https://git.io/JeW0O).
Explicitly send the SIGINT / SIGTERM signal to `now dev` server child processes, so that they are not left running when running the now-dev unit tests.
Related to #3113 which has hanging unit tests that never "complete".
Explicitly send the SIGINT / SIGTERM signal to `now dev` server child processes, so that they are not left running when running the now-dev unit tests.
Related to #3113 which has hanging unit tests that never "complete".
This PR should fixes `ENOENT` related errors
```
> Error! ENOENT: no such file or directory, stat '.../node_modules/.bin/...'
```
Related: https://github.com/zeit/now/issues/3104
As of https://github.com/zeit/now-builders/pull/679, this logic is unnecessary because the `@now/static-build` builder will never end up executing the `dev` script when there is a `now.json` file present (and thus, no builds present, aka zero config mode).
Also, statically detecting the `now dev` command from the script command is brittle, as the command could execute a separate shell script that ends up executing `now dev` (and this detection logic would be a false negative).
This is a follow up to #3117 which added a fix for `files` but did not observe directories.
This PR fixes the scenario where a directory is defined such that all files inside the directory should be added uploaded (recursively).
Thanks to @williamli
[PRODUCT-350] #close
[PRODUCT-350]: https://zeit.atlassian.net/browse/PRODUCT-350
This is a follow up to #3117 which added a fix for `files` but did not observe directories.
This PR fixes the scenario where a directory is defined such that all files inside the directory should be added uploaded (recursively).
Thanks to @williamli
[PRODUCT-350] #close
[PRODUCT-350]: https://zeit.atlassian.net/browse/PRODUCT-350
Since `@now/static-build` is no longer sniffing the stdio streams for the bound port number in `now dev`, there's no need to have separate stdio streams for the "dev" script. Instead, inherit stdio from the parent process, which will allow for ANSI colors to be used when stdout is a TTY in `now dev`.
Also simplifies the `checkForPort()` function and removes the `promise-timeout` dependency.
When now-client was implemented, it did not work with `--local-config` flag from now-cli because the only parameters it looks at are the files in a directory.
This fixes the regression in now@16.3.0 so that now-client can accept an optional `nowConfig` object or fallback to the `now.json` file.
Fixes#3099Fixes#3105Fixes#3107Fixes#3109
[PRODUCT-350] #close
[PRODUCT-350]: https://zeit.atlassian.net/browse/PRODUCT-350
For context, when you have a script that generates a new static file at build time (`sitemap.xml` for example), it has to be inside `.next/static`, and then you'll need a Now route for it, with this change you could generate the file inside `public`/`static` and the builder will now take care of it.
The util `includeOnlyEntryDirectory` is no longer being used after this change, should I remove it?
This PR integrates v2 of Projects API that fixes an issue for projects named `list` or `remove`, because of the naming of the endpoints in v1. For listing all projects, previously in v1 it was `GET /v1/projects/list` and now it is `GET /v2/projects/`, and for removing a project it was `DELETE /v1/projects/remove`.
Since `@now/static-build` is no longer sniffing the stdio streams for the bound port number in `now dev`, there's no need to have separate stdio streams for the "dev" script. Instead, inherit stdio from the parent process, which will allow for ANSI colors to be used when stdout is a TTY in `now dev`.
Also simplifies the `checkForPort()` function and removes the `promise-timeout` dependency.
When now-client was implemented, it did not work with `--local-config` flag from now-cli because the only parameters it looks at are the files in a directory.
This fixes the regression in now@16.3.0 so that now-client can accept an optional `nowConfig` object or fallback to the `now.json` file.
Fixes#3099Fixes#3105Fixes#3107Fixes#3109
[PRODUCT-350] #close
[PRODUCT-350]: https://zeit.atlassian.net/browse/PRODUCT-350
For context, when you have a script that generates a new static file at build time (`sitemap.xml` for example), it has to be inside `.next/static`, and then you'll need a Now route for it, with this change you could generate the file inside `public`/`static` and the builder will now take care of it.
The util `includeOnlyEntryDirectory` is no longer being used after this change, should I remove it?
This PR integrates v2 of Projects API that fixes an issue for projects named `list` or `remove`, because of the naming of the endpoints in v1. For listing all projects, previously in v1 it was `GET /v1/projects/list` and now it is `GET /v2/projects/`, and for removing a project it was `DELETE /v1/projects/remove`.
It will print `[v2]` for 1.0 deployments when logging initially:
```
• go $ now --force
> WARN! You are using an old version of the Now Platform. More: https://zeit.co/docs/v2/advanced/platform/changes-in-now-2-0
> Deploying ~/projects/zeit/now-builder-v1/examples/docker/go under andyschneider
> Using project now-v1-go-docker
> now-v1-go-docker-xxxxxxx.now.sh [v2] [1s]
> Build completed
> https://now-v1-go-docker-xxxxxxx.now.sh [v1] [in clipboard] (sfo1) [1m]
> Verifying instantiation in sfo1
> ✔ Scaled 1 instance in sfo1 [22s]
> Success! Deployment ready
```
Expected:
```
• go $ nowl --force
> WARN! You are using an old version of the Now Platform. More: https://zeit.co/docs/v2/advanced/platform/changes-in-now-2-0
> Deploying ~/projects/zeit/now-builder-v1/examples/docker/go under andyschneider
> Using project now-v1-go-docker
> now-v1-go-docker-xxxxxxx.now.sh [v1] [2s]
> Build completed
> https://now-v1-go-docker-xxxxxxx.now.sh [v1] [in clipboard] (sfo1) [1m]
> Verifying instantiation in sfo1
> ✔ Scaled 1 instance in sfo1 [23s]
> Success! Deployment ready
```
For v2 it shouldn't print anything, as it's the default.
This makes downstream compilation with `tsc` work correctly.
Otherwise, compilation fails with errors such as:
```
../now-client/dist/src/index.d.ts:1:40 - error TS2304: Cannot find name 'CreateDeploymentFunction'.
1 export declare const createDeployment: CreateDeploymentFunction;
~~~~~~~~~~~~~~~~~~~~~~~~
````
As of https://github.com/zeit/now/pull/3081, we make it necessary to group `Prerenders` together for being invalidated at the same time.
However, you might not want that. In turn, we'll make it optional.
This pull request removes the `PrerenderGroup` type in favor of a `group` parameter for the existing `Prerender` type.
This parameter takes in an integer that defines a group of prerenders that should be invalidated at the same time:
```
interface Prerender {
expiration: number;
lambda: Lambda;
fallback: FileBlob | FileFsRef | FileRef;
group: number;
}
```
**Example:** If two `Prerender` instances exist that have `group` set to `1`, they will both be invalidated at the same time.
This PR adds extensive debug logging to `now-client` and enables it in CLI based on the `--debug` flag
Debug logging works in either of the following two conditions:
- `debug: true` is provided in the `options` object of `createDeployment`/`createLegacyDeployment`
- `process.env.NOW_CLIENT_DEBUG` environment variable is set
It will print `[v2]` for 1.0 deployments when logging initially:
```
• go $ now --force
> WARN! You are using an old version of the Now Platform. More: https://zeit.co/docs/v2/advanced/platform/changes-in-now-2-0
> Deploying ~/projects/zeit/now-builder-v1/examples/docker/go under andyschneider
> Using project now-v1-go-docker
> now-v1-go-docker-xxxxxxx.now.sh [v2] [1s]
> Build completed
> https://now-v1-go-docker-xxxxxxx.now.sh [v1] [in clipboard] (sfo1) [1m]
> Verifying instantiation in sfo1
> ✔ Scaled 1 instance in sfo1 [22s]
> Success! Deployment ready
```
Expected:
```
• go $ nowl --force
> WARN! You are using an old version of the Now Platform. More: https://zeit.co/docs/v2/advanced/platform/changes-in-now-2-0
> Deploying ~/projects/zeit/now-builder-v1/examples/docker/go under andyschneider
> Using project now-v1-go-docker
> now-v1-go-docker-xxxxxxx.now.sh [v1] [2s]
> Build completed
> https://now-v1-go-docker-xxxxxxx.now.sh [v1] [in clipboard] (sfo1) [1m]
> Verifying instantiation in sfo1
> ✔ Scaled 1 instance in sfo1 [23s]
> Success! Deployment ready
```
For v2 it shouldn't print anything, as it's the default.
This makes downstream compilation with `tsc` work correctly.
Otherwise, compilation fails with errors such as:
```
../now-client/dist/src/index.d.ts:1:40 - error TS2304: Cannot find name 'CreateDeploymentFunction'.
1 export declare const createDeployment: CreateDeploymentFunction;
~~~~~~~~~~~~~~~~~~~~~~~~
````
As of https://github.com/zeit/now/pull/3081, we make it necessary to group `Prerenders` together for being invalidated at the same time.
However, you might not want that. In turn, we'll make it optional.
This pull request removes the `PrerenderGroup` type in favor of a `group` parameter for the existing `Prerender` type.
This parameter takes in an integer that defines a group of prerenders that should be invalidated at the same time:
```
interface Prerender {
expiration: number;
lambda: Lambda;
fallback: FileBlob | FileFsRef | FileRef;
group: number;
}
```
**Example:** If two `Prerender` instances exist that have `group` set to `1`, they will both be invalidated at the same time.
This PR adds extensive debug logging to `now-client` and enables it in CLI based on the `--debug` flag
Debug logging works in either of the following two conditions:
- `debug: true` is provided in the `options` object of `createDeployment`/`createLegacyDeployment`
- `process.env.NOW_CLIENT_DEBUG` environment variable is set
Previously, if you ran `now ls` with a URL for a path alias, then an
error message `Cannot read property 'replace' of undefined` would occur.
Now, a message is logged saying to instead run `now alias ls $url` which
is the correct command to get path rules relevant to a path alias URL.
> Found matching path alias: rules.domain.com
> Please run `now alias ls rules.domain.com` instead
Fixes#2987.
* [now-static-build] Run `bundle install` for Gemfile
* Add logs
* Add timeout in case proc hangs
* Rename test
* Remove console.log()
* Hide warnings
* Use runBundleInstall()
* [now-build-utils] Remove --deployment flag
* Run tests for build-utils
* [now-build-utils] Add function `runBundleInstall`
* Add additional flags
* Set jobs to number of cpus
* Format
* Fix formatting
* Add BUNDLE_APP_CONFIG
* [now-static-build] Fix dev server detection
* Code review
* Remove unused dependency
* Fix the checking by really waiting until the port is reachable
* [now-build-utils][now-cli] Warn instead of throwing on `api` and `pages/api`
* Remove slash and adjust tests
* Remove @now/build-utils
* Hardcode builders
* Add build-utils
* Change default flag
* More logging
* Add static-build
* Remove other packages from package.json
* New file for bundled function
No functionality change here, this just removes the `Package` and
`BuildConfig` types from `src/util/dev/types.ts` in favor of the
matching types from `@now/build-utils`.
Also a lot of prettier formatting…
Previously, if you ran `now ls` with a URL for a path alias, then an
error message `Cannot read property 'replace' of undefined` would occur.
Now, a message is logged saying to instead run `now alias ls $url` which
is the correct command to get path rules relevant to a path alias URL.
> Found matching path alias: rules.domain.com
> Please run `now alias ls rules.domain.com` instead
Fixes#2987.
* [now-static-build] Run `bundle install` for Gemfile
* Add logs
* Add timeout in case proc hangs
* Rename test
* Remove console.log()
* Hide warnings
* Use runBundleInstall()
* [now-build-utils] Remove --deployment flag
* Run tests for build-utils
* [now-build-utils] Add function `runBundleInstall`
* Add additional flags
* Set jobs to number of cpus
* Format
* Fix formatting
* Add BUNDLE_APP_CONFIG
* [now-static-build] Fix dev server detection
* Code review
* Remove unused dependency
* Fix the checking by really waiting until the port is reachable
* [now-build-utils][now-cli] Warn instead of throwing on `api` and `pages/api`
* Remove slash and adjust tests
* Remove @now/build-utils
* Hardcode builders
* Add build-utils
* Change default flag
* More logging
* Add static-build
* Remove other packages from package.json
* New file for bundled function
No functionality change here, this just removes the `Package` and
`BuildConfig` types from `src/util/dev/types.ts` in favor of the
matching types from `@now/build-utils`.
Also a lot of prettier formatting…
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>
* [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
* 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
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
* 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.
* 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-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-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>
* [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
* 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] 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 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 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
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.
* [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
* [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
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
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.
* [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 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
* 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
* [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
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.
* 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] 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
`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] 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
* 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.
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
* 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.
* 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.
* [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`.
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>
* [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.
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
* 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
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
* 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.
* 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.
* [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.
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
* [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.
* 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
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.
* 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
* [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
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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
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.
* 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
* 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`.
`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
* 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.
```
> 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
* 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
* 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
* 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 `--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.
* 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
* 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.
* 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.
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* 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
* Certificates revamped
* Change copy of certs loading msg
* Be more specific when we generate a certificate from alias
* Better messages when creating certs
* Ensure TTY works for alias
* Check if DNS records are configured instead of checking resolved server
* Fallback to a normal cert when the DNS settings are not valid for wildcard
* Be explicit setting alias.zeit.co DNS records
* Check DNS records to request a certificate that will success for zeit.world
* Only try to find more deployments if app name defined
* Made note util correct
* Added support for listing single deployments
* Reverted unnecessary change
* Only try to find more deployments if app name defined
* Made note util correct
* Added support for listing single deployments
* Reverted unnecessary change
* Introduce v3 deployment scaling API
* Less retries on setScale()
* now scale cmd v3
* Deployment id fixes
* bump `ecmaVersion` we lint against, to consider object rest spread
* move EPIPE workaround to the main file
* uniform exiting approach
* clean up list command to avoid globals, be simpler to read
* add ability to supply a custom API version to `now.list()` helper
* upgrade babel toolchain
* introduce `arg`, which will incrementally replace `mri`
* global args accepted by all subcommands
* update lock
* fix `>` to be red when rendering errors
* use new output helpers by @tootallnate
* make object spread work
* bump flow webpack plugin
* lock
* revert to ava 0.25.x
* deprecate `now ls help` since an app could be named `help`
* validate number of arguments
* Fixed integration tests to match downgraded AVA
* Trimmed newline
* WIP
* whitespace fix
* add source map support by @timneutkens
* fix source maps paths
* remove sort-deployments util. it only considers `package.json`
* created -> age for consistency
* remove sorting what wasn't working well
* multiple improvements and simplifications
* improve rendering of urls, fix filtering by app
* only attempt to fetch instances if we have a count > 0
* better check for no deployments
* add instance lists if --all is supplied
* prevent the `.map` file from being included by pkg
* Store artifacts in Circle CI
* adapt INITIALIZING display by suggestion of @tootallnate
* Nothing to return
* now scale: Args parsing and remove ls
* various code improvements, error link for deprecation of `now scale ls`
* improve help
* make error more specific to deployment
* use new error output utilities for `now deploy`
* make some requires conditional
* default command style fix
* add reusable dc validation and normalization utilities
* start doing dc / region validation in scale
* refactor deploy to use reusable dc / region utils
* add slug support for warn util
* add success helper
* improve `scale` command
* add `responseErrorMessage` helper
* add `now.fetch()` helper
* remove console.log
* tweak output
* draft of verification step
* better errors
* implement (customizable) verification timeout
* bump now-host api to v3
* finish verification
* improve verification and sanitization
* improve copy
* fix ctrl+c during scale
* fix max scale in the absense of max
* improved rules saving
* fix listing the context you're running `now list` under
* add context name to list commands from slots
* improve --no-verify
* add 'elapsed' utility to print out the elapsed time nicely
* add per-dc timers
* improve debug helper to save date, improve time helper to log eagerly
* log every request, automatically
* tweak
* general tweaks to `now deploy`
* pass additional now config fields
* refactor `now rm`
* begin `inspect` command
* bump fetch-h2
* nearly complete new inspect command
* add `(dev)` to --version while in development
* fix 404 error if app is not matched
* improve scaling
* pass event types to the events endpoint
* fix file uploads
* fix passing a deployment hostname with trailing `/`
* fetch events only for non-static
* include uid in inspect
* finish up events
* reduce one indent by recommendation of @leo
* fix debugging for `now ls`
* Always return and exit at top-level in now.js
* improved scale message
* more elegant way of exiting, allowing for resource cleanup & faster
* flowify
* fix strange error which happens when orderly cleanup is done
* flow
* flow fix
* invoke now.close()
* improve list indentation
* refactor alias
* exit clean
* improve fallthrough entry in path alias
* make scale exit properly
* fix closing agent for inspection
* add type of deployment to ls
* better error handling of 403
* improve list style
* various algorithmic improvements
* Certificates refactor to consume the new API (#1210)
* Adapt cert command to the new api
* Use the new certs api for cert command
* Console log certs table and point to the right endpoint
* Remove unused certs client file
* Refactor certs commands
* Fix access to args
* Always close client
* Refactor alias (#1216)
* remove unnecessary file
* reads events from /deployment/:id/events endpoint (#1219)
* add polling (#1220)
* add polling
* hack to prevent partial json to be unluckily parsed in _flush
* cleanupAndResolveCalled to prevent running twice
* call onOpen only of going to 'log'. also call from cleanup
* callOnOpenOnce, don't reject on stream error, polling to finish
* fix eraseLines, make cleanup routine reject
* remove build-logger.js
* restored printEvent from deleted build-logger.js
* print locations of instance events
* bump api versions
* Switch now logs to events endpoint (#1223)
* move eraseLines to onRetry. show error in onRetry
* move printEvents to 'sh/util/events.js'
* use printEvents in `now logs` command
* pass printEvent to events.js
* make both follow and non-follow modes work
* remove socket.io
* improve logs command
* clarify team context
* Refactor alias
* Use ellapsed util in stamp
* use v3
* Refactor alias (#1224)
* Refactor alias
* Use ellapsed util in stamp
* Improvements
* Fix unit tests
* Ensure body exists when copying error attrs
* Add hook to close socket and wait message on process exit
* More retries when verifying the DNS records in alias
* Remove nowExit event listener on close
* Add remaning DCs message right away on alias
* Consistent timestamp when creating a deployment + scale dcs
* Ignore flow error
* Remove not needed now.close from alias
* Remove not needed now.close from inspect
* Bugfix: bind context to close socket handler
* Better error handling for scale command
* Now logs limit (#1226)
* restored -n LIMIT cli arg
* show date in format usabe for since and until
* pass direction and limit to endpoint
* implement follow mode after backwards slice
* add query, fix linefeeds, strip term commands
* implement head argument
* better logs default
* logs: fix -o raw mode, fix all mode
* Add verification for deploy
* Run integration tests using random email address
* Fix flow errors
* Fix wrong scale check
* Finish deploy on state READY
* Correct URL parsing
* Bumped Node.js to the latest version
* Output node version
* fix url display
* Returned URLs
* Improve messages in scale
* Clear URLs
* Strip ANSI codes
* Better logging messages for deploy
* Print ls to console instead of stderr
* Add create certificate certificate and ensure verification is done for a domain
* Write success in alias to stdout
* clearURL in stdout for alias test
* Update scale integration test
* Use stdout for scale success message
* Write alias rm response to stdout
* Refactor alias rm to use fetch from now client
* Fix tests
* Introduce v3 deployment scaling API
* Less retries on setScale()
* now scale cmd v3
* Deployment id fixes
* bump `ecmaVersion` we lint against, to consider object rest spread
* move EPIPE workaround to the main file
* uniform exiting approach
* clean up list command to avoid globals, be simpler to read
* add ability to supply a custom API version to `now.list()` helper
* upgrade babel toolchain
* introduce `arg`, which will incrementally replace `mri`
* global args accepted by all subcommands
* update lock
* fix `>` to be red when rendering errors
* use new output helpers by @tootallnate
* make object spread work
* bump flow webpack plugin
* lock
* revert to ava 0.25.x
* deprecate `now ls help` since an app could be named `help`
* validate number of arguments
* Fixed integration tests to match downgraded AVA
* Trimmed newline
* WIP
* whitespace fix
* add source map support by @timneutkens
* fix source maps paths
* remove sort-deployments util. it only considers `package.json`
* created -> age for consistency
* remove sorting what wasn't working well
* multiple improvements and simplifications
* improve rendering of urls, fix filtering by app
* only attempt to fetch instances if we have a count > 0
* better check for no deployments
* add instance lists if --all is supplied
* prevent the `.map` file from being included by pkg
* Store artifacts in Circle CI
* adapt INITIALIZING display by suggestion of @tootallnate
* Nothing to return
* now scale: Args parsing and remove ls
* various code improvements, error link for deprecation of `now scale ls`
* improve help
* make error more specific to deployment
* use new error output utilities for `now deploy`
* make some requires conditional
* default command style fix
* add reusable dc validation and normalization utilities
* start doing dc / region validation in scale
* refactor deploy to use reusable dc / region utils
* add slug support for warn util
* add success helper
* improve `scale` command
* add `responseErrorMessage` helper
* add `now.fetch()` helper
* remove console.log
* tweak output
* draft of verification step
* better errors
* implement (customizable) verification timeout
* bump now-host api to v3
* finish verification
* improve verification and sanitization
* improve copy
* fix ctrl+c during scale
* fix max scale in the absense of max
* improved rules saving
* fix listing the context you're running `now list` under
* add context name to list commands from slots
* improve --no-verify
* add 'elapsed' utility to print out the elapsed time nicely
* add per-dc timers
* improve debug helper to save date, improve time helper to log eagerly
* log every request, automatically
* tweak
* general tweaks to `now deploy`
* pass additional now config fields
* refactor `now rm`
* begin `inspect` command
* bump fetch-h2
* nearly complete new inspect command
* add `(dev)` to --version while in development
* fix 404 error if app is not matched
* improve scaling
* pass event types to the events endpoint
* fix file uploads
* fix passing a deployment hostname with trailing `/`
* fetch events only for non-static
* include uid in inspect
* finish up events
* reduce one indent by recommendation of @leo
* fix debugging for `now ls`
* Always return and exit at top-level in now.js
* improved scale message
* more elegant way of exiting, allowing for resource cleanup & faster
* flowify
* fix strange error which happens when orderly cleanup is done
* flow
* flow fix
* invoke now.close()
* improve list indentation
* refactor alias
* exit clean
* improve fallthrough entry in path alias
* make scale exit properly
* fix closing agent for inspection
* add type of deployment to ls
* better error handling of 403
* improve list style
* various algorithmic improvements
* Certificates refactor to consume the new API (#1210)
* Adapt cert command to the new api
* Use the new certs api for cert command
* Console log certs table and point to the right endpoint
* Remove unused certs client file
* Refactor certs commands
* Fix access to args
* Always close client
* Refactor alias (#1216)
* remove unnecessary file
* reads events from /deployment/:id/events endpoint (#1219)
* add polling (#1220)
* add polling
* hack to prevent partial json to be unluckily parsed in _flush
* cleanupAndResolveCalled to prevent running twice
* call onOpen only of going to 'log'. also call from cleanup
* callOnOpenOnce, don't reject on stream error, polling to finish
* fix eraseLines, make cleanup routine reject
* remove build-logger.js
* restored printEvent from deleted build-logger.js
* print locations of instance events
* bump api versions
* Switch now logs to events endpoint (#1223)
* move eraseLines to onRetry. show error in onRetry
* move printEvents to 'sh/util/events.js'
* use printEvents in `now logs` command
* pass printEvent to events.js
* make both follow and non-follow modes work
* remove socket.io
* improve logs command
* clarify team context
* Refactor alias
* Use ellapsed util in stamp
* use v3
* Refactor alias (#1224)
* Refactor alias
* Use ellapsed util in stamp
* Improvements
* Fix unit tests
* Ensure body exists when copying error attrs
* Add hook to close socket and wait message on process exit
* More retries when verifying the DNS records in alias
* Remove nowExit event listener on close
* Add remaning DCs message right away on alias
* Consistent timestamp when creating a deployment + scale dcs
* Ignore flow error
* Remove not needed now.close from alias
* Remove not needed now.close from inspect
* Bugfix: bind context to close socket handler
* Better error handling for scale command
* Now logs limit (#1226)
* restored -n LIMIT cli arg
* show date in format usabe for since and until
* pass direction and limit to endpoint
* implement follow mode after backwards slice
* add query, fix linefeeds, strip term commands
* implement head argument
* better logs default
* logs: fix -o raw mode, fix all mode
* Add verification for deploy
* Run integration tests using random email address
* Fix flow errors
* Fix wrong scale check
* Finish deploy on state READY
* Correct URL parsing
* Bumped Node.js to the latest version
* Output node version
* fix url display
* Returned URLs
* Improve messages in scale
* Clear URLs
* Strip ANSI codes
* Better logging messages for deploy
* Print ls to console instead of stderr
* Add create certificate certificate and ensure verification is done for a domain
* Write success in alias to stdout
* clearURL in stdout for alias test
* Update scale integration test
* Use stdout for scale success message
* Write alias rm response to stdout
* Refactor alias rm to use fetch from now client
* Fix tests
* Added debounced waiting message to `list` command
Refs #1167, #1166
* Integrated debouncing directly into wait function
Refs #1167, #1166
* Moved debouncing in `wait` module directly to `wait` function
Refs #1167, #1166
* Added test for `wait`function
Refs #1167, #1166
* Removes oboslete logging from `wait` utitlity
* Removed semis
* Removed semis
* Make sense of it
* Bumped lockfile
* Moved stopping of spinner right before first output within `now ls`
* Added debounced waiting message to `list` command
Refs #1167, #1166
* Integrated debouncing directly into wait function
Refs #1167, #1166
* Moved debouncing in `wait` module directly to `wait` function
Refs #1167, #1166
* Added test for `wait`function
Refs #1167, #1166
* Removes oboslete logging from `wait` utitlity
* Removed semis
* Removed semis
* Make sense of it
* Bumped lockfile
* Added debounced waiting message to `list` command
Refs #1167, #1166
* Integrated debouncing directly into wait function
Refs #1167, #1166
* Moved debouncing in `wait` module directly to `wait` function
Refs #1167, #1166
* Added test for `wait`function
Refs #1167, #1166
* Removes oboslete logging from `wait` utitlity
* Removed semis
* Removed semis
* Make sense of it
* Bumped lockfile
* Moved stopping of spinner right before first output within `now ls`
* Added debounced waiting message to `list` command
Refs #1167, #1166
* Integrated debouncing directly into wait function
Refs #1167, #1166
* Moved debouncing in `wait` module directly to `wait` function
Refs #1167, #1166
* Added test for `wait`function
Refs #1167, #1166
* Removes oboslete logging from `wait` utitlity
* Removed semis
* Removed semis
* Make sense of it
* Bumped lockfile
* Added support for fallback error
* Better errors for uploading files
* Ensure all errors are covered
* Formatted properly
* Added a few tests
* Wrapped up tests
* Added support for fallback error
* Better errors for uploading files
* Ensure all errors are covered
* Formatted properly
* Added a few tests
* Wrapped up tests
* Proper unit tests
* Made integration tests run in CI
* Added packing to integration tests
* Don't lint test fixtures
* Added missing files
* Added command for local testing
* Correct command for local testing
* Compare client version
* Separate file for helper
* Added micro fixture
* Check OSS confirmation message
* Even better
* Deploy a microservice
* Made it run
* Remove deployment properly
* Clean up everything
* Fixed linting
* Added missing fixtures
* Added missing files
* Fixed linking
* Remove only deployments created in session
* Create alias for deployment
* Wrapped up 10 test
* Try scaling the deployment directly
* Wrapped up the 15 tests
* Ensure files are actually equal
* Test docker deployments
* Made sense of all
* Remove right after
* Set redirect URL properly
* Run integration tests on macOS
* Clean up in the end
* Use existing method to clean up
* Revoke the token properly
* Check for team error
* Wrapped up 18 tests
* Try deploying a static directory
* Try running it in user directory
* Auto-generate integration tests
* Removed Yarn lockfile
* Fixed linting
* Run test only if the one before was successful
* Bumped lockfile
* Removed catching
* Removed useless dependency
* Removed line
* Don't kill app and restore config
* Test properly locally
* Fixed linting
* Fixed properly
* Comment added
* Fixed arguments
* Proper unit tests
* Made integration tests run in CI
* Added packing to integration tests
* Don't lint test fixtures
* Added missing files
* Added command for local testing
* Correct command for local testing
* Compare client version
* Separate file for helper
* Added micro fixture
* Check OSS confirmation message
* Even better
* Deploy a microservice
* Made it run
* Remove deployment properly
* Clean up everything
* Fixed linting
* Added missing fixtures
* Added missing files
* Fixed linking
* Remove only deployments created in session
* Create alias for deployment
* Wrapped up 10 test
* Try scaling the deployment directly
* Wrapped up the 15 tests
* Ensure files are actually equal
* Test docker deployments
* Made sense of all
* Remove right after
* Set redirect URL properly
* Run integration tests on macOS
* Clean up in the end
* Use existing method to clean up
* Revoke the token properly
* Check for team error
* Wrapped up 18 tests
* Try deploying a static directory
* Try running it in user directory
* Auto-generate integration tests
* Removed Yarn lockfile
* Fixed linting
* Run test only if the one before was successful
* Bumped lockfile
* Removed catching
* Removed useless dependency
* Removed line
* Don't kill app and restore config
* Test properly locally
* Fixed linting
* Fixed properly
* Comment added
* Fixed arguments
* Added Circle CI config
* Test it
* Ensure machine property
* Another missing part
* Run one after another
* Use the same image in all jobs
* Made it shorter
* Sweeter syntax
* Split into separate jobs
* Pass on data
* Pass everything around
* Renamed workflow
* Fan-out/fan-in
* Added new build badge
* Better link for badge
* Named commands
* Show help
* Properly attach node modules for deployment
* Capitalized titles
* Install correct uploader
* Use correct image
* Try the uploading
* Try it like this
* Set user and repo
* Filter binaries properly
* Compress binaries only when deploying
* Switched image for deployment step
* Removed Cache
* Install Go properly
* Removed slash
* Set env var correctly for Go
* Use separate jobs
* Cache Go dependencies
* Only upload on tagged builds
* Separate jobs for channels
* Corrected description
* Optimized for maximum performance
* Removed dependency
* Use lockfile for checksum
* Switched commands to Yarn
* Only use what's needed
* Use correct command to link
* Show proper deploying output
* Handle everything
* Log it when doing it
* Make all others work
* Fixed syntax
* Removed semis
* Fixed rest
* Make GitHub uploads work again
* Made it work properly
* Ensure paths are relative
* Made it work
* Bumped lockfile
* Fixed code
* Corrected code
* Properly debug
* Fixed linting
* Made it work correctly
* Fixed missing parenthesis
* Added Circle CI config
* Test it
* Ensure machine property
* Another missing part
* Run one after another
* Use the same image in all jobs
* Made it shorter
* Sweeter syntax
* Split into separate jobs
* Pass on data
* Pass everything around
* Renamed workflow
* Fan-out/fan-in
* Added new build badge
* Better link for badge
* Named commands
* Show help
* Properly attach node modules for deployment
* Capitalized titles
* Install correct uploader
* Use correct image
* Try the uploading
* Try it like this
* Set user and repo
* Filter binaries properly
* Compress binaries only when deploying
* Switched image for deployment step
* Removed Cache
* Install Go properly
* Removed slash
* Set env var correctly for Go
* Use separate jobs
* Cache Go dependencies
* Only upload on tagged builds
* Separate jobs for channels
* Corrected description
* Optimized for maximum performance
* Removed dependency
* Use lockfile for checksum
* Switched commands to Yarn
* Only use what's needed
* Use correct command to link
* Show proper deploying output
* Handle everything
* Log it when doing it
* Make all others work
* Fixed syntax
* Removed semis
* Fixed rest
* Make GitHub uploads work again
* Made it work properly
* Ensure paths are relative
* Made it work
* Bumped lockfile
* Fixed code
* Corrected code
* Properly debug
* Fixed linting
* Made it work correctly
* Fixed missing parenthesis
* Add "output" helper
* Cleanup and use `output` helper in Now class
* Fixes
* Update `chalk` to v2.3.1
* More logging
* Finish `now deploy` using new output functions
* Remove `.only()`
* Tests are silent
* Prevent double `> >` at the beginning of the user log line
* Add "output" helper
* Cleanup and use `output` helper in Now class
* Fixes
* Update `chalk` to v2.3.1
* More logging
* Finish `now deploy` using new output functions
* Remove `.only()`
* Tests are silent
* Prevent double `> >` at the beginning of the user log line
* Added functionality for single static file deployments.
* Added friendly error message to now alias command
* Deleted temp files
* Removed empty line
* Make it work
* Removed alias message
* Corrected intentation
* Brought variable back
* Removed it
* Set correct name
* Bumped lockfile
* Added functionality for single static file deployments.
* Added friendly error message to now alias command
* Deleted temp files
* Removed empty line
* Make it work
* Removed alias message
* Corrected intentation
* Brought variable back
* Removed it
* Set correct name
* Bumped lockfile
When a domain is added with `now domains add` command it's often
because the user needs a working Zone file before changing the NS
records at the registrar or due to issues with the whois service.
Therefore the command is almost always run with `-f` flag.
Remove the `--force` option and always add send the domain add
request without client side verification.
* Updated how files are retrieved so whitelisted files specified in now.json or package.json are always added to the deployment, even if they are excluded in gitignore or npmignore.
* added new tests to check whitelisting of files in now.json and package.json and fixed/modified old tests to work with new behaviour.
* Ran linter, removed console statements.
* Wrote some documentation, fixed some typos, and removed some comments. Also ran prettier.
* Use spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Corrected indentation
* Corrected indentation
* Corrected indentation
Apparently azure deployment was listed in the docs before it was actually supported by now-cli.
I just went through and become confused by the same error message and found the issue:
https://github.com/zeit/now-cli/issues/787
It seems it's easy to remove this section and add it back later when the feature is added
Apparently azure deployment was listed in the docs before it was actually supported by now-cli.
I just went through and become confused by the same error message and found the issue:
https://github.com/zeit/now-cli/issues/787
It seems it's easy to remove this section and add it back later when the feature is added
* Updated how files are retrieved so whitelisted files specified in now.json or package.json are always added to the deployment, even if they are excluded in gitignore or npmignore.
* added new tests to check whitelisting of files in now.json and package.json and fixed/modified old tests to work with new behaviour.
* Ran linter, removed console statements.
* Wrote some documentation, fixed some typos, and removed some comments. Also ran prettier.
* Use spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Use more spaces
* Corrected indentation
* Corrected indentation
* Corrected indentation
* Start using v3 endpoint
* Make it work
* Make it bullet proof
* Hide message the second time
* Make sense
* Show upgrade link in note
* Removed useless space
* Show upgrade notice in all cases
* Start using v3 endpoint
* Make it work
* Make it bullet proof
* Hide message the second time
* Make sense
* Show upgrade link in note
* Removed useless space
* Show upgrade notice in all cases
* Correctly extract the subcommand
* Check team name charset upon every keypress
* Add missing `console.log`s
* Add missing `process.stdout.write`
* Add more missing console.logs
* Add missing return
* Add more missing `process.stdout.write`
* We have to treat `switch` differently, unfortunately
* No need to print the team id
* Fix grammar
* Correctly extract the subcommand
* Check team name charset upon every keypress
* Add missing `console.log`s
* Add missing `process.stdout.write`
* Add more missing console.logs
* Add missing return
* Add more missing `process.stdout.write`
* We have to treat `switch` differently, unfortunately
* No need to print the team id
* Fix grammar
When a domain is added with `now domains add` command it's often
because the user needs a working Zone file before changing the NS
records at the registrar or due to issues with the whois service.
Therefore the command is almost always run with `-f` flag.
Remove the `--force` option and always add send the domain add
request without client side verification.
* Bundle with compression
* Force gzip to overwrite existing compressions
* Clear directory
* Bring back progress bar
* Start using Cloudinary
* Always ungzip, since we're only shipping .gz
* Only upload .gz files
* Don't test after deployment
Exiting with 1 here doesn't crash test
* Bundle with compression
* Force gzip to overwrite existing compressions
* Clear directory
* Bring back progress bar
* Start using Cloudinary
* Always ungzip, since we're only shipping .gz
* Only upload .gz files
* Don't test after deployment
Exiting with 1 here doesn't crash test
Currently it's not possible to create a new auto-renewable
certificate if a custom certificate already exist for a domain,
as we only allow the other direction from the cli.
Add a command flag that allows overwriting a custom certificate
with an auto-renewable certificate.
`now cert create --overwrite zeit.rocks`
Currently it's not possible to create a new auto-renewable
certificate if a custom certificate already exist for a domain,
as we only allow the other direction from the cli.
Add a command flag that allows overwriting a custom certificate
with an auto-renewable certificate.
`now cert create --overwrite zeit.rocks`
The do..while loop causes event handlers to be registered
multiple times in case of an error occurs while creating a
deployment after uploading missing files. The loop doesn't
save nothing more than one call to `now.create()`.
* Simplify the `env` parsing logic
This should be 100% backwards compatible with the previous
behavior, but with some new additions:
* When using an Array in `package.json:now.env` or `now.json:env`, you
may specify the value or secret name after an `=` sign (before, the
entire string was attempted to be the env var key name, which was
just wrong _(this is the main "fix")_.
* Specifying `null` as the value of an env var in an Object forces the
user prompt (before, this was only possibly by using an Array without
an `=` sign).
* You may specify an env var on the CLI without an `=` sign and it will
show the user prompt (kind of silly since the user is invoking the
command anyways, but this works due to the new normalization)
* Less converting the env between Array and Object representations.
The code is also simpler to read now, and a few helpful comments added
as well.
* fix `now -e MY_SHELL_VAR` inheriting from user's env
It's been broken on the server-side for quite a while now,
and on top of that it's never been clear as to *how* you
get the binary value back out from within the deployment.
For these reasons, let's get rid of the option altogether.
Users who need to encode binary data as the secret value
should encode to base64 manually. For example:
```
$ now secret add my-secret $(echo 'foo' | base64)
```
* Return an empty object early when nothing to prompt
So that the `console.log()` a few lines down does
not get invoked
* Use `Object.keys()` to iterate over the answers
Fixes error:
$ now switch tootallnate
> Error! An unexpected error occurred in switch: TypeError: Cannot read property 'slug' of undefined
at module.exports (/snapshot/now-cli/dist/now.js:2995:81)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
- Don't prefix the domain with https as it may not be even using
https nor have any records
- Don't show domain ID after the domain is removed as it has no
meaning for cli users
* use `pluralize` module
Instead of manually formatting these singular vs. plural cases.
Note that `util/alias.js` was previously incorrectly always printing as
plural, which is what let me down this rabbit hole in the first place.
* Bumped pkg version
* Downgrade node temporarily
The do..while loop causes event handlers to be registered
multiple times in case of an error occurs while creating a
deployment after uploading missing files. The loop doesn't
save nothing more than one call to `now.create()`.
* Simplify the `env` parsing logic
This should be 100% backwards compatible with the previous
behavior, but with some new additions:
* When using an Array in `package.json:now.env` or `now.json:env`, you
may specify the value or secret name after an `=` sign (before, the
entire string was attempted to be the env var key name, which was
just wrong _(this is the main "fix")_.
* Specifying `null` as the value of an env var in an Object forces the
user prompt (before, this was only possibly by using an Array without
an `=` sign).
* You may specify an env var on the CLI without an `=` sign and it will
show the user prompt (kind of silly since the user is invoking the
command anyways, but this works due to the new normalization)
* Less converting the env between Array and Object representations.
The code is also simpler to read now, and a few helpful comments added
as well.
* fix `now -e MY_SHELL_VAR` inheriting from user's env
It's been broken on the server-side for quite a while now,
and on top of that it's never been clear as to *how* you
get the binary value back out from within the deployment.
For these reasons, let's get rid of the option altogether.
Users who need to encode binary data as the secret value
should encode to base64 manually. For example:
```
$ now secret add my-secret $(echo 'foo' | base64)
```
* Return an empty object early when nothing to prompt
So that the `console.log()` a few lines down does
not get invoked
* Use `Object.keys()` to iterate over the answers
Fixes error:
$ now switch tootallnate
> Error! An unexpected error occurred in switch: TypeError: Cannot read property 'slug' of undefined
at module.exports (/snapshot/now-cli/dist/now.js:2995:81)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
- Don't prefix the domain with https as it may not be even using
https nor have any records
- Don't show domain ID after the domain is removed as it has no
meaning for cli users
* use `pluralize` module
Instead of manually formatting these singular vs. plural cases.
Note that `util/alias.js` was previously incorrectly always printing as
plural, which is what let me down this rabbit hole in the first place.
* Bumped pkg version
* Downgrade node temporarily
* Fix `now alias` for domains without DNS records (#898)
* 8.3.9
* Overhaul JSON loading and parsing
Reading JSON files from disk is now simpler, with clearer error messages.
Fixes#893
* More robust JSON writing
Make directories if needed and write to disk atomically.
* Remove unused import
* Escape @ in MX record example (#900)
* Pinned dependencies
* Add missing `console.log`s
* Bubble the exit code correctly
* Clear the "final answer" output from inquirer on `now switch`
* Add more missing `console.log` :(
* Add the team slug to the success message
* Adjust `now log -f` to work with the new exit logic
* Add missing `console.log`s
* Bubble the exit code correctly
* Clear the "final answer" output from inquirer on `now switch`
* Add more missing `console.log` :(
* Add the team slug to the success message
* Adjust `now log -f` to work with the new exit logic
* look in APPDATA directory if not found in Program Files
* modifyGitBashFile to replace "now "with "now.exe"
* fix npm rm -g now
* fix fetch-h2 dep version
* look in APPDATA directory if not found in Program Files
* modifyGitBashFile to replace "now "with "now.exe"
* fix npm rm -g now
* fix fetch-h2 dep version
* Fix `now alias` for domains without DNS records (#898)
* 8.3.9
* Ensure that `now logout` revokes the token (#920)
* 8.3.10
* instead of opening url with xdg-open (which is causing #911), print the URL for the user to open or click, as diff versions of xdg-open may be needed on various linux distros and opn has some issues within pkg.
* adds check for the platform, uses opn on windows/mac and just prints out URL for linux
* fixed runtime issues
* Fix `now alias` for domains without DNS records (#898)
* 8.3.9
* Escape @ in MX record example (#900)
* Remove duplication of deployment complete print out
* Use v2 now API
v2 API requires the client to upload files before creating a
deployment.
Conflicting record is just the right record in most of the cases
and in other cases altering the record would break something
explicitly setup by the user.
* Fix `now alias` for domains without DNS records (#898)
* 8.3.9
* Ensure that `now logout` revokes the token (#920)
* 8.3.10
* instead of opening url with xdg-open (which is causing #911), print the URL for the user to open or click, as diff versions of xdg-open may be needed on various linux distros and opn has some issues within pkg.
* adds check for the platform, uses opn on windows/mac and just prints out URL for linux
* Fix `now alias` for domains without DNS records (#898)
* 8.3.9
* Ensure that `now logout` revokes the token (#920)
* 8.3.10
* instead of opening url with xdg-open (which is causing #911), print the URL for the user to open or click, as diff versions of xdg-open may be needed on various linux distros and opn has some issues within pkg.
* adds check for the platform, uses opn on windows/mac and just prints out URL for linux
* fixed runtime issues
* Fix `now alias` for domains without DNS records (#898)
* 8.3.9
* Ensure that `now logout` revokes the token (#920)
* 8.3.10
* instead of opening url with xdg-open (which is causing #911), print the URL for the user to open or click, as diff versions of xdg-open may be needed on various linux distros and opn has some issues within pkg.
* adds check for the platform, uses opn on windows/mac and just prints out URL for linux
Conflicting record is just the right record in most of the cases
and in other cases altering the record would break something
explicitly setup by the user.
* Fix `now alias` for domains without DNS records (#898)
* 8.3.9
* Overhaul JSON loading and parsing
Reading JSON files from disk is now simpler, with clearer error messages.
Fixes#893
* More robust JSON writing
Make directories if needed and write to disk atomically.
* Remove unused import
* Escape @ in MX record example (#900)
* Pinned dependencies
* Fix `now alias` for domains without DNS records (#898)
* 8.3.9
* Escape @ in MX record example (#900)
* Remove duplication of deployment complete print out
* Use v2 now API
v2 API requires the client to upload files before creating a
deployment.
Consider a deployment with an app name that matches the
alias URL. Rather than matching what deployment the alias
points to, we would match the first deployment where that
name equals the alias doman name, which is not correct.
Instead of trying to figure out whether a custom domain resolves
to a certain IP address we could just try to make a `HEAD` request
and check the `Server` header in the response. This change will
make the cli ready for anycast DNS that may resolve to any
location.
* Added two example error links
* More messages added
* Even more cool stuff
* Removed useless assignments
* Weird stuff removed
* Fixed exiting
* Added missing space
* Added another error message
* Remove the hack
That hack removed the path user/repo from argv
* Use rawPath instead of path
With path it's going to always pass that try, we need to check the the rawPath is valid not the path
* Make GH, relative path and current path deployments work
* Remove semicolon
* Fixed linting
* Use `mri` for setting the token
* Ability to set team scope using `--team` flag
* Added correct utils
* Handle 403 errors
* Better 403 error message
* Made it even more bullet proof
* Added to usage information
* Cleaned up help for `now scale`
* Made it even better
* Fixed dot notation
* Perfected secrets help
* Cleaned up teams help
* Help for upgrade cmd
* Fixed even more
* Help for login command
* Made output work for command
* Cleaned up domains help
* Cleaned up all remaining commands
* Fixed indentation for alias command
* Missing flag added
* Another missing flag added
* Replaced `minimist` with `mri` (faster and lighter)
* Cleaned up help for `now scale`
* Made it even better
* Fixed dot notation
* Perfected secrets help
* Cleaned up teams help
* Help for upgrade cmd
* Fixed even more
* Help for login command
* Made output work for command
* Cleaned up domains help
* Cleaned up all remaining commands
* Fixed indentation for alias command
* Missing flag added
* Another missing flag added
* Fixed help
* Added new config flag to usage info
* Different available short names for flags
* Made global config flag work
* Existance of global now dir is already handled
* Made it all work
* Revert "Deploy on Now if no provider is specified (#821)"
This reverts commit bbb33417ee.
* Revert "Made `now whoami` return the correct team context (#823)"
This reverts commit a9e6e6c247.
* Use same function to verify the deployed function
* Use Google CloudFunction property names
* change gcpConfig.name to gcpConfig.functionName
* availableMemoryMb => memory
When contributing to this repository, please first discuss the change you wish to make via [GitHub Discussions](https://github.com/vercel/vercel/discussions/new) with the owners of this repository before submitting a Pull Request.
Please read our [Code of Conduct](CODE_OF_CONDUCT.md) and follow it in all your interactions with the project.
## Local development
This project is configured in a monorepo, where one repository contains multiple npm packages. Dependencies are installed and managed with `pnpm`, not `npm` CLI.
To get started, execute the following:
```
git clone https://github.com/vercel/vercel
cd vercel
corepack enable
pnpm install
pnpm bootstrap
pnpm build
pnpm lint
pnpm test-unit
```
Make sure all the tests pass before making changes.
### Running Vercel CLI Changes
You can use `pnpm dev` from the `cli` package to invoke Vercel CLI with local changes:
```
cd ./packages/cli
pnpm dev <cli-commands...>
```
See [CLI Local Development](../packages/cli#local-development) for more details.
## Verifying your change
Once you are done with your changes (we even suggest doing it along the way), make sure all the tests still pass by running:
```
pnpm test-unit
```
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 Vercel account using the `test` project name. After each test is deployed, the `probes` key is used to check if the response is the expected value. If the value doesn't match, you'll see a message explaining the difference. If the deployment failed to build, you'll see a more generic message like the following:
```
[Error: Fetched page https://test-8ashcdlew.vercel.app/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` to see the build error. In the case above, that would be https://test-8ashcdlew.vercel.app/_logs
The logs of this deployment will contain the actual error which may help you to understand what went wrong.
### @vercel/nft
Some of the Builders use `@vercel/nft` 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
const{nodeFileTrace}=require('@vercel/nft');
nodeFileTrace(['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 the imported files. If anything file is missing, the bug is in [@vercel/nft](https://github.com/vercel/nft) 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 `vercel dev` or 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/node`
2. Run `pnpm build` to compile typescript and other build steps
3. Run `npm pack` to create a tarball file
4. Run `vercel *.tgz` to upload the tarball file and get a URL
5. Edit any existing `vercel.json` project and replace `use` with the URL
6. Run `vercel` or `vercel dev` to deploy with the experimental Builder
This directory is a brief example of a [Name](site-link) site that can be deployed to Vercel with zero configuration.
## Deploy Your Own
Deploy your own [Name] project with Vercel.
[](https://vercel.com/new/clone?repository-url=https://github.com/vercel/vercel/tree/main/example-directory)
### How We Created This Example
To get started with [Name] on Vercel, you can use the [CLI Tool Used](CLI-link) to initialize the project:
```shell
$ vercel init [Name]]
```
### Deploying From Your Terminal
Once initialized, you can deploy the [Name] example with just a single command:
We do try to keep issues in this repository focused on the vercel command line and related code.
At this point we think that this issue is best handled by our friendly Vercel support team. They can be found by contacting them at: https://vercel.com/help#issues
If you think closing of this is a mistake, then please re-open this issue and we'll take another look :bow:
The following page is a reference for how to create a Runtime by implementing
the Runtime API interface. It's a way to add support for a new programming language to Vercel.
> Note: If you're the author of a web framework, please use the [Build Output API](https://vercel.com/docs/build-output-api/v3) instead to make your framework compatible with Vercel.
A Runtime is an npm module that implements the following interface:
The `version` property and the `build()` function are the only _required_ fields.
The rest are optional extensions that a Runtime _may_ implement in order to
enhance functionality. These functions are documented in more detail below.
Official Runtimes are published to [the npm registry](https://npmjs.com) as a package and referenced in the `use` property of the `vercel.json` configuration file.
> **Note:** The `use` property in the `builds` array will work with any [npm
> install argument](https://docs.npmjs.com/cli/install) such as a git repo URL,
> which is useful for testing your Runtime. Alternatively, the `functions` property
> requires that you specify a specific tag published to npm, for stability purposes.
See the [Runtimes Documentation](https://vercel.com/docs/runtimes) to view example usage.
## Runtime Exports
### `version`
A **required** exported constant that decides which version of the Runtime API to use.
The latest and suggested version is `3`.
**Example:**
```typescript
exportconstversion=3;
```
### `build()`
A **required** exported function that returns a Serverless Function.
> What's a Serverless Function? Read about [Serverless Functions](https://vercel.com/docs/concepts/functions/serverless-functions) to learn more.
// In this example, the child process will write the port number to FD 3…
constportPipe=child.stdio[3];
constchildPort=awaitnewPromise(resolve=>{
portPipe.setEncoding('utf8');
portPipe.once('data',data=>{
resolve(Number(data));
});
});
return{pid: child.pid,port: childPort};
}
```
### Execution Context
- Runtimes are executed in a Linux container that closely matches the Servereless Function runtime environment.
- The Runtime code is executed using Node.js version **12.x**.
- 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),
[`prepareCache()`](#preparecache), etc.) are not guaranteed to be run in the
same process, but the filesystem we expose (e.g.: `workPath` and the results
of calling [`getWritableDirectory`](#getWritableDirectory) ) 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`.
### Accessing Environment and Secrets
The env and secrets specified by the user as `build.env` are passed to the Runtime process. This means you can access user env via `process.env` in Node.js.
### Supporting Large Environment
We provide the ability to support more than 4KB of environment (up to 64KB) by way of
a Lambda runtime wrapper that is added to every Lambda function we create. These are
supported by many of the existing Lambda runtimes, but custom runtimes may require
additional work.
The following Lambda runtime families have built-in support for the runtime wrapper:
-`nodejs`
-`python` (>= 3.8)
-`ruby`
-`java11`
-`java8.al2` (not `java8`)
-`dotnetcore`
If a custom runtime is based on one of these Lambda runtimes, large environment
support will be available without further configuration. Custom runtimes based on
other Lambda runtimes, including those that provide the runtime via `provided` and
`provided.al2`, must implement runtime wrapper support and indicate it via the
`supportsWrapper` flag when calling [`createLambda`](<#createlambda()>).
To add support for runtime wrappers to a custom runtime, first check the value of the
`AWS_LAMBDA_EXEC_WRAPPER` environment variable in the bootstrap script. Its value is
the path to the wrapper executable.
The wrapper must be passed the path to the runtime as well as any parameters that the
runtime requires. This is most easily done in a small `bootstrap` script.
In this simple `bash` example, the runtime is called directly if
`AWS_LAMBDA_EXEC_WRAPPER` has no value, otherwise the wrapper is called with the
This is achieved by using `exec` in `bash` to replace the running process with the wrapper,
maintaining the same PID and environment.
Once support for runtime wrappers is included, ensure `supportsWrapper` is set to
`true` in the call to [`createLambda`](<#createlambda()>). This will inform the build
process to enable large environment support for this runtime.
### Utilities as peerDependencies
When you publish your Runtime to npm, make sure to not specify `@vercel/build-utils` (as seen below in the API definitions) as a dependency, but rather as part of `peerDependencies`.
## `@vercel/build-utils` Types
### `Files`
```typescript
import{File}from'@vercel/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:
```javascript
{
"index.html":FileRef,
"api/index.js":Lambda
}
```
### `File`
This is an abstract type that can be imported if you are using TypeScript.
```typescript
import{File}from'@vercel/build-utils';
```
Valid `File` types include:
- [`FileRef`](#fileref)
- [`FileFsRef`](#filefsref)
- [`FileBlob`](#fileblob)
### `FileRef`
```typescript
import{FileRef}from'@vercel/build-utils';
```
This is a [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`
```typescript
import{FileFsRef}from'@vercel/build-utils';
```
This is a [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](#FileFsRef) from `Stream`, placing file at `fsPath` with `mode`
-`toStream(): Stream` creates a [Stream](https://nodejs.org/api/stream.html) of the file body
### `FileBlob`
```typescript
import{FileBlob}from'@vercel/build-utils';
```
This is a [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](#FileBlob) 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`
```typescript
import{Lambda}from'@vercel/build-utils';
```
This is a [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) that represents a Serverless Function. An instance 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, invoke the [`createLambda`](#createlambda) helper function.
**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
-`supportsWrapper: Boolean` set to true to indicate that Lambda runtime wrappers are supported by this runtime
### `LambdaRuntime`
This is an abstract enumeration type that is implemented by one of the following possible `String` values:
-`nodejs18.x`
-`nodejs16.x`
-`nodejs14.x`
-`go1.x`
-`java11`
-`python3.9`
-`dotnet6`
-`dotnetcore3.1`
-`ruby2.7`
-`provided.al2`
## `@vercel/build-utils` Helper Functions
The following is exposed by `@vercel/build-utils` to simplify the process of writing Runtimes, 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`
```typescript
import{glob}from'@vercel/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)):
Vercel is the platform for frontend developers, providing the speed and reliability innovators need to create at the moment of inspiration.
We enable teams to iterate quickly anddevelop, preview, and shipdelightful user experiences. Vercel has zero-configuration support for 35+ frontend frameworks and integrates with your headless content, commerce, or database of choice.
## Deploy
Get started by [importing a project](https://vercel.com/new) or using the [Vercel CLI](https://vercel.com/cli). Then, `git push` to deploy.
## Documentation
For details on how to use Vercel, check out our [documentation](https://vercel.com/docs).
## Contributing
This project uses [pnpm](https://pnpm.io/) to install dependencies and run scripts.
You can use the `dev` script to run local changes as if you were invoking Vercel CLI. For example, `vercel deploy --cwd=/path/to/project` could be run with local changes with `pnpm dev deploy --cwd=/path/to/project`.
See the [Contributing Guidelines](./.github/CONTRIBUTING.md) for more details.
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 Vercel DNS and you’re getting this error,
it could be that:
- The domain was acquired recently, and it might not be ready for use yet.
- 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 Vercel DNS and you’re getting this
error, the following methods could help:
- When solving challenges _manually_, ensure that the TXT
records required to solve the challenges exist and are propagated. You can do so by querying the nameservers with `nslookup -q=TXT _acme-challenge.domain.com` depending on the Common Names you want for your certificate.
- 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 deploying this project, there was not a successful deployment into the `READY` state.
## How to Fix It
This is a generic error to catch problems in the deployment. The error is likely to vary depending on the deployment and the conditions at the time.
Try looking in the logs for information about the deployment and the failure, this could be done at (vercel.com)[https://vercel.com]. You can also use the `vc logs` command to display the build logs for the deployment.
This might not be a permanent error and retrying the deployment might also resolve it.
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 Vercel DNS and you’re getting this error,
it could be that:
- The domain was acquired recently, and it might not be ready for use yet.
- 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 Vercel DNS and you’re getting this
error, you must ensure that you have an `ALIAS` and `CNAME` records in place.
Ensure also that you have disabled automatic redirects to `https` and ensure all changes were propagated.
The domain you supplied cannot be verified using the intended nameservers.
#### Possible Way to Fix It
Apply the intended set of nameservers to your domain.
You can retrieve both the intended nameservers and TXT verification record for the domain you wish to verify by running `vercel domains inspect <domain>`.
Vercel will also automatically check periodically that your domain has been verified and automatically mark it as such if we detect either verification method on the domain.
If you would not like to verify your domain, you can remove it from your account using `vercel domains rm <domain>`.
When defining custom routes a route was added that causes an error during parsing. This can be due to trying to use normal `RegExp` syntax like negative lookaheads (`?!exclude`) without following `path-to-regexp`'s syntax for it.
#### Possible Ways to Fix It
Wrap the `RegExp` part of your `source` as an un-named parameter.
**Before**
```js
{
source:'/feedback/(?!general)',
destination:'/api/feedback/general'
}
```
**After**
```js
{
source:'/feedback/((?!general).*)',
destination:'/api/feedback/general'
}
```
Ensure any segments used in the `destination` property are also used in the `source` property.
The `--token` flag was specified, but its contents are invalid.
#### Possible Ways to Fix It
The `--token` flag must only contain numbers (0-9) and letters from the alphabet (a-z and A-Z). This needs to be the token of the user account as which you'd like to act.
You can either get the token from the `./vercel/auth.json` file located in your user directory or [from the dashboard](https://vercel.com/account/tokens).
You ran `vercel dev` inside a project that contains a `vercel.json` file with `env` or `build.env` properties that use [Vercel Secrets](https://vercel.com/docs/concepts/projects/environment-variables).
In order to use environment variables in your project locally that have values defined using the Vercel Secrets format (e.g. `@my-secret-value`), you will need to provide the value as an environment variable using a `.env`.
We require this to ensure your app works as you intend it to, in the development 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 `.env`.
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://vercel.com/docs/concepts/projects/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://vercel.com/my-team`, you would set `--scope` to `my-team`.
The `--token` 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 `--token` flag. This needs to be the token of the user account as which you'd like to act.
You can either get the token from the `./vercel/auth.json` file located in your user directory or [from the dashboard](https://vercel.com/account/tokens).
`@vercel/next` by default now bundles pages into optimized functions, minimizing bootup time and increasing overall application throughput.
When legacy `routes` are added in `now.json` or `vercel.json`, they cause conflicts with this optimization, so it is opted-out.
#### Possible Ways to Fix It
Migrate from using legacy `routes` to the new `rewrites`, `redirects`, and `headers` configurations in your `now.json` or `vercel.json` file or leverage them directly in your `next.config.js` with the built-in [custom routes support](https://github.com/vercel/next.js/issues/9081)
You're running Vercel CLI in a non-terminal context and there are no credentials available. This means that Vercel CLI is not able to authenticate against our service.
#### Possible Ways to Fix It
- Specify a value for the `--token` flag (this needs to be the token of the user account as which you'd like to act). You can create a new token on your [Settings page](https://vercel.com/account/tokens).
- Run `vercel login` to sign in and generate a new token
You attempted to create a Vercel deployment where the input is a file, rather than a directory. Previously this was allowed, however this behavior has been removed as of Vercel CLI v24.0.0 because it exposed a potential security risk if the user accidentally created a deployment from a sensitive file.
#### Possible Ways to Fix It
- Run the `vercel deploy` command against a directory, instead of a file.
You tried to run a command that doesn't allow the `--token` flag (like `vercel switch`). This is not allowed because commands like these are influencing the configuration files.
In turn, they would have to take the value of the `--token` flag into consideration (which is not a good idea, because flags in Vercel CLI should never change the configuration).
#### Possible Ways to Fix It
Specify a value for the `--scope` flag. This needs to be the slug or ID of the team as which you'd like to act (as an example, if your team URL is `https://vercel.com/my-team`, the value can be `my-team`) or the username or ID of a user you'd like to act as.
The `package.json` file of the used project invokes `vercel dev` as `dev` script. This would cause `vercel 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.
`@vercel/next` has two modes: `legacy` and `serverless`. You will always want to use the `serverless` mode. `legacy` is to provide backwards compatibility with previous `@vercel/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/vercel/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/vercel/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
#### 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`
This error occurs when your application is not configured for Serverless Next.js build output.
#### 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. Check [Node.js Version](https://vercel.link/node-version) in your Project Settings. Using an old or incompatible version of Node.js can cause the Build Step to fail with this error message.
3. Add the `now-build` script to your `package.json` [deprecated]
```json
{
"scripts":{
"now-build":"next build"
}
}
```
4. Add `target: 'serverless'` to `next.config.js` [deprecated]
```js
module.exports={
target:'serverless',
// Other options
};
```
5. Remove `distDir` from `next.config.js` as `@vercel/next` can't parse this file and expects your build output at `/.next`
6. Optionally make sure the `"src"` in `"builds"` points to your application `package.json`
6. Make sure you have the correct Node.js version selected for your build step in your project settings (`https://vercel.com/[username]/[project]/settings`)
This error is often caused by a misconfigured "Build Command" or "Output Directory" for your Next.js project.
#### Possible Ways to Fix It
In the Vercel dashboard, open your "Project Settings" and draw attention to "Build & Development Settings":
1. Ensure that the "Build Command" setting is not overridden, or that it calls `next build`. If this command is not overridden but you are seeing this error, double check that your `build` script in `package.json` calls `next build`. If `buildCommand` exists in `vercel.json`, make sure it calls `next build`.
2. Ensure that the "Output Directory" setting is not overridden. This value almost never needs to be configured, and is only necessary if you override `distDir` in `next.config.js`. If `outputDirectory` exists in `vercel.json`, remove that property.
3. For `next export` users: **do not override the "Output Directory"**, even if you customized the `next export` output directory. It will automatically detects the correct output.
In rare scenarios, this error message can also be caused by a Next.js build failure (if your "Build Command" accidentally returns an exit code that is not 0).
Double check for any error messages above the Routes Manifest error, which may provide additional details.
You either tried to run Vercel CLI inside a directory that should never be deployed, or you specified a directory that should never be deployed like this: `vercel <directory>`.
#### Possible Ways to Fix It
Make sure that you're not trying to deploy one of these directories:
- User
- Downloads
- Desktop
These directories are not supported for security reasons.
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 `vercel ls` work just fine. This will ensure that your user credentials are valid. If it's not working correctly, please log in again using `vercel login`.
- If you're using the `--token` flag, make sure your token is not expired. You can generate a new token on your [Settings page](https://vercel.com/account/tokens).
- Ensure that the scope you specified using `--scope` flag shows up in the output of `vercel switch`. If it doesn't, you're either not a member of the team or you logged into the wrong user account. You can ask an owner of the team to invite you.
You specified the `--scope` flag and specified the ID or slug of a team that does not exist or that you're not a member. Similarly you might have specified the ID or username of user whose account you don't own.
#### Possible Ways to Fix It
- Make sure commands like `vercel ls` work just fine. This will ensure that your user credentials are valid. If it's not working correctly, please log in again using `vercel login`.
- If you're using the `--token` flag, make sure your token is not expired. You can generate a new token on your [Settings page](https://vercel.com/account/tokens).
- Ensure that the scope you specified using `--scope` flag shows up in the output of `vercel switch`. If it doesn't, you're either not a member of the team or you logged into the wrong user account. You can ask an owner of the team to invite you.
You tried to add or update a domain's configuration, but you don't have permission to modify the domain.
#### Possible Ways to Fix It
If you or your team owns the domain, then you are most likely in the wrong context. Use `vercel switch` to select the team or user that owns the domain.
To get started using any of these examples as your own project, [install Vercel](https://vercel.com/cli) and use either of the following commands in your terminal:
```sh
vercel init # Pick an example in the CLI
vercel init <example> # Create a new project from a specific <example>
vercel init <example> <name> # Create a new project from a specific <example> with a different folder <name>
```
Deploying your project can be done with **a single command**:
```sh
vercel # Deploy your project with the CLI
```
With the `vercel` command, your project will be built and served by Vercel, providing you with a URL that can be shared immediately.
## How to Contribute
Contributing examples should be an enjoyable experience, as such we have created a set of [contributing guidelines](https://github.com/vercel/vercel/blob/main/.github/CONTRIBUTING.md) to help you do so.
The guidelines cover important information such as the requirements for new examples and where to get help if you have any questions.
We have tried to make contributing to examples as easy as possible, especially for those new to Open Source. If anything is unclear or you have any questions then please reach out to us on [GitHub Discussions](https://github.com/vercel/vercel/discussions) where we will do our best to help you.
## Reporting Issues
We actively encourage our community to raise issues and provide feedback on areas of examples that could be improved.
An issue can be raised by clicking the 'Issues' tab at the top of the repository, followed by the Green 'New issue' button.
When submitting an issue, please thoroughly and concisely describe the problem you are experiencing so that we may easily understand and resolve the issue in a timely manner.
## Get In Touch
If you have any questions that are not covered by raising an issue then please get in touch with us on [GitHub Discussions](https://github.com/vercel/vercel/discussions). There you will find both members of the community and staff who are happy to help answer questions on anything Vercel related.
[](https://github.com/vercel/vercel/discussions)
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.