Compare commits

...

182 Commits

Author SHA1 Message Date
Nathan Rajlich
45bd855250 Publish Stable
- @vercel/build-utils@5.5.4
 - vercel@28.4.7
 - @vercel/client@12.2.12
 - @vercel/go@2.2.12
 - @vercel/hydrogen@0.0.25
 - @vercel/next@3.2.3
 - @vercel/node@2.5.22
 - @vercel/python@3.1.21
 - @vercel/redwood@1.0.30
 - @vercel/remix@1.0.31
 - @vercel/ruby@1.3.38
 - @vercel/static-build@1.0.30
2022-10-05 12:41:42 -07:00
Nathan Rajlich
49de8ad9a0 [node] Update edge-runtime to v1.1.0-beta.37 (#8687)
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.
2022-10-05 19:33:53 +00:00
JJ Kasper
a1ea56fd67 [next] Update max route src check for generated route (#8689)
### 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
2022-10-05 19:18:41 +00:00
JJ Kasper
e88addc9ed [next] Fix legacy pages/404 case (#8682)
### 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
2022-10-05 14:21:10 +00:00
Peter van der Zee
5d50013f93 [build-utils] Allow file-ref sema to be controlled through env flag (#8681)
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 :)
2022-10-05 13:21:27 +00:00
Lee Robinson
44e1eb3983 Update CLI README (#8675)
:another-one:
2022-10-04 04:48:10 +00:00
Lee Robinson
f8af013349 Update README (#8674)
Small changes 😄
2022-10-04 04:13:41 +00:00
Steven
972cc495ec [tests] Replace cancel-workflow-action with native cancel-in-progress (#8671)
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
2022-10-03 23:49:28 +00:00
Steven
1c580da3d8 [cli] Fix vc build to error early when runtime is discontinued (#8669)
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.
2022-10-03 22:07:02 +00:00
Steven
244554ab1b [tests] Remove nodejs12.x tests (#8667)
Now that `nodejs12.x` has passed the sunset date, new deployments will fail so we need to update a few tests.

https://vercel.com/changelog/node-js-12-is-being-deprecated
2022-10-03 20:59:05 +00:00
Steven
053c185481 Publish Stable
- vercel@28.4.6
 - @vercel/client@12.2.11
 - @vercel/next@3.2.2
2022-10-03 10:07:07 -04:00
JJ Kasper
8805b586ea [next] Allow revalidating ISR 404 path itself (#8663)
### 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
2022-10-02 13:09:24 +00:00
Chris Barber
681070ffa0 [tests] Adding test for next builder OS path separator for serverless file refs (#8661)
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
2022-09-30 18:29:39 +00:00
Chris Barber
362b17d60a [next] Use OS path separator to match serverless file references (#8657)
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
2022-09-30 15:25:33 +00:00
JJ Kasper
c7c9b1a791 [next] Update RSC header in has routes (#8651)
### 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
2022-09-28 13:24:01 -07:00
Nathan Rajlich
c42f309463 [cli] Print upload progress in increments of 25% when non-TTY (#8650)
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.
2022-09-28 19:33:33 +00:00
Sean Massa
a0ead28369 [tests] replace spinner messages with normal output during tests (#8634)
Convert spinner output to simple prints during test runs. This makes it easier to write tests against the output of commands.
2022-09-28 17:52:40 +00:00
chloetedder
8814fc1515 Publish Stable
- @vercel/build-utils@5.5.3
 - vercel@28.4.5
 - @vercel/client@12.2.10
 - @vercel/fs-detectors@3.4.1
 - @vercel/go@2.2.11
 - @vercel/hydrogen@0.0.24
 - @vercel/next@3.2.1
 - @vercel/node@2.5.21
 - @vercel/python@3.1.20
 - @vercel/redwood@1.0.29
 - @vercel/remix@1.0.30
 - @vercel/ruby@1.3.37
 - @vercel/static-build@1.0.29
2022-09-28 10:14:27 -05:00
chloetedder
0d044b4eac [fs-detectors] Use json5 parser for Rush to have valid json parsing (#8645)
### 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>
2022-09-28 06:38:25 -05:00
Steven
f6bd1aa8c0 [tests] Remove console.log() from test (#8647)
Remove `console.log()` from test
2022-09-27 23:38:49 +00:00
Steven
8cd84ec066 Publish Stable
- @vercel/build-utils@5.5.2
 - vercel@28.4.4
 - @vercel/client@12.2.9
 - @vercel/go@2.2.10
 - @vercel/hydrogen@0.0.23
 - @vercel/next@3.2.0
 - @vercel/node@2.5.20
 - @vercel/python@3.1.19
 - @vercel/redwood@1.0.28
 - @vercel/remix@1.0.29
 - @vercel/ruby@1.3.36
 - @vercel/static-build@1.0.28
2022-09-27 16:35:00 -04:00
Steven
a8df231e4c [build-utils] Fix npm version detection for --legacy-peer-deps (#8646)
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
2022-09-27 16:33:24 -04:00
Gal Schlezinger
f674842bed [next] read regions from middleware-manifest output (#8629)
### 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>
2022-09-27 10:46:02 -07:00
Steven
bf5cfa9a41 Publish Stable
- @vercel/build-utils@5.5.1
 - vercel@28.4.3
 - @vercel/client@12.2.8
 - @vercel/go@2.2.9
 - @vercel/hydrogen@0.0.22
 - @vercel/next@3.1.30
 - @vercel/node@2.5.19
 - @vercel/python@3.1.18
 - @vercel/redwood@1.0.27
 - @vercel/remix@1.0.28
 - @vercel/ruby@1.3.35
 - @vercel/static-build@1.0.27
2022-09-27 09:39:04 -04:00
JJ Kasper
12121b7a71 [next] Fix build time 404 route with trailingSlash: true (#8627)
This ensures we properly handle trailing slashes in the `notFound: true` build time routes. 

Fixes: [slack thread](https://vercel.slack.com/archives/C03S8ED1DKM/p1663691719703509)
2022-09-27 09:21:49 -04:00
Steven
baa56aed2c [tests] Fix timeout for actions/setup-node (#8639)
Try fixing the timeout again. For example: https://github.com/vercel/vercel/actions/runs/3130757219/jobs/5081381465

- Follow up to #8613 
- Related to https://github.com/actions/cache/issues/810 
- Related to https://github.com/Azure/azure-sdk-for-js/issues/22321
2022-09-26 18:33:43 -04:00
Steven
6f767367e4 [build-utils] Adjust nodejs12.x discontinueDate to Monday (#8638)
The previous date was on a Saturday so lets move it to the following Monday to ensure support tickets are quickly answered.
2022-09-26 22:22:32 +00:00
Sean Massa
0e4124f94c [cli] fix vc bisect off by one (#8399)
Co-authored-by: Nathan Rajlich <n@n8.io>
2022-09-26 14:47:15 -05:00
Sean Massa
30503d0a3f [go] remove unused, breaking watchlist from Go builder (#8633) 2022-09-26 14:31:36 -05:00
Steven
6c9164f67d [cli] Refactor doBuild to return void (#8626)
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.
2022-09-24 01:25:59 +00:00
Steven
906b7a8f2c [cli] Fix invalid vercel.json config error serialization (#8623)
Follow up to #8622 since we should be throwing errors so the error is correctly serialized to `builds.json`.
2022-09-23 22:08:53 +00:00
Steven
43499b13d8 [cli] Add vercel.json validation to vercel build (#8622)
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.
2022-09-23 20:33:28 +00:00
Sean Massa
7d6e56670f [cli][dev] Add strict mode to vc dev edge function handlers (#8616)
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.
2022-09-23 14:23:03 +00:00
Sean Massa
dba337f148 [cli][dev] extract edge/serverless handler logic into separate files (#8615) 2022-09-22 16:34:32 -05:00
Steven
a825bc9540 Publish Stable
- @vercel/build-utils@5.5.0
 - vercel@28.4.2
 - @vercel/client@12.2.7
 - @vercel/go@2.2.8
 - @vercel/hydrogen@0.0.21
 - @vercel/next@3.1.29
 - @vercel/node@2.5.18
 - @vercel/python@3.1.17
 - @vercel/redwood@1.0.26
 - @vercel/remix@1.0.27
 - @vercel/ruby@1.3.34
 - @vercel/static-build@1.0.26
2022-09-22 16:50:27 -04:00
JJ Kasper
f5486a8297 [next] Update to route app rsc paths correctly (#8611)
### Related Issues

x-ref: [slack thread](https://vercel.slack.com/archives/C035J346QQL/p1663799417151099)

Failing probes are unrelated, more info can be seen in [this thread](https://vercel.slack.com/archives/C035J346QQL/p1663820032810519?thread_ts=1663775935.504379&cid=C035J346QQL)
2022-09-22 20:44:40 +00:00
Mark Glagola
225e0a4de3 [tests] Use new VERCEL_TEST_TOKEN for tests (#8614)
Use `VERCEL_TEST_TOKEN` for tests
2022-09-22 16:07:43 -04:00
Steven
0ecfdc1325 [tests] Add timeout for broken actions/setup-node@v3 (#8613)
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
2022-09-22 14:42:48 +00:00
Gal Schlezinger
628409d233 [build-utils] support providing execution regions in Edge Functions (#8612) 2022-09-22 14:38:33 +03:00
Steven
51d968314f Publish Stable
- vercel@28.4.1
 - @vercel/fs-detectors@3.4.0
 - @vercel/next@3.1.28
 - @vercel/node@2.5.17
2022-09-21 18:47:45 -04:00
Chris Barber
b4e2cbc6e5 [tests] Test route src and dest for normalized path (#8609)
Adding assertions for normalized routes.
2022-09-21 18:44:52 -04:00
Jiachi Liu
7323beea8e [next] fix app dir SSG deployment paths (#8608)
### 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>
2022-09-21 15:40:38 -07:00
Chris Barber
e4bb311144 [cli] Disable git status background index refresh/optimization (#8569)
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
2022-09-21 21:47:10 +00:00
Andrew Gadzik
288546659d [fs-detectors] ensure processing of potentialFiles for readdir cache hits (#8604)
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
2022-09-21 20:59:21 +00:00
Sean Massa
822224e212 [cli][dev] Use browser platform when bundling edge functions for vc dev (#8605) 2022-09-21 15:50:22 -05:00
Nathan Rajlich
6b23950b65 [cli] Don't set analyticsId when Vercel Analytics are disabled in "vc pull" (#8607)
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.
2022-09-21 19:54:34 +00:00
Chris Barber
1558f21e49 [tests] Added lock file for normalize paths test fixture (#8600)
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
2022-09-21 19:31:27 +00:00
chloetedder
a6aee8b904 [fs-detectors] Rush json workspace (#8603)
### 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
2022-09-21 13:00:21 -05:00
Steven
27f4034bdc Publish Stable
- @vercel/build-utils@5.4.4
 - vercel@28.4.0
 - @vercel/client@12.2.6
 - @vercel/go@2.2.7
 - @vercel/hydrogen@0.0.20
 - @vercel/next@3.1.27
 - @vercel/node@2.5.16
 - @vercel/python@3.1.16
 - @vercel/redwood@1.0.25
 - @vercel/remix@1.0.26
 - @vercel/ruby@1.3.33
 - @vercel/static-build@1.0.25
2022-09-21 09:24:15 -04:00
Steven
e43b968fbe [build-utils] Retry with legacy peer deps on install failure (#8598)
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)
```
2022-09-21 13:14:21 +00:00
Chris Barber
48eb720556 [build-utils][next] Remove Path once copied to PATH. (#8596)
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
2022-09-20 22:10:26 +00:00
Steven
30e4d74db6 [tests] Add turbo caching to publish (#8597) 2022-09-20 20:50:56 +00:00
Steven
75840896ee [tests] Update workflows to use global env (#8594)
Follow up to #8586 because [that syntax](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-environment-variable) never worked on windows
2022-09-20 20:16:54 +00:00
Nathan Rajlich
9657bda86d [cli] Add "images" optimization configuration support in vercel.json (#8566)
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.
2022-09-20 19:58:20 +00:00
Steven
4536029d42 Revert "[fs-detectors] Rush json workspace" (#8591)
Reverts vercel/vercel#8565 since tests are failing on windows

https://github.com/vercel/vercel/actions/runs/3091763554/jobs/5002704682
2022-09-20 15:13:23 -04:00
Steven
a35654d047 [tests] Skip test 01-normalize-routes temporarily (#8590)
The  `01-normalize-routes` test is failing on windows so we need to temporarily disable until the root cause can be corrected.
2022-09-20 14:51:01 -04:00
github-actions[bot]
f6a01a1af3 [examples] Upgrade Next.js to version 12.3.1 (#8587)
This auto-generated PR updates Next.js to version 12.3.1
Co-authored-by: Steven <steven@ceriously.com>
2022-09-20 14:13:12 -04:00
chloetedder
c2bca954e0 [fs-detectors] Rush json workspace (#8565)
### 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
2022-09-20 12:14:45 -05:00
Steven
21701c3c3d [tests] Fix turbo remote cache (#8586)
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.
2022-09-20 12:19:38 -04:00
JJ Kasper
7f4723b3f8 [next] Update local app edge test (#8588)
### 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
2022-09-19 18:15:13 -07:00
Sean Massa
619ca93421 Publish Stable
- @vercel/build-utils@5.4.3
 - vercel@28.3.0
 - @vercel/client@12.2.5
 - @vercel/frameworks@1.1.6
 - @vercel/fs-detectors@3.3.0
 - @vercel/go@2.2.6
 - @vercel/hydrogen@0.0.19
 - @vercel/next@3.1.26
 - @vercel/node@2.5.15
 - @vercel/python@3.1.15
 - @vercel/redwood@1.0.24
 - @vercel/remix@1.0.25
 - @vercel/ruby@1.3.32
 - @vercel/static-build@1.0.24
2022-09-19 16:40:10 -05:00
Steven
cea2981512 [tests] Change some runNpmInstall() unit tests to mocks (#8581)
- Closes #8580
2022-09-19 21:30:32 +00:00
JJ Kasper
1f30e3a4b7 [next] Update app test fixture (#8584)
### 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
2022-09-19 13:08:10 -07:00
Steven
20e8fdd049 [tests] Add yarn cache to github actions (#8567)
We had this enable for some workflows but not all so this PR enables the yarn cache for the remaining workflows.
2022-09-15 02:05:26 +00:00
Chris Barber
3df8313d69 [next] Use posix path separator to join routes and overrides paths (#8530)
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
2022-09-14 23:47:57 +00:00
Steven
95c9ea92c4 [build-utils] Add flag for npm install --legacy-peer-deps (#8550)
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.
2022-09-14 22:18:40 +00:00
Chris Barber
7ddebb099d [build-utils][cli][go][node][ruby][static-build] Explicitly set PATH when copying env vars (#8532)
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
2022-09-14 20:29:52 +00:00
chloetedder
6498fd1aab [fs-detectors] Add Nx Workspace (#8549)
### 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
2022-09-14 15:10:14 -05:00
Nathan Rajlich
9d7d822da3 [tests] Add test for path segments when go.mod is present (#7361)
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.
2022-09-14 19:10:49 +00:00
Nathan Rajlich
b8110d97d1 [tests] Add more tests for importBuilders() scenarios (#8554)
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`
2022-09-13 23:56:10 +00:00
Nathan Rajlich
2d9373b0f1 [tests] Fix "50-ionic-react" test fixture (#8556)
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.
```
2022-09-13 23:28:36 +00:00
Nathan Rajlich
cc7577a648 [cli] Use Builder importing logic from vc build in vc dev (#8485)
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.
2022-09-13 21:35:01 +00:00
Nathan Rajlich
f3f3d7df5b [cli] Replace "0.0.0.0" with "localhost" in vc dev (#8547)
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.
2022-09-13 18:38:42 +00:00
Steven
0bafea6d51 [tests] Fix tarball lookup with sha contains 0 (#8552)
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.
2022-09-13 18:08:45 +00:00
Nathan Rajlich
5abb74eddd [cli] Use isStaticRuntime() helper function when importing Builders (#8551) 2022-09-13 12:40:06 +00:00
Steven
23d7eaccab [frameworks] Update framework logos to be file paths (#8546)
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.
2022-09-12 23:07:46 +00:00
Nathan Rajlich
2cb008e8ed [cli] Switch to npm and add more context to install errors during Builder import (#8545)
Before:

<img width="1012" alt="Screen Shot 2022-09-09 at 7 03 01 PM" src="https://user-images.githubusercontent.com/71256/189464732-8cf6398a-9432-423b-8509-a52bd714333e.png">

After:

<img width="579" alt="Screen Shot 2022-09-12 at 12 27 31 PM" src="https://user-images.githubusercontent.com/71256/189739091-86399428-d9b8-4d03-b0e6-7d27a1037bce.png">

This is a precursor to https://github.com/vercel/vercel/pull/8485, since the last remaining test failure there is related to specialized messaging we had for these same cases.
2022-09-12 22:05:38 +00:00
chloetedder
b5c3610113 Publish Stable
- vercel@28.2.5
 - @vercel/fs-detectors@3.2.0
2022-09-12 11:32:13 -05:00
chloetedder
f23c7fc4fc [fs-detectors] Add monorepo managers (#8534)
### 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
2022-09-09 22:51:56 +00:00
Sean Massa
3dc1ad6437 [dev] consolidate dev server address parsing (#8538)
Consolidates parsing and access to `this.address` so that we don't have to `new URL(this.address)` all over the place.

---

Follow-up from: https://github.com/vercel/vercel/pull/8457#issuecomment-1238653904
2022-09-09 22:07:58 +00:00
github-actions[bot]
4dc0bef62b [examples] Upgrade Next.js to version 12.3.0 (#8537)
This auto-generated PR updates Next.js to version 12.3.0

Co-authored-by: Steven <steven@ceriously.com>
2022-09-09 17:41:41 -04:00
Sean Massa
8b3c52b9e8 Publish Stable
- vercel@28.2.4
 - @vercel/frameworks@1.1.5
 - @vercel/fs-detectors@3.1.0
 - @vercel/static-build@1.0.23
2022-09-09 16:28:36 -05:00
Sean Massa
fc74300ad0 [dev] fix middleware rewrites to relative paths that do not exist (#8535)
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.
2022-09-09 20:34:14 +00:00
Andrew Gadzik
28f8a38e00 [fs-detectors] Add the writeFile function to DetectorFilesystem (#8536)
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
2022-09-09 19:39:05 +00:00
Jacob Ford
c318ce9695 [frameworks] Detect Sanity v3 config (#8540)
Sanity v3 is currently in [developer preview](https://www.sanity.io/blog/sanity-studio-v3-developer-preview), and has deprecated `sanity.json` in the project root, replacing it with `sanity.config.js`. This should detect either.

All commands remain the same in both v2 and v3.

Co-authored-by: Steven <steven@ceriously.com>
2022-09-09 14:59:12 -04:00
Nathan Rajlich
5b36eaacff [cli] Poll the Dev Command server on both IPv4 and IPv6 in vc dev (#8542)
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
2022-09-09 14:57:50 -04:00
Chris Barber
c9f7ca23a8 [tests] Skip tests that won't run on Windows due to 'mkdir -p' and symlinks (#8531)
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
2022-09-08 14:26:30 +00:00
Sean Massa
57e0db0f65 [dev] allow middleware rewrites to change origin in vc dev (#8457)
Middleware rewrites in `vc dev` were not respecting changes to the origin. This PR implements that to match prodution.

---

Paired with: @TooTallNate
2022-09-07 20:30:10 +00:00
Steven
d5537500d8 Publish Stable
- @vercel/build-utils@5.4.2
 - vercel@28.2.3
 - @vercel/client@12.2.4
 - @vercel/frameworks@1.1.4
 - @vercel/fs-detectors@3.0.0
 - @vercel/go@2.2.5
 - @vercel/hydrogen@0.0.18
 - @vercel/next@3.1.25
 - @vercel/node@2.5.14
 - @vercel/python@3.1.14
 - @vercel/redwood@1.0.23
 - @vercel/remix@1.0.24
 - @vercel/ruby@1.3.31
 - @vercel/static-build@1.0.22
2022-09-07 15:39:47 -04:00
Andrew Gadzik
4b1736b2f2 [fs-detectors] optimize readdir for framework detection (#8497)
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
2022-09-07 15:35:56 -04:00
Sean Massa
9da1c6fa66 [tests] set retry count to 0 when running tests locally (#8529)
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.
2022-09-07 18:47:09 +00:00
Jiachi Liu
a6c320846e [@vercel/next] Handle nextjs edge routes from app dir (#8524)
### 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>
2022-09-06 16:19:28 -07:00
Shu Uesugi
4973814978 [frameworks] Update Next.js Logos (#8505)
Update them to match the new logos. See: https://vercel.com/design/brands#next-js

<img width="869" alt="Screen Shot 2022-09-02 at 10 43 52 AM" src="https://user-images.githubusercontent.com/992008/188208956-aae10437-77ef-43c8-9bc1-c2499e509a7c.png">
2022-09-02 18:06:31 +00:00
Sean Massa
f1289ff263 [node] update middleware-no-response behavior to match production changes (#8500)
Production was updated to allow middleware without responses to pass through. This PR makes `vc dev` behave the same way. Tests were updated.
2022-09-01 22:19:10 +00:00
Steven
3ff93279cd Publish Stable
- vercel@28.2.2
 - @vercel/next@3.1.24
 - @vercel/node@2.5.13
 - @vercel/redwood@1.0.22
 - @vercel/remix@1.0.23
2022-09-01 16:42:27 -04:00
Steven
58f9d649a8 [next][node][remix][redwood] Bump @vercel/nft@0.22.1 (#8502)
Bump `@vercel/nft` to version [0.22.1](https://github.com/vercel/nft/releases/tag/0.22.1)
2022-09-01 16:41:30 -04:00
JJ Kasper
cadc082ad1 [next] Fix index app dir case (#8501)
### 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
2022-09-01 12:06:18 -07:00
Steven
2906d83eae Publish Stable
- @vercel/build-utils@5.4.1
 - vercel@28.2.1
 - @vercel/client@12.2.3
 - @vercel/edge@0.0.4
 - @vercel/fs-detectors@2.1.0
 - @vercel/go@2.2.4
 - @vercel/hydrogen@0.0.17
 - @vercel/next@3.1.23
 - @vercel/node@2.5.12
 - @vercel/python@3.1.13
 - @vercel/redwood@1.0.21
 - @vercel/remix@1.0.22
 - @vercel/ruby@1.3.30
 - @vercel/static-build@1.0.21
2022-09-01 13:16:42 -04:00
Steven
675c3e2915 [cli] Change error message from Error! to Error: (#8498)
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.
2022-09-01 13:12:41 -04:00
Steven
13a8a7dbf6 [next] Revert nft to 0.21.0 (#8499)
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.
2022-09-01 09:13:35 -07:00
Andrew Gadzik
b480e632a3 Add writeFile to DetectorFilesystem (#8493)
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
2022-08-31 18:51:03 +00:00
Chris Barber
bc6c364888 [node] Added 'cause' to error message (#8467)
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
2022-08-30 02:32:38 +00:00
Steven
6cad10c899 [build-utils] Replace npm bin with custom implementation (#8483)
This PR removes `npm bin` in favor of a custom implementation since the command will be removed in npm 9.

- Related to https://github.com/npm/statusboard/issues/537
2022-08-30 01:23:34 +00:00
Gal Schlezinger
0d78ec4666 [edge] Add markdown documentation using TypeDoc (#8446) 2022-08-29 12:36:44 +03:00
Nathan Rajlich
b05d653cf1 [cli] Use unique "name" in package.json test fixtures (#8475)
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
```
2022-08-26 21:43:25 +00:00
Nathan Rajlich
5a38b94de2 [cli] Replace "progress" module with custom implementation (#8397)
The `progress` module is overkill for what we are using it for and it's inconsistent with our styling for the rest of the deployment process.

So drop the npm module in favor of an in-house progress bar implementation that can be used inside of the Ora `output.spinner()` that we already use for the other steps of the deployment process.

**Before:**

<img width="307" alt="Screen Shot 2022-08-25 at 5 07 28 PM" src="https://user-images.githubusercontent.com/71256/186790052-18431ac0-b05b-434e-b885-9eb76d880b9d.png">

**After:**

<img width="347" alt="Screen Shot 2022-08-25 at 5 09 35 PM" src="https://user-images.githubusercontent.com/71256/186790168-8dd3e9a2-863a-45cc-bd21-d98308d34e22.png">
2022-08-26 21:03:38 +00:00
Nathan Rajlich
6668d6cf21 [client] Add "tar-fs" dependency (#8473)
Fixes #8471.
2022-08-26 18:02:01 +00:00
Andrew Gadzik
b63f444abd [fs-detectors] Add a default workspace manager when there's no lock file (#8469)
This fixes an issue with this example,

https://vercel.com/api/v1/integrations/detect-eligible-projects?url=https%3A%2F%2Fgithub.com%2Fvercel%2Fturborepo%2Ftree%2Fmain%2Fexamples%2Fkitchen-sink

Where the repo has no lockfile, and hence our workspace detection fails.  This fix is to add a fallback of "npm" in this scenario

### Related Issues

Fixes https://github.com/vercel/turbo-internal/issues/232

### 📋 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
2022-08-26 16:24:13 +00:00
Steven
9d71d4332f [tests] Update codeowners for fs-detectors (#8470)
Update codeowners for `@vercel/fs-detectors` to add @agadzik and @chloetedder
2022-08-26 15:43:14 +00:00
Steven
151db21a2f [tests] Add required labels (#8464)
This action will fail if the required labels are not applied to a PR.

We allow multiple `area` labels and only a single `semver` label.

- Example failure: https://github.com/vercel/vercel/runs/8024949804?check_suite_focus=true#step:2:19
- Example success: https://github.com/vercel/vercel/runs/8026212031?check_suite_focus=true#step:2:19
2022-08-25 22:20:37 +00:00
Steven
aba9c95ea2 [tests] Change PR automerge label (#8465)
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.
2022-08-25 22:05:55 +00:00
Sean Massa
e7e0a55b72 Publish Stable
- @vercel/build-utils@5.4.0
 - vercel@28.2.0
 - @vercel/client@12.2.2
 - @vercel/go@2.2.3
 - @vercel/hydrogen@0.0.16
 - @vercel/next@3.1.22
 - @vercel/node@2.5.11
 - @vercel/python@3.1.12
 - @vercel/redwood@1.0.20
 - @vercel/remix@1.0.21
 - @vercel/ruby@1.3.29
 - @vercel/static-build@1.0.20
2022-08-25 15:50:50 -05:00
Sean Massa
c2163e3e4f [tests] Update CODEOWNERS (#8463)
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
2022-08-25 20:06:49 +00:00
Nathan Rajlich
873f549637 [cli] Normalize Builder output paths in vc dev (#8461)
Fixes https://github.com/vercel/og-image/issues/180.
2022-08-25 19:09:12 +00:00
Naoyuki Kanezawa
ead1e411ee [next] support middleware-manifest v2 (#8319)
### 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
2022-08-25 18:57:12 +00:00
Sean Massa
7c1c089a70 [tests] rename go test function (#8458)
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.
2022-08-25 15:11:05 +00:00
Ethan Arrowood
a7dbd9649b [cli] add override support for vc build and vc dev (#8451)
### 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
2022-08-25 03:00:52 +00:00
Chris Barber
2e439045c9 [cli] Improved 'vc git' help description for --yes flag (#8460)
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
2022-08-25 01:25:30 +00:00
Steven
520e0d01f4 [frameworks] Fix link to framework logo (#8459)
This link should be using our custom domain
2022-08-24 16:07:17 -04:00
Steven
3856623785 [build-utils] Prefix debug message (#8378)
This PR adds `VERCEL_DEBUG_PREFIX` environment variable which lets you set a prefix for the debug logs.
2022-08-24 18:50:20 +00:00
Steven
1c14e945f9 [tests] Reduce test logs (#8455)
This PR reduces the noisy test logs that currently look like this:

<img width="1013" alt="image" src="https://user-images.githubusercontent.com/229881/186479890-e954ca9c-782e-49b8-89e7-6409185bb490.png">
2022-08-24 14:00:10 -04:00
Steven
32357fc06f [node][next][redwood][remix] Bump @vercel/nft@0.22.0 (#8454)
This PR bumps `@vercel/nft` to version [0.22.0](https://github.com/vercel/nft/releases/tag/0.22.0)
2022-08-24 12:13:34 -04:00
Lee Robinson
f7c57dc539 [examples] Update SvelteKit example for breaking changes. (#8439)
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.
2022-08-24 15:15:50 +00:00
github-actions[bot]
34f7c35c13 [examples] Upgrade Next.js to version 12.2.5 (#8453)
This auto-generated PR updates Next.js to version 12.2.5

Co-authored-by: Vercel Team Bot <team@zeit.co>
2022-08-24 10:41:54 -04:00
Sean Massa
6700630feb Publish Stable
- @vercel/build-utils@5.3.2
 - vercel@28.1.4
 - @vercel/client@12.2.1
 - @vercel/go@2.2.2
 - @vercel/hydrogen@0.0.15
 - @vercel/next@3.1.21
 - @vercel/node@2.5.10
 - @vercel/python@3.1.11
 - @vercel/redwood@1.0.19
 - @vercel/remix@1.0.20
 - @vercel/ruby@1.3.28
 - @vercel/static-build@1.0.19
2022-08-24 09:09:02 -05:00
Sean Massa
34cd8b4144 [cli] revert git connect inside vc link (#8450) 2022-08-24 09:07:04 -05:00
Sean Massa
ad0ed6d852 Publish Stable
- vercel@28.1.3
 - @vercel/node@2.5.9
2022-08-23 16:58:19 -05:00
Gal Schlezinger
0bad09b47a [node] fix WebAssembly bindings evaluating to undefined (#8417)
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
2022-08-23 21:56:13 +00:00
Steven
5120689bf2 [tests] Fix update-next script (#8452)
Follow up to #8447 since exec returns a buffer, not a string.
2022-08-23 17:28:38 -04:00
Steven
5a39fd9242 [tests] Automatically update Next.js example periodically (#8447)
Automatically update Next.js example every 4 hours using `create-next-app`
2022-08-23 17:19:55 +00:00
Sean Massa
352cd00ef0 Publish Stable
- vercel@28.1.2
 - @vercel/go@2.2.1
2022-08-23 10:15:26 -05:00
Sean Massa
abfe817f86 [go] ignore bad go handlers and rename functions with more precision (#8422)
Co-authored-by: Steven <steven@ceriously.com>
2022-08-23 10:14:21 -05:00
Sean Massa
ebb5e2b208 Publish Stable
- vercel@28.1.1
 - @vercel/next@3.1.20
 - @vercel/python@3.1.10
2022-08-22 15:33:41 -05:00
JJ Kasper
e34858d082 [next] Add handling for app-paths-manifest (#8098)
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
2022-08-22 14:58:21 -05:00
Ikko Ashimine
f03c947f91 [python] fix typo in install.ts comment (#8442)
overriden -> overridden
2022-08-22 11:58:27 -04:00
JJ Kasper
0d13fe7e34 [next] Ensure non-static pages/500 is handled (#8438)
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
2022-08-22 10:13:16 -05:00
JJ Kasper
4afec9d373 [next] Update middleware data routes to fix caching (#8431)
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
2022-08-22 09:52:24 -05:00
Sean Massa
09c85f63d2 Publish Stable
- vercel@28.1.0
 - @vercel/go@2.2.0
 - @vercel/next@3.1.19
2022-08-16 15:05:36 -05:00
Matthew Stanciu
9963965e9a [cli] Fix vc link not respecting --yes (#8412)
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
2022-08-16 19:16:54 +00:00
Matthew Stanciu
f3ed279007 [cli] Change mentions of "Aborted" to "Canceled" (#8411)
@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
2022-08-16 18:47:52 +00:00
Sean Massa
4fe489edad Revert "Revert "[go] add lambda wrapper support to the go runtime"" (#8407)
Co-authored-by: Craig Andrews <craig.andrews@vercel.com>
Co-authored-by: Craig Andrews <44933829+craigandrews@users.noreply.github.com>
2022-08-16 11:54:44 -05:00
Matthew Stanciu
e2911aac0b [cli] Small vc ls wording changes (#8405)
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
2022-08-16 14:47:41 +00:00
JJ Kasper
f3cbc5d746 [next] Fix un-necessary edge routes being added (#8408)
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
2022-08-16 15:14:49 +01:00
Sean Massa
40df88b483 Revert "add test for main.go scenario"
This reverts commit 75c4f45b73.
2022-08-16 03:03:11 -05:00
Sean Massa
75c4f45b73 add test for main.go scenario 2022-08-16 03:01:12 -05:00
Sean Massa
05a236f944 Publish Stable
- vercel@28.0.2
 - @vercel/ruby@1.3.27
2022-08-16 02:49:19 -05:00
Sean Massa
4b7383f521 [cli] serialize getDeployment calls in vercel bisect (#8403) 2022-08-16 02:45:48 -05:00
Sean Massa
c263c31e48 [cli][tests] remove dupe inspectorUrl (#8400) 2022-08-15 22:14:29 -05:00
Sean Massa
c80530f9b1 [cli] fix: undefined variable (#8401)
The variable `chunks` doesn't exist in this context. Updated the error message to reference the `lines` count instead.
2022-08-15 22:43:04 +00:00
Sean Massa
16fd4396ef [tests] skip ruby test for now (#8404) 2022-08-15 17:30:02 -05:00
Nathan Rajlich
4e7138f400 [docs] Remove "watch" from DEVELOPING_A_RUNTIME.md (#8391)
Remove "watch" from `DEVELOPING_A_RUNTIME.md`

`vercel dev` no longer utilizes the `watch` field, so let's not document it here.
2022-08-13 15:57:25 -07:00
Steven
5273279cf1 Publish Stable
- vercel@28.0.1
 - @vercel/ruby@1.3.26
2022-08-12 22:19:42 -04:00
Steven
37290039d6 [ruby] Fix bundle install (#8392)
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`.
2022-08-12 21:59:50 -04:00
Steven
b52d01f809 Publish Stable
- @vercel/build-utils@5.3.1
 - vercel@28.0.0
 - @vercel/client@12.2.0
 - @vercel/go@2.1.1
 - @vercel/hydrogen@0.0.14
 - @vercel/next@3.1.18
 - @vercel/node@2.5.8
 - @vercel/python@3.1.9
 - @vercel/redwood@1.0.18
 - @vercel/remix@1.0.19
 - @vercel/ruby@1.3.25
 - @vercel/static-build@1.0.18
2022-08-12 16:31:35 -04:00
Matthew Stanciu
ffefaf82a1 [cli] Fix vc env pull delta changes bug (#8382)
#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.
2022-08-12 15:56:47 -04:00
Steven
6d8dbfc7d6 [ruby] Handle exit code 18 gracefully (#8388)
This reverts #8381 and instead supports the "2.7.x" syntax.

- Related to https://github.com/vercel/customer-issues/issues/684
2022-08-12 15:56:13 -04:00
Steven
551cd7f688 [ruby] Fix ruby version error message (#8381)
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.
2022-08-12 11:31:36 -04:00
Chris Barber
2dfb6b45cd [cli] MAJOR: Remove update command (#8369)
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.
2022-08-12 11:24:31 -04:00
Steven
65ae2a289e Revert "[go] add lambda wrapper support to the go runtime" (#8385)
Revert "[go] add lambda wrapper support to the go runtime (#8350)"

This reverts commit 4c230c8436.
2022-08-12 10:51:43 -04:00
Damien Simonin Feugas
72ea3532b1 chore: does not add /index when already present (#8373) 2022-08-12 10:10:05 +02:00
Sean Massa
78fac00823 [cli] improve vc build --help language (#8380)
Tweak the `--yes` help language for the `build` command to be more consistent with other flag descriptions.

---

Related to: https://github.com/vercel/vercel/pull/8330
2022-08-12 02:16:07 +00:00
Nathan Rajlich
9e255afa37 [cli] Support more granular file upload progress bar (#8371)
### 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
2022-08-12 01:18:58 +00:00
Matthew Stanciu
e4be68270f [cli] MAJOR: vc ls visual changes (#8151)
- Username field does not show if all deployment usernames in the page match the context name
- The `age` field shows first in the table
- A new `duration` field shows the time it took to deploy
- A new `--prod` flag filters for production deployments
- Table headers are colored cyan

### Before

<img width="1000" alt="Screen Shot 2022-07-13 at 6 29 15 PM" src="https://user-images.githubusercontent.com/14811170/178867816-5d252c94-86c0-46f4-82bf-a33341686aa6.png">

<img width="1081" alt="Screen Shot 2022-07-13 at 6 31 15 PM" src="https://user-images.githubusercontent.com/14811170/178867934-4fa570a1-e2ba-4d1f-8a93-b88b095c1dca.png">

### After

<img width="1002" alt="Screen Shot 2022-07-26 at 2 23 27 PM" src="https://user-images.githubusercontent.com/14811170/181114658-b1cc0f8d-18a7-4996-8635-a7868af50a19.png">

<img width="1077" alt="Screen Shot 2022-07-26 at 2 23 21 PM" src="https://user-images.githubusercontent.com/14811170/181114646-f614a235-f962-468e-a8e0-ca65f1a94b69.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
2022-08-12 00:15:17 +00:00
Matthew Stanciu
9c636dc1ba [cli] MAJOR: Remove vc billing command (#8377) 2022-08-11 16:29:49 -07:00
Matthew Stanciu
c98c9996bf [cli] MAJOR: Connect a Git provider repository in vc link (#8290)
#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
2022-08-11 22:49:36 +00:00
Matthew Stanciu
0fcf172a10 [cli] vc project ls visual updates (#8157)
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
2022-08-11 22:08:27 +00:00
Matthew Stanciu
99e5c4a6db [cli] Accept URL argument in vc git connect (#8351)
* 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>
2022-08-11 14:28:58 -07:00
Nathan Rajlich
b8269b0111 [build-utils] Remove as cast in glob() (#8376)
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.
2022-08-11 21:08:53 +00:00
Sean Massa
decac0fe3f Revert "[remix] add image optimization configuration" (#8375)
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.
2022-08-11 19:20:20 +00:00
Mosaad
591d1686d0 [remix] add image optimization configuration (#8217)
### Feature
Makes it possible to use [Vercel's image optimization](https://vercel.com/docs/build-output-api/v3#build-output-configuration/supported-properties/images).

### Demo
This example is built locally with this patch:
https://github.com/theMosaad/remix-vercel-image
2022-08-11 18:30:21 +00:00
Matthew Stanciu
5e1d5c921c [client] Fix archive type on VercelClientOptions (#8367)
Fix `archive` type on `VercelClientOptions`
2022-08-10 13:44:20 -07:00
Matthew Stanciu
603b1256c6 [client] Send single source.tgz archive when creating deployment (#8356)
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
2022-08-10 19:35:25 +00:00
Nathan Rajlich
6957c72828 [client] Remove extraneous file read during deployment upload (#8366)
The `file` object already contains the contents as a Buffer, so there's no need to read the files again.

Extracted from #8356.
2022-08-10 12:09:04 -07:00
Steven
9be3650cb7 [tests] Use yarn --frozen-lockfile (#8363)
This PR updates CI to use `yarn install --frozen-lockfile` and also updates some github actions to v3.
2022-08-10 15:55:38 +00:00
Steven
6e1ee7a7d6 [cli] Fix dev query string merging (#8183)
Since `vercel dev` performs query string merging with `vercel.json` routes and the requested url, there is sometimes a slight difference between the request that the browser sends and the request that the upstream dev server receives.

Most servers treat the query string key with "empty" value the same as undefined value. Meaning, these two URLs should be equivalent because each has empty values:

- `http://example.com/src/App.vue?vue&type=style&index=0&lang.css`
- `http://example.com/src/App.vue?vue=&type=style&index=0&lang.css=`

However, `vite dev` handles these two URLs differently because of [string comparisons](2289d04af5/packages/plugin-vue/src/handleHotUpdate.ts (L98-L99)) instead of URL parsing, which causes requests from `vercel dev` to fail. Thus, this PR changes from Node.js native URL parsing to a custom implementation in order to handle this corner case and preserve the difference between `?a=` and `?a`.

Ideally this would be [fixed in vite](https://github.com/vitejs/vite/pull/9589), however we might run into other dev servers that also fail in the same way in the future.

- Fixes https://github.com/vercel/vercel/issues/7283
- Closes https://github.com/vitejs/vite/pull/9589
- Related to https://github.com/nodejs/node/issues/9500
2022-08-10 11:34:29 -04:00
Damien Simonin Feugas
767ce2cff1 [node] adds /index to / middleware matchers (#8349) 2022-08-10 15:17:15 +02:00
Craig Andrews
bb1d0ce1b7 chore(docs) Add details of how to enable lambda runtime wrappers to custom runtimes (#8360)
### 📋 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
2022-08-09 21:54:25 +00:00
Sean Massa
31f79c7de1 Publish Stable
- vercel@27.4.0
 - @vercel/go@2.1.0
 - @vercel/next@3.1.17
2022-08-09 16:11:57 -05:00
Craig Andrews
4c230c8436 [go] add lambda wrapper support to the go runtime (#8350)
Co-authored-by: Sean Massa <EndangeredMassa@gmail.com>
2022-08-09 16:08:20 -05:00
Lee Robinson
7941f5a104 [examples] Update Astro template for 1.0. (#8357)
To prepare for [Astro 1.0](https://github.com/withastro/astro/releases/tag/astro%401.0.0-rc.1), this PR updates the template (it has [been deployed](https://astro-template.vercel.app/)).
2022-08-09 18:09:38 +00:00
JJ Kasper
5b931afbf3 [next] Ensure $$ in ISR page is handled correctly (#8359)
* Ensure $$ in ISR page is handled correctly

* update test

* Remove duplicate tests

* add comment

* tweak
2022-08-09 11:13:15 -05:00
Chris Barber
15080364b8 [cli] Standardize on --yes instead of --confirm (#8330)
Allow for `--yes` flag consistently throughout CLI commands.

Also adds a deprecation warning for usage of `--confirm`,
since `--yes` is now preferred.
2022-08-08 18:05:22 -07:00
473 changed files with 26846 additions and 11910 deletions

28
.github/CODEOWNERS vendored
View File

@@ -1,23 +1,17 @@
# Documentation
# https://help.github.com/en/articles/about-code-owners
* @TooTallNate @EndangeredMassa @styfle
/.github/workflows @TooTallNate @EndangeredMassa @styfle @ijjk
/packages/frameworks @TooTallNate @EndangeredMassa @styfle @AndyBitz
/packages/cli/src/commands/domains @javivelasco @mglagola @anatrajkovska
/packages/cli/src/commands/certs @javivelasco @mglagola @anatrajkovska
/packages/cli/src/commands/env @styfle @lucleray
/packages/client @TooTallNate @EndangeredMassa @styfle
/packages/build-utils @TooTallNate @EndangeredMassa @styfle @AndyBitz
/packages/middleware @gdborton @javivelasco
/packages/node @TooTallNate @EndangeredMassa @styfle
/packages/node-bridge @TooTallNate @EndangeredMassa @styfle @ijjk
/packages/next @TooTallNate @ijjk
/packages/go @TooTallNate @EndangeredMassa @styfle
/packages/python @TooTallNate @EndangeredMassa @styfle
/packages/ruby @TooTallNate @EndangeredMassa @styfle
/packages/static-build @TooTallNate @EndangeredMassa @styfle @AndyBitz
/packages/routing-utils @TooTallNate @EndangeredMassa @styfle @ijjk
* @TooTallNate @EndangeredMassa @styfle @cb1kenobi @Ethan-Arrowood
/.github/workflows @TooTallNate @EndangeredMassa @styfle @cb1kenobi @Ethan-Arrowood @ijjk
/packages/cli/src/commands/domains @mglagola @anatrajkovska
/packages/cli/src/commands/certs @mglagola @anatrajkovska
/packages/cli/src/commands/env @TooTallNate @EndangeredMassa @styfle @cb1kenobi @Ethan-Arrowood
/packages/fs-detectors @TooTallNate @EndangeredMassa @styfle @cb1kenobi @Ethan-Arrowood @agadzik @chloetedder
/packages/middleware @gdborton @vercel/edge-function
/packages/node-bridge @TooTallNate @EndangeredMassa @styfle @cb1kenobi @Ethan-Arrowood @ijjk
/packages/next @TooTallNate @EndangeredMassa @styfle @cb1kenobi @Ethan-Arrowood @ijjk
/packages/routing-utils @TooTallNate @EndangeredMassa @styfle @cb1kenobi @Ethan-Arrowood @ijjk
/packages/edge @vercel/edge-function
/examples @leerob
/examples/create-react-app @Timer
/examples/nextjs @timneutkens @ijjk @styfle

View File

@@ -1,17 +0,0 @@
name: Cancel
on:
push:
branches:
- '**'
- '!main'
jobs:
cancel:
name: 'Cancel Previous Runs'
runs-on: ubuntu-latest
timeout-minutes: 2
steps:
- uses: styfle/cancel-workflow-action@0.9.1
with:
workflow_id: test.yml, test-integration-cli.yml, test-unit.yml
access_token: ${{ github.token }}

25
.github/workflows/cron-update-next.yml vendored Normal file
View File

@@ -0,0 +1,25 @@
name: Cron Update Next
on:
# Run every 4 hours https://crontab.guru/every-4-hours
schedule:
- cron: '0 */4 * * *'
jobs:
create-pull-request:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
# 0 means fetch all commits so we can commit and push in the script below
with:
fetch-depth: 0
- name: Create Pull Request
uses: actions/github-script@v6
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
# See https://github.com/actions/github-script#run-a-separate-file-with-an-async-function
with:
script: |
const script = require('./utils/update-next.js')
await script({ github, context })

View File

@@ -7,6 +7,11 @@ on:
tags:
- '!*'
env:
TURBO_REMOTE_ONLY: 'true'
TURBO_TEAM: 'vercel'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
jobs:
publish:
name: Publish
@@ -26,14 +31,16 @@ jobs:
fi
- name: Setup Go
if: ${{ steps.check-release.outputs.IS_RELEASE == 'true' }}
uses: actions/setup-go@v2
uses: actions/setup-go@v3
with:
go-version: '1.13.15'
- name: Setup Node
if: ${{ steps.check-release.outputs.IS_RELEASE == 'true' }}
uses: actions/setup-node@v2
uses: actions/setup-node@v3
timeout-minutes: 5 # See https://github.com/actions/cache/issues/810
with:
node-version: 14
cache: 'yarn'
- name: Install
if: ${{ steps.check-release.outputs.IS_RELEASE == 'true' }}
run: yarn install --check-files --frozen-lockfile --network-timeout 1000000

22
.github/workflows/required-pr-label.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
name: Required PR Label
on:
pull_request:
types: [opened, labeled, unlabeled, synchronize]
jobs:
label:
runs-on: ubuntu-latest
steps:
- name: Check PR Labels
uses: actions/github-script@v6
with:
script: |
const labels = context.payload.pull_request.labels.map(l => l.name);
if (labels.filter(l => l.startsWith('area:')).length === 0) {
console.error('\u001b[31mMissing label: Please add at least one "area" label.');
process.exit(1);
}
if (labels.filter(l => l.startsWith('semver:')).length !== 1) {
console.error('\u001b[31mMissing label: Please add exactly one "semver" label.');
process.exit(1);
}
console.log('\u001b[32mSuccess: This pull request has correct labels, thanks!');

View File

@@ -8,6 +8,15 @@ on:
- '!*'
pull_request:
env:
TURBO_REMOTE_ONLY: 'true'
TURBO_TEAM: 'vercel'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
test:
name: CLI
@@ -19,28 +28,20 @@ jobs:
node: [14]
runs-on: ${{ matrix.os }}
steps:
- name: Conditionally set remote env
if: github.event.pull_request.head.repo.full_name == github.repository
run: |
echo "TURBO_REMOTE_ONLY=true" >> $GITHUB_ENV
echo "TURBO_TEAM=vercel" >> $GITHUB_ENV
echo "TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}" >> $GITHUB_ENV
- uses: actions/setup-go@v2
- uses: actions/checkout@v3
with:
fetch-depth: 2
- uses: actions/setup-go@v3
with:
go-version: '1.13.15'
- uses: actions/setup-node@v2
- uses: actions/setup-node@v3
timeout-minutes: 5 # See https://github.com/actions/cache/issues/810
with:
node-version: ${{ matrix.node }}
- uses: actions/checkout@v2
with:
fetch-depth: 100
- run: git --version
- run: git fetch origin main --depth=100
- run: git fetch origin ${{ github.ref }} --depth=100
- run: git diff origin/main...HEAD --name-only
- run: yarn install --network-timeout 1000000
cache: 'yarn'
- run: yarn install --network-timeout 1000000 --frozen-lockfile
- run: yarn run build
- run: yarn test-integration-cli
env:
VERCEL_TEAM_TOKEN: ${{ secrets.VERCEL_TEAM_TOKEN }}
VERCEL_REGISTRATION_URL: ${{ secrets.VERCEL_REGISTRATION_URL }}
VERCEL_TEST_TOKEN: ${{ secrets.VERCEL_TEST_TOKEN }}
VERCEL_TEST_REGISTRATION_URL: ${{ secrets.VERCEL_TEST_REGISTRATION_URL }}

View File

@@ -8,6 +8,15 @@ on:
- '!*'
pull_request:
env:
TURBO_REMOTE_ONLY: 'true'
TURBO_TEAM: 'vercel'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
test:
name: Unit
@@ -19,26 +28,18 @@ jobs:
node: [14]
runs-on: ${{ matrix.os }}
steps:
- name: Conditionally set remote env
if: github.event.pull_request.head.repo.full_name == github.repository
run: |
echo "TURBO_REMOTE_ONLY=true" >> $GITHUB_ENV
echo "TURBO_TEAM=vercel" >> $GITHUB_ENV
echo "TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}" >> $GITHUB_ENV
- uses: actions/setup-go@v2
- uses: actions/setup-go@v3
with:
go-version: '1.13.15'
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
with:
fetch-depth: 2
- uses: actions/setup-node@v3
timeout-minutes: 5 # See https://github.com/actions/cache/issues/810
with:
node-version: ${{ matrix.node }}
- uses: actions/checkout@v2
with:
fetch-depth: 100
- run: git --version
- run: git fetch origin main --depth=100
- run: git fetch origin ${{ github.ref }} --depth=100
- run: git diff origin/main...HEAD --name-only
- run: yarn install --network-timeout 1000000
cache: 'yarn'
- run: yarn install --network-timeout 1000000 --frozen-lockfile
- run: yarn run build
- run: yarn run lint
if: matrix.os == 'ubuntu-latest' && matrix.node == 14 # only run lint once

View File

@@ -10,6 +10,13 @@ on:
env:
NODE_VERSION: '14'
TURBO_REMOTE_ONLY: 'true'
TURBO_TEAM: 'vercel'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
setup:
@@ -19,14 +26,18 @@ jobs:
tests: ${{ steps['set-tests'].outputs['tests'] }}
dplUrl: ${{ steps.waitForTarball.outputs.url }}
steps:
- uses: actions/checkout@v2
- run: git --version
- run: git fetch origin main
- uses: actions/setup-node@v2
- uses: actions/checkout@v3
with:
fetch-depth: 2
- uses: actions/setup-go@v3
with:
go-version: '1.13.15'
- uses: actions/setup-node@v3
timeout-minutes: 5 # See https://github.com/actions/cache/issues/810
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'yarn'
- run: yarn install --network-timeout 1000000
- run: yarn install --network-timeout 1000000 --frozen-lockfile
- id: set-tests
run: |
TESTS_ARRAY=$(node utils/chunk-tests.js $SCRIPT_NAME)
@@ -52,19 +63,14 @@ jobs:
matrix:
include: ${{ fromJson(needs.setup.outputs['tests']) }}
steps:
- name: Conditionally set remote env
if: github.event.pull_request.head.repo.full_name == github.repository
run: |
echo "TURBO_REMOTE_ONLY=true" >> $GITHUB_ENV
echo "TURBO_TEAM=vercel" >> $GITHUB_ENV
echo "TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}" >> $GITHUB_ENV
- uses: actions/checkout@v2
- uses: actions/checkout@v3
with:
fetch-depth: 2
- uses: actions/setup-go@v2
- uses: actions/setup-go@v3
with:
go-version: '1.13.15'
- uses: actions/setup-node@v2
- uses: actions/setup-node@v3
timeout-minutes: 5 # See https://github.com/actions/cache/issues/810
with:
node-version: ${{ env.NODE_VERSION }}
cache: 'yarn'
@@ -84,8 +90,8 @@ jobs:
shell: bash
env:
VERCEL_CLI_VERSION: ${{ needs.setup.outputs.dplUrl }}/tarballs/vercel.tgz
VERCEL_TEAM_TOKEN: ${{ secrets.VERCEL_TEAM_TOKEN }}
VERCEL_REGISTRATION_URL: ${{ secrets.VERCEL_REGISTRATION_URL }}
VERCEL_TEST_TOKEN: ${{ secrets.VERCEL_TEST_TOKEN }}
VERCEL_TEST_REGISTRATION_URL: ${{ secrets.VERCEL_TEST_REGISTRATION_URL }}
FORCE_COLOR: '1'
conclusion:

View File

@@ -1,7 +1,7 @@
version = 1
[merge]
automerge_label = ["semver-major","semver-minor","semver-patch"]
automerge_label = ["pr: automerge"]
blacklist_title_regex = "^WIP.*"
blacklist_labels = ["work in progress"]
method = "squash"

View File

@@ -63,9 +63,6 @@ export async function build(options: BuildOptions) {
const lambda = createLambda(/* … */);
return {
output: lambda,
watch: [
// Dependent files to trigger a rebuild in `vercel dev` go here…
],
routes: [
// If your Runtime needs to define additional routing, define it here…
],
@@ -115,7 +112,8 @@ export async function shouldServe(options: ShouldServeOptions) {
}
```
If this function is not defined, Vercel CLI will use the [default implementation](https://github.com/vercel/vercel/blob/52994bfe26c5f4f179bdb49783ee57ce19334631/packages/now-build-utils/src/should-serve.ts).
If this function is not defined, Vercel CLI will use the [default
implementation](https://github.com/vercel/vercel/blob/52994bfe26c5f4f179bdb49783ee57ce19334631/packages/now-build-utils/src/should-serve.ts).
### `startDevServer()`
@@ -189,7 +187,8 @@ 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.
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`.
@@ -197,6 +196,77 @@ The `analyze` step can modify that directory, and it will not be re-created when
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
runtime command as parameters.
```bash
#!/bin/bash
exec $AWS_LAMBDA_EXEC_WRAPPER path/to/runtime param1 param2
```
If the `bootstrap` file is not a launcher script, but the entrypoint of the runtime
itself, replace the bootstrap process with the wrapper. Pass the path and parameters
of the executing file, ensuring the `AWS_LAMBDA_EXEC_WRAPPER` environment variable is
set to blank.
This `bash` example uses `exec` to replace the running bootstrap process with the
wrapper, passing its own path and parameters.
```bash
#!/bin/bash
if [[ -n $AWS_LAMBDA_EXEC_WRAPPER ]]
__WRAPPER=$AWS_LAMBDA_EXEC_WRAPPER
AWS_LAMBDA_EXEC_WRAPPER=""
exec $__WRAPPER "$0" "${@}"
fi
# start the actual runtime functionality
```
Note that unsetting the variable may not have the desired effect due to the way
Lambda spawns runtime processes. It is better to explicitly set it to blank.
The best way to replace the existing bootstrap process is with the
[`execve`](https://www.man7.org/linux/man-pages/man2/execve.2.html) syscall.
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`.
@@ -304,13 +374,14 @@ This is a [class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refere
- `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:
- `nodejs16.x`
- `nodejs14.x`
- `nodejs12.x`
- `go1.x`
- `java11`
- `python3.9`

View File

@@ -19,11 +19,9 @@
## Vercel
Vercel is a platform for **static sites and frontend frameworks**, built to integrate with your headless content, commerce, or database.
Vercel is the platform for frontend developers, providing the speed and reliability innovators need to create at the moment of inspiration.
We provide a **frictionless developer experience** to take care of the hard things: deploy instantly, scale automatically, and serve personalized content around the globe.
We make it easy for frontend teams to **develop, preview, and ship** delightful user experiences, where performance is the default.
We enable teams to iterate quickly and develop, preview, and ship delightful user experiences. Vercel has zero-configuration support for 35+ frontend frameworks and integrates with your headless content, commerce, or database of choice.
## Deploy

View File

@@ -1,6 +1,5 @@
import fs from 'fs/promises';
import { join, dirname } from 'path';
import execa from 'execa';
import { getExampleList } from '../examples/example-list';
import { mapOldToNew } from '../examples/map-old-to-new';
@@ -13,6 +12,12 @@ async function main() {
await fs.rm(pubDir, { recursive: true, force: true });
await fs.mkdir(pubDir);
await fs.cp(
join(repoRoot, 'packages', 'frameworks', 'logos'),
join(pubDir, 'framework-logos'),
{ recursive: true, force: true }
);
const examples = await getExampleList();
const pathListAll = join(pubDir, 'list-all.json');
await fs.writeFile(pathListAll, JSON.stringify(examples));
@@ -41,10 +46,6 @@ async function main() {
JSON.stringify([...existingExamples, ...oldExamples])
);
const { stdout: sha } = await execa('git', ['rev-parse', '--short', 'HEAD'], {
cwd: repoRoot,
});
const tarballsDir = join(pubDir, 'tarballs');
const packagesDir = join(repoRoot, 'packages');
const packages = await fs.readdir(packagesDir);
@@ -55,12 +56,21 @@ async function main() {
'utf-8'
);
const packageJson = JSON.parse(packageJsonRaw);
const tarballName = `${packageJson.name
.replace('@', '')
.replace('/', '-')}-v${packageJson.version}-${sha.trim()}.tgz`;
const files = await fs.readdir(fullDir);
const tarballName = files.find(f => /^vercel-.+\.tgz$/.test(f));
if (!tarballName) {
throw new Error(
`Expected vercel-*.tgz in ${fullDir} but found ${JSON.stringify(
files,
null,
2
)}`
);
}
const srcTarballPath = join(fullDir, tarballName);
const destTarballPath = join(tarballsDir, `${packageJson.name}.tgz`);
await fs.mkdir(dirname(destTarballPath), { recursive: true });
await fs.copyFile(join(fullDir, tarballName), destTarballPath);
await fs.copyFile(srcTarballPath, destTarballPath);
}
console.log('Completed building static frontend.');

View File

@@ -16,10 +16,6 @@ const frameworks = (_frameworks as Framework[])
defaultRoutes: undefined,
};
if (framework.logo) {
framework.logo = `https://res.cloudinary.com/zeit-inc/image/fetch/${framework.logo}`;
}
return framework;
});

View File

@@ -18,3 +18,4 @@ pnpm-debug.log*
# macOS-specific files
.DS_Store
.vercel

View File

@@ -1 +0,0 @@
README.md

View File

@@ -1,10 +1,16 @@
# Welcome to [Astro](https://astro.build)
# Astro
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/astro/tree/latest/examples/starter)
This directory is a brief example of an [Astro](https://astro.build/) site that can be deployed to Vercel with zero configuration.
> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!
## Deploy Your Own
## 🚀 Project Structure
Deploy your own Astro project with Vercel.
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/vercel/tree/main/examples/astro&template=astro)
_Live Example: https://astro-template.vercel.app_
## Project Structure
Inside of your Astro project, you'll see the following folders and files:
@@ -26,17 +32,15 @@ There's nothing special about `src/components/`, but that's where we like to put
Any static assets, like images, can be placed in the `public/` directory.
## 🧞 Commands
## Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
| :---------------- | :------------------------------------------- |
| :--------------------- | :------------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:3000` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
## 👀 Want to learn more?
Feel free to check [our documentation](https://github.com/withastro/astro) or jump into our [Discord server](https://astro.build/chat).
| `npm run astro ...` | Run CLI commands like `astro add`, `astro preview` |
| `npm run astro --help` | Get help using the Astro CLI |

View File

@@ -1,14 +1,13 @@
{
"name": "@example/basics",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "astro dev",
"start": "astro dev",
"build": "astro build",
"preview": "astro preview"
"preview": "astro preview",
"astro": "astro"
},
"devDependencies": {
"astro": "^1.0.0-beta.20"
"astro": "^1.0.0-rc.8"
}
}

View File

@@ -0,0 +1,76 @@
---
export interface Props {
title: string;
body: string;
href: string;
}
const { href, title, body } = Astro.props as Props;
---
<li class="link-card">
<a href={href}>
<h2>
{title}
<span>&rarr;</span>
</h2>
<p>
{body}
</p>
</a>
</li>
<style>
:root {
--link-gradient: linear-gradient(45deg, #4f39fa, #da62c4 30%, var(--color-border) 60%);
}
.link-card {
list-style: none;
display: flex;
padding: 0.15rem;
background-image: var(--link-gradient);
background-size: 400%;
border-radius: 0.5rem;
background-position: 100%;
transition: background-position 0.6s cubic-bezier(0.22, 1, 0.36, 1);
}
.link-card > a {
width: 100%;
text-decoration: none;
line-height: 1.4;
padding: 1em 1.3em;
border-radius: 0.35rem;
color: var(--text-color);
background-color: white;
opacity: 0.8;
}
h2 {
margin: 0;
transition: color 0.6s cubic-bezier(0.22, 1, 0.36, 1);
}
p {
margin-top: 0.75rem;
margin-bottom: 0;
}
h2 span {
display: inline-block;
transition: transform 0.3s cubic-bezier(0.22, 1, 0.36, 1);
}
.link-card:is(:hover, :focus-within) {
background-position: 0;
}
.link-card:is(:hover, :focus-within) h2 {
color: #4f39fa;
}
.link-card:is(:hover, :focus-within) h2 span {
will-change: transform;
transform: translateX(2px);
}
</style>

View File

@@ -1,55 +0,0 @@
---
export interface Props {
title: string;
}
const { title } = Astro.props as Props;
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<title>{title}</title>
</head>
<body>
<slot />
</body>
</html>
<style>
:root {
--font-size-base: clamp(1rem, 0.34vw + 0.91rem, 1.19rem);
--font-size-lg: clamp(1.2rem, 0.7vw + 1.2rem, 1.5rem);
--font-size-xl: clamp(2.44rem, 2.38vw + 1.85rem, 3.75rem);
--color-text: hsl(12, 5%, 4%);
--color-bg: hsl(10, 21%, 95%);
}
html {
font-family: system-ui, sans-serif;
font-size: var(--font-size-base);
color: var(--color-text);
background-color: var(--color-bg);
}
body {
margin: 0;
}
:global(h1) {
font-size: var(--font-size-xl);
}
:global(h2) {
font-size: var(--font-size-lg);
}
:global(code) {
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
Bitstream Vera Sans Mono, Courier New, monospace;
}
</style>

1
examples/astro/src/env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="astro/client" />

View File

@@ -0,0 +1,56 @@
---
export interface Props {
title: string;
}
const { title } = Astro.props as Props;
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<meta name="generator" content={Astro.generator} />
<title>{title}</title>
</head>
<body>
<slot />
</body>
</html>
<style>
:root {
--font-size-base: clamp(1rem, 0.34vw + 0.91rem, 1.19rem);
--font-size-lg: clamp(1.2rem, 0.7vw + 1.2rem, 1.5rem);
--font-size-xl: clamp(2.44rem, 2.38vw + 1.85rem, 3.75rem);
--color-text: hsl(12, 5%, 4%);
--color-bg: hsl(10, 21%, 95%);
--color-border: hsl(17, 24%, 90%);
}
html {
font-family: system-ui, sans-serif;
font-size: var(--font-size-base);
color: var(--color-text);
background-color: var(--color-bg);
}
body {
margin: 0;
}
:global(h1) {
font-size: var(--font-size-xl);
}
:global(h2) {
font-size: var(--font-size-lg);
}
:global(code) {
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
Bitstream Vera Sans Mono, Courier New, monospace;
}
</style>

View File

@@ -1,76 +1,47 @@
---
import Layout from '../components/Layout.astro';
import Layout from '../layouts/Layout.astro';
import Card from '../components/Card.astro';
---
<Layout title="Welcome to Astro.">
<main>
<h1>Welcome to <span class="text-gradient">Astro</span></h1>
<p class="instructions"><strong>Your first mission:</strong> tweak this message to try our hot module reloading. Check the <code>src/pages</code> directory!</p>
<ul role="list" class="link-card-grid">
<li class="link-card">
<a href="https://astro.build/integrations/">
<h2>Integrations <span>&rarr;</span></h2>
<p>Add component frameworks, Tailwind, Partytown, and more!</p>
</a>
</li>
<li class="link-card">
<a href="https://astro.build/themes/">
<h2>Themes <span>&rarr;</span></h2>
<p>Explore a galaxy of community-built starters.</p>
</a>
</li>
<li class="link-card">
<a href="https://docs.astro.build/">
<h2>Docs <span>&rarr;</span></h2>
<p>Learn our complete feature set and explore the API.</p>
</a>
</li>
<li class="link-card">
<a href="https://astro.build/chat/">
<h2>Chat <span>&rarr;</span></h2>
<p>
Ask, contribute, and have fun on our community Discord
<svg
class="heart"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 512 512"
width="16"
height="16"
fill="currentColor"
>
<title>heart</title>
<path d="M256 448l-30.164-27.211C118.718 322.442 48 258.61 48 179.095 48 114.221 97.918 64 162.4 64c36.399 0 70.717 16.742 93.6 43.947C278.882 80.742 313.199 64 349.6 64 414.082 64 464 114.221 464 179.095c0 79.516-70.719 143.348-177.836 241.694L256 448z" />
</svg>
<p class="instructions">
Check out the <code>src/pages</code> directory to get started.<br />
<strong>Code Challenge:</strong> Tweak the "Welcome to Astro" message above.
</p>
</a>
</li>
<ul role="list" class="link-card-grid">
<Card
href="https://docs.astro.build/"
title="Documentation"
body="Learn how Astro works and explore the official API docs."
/>
<Card
href="https://astro.build/integrations/"
title="Integrations"
body="Supercharge your project with new frameworks and libraries."
/>
<Card
href="https://astro.build/themes/"
title="Themes"
body="Explore a galaxy of community-built starter themes."
/>
<Card
href="https://astro.build/chat/"
title="Chat"
body="Come say hi to our amazing Discord community. ❤️"
/>
</ul>
</main>
</Layout>
<style>
:root {
--color-border: hsl(17, 24%, 90%);
--astro-gradient: linear-gradient(0deg,#4F39FA, #DA62C4);
--link-gradient: linear-gradient(45deg, #4F39FA, #DA62C4 30%, var(--color-border) 60%);
--night-sky-gradient: linear-gradient(0deg, #392362 -33%, #431f69 10%, #30216b 50%, #1f1638 100%);
--astro-gradient: linear-gradient(0deg, #4f39fa, #da62c4);
}
h2 {
margin: 0;
transition: color 0.6s cubic-bezier(0.22, 1, 0.36, 1);
}
h2 span {
display: inline-block;
transition: transform 0.3s cubic-bezier(0.22, 1, 0.36, 1);
}
code {
font-size: 0.875em;
border: 0.1em solid var(--color-border);
border-radius: 4px;
padding: 0.15em 0.25em;
h1 {
margin: 2rem 0;
}
main {
@@ -91,7 +62,8 @@ import Layout from '../components/Layout.astro';
}
@keyframes pulse {
0%, 100% {
0%,
100% {
background-position-y: 0%;
}
50% {
@@ -100,75 +72,25 @@ import Layout from '../components/Layout.astro';
}
.instructions {
line-height: 1.8;
margin-bottom: 2rem;
background-image: var(--night-sky-gradient);
padding: 1.5rem;
line-height: 1.6;
margin: 1rem 0;
background: #4f39fa;
padding: 1rem;
border-radius: 0.4rem;
color: var(--color-bg);
}
.instructions code {
font-size: 0.875em;
border: 0.1em solid var(--color-border);
border-radius: 4px;
padding: 0.15em 0.25em;
}
.link-card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(24ch, 1fr));
gap: 1rem;
padding: 0;
}
.link-card {
list-style: none;
display: flex;
padding: 0.15rem;
background-image: var(--link-gradient);
background-size: 400%;
border-radius: 0.5rem;
background-position: 100%;
transition: background-position 0.6s cubic-bezier(0.22, 1, 0.36, 1);
}
.link-card > a {
width: 100%;
text-decoration: none;
line-height: 1.4;
padding: 1em 1.3em;
border-radius: 0.35rem;
color: var(--text-color);
background-color: white;
opacity: 0.8;
}
.link-card:is(:hover, :focus-within) {
background-position: 0;
}
.link-card:is(:hover, :focus-within) h2 {
color: #4F39FA;
}
.link-card:is(:hover, :focus-within) h2 span {
transform: translateX(2px);
}
.heart {
display: inline-block;
color: #DA62C4;
animation: heartbeat 3s ease-in-out infinite;
}
@keyframes heartbeat {
0%,
50%,
100% {
transform: scale(1);
}
5% {
transform: scale(1.125);
}
10% {
transform: scale(1.05);
}
15% {
transform: scale(1.25);
}
}
</style>

View File

@@ -1,15 +0,0 @@
{
"compilerOptions": {
// Enable top-level await, and other modern ESM features.
"target": "ESNext",
"module": "ESNext",
// Enable node-style module resolution, for things like npm package imports.
"moduleResolution": "node",
// Enable JSON imports.
"resolveJsonModule": true,
// Enable stricter transpilation for better output.
"isolatedModules": true,
// Add type definitions for our Vite runtime.
"types": ["vite/client"]
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -26,10 +26,11 @@ yarn-error.log*
.pnpm-debug.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@@ -1,6 +1,7 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
}
module.exports = nextConfig

File diff suppressed because it is too large Load Diff

View File

@@ -1,4 +1,6 @@
{
"name": "nextjs",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -7,12 +9,12 @@
"lint": "next lint"
},
"dependencies": {
"next": "12.1.4",
"react": "18.0.0",
"react-dom": "18.0.0"
"next": "12.3.1",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"eslint": "8.12.0",
"eslint-config-next": "12.1.4"
"eslint": "8.23.1",
"eslint-config-next": "12.3.1"
}
}

View File

@@ -114,3 +114,16 @@
flex-direction: column;
}
}
@media (prefers-color-scheme: dark) {
.card,
.footer {
border-color: #222;
}
.code {
background: #111;
}
.logo img {
filter: invert(1);
}
}

View File

@@ -14,3 +14,13 @@ a {
* {
box-sizing: border-box;
}
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
body {
color: white;
background: black;
}
}

1703
examples/nextjs/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -8,21 +8,9 @@ Everything you need to build a Svelte project, powered by [`create-svelte`](http
_Live Example: https://sveltekit-template.vercel.app_
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npm init svelte
# create a new project in my-app
npm init svelte my-app
```
## Developing
Once you've created a project and installed dependencies with `pnpm install`, start a development server:
Once you've installed dependencies with `pnpm install`, start a development server:
```bash
pnpm run dev

View File

@@ -10,4 +10,8 @@
"sourceMap": true,
"strict": true
}
// Path aliases are handled by https://kit.svelte.dev/docs/configuration#alias and https://kit.svelte.dev/docs/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

View File

@@ -1,25 +1,25 @@
{
"private": true,
"scripts": {
"dev": "svelte-kit dev",
"build": "svelte-kit build",
"dev": "vite dev",
"build": "vite build",
"package": "svelte-kit package",
"preview": "svelte-kit preview",
"prepare": "svelte-kit sync",
"preview": "vite preview",
"check": "svelte-check --tsconfig ./jsconfig.json",
"check:watch": "svelte-check --tsconfig ./jsconfig.json --watch",
"lint": "prettier --check --plugin-search-dir=. .",
"format": "prettier --write --plugin-search-dir=. ."
"lint": "prettier --check .",
"format": "prettier --write ."
},
"devDependencies": {
"@sveltejs/adapter-auto": "1.0.0-next.50",
"@sveltejs/kit": "1.0.0-next.347",
"@types/cookie": "^0.4.1",
"prettier": "^2.5.1",
"prettier-plugin-svelte": "^2.5.0",
"@sveltejs/adapter-auto": "next",
"@sveltejs/kit": "next",
"@types/cookie": "^0.5.1",
"prettier": "^2.6.2",
"prettier-plugin-svelte": "^2.7.0",
"svelte": "^3.46.0",
"svelte-check": "^2.2.6",
"typescript": "~4.6.2"
"svelte-check": "^2.7.1",
"typescript": "^4.7.4",
"vite": "^3.0.8"
},
"type": "module",
"dependencies": {

1458
examples/sveltekit/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,6 @@
/// <reference types="@sveltejs/kit" />
// See https://kit.svelte.dev/docs/types#app
// for information about these interfaces
// and what to do when importing types
declare namespace App {
interface Locals {
userid: string;
@@ -9,7 +8,7 @@ declare namespace App {
// interface Platform {}
// interface Session {}
// interface PrivateEnv {}
// interface Stuff {}
// interface PublicEnv {}
}

View File

@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="viewport" content="width=device-width" />
%sveltekit.head%
</head>
<body>

View File

@@ -31,11 +31,11 @@ import { invalidate } from '$app/navigation';
export function enhance(form, { pending, error, result } = {}) {
let current_token;
/** @param {SubmitEvent} e */
async function handle_submit(e) {
/** @param {SubmitEvent} event */
async function handle_submit(event) {
const token = (current_token = {});
e.preventDefault();
event.preventDefault();
const data = new FormData(form);
@@ -63,11 +63,11 @@ export function enhance(form, { pending, error, result } = {}) {
} else {
console.error(await response.text());
}
} catch (e) {
if (error && e instanceof Error) {
error({ data, form, error: e, response: null });
} catch (err) {
if (error && err instanceof Error) {
error({ data, form, error: err, response: null });
} else {
throw e;
throw err;
}
}
}

View File

@@ -0,0 +1,58 @@
<script>
import Header from '$lib/header/Header.svelte';
import { webVitals } from '$lib/vitals';
import { browser } from '$app/env';
import { page } from '$app/stores';
import '../app.css';
let analyticsId = import.meta.env.VERCEL_ANALYTICS_ID;
$: if (browser && analyticsId) {
webVitals({
path: $page.url.pathname,
params: $page.params,
analyticsId
})
}
</script>
<Header />
<main>
<slot />
</main>
<footer>
<p>visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to learn SvelteKit</p>
</footer>
<style>
main {
flex: 1;
display: flex;
flex-direction: column;
padding: 1rem;
width: 100%;
max-width: 1024px;
margin: 0 auto;
box-sizing: border-box;
}
footer {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 40px;
}
footer a {
font-weight: bold;
}
@media (min-width: 480px) {
footer {
padding: 40px 0;
}
}
</style>

View File

@@ -0,0 +1 @@
export const prerender = true;

View File

@@ -0,0 +1,57 @@
<script>
import Counter from '$lib/Counter.svelte';
</script>
<svelte:head>
<title>Home</title>
<meta name="description" content="Svelte demo app" />
</svelte:head>
<section>
<h1>
<span class="welcome">
<picture>
<source srcset="svelte-welcome.webp" type="image/webp" />
<img src="svelte-welcome.png" alt="Welcome" />
</picture>
</span>
to your new<br />SvelteKit app
</h1>
<h2>
try editing <strong>src/routes/index.svelte</strong>
</h2>
<Counter />
</section>
<style>
section {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
flex: 1;
}
h1 {
width: 100%;
}
.welcome {
display: block;
position: relative;
width: 100%;
height: 0;
padding: 0 0 calc(100% * 495 / 2048) 0;
}
.welcome img {
position: absolute;
width: 100%;
height: 100%;
top: 0;
display: block;
}
</style>

View File

@@ -1,58 +0,0 @@
<script>
import Header from '$lib/header/Header.svelte';
import { webVitals } from '$lib/vitals';
import { browser } from '$app/env';
import { page } from '$app/stores';
import '../app.css';
let analyticsId = import.meta.env.VERCEL_ANALYTICS_ID;
$: if (browser && analyticsId) {
webVitals({
path: $page.url.pathname,
params: $page.params,
analyticsId
})
}
</script>
<Header />
<main>
<slot />
</main>
<footer>
<p>visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to learn SvelteKit</p>
</footer>
<style>
main {
flex: 1;
display: flex;
flex-direction: column;
padding: 1rem;
width: 100%;
max-width: 1024px;
margin: 0 auto;
box-sizing: border-box;
}
footer {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 40px;
}
footer a {
font-weight: bold;
}
@media (min-width: 480px) {
footer {
padding: 40px 0;
}
}
</style>

View File

@@ -1,50 +0,0 @@
<script context="module">
import { browser, dev } from '$app/env';
// we don't need any JS on this page, though we'll load
// it in dev so that we get hot module replacement...
export const hydrate = dev;
// ...but if the client-side router is already loaded
// (i.e. we came here from elsewhere in the app), use it
export const router = browser;
// since there's no dynamic data here, we can prerender
// it so that it gets served as a static asset in prod
export const prerender = true;
</script>
<svelte:head>
<title>About</title>
<meta name="description" content="About this app" />
</svelte:head>
<div class="content">
<h1>About this app</h1>
<p>
This is a <a href="https://kit.svelte.dev">SvelteKit</a> app. You can make your own by typing the
following into your command line and following the prompts:
</p>
<pre>npm init svelte</pre>
<p>
The page you're looking at is purely static HTML, with no client-side interactivity needed.
Because of that, we don't need to load any JavaScript. Try viewing the page's source, or opening
the devtools network panel and reloading.
</p>
<p>
The <a href="/todos">TODOs</a> page illustrates SvelteKit's data loading and form handling. Try using
it with JavaScript disabled!
</p>
</div>
<style>
.content {
width: 100%;
max-width: var(--column-width);
margin: var(--column-margin-top) auto 0 auto;
}
</style>

View File

@@ -0,0 +1,13 @@
import { browser, dev } from '$app/env';
// we don't need any JS on this page, though we'll load
// it in dev so that we get hot module replacement...
export const hydrate = dev;
// ...but if the client-side router is already loaded
// (i.e. we came here from elsewhere in the app), use it
export const router = browser;
// since there's no dynamic data here, we can prerender
// it so that it gets served as a static asset in prod
export const prerender = true;

View File

@@ -0,0 +1,34 @@
<svelte:head>
<title>About</title>
<meta name="description" content="About this app" />
</svelte:head>
<div class="content">
<h1>About this app</h1>
<p>
This is a <a href="https://kit.svelte.dev">SvelteKit</a> app. You can make your own by typing the
following into your command line and following the prompts:
</p>
<pre>npm create svelte@latest</pre>
<p>
The page you're looking at is purely static HTML, with no client-side interactivity needed.
Because of that, we don't need to load any JavaScript. Try viewing the page's source, or opening
the devtools network panel and reloading.
</p>
<p>
The <a href="/todos">TODOs</a> page illustrates SvelteKit's data loading and form handling. Try using
it with JavaScript disabled!
</p>
</div>
<style>
.content {
width: 100%;
max-width: var(--column-width);
margin: var(--column-margin-top) auto 0 auto;
}
</style>

View File

@@ -1,60 +0,0 @@
<script context="module">
export const prerender = true;
</script>
<script>
import Counter from '$lib/Counter.svelte';
</script>
<svelte:head>
<title>Home</title>
<meta name="description" content="Svelte demo app" />
</svelte:head>
<section>
<h1>
<div class="welcome">
<picture>
<source srcset="svelte-welcome.webp" type="image/webp" />
<img src="svelte-welcome.png" alt="Welcome" />
</picture>
</div>
to your new<br />SvelteKit app
</h1>
<h2>
try editing <strong>src/routes/index.svelte</strong>
</h2>
<Counter />
</section>
<style>
section {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
flex: 1;
}
h1 {
width: 100%;
}
.welcome {
position: relative;
width: 100%;
height: 0;
padding: 0 0 calc(100% * 495 / 2048) 0;
}
.welcome img {
position: absolute;
width: 100%;
height: 100%;
top: 0;
display: block;
}
</style>

View File

@@ -0,0 +1,62 @@
import { error } from '@sveltejs/kit';
import { api } from './api';
/**
* @typedef {{
* uid: string;
* created_at: Date;
* text: string;
* done: boolean;
* pending_delete: boolean;
* }} Todo
*/
/** @type {import('./$types').PageServerLoad} */
export const load = async ({ locals }) => {
// locals.userid comes from src/hooks.js
const response = await api('GET', `todos/${locals.userid}`);
if (response.status === 404) {
// user hasn't created a todo list.
// start with an empty array
return {
/** @type {Todo[]} */
todos: []
};
}
if (response.status === 200) {
return {
/** @type {Todo[]} */
todos: await response.json()
};
}
throw error(response.status);
};
/** @type {import('./$types').Action} */
export const POST = async ({ request, locals }) => {
const form = await request.formData();
await api('POST', `todos/${locals.userid}`, {
text: form.get('text')
});
};
/** @type {import('./$types').Action} */
export const PATCH = async ({ request, locals }) => {
const form = await request.formData();
await api('PATCH', `todos/${locals.userid}/${form.get('uid')}`, {
text: form.has('text') ? form.get('text') : undefined,
done: form.has('done') ? !!form.get('done') : undefined
});
};
/** @type {import('./$types').Action} */
export const DELETE = async ({ request, locals }) => {
const form = await request.formData();
await api('DELETE', `todos/${locals.userid}/${form.get('uid')}`);
};

View File

@@ -0,0 +1,180 @@
<script>
import { enhance } from '$lib/form';
import { scale } from 'svelte/transition';
import { flip } from 'svelte/animate';
/** @type {import('./$types').PageData} */
export let data;
</script>
<svelte:head>
<title>Todos</title>
<meta name="description" content="A todo list app" />
</svelte:head>
<div class="todos">
<h1>Todos</h1>
<form
class="new"
action="/todos"
method="post"
use:enhance={{
result: async ({ form }) => {
form.reset();
}
}}
>
<input name="text" aria-label="Add todo" placeholder="+ tap to add a todo" />
</form>
{#each data.todos as todo (todo.uid)}
<div
class="todo"
class:done={todo.done}
transition:scale|local={{ start: 0.7 }}
animate:flip={{ duration: 200 }}
>
<form
action="/todos?_method=PATCH"
method="post"
use:enhance={{
pending: ({ data }) => {
todo.done = !!data.get('done');
}
}}
>
<input type="hidden" name="uid" value={todo.uid} />
<input type="hidden" name="done" value={todo.done ? '' : 'true'} />
<button class="toggle" aria-label="Mark todo as {todo.done ? 'not done' : 'done'}" />
</form>
<form class="text" action="/todos?_method=PATCH" method="post" use:enhance>
<input type="hidden" name="uid" value={todo.uid} />
<input aria-label="Edit todo" type="text" name="text" value={todo.text} />
<button class="save" aria-label="Save todo" />
</form>
<form
action="/todos?_method=DELETE"
method="post"
use:enhance={{
pending: () => (todo.pending_delete = true)
}}
>
<input type="hidden" name="uid" value={todo.uid} />
<button class="delete" aria-label="Delete todo" disabled={todo.pending_delete} />
</form>
</div>
{/each}
</div>
<style>
.todos {
width: 100%;
max-width: var(--column-width);
margin: var(--column-margin-top) auto 0 auto;
line-height: 1;
}
.new {
margin: 0 0 0.5rem 0;
}
input {
border: 1px solid transparent;
}
input:focus-visible {
box-shadow: inset 1px 1px 6px rgba(0, 0, 0, 0.1);
border: 1px solid #ff3e00 !important;
outline: none;
}
.new input {
font-size: 28px;
width: 100%;
padding: 0.5em 1em 0.3em 1em;
box-sizing: border-box;
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
text-align: center;
}
.todo {
display: grid;
grid-template-columns: 2rem 1fr 2rem;
grid-gap: 0.5rem;
align-items: center;
margin: 0 0 0.5rem 0;
padding: 0.5rem;
background-color: white;
border-radius: 8px;
filter: drop-shadow(2px 4px 6px rgba(0, 0, 0, 0.1));
transform: translate(-1px, -1px);
transition: filter 0.2s, transform 0.2s;
}
.done {
transform: none;
opacity: 0.4;
filter: drop-shadow(0 0 1px rgba(0, 0, 0, 0.1));
}
form.text {
position: relative;
display: flex;
align-items: center;
flex: 1;
}
.todo input {
flex: 1;
padding: 0.5em 2em 0.5em 0.8em;
border-radius: 3px;
}
.todo button {
width: 2em;
height: 2em;
border: none;
background-color: transparent;
background-position: 50% 50%;
background-repeat: no-repeat;
}
button.toggle {
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 50%;
box-sizing: border-box;
background-size: 1em auto;
}
.done .toggle {
background-image: url("data:image/svg+xml,%3Csvg width='22' height='16' viewBox='0 0 22 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M20.5 1.5L7.4375 14.5L1.5 8.5909' stroke='%23676778' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
}
.delete {
background-image: url("data:image/svg+xml,%3Csvg width='24' height='24' viewBox='0 0 24 24' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M4.5 5V22H19.5V5H4.5Z' fill='%23676778' stroke='%23676778' stroke-width='1.5' stroke-linejoin='round'/%3E%3Cpath d='M10 10V16.5' stroke='white' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M14 10V16.5' stroke='white' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M2 5H22' stroke='%23676778' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M8 5L9.6445 2H14.3885L16 5H8Z' fill='%23676778' stroke='%23676778' stroke-width='1.5' stroke-linejoin='round'/%3E%3C/svg%3E%0A");
opacity: 0.2;
}
.delete:hover,
.delete:focus {
transition: opacity 0.2s;
opacity: 1;
}
.save {
position: absolute;
right: 0;
opacity: 0;
background-image: url("data:image/svg+xml,%3Csvg width='24' height='24' viewBox='0 0 24 24' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M20.5 2H3.5C2.67158 2 2 2.67157 2 3.5V20.5C2 21.3284 2.67158 22 3.5 22H20.5C21.3284 22 22 21.3284 22 20.5V3.5C22 2.67157 21.3284 2 20.5 2Z' fill='%23676778' stroke='%23676778' stroke-width='1.5' stroke-linejoin='round'/%3E%3Cpath d='M17 2V11H7.5V2H17Z' fill='white' stroke='white' stroke-width='1.5' stroke-linejoin='round'/%3E%3Cpath d='M13.5 5.5V7.5' stroke='%23676778' stroke-width='1.5' stroke-linecap='round'/%3E%3Cpath d='M5.99844 2H18.4992' stroke='%23676778' stroke-width='1.5' stroke-linecap='round'/%3E%3C/svg%3E%0A");
}
.todo input:focus + .save,
.save:focus {
transition: opacity 0.2s;
opacity: 1;
}
</style>

View File

@@ -1,9 +1,7 @@
/*
This module is used by the /todos endpoint to
make calls to api.svelte.dev, which stores todos
for each user. The leading underscore indicates that this is
a private module, _not_ an endpoint visiting /todos/_api
will net you a 404 response.
for each user.
(The data on the todo app will expire periodically; no
guarantees are made. Don't use it to organise your life.)

View File

@@ -1,70 +0,0 @@
import { api } from './_api';
/** @type {import('./__types').RequestHandler} */
export const get = async ({ locals }) => {
// locals.userid comes from src/hooks.js
const response = await api('get', `todos/${locals.userid}`);
if (response.status === 404) {
// user hasn't created a todo list.
// start with an empty array
return {
body: {
todos: []
}
};
}
if (response.status === 200) {
return {
body: {
todos: await response.json()
}
};
}
return {
status: response.status
};
};
/** @type {import('./index').RequestHandler} */
export const post = async ({ request, locals }) => {
const form = await request.formData();
await api('post', `todos/${locals.userid}`, {
text: form.get('text')
});
return {};
};
// If the user has JavaScript disabled, the URL will change to
// include the method override unless we redirect back to /todos
const redirect = {
status: 303,
headers: {
location: '/todos'
}
};
/** @type {import('./index').RequestHandler} */
export const patch = async ({ request, locals }) => {
const form = await request.formData();
await api('patch', `todos/${locals.userid}/${form.get('uid')}`, {
text: form.has('text') ? form.get('text') : undefined,
done: form.has('done') ? !!form.get('done') : undefined
});
return redirect;
};
/** @type {import('./index').RequestHandler} */
export const del = async ({ request, locals }) => {
const form = await request.formData();
await api('delete', `todos/${locals.userid}/${form.get('uid')}`);
return redirect;
};

View File

@@ -1,190 +0,0 @@
<script>
import { enhance } from '$lib/form';
import { scale } from 'svelte/transition';
import { flip } from 'svelte/animate';
/**
* @typedef {{
* uid: string;
* created_at: Date;
* text: string;
* done: boolean;
* pending_delete: boolean;
* }} Todo
*/
/** @type {Todo[]} */
export let todos;
</script>
<svelte:head>
<title>Todos</title>
<meta name="description" content="A todo list app" />
</svelte:head>
<div class="todos">
<h1>Todos</h1>
<form
class="new"
action="/todos"
method="post"
use:enhance={{
result: async ({ form }) => {
form.reset();
}
}}
>
<input name="text" aria-label="Add todo" placeholder="+ tap to add a todo" />
</form>
{#each todos as todo (todo.uid)}
<div
class="todo"
class:done={todo.done}
transition:scale|local={{ start: 0.7 }}
animate:flip={{ duration: 200 }}
>
<form
action="/todos?_method=PATCH"
method="post"
use:enhance={{
pending: ({ data }) => {
todo.done = !!data.get('done');
}
}}
>
<input type="hidden" name="uid" value={todo.uid} />
<input type="hidden" name="done" value={todo.done ? '' : 'true'} />
<button class="toggle" aria-label="Mark todo as {todo.done ? 'not done' : 'done'}" />
</form>
<form class="text" action="/todos?_method=PATCH" method="post" use:enhance>
<input type="hidden" name="uid" value={todo.uid} />
<input aria-label="Edit todo" type="text" name="text" value={todo.text} />
<button class="save" aria-label="Save todo" />
</form>
<form
action="/todos?_method=DELETE"
method="post"
use:enhance={{
pending: () => (todo.pending_delete = true)
}}
>
<input type="hidden" name="uid" value={todo.uid} />
<button class="delete" aria-label="Delete todo" disabled={todo.pending_delete} />
</form>
</div>
{/each}
</div>
<style>
.todos {
width: 100%;
max-width: var(--column-width);
margin: var(--column-margin-top) auto 0 auto;
line-height: 1;
}
.new {
margin: 0 0 0.5rem 0;
}
input {
border: 1px solid transparent;
}
input:focus-visible {
box-shadow: inset 1px 1px 6px rgba(0, 0, 0, 0.1);
border: 1px solid #ff3e00 !important;
outline: none;
}
.new input {
font-size: 28px;
width: 100%;
padding: 0.5em 1em 0.3em 1em;
box-sizing: border-box;
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
text-align: center;
}
.todo {
display: grid;
grid-template-columns: 2rem 1fr 2rem;
grid-gap: 0.5rem;
align-items: center;
margin: 0 0 0.5rem 0;
padding: 0.5rem;
background-color: white;
border-radius: 8px;
filter: drop-shadow(2px 4px 6px rgba(0, 0, 0, 0.1));
transform: translate(-1px, -1px);
transition: filter 0.2s, transform 0.2s;
}
.done {
transform: none;
opacity: 0.4;
filter: drop-shadow(0 0 1px rgba(0, 0, 0, 0.1));
}
form.text {
position: relative;
display: flex;
align-items: center;
flex: 1;
}
.todo input {
flex: 1;
padding: 0.5em 2em 0.5em 0.8em;
border-radius: 3px;
}
.todo button {
width: 2em;
height: 2em;
border: none;
background-color: transparent;
background-position: 50% 50%;
background-repeat: no-repeat;
}
button.toggle {
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 50%;
box-sizing: border-box;
background-size: 1em auto;
}
.done .toggle {
background-image: url("data:image/svg+xml,%3Csvg width='22' height='16' viewBox='0 0 22 16' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M20.5 1.5L7.4375 14.5L1.5 8.5909' stroke='%23676778' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
}
.delete {
background-image: url("data:image/svg+xml,%3Csvg width='24' height='24' viewBox='0 0 24 24' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M4.5 5V22H19.5V5H4.5Z' fill='%23676778' stroke='%23676778' stroke-width='1.5' stroke-linejoin='round'/%3E%3Cpath d='M10 10V16.5' stroke='white' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M14 10V16.5' stroke='white' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M2 5H22' stroke='%23676778' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M8 5L9.6445 2H14.3885L16 5H8Z' fill='%23676778' stroke='%23676778' stroke-width='1.5' stroke-linejoin='round'/%3E%3C/svg%3E%0A");
opacity: 0.2;
}
.delete:hover,
.delete:focus {
transition: opacity 0.2s;
opacity: 1;
}
.save {
position: absolute;
right: 0;
opacity: 0;
background-image: url("data:image/svg+xml,%3Csvg width='24' height='24' viewBox='0 0 24 24' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M20.5 2H3.5C2.67158 2 2 2.67157 2 3.5V20.5C2 21.3284 2.67158 22 3.5 22H20.5C21.3284 22 22 21.3284 22 20.5V3.5C22 2.67157 21.3284 2 20.5 2Z' fill='%23676778' stroke='%23676778' stroke-width='1.5' stroke-linejoin='round'/%3E%3Cpath d='M17 2V11H7.5V2H17Z' fill='white' stroke='white' stroke-width='1.5' stroke-linejoin='round'/%3E%3Cpath d='M13.5 5.5V7.5' stroke='%23676778' stroke-width='1.5' stroke-linecap='round'/%3E%3Cpath d='M5.99844 2H18.4992' stroke='%23676778' stroke-width='1.5' stroke-linecap='round'/%3E%3C/svg%3E%0A");
}
.todo input:focus + .save,
.save:focus {
transition: opacity 0.2s;
opacity: 1;
}
</style>

View File

@@ -8,11 +8,6 @@ const config = {
// Override http methods in the Todo forms
methodOverride: {
allowed: ['PATCH', 'DELETE']
},
vite: {
define: {
'import.meta.env.VERCEL_ANALYTICS_ID': JSON.stringify(process.env.VERCEL_ANALYTICS_ID)
}
}
}
};

View File

@@ -0,0 +1,11 @@
import { sveltekit } from '@sveltejs/kit/vite';
/** @type {import('vite').UserConfig} */
const config = {
plugins: [sveltekit()],
define: {
'import.meta.env.VERCEL_ANALYTICS_ID': JSON.stringify(process.env.VERCEL_ANALYTICS_ID)
}
};
export default config;

File diff suppressed because it is too large Load Diff

View File

@@ -8,7 +8,10 @@
"packages/*"
],
"nohoist": [
"**/@types/**"
"**/@types/**",
"**/typedoc",
"**/typedoc-plugin-markdown",
"**/typedoc-plugin-mdn-links"
]
},
"dependencies": {
@@ -31,7 +34,7 @@
"prettier": "2.6.2",
"ts-eager": "2.0.2",
"ts-jest": "28.0.5",
"turbo": "1.3.2-canary.1"
"turbo": "1.4.7"
},
"scripts": {
"lerna": "lerna",
@@ -99,6 +102,7 @@
"selector": "MemberExpression > Identifier[name='substr']"
}
],
"no-dupe-keys": 2,
"require-atomic-updates": 0,
"@typescript-eslint/ban-ts-comment": 0,
"@typescript-eslint/camelcase": 0,

View File

@@ -1,6 +1,6 @@
{
"name": "@vercel/build-utils",
"version": "5.3.0",
"version": "5.5.4",
"license": "MIT",
"main": "./dist/index.js",
"types": "./dist/index.d.js",

View File

@@ -0,0 +1,34 @@
import type { Env } from './types';
const { hasOwnProperty } = Object.prototype;
/**
* Clones zero or more objects into a single new object while ensuring that the
* `PATH` environment variable is defined when the `PATH` or `Path` environment
* variables are defined.
*
* @param {Object} [...envs] Objects and/or `process.env` to clone and merge
* @returns {Object} The new object
*/
export function cloneEnv(...envs: (Env | undefined)[]): Env {
return envs.reduce((obj: Env, env) => {
if (env === undefined || env === null) {
return obj;
}
// mixin the env first
obj = Object.assign(obj, env);
if (hasOwnProperty.call(env, 'Path')) {
// the system path is called `Path` on Windows and Node.js will
// automatically return the system path when accessing `PATH`,
// however we lose this proxied value when we destructure and
// thus we must explicitly copy it, but we must also remove the
// `Path` property since we can't have both a `PATH` and `Path`
obj.PATH = obj.Path;
delete obj.Path;
}
return obj;
}, {});
}

View File

@@ -3,5 +3,7 @@ import { getPlatformEnv } from './get-platform-env';
export default function debug(message: string, ...additional: any[]) {
if (getPlatformEnv('BUILDER_DEBUG')) {
console.log(message, ...additional);
} else if (process.env.VERCEL_DEBUG_PREFIX) {
console.log(`${process.env.VERCEL_DEBUG_PREFIX}${message}`, ...additional);
}
}

View File

@@ -38,6 +38,9 @@ export class EdgeFunction {
*/
assets?: { name: string; path: string }[];
/** The regions where the edge function will be executed on */
regions?: 'auto' | string[] | 'all' | 'default';
constructor(params: Omit<EdgeFunction, 'type'>) {
this.type = 'EdgeFunction';
this.name = params.name;
@@ -46,5 +49,6 @@ export class EdgeFunction {
this.files = params.files;
this.envVarsInUse = params.envVarsInUse;
this.assets = params.assets;
this.regions = params.regions;
}
}

View File

@@ -61,14 +61,14 @@ export function getPrettyError(obj: {
}
return new NowBuildError({
code: 'DEV_VALIDATE_CONFIG',
code: 'INVALID_VERCEL_CONFIG',
message: message,
link: prop ? `${docsUrl}#project/${prop.toLowerCase()}` : docsUrl,
action: 'View Documentation',
});
} catch (e) {
return new NowBuildError({
code: 'DEV_VALIDATE_CONFIG',
code: 'INVALID_VERCEL_CONFIG',
message: `Failed to validate configuration.`,
link: docsUrl,
action: 'View Documentation',

View File

@@ -5,7 +5,13 @@ import path from 'path';
import Sema from 'async-sema';
import { FileBase } from './types';
const semaToPreventEMFILE = new Sema(20);
const DEFAULT_SEMA = 20;
const semaToPreventEMFILE = new Sema(
parseInt(
process.env.VERCEL_INTERNAL_FILE_FS_REF_SEMA || String(DEFAULT_SEMA),
10
) || DEFAULT_SEMA
);
interface FileFsRefOptions {
mode?: number;

View File

@@ -12,7 +12,13 @@ interface FileRefOptions {
mutable?: boolean;
}
const semaToDownloadFromS3 = new Sema(5);
const DEFAULT_SEMA = 5;
const semaToDownloadFromS3 = new Sema(
parseInt(
process.env.VERCEL_INTERNAL_FILE_REF_SEMA || String(DEFAULT_SEMA),
10
) || DEFAULT_SEMA
);
class BailableError extends Error {
public bail: boolean;

View File

@@ -8,17 +8,13 @@ import FileFsRef from '../file-fs-ref';
export type GlobOptions = vanillaGlob_.IOptions;
interface FsFiles {
[filePath: string]: FileFsRef;
}
const vanillaGlob = promisify(vanillaGlob_);
export default async function glob(
pattern: string,
opts: GlobOptions | string,
mountpoint?: string
): Promise<FsFiles> {
): Promise<Record<string, FileFsRef>> {
let options: GlobOptions;
if (typeof opts === 'string') {
options = { cwd: opts };
@@ -36,10 +32,11 @@ export default async function glob(
throw new Error(`basePath/cwd must be an absolute path (${options.cwd})`);
}
const results: FsFiles = {};
const results: Record<string, FileFsRef> = {};
const statCache: Record<string, Stats> = {};
options.symlinks = {};
options.statCache = {};
options.statCache = statCache;
options.stat = true;
options.dot = true;
@@ -47,7 +44,7 @@ export default async function glob(
for (const relativePath of files) {
const fsPath = normalizePath(path.join(options.cwd, relativePath));
let stat: Stats = options.statCache[fsPath] as Stats;
let stat = statCache[fsPath];
assert(
stat,
`statCache does not contain value for ${relativePath} (resolved to ${fsPath})`

View File

@@ -10,7 +10,7 @@ const allOptions = [
major: 12,
range: '12.x',
runtime: 'nodejs12.x',
discontinueDate: new Date('2022-10-01'),
discontinueDate: new Date('2022-10-03'),
},
{
major: 10,

View File

@@ -11,6 +11,7 @@ import { NowBuildError } from '../errors';
import { Meta, PackageJson, NodeVersion, Config } from '../types';
import { getSupportedNodeVersion, getLatestNodeVersion } from './node-version';
import { readConfigFile } from './read-config-file';
import { cloneEnv } from '../clone-env';
// Only allow one `runNpmInstall()` invocation to run concurrently
const runNpmInstallSema = new Sema(1);
@@ -23,8 +24,7 @@ export interface ScanParentDirsResult {
*/
cliType: CliType;
/**
* The file path of found `package.json` file, or `undefined` if none was
* found.
* The file path of found `package.json` file, or `undefined` if not found.
*/
packageJsonPath?: string;
/**
@@ -33,8 +33,13 @@ export interface ScanParentDirsResult {
*/
packageJson?: PackageJson;
/**
* The `lockfileVersion` number from the `package-lock.json` file,
* when present.
* The file path of the lockfile (`yarn.lock`, `package-lock.json`, or `pnpm-lock.yaml`)
* or `undefined` if not found.
*/
lockfilePath?: string;
/**
* The `lockfileVersion` number from lockfile (`package-lock.json` or `pnpm-lock.yaml`),
* or `undefined` if not found.
*/
lockfileVersion?: number;
}
@@ -178,25 +183,9 @@ export async function getNodeBinPath({
}: {
cwd: string;
}): Promise<string> {
const { code, stdout, stderr } = await execAsync('npm', ['bin'], {
cwd,
prettyCommand: 'npm bin',
// in some rare cases, we saw `npm bin` exit with a non-0 code, but still
// output the right bin path, so we ignore the exit code
ignoreNon0Exit: true,
});
const nodeBinPath = stdout.trim();
if (path.isAbsolute(nodeBinPath)) {
return nodeBinPath;
}
throw new NowBuildError({
code: `BUILD_UTILS_GET_NODE_BIN_PATH`,
message: `Running \`npm bin\` failed to return a valid bin path (code=${code}, stdout=${stdout}, stderr=${stderr})`,
});
const { lockfilePath } = await scanParentDirs(cwd);
const dir = path.dirname(lockfilePath || cwd);
return path.join(dir, 'node_modules', '.bin');
}
async function chmodPlusX(fsPath: string) {
@@ -229,7 +218,7 @@ export function getSpawnOptions(
nodeVersion: NodeVersion
): SpawnOptions {
const opts = {
env: { ...process.env },
env: cloneEnv(process.env),
};
if (!meta.isDev) {
@@ -319,6 +308,7 @@ export async function scanParentDirs(
start: destPath,
filenames: ['yarn.lock', 'package-lock.json', 'pnpm-lock.yaml'],
});
let lockfilePath: string | undefined;
let lockfileVersion: number | undefined;
let cliType: CliType = 'yarn';
@@ -335,17 +325,25 @@ export async function scanParentDirs(
// Priority order is Yarn > pnpm > npm
if (hasYarnLock) {
cliType = 'yarn';
lockfilePath = yarnLockPath;
} else if (pnpmLockYaml) {
cliType = 'pnpm';
// just ensure that it is read as a number and not a string
lockfilePath = pnpmLockPath;
lockfileVersion = Number(pnpmLockYaml.lockfileVersion);
} else if (packageLockJson) {
cliType = 'npm';
lockfilePath = npmLockPath;
lockfileVersion = packageLockJson.lockfileVersion;
}
const packageJsonPath = pkgJsonPath || undefined;
return { cliType, packageJson, lockfileVersion, packageJsonPath };
return {
cliType,
packageJson,
lockfilePath,
lockfileVersion,
packageJsonPath,
};
}
export async function walkParentDirs({
@@ -452,7 +450,7 @@ export async function runNpmInstall(
debug(`Installing to ${destPath}`);
const opts: SpawnOptionsExtended = { cwd: destPath, ...spawnOpts };
const env = opts.env ? { ...opts.env } : { ...process.env };
const env = cloneEnv(opts.env || process.env);
delete env.NODE_ENV;
opts.env = getEnvForPackageManager({
cliType,
@@ -461,12 +459,30 @@ export async function runNpmInstall(
env,
});
let commandArgs: string[];
const isPotentiallyBrokenNpm =
cliType === 'npm' &&
(nodeVersion?.major === 16 ||
opts.env.PATH?.includes('/node16/bin-npm7')) &&
!args.includes('--legacy-peer-deps') &&
spawnOpts?.env?.ENABLE_EXPERIMENTAL_COREPACK !== '1';
if (cliType === 'npm') {
opts.prettyCommand = 'npm install';
commandArgs = args
.filter(a => a !== '--prefer-offline')
.concat(['install', '--no-audit', '--unsafe-perm']);
if (
isPotentiallyBrokenNpm &&
spawnOpts?.env?.VERCEL_NPM_LEGACY_PEER_DEPS === '1'
) {
// Starting in npm@8.6.0, if you ran `npm install --legacy-peer-deps`,
// and then later ran `npm install`, it would fail. So the only way
// to safely upgrade npm from npm@8.5.0 is to set this flag. The docs
// say this flag is not recommended so its is behind a feature flag
// so we can remove it in node@18, which can introduce breaking changes.
// See https://docs.npmjs.com/cli/v8/using-npm/config#legacy-peer-deps
commandArgs.push('--legacy-peer-deps');
}
} else if (cliType === 'pnpm') {
// PNPM's install command is similar to NPM's but without the audit nonsense
// @see options https://pnpm.io/cli/install
@@ -483,7 +499,26 @@ export async function runNpmInstall(
commandArgs.push('--production');
}
try {
await spawnAsync(cliType, commandArgs, opts);
} catch (_) {
const potentialErrorPath = path.join(
process.env.HOME || '/',
'.npm',
'eresolve-report.txt'
);
if (
isPotentiallyBrokenNpm &&
!commandArgs.includes('--legacy-peer-deps') &&
fs.existsSync(potentialErrorPath)
) {
console.warn(
'Warning: Retrying "Install Command" with `--legacy-peer-deps` which may accept a potentially broken dependency and slow install time.'
);
commandArgs.push('--legacy-peer-deps');
await spawnAsync(cliType, commandArgs, opts);
}
}
debug(`Install complete [${Date.now() - installTime}ms]`);
return true;
} finally {
@@ -594,10 +629,7 @@ export async function runPackageJsonScript(
cliType,
lockfileVersion,
nodeVersion: undefined,
env: {
...process.env,
...spawnOpts?.env,
},
env: cloneEnv(process.env, spawnOpts?.env),
}),
};

View File

@@ -41,6 +41,7 @@ import debug from './debug';
import getIgnoreFilter from './get-ignore-filter';
import { getPlatformEnv } from './get-platform-env';
import { getPrefixedEnvVars } from './get-prefixed-env-vars';
import { cloneEnv } from './clone-env';
export {
FileBlob,
@@ -84,6 +85,7 @@ export {
getLambdaOptionsFromFunction,
scanParentDirs,
getIgnoreFilter,
cloneEnv,
};
export { EdgeFunction } from './edge-function';

View File

@@ -41,6 +41,7 @@ export interface Config {
devCommand?: string;
framework?: string | null;
nodeVersion?: string;
middleware?: boolean;
[key: string]: unknown;
}
@@ -341,6 +342,7 @@ export interface BuilderV2 {
version: 2;
build: BuildV2;
prepareCache?: PrepareCache;
shouldServe?: ShouldServe;
}
export interface BuilderV3 {

View File

@@ -0,0 +1,2 @@
node_modules
.vercel

View File

@@ -0,0 +1,64 @@
{
"requires": true,
"lockfileVersion": 1,
"dependencies": {
"js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
},
"loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"requires": {
"js-tokens": "^3.0.0 || ^4.0.0"
}
},
"object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="
},
"prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
"requires": {
"loose-envify": "^1.4.0",
"object-assign": "^4.1.1",
"react-is": "^16.13.1"
}
},
"react": {
"version": "16.8.0",
"resolved": "https://registry.npmjs.org/react/-/react-16.8.0.tgz",
"integrity": "sha512-g+nikW2D48kqgWSPwNo0NH9tIGG3DsQFlrtrQ1kj6W77z5ahyIHG0w8kPpz4Sdj6gyLnz0lEd/xsjOoGge2MYQ==",
"requires": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
"prop-types": "^15.6.2",
"scheduler": "^0.13.0"
}
},
"react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
},
"scheduler": {
"version": "0.13.6",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.13.6.tgz",
"integrity": "sha512-IWnObHt413ucAYKsD9J1QShUKkbKLQQHdxRyw73sw4FN26iWr3DY/H34xGPe4nmL1DwXyWmSWmMrA9TfQbE/XQ==",
"requires": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1"
}
},
"swr": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/swr/-/swr-1.3.0.tgz",
"integrity": "sha512-dkghQrOl2ORX9HYrMDtPa7LTVHJjCTeZoB1dqTbnnEDlSvN8JEKpYIYurDfvbQFUUS8Cg8PceFVZNkW0KNNYPw=="
}
}
}

View File

@@ -0,0 +1,11 @@
{
"private": true,
"scripts": {
"build": "mkdir -p public && echo 'legacy peer deps' > public/index.txt"
},
"packageManager": "npm@6.14.17",
"dependencies": {
"swr": "1.3.0",
"react": "16.8.0"
}
}

View File

@@ -0,0 +1,3 @@
{
"probes": [{ "path": "/", "mustContain": "legacy peer deps" }]
}

View File

@@ -0,0 +1,2 @@
node_modules
.vercel

View File

@@ -0,0 +1,143 @@
{
"name": "15-npm-8-legacy-peer-deps",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"dependencies": {
"react": "16.8.0",
"swr": "1.3.0"
}
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
"dependencies": {
"loose-envify": "^1.4.0",
"object-assign": "^4.1.1",
"react-is": "^16.13.1"
}
},
"node_modules/react": {
"version": "16.8.0",
"resolved": "https://registry.npmjs.org/react/-/react-16.8.0.tgz",
"integrity": "sha512-g+nikW2D48kqgWSPwNo0NH9tIGG3DsQFlrtrQ1kj6W77z5ahyIHG0w8kPpz4Sdj6gyLnz0lEd/xsjOoGge2MYQ==",
"dependencies": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
"prop-types": "^15.6.2",
"scheduler": "^0.13.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
},
"node_modules/scheduler": {
"version": "0.13.6",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.13.6.tgz",
"integrity": "sha512-IWnObHt413ucAYKsD9J1QShUKkbKLQQHdxRyw73sw4FN26iWr3DY/H34xGPe4nmL1DwXyWmSWmMrA9TfQbE/XQ==",
"dependencies": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1"
}
},
"node_modules/swr": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/swr/-/swr-1.3.0.tgz",
"integrity": "sha512-dkghQrOl2ORX9HYrMDtPa7LTVHJjCTeZoB1dqTbnnEDlSvN8JEKpYIYurDfvbQFUUS8Cg8PceFVZNkW0KNNYPw==",
"peerDependencies": {
"react": "^16.11.0 || ^17.0.0 || ^18.0.0"
}
}
},
"dependencies": {
"js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="
},
"loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"requires": {
"js-tokens": "^3.0.0 || ^4.0.0"
}
},
"object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="
},
"prop-types": {
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
"requires": {
"loose-envify": "^1.4.0",
"object-assign": "^4.1.1",
"react-is": "^16.13.1"
}
},
"react": {
"version": "16.8.0",
"resolved": "https://registry.npmjs.org/react/-/react-16.8.0.tgz",
"integrity": "sha512-g+nikW2D48kqgWSPwNo0NH9tIGG3DsQFlrtrQ1kj6W77z5ahyIHG0w8kPpz4Sdj6gyLnz0lEd/xsjOoGge2MYQ==",
"requires": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
"prop-types": "^15.6.2",
"scheduler": "^0.13.0"
}
},
"react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
},
"scheduler": {
"version": "0.13.6",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.13.6.tgz",
"integrity": "sha512-IWnObHt413ucAYKsD9J1QShUKkbKLQQHdxRyw73sw4FN26iWr3DY/H34xGPe4nmL1DwXyWmSWmMrA9TfQbE/XQ==",
"requires": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1"
}
},
"swr": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/swr/-/swr-1.3.0.tgz",
"integrity": "sha512-dkghQrOl2ORX9HYrMDtPa7LTVHJjCTeZoB1dqTbnnEDlSvN8JEKpYIYurDfvbQFUUS8Cg8PceFVZNkW0KNNYPw=="
}
}
}

View File

@@ -0,0 +1,11 @@
{
"private": true,
"scripts": {
"build": "mkdir -p public && echo 'legacy peer deps' > public/index.txt"
},
"packageManager": "npm@8.6.0",
"dependencies": {
"swr": "1.3.0",
"react": "16.8.0"
}
}

View File

@@ -0,0 +1,3 @@
{
"probes": [{ "path": "/", "mustContain": "legacy peer deps" }]
}

View File

@@ -5,6 +5,7 @@
"requires": true,
"packages": {
"": {
"name": "20-npm-7",
"version": "1.0.0"
}
}

View File

@@ -21,6 +21,8 @@ const skipFixtures: string[] = [
'08-zero-config-middleman',
'21-npm-workspaces',
'23-pnpm-workspaces',
'41-nx-monorepo',
'42-npm-workspace-with-nx',
];
// eslint-disable-next-line no-restricted-syntax

View File

@@ -0,0 +1,117 @@
import { cloneEnv } from '../src';
it('should clone env with Path', () => {
expect(
cloneEnv(
new Proxy(
{
foo: 'bar',
Path: 'baz',
},
{
get(target: typeof process.env, prop: string) {
if (prop === 'PATH') {
return target.PATH ?? target.Path;
}
return target[prop];
},
}
)
)
).toEqual({
foo: 'bar',
PATH: 'baz',
});
});
it('should clone env with PATH', () => {
expect(
cloneEnv({
foo: 'bar',
PATH: 'baz',
})
).toEqual({
foo: 'bar',
PATH: 'baz',
});
});
it('should clone and merge multiple env objects', () => {
// note: this also tests the last object doesn't overwrite `PATH` with
// `undefined`
expect(
cloneEnv(
{
foo: 'bar',
},
{
PATH: 'baz',
},
{
baz: 'wiz',
}
)
).toEqual({
foo: 'bar',
PATH: 'baz',
baz: 'wiz',
});
});
it('should clone the actual process.env object', () => {
expect(cloneEnv(process.env).PATH).toEqual(process.env.PATH);
});
it('should overwrite PATH with last value', () => {
expect(
cloneEnv(
new Proxy(
{
Path: 'foo',
},
{
get(target: typeof process.env, prop: string) {
if (prop === 'PATH') {
return target.PATH ?? target.Path;
}
return target[prop];
},
}
),
{
PATH: 'bar',
},
{
PATH: undefined,
}
)
).toEqual({
PATH: undefined,
});
});
it('should handle process.env at any argument position', () => {
expect(
cloneEnv(
{
foo: 'bar',
},
new Proxy(
{
Path: 'baz',
},
{
get(target: typeof process.env, prop: string) {
if (prop === 'PATH') {
return target.PATH ?? target.Path;
}
return target[prop];
},
}
)
)
).toEqual({
foo: 'bar',
PATH: 'baz',
});
});

View File

@@ -0,0 +1,46 @@
import { join, parse } from 'path';
import { getNodeBinPath } from '../src';
describe('Test `getNodeBinPath()`', () => {
it('should work with npm7', async () => {
const cwd = join(__dirname, 'fixtures', '20-npm-7');
const result = await getNodeBinPath({ cwd });
expect(result).toBe(join(cwd, 'node_modules', '.bin'));
});
it('should work with yarn', async () => {
const cwd = join(__dirname, 'fixtures', '19-yarn-v2');
const result = await getNodeBinPath({ cwd });
expect(result).toBe(join(cwd, 'node_modules', '.bin'));
});
it('should work with npm 6', async () => {
const cwd = join(__dirname, 'fixtures', '08-yarn-npm/with-npm');
const result = await getNodeBinPath({ cwd });
expect(result).toBe(join(cwd, 'node_modules', '.bin'));
});
it('should work with npm workspaces', async () => {
const cwd = join(__dirname, 'fixtures', '21-npm-workspaces/a');
const result = await getNodeBinPath({ cwd });
expect(result).toBe(join(cwd, '..', 'node_modules', '.bin'));
});
it('should work with pnpm', async () => {
const cwd = join(__dirname, 'fixtures', '22-pnpm');
const result = await getNodeBinPath({ cwd });
expect(result).toBe(join(cwd, 'node_modules', '.bin'));
});
it('should work with pnpm workspaces', async () => {
const cwd = join(__dirname, 'fixtures', '23-pnpm-workspaces/c');
const result = await getNodeBinPath({ cwd });
expect(result).toBe(join(cwd, '..', 'node_modules', '.bin'));
});
it('should fallback to cwd if no lockfile found', async () => {
const cwd = parse(process.cwd()).root;
const result = await getNodeBinPath({ cwd });
expect(result).toBe(join(cwd, 'node_modules', '.bin'));
});
});

View File

@@ -0,0 +1,197 @@
const spawnMock = jest.fn();
jest.mock('cross-spawn', () => {
const spawn = (...args: any) => {
spawnMock(...args);
const child = {
on: (type: string, fn: (code: number) => void) => {
if (type === 'close') {
return fn(0);
}
},
};
return child;
};
return spawn;
});
afterEach(() => {
spawnMock.mockClear();
});
import path from 'path';
import { runNpmInstall, cloneEnv } from '../src';
import type { Meta } from '../src/types';
function getTestSpawnOpts(env: Record<string, string>) {
return { env: cloneEnv(process.env, env) };
}
function getNodeVersion(major: number) {
return { major, range: `${major}.x`, runtime: `nodejs${major}.x` };
}
it('should not include peer dependencies when missing VERCEL_NPM_LEGACY_PEER_DEPS on node16', async () => {
const fixture = path.join(__dirname, 'fixtures', '20-npm-7');
const meta: Meta = {};
const spawnOpts = getTestSpawnOpts({});
const nodeVersion = getNodeVersion(16);
await runNpmInstall(fixture, [], spawnOpts, meta, nodeVersion);
expect(spawnMock.mock.calls.length).toBe(1);
const args = spawnMock.mock.calls[0];
expect(args[0]).toEqual('npm');
expect(args[1]).toEqual(['install', '--no-audit', '--unsafe-perm']);
expect(args[2]).toEqual({
cwd: fixture,
prettyCommand: 'npm install',
stdio: 'inherit',
env: expect.any(Object),
});
});
it('should include peer dependencies when VERCEL_NPM_LEGACY_PEER_DEPS=1 on node16', async () => {
const fixture = path.join(__dirname, 'fixtures', '20-npm-7');
const meta: Meta = {};
const spawnOpts = getTestSpawnOpts({ VERCEL_NPM_LEGACY_PEER_DEPS: '1' });
const nodeVersion = getNodeVersion(16);
await runNpmInstall(fixture, [], spawnOpts, meta, nodeVersion);
expect(spawnMock.mock.calls.length).toBe(1);
const args = spawnMock.mock.calls[0];
expect(args[0]).toEqual('npm');
expect(args[1]).toEqual([
'install',
'--no-audit',
'--unsafe-perm',
'--legacy-peer-deps',
]);
expect(args[2]).toEqual({
cwd: fixture,
prettyCommand: 'npm install',
stdio: 'inherit',
env: expect.any(Object),
});
});
it('should include peer dependencies when VERCEL_NPM_LEGACY_PEER_DEPS=1 on node14 and npm7+', async () => {
const fixture = path.join(__dirname, 'fixtures', '20-npm-7');
const meta: Meta = {};
const spawnOpts = getTestSpawnOpts({ VERCEL_NPM_LEGACY_PEER_DEPS: '1' });
const nodeVersion = getNodeVersion(14);
await runNpmInstall(fixture, [], spawnOpts, meta, nodeVersion);
expect(spawnMock.mock.calls.length).toBe(1);
const args = spawnMock.mock.calls[0];
expect(args[0]).toEqual('npm');
expect(args[1]).toEqual([
'install',
'--no-audit',
'--unsafe-perm',
'--legacy-peer-deps',
]);
expect(args[2]).toEqual({
cwd: fixture,
prettyCommand: 'npm install',
stdio: 'inherit',
env: expect.any(Object),
});
});
it('should not include peer dependencies when VERCEL_NPM_LEGACY_PEER_DEPS=1 on node14 and npm6', async () => {
const fixture = path.join(__dirname, 'fixtures', '14-npm-6-legacy-peer-deps');
const meta: Meta = {};
const spawnOpts = getTestSpawnOpts({ VERCEL_NPM_LEGACY_PEER_DEPS: '1' });
const nodeVersion = getNodeVersion(14);
await runNpmInstall(fixture, [], spawnOpts, meta, nodeVersion);
expect(spawnMock.mock.calls.length).toBe(1);
const args = spawnMock.mock.calls[0];
expect(args[0]).toEqual('npm');
expect(args[1]).toEqual(['install', '--no-audit', '--unsafe-perm']);
expect(args[2]).toEqual({
cwd: fixture,
prettyCommand: 'npm install',
stdio: 'inherit',
env: expect.any(Object),
});
});
it('should not include peer dependencies when VERCEL_NPM_LEGACY_PEER_DEPS=1 on node16 with corepack enabled', async () => {
const fixture = path.join(__dirname, 'fixtures', '20-npm-7');
const meta: Meta = {};
const spawnOpts = getTestSpawnOpts({
VERCEL_NPM_LEGACY_PEER_DEPS: '1',
ENABLE_EXPERIMENTAL_COREPACK: '1',
});
const nodeVersion = getNodeVersion(16);
await runNpmInstall(fixture, [], spawnOpts, meta, nodeVersion);
expect(spawnMock.mock.calls.length).toBe(1);
const args = spawnMock.mock.calls[0];
expect(args[0]).toEqual('npm');
expect(args[1]).toEqual(['install', '--no-audit', '--unsafe-perm']);
expect(args[2]).toEqual({
cwd: fixture,
prettyCommand: 'npm install',
stdio: 'inherit',
env: expect.any(Object),
});
});
it('should only invoke `runNpmInstall()` once per `package.json` file (serial)', async () => {
const meta: Meta = {};
const fixture = path.join(__dirname, 'fixtures', '02-zero-config-api');
const apiDir = path.join(fixture, 'api');
const run1 = await runNpmInstall(apiDir, [], undefined, meta);
expect(run1).toEqual(true);
expect(
(meta.runNpmInstallSet as Set<string>).has(
path.join(fixture, 'package.json')
)
).toEqual(true);
const run2 = await runNpmInstall(apiDir, [], undefined, meta);
expect(run2).toEqual(false);
const run3 = await runNpmInstall(fixture, [], undefined, meta);
expect(run3).toEqual(false);
expect(spawnMock.mock.calls.length).toBe(1);
const args = spawnMock.mock.calls[0];
expect(args[0]).toEqual('yarn');
expect(args[1]).toEqual(['install']);
expect(args[2]).toEqual({
cwd: apiDir,
prettyCommand: 'yarn install',
stdio: 'inherit',
env: expect.any(Object),
});
});
it('should only invoke `runNpmInstall()` once per `package.json` file (parallel)', async () => {
const meta: Meta = {};
const fixture = path.join(__dirname, 'fixtures', '02-zero-config-api');
const apiDir = path.join(fixture, 'api');
const [run1, run2, run3] = await Promise.all([
runNpmInstall(apiDir, [], undefined, meta),
runNpmInstall(apiDir, [], undefined, meta),
runNpmInstall(fixture, [], undefined, meta),
]);
expect(run1).toEqual(true);
expect(run2).toEqual(false);
expect(run3).toEqual(false);
expect(
(meta.runNpmInstallSet as Set<string>).has(
path.join(fixture, 'package.json')
)
).toEqual(true);
expect(spawnMock.mock.calls.length).toBe(1);
const args = spawnMock.mock.calls[0];
expect(args[0]).toEqual('yarn');
expect(args[1]).toEqual(['install']);
expect(args[2]).toEqual({
cwd: apiDir,
prettyCommand: 'yarn install',
stdio: 'inherit',
env: expect.any(Object),
});
});

View File

@@ -1,7 +1,6 @@
import ms from 'ms';
import path from 'path';
import fs, { readlink } from 'fs-extra';
import retry from 'async-retry';
import { strict as assert, strictEqual } from 'assert';
import { createZip } from '../src/lambda';
import { getSupportedNodeVersion } from '../src/fs/node-version';
@@ -16,7 +15,6 @@ import {
runPackageJsonScript,
scanParentDirs,
FileBlob,
Meta,
} from '../src';
jest.setTimeout(10 * 1000);
@@ -218,10 +216,6 @@ it('should download symlinks even with incorrect file', async () => {
});
it('should only match supported node versions, otherwise throw an error', async () => {
expect(await getSupportedNodeVersion('12.x', false)).toHaveProperty(
'major',
12
);
expect(await getSupportedNodeVersion('14.x', false)).toHaveProperty(
'major',
14
@@ -242,10 +236,6 @@ it('should only match supported node versions, otherwise throw an error', async
await expectBuilderError(getSupportedNodeVersion('foo', true), autoMessage);
await expectBuilderError(getSupportedNodeVersion('=> 10', true), autoMessage);
expect(await getSupportedNodeVersion('12.x', true)).toHaveProperty(
'major',
12
);
expect(await getSupportedNodeVersion('14.x', true)).toHaveProperty(
'major',
14
@@ -275,21 +265,21 @@ it('should only match supported node versions, otherwise throw an error', async
it('should match all semver ranges', async () => {
// See https://docs.npmjs.com/files/package.json#engines
expect(await getSupportedNodeVersion('12.0.0')).toHaveProperty('major', 12);
expect(await getSupportedNodeVersion('12.x')).toHaveProperty('major', 12);
expect(await getSupportedNodeVersion('14.0.0')).toHaveProperty('major', 14);
expect(await getSupportedNodeVersion('14.x')).toHaveProperty('major', 14);
expect(await getSupportedNodeVersion('>=10')).toHaveProperty('major', 16);
expect(await getSupportedNodeVersion('>=10.3.0')).toHaveProperty('major', 16);
expect(await getSupportedNodeVersion('11.5.0 - 12.5.0')).toHaveProperty(
expect(await getSupportedNodeVersion('16.5.0 - 16.9.0')).toHaveProperty(
'major',
12
16
);
expect(await getSupportedNodeVersion('>=9.5.0 <=12.5.0')).toHaveProperty(
expect(await getSupportedNodeVersion('>=9.5.0 <=14.5.0')).toHaveProperty(
'major',
12
14
);
expect(await getSupportedNodeVersion('~12.5.0')).toHaveProperty('major', 12);
expect(await getSupportedNodeVersion('^12.5.0')).toHaveProperty('major', 12);
expect(await getSupportedNodeVersion('12.5.0 - 14.5.0')).toHaveProperty(
expect(await getSupportedNodeVersion('~14.5.0')).toHaveProperty('major', 14);
expect(await getSupportedNodeVersion('^14.5.0')).toHaveProperty('major', 14);
expect(await getSupportedNodeVersion('14.5.0 - 14.20.0')).toHaveProperty(
'major',
14
);
@@ -436,8 +426,8 @@ it('should warn for deprecated versions, soon to be discontinued', async () => {
expect(warningMessages).toStrictEqual([
'Error: Node.js version 10.x has reached End-of-Life. Deployments created on or after 2021-04-20 will fail to build. Please set "engines": { "node": "16.x" } in your `package.json` file to use Node.js 16.',
'Error: Node.js version 10.x has reached End-of-Life. Deployments created on or after 2021-04-20 will fail to build. Please set Node.js Version to 16.x in your Project Settings to use Node.js 16.',
'Error: Node.js version 12.x has reached End-of-Life. Deployments created on or after 2022-10-01 will fail to build. Please set "engines": { "node": "16.x" } in your `package.json` file to use Node.js 16.',
'Error: Node.js version 12.x has reached End-of-Life. Deployments created on or after 2022-10-01 will fail to build. Please set Node.js Version to 16.x in your Project Settings to use Node.js 16.',
'Error: Node.js version 12.x has reached End-of-Life. Deployments created on or after 2022-10-03 will fail to build. Please set "engines": { "node": "16.x" } in your `package.json` file to use Node.js 16.',
'Error: Node.js version 12.x has reached End-of-Life. Deployments created on or after 2022-10-03 will fail to build. Please set Node.js Version to 16.x in your Project Settings to use Node.js 16.',
]);
global.Date.now = realDateNow;
@@ -501,6 +491,7 @@ it('should return lockfileVersion 2 with npm7', async () => {
const result = await scanParentDirs(fixture);
expect(result.cliType).toEqual('npm');
expect(result.lockfileVersion).toEqual(2);
expect(result.lockfilePath).toEqual(path.join(fixture, 'package-lock.json'));
expect(result.packageJsonPath).toEqual(path.join(fixture, 'package.json'));
});
@@ -509,6 +500,7 @@ it('should not return lockfileVersion with yarn', async () => {
const result = await scanParentDirs(fixture);
expect(result.cliType).toEqual('yarn');
expect(result.lockfileVersion).toEqual(undefined);
expect(result.lockfilePath).toEqual(path.join(fixture, 'yarn.lock'));
expect(result.packageJsonPath).toEqual(path.join(fixture, 'package.json'));
});
@@ -517,6 +509,7 @@ it('should return lockfileVersion 1 with older versions of npm', async () => {
const result = await scanParentDirs(fixture);
expect(result.cliType).toEqual('npm');
expect(result.lockfileVersion).toEqual(1);
expect(result.lockfilePath).toEqual(path.join(fixture, 'package-lock.json'));
expect(result.packageJsonPath).toEqual(path.join(fixture, 'package.json'));
});
@@ -525,6 +518,9 @@ it('should detect npm Workspaces', async () => {
const result = await scanParentDirs(fixture);
expect(result.cliType).toEqual('npm');
expect(result.lockfileVersion).toEqual(2);
expect(result.lockfilePath).toEqual(
path.join(fixture, '..', 'package-lock.json')
);
expect(result.packageJsonPath).toEqual(path.join(fixture, 'package.json'));
});
@@ -533,6 +529,7 @@ it('should detect pnpm without workspace', async () => {
const result = await scanParentDirs(fixture);
expect(result.cliType).toEqual('pnpm');
expect(result.lockfileVersion).toEqual(5.3);
expect(result.lockfilePath).toEqual(path.join(fixture, 'pnpm-lock.yaml'));
expect(result.packageJsonPath).toEqual(path.join(fixture, 'package.json'));
});
@@ -541,6 +538,9 @@ it('should detect pnpm with workspaces', async () => {
const result = await scanParentDirs(fixture);
expect(result.cliType).toEqual('pnpm');
expect(result.lockfileVersion).toEqual(5.3);
expect(result.lockfilePath).toEqual(
path.join(fixture, '..', 'pnpm-lock.yaml')
);
expect(result.packageJsonPath).toEqual(path.join(fixture, 'package.json'));
});
@@ -552,6 +552,7 @@ it('should detect package.json in nested backend', async () => {
const result = await scanParentDirs(fixture);
expect(result.cliType).toEqual('yarn');
expect(result.lockfileVersion).toEqual(undefined);
// There is no lockfile but this test will pick up vercel/vercel/yarn.lock
expect(result.packageJsonPath).toEqual(path.join(fixture, 'package.json'));
});
@@ -563,56 +564,20 @@ it('should detect package.json in nested frontend', async () => {
const result = await scanParentDirs(fixture);
expect(result.cliType).toEqual('yarn');
expect(result.lockfileVersion).toEqual(undefined);
// There is no lockfile but this test will pick up vercel/vercel/yarn.lock
expect(result.packageJsonPath).toEqual(path.join(fixture, 'package.json'));
});
it('should only invoke `runNpmInstall()` once per `package.json` file (serial)', async () => {
const meta: Meta = {};
const fixture = path.join(__dirname, 'fixtures', '02-zero-config-api');
const apiDir = path.join(fixture, 'api');
const retryOpts = { maxRetryTime: 1000 };
let run1, run2, run3;
await retry(async () => {
run1 = await runNpmInstall(apiDir, [], undefined, meta);
expect(run1).toEqual(true);
expect(
(meta.runNpmInstallSet as Set<string>).has(
path.join(fixture, 'package.json')
)
).toEqual(true);
}, retryOpts);
await retry(async () => {
run2 = await runNpmInstall(apiDir, [], undefined, meta);
expect(run2).toEqual(false);
}, retryOpts);
await retry(async () => {
run3 = await runNpmInstall(fixture, [], undefined, meta);
expect(run3).toEqual(false);
}, retryOpts);
});
it('should only invoke `runNpmInstall()` once per `package.json` file (parallel)', async () => {
const meta: Meta = {};
const fixture = path.join(__dirname, 'fixtures', '02-zero-config-api');
const apiDir = path.join(fixture, 'api');
let results: [boolean, boolean, boolean] | undefined;
await retry(
async () => {
results = await Promise.all([
runNpmInstall(apiDir, [], undefined, meta),
runNpmInstall(apiDir, [], undefined, meta),
runNpmInstall(fixture, [], undefined, meta),
it('should retry npm install when peer deps invalid and npm@8 on node@16', async () => {
const nodeMajor = Number(process.versions.node.split('.')[0]);
if (nodeMajor !== 16) {
console.log(`Skipping test on node@${nodeMajor}`);
return;
}
const fixture = path.join(__dirname, 'fixtures', '15-npm-8-legacy-peer-deps');
const nodeVersion = { major: nodeMajor } as any;
await runNpmInstall(fixture, [], {}, {}, nodeVersion);
expect(warningMessages).toStrictEqual([
'Warning: Retrying "Install Command" with `--legacy-peer-deps` which may accept a potentially broken dependency and slow install time.',
]);
},
{ maxRetryTime: 3000 }
);
const [run1, run2, run3] = results || [];
expect(run1).toEqual(true);
expect(run2).toEqual(false);
expect(run3).toEqual(false);
expect(
(meta.runNpmInstallSet as Set<string>).has(
path.join(fixture, 'package.json')
)
).toEqual(true);
});

View File

@@ -10,11 +10,9 @@
## Usage
Vercel is a platform for **static sites and frontend frameworks**, built to integrate with your headless content, commerce, or database.
Vercel is the platform for frontend developers, providing the speed and reliability innovators need to create at the moment of inspiration.
We provide a **frictionless developer experience** to take care of the hard things: deploy instantly, scale automatically, and serve personalized content around the globe.
We make it easy for frontend teams to **develop, preview, and ship** delightful user experiences, where performance is the default.
We enable teams to iterate quickly and develop, preview, and ship delightful user experiences. Vercel has zero-configuration support for 35+ frontend frameworks and integrates with your headless content, commerce, or database of choice.
To install the latest version of Vercel CLI, run this command:

View File

@@ -1,6 +1,6 @@
{
"name": "vercel",
"version": "27.3.8",
"version": "28.4.7",
"preferGlobal": true,
"license": "Apache-2.0",
"description": "The command-line interface for Vercel",
@@ -41,16 +41,16 @@
"node": ">= 14"
},
"dependencies": {
"@vercel/build-utils": "5.3.0",
"@vercel/go": "2.0.16",
"@vercel/hydrogen": "0.0.13",
"@vercel/next": "3.1.16",
"@vercel/node": "2.5.7",
"@vercel/python": "3.1.8",
"@vercel/redwood": "1.0.17",
"@vercel/remix": "1.0.18",
"@vercel/ruby": "1.3.24",
"@vercel/static-build": "1.0.17",
"@vercel/build-utils": "5.5.4",
"@vercel/go": "2.2.12",
"@vercel/hydrogen": "0.0.25",
"@vercel/next": "3.2.3",
"@vercel/node": "2.5.22",
"@vercel/python": "3.1.21",
"@vercel/redwood": "1.0.30",
"@vercel/remix": "1.0.31",
"@vercel/ruby": "1.3.38",
"@vercel/static-build": "1.0.30",
"update-notifier": "5.1.0"
},
"devDependencies": {
@@ -85,7 +85,6 @@
"@types/node-fetch": "2.5.10",
"@types/npm-package-arg": "6.1.0",
"@types/pluralize": "0.0.29",
"@types/progress": "2.0.3",
"@types/psl": "1.1.0",
"@types/semver": "6.0.1",
"@types/tar-fs": "1.16.1",
@@ -96,9 +95,9 @@
"@types/which": "1.3.2",
"@types/write-json-file": "2.2.1",
"@types/yauzl-promise": "2.1.0",
"@vercel/client": "12.1.11",
"@vercel/frameworks": "1.1.3",
"@vercel/fs-detectors": "2.0.5",
"@vercel/client": "12.2.12",
"@vercel/frameworks": "1.1.6",
"@vercel/fs-detectors": "3.4.1",
"@vercel/fun": "1.0.4",
"@vercel/ncc": "0.24.0",
"@zeit/source-map-support": "0.6.2",
@@ -118,7 +117,6 @@
"chokidar": "3.3.1",
"codecov": "3.8.2",
"cpy": "7.2.0",
"credit-card": "3.0.1",
"date-fns": "1.29.0",
"debug": "3.1.0",
"dot": "1.1.3",
@@ -154,7 +152,6 @@
"ora": "3.4.0",
"pcre-to-regexp": "1.0.0",
"pluralize": "7.0.0",
"progress": "2.0.3",
"promisepipe": "3.0.0",
"psl": "1.1.31",
"qr-image": "3.2.0",

View File

@@ -4,7 +4,7 @@ const { statSync } = require('fs');
const pkg = require('../package');
function error(command) {
console.error('> Error!', command);
console.error('> Error:', command);
}
function debug(str) {

View File

@@ -37,6 +37,7 @@ const help = () => {
)} Login token
-S, --scope Set a custom scope
-N, --next Show next page of results
-y, --yes Skip the confirmation prompt when removing an alias
${chalk.dim('Examples:')}

View File

@@ -59,7 +59,7 @@ export default async function rm(
const removeStamp = stamp();
if (!opts['--yes'] && !(await confirmAliasRemove(client, alias))) {
output.log('Aborted');
output.log('Canceled');
return 0;
}

View File

@@ -220,7 +220,7 @@ function handleSetupDomainError<T>(
}
if (error instanceof ERRORS.UserAborted) {
output.error(`User aborted`);
output.error(`User canceled.`);
return 1;
}

View File

@@ -1,170 +0,0 @@
import ansiEscapes from 'ansi-escapes';
import chalk from 'chalk';
import ccValidator from 'credit-card';
import textInput from '../../util/input/text';
import cardBrands from '../../util/billing/card-brands';
import success from '../../util/output/success';
import wait from '../../util/output/wait';
import chars from '../../util/output/chars';
import error from '../../util/output/error';
const expDateMiddleware = data => data;
export default async function ({ creditCards, clear = false, contextName }) {
const state = {
error: undefined,
cardGroupLabel: `> ${chalk.bold(
`Enter your card details for ${chalk.bold(contextName)}`
)}`,
name: {
label: 'Full Name'.padEnd(12),
placeholder: 'John Appleseed',
validateValue: data => data.trim().length > 0,
},
cardNumber: {
label: 'Number'.padEnd(12),
mask: 'cc',
placeholder: '#### #### #### ####',
validateKeypress: (data, value) => /\d/.test(data) && value.length < 19,
validateValue: data => {
data = data.replace(/ /g, '');
const type = ccValidator.determineCardType(data);
if (!type) {
return false;
}
return ccValidator.isValidCardNumber(data, type);
},
},
ccv: {
label: 'CCV'.padEnd(12),
mask: 'ccv',
placeholder: '###',
validateValue: data => {
const brand = state.cardNumber.brand.toLowerCase();
return ccValidator.doesCvvMatchType(data, brand);
},
},
expDate: {
label: 'Exp. Date'.padEnd(12),
mask: 'expDate',
placeholder: 'mm / yyyy',
middleware: expDateMiddleware,
validateValue: data => !ccValidator.isExpired(...data.split(' / ')),
},
};
async function render() {
for (const key in state) {
if (!Object.hasOwnProperty.call(state, key)) {
continue;
}
const piece = state[key];
if (typeof piece === 'string') {
console.log(piece);
} else if (typeof piece === 'object') {
let result;
try {
/* eslint-disable no-await-in-loop */
result = await textInput({
label: `- ${piece.label}`,
initialValue: piece.initialValue || piece.value,
placeholder: piece.placeholder,
mask: piece.mask,
validateKeypress: piece.validateKeypress,
validateValue: piece.validateValue,
autoComplete: piece.autoComplete,
});
piece.value = result;
if (key === 'cardNumber') {
let brand = cardBrands[ccValidator.determineCardType(result)];
piece.brand = brand;
if (brand === 'American Express') {
state.ccv.placeholder = '#'.repeat(4);
} else {
state.ccv.placeholder = '#'.repeat(3);
}
brand = chalk.cyan(`[${brand}]`);
const masked = chalk.gray('#### '.repeat(3)) + result.split(' ')[3];
process.stdout.write(
`${chalk.cyan(chars.tick)} ${piece.label}${masked} ${brand}\n`
);
} else if (key === 'ccv') {
process.stdout.write(
`${chalk.cyan(chars.tick)} ${piece.label}${'*'.repeat(
result.length
)}\n`
);
} else if (key === 'expDate') {
let text = result.split(' / ');
text = text[0] + chalk.gray(' / ') + text[1];
process.stdout.write(
`${chalk.cyan(chars.tick)} ${piece.label}${text}\n`
);
} else {
process.stdout.write(
`${chalk.cyan(chars.tick)} ${piece.label}${result}\n`
);
}
} catch (err) {
if (err.message === 'USER_ABORT') {
process.exit(1);
} else {
console.error(error(err));
}
}
}
}
console.log(''); // New line
const stopSpinner = wait(process.stderr, 'Saving card');
try {
const res = await creditCards.add({
name: state.name.value,
cardNumber: state.cardNumber.value,
ccv: state.ccv.value,
expDate: state.expDate.value,
});
stopSpinner();
if (clear) {
const linesToClear = state.error ? 15 : 14;
process.stdout.write(ansiEscapes.eraseLines(linesToClear));
}
console.log(
success(
`${state.cardNumber.brand || state.cardNumber.card.brand} ending in ${
res.last4 || res.card.last4
} was added to ${chalk.bold(contextName)}`
)
);
} catch (err) {
stopSpinner();
const linesToClear = state.error ? 15 : 14;
process.stdout.write(ansiEscapes.eraseLines(linesToClear));
state.error = `${chalk.red('> Error!')} ${
err.message
} Please make sure the info is correct`;
await render();
}
}
try {
await render();
} catch (err) {
console.erorr(err);
}
}

View File

@@ -1,353 +0,0 @@
import chalk from 'chalk';
import ms from 'ms';
import plural from 'pluralize';
import { error } from '../../util/error';
import NowCreditCards from '../../util/credit-cards';
import indent from '../../util/output/indent';
import listInput from '../../util/input/list';
import success from '../../util/output/success';
import promptBool from '../../util/input/prompt-bool';
import info from '../../util/output/info';
import logo from '../../util/output/logo';
import addBilling from './add';
import exit from '../../util/exit';
import getScope from '../../util/get-scope.ts';
import { getPkgName } from '../../util/pkg-name.ts';
import getArgs from '../../util/get-args.ts';
import handleError from '../../util/handle-error.ts';
const help = () => {
console.log(`
${chalk.bold(`${logo} ${getPkgName()} billing`)} [options] <command>
${chalk.dim('Options:')}
ls Show all of your credit cards
add Add a new credit card
rm [id] Remove a credit card
set-default [id] Make a credit card your default one
${chalk.dim('Options:')}
-h, --help Output usage information
-A ${chalk.bold.underline('FILE')}, --local-config=${chalk.bold.underline(
'FILE'
)} Path to the local ${'`vercel.json`'} file
-Q ${chalk.bold.underline('DIR')}, --global-config=${chalk.bold.underline(
'DIR'
)} Path to the global ${'`.vercel`'} directory
-d, --debug Debug mode [off]
-t ${chalk.bold.underline('TOKEN')}, --token=${chalk.bold.underline(
'TOKEN'
)} Login token
-S, --scope Set a custom scope
${chalk.dim('Examples:')}
${chalk.gray('')} Add a new credit card (interactively)
${chalk.cyan(`$ ${getPkgName()} billing add`)}
`);
};
let argv;
let subcommand;
export default async client => {
try {
argv = getArgs(client.argv.slice(2), {});
} catch (error) {
handleError(error);
return 1;
}
argv._ = argv._.slice(1);
subcommand = argv._[0];
if (argv['--help'] || !subcommand) {
help();
return 2;
}
const {
output,
config: { currentTeam },
} = client;
const start = new Date();
const creditCards = new NowCreditCards({
client,
currentTeam,
});
let contextName = null;
try {
({ contextName } = await getScope(client));
} catch (err) {
if (err.code === 'NOT_AUTHORIZED' || err.code === 'TEAM_DELETED') {
output.error(err.message);
return 1;
}
throw err;
}
const args = argv._.slice(1);
switch (subcommand) {
case 'ls':
case 'list': {
let cards;
try {
cards = await creditCards.ls();
} catch (err) {
console.error(error(err.message));
return 1;
}
const text = cards.sources
.map(source => {
const _default =
source.id === cards.defaultSource
? ` ${chalk.bold('(default)')}`
: '';
const id = `${chalk.gray('-')} ${chalk.cyan(
`ID: ${source.id}`
)}${_default}`;
const number = `${chalk.gray('#### ').repeat(3)}${
source.last4 || source.card.last4
}`;
return [
id,
indent(source.name || source.owner.name, 2),
indent(`${source.brand || source.card.brand} ${number}`, 2),
].join('\n');
})
.join('\n\n');
const elapsed = ms(new Date() - start);
console.log(
`> ${plural(
'card',
cards.sources.length,
true
)} found under ${chalk.bold(contextName)} ${chalk.gray(`[${elapsed}]`)}`
);
if (text) {
console.log(`\n${text}\n`);
}
break;
}
case 'set-default': {
if (args.length > 1) {
console.error(error('Invalid number of arguments'));
return 1;
}
const start = new Date();
let cards;
try {
cards = await creditCards.ls();
} catch (err) {
console.error(error(err.message));
return 1;
}
if (cards.sources.length === 0) {
console.error(error('You have no credit cards to choose from'));
return 0;
}
let cardId = args[0];
if (cardId === undefined) {
const elapsed = ms(new Date() - start);
const message = `Selecting a new default payment card for ${chalk.bold(
contextName
)} ${chalk.gray(`[${elapsed}]`)}`;
const choices = buildInquirerChoices(cards);
cardId = await listInput(client, {
message,
choices,
separator: true,
abort: 'end',
});
}
// Check if the provided cardId (in case the user
// typed `vercel billing set-default <some-id>`) is valid
if (cardId) {
const label = `Are you sure that you to set this card as the default?`;
const confirmation = await promptBool(label, {
...client,
trailing: '\n',
});
if (!confirmation) {
console.log(info('Aborted'));
break;
}
const start = new Date();
await creditCards.setDefault(cardId);
const card = cards.sources.find(card => card.id === cardId);
const elapsed = ms(new Date() - start);
console.log(
success(
`${card.brand || card.card.brand} ending in ${
card.last4 || card.card.last4
} is now the default ${chalk.gray(`[${elapsed}]`)}`
)
);
} else {
console.log('No changes made');
}
break;
}
case 'rm':
case 'remove': {
if (args.length > 1) {
console.error(error('Invalid number of arguments'));
return 1;
}
const start = new Date();
let cards;
try {
cards = await creditCards.ls();
} catch (err) {
console.error(error(err.message));
return 1;
}
if (cards.sources.length === 0) {
console.error(
error(
`You have no credit cards to choose from to delete under ${chalk.bold(
contextName
)}`
)
);
return 0;
}
let cardId = args[0];
if (cardId === undefined) {
const elapsed = ms(new Date() - start);
const message = `Selecting a card to ${chalk.underline(
'remove'
)} under ${chalk.bold(contextName)} ${chalk.gray(`[${elapsed}]`)}`;
const choices = buildInquirerChoices(cards);
cardId = await listInput(client, {
message,
choices,
separator: true,
abort: 'start',
});
}
// Shoud check if the provided cardId (in case the user
// typed `vercel billing rm <some-id>`) is valid
if (cardId) {
const label = `Are you sure that you want to remove this card?`;
const confirmation = await promptBool(label, client);
if (!confirmation) {
console.log('Aborted');
break;
}
const start = new Date();
await creditCards.rm(cardId);
const deletedCard = cards.sources.find(card => card.id === cardId);
const remainingCards = cards.sources.filter(card => card.id !== cardId);
let text = `${deletedCard.brand || deletedCard.card.brand} ending in ${
deletedCard.last4 || deletedCard.card.last4
} was deleted`;
// ${chalk.gray(`[${elapsed}]`)}
if (cardId === cards.defaultSource) {
if (remainingCards.length === 0) {
// The user deleted the last card in their account
text += `\n${chalk.yellow('Warning!')} You have no default card`;
} else {
// We can't guess the current default card let's ask the API
const cards = await creditCards.ls();
const newDefaultCard = cards.sources.find(
card => card.id === cards.defaultCardId
);
text += `\n${
newDefaultCard.brand || newDefaultCard.card.brand
} ending in ${
newDefaultCard.last4 || newDefaultCard.card.last4
} in now default for ${chalk.bold(contextName)}`;
}
}
const elapsed = ms(new Date() - start);
text += ` ${chalk.gray(`[${elapsed}]`)}`;
console.log(success(text));
} else {
console.log('No changes made');
}
break;
}
case 'add': {
await addBilling({
creditCards,
contextName,
});
break;
}
default:
console.error(
error('Please specify a valid subcommand: ls | add | rm | set-default')
);
help();
return 1;
}
// This is required, otherwise we get those weird zlib errors
return exit(0);
};
// Builds a `choices` object that can be passesd to inquirer.prompt()
function buildInquirerChoices(cards) {
return cards.sources.map(source => {
const _default =
source.id === cards.defaultSource ? ` ${chalk.bold('(default)')}` : '';
const id = `${chalk.cyan(`ID: ${source.id}`)}${_default}`;
const number = `${chalk.gray('#### ').repeat(3)}${
source.last4 || source.card.last4
}`;
const str = [
id,
indent(source.name || source.owner.name, 2),
indent(`${source.brand || source.card.brand} ${number}`, 2),
].join('\n');
return {
name: str, // Will be displayed by Inquirer
value: source.id, // Will be used to identify the answer
short: source.id, // Will be displayed after the users answers
};
});
}

View File

@@ -2,7 +2,6 @@ import open from 'open';
import boxen from 'boxen';
import execa from 'execa';
import plural from 'pluralize';
import inquirer from 'inquirer';
import { resolve } from 'path';
import chalk, { Chalk } from 'chalk';
import { URLSearchParams, parse } from 'url';
@@ -116,8 +115,6 @@ export default async function main(client: Client): Promise<number> {
}
}
const badDeploymentPromise = getDeployment(client, bad).catch(err => err);
good = normalizeURL(good);
parsed = parse(good);
if (!parsed.hostname) {
@@ -138,8 +135,6 @@ export default async function main(client: Client): Promise<number> {
);
}
const goodDeploymentPromise = getDeployment(client, good).catch(err => err);
if (!subpath) {
subpath = await prompt(
client,
@@ -148,14 +143,15 @@ export default async function main(client: Client): Promise<number> {
}
output.spinner('Retrieving deployments…');
const [badDeployment, goodDeployment] = await Promise.all([
badDeploymentPromise,
goodDeploymentPromise,
]);
// `getDeployment` cannot be parallelized because it might prompt for login
const badDeployment = await getDeployment(client, bad).catch(err => err);
if (badDeployment) {
if (badDeployment instanceof Error) {
badDeployment.message += ` "${bad}"`;
badDeployment.message += ` when requesting bad deployment "${normalizeURL(
bad
)}"`;
output.prettyError(badDeployment);
return 1;
}
@@ -165,11 +161,14 @@ export default async function main(client: Client): Promise<number> {
return 1;
}
const { projectId } = badDeployment;
// `getDeployment` cannot be parallelized because it might prompt for login
const goodDeployment = await getDeployment(client, good).catch(err => err);
if (goodDeployment) {
if (goodDeployment instanceof Error) {
goodDeployment.message += ` "${good}"`;
goodDeployment.message += ` when requesting good deployment "${normalizeURL(
good
)}"`;
output.prettyError(goodDeployment);
return 1;
}
@@ -181,6 +180,8 @@ export default async function main(client: Client): Promise<number> {
return 1;
}
const { projectId } = badDeployment;
if (projectId !== goodDeployment.projectId) {
output.error(`Good and Bad deployments must be from the same Project`);
return 1;
@@ -228,7 +229,8 @@ export default async function main(client: Client): Promise<number> {
// If we have the "good" deployment in this chunk, then we're done
for (let i = 0; i < newDeployments.length; i++) {
if (newDeployments[i].url === good) {
newDeployments = newDeployments.slice(0, i + 1);
// grab all deployments up until the good one
newDeployments = newDeployments.slice(0, i);
next = undefined;
break;
}
@@ -318,7 +320,7 @@ export default async function main(client: Client): Promise<number> {
if (openEnabled) {
await open(testUrl);
}
const answer = await inquirer.prompt({
const answer = await client.prompt({
type: 'expand',
name: 'action',
message: 'Select an action:',

View File

@@ -3,6 +3,7 @@ import chalk from 'chalk';
import dotenv from 'dotenv';
import { join, normalize, relative, resolve } from 'path';
import {
getDiscontinuedNodeVersions,
normalizePath,
Files,
FileFsRef,
@@ -25,6 +26,7 @@ import {
MergeRoutesProps,
Route,
} from '@vercel/routing-utils';
import { fileNameSymbol } from '@vercel/client';
import type { VercelConfig } from '@vercel/client';
import pull from './pull';
@@ -37,6 +39,7 @@ import cliPkg from '../util/pkg';
import readJSONFile from '../util/read-json-file';
import { CantParseJSONFile } from '../util/errors-ts';
import {
pickOverrides,
ProjectLinkAndSettings,
readProjectSettings,
} from '../util/projects/project-settings';
@@ -53,6 +56,7 @@ import { importBuilders } from '../util/build/import-builders';
import { initCorepack, cleanupCorepack } from '../util/build/corepack';
import { sortBuilders } from '../util/build/sort-builders';
import { toEnumerableError } from '../util/error';
import { validateConfig } from '../util/validate-config';
type BuildResult = BuildResultV2 | BuildResultV3;
@@ -91,7 +95,7 @@ const help = () => {
--output [path] Directory where built assets should be written to
--prod Build a production deployment
-d, --debug Debug mode [off]
-y, --yes Skip the confirmation prompt
-y, --yes Skip the confirmation prompt about pulling environment variables and project settings when not found locally
${chalk.dim('Examples:')}
@@ -171,7 +175,7 @@ export default async function main(client: Client): Promise<number> {
);
}
if (!confirmed) {
client.output.print(`Aborted. No Project Settings retrieved.\n`);
client.output.print(`Canceled. No Project Settings retrieved.\n`);
return 0;
}
const { argv: originalArgv } = client;
@@ -231,7 +235,8 @@ export default async function main(client: Client): Promise<number> {
process.env.VERCEL = '1';
process.env.NOW_BUILDER = '1';
return await doBuild(client, project, buildsJson, cwd, outputDir);
await doBuild(client, project, buildsJson, cwd, outputDir);
return 0;
} catch (err: any) {
output.prettyError(err);
@@ -264,31 +269,49 @@ async function doBuild(
buildsJson: BuildsManifest,
cwd: string,
outputDir: string
): Promise<number> {
): Promise<void> {
const { output } = client;
const workPath = join(cwd, project.settings.rootDirectory || '.');
// Load `package.json` and `vercel.json` files
const [pkg, vercelConfig] = await Promise.all([
const [pkg, vercelConfig, nowConfig] = await Promise.all([
readJSONFile<PackageJson>(join(workPath, 'package.json')),
readJSONFile<VercelConfig>(join(workPath, 'vercel.json')).then(
config => config || readJSONFile<VercelConfig>(join(workPath, 'now.json'))
),
readJSONFile<VercelConfig>(join(workPath, 'vercel.json')),
readJSONFile<VercelConfig>(join(workPath, 'now.json')),
]);
if (pkg instanceof CantParseJSONFile) throw pkg;
if (vercelConfig instanceof CantParseJSONFile) throw vercelConfig;
if (nowConfig instanceof CantParseJSONFile) throw nowConfig;
if (vercelConfig) {
vercelConfig[fileNameSymbol] = 'vercel.json';
} else if (nowConfig) {
nowConfig[fileNameSymbol] = 'now.json';
}
const localConfig = vercelConfig || nowConfig || {};
const validateError = validateConfig(localConfig);
if (validateError) {
throw validateError;
}
const projectSettings = {
...project.settings,
...pickOverrides(localConfig),
};
// Get a list of source files
const files = (await getFiles(workPath, client)).map(f =>
normalizePath(relative(workPath, f))
);
const routesResult = getTransformedRoutes(vercelConfig || {});
const routesResult = getTransformedRoutes(localConfig);
if (routesResult.error) {
throw routesResult.error;
}
if (vercelConfig?.builds && vercelConfig.functions) {
if (localConfig.builds && localConfig.functions) {
throw new NowBuildError({
code: 'bad_request',
message:
@@ -297,7 +320,7 @@ async function doBuild(
});
}
let builds = vercelConfig?.builds || [];
let builds = localConfig.builds || [];
let zeroConfigRoutes: Route[] = [];
let isZeroConfig = false;
@@ -312,8 +335,8 @@ async function doBuild(
// Detect the Vercel Builders that will need to be invoked
const detectedBuilders = await detectBuilders(files, pkg, {
...vercelConfig,
projectSettings: project.settings,
...localConfig,
projectSettings,
ignoreBuildScript: true,
featHandleMiss: true,
});
@@ -389,13 +412,10 @@ async function doBuild(
})
);
buildsJson.builds = Array.from(buildsJsonBuilds.values());
const buildsJsonPath = join(outputDir, 'builds.json');
const writeBuildsJsonPromise = fs.writeJSON(buildsJsonPath, buildsJson, {
await fs.writeJSON(join(outputDir, 'builds.json'), buildsJson, {
spaces: 2,
});
ops.push(writeBuildsJsonPromise);
// The `meta` config property is re-used for each Builder
// invocation so that Builders can share state between
// subsequent entrypoint builds.
@@ -425,14 +445,14 @@ async function doBuild(
const buildConfig: Config = isZeroConfig
? {
outputDirectory: project.settings.outputDirectory ?? undefined,
outputDirectory: projectSettings.outputDirectory ?? undefined,
...build.config,
projectSettings: project.settings,
installCommand: project.settings.installCommand ?? undefined,
devCommand: project.settings.devCommand ?? undefined,
buildCommand: project.settings.buildCommand ?? undefined,
framework: project.settings.framework,
nodeVersion: project.settings.nodeVersion,
projectSettings,
installCommand: projectSettings.installCommand ?? undefined,
devCommand: projectSettings.devCommand ?? undefined,
buildCommand: projectSettings.buildCommand ?? undefined,
framework: projectSettings.framework,
nodeVersion: projectSettings.nodeVersion,
}
: build.config || {};
const buildOptions: BuildOptions = {
@@ -448,6 +468,25 @@ async function doBuild(
);
const buildResult = await builder.build(buildOptions);
if (
buildResult &&
'output' in buildResult &&
'runtime' in buildResult.output &&
'type' in buildResult.output &&
buildResult.output.type === 'Lambda'
) {
const lambdaRuntime = buildResult.output.runtime;
if (
getDiscontinuedNodeVersions().some(o => o.runtime === lambdaRuntime)
) {
throw new NowBuildError({
code: 'NODEJS_DISCONTINUED_VERSION',
message: `The Runtime "${build.use}" is using "${lambdaRuntime}", which is discontinued. Please upgrade your Runtime to a more recent version or consult the author for more details.`,
link: 'https://github.com/vercel/vercel/blob/main/DEVELOPING_A_RUNTIME.md#lambdaruntime',
});
}
}
// Store the build result to generate the final `config.json` after
// all builds have completed
buildResults.set(build, buildResult);
@@ -460,7 +499,7 @@ async function doBuild(
build,
builder,
builderPkg,
vercelConfig
localConfig
).then(
override => {
if (override) overrides.push(override);
@@ -469,26 +508,11 @@ async function doBuild(
)
);
} catch (err: any) {
output.prettyError(err);
const writeConfigJsonPromise = fs.writeJSON(
join(outputDir, 'config.json'),
{ version: 3 },
{ spaces: 2 }
);
await Promise.all([writeBuildsJsonPromise, writeConfigJsonPromise]);
const buildJsonBuild = buildsJsonBuilds.get(build);
if (buildJsonBuild) {
buildJsonBuild.error = toEnumerableError(err);
await fs.writeJSON(buildsJsonPath, buildsJson, {
spaces: 2,
});
}
return 1;
throw err;
}
}
@@ -549,7 +573,7 @@ async function doBuild(
builds: builderRoutes,
});
const mergedImages = mergeImages(buildResults.values());
const mergedImages = mergeImages(localConfig.images, buildResults.values());
const mergedWildcard = mergeWildcard(buildResults.values());
const mergedOverrides: Record<string, PathOverride> =
overrides.length > 0 ? Object.assign({}, ...overrides) : undefined;
@@ -575,8 +599,6 @@ async function doBuild(
emoji('success')
)}\n`
);
return 0;
}
function expandBuild(files: string[], build: Builder): Builder[] {
@@ -618,9 +640,9 @@ function expandBuild(files: string[], build: Builder): Builder[] {
}
function mergeImages(
images: BuildResultV2Typical['images'],
buildResults: Iterable<BuildResult>
): BuildResultV2Typical['images'] {
let images: BuildResultV2Typical['images'] = undefined;
for (const result of buildResults) {
if ('images' in result && result.images) {
images = Object.assign({}, images, result.images);

View File

@@ -9,7 +9,6 @@ export const help = () => `
${chalk.dim('Basic')}
billing Manages the account payment methods
deploy [path] Performs a deployment ${chalk.bold(
'(default)'
)}
@@ -73,7 +72,7 @@ export const help = () => `
-S, --scope Set a custom scope
--regions Set default regions to enable the deployment on
--prod Create a production deployment
-c, --confirm Confirm default options and skip questions
-y, --yes Skip questions when setting up new project using default scope and settings
${chalk.dim('Examples:')}

View File

@@ -3,7 +3,11 @@ import fs from 'fs-extra';
import bytes from 'bytes';
import chalk from 'chalk';
import { join, resolve, basename } from 'path';
import { fileNameSymbol, VercelConfig } from '@vercel/client';
import {
fileNameSymbol,
VALID_ARCHIVE_FORMATS,
VercelConfig,
} from '@vercel/client';
import code from '../../util/output/code';
import highlight from '../../util/output/highlight';
import { readLocalConfig } from '../../util/config/files';
@@ -43,9 +47,7 @@ import {
import { SchemaValidationFailed } from '../../util/errors';
import purchaseDomainIfAvailable from '../../util/domains/purchase-domain-if-available';
import confirm from '../../util/input/confirm';
import editProjectSettings, {
PartialProjectSettings,
} from '../../util/input/edit-project-settings';
import editProjectSettings from '../../util/input/edit-project-settings';
import {
getLinkedProject,
linkFolderToProject,
@@ -66,10 +68,12 @@ import { getDeploymentChecks } from '../../util/deploy/get-deployment-checks';
import parseTarget from '../../util/deploy/parse-target';
import getPrebuiltJson from '../../util/deploy/get-prebuilt-json';
import { createGitMeta } from '../../util/create-git-meta';
import { isValidArchive } from '../../util/deploy/validate-archive-format';
import { parseEnv } from '../../util/parse-env';
import { errorToString, isErrnoException, isError } from '../../util/is-error';
import { pickOverrides } from '../../util/projects/project-settings';
export default async (client: Client) => {
export default async (client: Client): Promise<number> => {
const { output } = client;
let argv = null;
@@ -87,20 +91,28 @@ export default async (client: Client) => {
'--regions': String,
'--prebuilt': Boolean,
'--prod': Boolean,
'--confirm': Boolean,
'--archive': String,
'--yes': Boolean,
'-f': '--force',
'-p': '--public',
'-e': '--env',
'-b': '--build-env',
'-m': '--meta',
'-c': '--confirm',
'-y': '--yes',
// deprecated
'--name': String,
'-n': '--name',
'--no-clipboard': Boolean,
'--target': String,
'--confirm': Boolean,
'-c': '--confirm',
});
if ('--confirm' in argv) {
output.warn('`--confirm` is deprecated, please use `--yes` instead');
argv['--yes'] = argv['--confirm'];
}
} catch (error) {
handleError(error);
return 1;
@@ -173,7 +185,7 @@ export default async (client: Client) => {
}
const { path } = pathValidation;
const autoConfirm = argv['--confirm'];
const autoConfirm = argv['--yes'];
// deprecate --name
if (argv['--name']) {
@@ -254,6 +266,12 @@ export default async (client: Client) => {
}
}
const archive = argv['--archive'];
if (typeof archive === 'string' && !isValidArchive(archive)) {
output.error(`Format must be one of: ${VALID_ARCHIVE_FORMATS.join(', ')}`);
return 1;
}
// retrieve `project` and `org` from .vercel
const link = await getLinkedProject(client, path);
@@ -277,7 +295,7 @@ export default async (client: Client) => {
));
if (!shouldStartSetup) {
output.print(`Aborted. Project not set up.\n`);
output.print(`Canceled. Project not set up.\n`);
return 0;
}
@@ -490,14 +508,7 @@ export default async (client: Client) => {
let deployStamp = stamp();
let deployment = null;
const localConfigurationOverrides: PartialProjectSettings = {
buildCommand: localConfig?.buildCommand,
devCommand: localConfig?.devCommand,
framework: localConfig?.framework,
commandForIgnoringBuildStep: localConfig?.ignoreCommand,
installCommand: localConfig?.installCommand,
outputDirectory: localConfig?.outputDirectory,
};
const localConfigurationOverrides = pickOverrides(localConfig);
try {
const createArgs: any = {
@@ -511,7 +522,12 @@ export default async (client: Client) => {
quiet,
wantsPublic: argv['--public'] || localConfig.public,
type: null,
nowConfig: localConfig,
nowConfig: {
...localConfig,
// `images` is allowed in "vercel.json" and processed
// by `vc build`, but don't send it to the API endpoint
images: undefined,
},
regions,
meta,
gitMetadata,
@@ -538,7 +554,8 @@ export default async (client: Client) => {
createArgs,
org,
!project,
path
path,
archive
);
if (deployment.code === 'missing_project_settings') {
@@ -911,4 +928,6 @@ const printDeploymentStatus = async (
) + newline;
output.print(message + link);
}
return 0;
};

View File

@@ -2,11 +2,10 @@ import { resolve, join } from 'path';
import fs from 'fs-extra';
import DevServer from '../../util/dev/server';
import parseListen from '../../util/dev/parse-listen';
import { parseListen } from '../../util/dev/parse-listen';
import { ProjectEnvVariable } from '../../types';
import Client from '../../util/client';
import { getLinkedProject } from '../../util/projects/link';
import { getFrameworks } from '../../util/get-frameworks';
import { ProjectSettings } from '../../types';
import getDecryptedEnvRecords from '../../util/get-decrypted-env-records';
import setupAndLink from '../../util/link/setup-and-link';
@@ -17,7 +16,7 @@ import { OUTPUT_DIR } from '../../util/build/write-build-result';
type Options = {
'--listen': string;
'--confirm': boolean;
'--yes': boolean;
};
export default async function dev(
@@ -31,14 +30,11 @@ export default async function dev(
const listen = parseListen(opts['--listen'] || '3000');
// retrieve dev command
let [link, frameworks] = await Promise.all([
getLinkedProject(client, cwd),
getFrameworks(client),
]);
let link = await getLinkedProject(client, cwd);
if (link.status === 'not_linked' && !process.env.__VERCEL_SKIP_DEV_CMD) {
link = await setupAndLink(client, cwd, {
autoConfirm: opts['--confirm'],
autoConfirm: opts['--yes'],
successEmoji: 'link',
setupMsg: 'Set up and develop',
});
@@ -54,13 +50,12 @@ export default async function dev(
client.output.error(
`Command ${getCommandName(
'dev'
)} requires confirmation. Use option ${param('--confirm')} to confirm.`
)} requires confirmation. Use option ${param('--yes')} to confirm.`
);
}
return link.exitCode;
}
let devCommand: string | undefined;
let projectSettings: ProjectSettings | undefined;
let projectEnvs: ProjectEnvVariable[] = [];
let systemEnvValues: string[] = [];
@@ -70,19 +65,6 @@ export default async function dev(
projectSettings = project;
if (project.devCommand) {
devCommand = project.devCommand;
} else if (project.framework) {
const framework = frameworks.find(f => f.slug === project.framework);
if (framework) {
const defaults = framework.settings.devCommand.value;
if (defaults) {
devCommand = defaults;
}
}
}
if (project.rootDirectory) {
cwd = join(cwd, project.rootDirectory);
}
@@ -95,16 +77,17 @@ export default async function dev(
]);
}
// This is just for tests - can be removed once project settings
// are respected locally in `.vercel/project.json`
if (process.env.VERCEL_DEV_COMMAND) {
devCommand = process.env.VERCEL_DEV_COMMAND;
}
const devServer = new DevServer(cwd, {
output,
projectSettings,
projectEnvs,
systemEnvValues,
});
// If there is no Development Command, we must delete the
// v3 Build Output because it will incorrectly be detected by
// @vercel/static-build in BuildOutputV3.getBuildOutputDirectory()
if (!devCommand) {
if (!devServer.devCommand) {
const outputDir = join(cwd, OUTPUT_DIR);
if (await fs.pathExists(outputDir)) {
output.log(`Removing ${OUTPUT_DIR}`);
@@ -112,13 +95,5 @@ export default async function dev(
}
}
const devServer = new DevServer(cwd, {
output,
devCommand,
projectSettings,
projectEnvs,
systemEnvValues,
});
await devServer.start(...listen);
}

View File

@@ -33,7 +33,7 @@ const help = () => {
-d, --debug Debug mode [off]
-l, --listen [uri] Specify a URI endpoint on which to listen [0.0.0.0:3000]
-t, --token [token] Specify an Authorization Token
--confirm Skip questions and use defaults when setting up a new project
-y, --yes Skip questions when setting up new project using default scope and settings
${chalk.dim('Examples:')}
@@ -74,14 +74,22 @@ export default async function main(client: Client) {
argv = getArgs(client.argv.slice(2), {
'--listen': String,
'-l': '--listen',
'--confirm': Boolean,
'--yes': Boolean,
'-y': '--yes',
// Deprecated
'--port': Number,
'-p': '--port',
'--confirm': Boolean,
'-c': '--confirm',
});
args = getSubcommand(argv._.slice(1), COMMAND_CONFIG).args;
if ('--confirm' in argv) {
output.warn('`--confirm` is deprecated, please use `--yes` instead');
argv['--yes'] = argv['--confirm'];
}
if ('--port' in argv) {
output.warn('`--port` is deprecated, please use `--listen` instead');
argv['--listen'] = String(argv['--port']);

View File

@@ -37,7 +37,7 @@ export default async function add(
const { domain, data: argData } = parsedParams;
const data = await getDNSData(client, argData);
if (!data) {
output.log(`Aborted`);
output.log(`Canceled`);
return 1;
}

View File

@@ -46,7 +46,7 @@ export default async function rm(
);
if (!yes) {
output.error(`User aborted.`);
output.error(`User canceled.`);
return 0;
}

View File

@@ -116,9 +116,7 @@ export default async function buy(
if (buyResult instanceof ERRORS.SourceNotFound) {
output.error(
`Could not purchase domain. Please add a payment method using ${getCommandName(
`billing add`
)}.`
`Could not purchase domain. Please add a payment method using the dashboard.`
);
return 1;
}

View File

@@ -45,6 +45,7 @@ const help = () => {
)} Login token
-S, --scope Set a custom scope
-N, --next Show next page of results
-y, --yes Skip the confirmation prompt when removing a domain
${chalk.dim('Examples:')}
@@ -92,6 +93,7 @@ export default async function main(client: Client) {
'--force': Boolean,
'--next': Number,
'-N': '--next',
'-y': '--yes',
});
} catch (error) {
handleError(error);

View File

@@ -68,7 +68,7 @@ export default async function move(
client
))
) {
output.log('Aborted');
output.log('Canceled');
return 0;
}
}
@@ -87,7 +87,7 @@ export default async function move(
client
))
) {
output.log('Aborted');
output.log('Canceled');
return 0;
}
}

Some files were not shown because too many files have changed in this diff Show More