From dc529d7efa8f8568ea8f71b5cdcf78df89be6c12 Mon Sep 17 00:00:00 2001 From: Dario Piotrowicz Date: Mon, 10 Jul 2023 23:31:55 +0100 Subject: [PATCH] Improve prettier setup (#378) * ignore CHANGELOG files in prettier commands * externalize prettier config * bump prettier --- .changeset/dry-terms-call.md | 5 + .github/version-script.js | 8 +- .prettierignore | 1 + .prettierrc | 6 + .../docs-scraper/scripts/checkDocs.ts | 22 +-- .../scripts/createOrUpdateIssue.ts | 8 +- .../scripts/utils/scrapeConfigs.ts | 24 +-- package-lock.json | 143 ++++++++++++++++-- package.json | 10 +- .../src/rules/no-unsupported-configs.ts | 16 +- packages/next-on-pages/bin/index.js | 4 +- packages/next-on-pages/docs/examples.md | 4 +- .../src/buildApplication/buildApplication.ts | 24 +-- .../buildApplication/buildMetadataFiles.ts | 8 +- .../src/buildApplication/buildSummary.ts | 12 +- .../src/buildApplication/buildVercelOutput.ts | 18 +-- .../src/buildApplication/buildWorkerFile.ts | 12 +- .../buildApplication/fixPrerenderedRoutes.ts | 22 +-- .../buildApplication/generateFunctionsMap.ts | 100 ++++++------ .../src/buildApplication/getVercelConfig.ts | 10 +- .../buildApplication/packageManagerUtils.ts | 6 +- .../buildApplication/processVercelOutput.ts | 24 +-- packages/next-on-pages/src/cli.ts | 14 +- packages/next-on-pages/src/index.ts | 2 +- packages/next-on-pages/src/utils/fs.ts | 2 +- .../next-on-pages/src/utils/getNodeEnv.ts | 2 +- packages/next-on-pages/src/utils/routing.ts | 2 +- .../templates/_worker.js/handleRequest.ts | 8 +- .../templates/_worker.js/index.ts | 6 +- .../templates/_worker.js/routes-matcher.ts | 24 +-- .../templates/_worker.js/utils/http.ts | 4 +- .../templates/_worker.js/utils/images.ts | 10 +- .../templates/_worker.js/utils/matcher.ts | 2 +- .../templates/_worker.js/utils/pcre.ts | 4 +- .../templates/_worker.js/utils/request.ts | 6 +- .../templates/_worker.js/utils/routing.ts | 6 +- .../next-on-pages/tests/_helpers/index.ts | 53 ++++--- .../src/buildApplication/buildSummary.test.ts | 10 +- .../generateFunctionsMap.test.ts | 24 +-- .../buildApplication/generateGlobalJs.test.ts | 12 +- .../packageManagerUtils.test.ts | 10 +- .../processVercelOutput.test.ts | 6 +- .../next-on-pages/tests/src/utils/fs.test.ts | 14 +- .../tests/src/utils/routing.test.ts | 2 +- .../tests/templates/handleRequest.test.ts | 10 +- .../tests/templates/requestTestData/i18n.ts | 4 +- .../requestTestData/trailingSlash.ts | 2 +- .../tests/templates/utils/getNodeEnv.test.ts | 4 +- .../tests/templates/utils/http.test.ts | 2 +- .../tests/templates/utils/images.test.ts | 12 +- .../tests/templates/utils/matcher.test.ts | 2 +- .../tests/templates/utils/pcre.test.ts | 6 +- packages/next-on-pages/vercel.types.d.ts | 2 +- .../setup.ts | 2 +- .../next-12-3-1/styles/Home.module.css | 15 +- .../fixtures/next-12-3-1/styles/globals.css | 14 +- 56 files changed, 467 insertions(+), 318 deletions(-) create mode 100644 .changeset/dry-terms-call.md create mode 100644 .prettierignore create mode 100644 .prettierrc diff --git a/.changeset/dry-terms-call.md b/.changeset/dry-terms-call.md new file mode 100644 index 000000000..c442da771 --- /dev/null +++ b/.changeset/dry-terms-call.md @@ -0,0 +1,5 @@ +--- +'@cloudflare/next-on-pages': patch +--- + +ignore CHANGELOG.md files in prettier commands and fix prettier diff --git a/.github/version-script.js b/.github/version-script.js index 9bce5d251..3fbbba462 100644 --- a/.github/version-script.js +++ b/.github/version-script.js @@ -3,10 +3,10 @@ const { exec } = require('child_process'); try { const nextOnPagesPackage = JSON.parse( - fs.readFileSync('./packages/next-on-pages/package.json') + fs.readFileSync('./packages/next-on-pages/package.json'), ); const eslintPluginPackage = JSON.parse( - fs.readFileSync('./packages/eslint-plugin-next-on-pages/package.json') + fs.readFileSync('./packages/eslint-plugin-next-on-pages/package.json'), ); exec('git rev-parse --short HEAD', (err, stdout) => { @@ -26,11 +26,11 @@ try { fs.writeFileSync( './packages/next-on-pages/package.json', - JSON.stringify(nextOnPagesPackage, null, '\t') + '\n' + JSON.stringify(nextOnPagesPackage, null, '\t') + '\n', ); fs.writeFileSync( './packages/eslint-plugin-next-on-pages/package.json', - JSON.stringify(eslintPluginPackage, null, '\t') + '\n' + JSON.stringify(eslintPluginPackage, null, '\t') + '\n', ); }); } catch (error) { diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..016701f1b --- /dev/null +++ b/.prettierignore @@ -0,0 +1 @@ +**/CHANGELOG.md diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..e9c260d92 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,6 @@ +{ + "printWidth": 80, + "singleQuote": true, + "arrowParens": "avoid", + "semi": true +} diff --git a/internal-packages/docs-scraper/scripts/checkDocs.ts b/internal-packages/docs-scraper/scripts/checkDocs.ts index ebc2219f7..dd476e2b3 100644 --- a/internal-packages/docs-scraper/scripts/checkDocs.ts +++ b/internal-packages/docs-scraper/scripts/checkDocs.ts @@ -11,7 +11,7 @@ void (async function (): Promise { const undocumentedNextConfigs: NextConfig[] = []; allNextConfigs.forEach(config => { const configIsDocumented = nextOnPagesDocumentedNextConfigs.includes( - config.configName + config.configName, ); if (!configIsDocumented) { undocumentedNextConfigs.push(config); @@ -21,7 +21,7 @@ void (async function (): Promise { const documentedNonNextConfigs: string[] = []; nextOnPagesDocumentedNextConfigs.forEach(config => { const configExists = allNextConfigs.find( - nextConfig => nextConfig.configName === config + nextConfig => nextConfig.configName === config, ); if (!configExists) { documentedNonNextConfigs.push(config); @@ -33,13 +33,13 @@ void (async function (): Promise { nextOnPagesDocumentedNextConfigs.length; console.log( - `The number of next configs is ${numOfNextConfigs} the next-on-pages documented next configs are ${numOfNextOnPagesDocumentedNextConfigs}` + `The number of next configs is ${numOfNextConfigs} the next-on-pages documented next configs are ${numOfNextOnPagesDocumentedNextConfigs}`, ); console.log( - `The number of undocumented next configs is ${undocumentedNextConfigs.length}` + `The number of undocumented next configs is ${undocumentedNextConfigs.length}`, ); console.log( - `The number of documented non-next configs is ${documentedNonNextConfigs.length}` + `The number of documented non-next configs is ${documentedNonNextConfigs.length}`, ); if ( @@ -49,13 +49,13 @@ void (async function (): Promise { ) { console.log('\nThe next-on-pages documentation is out of date'); console.log( - `The number of next configs is ${numOfNextConfigs} the next-on-pages documented next configs are ${numOfNextOnPagesDocumentedNextConfigs}` + `The number of next configs is ${numOfNextConfigs} the next-on-pages documented next configs are ${numOfNextOnPagesDocumentedNextConfigs}`, ); console.log('============================================'); console.log('The following configs are undocumented:'); console.log(undocumentedNextConfigs.map(config => config.configName)); console.log( - 'The following configs are documented but do not exist in the nextjs documentation:' + 'The following configs are documented but do not exist in the nextjs documentation:', ); console.log(documentedNonNextConfigs); @@ -63,11 +63,11 @@ void (async function (): Promise { setOutput('result', 'out-of-date'); setOutput( 'undocumented_next_configs', - `${undocumentedNextConfigs.map(config => config.configName).join(',')}` + `${undocumentedNextConfigs.map(config => config.configName).join(',')}`, ); setOutput( 'documented_non_next_configs', - `${documentedNonNextConfigs.join(',')}` + `${documentedNonNextConfigs.join(',')}`, ); } } else { @@ -81,7 +81,7 @@ void (async function (): Promise { const noNextConfigsDetected = allNextConfigs.length === 0; if (noNextConfigsDetected) { console.log( - '\nERROR! No next configs were detected, the next docs might have changed!' + '\nERROR! No next configs were detected, the next docs might have changed!', ); if (fromGithub) { @@ -93,7 +93,7 @@ void (async function (): Promise { nextOnPagesDocumentedNextConfigs.length === 0; if (noNextOnPagesConfigsDetected) { console.log( - '\nERROR! No next-on-pages configs were detected, the docs might have changed!' + '\nERROR! No next-on-pages configs were detected, the docs might have changed!', ); if (fromGithub) { diff --git a/internal-packages/docs-scraper/scripts/createOrUpdateIssue.ts b/internal-packages/docs-scraper/scripts/createOrUpdateIssue.ts index eb639de5e..5b3bc27b0 100644 --- a/internal-packages/docs-scraper/scripts/createOrUpdateIssue.ts +++ b/internal-packages/docs-scraper/scripts/createOrUpdateIssue.ts @@ -44,7 +44,7 @@ void (async function (): Promise { const issueBody = generateIssueBody( undocumentedNextConfigs, - documentedNonNextConfigs + documentedNonNextConfigs, ); if (issues.length === 0) { @@ -71,7 +71,7 @@ void (async function (): Promise { function generateIssueBody( undocumentedNextConfigs: string[], - documentedNonNextConfigs: string[] + documentedNonNextConfigs: string[], ): string { let issueBody = '### The next-on-pages documentation of the next.config.js options is out of date\n'; @@ -79,14 +79,14 @@ function generateIssueBody( if (undocumentedNextConfigs.length > 0) { issueBody += `\n\n${generateMdList( 'The following next.config.js configs are not documented in our supported doc', - undocumentedNextConfigs + undocumentedNextConfigs, )}`; } if (documentedNonNextConfigs.length > 0) { issueBody += `\n\n${generateMdList( 'The following configs present in our supported doc are not present in the next.config.js documentation pages', - documentedNonNextConfigs + documentedNonNextConfigs, )}`; } diff --git a/internal-packages/docs-scraper/scripts/utils/scrapeConfigs.ts b/internal-packages/docs-scraper/scripts/utils/scrapeConfigs.ts index 49f8074fc..8625da3e9 100644 --- a/internal-packages/docs-scraper/scripts/utils/scrapeConfigs.ts +++ b/internal-packages/docs-scraper/scripts/utils/scrapeConfigs.ts @@ -7,7 +7,7 @@ export async function scrapeConfigs(includeNextOnPages?: true): Promise<{ nextOnPagesDocumentedNextConfigs: string[]; }>; export async function scrapeConfigs( - includeNextOnPages: false + includeNextOnPages: false, ): Promise<{ allNextConfigs: NextConfig[] }>; export async function scrapeConfigs(includeNextOnPages = true): Promise<{ allNextConfigs: NextConfig[]; @@ -29,10 +29,10 @@ export async function scrapeConfigs(includeNextOnPages = true): Promise<{ } async function getNextOnPagesDocumentedNextConfigs( - page: Page + page: Page, ): Promise { await page.goto( - 'https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/supported.md' + 'https://github.com/cloudflare/next-on-pages/blob/main/packages/next-on-pages/docs/supported.md', ); const nextOnPagesDocumentedNextConfigs: string[] = await page.$$eval( 'h3:has( > a[href="#nextconfigjs-properties"]) ~ table > tbody > tr > td:first-child', @@ -40,7 +40,7 @@ async function getNextOnPagesDocumentedNextConfigs( els.map(el => { // Note: footnotes leave a number at the end of the text, so we remove it here return el.textContent.replace(/\d*$/, ''); - }) + }), ); return nextOnPagesDocumentedNextConfigs; } @@ -48,18 +48,18 @@ async function getNextOnPagesDocumentedNextConfigs( async function getNextConfigsFromNextDocs(page: Page): Promise { const pagesNextConfigsArray = await extractNextConfigsInfoFromNextDocsPage( page, - 'pages' + 'pages', ); const appNextConfigsArray = await extractNextConfigsInfoFromNextDocsPage( page, - 'app' + 'app', ); const commonNextConfigs = appNextConfigsArray .map(config => ({ app: config, pages: pagesNextConfigsArray.find( - pagesConfig => pagesConfig.configName === config.configName + pagesConfig => pagesConfig.configName === config.configName, ), })) .filter(configs => !!configs.pages) @@ -71,14 +71,14 @@ async function getNextConfigsFromNextDocs(page: Page): Promise { const isCommonConfigName = (configName: string) => !!commonNextConfigs.find( - commonConfig => commonConfig.configName === configName + commonConfig => commonConfig.configName === configName, ); const appSpecificNextConfigs = appNextConfigsArray.filter( - config => !isCommonConfigName(config.configName) + config => !isCommonConfigName(config.configName), ); const pagesSpecificNextConfigs = pagesNextConfigsArray.filter( - config => !isCommonConfigName(config.configName) + config => !isCommonConfigName(config.configName), ); const configs = [ @@ -91,7 +91,7 @@ async function getNextConfigsFromNextDocs(page: Page): Promise { async function extractNextConfigsInfoFromNextDocsPage( page: Page, - type: 'app' | 'pages' + type: 'app' | 'pages', ): Promise { const url = `https://nextjs.org/docs/${type}/api-reference/next-config-js`; @@ -108,7 +108,7 @@ async function extractNextConfigsInfoFromNextDocsPage( }; return { configName, urls: [url] }; }), - type + type, ); return configs; } diff --git a/package-lock.json b/package-lock.json index add006d9c..59b1b0da2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,7 +12,7 @@ ], "devDependencies": { "@cfpreview/pages-e2e-test-runner-cli": "^0.0.18", - "prettier": "^2.8.8", + "prettier": "^3.0.0", "turbo": "^1.10.3" } }, @@ -2001,6 +2001,21 @@ "semver": "^5.4.1" } }, + "node_modules/@changesets/apply-release-plan/node_modules/prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/@changesets/apply-release-plan/node_modules/semver": { "version": "5.7.1", "dev": true, @@ -2463,6 +2478,21 @@ "prettier": "^2.7.1" } }, + "node_modules/@changesets/write/node_modules/prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/@cloudflare/eslint-config-next-on-pages": { "resolved": "internal-packages/eslint-config-next-on-pages", "link": true @@ -14503,14 +14533,15 @@ } }, "node_modules/prettier": { - "version": "2.8.8", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", - "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.0.0.tgz", + "integrity": "sha512-zBf5eHpwHOGPC47h0zrPyNn+eAEIdEzfywMoYn2XPi0P44Zp0tSq64rq0xAREh4auw2cJZHo9QUob+NqCQky4g==", + "dev": true, "bin": { - "prettier": "bin-prettier.js" + "prettier": "bin/prettier.cjs" }, "engines": { - "node": ">=10.13.0" + "node": ">=14" }, "funding": { "url": "https://github.com/prettier/prettier?sponsor=1" @@ -18480,6 +18511,18 @@ "node": ">=8" } }, + "node_modules/vercel/node_modules/jsesc": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.0.2.tgz", + "integrity": "sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==", + "peer": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/vercel/node_modules/jsonfile": { "version": "6.1.0", "license": "MIT", @@ -18491,6 +18534,15 @@ "graceful-fs": "^4.1.6" } }, + "node_modules/vercel/node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "peer": true, + "engines": { + "node": ">=12" + } + }, "node_modules/vercel/node_modules/minimatch": { "version": "9.0.1", "license": "ISC", @@ -18505,6 +18557,21 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/vercel/node_modules/prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "peer": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "node_modules/vercel/node_modules/semver": { "version": "7.3.8", "license": "ISC", @@ -19762,7 +19829,7 @@ } }, "packages/eslint-plugin-next-on-pages": { - "version": "1.2.0", + "version": "1.3.0", "license": "MIT", "dependencies": { "@types/estree-jsx": "^1.0.0", @@ -19801,7 +19868,7 @@ }, "packages/next-on-pages": { "name": "@cloudflare/next-on-pages", - "version": "1.2.0", + "version": "1.3.0", "license": "MIT", "dependencies": { "acorn": "^8.8.0", @@ -19911,6 +19978,21 @@ "node": "^14.15.0 || ^16.10.0 || >=18.0.0" } }, + "packages/next-on-pages/node_modules/prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true, + "bin": { + "prettier": "bin-prettier.js" + }, + "engines": { + "node": ">=10.13.0" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, "packages/next-on-pages/node_modules/pretty-format": { "version": "27.5.1", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", @@ -21270,6 +21352,12 @@ "semver": "^5.4.1" }, "dependencies": { + "prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true + }, "semver": { "version": "5.7.1", "dev": true @@ -21618,6 +21706,14 @@ "fs-extra": "^7.0.1", "human-id": "^1.0.2", "prettier": "^2.7.1" + }, + "dependencies": { + "prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true + } } }, "@cloudflare/eslint-config-next-on-pages": { @@ -21724,6 +21820,12 @@ "integrity": "sha512-ofrBgwpPhCD85kMKtE9RYFFq6OC1A89oW2vvgWZNCwxrUpRUILopY7lsYyMDSjc8g6U6aiO0Qubg6r4Wgt5ZnA==", "dev": true }, + "prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "dev": true + }, "pretty-format": { "version": "27.5.1", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-27.5.1.tgz", @@ -29419,9 +29521,10 @@ "version": "1.2.1" }, "prettier": { - "version": "2.8.8", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", - "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==" + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.0.0.tgz", + "integrity": "sha512-zBf5eHpwHOGPC47h0zrPyNn+eAEIdEzfywMoYn2XPi0P44Zp0tSq64rq0xAREh4auw2cJZHo9QUob+NqCQky4g==", + "dev": true }, "pretty-bytes": { "version": "5.6.0", @@ -31876,6 +31979,12 @@ "version": "4.0.0", "peer": true }, + "jsesc": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.0.2.tgz", + "integrity": "sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==", + "peer": true + }, "jsonfile": { "version": "6.1.0", "peer": true, @@ -31884,6 +31993,12 @@ "universalify": "^2.0.0" } }, + "lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "peer": true + }, "minimatch": { "version": "9.0.1", "peer": true, @@ -31891,6 +32006,12 @@ "brace-expansion": "^2.0.1" } }, + "prettier": { + "version": "2.8.8", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", + "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "peer": true + }, "semver": { "version": "7.3.8", "peer": true, diff --git a/package.json b/package.json index 8d395d7ec..2bd41ea98 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "pages-e2e/features/*" ], "scripts": { - "prettier": "npx prettier --ignore-path .gitignore --ignore-unknown .", + "prettier": "npx prettier --ignore-path .prettierignore --ignore-path .gitignore .", "prettier:check": "npm run prettier -- --check", "prettier:fix": "npm run prettier -- --write", "lint": "FORCE_COLOR=1 turbo lint", @@ -21,13 +21,7 @@ }, "devDependencies": { "@cfpreview/pages-e2e-test-runner-cli": "^0.0.18", - "prettier": "^2.8.8", + "prettier": "^3.0.0", "turbo": "^1.10.3" - }, - "prettier": { - "printWidth": 80, - "singleQuote": true, - "arrowParens": "avoid", - "semi": true } } diff --git a/packages/eslint-plugin-next-on-pages/src/rules/no-unsupported-configs.ts b/packages/eslint-plugin-next-on-pages/src/rules/no-unsupported-configs.ts index 5a959541a..789c5aa5c 100644 --- a/packages/eslint-plugin-next-on-pages/src/rules/no-unsupported-configs.ts +++ b/packages/eslint-plugin-next-on-pages/src/rules/no-unsupported-configs.ts @@ -50,7 +50,7 @@ const configs: Config[] = [ ]; function filterAndExtractConfigs( - support: Config['support'] | Config['support'][] + support: Config['support'] | Config['support'][], ): string[] { const comparisonFn = (config: Config) => Array.isArray(support) @@ -61,7 +61,7 @@ function filterAndExtractConfigs( const supportedConfigs = new Set(filterAndExtractConfigs('✅')); const indefinitelyUnsupportedConfigs = new Set( - filterAndExtractConfigs(['❌', 'N/A']) + filterAndExtractConfigs(['❌', 'N/A']), ); const currentlyUnsupportedConfigs = new Set(filterAndExtractConfigs('🔄')); @@ -73,7 +73,7 @@ const nestedConfigPaths: Readonly> = new Set( ...supportedConfigs, ...indefinitelyUnsupportedConfigs, ...currentlyUnsupportedConfigs, - ].flatMap(extractPaths) + ].flatMap(extractPaths), ); const ruleSchema = { @@ -119,7 +119,7 @@ const rule: Rule.RuleModule = { node.declarations[0].init?.type === 'ObjectExpression' ) { const nextConfigProps = node.declarations[0].init.properties.filter( - p => p.type === 'Property' + p => p.type === 'Property', ) as Property[]; checkConfigPropsRecursively(nextConfigProps, context, options); } @@ -128,7 +128,7 @@ const rule: Rule.RuleModule = { const exportedValue = extractModuleExportValue(node); if (exportedValue?.type === 'ObjectExpression') { const nextConfigProps = exportedValue.properties.filter( - p => p.type === 'Property' + p => p.type === 'Property', ) as Property[]; checkConfigPropsRecursively(nextConfigProps, context, options); } @@ -153,7 +153,7 @@ function checkConfigPropsRecursively( includeCurrentlyUnsupported: boolean; includeUnrecognized: boolean; }, - propPath = '' + propPath = '', ) { nextConfigProps.forEach(prop => { if (prop.type !== 'Property' || prop.key.type !== 'Identifier') return; @@ -165,7 +165,7 @@ function checkConfigPropsRecursively( nestedConfigPaths.has(fullPropName) ) { const props = prop.value.properties.filter( - p => p.type === 'Property' + p => p.type === 'Property', ) as Property[]; checkConfigPropsRecursively(props, context, options, `${fullPropName}/`); return; @@ -247,7 +247,7 @@ function getNodeAfterNextConfigTypeComment(code: SourceCode): Node | null { return parsedComment?.tags.find( ({ tag, type }) => tag === 'type' && - /^import\s*\(\s*(['"])next\1\s*\)\s*\.\s*NextConfig$/.test(type) + /^import\s*\(\s*(['"])next\1\s*\)\s*\.\s*NextConfig$/.test(type), ); }); }) ?? null diff --git a/packages/next-on-pages/bin/index.js b/packages/next-on-pages/bin/index.js index 93a19796c..d862cf886 100755 --- a/packages/next-on-pages/bin/index.js +++ b/packages/next-on-pages/bin/index.js @@ -9,7 +9,7 @@ spawn( join(__dirname, '..', 'dist', 'index.js'), ...process.argv.slice(2), ], - { stdio: 'inherit' } + { stdio: 'inherit' }, ).on('exit', code => - process.exit(code === undefined || code === null ? 0 : code) + process.exit(code === undefined || code === null ? 0 : code), ); diff --git a/packages/next-on-pages/docs/examples.md b/packages/next-on-pages/docs/examples.md index cbe7c8989..32fc125bd 100644 --- a/packages/next-on-pages/docs/examples.md +++ b/packages/next-on-pages/docs/examples.md @@ -89,7 +89,7 @@ export default async function handler(req: NextRequest) { headers: { 'content-type': 'application/json', }, - } + }, ); } ``` @@ -110,7 +110,7 @@ export const getServerSideProps = async () => { props: { runtime: process.env.NEXT_RUNTIME, uuid: await fetch('https://uuid.rocks/plain').then(response => - response.text() + response.text(), ), }, }; diff --git a/packages/next-on-pages/src/buildApplication/buildApplication.ts b/packages/next-on-pages/src/buildApplication/buildApplication.ts index ec95a793c..ba17fd7d0 100644 --- a/packages/next-on-pages/src/buildApplication/buildApplication.ts +++ b/packages/next-on-pages/src/buildApplication/buildApplication.ts @@ -50,7 +50,7 @@ export async function buildApplication({ The Vercel build (\`${await getCurrentPackageExecuter()} vercel build\`) command failed. For more details see the Vercel logs above. If you need help solving the issue, refer to the Vercel or Next.js documentation or their repositories. `, - { spaced: true } + { spaced: true }, ); buildSuccess = false; } @@ -73,7 +73,7 @@ async function prepareAndBuildWorker( { disableChunksDedup, disableWorkerMinification, - }: Pick + }: Pick, ): Promise { let vercelConfig: VercelConfig; try { @@ -94,18 +94,18 @@ async function prepareAndBuildWorker( const functionsDir = resolve('.vercel', 'output', 'functions'); if (!(await validateDir(functionsDir))) { cliLog( - 'No functions detected (no functions directory generated by Vercel).' + 'No functions detected (no functions directory generated by Vercel).', ); } else { generatedFunctionsMaps = await generateFunctionsMap( functionsDir, outputDir, - disableChunksDedup + disableChunksDedup, ); if (generatedFunctionsMaps.invalidFunctions.size > 0) { await printInvalidFunctionsErrorMessage( - Array.from(generatedFunctionsMaps.invalidFunctions) + Array.from(generatedFunctionsMaps.invalidFunctions), ); exit(1); } @@ -119,30 +119,30 @@ async function prepareAndBuildWorker( vercelConfig, staticAssets, generatedFunctionsMaps?.prerenderedRoutes, - generatedFunctionsMaps?.functionsMap + generatedFunctionsMaps?.functionsMap, ); printBuildSummary( staticAssets, processedVercelOutput, - generatedFunctionsMaps + generatedFunctionsMaps, ); await writeBuildInfo( join(outputDir, '_worker.js'), staticAssets, processedVercelOutput, - generatedFunctionsMaps + generatedFunctionsMaps, ); await buildWorkerFile( processedVercelOutput, outputDir, - !disableWorkerMinification + !disableWorkerMinification, ); } async function printInvalidFunctionsErrorMessage( - invalidFunctions: string[] + invalidFunctions: string[], ): Promise { const nextVersion = coerce(await getPackageVersion('next')); @@ -158,7 +158,7 @@ async function printInvalidFunctionsErrorMessage( }; const invalidRoutes = Array.from( - new Set(invalidFunctions.map(fn => fn.replace(/(\.rsc)?\.func$/, ''))) + new Set(invalidFunctions.map(fn => fn.replace(/(\.rsc)?\.func$/, ''))), ); cliError( @@ -175,6 +175,6 @@ async function printInvalidFunctionsErrorMessage( You can read more about the Edge Runtime on the Next.js documentation: https://nextjs.org/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes `, - { spaced: true } + { spaced: true }, ); } diff --git a/packages/next-on-pages/src/buildApplication/buildMetadataFiles.ts b/packages/next-on-pages/src/buildApplication/buildMetadataFiles.ts index b1dff7ec0..ac4ad3cfd 100644 --- a/packages/next-on-pages/src/buildApplication/buildMetadataFiles.ts +++ b/packages/next-on-pages/src/buildApplication/buildMetadataFiles.ts @@ -18,8 +18,8 @@ async function buildNextStaticHeaders(outputDir: string) { const hitRoutes = getPhaseRoutes(vercelConfig.routes ?? [], 'hit'); - const nextStaticRoute = hitRoutes.find(route => - route.src?.startsWith('/_next/static/') + const nextStaticRoute = hitRoutes.find( + route => route.src?.startsWith('/_next/static/'), ); const nextStaticHeaders = (nextStaticRoute as VercelSource)?.headers; @@ -36,7 +36,7 @@ ${Object.entries(nextStaticHeaders) { // in case someone configured redirects already, append to the end flag: 'a', - } + }, ); } } @@ -51,7 +51,7 @@ async function buildRoutes(outputDir: string) { include: ['/*'], exclude: ['/_next/static/*'], }), - { flag: 'ax' } // don't generate file if it's already manually maintained + { flag: 'ax' }, // don't generate file if it's already manually maintained ); } catch (e) { if ((e as { code?: string }).code !== 'EEXIST') { diff --git a/packages/next-on-pages/src/buildApplication/buildSummary.ts b/packages/next-on-pages/src/buildApplication/buildSummary.ts index 82e9edce6..ad3fe2c98 100644 --- a/packages/next-on-pages/src/buildApplication/buildSummary.ts +++ b/packages/next-on-pages/src/buildApplication/buildSummary.ts @@ -19,7 +19,7 @@ export function printBuildSummary( functionsMap = new Map(), prerenderedRoutes = new Map(), wasmIdentifiers = new Map(), - }: Partial = {} + }: Partial = {}, ): void { const middlewareFunctions = [...vercelOutput.entries()] .filter(([, { type }]) => type === 'middleware') @@ -27,8 +27,8 @@ export function printBuildSummary( .sort((a, b) => a.localeCompare(b)); const routeFunctions = new Set( processItemsMap(functionsMap).filter( - path => !middlewareFunctions.includes(path.replace(/^\//, '')) - ) + path => !middlewareFunctions.includes(path.replace(/^\//, '')), + ), ); const prerendered = processItemsMap(prerenderedRoutes); const otherStatic = staticAssets @@ -73,7 +73,7 @@ export async function writeBuildInfo( functionsMap = new Map(), prerenderedRoutes = new Map(), wasmIdentifiers = new Map(), - }: Partial = {} + }: Partial = {}, ): Promise { const currentDir = resolve(); const buildLogFilePath = join(outputDir, 'nop-build-log.json'); @@ -83,7 +83,7 @@ export async function writeBuildInfo( ({ originalFileLocation, ...rest }) => ({ ...rest, originalFileLocation: relative(currentDir, originalFileLocation), - }) + }), ); const buildLogObject: BuildLog = { @@ -174,7 +174,7 @@ function constructSummarySections( name: string; rawItems: string[]; limit?: number; - }[] + }[], ): string { return sections .map(({ name, rawItems, limit }) => { diff --git a/packages/next-on-pages/src/buildApplication/buildVercelOutput.ts b/packages/next-on-pages/src/buildApplication/buildVercelOutput.ts index c511fa609..c51816a60 100644 --- a/packages/next-on-pages/src/buildApplication/buildVercelOutput.ts +++ b/packages/next-on-pages/src/buildApplication/buildVercelOutput.ts @@ -42,7 +42,7 @@ async function generateProjectJsonFileIfNeeded(): Promise { await mkdir('.vercel', { recursive: true }); await writeFile( projectJsonFilePath, - JSON.stringify({ projectId: '_', orgId: '_', settings: {} }) + JSON.stringify({ projectId: '_', orgId: '_', settings: {} }), ); } } @@ -52,19 +52,19 @@ async function runVercelBuild(pkgMng: PackageManager): Promise { if (pkgMng === 'yarn (classic)') { cliLog( - `Installing vercel as dev dependencies with 'yarn add vercel -D'...` + `Installing vercel as dev dependencies with 'yarn add vercel -D'...`, ); const installVercel = spawn(pkgMngCMD, ['add', 'vercel', '-D']); installVercel.stdout.on('data', data => - cliLog(`\n${data}`, { fromVercelCli: true }) + cliLog(`\n${data}`, { fromVercelCli: true }), ); installVercel.stderr.on('data', data => // here we use cliLog instead of cliError because the Vercel cli // currently displays non-error messages in stderr // so we just display all Vercel logs as standard logs - cliLog(`\n${data}`, { fromVercelCli: true }) + cliLog(`\n${data}`, { fromVercelCli: true }), ); await new Promise((resolve, reject) => { @@ -85,13 +85,13 @@ async function runVercelBuild(pkgMng: PackageManager): Promise { const vercelBuild = await getVercelBuildChildProcess(pkgMng); vercelBuild.stdout.on('data', data => - cliLog(`\n${data}`, { fromVercelCli: true }) + cliLog(`\n${data}`, { fromVercelCli: true }), ); vercelBuild.stderr.on('data', data => // here we use cliLog instead of cliError because the Vercel cli // currently displays non-error messages in stderr // so we just display all Vercel logs as standard logs - cliLog(`\n${data}`, { fromVercelCli: true }) + cliLog(`\n${data}`, { fromVercelCli: true }), ); await new Promise((resolve, reject) => { @@ -106,7 +106,7 @@ async function runVercelBuild(pkgMng: PackageManager): Promise { } async function getVercelBuildChildProcess( - pkgMng: PackageManager + pkgMng: PackageManager, ): Promise { const pkgMngCMD = getPackageManagerSpawnCommand(pkgMng); const isYarnBerry = pkgMng === 'yarn (berry)'; @@ -122,7 +122,7 @@ async function getVercelBuildChildProcess( } async function isVercelPackageInstalled( - pkgMng: PackageManager + pkgMng: PackageManager, ): Promise { const packageVersion = await getPackageVersion('vercel', pkgMng); return !!packageVersion; @@ -136,7 +136,7 @@ async function isVercelPackageInstalled( * We do not need these files, nor do we want to run the risk of them being available. Therefore, we should delete them instead of uploading them to Cloudflare Pages. */ export async function deleteNextTelemetryFiles( - outputDir: string + outputDir: string, ): Promise { const nextDir = resolve(outputDir, '_next'); const privateDir = join(nextDir, '__private'); diff --git a/packages/next-on-pages/src/buildApplication/buildWorkerFile.ts b/packages/next-on-pages/src/buildApplication/buildWorkerFile.ts index 4987869e4..55b740272 100644 --- a/packages/next-on-pages/src/buildApplication/buildWorkerFile.ts +++ b/packages/next-on-pages/src/buildApplication/buildWorkerFile.ts @@ -16,7 +16,7 @@ import { getNodeEnv } from '../utils/getNodeEnv'; */ export function constructBuildOutputRecord( item: BuildOutputItem, - outputDir: string + outputDir: string, ) { if (item.type === 'static') { return `{ type: ${JSON.stringify(item.type)} }`; @@ -36,7 +36,7 @@ export function constructBuildOutputRecord( .replace(outputDir, '') .replace( /^\/_worker\.js\/__next-on-pages-dist__\//, - './__next-on-pages-dist__/' + './__next-on-pages-dist__/', )}' }`; } @@ -44,11 +44,11 @@ export function constructBuildOutputRecord( export async function buildWorkerFile( { vercelConfig, vercelOutput }: ProcessedVercelOutput, outputDir: string, - minify: boolean + minify: boolean, ) { const functionsFile = join( tmpdir(), - `functions-${Math.random().toString(36).slice(2)}.js` + `functions-${Math.random().toString(36).slice(2)}.js`, ); await writeFile( @@ -56,9 +56,9 @@ export async function buildWorkerFile( `export const __BUILD_OUTPUT__ = {${[...vercelOutput.entries()] .map( ([name, item]) => - `"${name}": ${constructBuildOutputRecord(item, outputDir)}` + `"${name}": ${constructBuildOutputRecord(item, outputDir)}`, ) - .join(',')}};` + .join(',')}};`, ); const outputFile = join(outputDir, '_worker.js', 'index.js'); diff --git a/packages/next-on-pages/src/buildApplication/fixPrerenderedRoutes.ts b/packages/next-on-pages/src/buildApplication/fixPrerenderedRoutes.ts index 5201db747..5c2baf3e1 100644 --- a/packages/next-on-pages/src/buildApplication/fixPrerenderedRoutes.ts +++ b/packages/next-on-pages/src/buildApplication/fixPrerenderedRoutes.ts @@ -32,7 +32,7 @@ export type PrerenderedFileData = { async function getRouteConfig( baseDir: string, file: string, - dirName: string + dirName: string, ): Promise { const configPath = join(baseDir, file); const config = await readJsonFile(configPath); @@ -61,7 +61,7 @@ async function getRouteConfig( async function getRoutePath( { fallback }: VercelPrerenderConfig, dirName: string, - outputDir: string + outputDir: string, ): Promise { const prerenderRoute = normalizePath(join(dirName, fallback.fsPath)); const prerenderFile = join(outputDir, 'functions', prerenderRoute); @@ -94,16 +94,16 @@ async function getRoutePath( async function getRouteDest( { fallback }: VercelPrerenderConfig, dirName: string, - outputDir: string + outputDir: string, ): Promise<{ destFile: string; destRoute: string }> { const destRoute = normalizePath( join( dirName, fallback.fsPath.replace( /\.prerender-fallback(?:\.(?:rsc|body|json))?/gi, - '' - ) - ) + '', + ), + ), ); const destFile = join(outputDir, destRoute); @@ -128,7 +128,7 @@ async function validateRoute( baseDir: string, file: string, vercelDir: string, - outputDir: string + outputDir: string, ) { const dirName = relative(join(vercelDir, 'functions'), baseDir); const config = await getRouteConfig(baseDir, file, dirName); @@ -160,8 +160,8 @@ function getRouteOverrides(newRoute: string): string[] { const strippedIndexRoute = stripIndexRoute(withoutHtmlExt); const overrides = new Set( [formattedPathName, withoutHtmlExt, strippedIndexRoute].filter( - route => route !== `/${newRoute}` - ) + route => route !== `/${newRoute}`, + ), ); return [...overrides]; @@ -184,11 +184,11 @@ export async function fixPrerenderedRoutes( prerenderedRoutes: Map, files: string[], baseDir: string, - outputDir: string + outputDir: string, ): Promise { const vercelDir = resolve('.vercel', 'output'); const configs = files.filter(file => - /.+\.prerender-config\.json$/gi.test(file) + /.+\.prerender-config\.json$/gi.test(file), ); const validRoutePaths = new Set(); diff --git a/packages/next-on-pages/src/buildApplication/generateFunctionsMap.ts b/packages/next-on-pages/src/buildApplication/generateFunctionsMap.ts index 692e9dd47..dbd74b346 100644 --- a/packages/next-on-pages/src/buildApplication/generateFunctionsMap.ts +++ b/packages/next-on-pages/src/buildApplication/generateFunctionsMap.ts @@ -34,12 +34,12 @@ import { build } from 'esbuild'; export async function generateFunctionsMap( functionsDir: string, outputDir: string, - disableChunksDedup: CliOptions['disableChunksDedup'] + disableChunksDedup: CliOptions['disableChunksDedup'], ): Promise { const nextOnPagesDistDir = join( outputDir, '_worker.js', - '__next-on-pages-dist__' + '__next-on-pages-dist__', ); const processingSetup: ProcessingSetup = { @@ -54,18 +54,18 @@ export async function generateFunctionsMap( if (!disableChunksDedup) { const chunksConsumersInfos = await collectChunksConsumersInfoRecursively( processingSetup, - functionsDir + functionsDir, ); processingSetup.chunksToDedup = new Set( Array.from(chunksConsumersInfos.entries()) .filter(([, chunkConsumers]) => chunkConsumers.size > 1) - .map(([chunkNumber]) => chunkNumber) + .map(([chunkNumber]) => chunkNumber), ); } const processingResults = await processDirectoryRecursively( processingSetup, - functionsDir + functionsDir, ); await tryToFixInvalidFunctions(processingResults); @@ -74,7 +74,7 @@ export async function generateFunctionsMap( await buildWebpackChunkFiles( processingResults.webpackChunks, processingSetup.distWebpackDir, - processingResults.wasmIdentifiers + processingResults.wasmIdentifiers, ); } @@ -85,7 +85,7 @@ export async function generateFunctionsMap( if (processingResults.nextJsManifests.size) { await createNextJsManifestFiles( nextOnPagesDistDir, - processingResults.nextJsManifests + processingResults.nextJsManifests, ); } @@ -147,7 +147,7 @@ type WasmModuleInfo = { async function processDirectoryRecursively( setup: ProcessingSetup, - dir: string + dir: string, ): Promise { const invalidFunctions = new Set(); const functionsMap = new Map(); @@ -161,7 +161,7 @@ async function processDirectoryRecursively( prerenderedRoutes, files, dir, - setup.outputDir + setup.outputDir, ); // Note: the following could be implemented via `await Promise.all` since different directories are independent to each other @@ -176,19 +176,19 @@ async function processDirectoryRecursively( const dirResults = await dirResultsPromise; dirResults.invalidFunctions?.forEach(fn => invalidFunctions.add(fn)); dirResults.functionsMap?.forEach((value, key) => - functionsMap.set(key, value) + functionsMap.set(key, value), ); dirResults.webpackChunks?.forEach((value, key) => - webpackChunks.set(key, value) + webpackChunks.set(key, value), ); dirResults.prerenderedRoutes?.forEach((value, key) => - prerenderedRoutes.set(key, value) + prerenderedRoutes.set(key, value), ); dirResults.wasmIdentifiers?.forEach((value, key) => - wasmIdentifiers.set(key, value) + wasmIdentifiers.set(key, value), ); dirResults.nextJsManifests?.forEach((value, key) => - nextJsManifests.set(key, value) + nextJsManifests.set(key, value), ); } } @@ -216,12 +216,12 @@ type FunctionConfig = { async function processFuncDirectory( setup: ProcessingSetup, - filepath: string + filepath: string, ): Promise> { const relativePath = relative(setup.functionsDir, filepath); const functionConfig = await readJsonFile( - join(filepath, '.vc-config.json') + join(filepath, '.vc-config.json'), ); if (functionConfig?.runtime !== 'edge') { @@ -245,7 +245,7 @@ async function processFuncDirectory( // We sometimes encounter an uncompiled `middleware.js` with no compiled `index.js` outside of a base path. // Outside the base path, it should not be utilised, so it should be safe to ignore the function. cliWarn( - `Detected an invalid middleware function for ${relativePath}. Skipping...` + `Detected an invalid middleware function for ${relativePath}. Skipping...`, ); return {}; } @@ -269,24 +269,24 @@ async function processFuncDirectory( contents, functionFilePath, webpackChunks, - setup.chunksToDedup + setup.chunksToDedup, ); extractedWebpackChunks.forEach((value, key) => - webpackChunks.set(key, value) + webpackChunks.set(key, value), ); contents = updatedFunctionContents; } const manifestExtractionResult = await extractNextJsManifests( functionFilePath, - contents + contents, ); contents = manifestExtractionResult.updatedContents; const nextJsManifests = manifestExtractionResult.manifests; const wasmExtractionResult = await extractAndFixWasmRequires( functionFilePath, - contents + contents, ); contents = wasmExtractionResult.updatedContents; wasmIdentifiers = wasmExtractionResult.wasmIdentifiers; @@ -343,7 +343,7 @@ type RawWasmModuleInfo = { */ async function extractAndFixWasmRequires( functionFilePath: string, - originalFileContents: string + originalFileContents: string, ): Promise<{ wasmIdentifiers: Map; updatedContents: string; @@ -367,15 +367,15 @@ async function extractAndFixWasmRequires( originalFileLocation: join( dirname(functionFilePath), 'wasm', - `${identifier}.wasm` + `${identifier}.wasm`, ), }); const originalWasmModuleRequire = originalFileContents.slice(start, end); updatedContents = updatedContents.replace( originalWasmModuleRequire, `import ${identifier} from "${'../'.repeat( - getFunctionNestingLevel(functionFilePath) - 1 - )}wasm/${identifier}.wasm";` + getFunctionNestingLevel(functionFilePath) - 1, + )}wasm/${identifier}.wasm";`, ); }); @@ -394,7 +394,7 @@ async function extractAndFixWasmRequires( */ async function extractNextJsManifests( functionFilePath: string, - originalFileContents: string + originalFileContents: string, ): Promise<{ manifests: Map; updatedContents: string; @@ -414,11 +414,11 @@ async function extractNextJsManifests( manifestStatementInfos.forEach(({ manifestIdentifier, start, end }) => { const originalManifestCode = originalFileContents.slice(start, end); updatedContents = `${`import ${manifestIdentifier} from "${'../'.repeat( - getFunctionNestingLevel(functionFilePath) - 1 + getFunctionNestingLevel(functionFilePath) - 1, )}../__next-on-pages-dist__/nextjs-manifests/${manifestIdentifier}.js";`}${updatedContents}`; updatedContents = updatedContents.replace( originalManifestCode, - `self.${manifestIdentifier}=${manifestIdentifier};` + `self.${manifestIdentifier}=${manifestIdentifier};`, ); const manifestContent = originalManifestCode .slice(`self.${manifestIdentifier}=`.length) @@ -444,7 +444,7 @@ type ManifestStatementInfo = { * @returns information about the manifest statement if it follows the required format, null otherwise */ function extractManifestStatementInfo( - statement: AST.StatementKind + statement: AST.StatementKind, ): ManifestStatementInfo | null { if ( statement.type !== 'ExpressionStatement' || @@ -488,7 +488,7 @@ function fixFunctionContents(contents: string) { // TODO: This hack is not good. We should replace this with something less brittle ASAP // https://github.com/vercel/next.js/blob/2e7dfca362931be99e34eccec36074ab4a46ffba/packages/next/src/server/web/adapter.ts#L276-L282 /(Object.defineProperty\(globalThis,\s*"__import_unsupported",\s*{[\s\S]*?configurable:\s*)([^,}]*)(.*}\s*\))/gm, - '$1true$3' + '$1true$3', ); // TODO: Investigate alternatives or a real fix. This hack is rather brittle. @@ -497,7 +497,7 @@ function fixFunctionContents(contents: string) { // https://github.com/vercel/next.js/blob/canary/packages/next/src/compiled/react/cjs/react.shared-subset.development.js#L198 contents = contents.replace( /(?:(JSON\.stringify\(\[\w+\.method\S+,)\w+\.mode(,\S+,)\w+\.credentials(,\S+,)\w+\.integrity(\]\)))/gm, - '$1null$2null$3null$4' + '$1null$2null$3null$4', ); return contents; } @@ -517,7 +517,7 @@ async function extractWebpackChunks( originalFunctionContents: string, filePath: string, existingWebpackChunks: Map = new Map(), - chunksToExtract?: Set + chunksToExtract?: Set, ): Promise<{ updatedFunctionContents: string; extractedWebpackChunks: Map; @@ -548,7 +548,7 @@ async function extractWebpackChunks( const chunkExpressionCode = functionContents.slice( (chunk.value as Node).start, - (chunk.value as Node).end + (chunk.value as Node).end, ); if ( @@ -560,7 +560,7 @@ async function extractWebpackChunks( ERROR: Detected a collision with the webpack chunks deduplication. Try adding the '--disable-chunks-dedup' argument to temporarily solve the issue. `, - { spaced: true, showReport: true } + { spaced: true, showReport: true }, ); exit(1); } @@ -571,7 +571,7 @@ async function extractWebpackChunks( webpackChunksCodeReplaceMap.set( chunkExpressionCode, - getChunkIdentifier(key) + getChunkIdentifier(key), ); }); @@ -581,7 +581,7 @@ async function extractWebpackChunks( return { updatedFunctionContents: [...webpackChunksImports, functionContents].join( - ';\n' + ';\n', ), extractedWebpackChunks: webpackChunks, }; @@ -590,7 +590,7 @@ async function extractWebpackChunks( async function buildWebpackChunkFiles( webpackChunks: Map, tmpWebpackDir: string, - wasmIdentifiers: Map + wasmIdentifiers: Map, ) { for (const [chunkIdentifier, code] of webpackChunks) { const chunkFilePath = join(tmpWebpackDir, `${chunkIdentifier}.js`); @@ -612,7 +612,7 @@ async function buildWebpackChunkFiles( .filter(([identifier]) => fileContents.includes(identifier)) .map( ([identifier, { importPath }]) => - `import ${identifier} from '..${importPath}';` + `import ${identifier} from '..${importPath}';`, ) .join('\n'); await writeFile(chunkFilePath, `${wasmChunkImports}\n${fileContents}`); @@ -657,7 +657,7 @@ export type DirectoryProcessingResults = { * @returns the chunks as an array of AST Properties if the statement represent the target javascript code, an empty array otherwise */ function getWebpackChunksFromStatement( - statement: AST.StatementKind + statement: AST.StatementKind, ): AST.PropertyKind[] { if ( statement.type !== 'ExpressionStatement' || @@ -682,7 +682,7 @@ function getWebpackChunksFromStatement( p.type === 'Property' && p.key.type === 'Literal' && typeof p.key.value === 'number' && - p.value.type === 'ArrowFunctionExpression' + p.value.type === 'ArrowFunctionExpression', ) as AST.PropertyKind[]; } @@ -699,7 +699,7 @@ function getWebpackChunksFromStatement( * import wasm_fbeb8adedbc833032bda6f13925ba235b8d09114 from "../wasm/wasm_fbeb8adedbc833032bda6f13925ba235b8d09114.wasm"; */ function getWasmIdentifier( - statement: AST.StatementKind + statement: AST.StatementKind, ): RawWasmModuleInfo | null { if ( statement.type !== 'VariableDeclaration' || @@ -751,7 +751,7 @@ function getRelativeNextOnPagesDistPath(functionPath: string): string { function getChunkImportFn(functionPath: string): (chunkKey: number) => string { const relativeChunksPath = `${getRelativeNextOnPagesDistPath( - functionPath + functionPath, )}/chunks`; return chunkKey => { const chunkIdentifier = getChunkIdentifier(chunkKey); @@ -773,7 +773,7 @@ function getFunctionNestingLevel(functionPath: string): number { if (nestingLevel < 0) { throw new Error( - `Error: could not determine nesting level of the following function: ${functionPath}` + `Error: could not determine nesting level of the following function: ${functionPath}`, ); } @@ -806,7 +806,7 @@ export const nodeBuiltInModulesPlugin: Plugin = { contents: `export * from '${path}'`, loader: 'js', }; - } + }, ); }, }; @@ -820,7 +820,7 @@ export const nodeBuiltInModulesPlugin: Plugin = { */ async function copyWasmFiles( distDir: string, - wasmIdentifiers: Map + wasmIdentifiers: Map, ): Promise { const wasmDistDir = join(distDir, 'wasm'); await mkdir(wasmDistDir); @@ -839,7 +839,7 @@ async function copyWasmFiles( */ async function createNextJsManifestFiles( distDir: string, - manifests: Map + manifests: Map, ): Promise { const manifestsDistDir = join(distDir, 'nextjs-manifests'); await mkdir(manifestsDistDir); @@ -858,7 +858,7 @@ type ChunkConsumers = Set; async function collectChunksConsumersInfoRecursively( setup: ProcessingSetup, - dir: string + dir: string, ): Promise { const chunksConsumersInfos: ChunksConsumersInfo = new Map(); @@ -894,12 +894,12 @@ async function collectChunksConsumersInfoRecursively( } async function collectChunksConsumersInfosFromFuncDirectory( - filepath: string + filepath: string, ): Promise { const chunksConsumersInfos: ChunksConsumersInfo = new Map(); const functionConfig = await readJsonFile( - join(filepath, '.vc-config.json') + join(filepath, '.vc-config.json'), ); if (functionConfig?.runtime !== 'edge') { @@ -913,7 +913,7 @@ async function collectChunksConsumersInfosFromFuncDirectory( const { extractedWebpackChunks } = await extractWebpackChunks( contents, - functionFilePath + functionFilePath, ); extractedWebpackChunks.forEach((_, number) => { diff --git a/packages/next-on-pages/src/buildApplication/getVercelConfig.ts b/packages/next-on-pages/src/buildApplication/getVercelConfig.ts index 0726b381d..53b4bf052 100644 --- a/packages/next-on-pages/src/buildApplication/getVercelConfig.ts +++ b/packages/next-on-pages/src/buildApplication/getVercelConfig.ts @@ -21,7 +21,7 @@ export async function getVercelConfig(): Promise { if (config.version !== supportedConfigVersion) { throw new Error( - `Unknown '${configPath}' version. Expected ${supportedConfigVersion} but found ${config.version}.` + `Unknown '${configPath}' version. Expected ${supportedConfigVersion} but found ${config.version}.`, ); } @@ -37,7 +37,7 @@ export async function getVercelConfig(): Promise { */ export function getPhaseRoutes( routes: VercelRoute[], - phase: VercelPhase + phase: VercelPhase, ): VercelRoute[] { if (!routes.length) { return []; @@ -54,20 +54,20 @@ function getPhaseStart(routes: VercelRoute[], phase: VercelPhase): number { } const index = routes.findIndex( - route => isVercelHandler(route) && route.handle === phase + route => isVercelHandler(route) && route.handle === phase, ); return index === -1 ? routes.length : index + 1; } function getPhaseEnd(routes: VercelRoute[], phaseStart: number): number { const index = routes.findIndex( - (route, i) => i >= phaseStart && isVercelHandler(route) + (route, i) => i >= phaseStart && isVercelHandler(route), ); return index === -1 ? routes.length : index; } export function processVercelConfig( - config: VercelConfig + config: VercelConfig, ): ProcessedVercelConfig { const processedConfig: ProcessedVercelConfig = { ...config, diff --git a/packages/next-on-pages/src/buildApplication/packageManagerUtils.ts b/packages/next-on-pages/src/buildApplication/packageManagerUtils.ts index 774ed711e..15db4d6e4 100644 --- a/packages/next-on-pages/src/buildApplication/packageManagerUtils.ts +++ b/packages/next-on-pages/src/buildApplication/packageManagerUtils.ts @@ -81,7 +81,7 @@ type PackageManagerCommand = `${(typeof packageManagers)[PackageManager]}${ | ''}`; export function getPackageManagerSpawnCommand( - pkgMng: keyof typeof packageManagers + pkgMng: keyof typeof packageManagers, ): PackageManagerCommand { const winCMD = isWindows() ? '.cmd' : ''; return `${packageManagers[pkgMng]}${winCMD}`; @@ -93,7 +93,7 @@ function isWindows(): boolean { export async function getPackageVersion( packageName: string, - packageManager?: PackageManager + packageManager?: PackageManager, ): Promise { try { packageManager ??= await getCurrentPackageManager(); @@ -106,7 +106,7 @@ export async function getPackageVersion( '--json', ...(command === 'yarn' ? [] : ['--depth=0']), ], - { stdio: 'pipe' } + { stdio: 'pipe' }, ) .toString() .trim(); diff --git a/packages/next-on-pages/src/buildApplication/processVercelOutput.ts b/packages/next-on-pages/src/buildApplication/processVercelOutput.ts index b8c3358d5..7a2ff2fb6 100644 --- a/packages/next-on-pages/src/buildApplication/processVercelOutput.ts +++ b/packages/next-on-pages/src/buildApplication/processVercelOutput.ts @@ -47,12 +47,12 @@ export async function getVercelStaticAssets(): Promise { export async function copyVercelStaticAssets( vercelDir: string, outputDir: string, - staticAssets: string[] + staticAssets: string[], ): Promise { if (staticAssets.length === 0) return; const plural = staticAssets.length > 1 ? 's' : ''; cliLog( - `Copying ${staticAssets.length} static asset${plural} to output directory...` + `Copying ${staticAssets.length} static asset${plural} to output directory...`, ); await Promise.all( @@ -65,7 +65,7 @@ export async function copyVercelStaticAssets( } catch (e) { cliError(`Failed to copy static asset '${file}' to output directory.`); } - }) + }), ); } @@ -79,7 +79,7 @@ export async function copyVercelStaticAssets( */ export async function processOutputDir( outputDir: string, - staticAssets: string[] + staticAssets: string[], ) { const vercelDir = normalizePath(resolve('.vercel', 'output', 'static')); @@ -116,12 +116,12 @@ export function processVercelOutput( config: VercelConfig, staticAssets: string[], prerenderedRoutes = new Map(), - functionsMap = new Map() + functionsMap = new Map(), ): ProcessedVercelOutput { const processedConfig = processVercelConfig(config); const processedOutput = new Map( - staticAssets.map(path => [path, { type: 'static' }]) + staticAssets.map(path => [path, { type: 'static' }]), ); functionsMap.forEach((value, key) => { @@ -147,7 +147,7 @@ export function processVercelOutput( rewriteMiddlewarePaths( processedOutput, - collectMiddlewarePaths(processedConfig.routes.none) + collectMiddlewarePaths(processedConfig.routes.none), ); return { @@ -164,7 +164,7 @@ export function processVercelOutput( */ function collectMiddlewarePaths(routes: VercelSource[]): Set { return new Set( - routes.map(route => route.middlewarePath ?? '').filter(Boolean) + routes.map(route => route.middlewarePath ?? '').filter(Boolean), ); } @@ -187,7 +187,7 @@ function collectMiddlewarePaths(routes: VercelSource[]): Set { */ function rewriteMiddlewarePaths( processedOutput: Map, - middlewarePaths: Set + middlewarePaths: Set, ): void { for (const middlewarePath of middlewarePaths) { const withLeadingSlash = addLeadingSlash(middlewarePath); @@ -221,7 +221,7 @@ function rewriteMiddlewarePaths( */ function applyVercelOverrides( { overrides }: ProcessedVercelConfig, - vercelOutput: Map + vercelOutput: Map, ): void { Object.entries(overrides ?? []).forEach( ([rawAssetPath, { path: rawServedPath, contentType }]) => { @@ -250,7 +250,7 @@ function applyVercelOverrides( if (strippedServedPath !== servedPath) { vercelOutput.set(strippedServedPath, newValue); } - } + }, ); } @@ -262,7 +262,7 @@ function applyVercelOverrides( */ function applyPrerenderedRoutes( prerenderedRoutes: Map, - vercelOutput: Map + vercelOutput: Map, ): void { prerenderedRoutes.forEach(({ headers, overrides }, path) => { vercelOutput.set(path, { diff --git a/packages/next-on-pages/src/cli.ts b/packages/next-on-pages/src/cli.ts index da0e365ef..6586bac1e 100644 --- a/packages/next-on-pages/src/cli.ts +++ b/packages/next-on-pages/src/cli.ts @@ -48,7 +48,7 @@ const cliOptions = z { message: 'The output directory should be inside the current working directory', - } + }, ), }) .strict(); @@ -188,7 +188,7 @@ export function cliLog(message: string, opts: LogOptions = {}): void { export function cliSuccess(message: string, opts: LogOptions = {}): void { // eslint-disable-next-line no-console console.log( - prepareCliMessage(message, { ...opts, styleFormatter: chalk.green }) + prepareCliMessage(message, { ...opts, styleFormatter: chalk.green }), ); } @@ -198,7 +198,7 @@ export function cliError( showReport, fromVercelCli, ...opts - }: LogOptions & { showReport?: boolean } = {} + }: LogOptions & { showReport?: boolean } = {}, ): void { // eslint-disable-next-line no-console console.error( @@ -206,12 +206,12 @@ export function cliError( ...opts, fromVercelCli, styleFormatter: chalk.red, - }) + }), ); if (showReport) { cliError( 'Please report this at https://github.com/cloudflare/next-on-pages/issues.', - { fromVercelCli } + { fromVercelCli }, ); } } @@ -219,7 +219,7 @@ export function cliError( export function cliWarn(message: string, opts: LogOptions = {}): void { // eslint-disable-next-line no-console console.warn( - prepareCliMessage(message, { ...opts, styleFormatter: chalk.yellow }) + prepareCliMessage(message, { ...opts, styleFormatter: chalk.yellow }), ); } @@ -238,7 +238,7 @@ function prepareCliMessage( skipDedent, }: LogOptions & { styleFormatter?: ChalkInstance; - } + }, ): string { const prefix = fromVercelCli ? '▲ ' : '⚡️'; const preparedMessage = (skipDedent ? message : dedent(message)) diff --git a/packages/next-on-pages/src/index.ts b/packages/next-on-pages/src/index.ts index 9139d50e2..0581cc34f 100644 --- a/packages/next-on-pages/src/index.ts +++ b/packages/next-on-pages/src/index.ts @@ -39,7 +39,7 @@ async function runNextOnPages(): Promise { Note: if you're using the --experimental-minify|-e flag in your build command please remove it as it will be removed in a future version of the package (causing your command to fail). `, - { spaced: true } + { spaced: true }, ); } diff --git a/packages/next-on-pages/src/utils/fs.ts b/packages/next-on-pages/src/utils/fs.ts index d59825a12..51a9c86d1 100644 --- a/packages/next-on-pages/src/utils/fs.ts +++ b/packages/next-on-pages/src/utils/fs.ts @@ -105,7 +105,7 @@ export async function readPathsRecursively(dir: string): Promise { const path = resolve(dir, file); return (await validateDir(path)) ? readPathsRecursively(path) : [path]; - }) + }), ); return paths.flat(); diff --git a/packages/next-on-pages/src/utils/getNodeEnv.ts b/packages/next-on-pages/src/utils/getNodeEnv.ts index 6f41ebab5..bfc9ae689 100644 --- a/packages/next-on-pages/src/utils/getNodeEnv.ts +++ b/packages/next-on-pages/src/utils/getNodeEnv.ts @@ -24,7 +24,7 @@ export function getNodeEnv(): string { .join(', ')}. See: https://nextjs.org/docs/basic-features/environment-variables. `, - { spaced: true } + { spaced: true }, ); } diff --git a/packages/next-on-pages/src/utils/routing.ts b/packages/next-on-pages/src/utils/routing.ts index 93d79108b..2503aa1ab 100644 --- a/packages/next-on-pages/src/utils/routing.ts +++ b/packages/next-on-pages/src/utils/routing.ts @@ -65,6 +65,6 @@ export function stripFuncExtension(path: string) { */ export function formatRoutePath(path: string) { return addLeadingSlash( - stripRouteGroups(addLeadingSlash(normalizePath(stripFuncExtension(path)))) + stripRouteGroups(addLeadingSlash(normalizePath(stripFuncExtension(path)))), ); } diff --git a/packages/next-on-pages/templates/_worker.js/handleRequest.ts b/packages/next-on-pages/templates/_worker.js/handleRequest.ts index 64ff3f635..de42f399b 100644 --- a/packages/next-on-pages/templates/_worker.js/handleRequest.ts +++ b/packages/next-on-pages/templates/_worker.js/handleRequest.ts @@ -14,13 +14,13 @@ import type { RequestContext } from '../../src/utils/requestContext'; export async function handleRequest( reqCtx: RequestContext, config: ProcessedVercelConfig, - output: VercelBuildOutput + output: VercelBuildOutput, ): Promise { const matcher = new RoutesMatcher( config.routes, output, reqCtx, - config.wildcard + config.wildcard, ); const match = await findMatch(matcher); @@ -38,7 +38,7 @@ export async function handleRequest( async function findMatch( matcher: RoutesMatcher, phase: 'none' | 'error' = 'none', - skipErrorMatch = false + skipErrorMatch = false, ): Promise { const result = await matcher.run(phase); @@ -68,7 +68,7 @@ async function findMatch( async function generateResponse( reqCtx: RequestContext, { path = '/404', status, headers, searchParams, body }: MatchedSet, - output: VercelBuildOutput + output: VercelBuildOutput, ): Promise { // Redirect user to external URL for redirects. const locationHeader = headers.normal.get('location'); diff --git a/packages/next-on-pages/templates/_worker.js/index.ts b/packages/next-on-pages/templates/_worker.js/index.ts index 8272fad8f..6aa478a7f 100644 --- a/packages/next-on-pages/templates/_worker.js/index.ts +++ b/packages/next-on-pages/templates/_worker.js/index.ts @@ -16,7 +16,7 @@ export default { if (!envAsyncLocalStorage) { return new Response( `Error: Could not access built-in Node.js modules. Please make sure that your Cloudflare Pages project has the 'nodejs_compat' compatibility flag set.`, - { status: 503 } + { status: 503 }, ); } return envAsyncLocalStorage.run( @@ -40,9 +40,9 @@ export default { assetsFetcher: env.ASSETS, }, __CONFIG__, - __BUILD_OUTPUT__ + __BUILD_OUTPUT__, ); - } + }, ); }, } as ExportedHandler<{ ASSETS: Fetcher }>; diff --git a/packages/next-on-pages/templates/_worker.js/routes-matcher.ts b/packages/next-on-pages/templates/_worker.js/routes-matcher.ts index 282e06489..76921a515 100644 --- a/packages/next-on-pages/templates/_worker.js/routes-matcher.ts +++ b/packages/next-on-pages/templates/_worker.js/routes-matcher.ts @@ -63,7 +63,7 @@ export class RoutesMatcher { private output: VercelBuildOutput, /** Request Context object for the request to match */ private reqCtx: RequestContext, - wildcardConfig?: VercelWildcardConfig + wildcardConfig?: VercelWildcardConfig, ) { this.url = new URL(reqCtx.request.url); this.cookies = parse(reqCtx.request.headers.get('cookie') || ''); @@ -77,7 +77,7 @@ export class RoutesMatcher { this.middlewareInvoked = []; this.wildcardMatch = wildcardConfig?.find( - w => w.domain === this.url.hostname + w => w.domain === this.url.hostname, ); } @@ -90,7 +90,7 @@ export class RoutesMatcher { */ private checkRouteMatch( route: VercelSource, - checkStatus?: boolean + checkStatus?: boolean, ): MatchPCREResult | undefined { const srcMatch = matchPCRE(route.src, this.path, route.caseSensitive); if (!srcMatch.match) return; @@ -141,7 +141,7 @@ export class RoutesMatcher { const overrideHeader = resp.headers.get(overrideKey); if (overrideHeader) { const overridenHeaderKeys = new Set( - overrideHeader.split(',').map(h => h.trim()) + overrideHeader.split(',').map(h => h.trim()), ); for (const key of overridenHeaderKeys.keys()) { @@ -245,7 +245,7 @@ export class RoutesMatcher { private applyRouteHeaders( route: VercelSource, srcMatch: RegExpMatchArray, - captureGroupKeys: string[] + captureGroupKeys: string[], ): void { if (!route.headers) return; @@ -286,7 +286,7 @@ export class RoutesMatcher { private applyRouteDest( route: VercelSource, srcMatch: RegExpMatchArray, - captureGroupKeys: string[] + captureGroupKeys: string[], ): string { if (!route.dest) return this.path; @@ -297,7 +297,7 @@ export class RoutesMatcher { if (this.wildcardMatch && /\$wildcard/.test(processedDest)) { processedDest = processedDest.replace( /\$wildcard/g, - this.wildcardMatch.value + this.wildcardMatch.value, ); } @@ -358,7 +358,7 @@ export class RoutesMatcher { const cookieLocales = parseAcceptLanguage(cookieValue ?? ''); const headerLocales = parseAcceptLanguage( - this.reqCtx.request.headers.get('accept-language') ?? '' + this.reqCtx.request.headers.get('accept-language') ?? '', ); // Locales from the cookie take precedence over the header. @@ -398,7 +398,7 @@ export class RoutesMatcher { */ private getLocaleFriendlyRoute( route: VercelSource, - phase: VercelPhase + phase: VercelPhase, ): VercelSource { if (!this.locales || phase !== 'miss') { return route; @@ -426,7 +426,7 @@ export class RoutesMatcher { */ private async checkRoute( phase: VercelPhase, - rawRoute: VercelSource + rawRoute: VercelSource, ): Promise { const route = this.getLocaleFriendlyRoute(rawRoute, phase); const routeMatch = this.checkRouteMatch(route, phase === 'error'); @@ -514,7 +514,7 @@ export class RoutesMatcher { if (this.checkPhaseCounter++ >= 50) { // eslint-disable-next-line no-console console.error( - `Routing encountered an infinite loop while checking ${this.url.pathname}` + `Routing encountered an infinite loop while checking ${this.url.pathname}`, ); this.status = 500; return 'error'; @@ -585,7 +585,7 @@ export class RoutesMatcher { * @returns The status from checking for matches. */ public async run( - phase: Extract = 'none' + phase: Extract = 'none', ): Promise { // Reset the counter for each run. this.checkPhaseCounter = 0; diff --git a/packages/next-on-pages/templates/_worker.js/utils/http.ts b/packages/next-on-pages/templates/_worker.js/utils/http.ts index 7a1b1ed1f..03085261e 100644 --- a/packages/next-on-pages/templates/_worker.js/utils/http.ts +++ b/packages/next-on-pages/templates/_worker.js/utils/http.ts @@ -14,7 +14,7 @@ import { applyPCREMatches } from './pcre'; export function applyHeaders( target: Headers, source: Record | Headers, - pcreMatch?: MatchPCREResult + pcreMatch?: MatchPCREResult, ): void { const entries = source instanceof Headers ? source.entries() : Object.entries(source); @@ -57,7 +57,7 @@ export function isUrl(url: string): boolean { */ export function applySearchParams( target: URLSearchParams, - source: URLSearchParams + source: URLSearchParams, ) { for (const [key, value] of source.entries()) { if (!target.has(key) || !!value) { diff --git a/packages/next-on-pages/templates/_worker.js/utils/images.ts b/packages/next-on-pages/templates/_worker.js/utils/images.ts index bc17a8acd..f75b9a257 100644 --- a/packages/next-on-pages/templates/_worker.js/utils/images.ts +++ b/packages/next-on-pages/templates/_worker.js/utils/images.ts @@ -12,7 +12,7 @@ import { applyHeaders, createMutableResponse } from './http'; */ export function isRemotePatternMatch( url: URL, - { protocol, hostname, port, pathname }: VercelImageRemotePattern + { protocol, hostname, port, pathname }: VercelImageRemotePattern, ): boolean { // Protocol must match if defined. if (protocol && url.protocol.replace(/:$/, '') !== protocol) return false; @@ -44,7 +44,7 @@ type ResizingProperties = { */ export function getResizingProperties( request: Request, - config?: VercelImagesConfig + config?: VercelImagesConfig, ): ResizingProperties | undefined { if (request.method !== 'GET') return undefined; @@ -105,7 +105,7 @@ export function getResizingProperties( export function formatResp( resp: Response, imageUrl: URL, - config?: VercelImagesConfig + config?: VercelImagesConfig, ): Response { const newHeaders = new Headers(); @@ -127,7 +127,7 @@ export function formatResp( // https://vercel.com/docs/concepts/image-optimization#caching newHeaders.set( 'Cache-Control', - `public, max-age=${config?.minimumCacheTTL ?? 60}` + `public, max-age=${config?.minimumCacheTTL ?? 60}`, ); } @@ -146,7 +146,7 @@ export function formatResp( */ export async function handleImageResizingRequest( request: Request, - { buildOutput, assetsFetcher, imagesConfig }: ImageResizingOpts + { buildOutput, assetsFetcher, imagesConfig }: ImageResizingOpts, ): Promise { const opts = getResizingProperties(request, imagesConfig); diff --git a/packages/next-on-pages/templates/_worker.js/utils/matcher.ts b/packages/next-on-pages/templates/_worker.js/utils/matcher.ts index 257f9857d..1a8dc1ff6 100644 --- a/packages/next-on-pages/templates/_worker.js/utils/matcher.ts +++ b/packages/next-on-pages/templates/_worker.js/utils/matcher.ts @@ -13,7 +13,7 @@ type HasFieldRequestProperties = { */ export function hasField( has: VercelHasField, - { url, cookies, headers }: HasFieldRequestProperties + { url, cookies, headers }: HasFieldRequestProperties, ): boolean { switch (has.type) { case 'host': { diff --git a/packages/next-on-pages/templates/_worker.js/utils/pcre.ts b/packages/next-on-pages/templates/_worker.js/utils/pcre.ts index e6c808529..108e27820 100644 --- a/packages/next-on-pages/templates/_worker.js/utils/pcre.ts +++ b/packages/next-on-pages/templates/_worker.js/utils/pcre.ts @@ -20,7 +20,7 @@ export type MatchPCREResult = { export function matchPCRE( expr: string, val: string, - caseSensitive?: boolean + caseSensitive?: boolean, ): MatchPCREResult { const flag = caseSensitive ? '' : 'i'; const captureGroupKeys: string[] = []; @@ -42,7 +42,7 @@ export function matchPCRE( export function applyPCREMatches( rawStr: string, match: RegExpMatchArray, - captureGroupKeys: string[] + captureGroupKeys: string[], ): string { return rawStr.replace(/\$([a-zA-Z0-9]+)/g, (_, key) => { const index = captureGroupKeys.indexOf(key); diff --git a/packages/next-on-pages/templates/_worker.js/utils/request.ts b/packages/next-on-pages/templates/_worker.js/utils/request.ts index e63bade4b..6ab1b4e1c 100644 --- a/packages/next-on-pages/templates/_worker.js/utils/request.ts +++ b/packages/next-on-pages/templates/_worker.js/utils/request.ts @@ -12,15 +12,15 @@ export function adjustRequestForVercel(request: Request): Request { adjustedHeaders.append('x-vercel-ip-country', request.cf.country as string); adjustedHeaders.append( 'x-vercel-ip-country-region', - request.cf.region as string + request.cf.region as string, ); adjustedHeaders.append( 'x-vercel-ip-latitude', - request.cf.latitude as string + request.cf.latitude as string, ); adjustedHeaders.append( 'x-vercel-ip-longitude', - request.cf.longitude as string + request.cf.longitude as string, ); } diff --git a/packages/next-on-pages/templates/_worker.js/utils/routing.ts b/packages/next-on-pages/templates/_worker.js/utils/routing.ts index b05ad38b3..b16e77df3 100644 --- a/packages/next-on-pages/templates/_worker.js/utils/routing.ts +++ b/packages/next-on-pages/templates/_worker.js/utils/routing.ts @@ -77,7 +77,7 @@ export function getNextPhase(phase: VercelPhase): VercelHandleValue { export async function runOrFetchBuildOutputItem( item: VercelBuildOutputItem | undefined, { request, assetsFetcher, ctx }: RequestContext, - { path, searchParams }: Omit + { path, searchParams }: Omit, ) { let resp: Response | undefined = undefined; @@ -96,7 +96,7 @@ export async function runOrFetchBuildOutputItem( } case 'override': { resp = createMutableResponse( - await assetsFetcher.fetch(createRouteRequest(req, item.path ?? path)) + await assetsFetcher.fetch(createRouteRequest(req, item.path ?? path)), ); if (item.headers) { @@ -133,7 +133,7 @@ export async function runOrFetchBuildOutputItem( */ export function isLocaleTrailingSlashRegex( src: string, - locales: Record + locales: Record, ) { const prefix = '^//?(?:'; const suffix = ')/(.*)'; diff --git a/packages/next-on-pages/tests/_helpers/index.ts b/packages/next-on-pages/tests/_helpers/index.ts index a1c42e93c..02330d7b9 100644 --- a/packages/next-on-pages/tests/_helpers/index.ts +++ b/packages/next-on-pages/tests/_helpers/index.ts @@ -37,7 +37,7 @@ export class MockAssetFetcher { constructor(assets: Record = {}) { this.assets = Object.fromEntries( - [...Object.entries(assets)].map(([key, value]) => [key, value]) + [...Object.entries(assets)].map(([key, value]) => [key, value]), ); } @@ -55,7 +55,7 @@ export class MockAssetFetcher { new Response(asset.data, { status: 200, headers: { 'content-type': asset.type }, - }) + }), ); }; @@ -70,7 +70,7 @@ function createMockEntrypoint(file = 'unknown'): EdgeFunction { const params = [...new URL(request.url).searchParams.entries()]; return Promise.resolve( - new Response(JSON.stringify({ file, params }), { status: 200 }) + new Response(JSON.stringify({ file, params }), { status: 200 }), ); }, }; @@ -163,7 +163,7 @@ function createMockMiddlewareEntrypoint(file = '/'): EdgeFunction { } function constructBuildOutputRecord( - item: BuildOutputItem + item: BuildOutputItem, ): VercelBuildOutputItem { if (item.type === 'static') { return { type: item.type }; @@ -181,7 +181,7 @@ function constructBuildOutputRecord( if (item.type === 'middleware') { vi.doMock(item.entrypoint, () => - createMockMiddlewareEntrypoint(fileContents) + createMockMiddlewareEntrypoint(fileContents), ); } else if (item.type === 'function') { vi.doMock(item.entrypoint, () => createMockEntrypoint(fileContents)); @@ -200,14 +200,14 @@ type RouterTestData = { export async function createRouterTestData( rawVercelConfig: VercelConfig, files: DirectoryItems, - outputDir = join('.vercel', 'output', 'static') + outputDir = join('.vercel', 'output', 'static'), ): Promise { mockFs({ '.vercel': { output: files } }); const { functionsMap, prerenderedRoutes } = await generateFunctionsMap( join('.vercel', 'output', 'functions'), outputDir, - true + true, ); const staticAssets = await getVercelStaticAssets(); @@ -216,7 +216,7 @@ export async function createRouterTestData( rawVercelConfig, staticAssets, prerenderedRoutes, - functionsMap + functionsMap, ); const buildOutput = [...vercelOutput.entries()].reduce( @@ -224,26 +224,29 @@ export async function createRouterTestData( prev[name] = constructBuildOutputRecord(item); return prev; }, - {} as VercelBuildOutput + {} as VercelBuildOutput, ); - const staticAssetsForFetcher = staticAssets.reduce((acc, path) => { - const newAcc = { ...acc }; + const staticAssetsForFetcher = staticAssets.reduce( + (acc, path) => { + const newAcc = { ...acc }; - const item = buildOutput[path]; - const contentType = - (item?.type === 'override' && item.headers?.['content-type']) || - 'text/plain;charset=UTF-8'; + const item = buildOutput[path]; + const contentType = + (item?.type === 'override' && item.headers?.['content-type']) || + 'text/plain;charset=UTF-8'; - const fsPath = join(resolve('.vercel', 'output', 'static'), path); - const data = readFileSync(fsPath, 'utf-8'); + const fsPath = join(resolve('.vercel', 'output', 'static'), path); + const data = readFileSync(fsPath, 'utf-8'); - newAcc[path] = { data, type: contentType }; - return newAcc; - }, {} as Record); + newAcc[path] = { data, type: contentType }; + return newAcc; + }, + {} as Record, + ); const assetsFetcher = new MockAssetFetcher( - staticAssetsForFetcher + staticAssetsForFetcher, ) as unknown as Fetcher; mockFs.restore(); @@ -311,7 +314,7 @@ export function mockPrerenderConfigFile(path: string, ext?: string): string { export function createPrerenderedRoute( file: string, - base = '' + base = '', ): DirectoryItems { const fileWithBase = `${base}/${file}`; return { @@ -320,7 +323,7 @@ export function createPrerenderedRoute( [`${file}.prerender-config.json`]: mockPrerenderConfigFile(`${file}`), [`${file}.prerender-fallback.html`]: `${fileWithBase}.prerender-fallback.html`, [`${file}.rsc.prerender-config.json`]: mockPrerenderConfigFile( - `${file}.rsc` + `${file}.rsc`, ), [`${file}.rsc.prerender-fallback.rsc`]: `${fileWithBase}.rsc.prerender-fallback.rsc`, }; @@ -341,8 +344,8 @@ export function mockConsole(method: ConsoleMethods) { expect(mockedMethod).toHaveBeenCalledTimes(calls.length); calls.forEach(msg => expect(mockedMethod).toHaveBeenCalledWith( - msg instanceof RegExp ? expect.stringMatching(msg) : msg - ) + msg instanceof RegExp ? expect.stringMatching(msg) : msg, + ), ); }; diff --git a/packages/next-on-pages/tests/src/buildApplication/buildSummary.test.ts b/packages/next-on-pages/tests/src/buildApplication/buildSummary.test.ts index 3c3930254..397fcde86 100644 --- a/packages/next-on-pages/tests/src/buildApplication/buildSummary.test.ts +++ b/packages/next-on-pages/tests/src/buildApplication/buildSummary.test.ts @@ -55,7 +55,7 @@ describe('buildSummary', () => { printBuildSummary( staticAssets, processedVercelOutput, - directoryProcessingResults + directoryProcessingResults, ); expect(mockedConsole).toHaveBeenCalledTimes(1); @@ -84,7 +84,7 @@ describe('buildSummary', () => { ⚡️ ├ /_next/static-a ⚡️ ├ /_next/static-b ⚡️ └ ... 2 more - `.replace(/\n\t{3}/g, '\n') + `.replace(/\n\t{3}/g, '\n'), ); mockedConsole.mockRestore(); @@ -129,12 +129,12 @@ describe('buildSummary', () => { 'dist', staticAssets, processedVercelOutput, - directoryProcessingResults + directoryProcessingResults, ); expect(mockedConsole).toHaveBeenCalledTimes(1); expect(mockedConsole).lastCalledWith( - expect.stringMatching(/Build log saved to 'dist\/nop-build-log\.json'/) + expect.stringMatching(/Build log saved to 'dist\/nop-build-log\.json'/), ); const logFile = await readJsonFile('dist/nop-build-log.json'); @@ -154,7 +154,7 @@ describe('buildSummary', () => { identifier: 'wasm-one', importPath: '/wasm/wasm-one.wasm', originalFileLocation: expect.stringMatching( - /\/assets\/wasm\/wasm-one\.wasm/ + /\/assets\/wasm\/wasm-one\.wasm/, ), }, ], diff --git a/packages/next-on-pages/tests/src/buildApplication/generateFunctionsMap.test.ts b/packages/next-on-pages/tests/src/buildApplication/generateFunctionsMap.test.ts index d3d6c7a65..2f064fd94 100644 --- a/packages/next-on-pages/tests/src/buildApplication/generateFunctionsMap.test.ts +++ b/packages/next-on-pages/tests/src/buildApplication/generateFunctionsMap.test.ts @@ -67,10 +67,10 @@ describe('generateFunctionsMap', async () => { expect(functionsMap.size).toEqual(2); expect(functionsMap.get('/middlewarejs')).toMatch( - /\/middlewarejs\.func\.js$/ + /\/middlewarejs\.func\.js$/, ); expect(functionsMap.get('/base/middleware')).toMatch( - /\/base\/middleware\.func\.js$/ + /\/base\/middleware\.func\.js$/, ); }); }); @@ -90,7 +90,7 @@ describe('generateFunctionsMap', async () => { expect(functionsMap.size).toEqual(1); expect(functionsMap.get('/path/to/page')).toMatch( - /\/path\/\(group-1\)\/to\/\(group-2\)\/page\.func\.js$/ + /\/path\/\(group-1\)\/to\/\(group-2\)\/page\.func\.js$/, ); }); @@ -105,7 +105,7 @@ describe('generateFunctionsMap', async () => { expect(Array.from(invalidFunctions.values())).toEqual([]); expect(functionsMap.size).toEqual(1); expect(functionsMap.get('/should-be-valid')).toMatch( - /\(is-actually-valid\)\/should-be-valid\.func\.js$/ + /\(is-actually-valid\)\/should-be-valid\.func\.js$/, ); }); @@ -184,7 +184,7 @@ describe('generateFunctionsMap', async () => { 'favicon.ico.func': invalidFuncDir, 'favicon.ico.prerender-config.json': mockPrerenderConfigFile( 'favicon.ico', - 'body' + 'body', ), 'favicon.ico.prerender-fallback.body': 'favicon.ico', }); @@ -211,7 +211,7 @@ describe('generateFunctionsMap', async () => { 'data.json.func': invalidFuncDir, 'data.json.prerender-config.json': mockPrerenderConfigFile( 'data.json', - 'json' + 'json', ), 'data.json.prerender-fallback.json': 'data.json', }, @@ -315,7 +315,7 @@ describe('generateFunctionsMap', async () => { mockPrerenderConfigFile('index.rsc'), 'index.rsc.prerender-fallback.rsc': '', }, - { 'index.rsc': '' } + { 'index.rsc': '' }, ); expect(functionsMap.size).toEqual(0); @@ -355,7 +355,7 @@ describe('generateFunctionsMap', async () => { 'page.rsc.prerender-fallback.rsc': '', }, }, - { nested: { 'page.rsc': '' } } + { nested: { 'page.rsc': '' } }, ); expect(functionsMap.size).toEqual(0); @@ -455,7 +455,7 @@ describe('generateFunctionsMap', async () => { }, { 'index.rsc': '' }, true, - resolve('custom') + resolve('custom'), ); expect(functionsMap.size).toEqual(0); @@ -501,7 +501,7 @@ describe('generateFunctionsMap', async () => { }, {}, true, - resolve('custom') + resolve('custom'), ); expect(functionsMap.size).toEqual(2); @@ -561,7 +561,7 @@ async function generateFunctionsMapFrom( staticAssets: DirectoryItems = {}, disableChunksDedup = true, outputDir = resolve('.vercel', 'output', 'static'), - otherDirs: DirectoryItems = {} + otherDirs: DirectoryItems = {}, ) { mockFs({ '.vercel': { @@ -577,7 +577,7 @@ async function generateFunctionsMapFrom( const result = await generateFunctionsMap( resolve('.vercel', 'output', 'functions'), outputDir, - disableChunksDedup + disableChunksDedup, ); return result; } diff --git a/packages/next-on-pages/tests/src/buildApplication/generateGlobalJs.test.ts b/packages/next-on-pages/tests/src/buildApplication/generateGlobalJs.test.ts index 974db7dbc..136c25c2c 100644 --- a/packages/next-on-pages/tests/src/buildApplication/generateGlobalJs.test.ts +++ b/packages/next-on-pages/tests/src/buildApplication/generateGlobalJs.test.ts @@ -6,35 +6,35 @@ describe('generateGlobalJs', async () => { test('should generate a promise for the AsyncLocalStorage import', async () => { const globalJs = generateGlobalJs(); expect(globalJs).toContain( - "const __ENV_ALS_PROMISE__ = import('node:async_hooks')" + "const __ENV_ALS_PROMISE__ = import('node:async_hooks')", ); }); test('should make the AsyncLocalStorage globally available', async () => { const globalJs = generateGlobalJs(); expect(globalJs).toContain( - 'globalThis.AsyncLocalStorage = AsyncLocalStorage' + 'globalThis.AsyncLocalStorage = AsyncLocalStorage', ); }); test('create an AsyncLocalStorage and set it as a proxy to process.env', async () => { const globalJs = generateGlobalJs(); expect(globalJs).toContain( - 'const envAsyncLocalStorage = new AsyncLocalStorage()' + 'const envAsyncLocalStorage = new AsyncLocalStorage()', ); const proxyRegexMatch = globalJs.match( - /globalThis.process = {[\S\s]*Proxy\(([\s\S]+)\)[\s\S]+}/ + /globalThis.process = {[\S\s]*Proxy\(([\s\S]+)\)[\s\S]+}/, ); expect(proxyRegexMatch?.length).toBe(2); const proxyBody = proxyRegexMatch?.[1]; expect(proxyBody).toContain( - 'Reflect.get(envAsyncLocalStorage.getStore()' + 'Reflect.get(envAsyncLocalStorage.getStore()', ); expect(proxyBody).toContain( - 'Reflect.set(envAsyncLocalStorage.getStore()' + 'Reflect.set(envAsyncLocalStorage.getStore()', ); }); }); diff --git a/packages/next-on-pages/tests/src/buildApplication/packageManagerUtils.test.ts b/packages/next-on-pages/tests/src/buildApplication/packageManagerUtils.test.ts index 589d461f4..0cf991150 100644 --- a/packages/next-on-pages/tests/src/buildApplication/packageManagerUtils.test.ts +++ b/packages/next-on-pages/tests/src/buildApplication/packageManagerUtils.test.ts @@ -65,7 +65,7 @@ describe('getCurrentPackageExecuter', () => { async () => { const pkgMng = await getCurrentPackageExecuter(); expect(pkgMng).toEqual('yarn.cmd dlx'); - } + }, ); }); it('should detect yarn (classic) on windows', async () => { @@ -74,7 +74,7 @@ describe('getCurrentPackageExecuter', () => { async () => { const pkgMng = await getCurrentPackageExecuter(); expect(pkgMng).toEqual('yarn.cmd'); - } + }, ); }); it('should detected pnpm on windows', async () => { @@ -99,13 +99,13 @@ async function testWith( packageManager: Exclude; os?: 'windows' | 'linux/macos'; }, - test: () => Promise + test: () => Promise, ): Promise { currentMocks.packageManager = packageManager; currentMocks.os = os; vi.stubEnv('npm_config_user_agent', packageManager); vi.spyOn(process, 'platform', 'get').mockReturnValue( - currentMocks.os === 'windows' ? 'win32' : 'linux' + currentMocks.os === 'windows' ? 'win32' : 'linux', ); await test(); vi.unstubAllEnvs(); @@ -138,7 +138,7 @@ vi.mock('child_process', async () => { setTimeout(() => { event.stdout.emit( 'data', - currentMocks.packageManager === 'yarn (berry)' ? '3.0.0' : '1.0.0' + currentMocks.packageManager === 'yarn (berry)' ? '3.0.0' : '1.0.0', ); event.emit('close', 0); }, 100); diff --git a/packages/next-on-pages/tests/src/buildApplication/processVercelOutput.test.ts b/packages/next-on-pages/tests/src/buildApplication/processVercelOutput.test.ts index f43f6529f..7d3ec9063 100644 --- a/packages/next-on-pages/tests/src/buildApplication/processVercelOutput.test.ts +++ b/packages/next-on-pages/tests/src/buildApplication/processVercelOutput.test.ts @@ -33,7 +33,7 @@ describe('processVercelOutput', () => { inputtedConfig, inputtedAssets, inputtedPrerendered, - inputtedFunctions + inputtedFunctions, ); const expected: ProcessedVercelOutput = { @@ -102,7 +102,7 @@ describe('processVercelOutput', () => { inputtedConfig, inputtedAssets, inputtedPrerendered, - inputtedFunctions + inputtedFunctions, ); const expected: ProcessedVercelOutput = { @@ -266,7 +266,7 @@ describe('processVercelOutput', () => { inputtedConfig, inputtedAssets, inputtedPrerendered, - inputtedFunctions + inputtedFunctions, ); const expected: ProcessedVercelOutput = { diff --git a/packages/next-on-pages/tests/src/utils/fs.test.ts b/packages/next-on-pages/tests/src/utils/fs.test.ts index 0b7e3c44d..ae0804d3b 100644 --- a/packages/next-on-pages/tests/src/utils/fs.test.ts +++ b/packages/next-on-pages/tests/src/utils/fs.test.ts @@ -40,7 +40,7 @@ describe('readJsonFile', () => { '.vc-config.json': JSON.stringify(vcConfigContent), }); await expect(readJsonFile('.vc-config.json')).resolves.toEqual( - vcConfigContent + vcConfigContent, ); mockFs.restore(); }); @@ -65,7 +65,7 @@ describe('validateFile', () => { }); test('valid file returns true', async () => { await expect( - validateFile('functions/index.func/index.js') + validateFile('functions/index.func/index.js'), ).resolves.toEqual(true); }); @@ -75,7 +75,7 @@ describe('validateFile', () => { test('invalid path returns false', async () => { await expect( - validateFile('functions/invalid-index.func/index.js') + validateFile('functions/invalid-index.func/index.js'), ).resolves.toEqual(false); }); }); @@ -99,7 +99,7 @@ describe('validateDir', () => { test('valid file returns false', async () => { await expect(validateDir('functions/index.func/index.js')).resolves.toEqual( - false + false, ); }); @@ -133,11 +133,11 @@ describe('readPathsRecursively', () => { }); test('should read all paths recursively', async () => { const paths = (await readPathsRecursively('root/functions')).map(path => - normalizePath(path) + normalizePath(path), ); expect(paths.length).toEqual(3); expect(paths[0]).toMatch( - /root\/functions\/\(route-group\)\/page\.func\/index\.js$/ + /root\/functions\/\(route-group\)\/page\.func\/index\.js$/, ); expect(paths[1]).toMatch(/root\/functions\/home\.func\/index\.js$/); expect(paths[2]).toMatch(/root\/functions\/index\.func\/index\.js$/); @@ -145,7 +145,7 @@ describe('readPathsRecursively', () => { test('invalid directory, returns empty array', async () => { await expect( - readPathsRecursively('invalid-root/functions') + readPathsRecursively('invalid-root/functions'), ).resolves.toEqual([]); }); }); diff --git a/packages/next-on-pages/tests/src/utils/routing.test.ts b/packages/next-on-pages/tests/src/utils/routing.test.ts index 4ab5694f0..88e4c4175 100644 --- a/packages/next-on-pages/tests/src/utils/routing.test.ts +++ b/packages/next-on-pages/tests/src/utils/routing.test.ts @@ -17,7 +17,7 @@ describe('routing', () => { test('stripRouteGroups does not strip intercepts', () => { expect(stripRouteGroups('/(.)intercept')).toEqual('/(.)intercept'); expect(stripRouteGroups('/(..)(..)intercept')).toEqual( - '/(..)(..)intercept' + '/(..)(..)intercept', ); }); diff --git a/packages/next-on-pages/tests/templates/handleRequest.test.ts b/packages/next-on-pages/tests/templates/handleRequest.test.ts index b4816f5f4..0eef0b66f 100644 --- a/packages/next-on-pages/tests/templates/handleRequest.test.ts +++ b/packages/next-on-pages/tests/templates/handleRequest.test.ts @@ -39,7 +39,7 @@ function runTestCase( reqCtx: Pick, config: ProcessedVercelConfig, output: VercelBuildOutput, - testCase: TestCase + testCase: TestCase, ) { test(testCase.name, async () => { const { @@ -59,17 +59,17 @@ function runTestCase( const res = await handleRequest( { ...reqCtx, request: req }, config, - output + output, ); expect(res.status).toEqual(expected.status); await expect(res.text()).resolves.toEqual(expected.data); expect(Object.fromEntries(res.headers.entries())).toEqual( - expected.headers || {} + expected.headers || {}, ); if (expected.reqHeaders) { expect(Object.fromEntries(req.headers.entries())).toEqual( - expected.reqHeaders + expected.reqHeaders, ); } @@ -96,7 +96,7 @@ async function runTestSet({ config, files, testCases }: TestSet) { }; testCases.forEach(testCase => - runTestCase(reqCtx, vercelConfig, buildOutput, testCase) + runTestCase(reqCtx, vercelConfig, buildOutput, testCase), ); afterAll(() => restoreMocks()); diff --git a/packages/next-on-pages/tests/templates/requestTestData/i18n.ts b/packages/next-on-pages/tests/templates/requestTestData/i18n.ts index 57de36460..187b2812e 100644 --- a/packages/next-on-pages/tests/templates/requestTestData/i18n.ts +++ b/packages/next-on-pages/tests/templates/requestTestData/i18n.ts @@ -162,7 +162,7 @@ export const testSet: TestSet = { ...acc, [locale]: { 'gsp.json': JSON.stringify({ locale }) }, }), - {} + {}, ), }, }, @@ -178,7 +178,7 @@ export const testSet: TestSet = { 'gsp.html': `${locale}: gsp`, }, }), - {} + {}, ), }, }, diff --git a/packages/next-on-pages/tests/templates/requestTestData/trailingSlash.ts b/packages/next-on-pages/tests/templates/requestTestData/trailingSlash.ts index a8b67e33d..f14355a55 100644 --- a/packages/next-on-pages/tests/templates/requestTestData/trailingSlash.ts +++ b/packages/next-on-pages/tests/templates/requestTestData/trailingSlash.ts @@ -63,7 +63,7 @@ export const testSet: TestSet = { '[lang].func': createValidFuncDir('/[lang]'), 'robots.txt.prerender-config.json': mockPrerenderConfigFile( 'robots.txt', - 'body' + 'body', ), 'robots.txt.prerender-fallback.body': 'robots.txt fallback', }, diff --git a/packages/next-on-pages/tests/templates/utils/getNodeEnv.test.ts b/packages/next-on-pages/tests/templates/utils/getNodeEnv.test.ts index 5f0055fee..afae7a197 100644 --- a/packages/next-on-pages/tests/templates/utils/getNodeEnv.test.ts +++ b/packages/next-on-pages/tests/templates/utils/getNodeEnv.test.ts @@ -16,7 +16,7 @@ describe('getNodeEnv', () => { const nodeEnv = getNodeEnv(); expect(nodeEnv).toBe(testNodeEnv); }); - }) + }), ); test('should set the NODE_ENV to a non-Next.js value correctly but generate a warning', async () => { @@ -32,7 +32,7 @@ describe('getNodeEnv', () => { function runWithNodeEnv void>( value: string, - testFn: F + testFn: F, ): void { const oldNodeEnv = process.env.NODE_ENV; process.env.NODE_ENV = value; diff --git a/packages/next-on-pages/tests/templates/utils/http.test.ts b/packages/next-on-pages/tests/templates/utils/http.test.ts index 1f8da7f02..dc8460ccd 100644 --- a/packages/next-on-pages/tests/templates/utils/http.test.ts +++ b/packages/next-on-pages/tests/templates/utils/http.test.ts @@ -78,7 +78,7 @@ describe('applySearchParams', () => { expect([...target.searchParams.entries()].length).toEqual(2); expect(target.toString()).toEqual( - 'http://localhost/page?other=value&foo=bar' + 'http://localhost/page?other=value&foo=bar', ); }); }); diff --git a/packages/next-on-pages/tests/templates/utils/images.test.ts b/packages/next-on-pages/tests/templates/utils/images.test.ts index ceafa5c40..c0d55fdf1 100644 --- a/packages/next-on-pages/tests/templates/utils/images.test.ts +++ b/packages/next-on-pages/tests/templates/utils/images.test.ts @@ -170,7 +170,7 @@ describe('getResizingProperties', () => { describe('external image', () => { test('external image fails with disallowed domain', () => { const url = new URL( - `${baseUrl}https%3A%2F%2Finvalid.com%2Fimage.jpg&w=640` + `${baseUrl}https%3A%2F%2Finvalid.com%2Fimage.jpg&w=640`, ); const req = new Request(url); @@ -179,7 +179,7 @@ describe('getResizingProperties', () => { test('external image succeeds with allowed domain', () => { const url = new URL( - `${baseUrl}https%3A%2F%2Fexample.com%2Fimage.jpg&w=640` + `${baseUrl}https%3A%2F%2Fexample.com%2Fimage.jpg&w=640`, ); const req = new Request(url); @@ -193,7 +193,7 @@ describe('getResizingProperties', () => { test('external image suceeds with allowed remote pattern', () => { const url = new URL( - `${baseUrl}https%3A%2F%2Fvia.placeholder.com%2Fimage.jpg&w=640` + `${baseUrl}https%3A%2F%2Fvia.placeholder.com%2Fimage.jpg&w=640`, ); const req = new Request(url); @@ -242,7 +242,7 @@ describe('formatResp', () => { const newResp = formatResp(new Response(), imageUrl, config); expect(newResp.headers.get('Content-Security-Policy')).toEqual( - 'default-src' + 'default-src', ); }); @@ -252,7 +252,7 @@ describe('formatResp', () => { const newResp = formatResp(new Response(), imageUrl, config); expect(newResp.headers.get('Content-Disposition')).toEqual( - 'inline; filename="1.jpg"' + 'inline; filename="1.jpg"', ); }); @@ -271,7 +271,7 @@ describe('formatResp', () => { const newResp = formatResp( new Response(null, { headers: { 'cache-control': 'test-value' } }), imageUrl, - config + config, ); expect(newResp.headers.get('Cache-Control')).toEqual('test-value'); }); diff --git a/packages/next-on-pages/tests/templates/utils/matcher.test.ts b/packages/next-on-pages/tests/templates/utils/matcher.test.ts index 9d6343c93..e0d67bf40 100644 --- a/packages/next-on-pages/tests/templates/utils/matcher.test.ts +++ b/packages/next-on-pages/tests/templates/utils/matcher.test.ts @@ -16,7 +16,7 @@ const req = new Request( headerWithoutValue: undefined as unknown as string, cookie: 'cookieWithValue=value; cookieWithoutValue=', }, - } + }, ); const url = new URL(req.url); const cookies = parse(req.headers.get('cookie') ?? ''); diff --git a/packages/next-on-pages/tests/templates/utils/pcre.test.ts b/packages/next-on-pages/tests/templates/utils/pcre.test.ts index 8ae1f0ffe..f8f7a7580 100644 --- a/packages/next-on-pages/tests/templates/utils/pcre.test.ts +++ b/packages/next-on-pages/tests/templates/utils/pcre.test.ts @@ -50,7 +50,7 @@ describe('matchPCRE', () => { const result = matchPCRE( testCase.route.src, new URL(testCase.url).pathname, - testCase.route.caseSensitive + testCase.route.caseSensitive, ); expect({ ...result, match: !!result.match }).toEqual(testCase.expected); }); @@ -134,13 +134,13 @@ describe('applyPCREMatches', () => { const { match, captureGroupKeys } = matchPCRE( testCase.route.src, new URL(testCase.url).pathname, - testCase.route.caseSensitive + testCase.route.caseSensitive, ); const result = applyPCREMatches( testCase.route.dest ?? '', // eslint-disable-next-line @typescript-eslint/no-non-null-assertion match!, - captureGroupKeys + captureGroupKeys, ); const { newDest: expectedNewDest, ...expected } = testCase.expected; diff --git a/packages/next-on-pages/vercel.types.d.ts b/packages/next-on-pages/vercel.types.d.ts index 4433d8ab6..1bed8b98d 100644 --- a/packages/next-on-pages/vercel.types.d.ts +++ b/packages/next-on-pages/vercel.types.d.ts @@ -169,7 +169,7 @@ type ProcessedVercelBuildOutput = Map; type EdgeFunction = { default: ( request: Request, - context: ExecutionContext + context: ExecutionContext, ) => Response | Promise; }; diff --git a/pages-e2e/features/next-pages-experimental-edge-api-route/setup.ts b/pages-e2e/features/next-pages-experimental-edge-api-route/setup.ts index 1b190d3f7..067cbe7e9 100644 --- a/pages-e2e/features/next-pages-experimental-edge-api-route/setup.ts +++ b/pages-e2e/features/next-pages-experimental-edge-api-route/setup.ts @@ -7,5 +7,5 @@ const { WORKSPACE_DIR } = process.env; await cp( join(process.cwd(), 'assets/pages-api-hello.js'), - join(WORKSPACE_DIR, 'pages/api/hello.js') + join(WORKSPACE_DIR, 'pages/api/hello.js'), ); diff --git a/pages-e2e/fixtures/next-12-3-1/styles/Home.module.css b/pages-e2e/fixtures/next-12-3-1/styles/Home.module.css index e8e54acb2..21879d3c4 100644 --- a/pages-e2e/fixtures/next-12-3-1/styles/Home.module.css +++ b/pages-e2e/fixtures/next-12-3-1/styles/Home.module.css @@ -61,8 +61,15 @@ border-radius: 5px; padding: 0.75rem; font-size: 1.1rem; - font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, - Bitstream Vera Sans Mono, Courier New, monospace; + font-family: + Menlo, + Monaco, + Lucida Console, + Liberation Mono, + DejaVu Sans Mono, + Bitstream Vera Sans Mono, + Courier New, + monospace; } .grid { @@ -81,7 +88,9 @@ text-decoration: none; border: 1px solid #eaeaea; border-radius: 10px; - transition: color 0.15s ease, border-color 0.15s ease; + transition: + color 0.15s ease, + border-color 0.15s ease; max-width: 300px; } diff --git a/pages-e2e/fixtures/next-12-3-1/styles/globals.css b/pages-e2e/fixtures/next-12-3-1/styles/globals.css index 6b9cea73c..4ab07e25f 100644 --- a/pages-e2e/fixtures/next-12-3-1/styles/globals.css +++ b/pages-e2e/fixtures/next-12-3-1/styles/globals.css @@ -2,8 +2,18 @@ html, body { padding: 0; margin: 0; - font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, - Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; + font-family: + -apple-system, + BlinkMacSystemFont, + Segoe UI, + Roboto, + Oxygen, + Ubuntu, + Cantarell, + Fira Sans, + Droid Sans, + Helvetica Neue, + sans-serif; } a {