vinext 0.0.15 → 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +6 -0
  2. package/dist/cli.js +21 -11
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config/config-matchers.d.ts +13 -7
  5. package/dist/config/config-matchers.d.ts.map +1 -1
  6. package/dist/config/config-matchers.js +18 -9
  7. package/dist/config/config-matchers.js.map +1 -1
  8. package/dist/config/next-config.d.ts +2 -0
  9. package/dist/config/next-config.d.ts.map +1 -1
  10. package/dist/config/next-config.js.map +1 -1
  11. package/dist/deploy.d.ts.map +1 -1
  12. package/dist/deploy.js +3 -1
  13. package/dist/deploy.js.map +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +75 -62
  16. package/dist/index.js.map +1 -1
  17. package/dist/routing/app-router.d.ts.map +1 -1
  18. package/dist/routing/app-router.js +3 -2
  19. package/dist/routing/app-router.js.map +1 -1
  20. package/dist/routing/pages-router.d.ts.map +1 -1
  21. package/dist/routing/pages-router.js +2 -1
  22. package/dist/routing/pages-router.js.map +1 -1
  23. package/dist/server/app-dev-server.d.ts.map +1 -1
  24. package/dist/server/app-dev-server.js +43 -9
  25. package/dist/server/app-dev-server.js.map +1 -1
  26. package/dist/server/middleware.d.ts +23 -1
  27. package/dist/server/middleware.d.ts.map +1 -1
  28. package/dist/server/middleware.js +42 -8
  29. package/dist/server/middleware.js.map +1 -1
  30. package/dist/server/prod-server.js +1 -1
  31. package/dist/server/prod-server.js.map +1 -1
  32. package/dist/shims/fetch-cache.d.ts.map +1 -1
  33. package/dist/shims/fetch-cache.js +73 -41
  34. package/dist/shims/fetch-cache.js.map +1 -1
  35. package/dist/shims/font-google-base.d.ts +68 -0
  36. package/dist/shims/font-google-base.d.ts.map +1 -0
  37. package/dist/shims/font-google-base.js +365 -0
  38. package/dist/shims/font-google-base.js.map +1 -0
  39. package/dist/shims/font-google.d.ts +2 -121
  40. package/dist/shims/font-google.d.ts.map +1 -1
  41. package/dist/shims/font-google.generated.d.ts +1925 -0
  42. package/dist/shims/font-google.generated.d.ts.map +1 -0
  43. package/dist/shims/font-google.generated.js +1928 -0
  44. package/dist/shims/font-google.generated.js.map +1 -0
  45. package/dist/shims/font-google.js +2 -386
  46. package/dist/shims/font-google.js.map +1 -1
  47. package/dist/utils/project.d.ts.map +1 -1
  48. package/dist/utils/project.js +4 -0
  49. package/dist/utils/project.js.map +1 -1
  50. package/package.json +2 -1
package/README.md CHANGED
@@ -535,6 +535,12 @@ vinext has peer dependencies on `react ^19.2.4`, `react-dom ^19.2.4`, and `vite
535
535
 
536
536
  This project is experimental and under active development. Issues and PRs are welcome.
537
537
 
538
+ ### CI
539
+
540
+ When you open a PR, CI (lint, typecheck, Vitest, Playwright E2E) runs automatically. First-time contributors need one manual approval from a maintainer, then subsequent PRs run without intervention.
541
+
542
+ Deploy previews (building and deploying examples to Cloudflare Workers) only run for branches pushed to the main repo. If you're a Cloudflare employee, push your branch to the main repo instead of forking, and previews deploy automatically. For fork PRs, a maintainer can comment `/deploy-preview` to trigger the deploy and post preview URLs.
543
+
538
544
  ### Reporting bugs
539
545
 
540
546
  If something doesn't work with your Next.js app, please file an issue — we want to hear about it.
package/dist/cli.js CHANGED
@@ -19,8 +19,9 @@ import { createRequire } from "node:module";
19
19
  import { execFileSync } from "node:child_process";
20
20
  import { deploy as runDeploy, parseDeployArgs } from "./deploy.js";
21
21
  import { runCheck, formatReport } from "./check.js";
22
- import { init as runInit } from "./init.js";
22
+ import { init as runInit, getReactUpgradeDeps } from "./init.js";
23
23
  import { loadDotenv } from "./config/dotenv.js";
24
+ import { detectPackageManager as _detectPackageManager } from "./utils/project.js";
24
25
  let _viteModule = null;
25
26
  /**
26
27
  * Dynamically load Vite from the project root. Falls back to the bundled
@@ -165,6 +166,18 @@ async function buildApp() {
165
166
  const vite = await loadVite();
166
167
  console.log(`\n vinext build (Vite ${getViteVersion()})\n`);
167
168
  const isApp = hasAppDir();
169
+ // For App Router: upgrade React if needed for react-server-dom-webpack compatibility.
170
+ // Without this, builds with react<19.2.4 produce a Worker that crashes at
171
+ // runtime with "Cannot read properties of undefined (reading 'moduleMap')".
172
+ if (isApp) {
173
+ const reactUpgrade = getReactUpgradeDeps(process.cwd());
174
+ if (reactUpgrade.length > 0) {
175
+ const installCmd = _detectPackageManager(process.cwd()).replace(/ -D$/, "");
176
+ const [pm, ...pmArgs] = installCmd.split(" ");
177
+ console.log(" Upgrading React for RSC compatibility...");
178
+ execFileSync(pm, [...pmArgs, ...reactUpgrade], { cwd: process.cwd(), stdio: "inherit" });
179
+ }
180
+ }
168
181
  if (isApp) {
169
182
  // App Router: use createBuilder for multi-environment RSC builds
170
183
  const config = buildViteConfig();
@@ -172,12 +185,11 @@ async function buildApp() {
172
185
  await builder.buildApp();
173
186
  }
174
187
  else {
175
- // Pages Router: client + SSR builds
176
- const appRoot = process.cwd();
188
+ // Pages Router: client + SSR builds.
189
+ // Use buildViteConfig() so that when a vite.config exists we don't
190
+ // duplicate the vinext() plugin.
177
191
  console.log(" Building client...");
178
- await vite.build({
179
- root: appRoot,
180
- plugins: [vinext()],
192
+ await vite.build(buildViteConfig({
181
193
  build: {
182
194
  outDir: "dist/client",
183
195
  manifest: true,
@@ -188,11 +200,9 @@ async function buildApp() {
188
200
  treeshake: clientTreeshakeConfig,
189
201
  },
190
202
  },
191
- });
203
+ }));
192
204
  console.log(" Building server...");
193
- await vite.build({
194
- root: appRoot,
195
- plugins: [vinext()],
205
+ await vite.build(buildViteConfig({
196
206
  build: {
197
207
  outDir: "dist/server",
198
208
  ssr: "virtual:vinext-server-entry",
@@ -202,7 +212,7 @@ async function buildApp() {
202
212
  },
203
213
  },
204
214
  },
205
- });
215
+ }));
206
216
  }
207
217
  console.log("\n Build complete. Run `vinext start` to start the production server.\n");
208
218
  }
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../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YACxB,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QACH,MAAM;IAER,KAAK,OAAO;QACV,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;YAClB,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QACH,MAAM;IAER,KAAK,MAAM;QACT,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;YACjB,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QACH,MAAM;IAER;QACE,OAAO,CAAC,KAAK,CAAC,wBAAwB,OAAO,IAAI,CAAC,CAAC;QACnD,SAAS,EAAE,CAAC;QACZ,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC","sourcesContent":["#!/usr/bin/env node\n\n/**\n * vinext CLI — drop-in replacement for the `next` command\n *\n * vinext dev Start development server (Vite)\n * vinext build Build for production\n * vinext start Start production server\n * vinext deploy Deploy to Cloudflare Workers\n * vinext lint Run linter (delegates to eslint/oxlint)\n *\n * Automatically configures Vite with the vinext plugin — no vite.config.ts\n * needed for most Next.js apps.\n */\n\nimport vinext, { clientOutputConfig, clientTreeshakeConfig } from \"./index.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport { execFileSync } from \"node:child_process\";\nimport { deploy as runDeploy, parseDeployArgs } from \"./deploy.js\";\nimport { runCheck, formatReport } from \"./check.js\";\nimport { init as runInit } from \"./init.js\";\nimport { loadDotenv } from \"./config/dotenv.js\";\n\n// ─── Resolve Vite from the project root ────────────────────────────────────────\n//\n// When vinext is installed via `bun link` or `npm link`, Node follows the\n// symlink back to the monorepo and resolves `vite` from the monorepo's\n// node_modules — not the project's. This causes dual Vite instances, dual\n// React copies, and plugin resolution failures.\n//\n// To fix this, we resolve Vite dynamically from `process.cwd()` at runtime\n// using `createRequire`. This ensures we always use the project's Vite.\n\ninterface ViteModule {\n createServer: typeof import(\"vite\").createServer;\n build: typeof import(\"vite\").build;\n createBuilder: typeof import(\"vite\").createBuilder;\n version: string;\n}\n\nlet _viteModule: ViteModule | null = null;\n\n/**\n * Dynamically load Vite from the project root. Falls back to the bundled\n * copy if the project doesn't have its own Vite installation.\n */\nasync function loadVite(): Promise<ViteModule> {\n if (_viteModule) return _viteModule;\n\n const projectRoot = process.cwd();\n let vitePath: string;\n\n try {\n // Resolve \"vite\" from the project root, not from vinext's location\n const require = createRequire(path.join(projectRoot, \"package.json\"));\n vitePath = require.resolve(\"vite\");\n } catch {\n // Fallback: use the Vite that ships with vinext (works for non-linked installs)\n vitePath = \"vite\";\n }\n\n // On Windows, absolute paths must be file:// URLs for ESM import().\n // The fallback (\"vite\") is a bare specifier and works as-is.\n const viteUrl = vitePath === \"vite\" ? vitePath : pathToFileURL(vitePath).href;\n const vite = (await import(/* @vite-ignore */ viteUrl)) as ViteModule;\n _viteModule = vite;\n return vite;\n}\n\n/**\n * Get the Vite version string. Returns \"unknown\" before loadVite() is called.\n */\nfunction getViteVersion(): string {\n return _viteModule?.version ?? \"unknown\";\n}\n\nconst VERSION = JSON.parse(\n fs.readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\"),\n).version as string;\n\n// ─── CLI Argument Parsing ──────────────────────────────────────────────────────\n\nconst command = process.argv[2];\nconst rawArgs = process.argv.slice(3);\n\ninterface ParsedArgs {\n port?: number;\n hostname?: string;\n help?: boolean;\n turbopack?: boolean; // accepted for compat, always ignored\n experimental?: boolean; // accepted for compat, always ignored\n}\n\nfunction parseArgs(args: string[]): ParsedArgs {\n const result: ParsedArgs = {};\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === \"--help\" || arg === \"-h\") {\n result.help = true;\n } else if (arg === \"--turbopack\") {\n result.turbopack = true; // no-op, accepted for script compat\n } else if (arg === \"--experimental-https\") {\n result.experimental = true; // no-op\n } else if (arg === \"--port\" || arg === \"-p\") {\n result.port = parseInt(args[++i], 10);\n } else if (arg.startsWith(\"--port=\")) {\n result.port = parseInt(arg.split(\"=\")[1], 10);\n } else if (arg === \"--hostname\" || arg === \"-H\") {\n result.hostname = args[++i];\n } else if (arg.startsWith(\"--hostname=\")) {\n result.hostname = arg.split(\"=\")[1];\n }\n }\n return result;\n}\n\n// ─── Auto-configuration ───────────────────────────────────────────────────────\n\n/**\n * Build the Vite config automatically. If a vite.config.ts exists in the\n * project, Vite will merge our config with it (theirs takes precedence).\n * If there's no vite.config, this provides everything needed.\n */\nfunction hasAppDir(): boolean {\n return (\n fs.existsSync(path.join(process.cwd(), \"app\")) ||\n fs.existsSync(path.join(process.cwd(), \"src\", \"app\"))\n );\n}\n\nfunction hasViteConfig(): boolean {\n return (\n fs.existsSync(path.join(process.cwd(), \"vite.config.ts\")) ||\n fs.existsSync(path.join(process.cwd(), \"vite.config.js\")) ||\n fs.existsSync(path.join(process.cwd(), \"vite.config.mjs\"))\n );\n}\n\nfunction buildViteConfig(overrides: Record<string, unknown> = {}) {\n const hasConfig = hasViteConfig();\n\n // If a vite.config exists, let Vite load it — only set root and overrides.\n // The user's config already has vinext() + rsc() plugins configured.\n // Adding them here too would duplicate the RSC transform (causes\n // \"Identifier has already been declared\" errors in production builds).\n if (hasConfig) {\n return {\n root: process.cwd(),\n ...overrides,\n };\n }\n\n // No vite.config — auto-configure everything.\n // vinext() auto-registers @vitejs/plugin-rsc when app/ is detected,\n // so we only need vinext() in the plugins array.\n const config: Record<string, unknown> = {\n root: process.cwd(),\n configFile: false,\n plugins: [vinext()],\n // Deduplicate React packages to prevent \"Invalid hook call\" errors\n // when vinext is symlinked (bun link / npm link) and both vinext's\n // and the project's node_modules contain React.\n resolve: {\n dedupe: [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ],\n },\n ...overrides,\n };\n\n return config;\n}\n\n// ─── Commands ─────────────────────────────────────────────────────────────────\n\nasync function dev() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"dev\");\n\n loadDotenv({\n root: process.cwd(),\n mode: \"development\",\n });\n\n const vite = await loadVite();\n\n const port = parsed.port ?? 3000;\n const host = parsed.hostname ?? \"localhost\";\n\n console.log(`\\n vinext dev (Vite ${getViteVersion()})\\n`);\n\n const config = buildViteConfig({\n server: { port, host },\n });\n\n const server = await vite.createServer(config);\n await server.listen();\n server.printUrls();\n}\n\nasync function buildApp() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"build\");\n\n loadDotenv({\n root: process.cwd(),\n mode: \"production\",\n });\n\n const vite = await loadVite();\n\n console.log(`\\n vinext build (Vite ${getViteVersion()})\\n`);\n\n const isApp = hasAppDir();\n\n if (isApp) {\n // App Router: use createBuilder for multi-environment RSC builds\n const config = buildViteConfig();\n const builder = await vite.createBuilder(config);\n await builder.buildApp();\n } else {\n // Pages Router: client + SSR builds\n const appRoot = process.cwd();\n\n console.log(\" Building client...\");\n await vite.build({\n root: appRoot,\n plugins: [vinext()],\n build: {\n outDir: \"dist/client\",\n manifest: true,\n ssrManifest: true,\n rollupOptions: {\n input: \"virtual:vinext-client-entry\",\n output: clientOutputConfig,\n treeshake: clientTreeshakeConfig,\n },\n },\n });\n\n console.log(\" Building server...\");\n await vite.build({\n root: appRoot,\n plugins: [vinext()],\n build: {\n outDir: \"dist/server\",\n ssr: \"virtual:vinext-server-entry\",\n rollupOptions: {\n output: {\n entryFileNames: \"entry.js\",\n },\n },\n },\n });\n }\n\n console.log(\"\\n Build complete. Run `vinext start` to start the production server.\\n\");\n}\n\nasync function start() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"start\");\n\n loadDotenv({\n root: process.cwd(),\n mode: \"production\",\n });\n\n const port = parsed.port ?? parseInt(process.env.PORT ?? \"3000\", 10);\n const host = parsed.hostname ?? \"0.0.0.0\";\n\n console.log(`\\n vinext start (port ${port})\\n`);\n\n const { startProdServer } = (await import(\n /* @vite-ignore */ \"./server/prod-server.js\"\n )) as {\n startProdServer: (opts: {\n port: number;\n host: string;\n outDir: string;\n }) => Promise<unknown>;\n };\n\n await startProdServer({\n port,\n host,\n outDir: path.resolve(process.cwd(), \"dist\"),\n });\n}\n\nasync function lint() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"lint\");\n\n console.log(`\\n vinext lint\\n`);\n\n // Try oxlint first (fast), fall back to eslint\n const cwd = process.cwd();\n const hasOxlint = fs.existsSync(path.join(cwd, \"node_modules\", \".bin\", \"oxlint\"));\n const hasEslint = fs.existsSync(path.join(cwd, \"node_modules\", \".bin\", \"eslint\"));\n\n // Check for next lint config (eslint-config-next)\n const hasNextLintConfig =\n fs.existsSync(path.join(cwd, \".eslintrc.json\")) ||\n fs.existsSync(path.join(cwd, \".eslintrc.js\")) ||\n fs.existsSync(path.join(cwd, \".eslintrc.cjs\")) ||\n fs.existsSync(path.join(cwd, \"eslint.config.js\")) ||\n fs.existsSync(path.join(cwd, \"eslint.config.mjs\"));\n\n try {\n if (hasEslint && hasNextLintConfig) {\n console.log(\" Using eslint (with existing config)\\n\");\n execFileSync(\"npx\", [\"eslint\", \".\"], { cwd, stdio: \"inherit\" });\n } else if (hasOxlint) {\n console.log(\" Using oxlint\\n\");\n execFileSync(\"npx\", [\"oxlint\", \".\"], { cwd, stdio: \"inherit\" });\n } else if (hasEslint) {\n console.log(\" Using eslint\\n\");\n execFileSync(\"npx\", [\"eslint\", \".\"], { cwd, stdio: \"inherit\" });\n } else {\n console.log(\n \" No linter found. Install eslint or oxlint:\\n\\n\" +\n \" npm install -D eslint eslint-config-next\\n\" +\n \" # or\\n\" +\n \" npm install -D oxlint\\n\",\n );\n process.exit(1);\n }\n console.log(\"\\n Lint passed.\\n\");\n } catch {\n process.exit(1);\n }\n}\n\nasync function deployCommand() {\n const parsed = parseDeployArgs(rawArgs);\n if (parsed.help) return printHelp(\"deploy\");\n\n await loadVite();\n console.log(`\\n vinext deploy (Vite ${getViteVersion()})\\n`);\n\n await runDeploy({\n root: process.cwd(),\n preview: parsed.preview,\n env: parsed.env,\n skipBuild: parsed.skipBuild,\n dryRun: parsed.dryRun,\n name: parsed.name,\n experimentalTPR: parsed.experimentalTPR,\n tprCoverage: parsed.tprCoverage,\n tprLimit: parsed.tprLimit,\n tprWindow: parsed.tprWindow,\n });\n}\n\nasync function check() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"check\");\n\n const root = process.cwd();\n console.log(`\\n vinext check\\n`);\n console.log(\" Scanning project...\\n\");\n\n const result = runCheck(root);\n console.log(formatReport(result));\n}\n\nasync function initCommand() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"init\");\n\n console.log(`\\n vinext init\\n`);\n\n // Parse init-specific flags\n const port = parsed.port ?? 3001;\n const skipCheck = rawArgs.includes(\"--skip-check\");\n const force = rawArgs.includes(\"--force\");\n\n await runInit({\n root: process.cwd(),\n port,\n skipCheck,\n force,\n });\n}\n\n// ─── Help ─────────────────────────────────────────────────────────────────────\n\nfunction printHelp(cmd?: string) {\n if (cmd === \"dev\") {\n console.log(`\n vinext dev - Start development server\n\n Usage: vinext dev [options]\n\n Options:\n -p, --port <port> Port to listen on (default: 3000)\n -H, --hostname <host> Hostname to bind to (default: localhost)\n --turbopack Accepted for compatibility (no-op, Vite is always used)\n -h, --help Show this help\n`);\n return;\n }\n\n if (cmd === \"build\") {\n console.log(`\n vinext build - Build for production\n\n Usage: vinext build [options]\n\n Automatically detects App Router (app/) or Pages Router (pages/) and\n runs the appropriate multi-environment build via Vite.\n\n Options:\n -h, --help Show this help\n`);\n return;\n }\n\n if (cmd === \"start\") {\n console.log(`\n vinext start - Start production server\n\n Usage: vinext start [options]\n\n Serves the output from \\`vinext build\\`. Supports SSR, static files,\n compression, and all middleware.\n\n Options:\n -p, --port <port> Port to listen on (default: 3000, or PORT env)\n -H, --hostname <host> Hostname to bind to (default: 0.0.0.0)\n -h, --help Show this help\n`);\n return;\n }\n\n if (cmd === \"deploy\") {\n console.log(`\n vinext deploy - Deploy to Cloudflare Workers\n\n Usage: vinext deploy [options]\n\n One-command deployment to Cloudflare Workers. Automatically:\n - Detects App Router or Pages Router\n - Generates wrangler.jsonc, worker/index.ts, vite.config.ts if missing\n - Installs @cloudflare/vite-plugin and wrangler if needed\n - Builds the project with Vite\n - Deploys via wrangler\n\n Options:\n --preview Deploy to preview environment (same as --env preview)\n --env <name> Deploy using wrangler env.<name>\n --name <name> Custom Worker name (default: from package.json)\n --skip-build Skip the build step (use existing dist/)\n --dry-run Generate config files without building or deploying\n -h, --help Show this help\n\n Experimental:\n --experimental-tpr Enable Traffic-aware Pre-Rendering\n --tpr-coverage <pct> Traffic coverage target, 0–100 (default: 90)\n --tpr-limit <count> Hard cap on pages to pre-render (default: 1000)\n --tpr-window <hours> Analytics lookback window in hours (default: 24)\n\n TPR (Traffic-aware Pre-Rendering) uses Cloudflare zone analytics to determine\n which pages get the most traffic and pre-renders them into KV cache during\n deploy. This feature is experimental and must be explicitly enabled. Requires\n a custom domain (zone analytics are unavailable on *.workers.dev) and the\n CLOUDFLARE_API_TOKEN environment variable with Zone.Analytics read permission.\n\n Examples:\n vinext deploy Build and deploy to production\n vinext deploy --preview Deploy to a preview URL\n vinext deploy --env staging Deploy using wrangler env.staging\n vinext deploy --dry-run See what files would be generated\n vinext deploy --name my-app Deploy with a custom Worker name\n vinext deploy --experimental-tpr Enable TPR during deploy\n vinext deploy --experimental-tpr --tpr-coverage 95 Cover 95% of traffic\n vinext deploy --experimental-tpr --tpr-limit 500 Cap at 500 pages\n`);\n return;\n }\n\n if (cmd === \"check\") {\n console.log(`\n vinext check - Scan Next.js app for compatibility\n\n Usage: vinext check [options]\n\n Scans your Next.js project and produces a compatibility report showing\n which imports, config options, libraries, and conventions are supported,\n partially supported, or unsupported by vinext.\n\n Options:\n -h, --help Show this help\n`);\n return;\n }\n\n if (cmd === \"init\") {\n console.log(`\n vinext init - Migrate a Next.js project to run under vinext\n\n Usage: vinext init [options]\n\n One-command migration: installs dependencies, configures ESM,\n generates vite.config.ts, and adds npm scripts. Your Next.js\n setup continues to work alongside vinext.\n\n Options:\n -p, --port <port> Dev server port for the vinext script (default: 3001)\n --skip-check Skip the compatibility check step\n --force Overwrite existing vite.config.ts\n -h, --help Show this help\n\n Examples:\n vinext init Migrate with defaults\n vinext init -p 4000 Use port 4000 for dev:vinext\n vinext init --force Overwrite existing vite.config.ts\n vinext init --skip-check Skip the compatibility report\n`);\n return;\n }\n\n if (cmd === \"lint\") {\n console.log(`\n vinext lint - Run linter\n\n Usage: vinext lint [options]\n\n Delegates to your project's eslint (with eslint-config-next) or oxlint.\n If neither is installed, suggests how to add one.\n\n Options:\n -h, --help Show this help\n`);\n return;\n }\n\n console.log(`\n vinext v${VERSION} - Run Next.js apps on Vite\n\n Usage: vinext <command> [options]\n\n Commands:\n dev Start development server\n build Build for production\n start Start production server\n deploy Deploy to Cloudflare Workers\n init Migrate a Next.js project to vinext\n check Scan Next.js app for compatibility\n lint Run linter\n\n Options:\n -h, --help Show this help\n --version Show version\n\n Examples:\n vinext dev Start dev server on port 3000\n vinext dev -p 4000 Start dev server on port 4000\n vinext build Build for production\n vinext start Start production server\n vinext deploy Deploy to Cloudflare Workers\n vinext init Migrate a Next.js project\n vinext check Check compatibility\n vinext lint Run linter\n\n vinext is a drop-in replacement for the \\`next\\` CLI.\n No vite.config.ts needed — just run \\`vinext dev\\` in your Next.js project.\n`);\n}\n\n// ─── Entry ────────────────────────────────────────────────────────────────────\n\nif (command === \"--version\" || command === \"-v\") {\n console.log(`vinext v${VERSION}`);\n process.exit(0);\n}\n\nif (command === \"--help\" || command === \"-h\" || !command) {\n printHelp();\n if (!command) process.exit(0);\n process.exit(0);\n}\n\nswitch (command) {\n case \"dev\":\n dev().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"build\":\n buildApp().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"start\":\n start().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"deploy\":\n deployCommand().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"init\":\n initCommand().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"check\":\n check().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"lint\":\n lint().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n default:\n console.error(`\\n Unknown command: ${command}\\n`);\n printHelp();\n process.exit(1);\n}\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA;;;;;;;;;;;GAWG;AAEH,OAAO,MAAM,EAAE,EAAE,kBAAkB,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAC/E,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,MAAM,IAAI,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,IAAI,IAAI,OAAO,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,oBAAoB,IAAI,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAmBnF,IAAI,WAA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AI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QACH,MAAM;IAER,KAAK,OAAO;QACV,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;YAClB,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QACH,MAAM;IAER,KAAK,MAAM;QACT,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE;YACjB,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;QACH,MAAM;IAER;QACE,OAAO,CAAC,KAAK,CAAC,wBAAwB,OAAO,IAAI,CAAC,CAAC;QACnD,SAAS,EAAE,CAAC;QACZ,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC","sourcesContent":["#!/usr/bin/env node\n\n/**\n * vinext CLI — drop-in replacement for the `next` command\n *\n * vinext dev Start development server (Vite)\n * vinext build Build for production\n * vinext start Start production server\n * vinext deploy Deploy to Cloudflare Workers\n * vinext lint Run linter (delegates to eslint/oxlint)\n *\n * Automatically configures Vite with the vinext plugin — no vite.config.ts\n * needed for most Next.js apps.\n */\n\nimport vinext, { clientOutputConfig, clientTreeshakeConfig } from \"./index.js\";\nimport path from \"node:path\";\nimport fs from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport { execFileSync } from \"node:child_process\";\nimport { deploy as runDeploy, parseDeployArgs } from \"./deploy.js\";\nimport { runCheck, formatReport } from \"./check.js\";\nimport { init as runInit, getReactUpgradeDeps } from \"./init.js\";\nimport { loadDotenv } from \"./config/dotenv.js\";\nimport { detectPackageManager as _detectPackageManager } from \"./utils/project.js\";\n\n// ─── Resolve Vite from the project root ────────────────────────────────────────\n//\n// When vinext is installed via `bun link` or `npm link`, Node follows the\n// symlink back to the monorepo and resolves `vite` from the monorepo's\n// node_modules — not the project's. This causes dual Vite instances, dual\n// React copies, and plugin resolution failures.\n//\n// To fix this, we resolve Vite dynamically from `process.cwd()` at runtime\n// using `createRequire`. This ensures we always use the project's Vite.\n\ninterface ViteModule {\n createServer: typeof import(\"vite\").createServer;\n build: typeof import(\"vite\").build;\n createBuilder: typeof import(\"vite\").createBuilder;\n version: string;\n}\n\nlet _viteModule: ViteModule | null = null;\n\n/**\n * Dynamically load Vite from the project root. Falls back to the bundled\n * copy if the project doesn't have its own Vite installation.\n */\nasync function loadVite(): Promise<ViteModule> {\n if (_viteModule) return _viteModule;\n\n const projectRoot = process.cwd();\n let vitePath: string;\n\n try {\n // Resolve \"vite\" from the project root, not from vinext's location\n const require = createRequire(path.join(projectRoot, \"package.json\"));\n vitePath = require.resolve(\"vite\");\n } catch {\n // Fallback: use the Vite that ships with vinext (works for non-linked installs)\n vitePath = \"vite\";\n }\n\n // On Windows, absolute paths must be file:// URLs for ESM import().\n // The fallback (\"vite\") is a bare specifier and works as-is.\n const viteUrl = vitePath === \"vite\" ? vitePath : pathToFileURL(vitePath).href;\n const vite = (await import(/* @vite-ignore */ viteUrl)) as ViteModule;\n _viteModule = vite;\n return vite;\n}\n\n/**\n * Get the Vite version string. Returns \"unknown\" before loadVite() is called.\n */\nfunction getViteVersion(): string {\n return _viteModule?.version ?? \"unknown\";\n}\n\nconst VERSION = JSON.parse(\n fs.readFileSync(new URL(\"../package.json\", import.meta.url), \"utf-8\"),\n).version as string;\n\n// ─── CLI Argument Parsing ──────────────────────────────────────────────────────\n\nconst command = process.argv[2];\nconst rawArgs = process.argv.slice(3);\n\ninterface ParsedArgs {\n port?: number;\n hostname?: string;\n help?: boolean;\n turbopack?: boolean; // accepted for compat, always ignored\n experimental?: boolean; // accepted for compat, always ignored\n}\n\nfunction parseArgs(args: string[]): ParsedArgs {\n const result: ParsedArgs = {};\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === \"--help\" || arg === \"-h\") {\n result.help = true;\n } else if (arg === \"--turbopack\") {\n result.turbopack = true; // no-op, accepted for script compat\n } else if (arg === \"--experimental-https\") {\n result.experimental = true; // no-op\n } else if (arg === \"--port\" || arg === \"-p\") {\n result.port = parseInt(args[++i], 10);\n } else if (arg.startsWith(\"--port=\")) {\n result.port = parseInt(arg.split(\"=\")[1], 10);\n } else if (arg === \"--hostname\" || arg === \"-H\") {\n result.hostname = args[++i];\n } else if (arg.startsWith(\"--hostname=\")) {\n result.hostname = arg.split(\"=\")[1];\n }\n }\n return result;\n}\n\n// ─── Auto-configuration ───────────────────────────────────────────────────────\n\n/**\n * Build the Vite config automatically. If a vite.config.ts exists in the\n * project, Vite will merge our config with it (theirs takes precedence).\n * If there's no vite.config, this provides everything needed.\n */\nfunction hasAppDir(): boolean {\n return (\n fs.existsSync(path.join(process.cwd(), \"app\")) ||\n fs.existsSync(path.join(process.cwd(), \"src\", \"app\"))\n );\n}\n\nfunction hasViteConfig(): boolean {\n return (\n fs.existsSync(path.join(process.cwd(), \"vite.config.ts\")) ||\n fs.existsSync(path.join(process.cwd(), \"vite.config.js\")) ||\n fs.existsSync(path.join(process.cwd(), \"vite.config.mjs\"))\n );\n}\n\nfunction buildViteConfig(overrides: Record<string, unknown> = {}) {\n const hasConfig = hasViteConfig();\n\n // If a vite.config exists, let Vite load it — only set root and overrides.\n // The user's config already has vinext() + rsc() plugins configured.\n // Adding them here too would duplicate the RSC transform (causes\n // \"Identifier has already been declared\" errors in production builds).\n if (hasConfig) {\n return {\n root: process.cwd(),\n ...overrides,\n };\n }\n\n // No vite.config — auto-configure everything.\n // vinext() auto-registers @vitejs/plugin-rsc when app/ is detected,\n // so we only need vinext() in the plugins array.\n const config: Record<string, unknown> = {\n root: process.cwd(),\n configFile: false,\n plugins: [vinext()],\n // Deduplicate React packages to prevent \"Invalid hook call\" errors\n // when vinext is symlinked (bun link / npm link) and both vinext's\n // and the project's node_modules contain React.\n resolve: {\n dedupe: [\n \"react\",\n \"react-dom\",\n \"react/jsx-runtime\",\n \"react/jsx-dev-runtime\",\n ],\n },\n ...overrides,\n };\n\n return config;\n}\n\n// ─── Commands ─────────────────────────────────────────────────────────────────\n\nasync function dev() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"dev\");\n\n loadDotenv({\n root: process.cwd(),\n mode: \"development\",\n });\n\n const vite = await loadVite();\n\n const port = parsed.port ?? 3000;\n const host = parsed.hostname ?? \"localhost\";\n\n console.log(`\\n vinext dev (Vite ${getViteVersion()})\\n`);\n\n const config = buildViteConfig({\n server: { port, host },\n });\n\n const server = await vite.createServer(config);\n await server.listen();\n server.printUrls();\n}\n\nasync function buildApp() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"build\");\n\n loadDotenv({\n root: process.cwd(),\n mode: \"production\",\n });\n\n const vite = await loadVite();\n\n console.log(`\\n vinext build (Vite ${getViteVersion()})\\n`);\n\n const isApp = hasAppDir();\n\n // For App Router: upgrade React if needed for react-server-dom-webpack compatibility.\n // Without this, builds with react<19.2.4 produce a Worker that crashes at\n // runtime with \"Cannot read properties of undefined (reading 'moduleMap')\".\n if (isApp) {\n const reactUpgrade = getReactUpgradeDeps(process.cwd());\n if (reactUpgrade.length > 0) {\n const installCmd = _detectPackageManager(process.cwd()).replace(/ -D$/, \"\");\n const [pm, ...pmArgs] = installCmd.split(\" \");\n console.log(\" Upgrading React for RSC compatibility...\");\n execFileSync(pm, [...pmArgs, ...reactUpgrade], { cwd: process.cwd(), stdio: \"inherit\" });\n }\n }\n\n if (isApp) {\n // App Router: use createBuilder for multi-environment RSC builds\n const config = buildViteConfig();\n const builder = await vite.createBuilder(config);\n await builder.buildApp();\n } else {\n // Pages Router: client + SSR builds.\n // Use buildViteConfig() so that when a vite.config exists we don't\n // duplicate the vinext() plugin.\n console.log(\" Building client...\");\n await vite.build(buildViteConfig({\n build: {\n outDir: \"dist/client\",\n manifest: true,\n ssrManifest: true,\n rollupOptions: {\n input: \"virtual:vinext-client-entry\",\n output: clientOutputConfig,\n treeshake: clientTreeshakeConfig,\n },\n },\n }));\n\n console.log(\" Building server...\");\n await vite.build(buildViteConfig({\n build: {\n outDir: \"dist/server\",\n ssr: \"virtual:vinext-server-entry\",\n rollupOptions: {\n output: {\n entryFileNames: \"entry.js\",\n },\n },\n },\n }));\n }\n\n console.log(\"\\n Build complete. Run `vinext start` to start the production server.\\n\");\n}\n\nasync function start() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"start\");\n\n loadDotenv({\n root: process.cwd(),\n mode: \"production\",\n });\n\n const port = parsed.port ?? parseInt(process.env.PORT ?? \"3000\", 10);\n const host = parsed.hostname ?? \"0.0.0.0\";\n\n console.log(`\\n vinext start (port ${port})\\n`);\n\n const { startProdServer } = (await import(\n /* @vite-ignore */ \"./server/prod-server.js\"\n )) as {\n startProdServer: (opts: {\n port: number;\n host: string;\n outDir: string;\n }) => Promise<unknown>;\n };\n\n await startProdServer({\n port,\n host,\n outDir: path.resolve(process.cwd(), \"dist\"),\n });\n}\n\nasync function lint() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"lint\");\n\n console.log(`\\n vinext lint\\n`);\n\n // Try oxlint first (fast), fall back to eslint\n const cwd = process.cwd();\n const hasOxlint = fs.existsSync(path.join(cwd, \"node_modules\", \".bin\", \"oxlint\"));\n const hasEslint = fs.existsSync(path.join(cwd, \"node_modules\", \".bin\", \"eslint\"));\n\n // Check for next lint config (eslint-config-next)\n const hasNextLintConfig =\n fs.existsSync(path.join(cwd, \".eslintrc.json\")) ||\n fs.existsSync(path.join(cwd, \".eslintrc.js\")) ||\n fs.existsSync(path.join(cwd, \".eslintrc.cjs\")) ||\n fs.existsSync(path.join(cwd, \"eslint.config.js\")) ||\n fs.existsSync(path.join(cwd, \"eslint.config.mjs\"));\n\n try {\n if (hasEslint && hasNextLintConfig) {\n console.log(\" Using eslint (with existing config)\\n\");\n execFileSync(\"npx\", [\"eslint\", \".\"], { cwd, stdio: \"inherit\" });\n } else if (hasOxlint) {\n console.log(\" Using oxlint\\n\");\n execFileSync(\"npx\", [\"oxlint\", \".\"], { cwd, stdio: \"inherit\" });\n } else if (hasEslint) {\n console.log(\" Using eslint\\n\");\n execFileSync(\"npx\", [\"eslint\", \".\"], { cwd, stdio: \"inherit\" });\n } else {\n console.log(\n \" No linter found. Install eslint or oxlint:\\n\\n\" +\n \" npm install -D eslint eslint-config-next\\n\" +\n \" # or\\n\" +\n \" npm install -D oxlint\\n\",\n );\n process.exit(1);\n }\n console.log(\"\\n Lint passed.\\n\");\n } catch {\n process.exit(1);\n }\n}\n\nasync function deployCommand() {\n const parsed = parseDeployArgs(rawArgs);\n if (parsed.help) return printHelp(\"deploy\");\n\n await loadVite();\n console.log(`\\n vinext deploy (Vite ${getViteVersion()})\\n`);\n\n await runDeploy({\n root: process.cwd(),\n preview: parsed.preview,\n env: parsed.env,\n skipBuild: parsed.skipBuild,\n dryRun: parsed.dryRun,\n name: parsed.name,\n experimentalTPR: parsed.experimentalTPR,\n tprCoverage: parsed.tprCoverage,\n tprLimit: parsed.tprLimit,\n tprWindow: parsed.tprWindow,\n });\n}\n\nasync function check() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"check\");\n\n const root = process.cwd();\n console.log(`\\n vinext check\\n`);\n console.log(\" Scanning project...\\n\");\n\n const result = runCheck(root);\n console.log(formatReport(result));\n}\n\nasync function initCommand() {\n const parsed = parseArgs(rawArgs);\n if (parsed.help) return printHelp(\"init\");\n\n console.log(`\\n vinext init\\n`);\n\n // Parse init-specific flags\n const port = parsed.port ?? 3001;\n const skipCheck = rawArgs.includes(\"--skip-check\");\n const force = rawArgs.includes(\"--force\");\n\n await runInit({\n root: process.cwd(),\n port,\n skipCheck,\n force,\n });\n}\n\n// ─── Help ─────────────────────────────────────────────────────────────────────\n\nfunction printHelp(cmd?: string) {\n if (cmd === \"dev\") {\n console.log(`\n vinext dev - Start development server\n\n Usage: vinext dev [options]\n\n Options:\n -p, --port <port> Port to listen on (default: 3000)\n -H, --hostname <host> Hostname to bind to (default: localhost)\n --turbopack Accepted for compatibility (no-op, Vite is always used)\n -h, --help Show this help\n`);\n return;\n }\n\n if (cmd === \"build\") {\n console.log(`\n vinext build - Build for production\n\n Usage: vinext build [options]\n\n Automatically detects App Router (app/) or Pages Router (pages/) and\n runs the appropriate multi-environment build via Vite.\n\n Options:\n -h, --help Show this help\n`);\n return;\n }\n\n if (cmd === \"start\") {\n console.log(`\n vinext start - Start production server\n\n Usage: vinext start [options]\n\n Serves the output from \\`vinext build\\`. Supports SSR, static files,\n compression, and all middleware.\n\n Options:\n -p, --port <port> Port to listen on (default: 3000, or PORT env)\n -H, --hostname <host> Hostname to bind to (default: 0.0.0.0)\n -h, --help Show this help\n`);\n return;\n }\n\n if (cmd === \"deploy\") {\n console.log(`\n vinext deploy - Deploy to Cloudflare Workers\n\n Usage: vinext deploy [options]\n\n One-command deployment to Cloudflare Workers. Automatically:\n - Detects App Router or Pages Router\n - Generates wrangler.jsonc, worker/index.ts, vite.config.ts if missing\n - Installs @cloudflare/vite-plugin and wrangler if needed\n - Builds the project with Vite\n - Deploys via wrangler\n\n Options:\n --preview Deploy to preview environment (same as --env preview)\n --env <name> Deploy using wrangler env.<name>\n --name <name> Custom Worker name (default: from package.json)\n --skip-build Skip the build step (use existing dist/)\n --dry-run Generate config files without building or deploying\n -h, --help Show this help\n\n Experimental:\n --experimental-tpr Enable Traffic-aware Pre-Rendering\n --tpr-coverage <pct> Traffic coverage target, 0–100 (default: 90)\n --tpr-limit <count> Hard cap on pages to pre-render (default: 1000)\n --tpr-window <hours> Analytics lookback window in hours (default: 24)\n\n TPR (Traffic-aware Pre-Rendering) uses Cloudflare zone analytics to determine\n which pages get the most traffic and pre-renders them into KV cache during\n deploy. This feature is experimental and must be explicitly enabled. Requires\n a custom domain (zone analytics are unavailable on *.workers.dev) and the\n CLOUDFLARE_API_TOKEN environment variable with Zone.Analytics read permission.\n\n Examples:\n vinext deploy Build and deploy to production\n vinext deploy --preview Deploy to a preview URL\n vinext deploy --env staging Deploy using wrangler env.staging\n vinext deploy --dry-run See what files would be generated\n vinext deploy --name my-app Deploy with a custom Worker name\n vinext deploy --experimental-tpr Enable TPR during deploy\n vinext deploy --experimental-tpr --tpr-coverage 95 Cover 95% of traffic\n vinext deploy --experimental-tpr --tpr-limit 500 Cap at 500 pages\n`);\n return;\n }\n\n if (cmd === \"check\") {\n console.log(`\n vinext check - Scan Next.js app for compatibility\n\n Usage: vinext check [options]\n\n Scans your Next.js project and produces a compatibility report showing\n which imports, config options, libraries, and conventions are supported,\n partially supported, or unsupported by vinext.\n\n Options:\n -h, --help Show this help\n`);\n return;\n }\n\n if (cmd === \"init\") {\n console.log(`\n vinext init - Migrate a Next.js project to run under vinext\n\n Usage: vinext init [options]\n\n One-command migration: installs dependencies, configures ESM,\n generates vite.config.ts, and adds npm scripts. Your Next.js\n setup continues to work alongside vinext.\n\n Options:\n -p, --port <port> Dev server port for the vinext script (default: 3001)\n --skip-check Skip the compatibility check step\n --force Overwrite existing vite.config.ts\n -h, --help Show this help\n\n Examples:\n vinext init Migrate with defaults\n vinext init -p 4000 Use port 4000 for dev:vinext\n vinext init --force Overwrite existing vite.config.ts\n vinext init --skip-check Skip the compatibility report\n`);\n return;\n }\n\n if (cmd === \"lint\") {\n console.log(`\n vinext lint - Run linter\n\n Usage: vinext lint [options]\n\n Delegates to your project's eslint (with eslint-config-next) or oxlint.\n If neither is installed, suggests how to add one.\n\n Options:\n -h, --help Show this help\n`);\n return;\n }\n\n console.log(`\n vinext v${VERSION} - Run Next.js apps on Vite\n\n Usage: vinext <command> [options]\n\n Commands:\n dev Start development server\n build Build for production\n start Start production server\n deploy Deploy to Cloudflare Workers\n init Migrate a Next.js project to vinext\n check Scan Next.js app for compatibility\n lint Run linter\n\n Options:\n -h, --help Show this help\n --version Show version\n\n Examples:\n vinext dev Start dev server on port 3000\n vinext dev -p 4000 Start dev server on port 4000\n vinext build Build for production\n vinext start Start production server\n vinext deploy Deploy to Cloudflare Workers\n vinext init Migrate a Next.js project\n vinext check Check compatibility\n vinext lint Run linter\n\n vinext is a drop-in replacement for the \\`next\\` CLI.\n No vite.config.ts needed — just run \\`vinext dev\\` in your Next.js project.\n`);\n}\n\n// ─── Entry ────────────────────────────────────────────────────────────────────\n\nif (command === \"--version\" || command === \"-v\") {\n console.log(`vinext v${VERSION}`);\n process.exit(0);\n}\n\nif (command === \"--help\" || command === \"-h\" || !command) {\n printHelp();\n if (!command) process.exit(0);\n process.exit(0);\n}\n\nswitch (command) {\n case \"dev\":\n dev().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"build\":\n buildApp().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"start\":\n start().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"deploy\":\n deployCommand().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"init\":\n initCommand().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"check\":\n check().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n case \"lint\":\n lint().catch((e) => {\n console.error(e);\n process.exit(1);\n });\n break;\n\n default:\n console.error(`\\n Unknown command: ${command}\\n`);\n printHelp();\n process.exit(1);\n}\n"]}
@@ -73,10 +73,11 @@ export declare function matchConfigPattern(pathname: string, pattern: string): R
73
73
  * Apply redirect rules from next.config.js.
74
74
  * Returns the redirect info if a redirect was matched, or null.
75
75
  *
76
- * When `ctx` is provided, has/missing conditions on the redirect rules
77
- * are evaluated against the request context (cookies, headers, query, host).
76
+ * `ctx` provides the request context (cookies, headers, query, host) used
77
+ * to evaluate has/missing conditions. Next.js always has request context
78
+ * when evaluating redirects, so this parameter is required.
78
79
  */
79
- export declare function matchRedirect(pathname: string, redirects: NextRedirect[], ctx?: RequestContext): {
80
+ export declare function matchRedirect(pathname: string, redirects: NextRedirect[], ctx: RequestContext): {
80
81
  destination: string;
81
82
  permanent: boolean;
82
83
  } | null;
@@ -84,10 +85,11 @@ export declare function matchRedirect(pathname: string, redirects: NextRedirect[
84
85
  * Apply rewrite rules from next.config.js.
85
86
  * Returns the rewritten URL or null if no rewrite matched.
86
87
  *
87
- * When `ctx` is provided, has/missing conditions on the rewrite rules
88
- * are evaluated against the request context (cookies, headers, query, host).
88
+ * `ctx` provides the request context (cookies, headers, query, host) used
89
+ * to evaluate has/missing conditions. Next.js always has request context
90
+ * when evaluating rewrites, so this parameter is required.
89
91
  */
90
- export declare function matchRewrite(pathname: string, rewrites: NextRewrite[], ctx?: RequestContext): string | null;
92
+ export declare function matchRewrite(pathname: string, rewrites: NextRewrite[], ctx: RequestContext): string | null;
91
93
  /**
92
94
  * Sanitize a redirect/rewrite destination to collapse protocol-relative URLs.
93
95
  *
@@ -119,8 +121,12 @@ export declare function proxyExternalRequest(request: Request, externalUrl: stri
119
121
  /**
120
122
  * Apply custom header rules from next.config.js.
121
123
  * Returns an array of { key, value } pairs to set on the response.
124
+ *
125
+ * `ctx` provides the request context (cookies, headers, query, host) used
126
+ * to evaluate has/missing conditions. Next.js always has request context
127
+ * when evaluating headers, so this parameter is required.
122
128
  */
123
- export declare function matchHeaders(pathname: string, headers: NextHeader[]): Array<{
129
+ export declare function matchHeaders(pathname: string, headers: NextHeader[], ctx: RequestContext): Array<{
124
130
  key: string;
125
131
  value: string;
126
132
  }>;
@@ -1 +1 @@
1
- {"version":3,"file":"config-matchers.d.ts","sourceRoot":"","sources":["../../src/config/config-matchers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAc5F;;;;;;;;;GASG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAsGpD;AAED;;;;;GAKG;AACH,wBAAgB,UAAU,CAAC,OAA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IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC,CAevC"}
@@ -455,15 +455,15 @@ export function matchConfigPattern(pathname, pattern) {
455
455
  * Apply redirect rules from next.config.js.
456
456
  * Returns the redirect info if a redirect was matched, or null.
457
457
  *
458
- * When `ctx` is provided, has/missing conditions on the redirect rules
459
- * are evaluated against the request context (cookies, headers, query, host).
458
+ * `ctx` provides the request context (cookies, headers, query, host) used
459
+ * to evaluate has/missing conditions. Next.js always has request context
460
+ * when evaluating redirects, so this parameter is required.
460
461
  */
461
462
  export function matchRedirect(pathname, redirects, ctx) {
462
463
  for (const redirect of redirects) {
463
464
  const params = matchConfigPattern(pathname, redirect.source);
464
465
  if (params) {
465
- // Check has/missing conditions if present and context is available
466
- if (ctx && (redirect.has || redirect.missing)) {
466
+ if (redirect.has || redirect.missing) {
467
467
  if (!checkHasConditions(redirect.has, redirect.missing, ctx)) {
468
468
  continue;
469
469
  }
@@ -487,15 +487,15 @@ export function matchRedirect(pathname, redirects, ctx) {
487
487
  * Apply rewrite rules from next.config.js.
488
488
  * Returns the rewritten URL or null if no rewrite matched.
489
489
  *
490
- * When `ctx` is provided, has/missing conditions on the rewrite rules
491
- * are evaluated against the request context (cookies, headers, query, host).
490
+ * `ctx` provides the request context (cookies, headers, query, host) used
491
+ * to evaluate has/missing conditions. Next.js always has request context
492
+ * when evaluating rewrites, so this parameter is required.
492
493
  */
493
494
  export function matchRewrite(pathname, rewrites, ctx) {
494
495
  for (const rewrite of rewrites) {
495
496
  const params = matchConfigPattern(pathname, rewrite.source);
496
497
  if (params) {
497
- // Check has/missing conditions if present and context is available
498
- if (ctx && (rewrite.has || rewrite.missing)) {
498
+ if (rewrite.has || rewrite.missing) {
499
499
  if (!checkHasConditions(rewrite.has, rewrite.missing, ctx)) {
500
500
  continue;
501
501
  }
@@ -635,13 +635,22 @@ export async function proxyExternalRequest(request, externalUrl) {
635
635
  /**
636
636
  * Apply custom header rules from next.config.js.
637
637
  * Returns an array of { key, value } pairs to set on the response.
638
+ *
639
+ * `ctx` provides the request context (cookies, headers, query, host) used
640
+ * to evaluate has/missing conditions. Next.js always has request context
641
+ * when evaluating headers, so this parameter is required.
638
642
  */
639
- export function matchHeaders(pathname, headers) {
643
+ export function matchHeaders(pathname, headers, ctx) {
640
644
  const result = [];
641
645
  for (const rule of headers) {
642
646
  const escaped = escapeHeaderSource(rule.source);
643
647
  const sourceRegex = safeRegExp("^" + escaped + "$");
644
648
  if (sourceRegex && sourceRegex.test(pathname)) {
649
+ if (rule.has || rule.missing) {
650
+ if (!checkHasConditions(rule.has, rule.missing, ctx)) {
651
+ continue;
652
+ }
653
+ }
645
654
  result.push(...rule.headers);
646
655
  }
647
656
  }
@@ -1 +1 @@
1
- {"version":3,"file":"config-matchers.js","sourceRoot":"","sources":["../../src/config/config-matchers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,uEAAuE;AACvE,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACjC,YAAY;IACZ,YAAY;IACZ,oBAAoB;IACpB,qBAAqB;IACrB,IAAI;IACJ,UAAU;IACV,mBAAmB;IACnB,SAAS;CACV,CAAC,CAAC;AAEH;;;;;;;;;GASG;AACH,MAAM,UAAU,WAAW,CAAC,OAAe;IACzC,sEAAsE;IACtE,uBAAuB;IACvB,MAAM,iBAAiB,GAAc,EAAE,CAAC;IACxC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,CAAC,GAAG,CAAC,CAAC;IAEV,OAAO,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;QAC1B,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;QAEtB,0BAA0B;QAC1B,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC;YAChB,CAAC,IAAI,CAAC,CAAC;YACP,SAAS;QACX,CAAC;QAED,qEAAqE;QACrE,IAAI,EAAE,KAAK,GAAG,EAAE,CAAC;YACf,CAAC,EAAE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AI,WAAW,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC9C,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Config pattern matching and rule application utilities.\n *\n * Shared between the dev server (index.ts) and the production server\n * (prod-server.ts) so both apply next.config.js rules identically.\n */\n\nimport type { NextRedirect, NextRewrite, NextHeader, HasCondition } from \"./next-config.js\";\n\n/** Hop-by-hop headers that should not be forwarded through a proxy. */\nconst HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/**\n * Detect regex patterns vulnerable to catastrophic backtracking (ReDoS).\n *\n * Uses a lightweight heuristic: scans the pattern string for nested quantifiers\n * (a quantifier applied to a group that itself contains a quantifier). This\n * catches the most common pathological patterns like `(a+)+`, `(.*)*`,\n * `([^/]+)+`, `(a|a+)+` without needing a full regex parser.\n *\n * Returns true if the pattern appears safe, false if it's potentially dangerous.\n */\nexport function isSafeRegex(pattern: string): boolean {\n // Track parenthesis nesting depth and whether we've seen a quantifier\n // at each depth level.\n const quantifierAtDepth: boolean[] = [];\n let depth = 0;\n let i = 0;\n\n while (i < pattern.length) {\n const ch = pattern[i];\n\n // Skip escaped characters\n if (ch === \"\\\\\") {\n i += 2;\n continue;\n }\n\n // Skip character classes [...] — quantifiers inside them are literal\n if (ch === \"[\") {\n i++;\n while (i < pattern.length && pattern[i] !== \"]\") {\n if (pattern[i] === \"\\\\\") i++; // skip escaped char in class\n i++;\n }\n i++; // skip closing ]\n continue;\n }\n\n if (ch === \"(\") {\n depth++;\n // Initialize: no quantifier seen yet at this new depth\n if (quantifierAtDepth.length <= depth) {\n quantifierAtDepth.push(false);\n } else {\n quantifierAtDepth[depth] = false;\n }\n i++;\n continue;\n }\n\n if (ch === \")\") {\n const hadQuantifier = depth > 0 && quantifierAtDepth[depth];\n if (depth > 0) depth--;\n\n // Look ahead for a quantifier on this group: +, *, {n,m}\n // Note: '?' after ')' means \"zero or one\" which does NOT cause catastrophic\n // backtracking — it only allows 2 paths (match/skip), not exponential.\n // Only unbounded repetition (+, *, {n,}) on a group with inner quantifiers is dangerous.\n const next = pattern[i + 1];\n if (next === \"+\" || next === \"*\" || next === \"{\") {\n if (hadQuantifier) {\n // Nested quantifier detected: quantifier on a group that contains a quantifier\n return false;\n }\n // Mark the enclosing depth as having a quantifier\n if (depth >= 0 && depth < quantifierAtDepth.length) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n // Detect quantifiers: +, *, ?, {n,m}\n // '?' is a quantifier (optional) unless it follows another quantifier (+, *, ?, })\n // in which case it's a non-greedy modifier.\n if (ch === \"+\" || ch === \"*\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i++;\n continue;\n }\n\n if (ch === \"?\") {\n // '?' after +, *, ?, or } is a non-greedy modifier, not a quantifier\n const prev = i > 0 ? pattern[i - 1] : \"\";\n if (prev !== \"+\" && prev !== \"*\" && prev !== \"?\" && prev !== \"}\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n if (ch === \"{\") {\n // Check if this is a quantifier {n}, {n,}, {n,m}\n let j = i + 1;\n while (j < pattern.length && /[\\d,]/.test(pattern[j])) j++;\n if (j < pattern.length && pattern[j] === \"}\" && j > i + 1) {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i = j + 1;\n continue;\n }\n }\n\n i++;\n }\n\n return true;\n}\n\n/**\n * Compile a regex pattern safely. Returns the compiled RegExp or null if the\n * pattern is invalid or vulnerable to ReDoS.\n *\n * Logs a warning when a pattern is rejected so developers can fix their config.\n */\nexport function safeRegExp(pattern: string, flags?: string): RegExp | null {\n if (!isSafeRegex(pattern)) {\n console.warn(\n `[vinext] Ignoring potentially unsafe regex pattern (ReDoS risk): ${pattern}\\n` +\n ` Patterns with nested quantifiers (e.g. (a+)+) can cause catastrophic backtracking.\\n` +\n ` Simplify the pattern to avoid nested repetition.`,\n );\n return null;\n }\n try {\n return new RegExp(pattern, flags);\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a Next.js header/rewrite/redirect source pattern into a regex string.\n *\n * Regex groups in the source (e.g. `(\\d+)`) are extracted first, the remaining\n * text is escaped/converted in a **single pass** (avoiding chained `.replace()`\n * which CodeQL flags as incomplete sanitization), then groups are restored.\n */\nexport function escapeHeaderSource(source: string): string {\n // Sentinel character for group placeholders. Uses a Unicode private-use-area\n // codepoint that will never appear in real source patterns.\n const S = \"\\uE000\";\n\n // Step 1: extract regex groups and replace with numbered placeholders.\n const groups: string[] = [];\n const withPlaceholders = source.replace(/\\(([^)]+)\\)/g, (_m, inner) => {\n groups.push(inner);\n return `${S}G${groups.length - 1}${S}`;\n });\n\n // Step 2: single-pass conversion of the placeholder-bearing string.\n // Match named params (:[\\w-]+), sentinel group placeholders, metacharacters, and literal text.\n // The regex uses non-overlapping alternatives to avoid backtracking:\n // :[\\w-]+ — named parameter (constraint sentinel is checked procedurally;\n // param names may contain hyphens, e.g. :auth-method)\n // sentinel group — standalone regex group placeholder\n // [.+?*] — single metachar to escape/convert\n // [^.+?*:\\uE000]+ — literal text (excludes all chars that start other alternatives)\n let result = \"\";\n const re = new RegExp(\n `${S}G(\\\\d+)${S}|:[\\\\w-]+|[.+?*]|[^.+?*:\\\\uE000]+`, // lgtm[js/redos] — alternatives are non-overlapping\n \"g\",\n );\n let m: RegExpExecArray | null;\n while ((m = re.exec(withPlaceholders)) !== null) {\n if (m[1] !== undefined) {\n // Standalone regex group — restore as-is\n result += `(${groups[Number(m[1])]})`;\n } else if (m[0].startsWith(\":\")) {\n // Named parameter — check if followed by a constraint group placeholder\n const afterParam = withPlaceholders.slice(re.lastIndex);\n const constraintMatch = afterParam.match(new RegExp(`^${S}G(\\\\d+)${S}`));\n if (constraintMatch) {\n // :param(constraint) — use the constraint as the capture group\n re.lastIndex += constraintMatch[0].length;\n result += `(${groups[Number(constraintMatch[1])]})`;\n } else {\n // Plain named parameter → match one segment\n result += \"[^/]+\";\n }\n } else {\n switch (m[0]) {\n case \".\": result += \"\\\\.\"; break;\n case \"+\": result += \"\\\\+\"; break;\n case \"?\": result += \"\\\\?\"; break;\n case \"*\": result += \".*\"; break;\n default: result += m[0]; break;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Request context needed for evaluating has/missing conditions.\n * Callers extract the relevant parts from the incoming Request.\n */\nexport interface RequestContext {\n headers: Headers;\n cookies: Record<string, string>;\n query: URLSearchParams;\n host: string;\n}\n\n/**\n * Parse a Cookie header string into a key-value record.\n */\nexport function parseCookies(cookieHeader: string | null): Record<string, string> {\n if (!cookieHeader) return {};\n const cookies: Record<string, string> = {};\n for (const part of cookieHeader.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim();\n if (key) cookies[key] = value;\n }\n return cookies;\n}\n\n/**\n * Build a RequestContext from a Web Request object.\n */\nexport function requestContextFromRequest(request: Request): RequestContext {\n const url = new URL(request.url);\n return {\n headers: request.headers,\n cookies: parseCookies(request.headers.get(\"cookie\")),\n query: url.searchParams,\n host: request.headers.get(\"host\") ?? url.host,\n };\n}\n\n/**\n * Check a single has/missing condition against request context.\n * Returns true if the condition is satisfied.\n */\nfunction checkSingleCondition(condition: HasCondition, ctx: RequestContext): boolean {\n switch (condition.type) {\n case \"header\": {\n const headerValue = ctx.headers.get(condition.key);\n if (headerValue === null) return false;\n if (condition.value !== undefined) {\n const re = safeRegExp(condition.value);\n if (re) return re.test(headerValue);\n return headerValue === condition.value;\n }\n return true; // Key exists, no value constraint\n }\n case \"cookie\": {\n const cookieValue = ctx.cookies[condition.key];\n if (cookieValue === undefined) return false;\n if (condition.value !== undefined) {\n const re = safeRegExp(condition.value);\n if (re) return re.test(cookieValue);\n return cookieValue === condition.value;\n }\n return true;\n }\n case \"query\": {\n const queryValue = ctx.query.get(condition.key);\n if (queryValue === null) return false;\n if (condition.value !== undefined) {\n const re = safeRegExp(condition.value);\n if (re) return re.test(queryValue);\n return queryValue === condition.value;\n }\n return true;\n }\n case \"host\": {\n if (condition.value !== undefined) {\n const re = safeRegExp(condition.value);\n if (re) return re.test(ctx.host);\n return ctx.host === condition.value;\n }\n return ctx.host === condition.key;\n }\n default:\n return false;\n }\n}\n\n/**\n * Check all has/missing conditions for a config rule.\n * Returns true if the rule should be applied (all has conditions pass, all missing conditions pass).\n *\n * - has: every condition must match (the request must have it)\n * - missing: every condition must NOT match (the request must not have it)\n */\nexport function checkHasConditions(\n has: HasCondition[] | undefined,\n missing: HasCondition[] | undefined,\n ctx: RequestContext,\n): boolean {\n if (has) {\n for (const condition of has) {\n if (!checkSingleCondition(condition, ctx)) return false;\n }\n }\n if (missing) {\n for (const condition of missing) {\n if (checkSingleCondition(condition, ctx)) return false;\n }\n }\n return true;\n}\n\n/**\n * If the current position in `str` starts with a parenthesized group, consume\n * it and advance `re.lastIndex` past the closing `)`. Returns the group\n * contents or null if no group is present.\n */\nfunction extractConstraint(str: string, re: RegExp): string | null {\n if (str[re.lastIndex] !== \"(\") return null;\n const start = re.lastIndex + 1;\n let depth = 1;\n let i = start;\n while (i < str.length && depth > 0) {\n if (str[i] === \"(\") depth++;\n else if (str[i] === \")\") depth--;\n i++;\n }\n if (depth !== 0) return null;\n re.lastIndex = i;\n return str.slice(start, i - 1);\n}\n\n/**\n * Match a Next.js config pattern (from redirects/rewrites sources) against a pathname.\n * Returns matched params or null.\n *\n * Supports:\n * :param - matches a single path segment\n * :param* - matches zero or more segments (catch-all)\n * :param+ - matches one or more segments\n * (regex) - inline regex patterns in the source\n * :param(constraint) - named param with inline regex constraint\n */\nexport function matchConfigPattern(\n pathname: string,\n pattern: string,\n): Record<string, string> | null {\n // If the pattern contains regex groups like (\\d+) or (.*), use regex matching.\n // Also enter this branch when a catch-all parameter (:param* or :param+) is\n // followed by a literal suffix (e.g. \"/:path*.md\"). Without this, the suffix\n // pattern falls through to the simple segment matcher which incorrectly treats\n // the whole segment (\":path*.md\") as a named parameter and matches everything.\n if (\n pattern.includes(\"(\") ||\n pattern.includes(\"\\\\\") ||\n /:[\\w-]+[*+][^/]/.test(pattern)\n ) {\n try {\n // Param names may contain hyphens (e.g. :auth-method, :sign-in).\n const paramNames: string[] = [];\n // Single-pass conversion with procedural suffix handling. The tokenizer\n // matches only simple, non-overlapping tokens; quantifier/constraint\n // suffixes after :param are consumed procedurally to avoid polynomial\n // backtracking in the regex engine.\n let regexStr = \"\";\n const tokenRe = /:([\\w-]+)|[.]|[^:.]+/g; // lgtm[js/redos] — alternatives are non-overlapping (`:` and `.` excluded from `[^:.]+`)\n let tok: RegExpExecArray | null;\n while ((tok = tokenRe.exec(pattern)) !== null) {\n if (tok[1] !== undefined) {\n const name = tok[1];\n const rest = pattern.slice(tokenRe.lastIndex);\n // Check for quantifier (* or +) with optional constraint\n if (rest.startsWith(\"*\") || rest.startsWith(\"+\")) {\n const quantifier = rest[0];\n tokenRe.lastIndex += 1;\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n if (constraint !== null) {\n regexStr += `(${constraint})`;\n } else {\n regexStr += quantifier === \"*\" ? \"(.*)\" : \"(.+)\";\n }\n } else {\n // Check for inline constraint without quantifier\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n regexStr += constraint !== null ? `(${constraint})` : \"([^/]+)\";\n }\n } else if (tok[0] === \".\") {\n regexStr += \"\\\\.\";\n } else {\n regexStr += tok[0];\n }\n }\n const re = safeRegExp(\"^\" + regexStr + \"$\");\n if (!re) return null;\n const match = re.exec(pathname);\n if (!match) return null;\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < paramNames.length; i++) {\n params[paramNames[i]] = match[i + 1] ?? \"\";\n }\n return params;\n } catch {\n // Fall through to segment-based matching\n }\n }\n\n // Check for catch-all patterns (:param* or :param+) without regex groups\n // Param names may contain hyphens (e.g. :sign-in*, :sign-up+).\n const catchAllMatch = pattern.match(/:([\\w-]+)(\\*|\\+)$/);\n if (catchAllMatch) {\n const prefix = pattern.slice(0, pattern.lastIndexOf(\":\"));\n const paramName = catchAllMatch[1];\n const isPlus = catchAllMatch[2] === \"+\";\n\n if (!pathname.startsWith(prefix.replace(/\\/$/, \"\"))) return null;\n\n const rest = pathname.slice(prefix.replace(/\\/$/, \"\").length);\n if (isPlus && (!rest || rest === \"/\")) return null;\n let restValue = rest.startsWith(\"/\") ? rest.slice(1) : rest;\n // NOTE: Do NOT decodeURIComponent here. The pathname is already decoded at\n // the request entry point. Decoding again would produce incorrect param values.\n return { [paramName]: restValue };\n }\n\n // Simple segment-based matching for exact patterns and :param\n const parts = pattern.split(\"/\");\n const pathParts = pathname.split(\"/\");\n\n if (parts.length !== pathParts.length) return null;\n\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < parts.length; i++) {\n if (parts[i].startsWith(\":\")) {\n params[parts[i].slice(1)] = pathParts[i];\n } else if (parts[i] !== pathParts[i]) {\n return null;\n }\n }\n return params;\n}\n\n/**\n * Apply redirect rules from next.config.js.\n * Returns the redirect info if a redirect was matched, or null.\n *\n * When `ctx` is provided, has/missing conditions on the redirect rules\n * are evaluated against the request context (cookies, headers, query, host).\n */\nexport function matchRedirect(\n pathname: string,\n redirects: NextRedirect[],\n ctx?: RequestContext,\n): { destination: string; permanent: boolean } | null {\n for (const redirect of redirects) {\n const params = matchConfigPattern(pathname, redirect.source);\n if (params) {\n // Check has/missing conditions if present and context is available\n if (ctx && (redirect.has || redirect.missing)) {\n if (!checkHasConditions(redirect.has, redirect.missing, ctx)) {\n continue;\n }\n }\n let dest = redirect.destination;\n for (const [key, value] of Object.entries(params)) {\n // Replace :param*, :param+, and :param forms in the destination.\n // The catch-all suffixes (* and +) must be stripped along with the param name.\n dest = dest.replace(`:${key}*`, value);\n dest = dest.replace(`:${key}+`, value);\n dest = dest.replace(`:${key}`, value);\n }\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n dest = sanitizeDestination(dest);\n return { destination: dest, permanent: redirect.permanent };\n }\n }\n return null;\n}\n\n/**\n * Apply rewrite rules from next.config.js.\n * Returns the rewritten URL or null if no rewrite matched.\n *\n * When `ctx` is provided, has/missing conditions on the rewrite rules\n * are evaluated against the request context (cookies, headers, query, host).\n */\nexport function matchRewrite(\n pathname: string,\n rewrites: NextRewrite[],\n ctx?: RequestContext,\n): string | null {\n for (const rewrite of rewrites) {\n const params = matchConfigPattern(pathname, rewrite.source);\n if (params) {\n // Check has/missing conditions if present and context is available\n if (ctx && (rewrite.has || rewrite.missing)) {\n if (!checkHasConditions(rewrite.has, rewrite.missing, ctx)) {\n continue;\n }\n }\n let dest = rewrite.destination;\n for (const [key, value] of Object.entries(params)) {\n // Replace :param*, :param+, and :param forms in the destination.\n // The catch-all suffixes (* and +) must be stripped along with the param name.\n dest = dest.replace(`:${key}*`, value);\n dest = dest.replace(`:${key}+`, value);\n dest = dest.replace(`:${key}`, value);\n }\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n dest = sanitizeDestination(dest);\n return dest;\n }\n }\n return null;\n}\n\n/**\n * Sanitize a redirect/rewrite destination to collapse protocol-relative URLs.\n *\n * After parameter substitution, a destination like `/:path*` can become\n * `//evil.com` if the catch-all captured a decoded `%2F` (`/evil.com`).\n * Browsers interpret `//evil.com` as a protocol-relative URL, redirecting\n * users off-site.\n *\n * This function collapses any leading double (or more) slashes to a single\n * slash for non-external (relative) destinations.\n */\nexport function sanitizeDestination(dest: string): string {\n // External URLs (http://, https://) are intentional — don't touch them\n if (dest.startsWith(\"http://\") || dest.startsWith(\"https://\")) {\n return dest;\n }\n // Normalize leading backslashes to forward slashes. Browsers interpret\n // backslash as forward slash in URL contexts, so \"\\/evil.com\" becomes\n // \"//evil.com\" (protocol-relative redirect). Replace any mix of leading\n // slashes and backslashes with a single forward slash.\n dest = dest.replace(/^[\\\\/]+/, \"/\");\n return dest;\n}\n\n/**\n * Check if a URL is external (absolute URL or protocol-relative).\n * Detects any URL scheme (http:, https:, data:, javascript:, blob:, etc.)\n * per RFC 3986, plus protocol-relative URLs (//).\n */\nexport function isExternalUrl(url: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith(\"//\");\n}\n\n/**\n * Proxy an incoming request to an external URL and return the upstream response.\n *\n * Used for external rewrites (e.g. `/ph/:path*` → `https://us.i.posthog.com/:path*`).\n * Next.js handles these as server-side reverse proxies, forwarding the request\n * method, headers, and body to the external destination.\n *\n * Works in all runtimes (Node.js, Cloudflare Workers) via the standard fetch() API.\n */\nexport async function proxyExternalRequest(\n request: Request,\n externalUrl: string,\n): Promise<Response> {\n // Build the full external URL, preserving query parameters from the original request\n const originalUrl = new URL(request.url);\n const targetUrl = new URL(externalUrl);\n\n // If the rewrite destination already has query params, merge them.\n // Destination params take precedence — original request params are only added\n // when the destination doesn't already specify that key.\n for (const [key, value] of originalUrl.searchParams) {\n if (!targetUrl.searchParams.has(key)) {\n targetUrl.searchParams.set(key, value);\n }\n }\n\n // Forward the request with appropriate headers\n const headers = new Headers(request.headers);\n // Set Host to the external target (required for correct routing)\n headers.set(\"host\", targetUrl.host);\n // Remove headers that should not be forwarded to external services\n headers.delete(\"connection\");\n // Strip credentials and internal headers to prevent leaking auth tokens,\n // session cookies, and middleware internals to third-party origins.\n headers.delete(\"cookie\");\n headers.delete(\"authorization\");\n headers.delete(\"x-api-key\");\n headers.delete(\"proxy-authorization\");\n const keysToDelete: string[] = [];\n for (const key of headers.keys()) {\n if (key.startsWith(\"x-middleware-\")) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n headers.delete(key);\n }\n\n const method = request.method;\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n const init: RequestInit & { duplex?: string } = {\n method,\n headers,\n redirect: \"manual\", // Don't follow redirects — pass them through to the client\n };\n\n if (hasBody && request.body) {\n init.body = request.body;\n init.duplex = \"half\";\n }\n\n // Enforce a timeout so slow/unresponsive upstreams don't hold connections\n // open indefinitely (DoS amplification risk on Node.js dev/prod servers).\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 30_000);\n let upstreamResponse: Response;\n try {\n upstreamResponse = await fetch(targetUrl.href, { ...init, signal: controller.signal });\n } catch (e: any) {\n if (e?.name === \"AbortError\") {\n console.error(\"[vinext] External rewrite proxy timeout:\", targetUrl.href);\n return new Response(\"Gateway Timeout\", { status: 504 });\n }\n console.error(\"[vinext] External rewrite proxy error:\", e);\n return new Response(\"Bad Gateway\", { status: 502 });\n } finally {\n clearTimeout(timeout);\n }\n\n // Build the response to return to the client.\n // Copy all upstream headers except hop-by-hop headers.\n const responseHeaders = new Headers();\n upstreamResponse.headers.forEach((value, key) => {\n if (!HOP_BY_HOP_HEADERS.has(key.toLowerCase())) {\n responseHeaders.append(key, value);\n }\n });\n\n return new Response(upstreamResponse.body, {\n status: upstreamResponse.status,\n statusText: upstreamResponse.statusText,\n headers: responseHeaders,\n });\n}\n\n/**\n * Apply custom header rules from next.config.js.\n * Returns an array of { key, value } pairs to set on the response.\n */\nexport function matchHeaders(\n pathname: string,\n headers: NextHeader[],\n): Array<{ key: string; value: string }> {\n const result: Array<{ key: string; value: string }> = [];\n for (const rule of headers) {\n const escaped = escapeHeaderSource(rule.source);\n const sourceRegex = safeRegExp(\"^\" + escaped + \"$\");\n if (sourceRegex && sourceRegex.test(pathname)) {\n result.push(...rule.headers);\n }\n }\n return result;\n}\n"]}
1
+ {"version":3,"file":"config-matchers.js","sourceRoot":"","sources":["../../src/config/config-matchers.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,uEAAuE;AACvE,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACjC,YAAY;IACZ,YAAY;IACZ,oBAAoB;IACpB,qBAAqB;IACrB,IAAI;IACJ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B,CAAC,IAAI,EAAE;QACzC,MAAM,EAAE,gBAAgB,CAAC,MAAM;QAC/B,UAAU,EAAE,gBAAgB,CAAC,UAAU;QACvC,OAAO,EAAE,eAAe;KACzB,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAC1B,QAAgB,EAChB,OAAqB,EACrB,GAAmB;IAEnB,MAAM,MAAM,GAA0C,EAAE,CAAC;IACzD,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;QAC3B,MAAM,OAAO,GAAG,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAChD,MAAM,WAAW,GAAG,UAAU,CAAC,GAAG,GAAG,OAAO,GAAG,GAAG,CAAC,CAAC;QACpD,IAAI,WAAW,IAAI,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC9C,IAAI,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;gBAC7B,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;oBACrD,SAAS;gBACX,CAAC;YACH,CAAC;YACD,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC;QAC/B,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * Config pattern matching and rule application utilities.\n *\n * Shared between the dev server (index.ts) and the production server\n * (prod-server.ts) so both apply next.config.js rules identically.\n */\n\nimport type { NextRedirect, NextRewrite, NextHeader, HasCondition } from \"./next-config.js\";\n\n/** Hop-by-hop headers that should not be forwarded through a proxy. */\nconst HOP_BY_HOP_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailers\",\n \"transfer-encoding\",\n \"upgrade\",\n]);\n\n/**\n * Detect regex patterns vulnerable to catastrophic backtracking (ReDoS).\n *\n * Uses a lightweight heuristic: scans the pattern string for nested quantifiers\n * (a quantifier applied to a group that itself contains a quantifier). This\n * catches the most common pathological patterns like `(a+)+`, `(.*)*`,\n * `([^/]+)+`, `(a|a+)+` without needing a full regex parser.\n *\n * Returns true if the pattern appears safe, false if it's potentially dangerous.\n */\nexport function isSafeRegex(pattern: string): boolean {\n // Track parenthesis nesting depth and whether we've seen a quantifier\n // at each depth level.\n const quantifierAtDepth: boolean[] = [];\n let depth = 0;\n let i = 0;\n\n while (i < pattern.length) {\n const ch = pattern[i];\n\n // Skip escaped characters\n if (ch === \"\\\\\") {\n i += 2;\n continue;\n }\n\n // Skip character classes [...] — quantifiers inside them are literal\n if (ch === \"[\") {\n i++;\n while (i < pattern.length && pattern[i] !== \"]\") {\n if (pattern[i] === \"\\\\\") i++; // skip escaped char in class\n i++;\n }\n i++; // skip closing ]\n continue;\n }\n\n if (ch === \"(\") {\n depth++;\n // Initialize: no quantifier seen yet at this new depth\n if (quantifierAtDepth.length <= depth) {\n quantifierAtDepth.push(false);\n } else {\n quantifierAtDepth[depth] = false;\n }\n i++;\n continue;\n }\n\n if (ch === \")\") {\n const hadQuantifier = depth > 0 && quantifierAtDepth[depth];\n if (depth > 0) depth--;\n\n // Look ahead for a quantifier on this group: +, *, {n,m}\n // Note: '?' after ')' means \"zero or one\" which does NOT cause catastrophic\n // backtracking — it only allows 2 paths (match/skip), not exponential.\n // Only unbounded repetition (+, *, {n,}) on a group with inner quantifiers is dangerous.\n const next = pattern[i + 1];\n if (next === \"+\" || next === \"*\" || next === \"{\") {\n if (hadQuantifier) {\n // Nested quantifier detected: quantifier on a group that contains a quantifier\n return false;\n }\n // Mark the enclosing depth as having a quantifier\n if (depth >= 0 && depth < quantifierAtDepth.length) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n // Detect quantifiers: +, *, ?, {n,m}\n // '?' is a quantifier (optional) unless it follows another quantifier (+, *, ?, })\n // in which case it's a non-greedy modifier.\n if (ch === \"+\" || ch === \"*\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i++;\n continue;\n }\n\n if (ch === \"?\") {\n // '?' after +, *, ?, or } is a non-greedy modifier, not a quantifier\n const prev = i > 0 ? pattern[i - 1] : \"\";\n if (prev !== \"+\" && prev !== \"*\" && prev !== \"?\" && prev !== \"}\") {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n }\n i++;\n continue;\n }\n\n if (ch === \"{\") {\n // Check if this is a quantifier {n}, {n,}, {n,m}\n let j = i + 1;\n while (j < pattern.length && /[\\d,]/.test(pattern[j])) j++;\n if (j < pattern.length && pattern[j] === \"}\" && j > i + 1) {\n if (depth > 0) {\n quantifierAtDepth[depth] = true;\n }\n i = j + 1;\n continue;\n }\n }\n\n i++;\n }\n\n return true;\n}\n\n/**\n * Compile a regex pattern safely. Returns the compiled RegExp or null if the\n * pattern is invalid or vulnerable to ReDoS.\n *\n * Logs a warning when a pattern is rejected so developers can fix their config.\n */\nexport function safeRegExp(pattern: string, flags?: string): RegExp | null {\n if (!isSafeRegex(pattern)) {\n console.warn(\n `[vinext] Ignoring potentially unsafe regex pattern (ReDoS risk): ${pattern}\\n` +\n ` Patterns with nested quantifiers (e.g. (a+)+) can cause catastrophic backtracking.\\n` +\n ` Simplify the pattern to avoid nested repetition.`,\n );\n return null;\n }\n try {\n return new RegExp(pattern, flags);\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a Next.js header/rewrite/redirect source pattern into a regex string.\n *\n * Regex groups in the source (e.g. `(\\d+)`) are extracted first, the remaining\n * text is escaped/converted in a **single pass** (avoiding chained `.replace()`\n * which CodeQL flags as incomplete sanitization), then groups are restored.\n */\nexport function escapeHeaderSource(source: string): string {\n // Sentinel character for group placeholders. Uses a Unicode private-use-area\n // codepoint that will never appear in real source patterns.\n const S = \"\\uE000\";\n\n // Step 1: extract regex groups and replace with numbered placeholders.\n const groups: string[] = [];\n const withPlaceholders = source.replace(/\\(([^)]+)\\)/g, (_m, inner) => {\n groups.push(inner);\n return `${S}G${groups.length - 1}${S}`;\n });\n\n // Step 2: single-pass conversion of the placeholder-bearing string.\n // Match named params (:[\\w-]+), sentinel group placeholders, metacharacters, and literal text.\n // The regex uses non-overlapping alternatives to avoid backtracking:\n // :[\\w-]+ — named parameter (constraint sentinel is checked procedurally;\n // param names may contain hyphens, e.g. :auth-method)\n // sentinel group — standalone regex group placeholder\n // [.+?*] — single metachar to escape/convert\n // [^.+?*:\\uE000]+ — literal text (excludes all chars that start other alternatives)\n let result = \"\";\n const re = new RegExp(\n `${S}G(\\\\d+)${S}|:[\\\\w-]+|[.+?*]|[^.+?*:\\\\uE000]+`, // lgtm[js/redos] — alternatives are non-overlapping\n \"g\",\n );\n let m: RegExpExecArray | null;\n while ((m = re.exec(withPlaceholders)) !== null) {\n if (m[1] !== undefined) {\n // Standalone regex group — restore as-is\n result += `(${groups[Number(m[1])]})`;\n } else if (m[0].startsWith(\":\")) {\n // Named parameter — check if followed by a constraint group placeholder\n const afterParam = withPlaceholders.slice(re.lastIndex);\n const constraintMatch = afterParam.match(new RegExp(`^${S}G(\\\\d+)${S}`));\n if (constraintMatch) {\n // :param(constraint) — use the constraint as the capture group\n re.lastIndex += constraintMatch[0].length;\n result += `(${groups[Number(constraintMatch[1])]})`;\n } else {\n // Plain named parameter → match one segment\n result += \"[^/]+\";\n }\n } else {\n switch (m[0]) {\n case \".\": result += \"\\\\.\"; break;\n case \"+\": result += \"\\\\+\"; break;\n case \"?\": result += \"\\\\?\"; break;\n case \"*\": result += \".*\"; break;\n default: result += m[0]; break;\n }\n }\n }\n\n return result;\n}\n\n/**\n * Request context needed for evaluating has/missing conditions.\n * Callers extract the relevant parts from the incoming Request.\n */\nexport interface RequestContext {\n headers: Headers;\n cookies: Record<string, string>;\n query: URLSearchParams;\n host: string;\n}\n\n/**\n * Parse a Cookie header string into a key-value record.\n */\nexport function parseCookies(cookieHeader: string | null): Record<string, string> {\n if (!cookieHeader) return {};\n const cookies: Record<string, string> = {};\n for (const part of cookieHeader.split(\";\")) {\n const eq = part.indexOf(\"=\");\n if (eq === -1) continue;\n const key = part.slice(0, eq).trim();\n const value = part.slice(eq + 1).trim();\n if (key) cookies[key] = value;\n }\n return cookies;\n}\n\n/**\n * Build a RequestContext from a Web Request object.\n */\nexport function requestContextFromRequest(request: Request): RequestContext {\n const url = new URL(request.url);\n return {\n headers: request.headers,\n cookies: parseCookies(request.headers.get(\"cookie\")),\n query: url.searchParams,\n host: request.headers.get(\"host\") ?? url.host,\n };\n}\n\n/**\n * Check a single has/missing condition against request context.\n * Returns true if the condition is satisfied.\n */\nfunction checkSingleCondition(condition: HasCondition, ctx: RequestContext): boolean {\n switch (condition.type) {\n case \"header\": {\n const headerValue = ctx.headers.get(condition.key);\n if (headerValue === null) return false;\n if (condition.value !== undefined) {\n const re = safeRegExp(condition.value);\n if (re) return re.test(headerValue);\n return headerValue === condition.value;\n }\n return true; // Key exists, no value constraint\n }\n case \"cookie\": {\n const cookieValue = ctx.cookies[condition.key];\n if (cookieValue === undefined) return false;\n if (condition.value !== undefined) {\n const re = safeRegExp(condition.value);\n if (re) return re.test(cookieValue);\n return cookieValue === condition.value;\n }\n return true;\n }\n case \"query\": {\n const queryValue = ctx.query.get(condition.key);\n if (queryValue === null) return false;\n if (condition.value !== undefined) {\n const re = safeRegExp(condition.value);\n if (re) return re.test(queryValue);\n return queryValue === condition.value;\n }\n return true;\n }\n case \"host\": {\n if (condition.value !== undefined) {\n const re = safeRegExp(condition.value);\n if (re) return re.test(ctx.host);\n return ctx.host === condition.value;\n }\n return ctx.host === condition.key;\n }\n default:\n return false;\n }\n}\n\n/**\n * Check all has/missing conditions for a config rule.\n * Returns true if the rule should be applied (all has conditions pass, all missing conditions pass).\n *\n * - has: every condition must match (the request must have it)\n * - missing: every condition must NOT match (the request must not have it)\n */\nexport function checkHasConditions(\n has: HasCondition[] | undefined,\n missing: HasCondition[] | undefined,\n ctx: RequestContext,\n): boolean {\n if (has) {\n for (const condition of has) {\n if (!checkSingleCondition(condition, ctx)) return false;\n }\n }\n if (missing) {\n for (const condition of missing) {\n if (checkSingleCondition(condition, ctx)) return false;\n }\n }\n return true;\n}\n\n/**\n * If the current position in `str` starts with a parenthesized group, consume\n * it and advance `re.lastIndex` past the closing `)`. Returns the group\n * contents or null if no group is present.\n */\nfunction extractConstraint(str: string, re: RegExp): string | null {\n if (str[re.lastIndex] !== \"(\") return null;\n const start = re.lastIndex + 1;\n let depth = 1;\n let i = start;\n while (i < str.length && depth > 0) {\n if (str[i] === \"(\") depth++;\n else if (str[i] === \")\") depth--;\n i++;\n }\n if (depth !== 0) return null;\n re.lastIndex = i;\n return str.slice(start, i - 1);\n}\n\n/**\n * Match a Next.js config pattern (from redirects/rewrites sources) against a pathname.\n * Returns matched params or null.\n *\n * Supports:\n * :param - matches a single path segment\n * :param* - matches zero or more segments (catch-all)\n * :param+ - matches one or more segments\n * (regex) - inline regex patterns in the source\n * :param(constraint) - named param with inline regex constraint\n */\nexport function matchConfigPattern(\n pathname: string,\n pattern: string,\n): Record<string, string> | null {\n // If the pattern contains regex groups like (\\d+) or (.*), use regex matching.\n // Also enter this branch when a catch-all parameter (:param* or :param+) is\n // followed by a literal suffix (e.g. \"/:path*.md\"). Without this, the suffix\n // pattern falls through to the simple segment matcher which incorrectly treats\n // the whole segment (\":path*.md\") as a named parameter and matches everything.\n if (\n pattern.includes(\"(\") ||\n pattern.includes(\"\\\\\") ||\n /:[\\w-]+[*+][^/]/.test(pattern)\n ) {\n try {\n // Param names may contain hyphens (e.g. :auth-method, :sign-in).\n const paramNames: string[] = [];\n // Single-pass conversion with procedural suffix handling. The tokenizer\n // matches only simple, non-overlapping tokens; quantifier/constraint\n // suffixes after :param are consumed procedurally to avoid polynomial\n // backtracking in the regex engine.\n let regexStr = \"\";\n const tokenRe = /:([\\w-]+)|[.]|[^:.]+/g; // lgtm[js/redos] — alternatives are non-overlapping (`:` and `.` excluded from `[^:.]+`)\n let tok: RegExpExecArray | null;\n while ((tok = tokenRe.exec(pattern)) !== null) {\n if (tok[1] !== undefined) {\n const name = tok[1];\n const rest = pattern.slice(tokenRe.lastIndex);\n // Check for quantifier (* or +) with optional constraint\n if (rest.startsWith(\"*\") || rest.startsWith(\"+\")) {\n const quantifier = rest[0];\n tokenRe.lastIndex += 1;\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n if (constraint !== null) {\n regexStr += `(${constraint})`;\n } else {\n regexStr += quantifier === \"*\" ? \"(.*)\" : \"(.+)\";\n }\n } else {\n // Check for inline constraint without quantifier\n const constraint = extractConstraint(pattern, tokenRe);\n paramNames.push(name);\n regexStr += constraint !== null ? `(${constraint})` : \"([^/]+)\";\n }\n } else if (tok[0] === \".\") {\n regexStr += \"\\\\.\";\n } else {\n regexStr += tok[0];\n }\n }\n const re = safeRegExp(\"^\" + regexStr + \"$\");\n if (!re) return null;\n const match = re.exec(pathname);\n if (!match) return null;\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < paramNames.length; i++) {\n params[paramNames[i]] = match[i + 1] ?? \"\";\n }\n return params;\n } catch {\n // Fall through to segment-based matching\n }\n }\n\n // Check for catch-all patterns (:param* or :param+) without regex groups\n // Param names may contain hyphens (e.g. :sign-in*, :sign-up+).\n const catchAllMatch = pattern.match(/:([\\w-]+)(\\*|\\+)$/);\n if (catchAllMatch) {\n const prefix = pattern.slice(0, pattern.lastIndexOf(\":\"));\n const paramName = catchAllMatch[1];\n const isPlus = catchAllMatch[2] === \"+\";\n\n if (!pathname.startsWith(prefix.replace(/\\/$/, \"\"))) return null;\n\n const rest = pathname.slice(prefix.replace(/\\/$/, \"\").length);\n if (isPlus && (!rest || rest === \"/\")) return null;\n let restValue = rest.startsWith(\"/\") ? rest.slice(1) : rest;\n // NOTE: Do NOT decodeURIComponent here. The pathname is already decoded at\n // the request entry point. Decoding again would produce incorrect param values.\n return { [paramName]: restValue };\n }\n\n // Simple segment-based matching for exact patterns and :param\n const parts = pattern.split(\"/\");\n const pathParts = pathname.split(\"/\");\n\n if (parts.length !== pathParts.length) return null;\n\n const params: Record<string, string> = Object.create(null);\n for (let i = 0; i < parts.length; i++) {\n if (parts[i].startsWith(\":\")) {\n params[parts[i].slice(1)] = pathParts[i];\n } else if (parts[i] !== pathParts[i]) {\n return null;\n }\n }\n return params;\n}\n\n/**\n * Apply redirect rules from next.config.js.\n * Returns the redirect info if a redirect was matched, or null.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating redirects, so this parameter is required.\n */\nexport function matchRedirect(\n pathname: string,\n redirects: NextRedirect[],\n ctx: RequestContext,\n): { destination: string; permanent: boolean } | null {\n for (const redirect of redirects) {\n const params = matchConfigPattern(pathname, redirect.source);\n if (params) {\n if (redirect.has || redirect.missing) {\n if (!checkHasConditions(redirect.has, redirect.missing, ctx)) {\n continue;\n }\n }\n let dest = redirect.destination;\n for (const [key, value] of Object.entries(params)) {\n // Replace :param*, :param+, and :param forms in the destination.\n // The catch-all suffixes (* and +) must be stripped along with the param name.\n dest = dest.replace(`:${key}*`, value);\n dest = dest.replace(`:${key}+`, value);\n dest = dest.replace(`:${key}`, value);\n }\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n dest = sanitizeDestination(dest);\n return { destination: dest, permanent: redirect.permanent };\n }\n }\n return null;\n}\n\n/**\n * Apply rewrite rules from next.config.js.\n * Returns the rewritten URL or null if no rewrite matched.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating rewrites, so this parameter is required.\n */\nexport function matchRewrite(\n pathname: string,\n rewrites: NextRewrite[],\n ctx: RequestContext,\n): string | null {\n for (const rewrite of rewrites) {\n const params = matchConfigPattern(pathname, rewrite.source);\n if (params) {\n if (rewrite.has || rewrite.missing) {\n if (!checkHasConditions(rewrite.has, rewrite.missing, ctx)) {\n continue;\n }\n }\n let dest = rewrite.destination;\n for (const [key, value] of Object.entries(params)) {\n // Replace :param*, :param+, and :param forms in the destination.\n // The catch-all suffixes (* and +) must be stripped along with the param name.\n dest = dest.replace(`:${key}*`, value);\n dest = dest.replace(`:${key}+`, value);\n dest = dest.replace(`:${key}`, value);\n }\n // Collapse protocol-relative URLs (e.g. //evil.com from decoded %2F in catch-all params).\n dest = sanitizeDestination(dest);\n return dest;\n }\n }\n return null;\n}\n\n/**\n * Sanitize a redirect/rewrite destination to collapse protocol-relative URLs.\n *\n * After parameter substitution, a destination like `/:path*` can become\n * `//evil.com` if the catch-all captured a decoded `%2F` (`/evil.com`).\n * Browsers interpret `//evil.com` as a protocol-relative URL, redirecting\n * users off-site.\n *\n * This function collapses any leading double (or more) slashes to a single\n * slash for non-external (relative) destinations.\n */\nexport function sanitizeDestination(dest: string): string {\n // External URLs (http://, https://) are intentional — don't touch them\n if (dest.startsWith(\"http://\") || dest.startsWith(\"https://\")) {\n return dest;\n }\n // Normalize leading backslashes to forward slashes. Browsers interpret\n // backslash as forward slash in URL contexts, so \"\\/evil.com\" becomes\n // \"//evil.com\" (protocol-relative redirect). Replace any mix of leading\n // slashes and backslashes with a single forward slash.\n dest = dest.replace(/^[\\\\/]+/, \"/\");\n return dest;\n}\n\n/**\n * Check if a URL is external (absolute URL or protocol-relative).\n * Detects any URL scheme (http:, https:, data:, javascript:, blob:, etc.)\n * per RFC 3986, plus protocol-relative URLs (//).\n */\nexport function isExternalUrl(url: string): boolean {\n return /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith(\"//\");\n}\n\n/**\n * Proxy an incoming request to an external URL and return the upstream response.\n *\n * Used for external rewrites (e.g. `/ph/:path*` → `https://us.i.posthog.com/:path*`).\n * Next.js handles these as server-side reverse proxies, forwarding the request\n * method, headers, and body to the external destination.\n *\n * Works in all runtimes (Node.js, Cloudflare Workers) via the standard fetch() API.\n */\nexport async function proxyExternalRequest(\n request: Request,\n externalUrl: string,\n): Promise<Response> {\n // Build the full external URL, preserving query parameters from the original request\n const originalUrl = new URL(request.url);\n const targetUrl = new URL(externalUrl);\n\n // If the rewrite destination already has query params, merge them.\n // Destination params take precedence — original request params are only added\n // when the destination doesn't already specify that key.\n for (const [key, value] of originalUrl.searchParams) {\n if (!targetUrl.searchParams.has(key)) {\n targetUrl.searchParams.set(key, value);\n }\n }\n\n // Forward the request with appropriate headers\n const headers = new Headers(request.headers);\n // Set Host to the external target (required for correct routing)\n headers.set(\"host\", targetUrl.host);\n // Remove headers that should not be forwarded to external services\n headers.delete(\"connection\");\n // Strip credentials and internal headers to prevent leaking auth tokens,\n // session cookies, and middleware internals to third-party origins.\n headers.delete(\"cookie\");\n headers.delete(\"authorization\");\n headers.delete(\"x-api-key\");\n headers.delete(\"proxy-authorization\");\n const keysToDelete: string[] = [];\n for (const key of headers.keys()) {\n if (key.startsWith(\"x-middleware-\")) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n headers.delete(key);\n }\n\n const method = request.method;\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n const init: RequestInit & { duplex?: string } = {\n method,\n headers,\n redirect: \"manual\", // Don't follow redirects — pass them through to the client\n };\n\n if (hasBody && request.body) {\n init.body = request.body;\n init.duplex = \"half\";\n }\n\n // Enforce a timeout so slow/unresponsive upstreams don't hold connections\n // open indefinitely (DoS amplification risk on Node.js dev/prod servers).\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 30_000);\n let upstreamResponse: Response;\n try {\n upstreamResponse = await fetch(targetUrl.href, { ...init, signal: controller.signal });\n } catch (e: any) {\n if (e?.name === \"AbortError\") {\n console.error(\"[vinext] External rewrite proxy timeout:\", targetUrl.href);\n return new Response(\"Gateway Timeout\", { status: 504 });\n }\n console.error(\"[vinext] External rewrite proxy error:\", e);\n return new Response(\"Bad Gateway\", { status: 502 });\n } finally {\n clearTimeout(timeout);\n }\n\n // Build the response to return to the client.\n // Copy all upstream headers except hop-by-hop headers.\n const responseHeaders = new Headers();\n upstreamResponse.headers.forEach((value, key) => {\n if (!HOP_BY_HOP_HEADERS.has(key.toLowerCase())) {\n responseHeaders.append(key, value);\n }\n });\n\n return new Response(upstreamResponse.body, {\n status: upstreamResponse.status,\n statusText: upstreamResponse.statusText,\n headers: responseHeaders,\n });\n}\n\n/**\n * Apply custom header rules from next.config.js.\n * Returns an array of { key, value } pairs to set on the response.\n *\n * `ctx` provides the request context (cookies, headers, query, host) used\n * to evaluate has/missing conditions. Next.js always has request context\n * when evaluating headers, so this parameter is required.\n */\nexport function matchHeaders(\n pathname: string,\n headers: NextHeader[],\n ctx: RequestContext,\n): Array<{ key: string; value: string }> {\n const result: Array<{ key: string; value: string }> = [];\n for (const rule of headers) {\n const escaped = escapeHeaderSource(rule.source);\n const sourceRegex = safeRegExp(\"^\" + escaped + \"$\");\n if (sourceRegex && sourceRegex.test(pathname)) {\n if (rule.has || rule.missing) {\n if (!checkHasConditions(rule.has, rule.missing, ctx)) {\n continue;\n }\n }\n result.push(...rule.headers);\n }\n }\n return result;\n}\n"]}
@@ -18,6 +18,8 @@ export interface NextRewrite {
18
18
  }
19
19
  export interface NextHeader {
20
20
  source: string;
21
+ has?: HasCondition[];
22
+ missing?: HasCondition[];
21
23
  headers: Array<{
22
24
  key: string;
23
25
  value: string;