@ngrok/app-server 0.3.3 → 0.3.5

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 (70) hide show
  1. package/README.md +14 -10
  2. package/dist/brotli-only-DrA29Ecw.js +97 -0
  3. package/dist/brotli-only-DrA29Ecw.js.map +1 -0
  4. package/dist/cli.js +3 -3
  5. package/dist/compress-CO0Nwc8x.js +386 -0
  6. package/dist/compress-CO0Nwc8x.js.map +1 -0
  7. package/dist/{compression-7_gToa8R.js → compression-CT2mWlKM.js} +9 -2
  8. package/dist/compression-CT2mWlKM.js.map +1 -0
  9. package/dist/{create-server-jMl2ltHD.js → create-server-C_90R50y.js} +54 -33
  10. package/dist/{create-server-jMl2ltHD.js.map → create-server-C_90R50y.js.map} +1 -1
  11. package/dist/{create-server-D4-nVOVJ.d.ts → create-server-kxyhCdhv.d.ts} +3 -3
  12. package/dist/{entry-D9H4LA9c.js → entry-65IESBSA.js} +5 -4
  13. package/dist/{entry-D9H4LA9c.js.map → entry-65IESBSA.js.map} +1 -1
  14. package/dist/{entry-BPrgE_6K.d.ts → entry-CNL4OsEn.d.ts} +3 -3
  15. package/dist/{index-Db7dspq6.d.ts → index-B8LsM6Mh.d.ts} +21 -1
  16. package/dist/index.d.ts +13 -12
  17. package/dist/index.js +4 -4
  18. package/dist/{load-entry-D7r0mjEp.js → load-entry-svVuPIFq.js} +4 -4
  19. package/dist/{load-entry-D7r0mjEp.js.map → load-entry-svVuPIFq.js.map} +1 -1
  20. package/dist/{log-BP6xXXZl.js → log-C8LGQ23s.js} +29 -2
  21. package/dist/log-C8LGQ23s.js.map +1 -0
  22. package/dist/{node-tBVQPjQv.js → node-Bgzhwix0.js} +2 -2
  23. package/dist/{node-tBVQPjQv.js.map → node-Bgzhwix0.js.map} +1 -1
  24. package/dist/{node-C1qudLs_.js → node-DFI5TjTk.js} +6 -5
  25. package/dist/{node-C1qudLs_.js.map → node-DFI5TjTk.js.map} +1 -1
  26. package/dist/node-vite.d.ts +1 -1
  27. package/dist/node.d.ts +1 -1
  28. package/dist/node.js +2 -2
  29. package/dist/react-router-vite.d.ts +1 -1
  30. package/dist/react-router.d.ts +1 -1
  31. package/dist/react-router.js +1 -1
  32. package/dist/{response-edge-Bc1-C_Cx.js → response-edge-D3CAjukJ.js} +2 -2
  33. package/dist/{response-edge-Bc1-C_Cx.js.map → response-edge-D3CAjukJ.js.map} +1 -1
  34. package/dist/{response-writer-B7FoJjEE.js → response-writer-5SOKsW3C.js} +4 -4
  35. package/dist/response-writer-5SOKsW3C.js.map +1 -0
  36. package/dist/{script-hashes-C6hQ5XnP.js → script-hashes-CU7P9oZU.js} +2 -2
  37. package/dist/{script-hashes-C6hQ5XnP.js.map → script-hashes-CU7P9oZU.js.map} +1 -1
  38. package/dist/{serve-E0hSGe6_.js → serve-DKoZxZj4.js} +2 -2
  39. package/dist/{serve-E0hSGe6_.js.map → serve-DKoZxZj4.js.map} +1 -1
  40. package/dist/{start-CifYPRq1.js → start-3_WlRLdK.js} +64 -9
  41. package/dist/start-3_WlRLdK.js.map +1 -0
  42. package/dist/{static-files-Beju9riB.js → static-files-C2ea8KQ6.js} +11 -3
  43. package/dist/static-files-C2ea8KQ6.js.map +1 -0
  44. package/dist/tanstack-start-vite.d.ts +1 -1
  45. package/dist/tanstack-start.d.ts +2 -2
  46. package/dist/{tcp-Dd1Mt6sN.js → tcp-CKMCT9RP.js} +2 -2
  47. package/dist/{tcp-Dd1Mt6sN.js.map → tcp-CKMCT9RP.js.map} +1 -1
  48. package/dist/testing.d.ts +2 -2
  49. package/dist/testing.js +4 -4
  50. package/dist/{trailing-slash-CFSv_Gzx.d.ts → trailing-slash-DeOUxMYo.d.ts} +2 -2
  51. package/dist/{types-j29vspx_.d.ts → types-BKJxtIuj.d.ts} +10 -3
  52. package/dist/vercel-vite.d.ts +1 -1
  53. package/dist/vercel-vite.js +24 -4
  54. package/dist/vercel-vite.js.map +1 -1
  55. package/dist/vercel.d.ts +4 -3
  56. package/dist/vercel.js +8 -6
  57. package/dist/vercel.js.map +1 -1
  58. package/dist/{vite-BDREIgiH.js → vite-DPiSKHDn.js} +139 -33
  59. package/dist/vite-DPiSKHDn.js.map +1 -0
  60. package/dist/vite.d.ts +1 -1
  61. package/dist/vite.js +1 -1
  62. package/package.json +2 -1
  63. package/dist/compression-7_gToa8R.js.map +0 -1
  64. package/dist/gzip-Doi4wqjX.js +0 -294
  65. package/dist/gzip-Doi4wqjX.js.map +0 -1
  66. package/dist/log-BP6xXXZl.js.map +0 -1
  67. package/dist/response-writer-B7FoJjEE.js.map +0 -1
  68. package/dist/start-CifYPRq1.js.map +0 -1
  69. package/dist/static-files-Beju9riB.js.map +0 -1
  70. package/dist/vite-BDREIgiH.js.map +0 -1
@@ -194,10 +194,15 @@ type HostRuntime = {
194
194
  /** The storage for {@link requestContext}. Without it, `requestContext()` gives `undefined`. */
195
195
  storage?: RequestStore;
196
196
  /**
197
- * Gzips a byte stream and flushes after each chunk. Without it,
198
- * `streamingCompress` sends each response as it is.
197
+ * Gzips a byte stream and flushes after each chunk. Without it and
198
+ * `brotli`, `streamingCompress` sends each response as it is.
199
199
  */
200
200
  gzip?: (source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>;
201
+ /**
202
+ * Compresses a byte stream with brotli and flushes after each chunk.
203
+ * `streamingCompress` uses it for a client that prefers brotli to gzip.
204
+ */
205
+ brotli?: (source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>;
201
206
  lifecycle?: Lifecycle;
202
207
  };
203
208
  /**
@@ -320,6 +325,8 @@ type SetupInfo = {
320
325
  contentTypes: Readonly<Record<string, string>>;
321
326
  /** The host's gzip stream, when it has one. */
322
327
  gzip: ((source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>) | undefined;
328
+ /** The host's brotli stream, when it has one. */
329
+ brotli?: ((source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>) | undefined;
323
330
  logger: LogSink;
324
331
  } & ({
325
332
  mode: "production";
@@ -403,4 +410,4 @@ type ListenerStartOptions = {
403
410
  trustForwardedProto?: boolean;
404
411
  };
405
412
  export { SetupInfo as C, ResponseEdge as E, ServerBindings as S, StaticFiles as T, RequestContext as _, FrameworkRuntime as a, ResponseHeaders as b, HostRuntime as c, ListenerBindings as d, ListenerStartOptions as f, Plugin as g, Mode as h, FileInfo as i, Lifecycle as l, LogSink as m, ByteRange as n, FrameworkRuntimeFactory as o, LogLevel as p, FetchHandler as r, HeaderHook as s, AppServerEnv as t, Listener as u, RequestLogger as v, StartedListener as w, SentResponse as x, RequestStore as y };
406
- //# sourceMappingURL=types-j29vspx_.d.ts.map
413
+ //# sourceMappingURL=types-BKJxtIuj.d.ts.map
@@ -1,4 +1,4 @@
1
- import { r as HostBuild } from "./index-Db7dspq6.js";
1
+ import { r as HostBuild } from "./index-B8LsM6Mh.js";
2
2
  /** Options for {@link vercel}. */
3
3
  export type VercelOptions = {
4
4
  /**
@@ -1,4 +1,6 @@
1
- import { r as hasDotSegment } from "./static-files-Beju9riB.js";
1
+ import { r as copyName } from "./compression-CT2mWlKM.js";
2
+ import { r as hasDotSegment } from "./static-files-C2ea8KQ6.js";
3
+ import { t as BROTLI_ONLY_LIST } from "./brotli-only-DrA29Ecw.js";
2
4
  import { copyFileSync, cpSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
5
  import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
4
6
  import { fileURLToPath } from "node:url";
@@ -214,11 +216,29 @@ function writeOutput({ root, clientDirectory, entryFile, assetsPath }, { cdnPath
214
216
  };
215
217
  const functionDirectory = join(output, "functions/index.func");
216
218
  const isCdnFile = (file) => prefixes.some((prefix) => `/${posix$1(file)}`.startsWith(prefix));
217
- for (const file of filesUnder(clientDirectory)) {
219
+ const clientFiles = filesUnder(clientDirectory);
220
+ const listed = new Set(clientFiles);
221
+ /** The file of each brotli copy that the function keeps, with the size of the file. */
222
+ const brotliOnly = {};
223
+ /**
224
+ * Whether the function drops `file`, a file or a gzip copy, because the
225
+ * brotli copy of its file takes its place. Why: the function then holds one
226
+ * copy of each text file, not three. Each browser accepts brotli, and the
227
+ * CDN compresses the decompressed file for a client that does not.
228
+ */
229
+ const brotliCopyOnly = (file) => {
230
+ const name = basename(file);
231
+ const original = name.startsWith(".") ? /^\.(?<name>.+)\.gz$/u.exec(name)?.groups?.name : name;
232
+ return original != null && listed.has(join(dirname(file), original)) && listed.has(join(dirname(file), copyName(original, "br")));
233
+ };
234
+ for (const file of clientFiles) {
218
235
  const from = join(clientDirectory, file);
219
- if (!isCdnFile(file)) copyFile(from, join(functionDirectory, fromRoot(from)));
220
- else if (!hasDotSegment(`/${posix$1(file)}`)) copyFile(from, join(output, "static", file));
236
+ if (!isCdnFile(file)) {
237
+ if (!brotliCopyOnly(file)) copyFile(from, join(functionDirectory, fromRoot(from)));
238
+ else if (!basename(file).startsWith(".")) brotliOnly[`/${posix$1(file)}`] = statSync(from).size;
239
+ } else if (!hasDotSegment(`/${posix$1(file)}`)) copyFile(from, join(output, "static", file));
221
240
  }
241
+ if (Object.keys(brotliOnly).length > 0) writeFileSync(join(functionDirectory, fromRoot(clientDirectory), BROTLI_ONLY_LIST), JSON.stringify(brotliOnly));
222
242
  const serverDirectory = dirname(entryFile);
223
243
  const functionFile = join(serverDirectory, FUNCTION_FILE);
224
244
  cpSync(serverDirectory, join(functionDirectory, fromRoot(serverDirectory)), {
@@ -1 +1 @@
1
- {"version":3,"file":"vercel-vite.js","names":["posix"],"sources":["../src/vercel/vite.ts"],"sourcesContent":["import { execFileSync } from \"node:child_process\";\nimport {\n\tcopyFileSync,\n\tcpSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { hasDotSegment } from \"../core/static-files.js\";\nimport type { HostBuild, HostOutput } from \"../vite/index.js\";\nimport type { CdnPageReport, PagesReport } from \"./pages.js\";\n\n/** Options for {@link vercel}. */\nexport type VercelOptions = {\n\t/**\n\t * More URL path prefixes of the client build that Vercel's CDN serves,\n\t * such as `[\"/blog-assets/\"]`. Each starts and ends with `/`. The URL path\n\t * of Vite's `build.assetsDir`, `/assets/` by default, is always one. Their\n\t * files skip the pipeline, and the function does not carry them.\n\t */\n\tcdnPaths?: readonly string[];\n\t/** Headers for each file under `cdnPaths` and Vite's `build.assetsDir`, such as CORS headers. */\n\tcdnHeaders?: Readonly<Record<string, string>>;\n\t/**\n\t * Which prerendered pages the CDN serves, with no function. With `true`,\n\t * `vercel()` starts the server build once after the build and sends each\n\t * prerendered path through the pipeline as an anonymous client. The CDN\n\t * serves a page when its answer is a public 200 from its file, and the\n\t * same for a second client with another host, address, query, cookie,\n\t * `Authorization`, language, and country. The CDN then sends the\n\t * pipeline's body and headers. The function serves each other page, and\n\t * the CDN never keeps its answer. A function keeps each path that it\n\t * refuses in either trailing-slash form in the function, such as a page\n\t * whose answer depends on one query key. Why off by default: the build\n\t * runs each plugin's `setup`, and a check that the build cannot see can\n\t * then reach the CDN.\n\t * @default false\n\t */\n\tcdnPages?: boolean | ((path: string) => boolean);\n\t/** The Vercel regions of the function, such as `[\"iad1\"]`. @default the project's */\n\tregions?: readonly string[];\n\t/** The memory of the function, in MB. @default the project's */\n\tmemory?: number;\n\t/**\n\t * The longest time that a request runs, in seconds. It applies to each\n\t * request, because one function serves each route. A route module's\n\t * `config` export does nothing. @default the project's\n\t */\n\tmaxDuration?: number;\n};\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/** The most routes of a deployment. See https://vercel.com/docs/limits. */\nconst ROUTE_LIMIT = 2048;\n\n/**\n * The URL path under `static/` of the bodies of the pages that the CDN\n * serves. A route sends a request for it to the function, so a page has one\n * URL.\n */\nconst PAGES = \"/_app-server/pages\";\n\n/**\n * The script that finds the pages that the CDN serves. Why the source in a\n * `.ts` module: the tests of this package run the source, and Node.js runs a\n * `.ts` file with no import of its own.\n */\nconst PAGES_SCRIPT = fileURLToPath(\n\tnew URL(import.meta.url.endsWith(\".ts\") ? \"./pages.ts\" : \"./vercel-pages.js\", import.meta.url),\n);\n\n/** A case-insensitive pattern for `text/markdown`, in the regular expression syntax of any engine. */\nconst MARKDOWN = \"text/markdown\".replaceAll(\n\t/[a-z]/gu,\n\t(letter) => `[${letter}${letter.toUpperCase()}]`,\n);\n\n/** The variable that gives the function the time of the build, in milliseconds. */\nconst BUILT_AT = \"APP_SERVER_BUILT_AT\";\n\n/** The function's file, next to the server entry. */\nconst FUNCTION_FILE = \"vercel-function.js\";\n\n/** A path with `/` separators, as Vercel's config reads it. */\nfunction posix(path: string): string {\n\treturn path.split(sep).join(\"/\");\n}\n\n/** A regular expression source that matches `text` as it is. */\nfunction escaped(text: string): string {\n\treturn text.replaceAll(/[$()*+.?[\\\\\\]^{|}]/gu, String.raw`\\$&`);\n}\n\n/** Copies the file at `from` to `to`, and makes the directories of `to`. */\nfunction copyFile(from: string, to: string): void {\n\tmkdirSync(dirname(to), { recursive: true });\n\tcopyFileSync(from, to);\n}\n\n/**\n * The path of each file under `directory`, relative to it. Why follow links:\n * the CDN and the function each get a copy of the linked file, not a link\n * whose target can be in the other part. Why the inodes of the parents: a\n * link to a parent directory must not make the walk endless.\n */\nfunction filesUnder(\n\tdirectory: string,\n\tunder = \"\",\n\tparents: ReadonlySet<string> = new Set(),\n): string[] {\n\tconst stats = statSync(join(directory, under), { throwIfNoEntry: false });\n\tif (stats == null) {\n\t\treturn [];\n\t}\n\tif (!stats.isDirectory()) {\n\t\treturn [under];\n\t}\n\tconst inode = `${stats.dev}:${stats.ino}`;\n\tif (parents.has(inode)) {\n\t\treturn [];\n\t}\n\tconst inside = new Set(parents).add(inode);\n\treturn readdirSync(join(directory, under)).flatMap((name) =>\n\t\tfilesUnder(directory, join(under, name), inside),\n\t);\n}\n\n/**\n * The `.vercel/output` routes: a CDN file gets its headers, and each other\n * request goes to the function. A file under `assetsPath` also gets the\n * immutable cache. Why the `hit` phase: a CDN path with no file goes to the\n * function, whose `no-store` 404 must not get the immutable cache.\n */\nfunction routes(\n\tprefixes: readonly string[],\n\t{\n\t\tassetsPath,\n\t\tcdnHeaders,\n\t\tpages,\n\t}: {\n\t\tassetsPath: string;\n\t\tcdnHeaders: Readonly<Record<string, string>>;\n\t\tpages: readonly CdnPageReport[];\n\t},\n) {\n\treturn [\n\t\t...(pages.length === 0 ? [] : [{ src: `^${escaped(PAGES)}(?:/.*)?$`, dest: \"/index\" }]),\n\t\t...pages.flatMap((page) => pageRoutes(page)),\n\t\t{ handle: \"filesystem\" },\n\t\t{ src: \"^/(.*)$\", dest: \"/index\" },\n\t\t{ handle: \"hit\" },\n\t\t...prefixes.map((prefix) => ({\n\t\t\t// Why `.*$`: Vercel adds `$` to a pattern that has none.\n\t\t\tsrc: `^${escaped(prefix)}.*$`,\n\t\t\theaders: prefix === assetsPath ? { ...cdnHeaders, \"Cache-Control\": IMMUTABLE } : cdnHeaders,\n\t\t\tcontinue: true,\n\t\t})),\n\t];\n}\n\n/**\n * The routes of one page that the CDN serves: one for each case of the\n * presence headers, with the headers of that case. Why only GET and HEAD: the\n * function answers the other methods, such as a form's POST. Why the\n * function for a request that names `text/markdown`: it negotiates the twin.\n */\nfunction pageRoutes({ path, file, answers, twin }: CdnPageReport) {\n\tconst src = `^${escaped(path)}$`;\n\tconst names = [...new Set(answers.flatMap(({ present }) => present))];\n\treturn [\n\t\t...(twin == null\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tsrc,\n\t\t\t\t\t\thas: [{ type: \"header\", key: \"accept\", value: { re: MARKDOWN } }],\n\t\t\t\t\t\tdest: \"/index\",\n\t\t\t\t\t},\n\t\t\t\t]),\n\t\t...answers.map(({ present, headers }) => {\n\t\t\tconst missing = names.filter((name) => !present.includes(name));\n\t\t\treturn {\n\t\t\t\tsrc,\n\t\t\t\tcaseSensitive: true,\n\t\t\t\tmethods: [\"GET\", \"HEAD\"],\n\t\t\t\t...(present.length === 0 ? {} : { has: present.map((key) => ({ type: \"header\", key })) }),\n\t\t\t\t...(missing.length === 0\n\t\t\t\t\t? {}\n\t\t\t\t\t: { missing: missing.map((key) => ({ type: \"header\", key })) }),\n\t\t\t\theaders,\n\t\t\t\tdest: `${PAGES}${file}`,\n\t\t\t};\n\t\t}),\n\t];\n}\n\n/**\n * Whether `cdnPages` accepts `path`. Why both trailing-slash forms: with\n * `trailingSlash: \"always\"`, the CDN serves `/blog/` for the prerendered\n * path `/blog`.\n */\nfunction accepts(cdnPages: (path: string) => boolean, path: string): boolean {\n\treturn cdnPages(path) && (path === \"/\" || !path.endsWith(\"/\") || cdnPages(path.slice(0, -1)));\n}\n\n/**\n * Finds the pages that the CDN serves ({@link VercelOptions.cdnPages}), and\n * writes their bodies under `static/`.\n */\nfunction findCdnPages(\n\tentryFile: string,\n\toutput: string,\n\t{\n\t\tcdnPages,\n\t\trouteBudget,\n\t}: { cdnPages: NonNullable<VercelOptions[\"cdnPages\"]>; routeBudget: number },\n): PagesReport {\n\tif (cdnPages === false) {\n\t\treturn { cdn: [], server: [] };\n\t}\n\tconst pagesDirectory = join(output, \"static\", PAGES);\n\tconst reportFile = join(output, \"pages.json\");\n\ttry {\n\t\texecFileSync(process.execPath, [PAGES_SCRIPT, entryFile, pagesDirectory, reportFile], {\n\t\t\tstdio: \"inherit\",\n\t\t\tenv: { ...process.env, NODE_ENV: \"production\" },\n\t\t});\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t\"@ngrok/app-server/vercel could not start the server build to find the prerendered pages that the CDN can serve. Give the build the environment of the app, or remove `cdnPages`.\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the step of this package wrote the file.\n\tconst report = JSON.parse(readFileSync(reportFile, \"utf8\")) as PagesReport;\n\trmSync(reportFile);\n\tconst pages: PagesReport = { cdn: [], server: [...report.server] };\n\tlet routeCount = 0;\n\tfor (const page of report.cdn) {\n\t\tconst count = pageRoutes(page).length;\n\t\tlet reason: string | undefined;\n\t\tif (cdnPages !== true && !accepts(cdnPages, page.path)) {\n\t\t\treason = \"`cdnPages` keeps it in the function\";\n\t\t} else if (\n\t\t\tpage.answers.some(({ headers }) =>\n\t\t\t\tObject.values(headers).some((value) => value.includes(\"$\")),\n\t\t\t)\n\t\t) {\n\t\t\t// Why: Vercel reads `$1` or `$name` in a route's header as a capture of its `src`.\n\t\t\treason = \"a header has a `$`, which a Vercel route reads as a capture\";\n\t\t} else if (routeCount + count > routeBudget) {\n\t\t\treason = `the CDN routes of the pages reach Vercel's limit of ${ROUTE_LIMIT} routes`;\n\t\t}\n\t\tif (reason == null) {\n\t\t\tpages.cdn.push(page);\n\t\t\trouteCount += count;\n\t\t} else {\n\t\t\trmSync(join(pagesDirectory, page.file));\n\t\t\tpages.server.push({ path: page.path, reason });\n\t\t}\n\t}\n\treturn pages;\n}\n\n/** Writes the paths that the function serves, and why, so the build log shows them. */\nfunction reportPages({ cdn, server }: PagesReport): void {\n\tconst shown = server.slice(0, 20);\n\tprocess.stdout.write(\n\t\t[\n\t\t\t`@ngrok/app-server/vercel: the CDN serves ${cdn.length} prerendered paths, and the function serves ${server.length}.`,\n\t\t\t...shown.map(({ path, reason }) => ` ${path}: ${reason}`),\n\t\t\t...(server.length > shown.length ? [` and ${server.length - shown.length} more`] : []),\n\t\t\t\"\",\n\t\t].join(\"\\n\"),\n\t);\n}\n\n/** Writes `.vercel/output` (the Build Output API, version 3) for one build. */\nfunction writeOutput(\n\t{ root, clientDirectory, entryFile, assetsPath }: HostOutput,\n\t{ cdnPaths = [], cdnHeaders = {}, cdnPages = false, regions, memory, maxDuration }: VercelOptions,\n): void {\n\t// Why `assetsPath` last: Vercel applies each matched rule in order, so its immutable cache wins\n\t// over a `cdnHeaders` value for a `cdnPaths` entry that holds it.\n\tconst prefixes = [...cdnPaths.filter((path) => path !== assetsPath), assetsPath];\n\tconst output = join(root, \".vercel/output\");\n\trmSync(output, { recursive: true, force: true });\n\tconst pages = findCdnPages(entryFile, output, {\n\t\tcdnPages,\n\t\t// Why one less: the route that sends a request for a page's body to the function.\n\t\trouteBudget: ROUTE_LIMIT - routes(prefixes, { assetsPath, cdnHeaders, pages: [] }).length - 1,\n\t});\n\tif (cdnPages !== false) {\n\t\treportPages(pages);\n\t}\n\tconst fromRoot = (path: string): string => {\n\t\tconst inside = relative(root, path);\n\t\tif (inside.startsWith(\"..\") || isAbsolute(inside)) {\n\t\t\tthrow new Error(`@ngrok/app-server/vercel needs ${path} inside the Vite root ${root}.`);\n\t\t}\n\t\treturn inside;\n\t};\n\tconst functionDirectory = join(output, \"functions/index.func\");\n\tconst isCdnFile = (file: string): boolean =>\n\t\tprefixes.some((prefix) => `/${posix(file)}`.startsWith(prefix));\n\n\tfor (const file of filesUnder(clientDirectory)) {\n\t\tconst from = join(clientDirectory, file);\n\t\t// Why the function keeps the file of a page that the CDN serves: a request that no page route\n\t\t// matches, such as the other trailing slash form, or a markdown request, reaches the function.\n\t\tif (!isCdnFile(file)) {\n\t\t\tcopyFile(from, join(functionDirectory, fromRoot(from)));\n\t\t} else if (!hasDotSegment(`/${posix(file)}`)) {\n\t\t\t// Why the static stages' check: the CDN sends each file that it has, and the static stages\n\t\t\t// send no dotfile, such as a compressed copy, and no file in a dot directory.\n\t\t\tcopyFile(from, join(output, \"static\", file));\n\t\t}\n\t}\n\n\t// Why the whole server build: it runs with no install, and it keeps the client build's path.\n\tconst serverDirectory = dirname(entryFile);\n\tconst functionFile = join(serverDirectory, FUNCTION_FILE);\n\tcpSync(serverDirectory, join(functionDirectory, fromRoot(serverDirectory)), {\n\t\trecursive: true,\n\t\t// Why: a link that keeps its target can point at the build machine.\n\t\tdereference: true,\n\t\t// Why: the client build can be inside the server build, and the loop above copied its part.\n\t\tfilter: (path) => path !== clientDirectory,\n\t});\n\twriteFileSync(\n\t\tjoin(functionDirectory, fromRoot(functionFile)),\n\t\t[\n\t\t\t`import { appServer, hostModule } from ${JSON.stringify(`./${basename(entryFile)}`)};`,\n\t\t\t`export default hostModule.handler(appServer);`,\n\t\t\t\"\",\n\t\t].join(\"\\n\"),\n\t);\n\twriteFileSync(\n\t\tjoin(functionDirectory, \".vc-config.json\"),\n\t\t`${JSON.stringify(\n\t\t\t{\n\t\t\t\t// Why the build's Node.js: the server build targets the Node.js that built it.\n\t\t\t\truntime: `nodejs${process.versions.node.split(\".\")[0]}.x`,\n\t\t\t\thandler: posix(fromRoot(functionFile)),\n\t\t\t\tlauncherType: \"Nodejs\",\n\t\t\t\tsupportsResponseStreaming: true,\n\t\t\t\t// Why: the deploy gives each file of the function one fixed time, and the ETag of a file\n\t\t\t\t// reads its time. See `host` in `@ngrok/app-server/vercel`.\n\t\t\t\tenvironment: { [BUILT_AT]: String(Date.now()) },\n\t\t\t\t...(regions == null ? {} : { regions }),\n\t\t\t\t...(memory == null ? {} : { memory }),\n\t\t\t\t...(maxDuration == null ? {} : { maxDuration }),\n\t\t\t},\n\t\t\tnull,\n\t\t\t\"\\t\",\n\t\t)}\\n`,\n\t);\n\twriteFileSync(\n\t\tjoin(output, \"config.json\"),\n\t\t`${JSON.stringify({ version: 3, routes: routes(prefixes, { assetsPath, cdnHeaders, pages: pages.cdn }) }, null, \"\\t\")}\\n`,\n\t);\n}\n\n/** Throws for a CDN path that is not a URL path prefix, so the config fails, not the deploy. */\nfunction checkCdnPaths(paths: readonly string[]): void {\n\tfor (const path of paths) {\n\t\tif (!path.startsWith(\"/\") || !path.endsWith(\"/\") || path === \"/\" || path.includes(\"..\")) {\n\t\t\tthrow new Error(\n\t\t\t\t`Each cdnPaths entry is a URL path prefix that starts and ends with \"/\", such as \"/blog-assets/\", not ${JSON.stringify(path)}.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * The build side of the vercel host. After the build, it writes\n * `.vercel/output` in the Vite root, for `vercel deploy --prebuilt`:\n *\n * - `static/`: the files of Vite's `build.assetsDir` (`/assets/` by default)\n * and the other `cdnPaths`. The CDN serves them, and each file of\n * `build.assetsDir` gets a one-year immutable cache. It also holds the\n * prerendered pages that the CDN serves, with `cdnPages`.\n * - `functions/index.func/`: one Node.js function that runs the pipeline for\n * each other request, with the whole server build and the rest of the\n * client build.\n *\n * @example\n * appServer({ host: vercel() });\n */\nexport function vercel(options: VercelOptions = {}): HostBuild {\n\tcheckCdnPaths(options.cdnPaths ?? []);\n\treturn {\n\t\tname: \"vercel\",\n\t\truntimeModule: \"@ngrok/app-server/vercel\",\n\t\tentryFileName: \"app-server.js\",\n\t\toutput: (build) => {\n\t\t\twriteOutput(build, options);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;AAwDA,MAAM,YAAY;;AAGlB,MAAM,cAAc;;;;;;AAOpB,MAAM,QAAQ;;;;;;AAOd,MAAM,eAAe,cACpB,IAAI,IAAI,YAAY,IAAI,SAAS,KAAK,IAAI,eAAe,qBAAqB,YAAY,GAAG,CAC9F;;AAGA,MAAM,WAAW,gBAAgB,WAChC,YACC,WAAW,IAAI,SAAS,OAAO,YAAY,EAAE,EAC/C;;AAGA,MAAM,WAAW;;AAGjB,MAAM,gBAAgB;;AAGtB,SAASA,QAAM,MAAsB;CACpC,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;AAChC;;AAGA,SAAS,QAAQ,MAAsB;CACtC,OAAO,KAAK,WAAW,wBAAwB,OAAO,GAAG,KAAK;AAC/D;;AAGA,SAAS,SAAS,MAAc,IAAkB;CACjD,UAAU,QAAQ,EAAE,GAAG,EAAE,WAAW,KAAK,CAAC;CAC1C,aAAa,MAAM,EAAE;AACtB;;;;;;;AAQA,SAAS,WACR,WACA,QAAQ,IACR,0BAA+B,IAAI,IAAI,GAC5B;CACX,MAAM,QAAQ,SAAS,KAAK,WAAW,KAAK,GAAG,EAAE,gBAAgB,MAAM,CAAC;CACxE,IAAI,SAAS,MACZ,OAAO,CAAC;CAET,IAAI,CAAC,MAAM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AE,QAAQ;EACrC,GAAI,UAAU,OAAO,CAAC,IAAI,EAAE,OAAO;EACnC,GAAI,eAAe,OAAO,CAAC,IAAI,EAAE,YAAY;CAC9C,GACA,MACA,GACD,EAAE,GACH;CACA,cACC,KAAK,QAAQ,aAAa,GAC1B,GAAG,KAAK,UAAU;EAAE,SAAS;EAAG,QAAQ,OAAO,UAAU;GAAE;GAAY;GAAY,OAAO,MAAM;EAAI,CAAC;CAAE,GAAG,MAAM,GAAI,EAAE,GACvH;AACD;;AAGA,SAAS,cAAc,OAAgC;CACtD,KAAK,MAAM,QAAQ,OAClB,IAAI,CAAC,KAAK,WAAW,GAAG,KAAK,CAAC,KAAK,SAAS,GAAG,KAAK,SAAS,OAAO,KAAK,SAAS,IAAI,GACrF,MAAM,IAAI,MACT,wGAAwG,KAAK,UAAU,IAAI,EAAE,EAC9H;AAGH;;;;;;;;;;;;;;;;AAiBA,SAAgB,OAAO,UAAyB,CAAC,GAAc;CAC9D,cAAc,QAAQ,YAAY,CAAC,CAAC;CACpC,OAAO;EACN,MAAM;EACN,eAAe;EACf,eAAe;EACf,SAAS,UAAU;GAClB,YAAY,OAAO,OAAO;EAC3B;CACD;AACD"}
1
+ {"version":3,"file":"vercel-vite.js","names":["posix"],"sources":["../src/vercel/vite.ts"],"sourcesContent":["import { execFileSync } from \"node:child_process\";\nimport {\n\tcopyFileSync,\n\tcpSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmSync,\n\tstatSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { basename, dirname, isAbsolute, join, relative, sep } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { copyName } from \"../core/compression.js\";\nimport { hasDotSegment } from \"../core/static-files.js\";\nimport type { HostBuild, HostOutput } from \"../vite/index.js\";\nimport { BROTLI_ONLY_LIST } from \"./brotli-only.js\";\nimport type { CdnPageReport, PagesReport } from \"./pages.js\";\n\n/** Options for {@link vercel}. */\nexport type VercelOptions = {\n\t/**\n\t * More URL path prefixes of the client build that Vercel's CDN serves,\n\t * such as `[\"/blog-assets/\"]`. Each starts and ends with `/`. The URL path\n\t * of Vite's `build.assetsDir`, `/assets/` by default, is always one. Their\n\t * files skip the pipeline, and the function does not carry them.\n\t */\n\tcdnPaths?: readonly string[];\n\t/** Headers for each file under `cdnPaths` and Vite's `build.assetsDir`, such as CORS headers. */\n\tcdnHeaders?: Readonly<Record<string, string>>;\n\t/**\n\t * Which prerendered pages the CDN serves, with no function. With `true`,\n\t * `vercel()` starts the server build once after the build and sends each\n\t * prerendered path through the pipeline as an anonymous client. The CDN\n\t * serves a page when its answer is a public 200 from its file, and the\n\t * same for a second client with another host, address, query, cookie,\n\t * `Authorization`, language, and country. The CDN then sends the\n\t * pipeline's body and headers. The function serves each other page, and\n\t * the CDN never keeps its answer. A function keeps each path that it\n\t * refuses in either trailing-slash form in the function, such as a page\n\t * whose answer depends on one query key. Why off by default: the build\n\t * runs each plugin's `setup`, and a check that the build cannot see can\n\t * then reach the CDN.\n\t * @default false\n\t */\n\tcdnPages?: boolean | ((path: string) => boolean);\n\t/** The Vercel regions of the function, such as `[\"iad1\"]`. @default the project's */\n\tregions?: readonly string[];\n\t/** The memory of the function, in MB. @default the project's */\n\tmemory?: number;\n\t/**\n\t * The longest time that a request runs, in seconds. It applies to each\n\t * request, because one function serves each route. A route module's\n\t * `config` export does nothing. @default the project's\n\t */\n\tmaxDuration?: number;\n};\n\nconst IMMUTABLE = \"public, max-age=31536000, immutable\";\n\n/** The most routes of a deployment. See https://vercel.com/docs/limits. */\nconst ROUTE_LIMIT = 2048;\n\n/**\n * The URL path under `static/` of the bodies of the pages that the CDN\n * serves. A route sends a request for it to the function, so a page has one\n * URL.\n */\nconst PAGES = \"/_app-server/pages\";\n\n/**\n * The script that finds the pages that the CDN serves. Why the source in a\n * `.ts` module: the tests of this package run the source, and Node.js runs a\n * `.ts` file with no import of its own.\n */\nconst PAGES_SCRIPT = fileURLToPath(\n\tnew URL(import.meta.url.endsWith(\".ts\") ? \"./pages.ts\" : \"./vercel-pages.js\", import.meta.url),\n);\n\n/** A case-insensitive pattern for `text/markdown`, in the regular expression syntax of any engine. */\nconst MARKDOWN = \"text/markdown\".replaceAll(\n\t/[a-z]/gu,\n\t(letter) => `[${letter}${letter.toUpperCase()}]`,\n);\n\n/** The variable that gives the function the time of the build, in milliseconds. */\nconst BUILT_AT = \"APP_SERVER_BUILT_AT\";\n\n/** The function's file, next to the server entry. */\nconst FUNCTION_FILE = \"vercel-function.js\";\n\n/** A path with `/` separators, as Vercel's config reads it. */\nfunction posix(path: string): string {\n\treturn path.split(sep).join(\"/\");\n}\n\n/** A regular expression source that matches `text` as it is. */\nfunction escaped(text: string): string {\n\treturn text.replaceAll(/[$()*+.?[\\\\\\]^{|}]/gu, String.raw`\\$&`);\n}\n\n/** Copies the file at `from` to `to`, and makes the directories of `to`. */\nfunction copyFile(from: string, to: string): void {\n\tmkdirSync(dirname(to), { recursive: true });\n\tcopyFileSync(from, to);\n}\n\n/**\n * The path of each file under `directory`, relative to it. Why follow links:\n * the CDN and the function each get a copy of the linked file, not a link\n * whose target can be in the other part. Why the inodes of the parents: a\n * link to a parent directory must not make the walk endless.\n */\nfunction filesUnder(\n\tdirectory: string,\n\tunder = \"\",\n\tparents: ReadonlySet<string> = new Set(),\n): string[] {\n\tconst stats = statSync(join(directory, under), { throwIfNoEntry: false });\n\tif (stats == null) {\n\t\treturn [];\n\t}\n\tif (!stats.isDirectory()) {\n\t\treturn [under];\n\t}\n\tconst inode = `${stats.dev}:${stats.ino}`;\n\tif (parents.has(inode)) {\n\t\treturn [];\n\t}\n\tconst inside = new Set(parents).add(inode);\n\treturn readdirSync(join(directory, under)).flatMap((name) =>\n\t\tfilesUnder(directory, join(under, name), inside),\n\t);\n}\n\n/**\n * The `.vercel/output` routes: a CDN file gets its headers, and each other\n * request goes to the function. A file under `assetsPath` also gets the\n * immutable cache. Why the `hit` phase: a CDN path with no file goes to the\n * function, whose `no-store` 404 must not get the immutable cache.\n */\nfunction routes(\n\tprefixes: readonly string[],\n\t{\n\t\tassetsPath,\n\t\tcdnHeaders,\n\t\tpages,\n\t}: {\n\t\tassetsPath: string;\n\t\tcdnHeaders: Readonly<Record<string, string>>;\n\t\tpages: readonly CdnPageReport[];\n\t},\n) {\n\treturn [\n\t\t...(pages.length === 0 ? [] : [{ src: `^${escaped(PAGES)}(?:/.*)?$`, dest: \"/index\" }]),\n\t\t...pages.flatMap((page) => pageRoutes(page)),\n\t\t{ handle: \"filesystem\" },\n\t\t{ src: \"^/(.*)$\", dest: \"/index\" },\n\t\t{ handle: \"hit\" },\n\t\t...prefixes.map((prefix) => ({\n\t\t\t// Why `.*$`: Vercel adds `$` to a pattern that has none.\n\t\t\tsrc: `^${escaped(prefix)}.*$`,\n\t\t\theaders: prefix === assetsPath ? { ...cdnHeaders, \"Cache-Control\": IMMUTABLE } : cdnHeaders,\n\t\t\tcontinue: true,\n\t\t})),\n\t];\n}\n\n/**\n * The routes of one page that the CDN serves: one for each case of the\n * presence headers, with the headers of that case. Why only GET and HEAD: the\n * function answers the other methods, such as a form's POST. Why the\n * function for a request that names `text/markdown`: it negotiates the twin.\n */\nfunction pageRoutes({ path, file, answers, twin }: CdnPageReport) {\n\tconst src = `^${escaped(path)}$`;\n\tconst names = [...new Set(answers.flatMap(({ present }) => present))];\n\treturn [\n\t\t...(twin == null\n\t\t\t? []\n\t\t\t: [\n\t\t\t\t\t{\n\t\t\t\t\t\tsrc,\n\t\t\t\t\t\thas: [{ type: \"header\", key: \"accept\", value: { re: MARKDOWN } }],\n\t\t\t\t\t\tdest: \"/index\",\n\t\t\t\t\t},\n\t\t\t\t]),\n\t\t...answers.map(({ present, headers }) => {\n\t\t\tconst missing = names.filter((name) => !present.includes(name));\n\t\t\treturn {\n\t\t\t\tsrc,\n\t\t\t\tcaseSensitive: true,\n\t\t\t\tmethods: [\"GET\", \"HEAD\"],\n\t\t\t\t...(present.length === 0 ? {} : { has: present.map((key) => ({ type: \"header\", key })) }),\n\t\t\t\t...(missing.length === 0\n\t\t\t\t\t? {}\n\t\t\t\t\t: { missing: missing.map((key) => ({ type: \"header\", key })) }),\n\t\t\t\theaders,\n\t\t\t\tdest: `${PAGES}${file}`,\n\t\t\t};\n\t\t}),\n\t];\n}\n\n/**\n * Whether `cdnPages` accepts `path`. Why both trailing-slash forms: with\n * `trailingSlash: \"always\"`, the CDN serves `/blog/` for the prerendered\n * path `/blog`.\n */\nfunction accepts(cdnPages: (path: string) => boolean, path: string): boolean {\n\treturn cdnPages(path) && (path === \"/\" || !path.endsWith(\"/\") || cdnPages(path.slice(0, -1)));\n}\n\n/**\n * Finds the pages that the CDN serves ({@link VercelOptions.cdnPages}), and\n * writes their bodies under `static/`.\n */\nfunction findCdnPages(\n\tentryFile: string,\n\toutput: string,\n\t{\n\t\tcdnPages,\n\t\trouteBudget,\n\t}: { cdnPages: NonNullable<VercelOptions[\"cdnPages\"]>; routeBudget: number },\n): PagesReport {\n\tif (cdnPages === false) {\n\t\treturn { cdn: [], server: [] };\n\t}\n\tconst pagesDirectory = join(output, \"static\", PAGES);\n\tconst reportFile = join(output, \"pages.json\");\n\ttry {\n\t\texecFileSync(process.execPath, [PAGES_SCRIPT, entryFile, pagesDirectory, reportFile], {\n\t\t\tstdio: \"inherit\",\n\t\t\tenv: { ...process.env, NODE_ENV: \"production\" },\n\t\t});\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t\"@ngrok/app-server/vercel could not start the server build to find the prerendered pages that the CDN can serve. Give the build the environment of the app, or remove `cdnPages`.\",\n\t\t\t{ cause: error },\n\t\t);\n\t}\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the step of this package wrote the file.\n\tconst report = JSON.parse(readFileSync(reportFile, \"utf8\")) as PagesReport;\n\trmSync(reportFile);\n\tconst pages: PagesReport = { cdn: [], server: [...report.server] };\n\tlet routeCount = 0;\n\tfor (const page of report.cdn) {\n\t\tconst count = pageRoutes(page).length;\n\t\tlet reason: string | undefined;\n\t\tif (cdnPages !== true && !accepts(cdnPages, page.path)) {\n\t\t\treason = \"`cdnPages` keeps it in the function\";\n\t\t} else if (\n\t\t\tpage.answers.some(({ headers }) =>\n\t\t\t\tObject.values(headers).some((value) => value.includes(\"$\")),\n\t\t\t)\n\t\t) {\n\t\t\t// Why: Vercel reads `$1` or `$name` in a route's header as a capture of its `src`.\n\t\t\treason = \"a header has a `$`, which a Vercel route reads as a capture\";\n\t\t} else if (routeCount + count > routeBudget) {\n\t\t\treason = `the CDN routes of the pages reach Vercel's limit of ${ROUTE_LIMIT} routes`;\n\t\t}\n\t\tif (reason == null) {\n\t\t\tpages.cdn.push(page);\n\t\t\trouteCount += count;\n\t\t} else {\n\t\t\trmSync(join(pagesDirectory, page.file));\n\t\t\tpages.server.push({ path: page.path, reason });\n\t\t}\n\t}\n\treturn pages;\n}\n\n/** Writes the paths that the function serves, and why, so the build log shows them. */\nfunction reportPages({ cdn, server }: PagesReport): void {\n\tconst shown = server.slice(0, 20);\n\tprocess.stdout.write(\n\t\t[\n\t\t\t`@ngrok/app-server/vercel: the CDN serves ${cdn.length} prerendered paths, and the function serves ${server.length}.`,\n\t\t\t...shown.map(({ path, reason }) => ` ${path}: ${reason}`),\n\t\t\t...(server.length > shown.length ? [` and ${server.length - shown.length} more`] : []),\n\t\t\t\"\",\n\t\t].join(\"\\n\"),\n\t);\n}\n\n/** Writes `.vercel/output` (the Build Output API, version 3) for one build. */\nfunction writeOutput(\n\t{ root, clientDirectory, entryFile, assetsPath }: HostOutput,\n\t{ cdnPaths = [], cdnHeaders = {}, cdnPages = false, regions, memory, maxDuration }: VercelOptions,\n): void {\n\t// Why `assetsPath` last: Vercel applies each matched rule in order, so its immutable cache wins\n\t// over a `cdnHeaders` value for a `cdnPaths` entry that holds it.\n\tconst prefixes = [...cdnPaths.filter((path) => path !== assetsPath), assetsPath];\n\tconst output = join(root, \".vercel/output\");\n\trmSync(output, { recursive: true, force: true });\n\tconst pages = findCdnPages(entryFile, output, {\n\t\tcdnPages,\n\t\t// Why one less: the route that sends a request for a page's body to the function.\n\t\trouteBudget: ROUTE_LIMIT - routes(prefixes, { assetsPath, cdnHeaders, pages: [] }).length - 1,\n\t});\n\tif (cdnPages !== false) {\n\t\treportPages(pages);\n\t}\n\tconst fromRoot = (path: string): string => {\n\t\tconst inside = relative(root, path);\n\t\tif (inside.startsWith(\"..\") || isAbsolute(inside)) {\n\t\t\tthrow new Error(`@ngrok/app-server/vercel needs ${path} inside the Vite root ${root}.`);\n\t\t}\n\t\treturn inside;\n\t};\n\tconst functionDirectory = join(output, \"functions/index.func\");\n\tconst isCdnFile = (file: string): boolean =>\n\t\tprefixes.some((prefix) => `/${posix(file)}`.startsWith(prefix));\n\n\tconst clientFiles = filesUnder(clientDirectory);\n\tconst listed = new Set(clientFiles);\n\t/** The file of each brotli copy that the function keeps, with the size of the file. */\n\tconst brotliOnly: Record<string, number> = {};\n\t/**\n\t * Whether the function drops `file`, a file or a gzip copy, because the\n\t * brotli copy of its file takes its place. Why: the function then holds one\n\t * copy of each text file, not three. Each browser accepts brotli, and the\n\t * CDN compresses the decompressed file for a client that does not.\n\t */\n\tconst brotliCopyOnly = (file: string): boolean => {\n\t\tconst name = basename(file);\n\t\tconst original = name.startsWith(\".\") ? /^\\.(?<name>.+)\\.gz$/u.exec(name)?.groups?.name : name;\n\t\treturn (\n\t\t\toriginal != null &&\n\t\t\tlisted.has(join(dirname(file), original)) &&\n\t\t\tlisted.has(join(dirname(file), copyName(original, \"br\")))\n\t\t);\n\t};\n\tfor (const file of clientFiles) {\n\t\tconst from = join(clientDirectory, file);\n\t\t// Why the function keeps the file of a page that the CDN serves: a request that no page route\n\t\t// matches, such as the other trailing slash form, or a markdown request, reaches the function.\n\t\tif (!isCdnFile(file)) {\n\t\t\tif (!brotliCopyOnly(file)) {\n\t\t\t\tcopyFile(from, join(functionDirectory, fromRoot(from)));\n\t\t\t} else if (!basename(file).startsWith(\".\")) {\n\t\t\t\tbrotliOnly[`/${posix(file)}`] = statSync(from).size;\n\t\t\t}\n\t\t} else if (!hasDotSegment(`/${posix(file)}`)) {\n\t\t\t// Why the static stages' check: the CDN sends each file that it has, and the static stages\n\t\t\t// send no dotfile, such as a compressed copy, and no file in a dot directory.\n\t\t\tcopyFile(from, join(output, \"static\", file));\n\t\t}\n\t}\n\n\tif (Object.keys(brotliOnly).length > 0) {\n\t\twriteFileSync(\n\t\t\tjoin(functionDirectory, fromRoot(clientDirectory), BROTLI_ONLY_LIST),\n\t\t\tJSON.stringify(brotliOnly),\n\t\t);\n\t}\n\n\t// Why the whole server build: it runs with no install, and it keeps the client build's path.\n\tconst serverDirectory = dirname(entryFile);\n\tconst functionFile = join(serverDirectory, FUNCTION_FILE);\n\tcpSync(serverDirectory, join(functionDirectory, fromRoot(serverDirectory)), {\n\t\trecursive: true,\n\t\t// Why: a link that keeps its target can point at the build machine.\n\t\tdereference: true,\n\t\t// Why: the client build can be inside the server build, and the loop above copied its part.\n\t\tfilter: (path) => path !== clientDirectory,\n\t});\n\twriteFileSync(\n\t\tjoin(functionDirectory, fromRoot(functionFile)),\n\t\t[\n\t\t\t`import { appServer, hostModule } from ${JSON.stringify(`./${basename(entryFile)}`)};`,\n\t\t\t`export default hostModule.handler(appServer);`,\n\t\t\t\"\",\n\t\t].join(\"\\n\"),\n\t);\n\twriteFileSync(\n\t\tjoin(functionDirectory, \".vc-config.json\"),\n\t\t`${JSON.stringify(\n\t\t\t{\n\t\t\t\t// Why the build's Node.js: the server build targets the Node.js that built it.\n\t\t\t\truntime: `nodejs${process.versions.node.split(\".\")[0]}.x`,\n\t\t\t\thandler: posix(fromRoot(functionFile)),\n\t\t\t\tlauncherType: \"Nodejs\",\n\t\t\t\tsupportsResponseStreaming: true,\n\t\t\t\t// Why: the deploy gives each file of the function one fixed time, and the ETag of a file\n\t\t\t\t// reads its time. See `host` in `@ngrok/app-server/vercel`.\n\t\t\t\tenvironment: { [BUILT_AT]: String(Date.now()) },\n\t\t\t\t...(regions == null ? {} : { regions }),\n\t\t\t\t...(memory == null ? {} : { memory }),\n\t\t\t\t...(maxDuration == null ? {} : { maxDuration }),\n\t\t\t},\n\t\t\tnull,\n\t\t\t\"\\t\",\n\t\t)}\\n`,\n\t);\n\twriteFileSync(\n\t\tjoin(output, \"config.json\"),\n\t\t`${JSON.stringify({ version: 3, routes: routes(prefixes, { assetsPath, cdnHeaders, pages: pages.cdn }) }, null, \"\\t\")}\\n`,\n\t);\n}\n\n/** Throws for a CDN path that is not a URL path prefix, so the config fails, not the deploy. */\nfunction checkCdnPaths(paths: readonly string[]): void {\n\tfor (const path of paths) {\n\t\tif (!path.startsWith(\"/\") || !path.endsWith(\"/\") || path === \"/\" || path.includes(\"..\")) {\n\t\t\tthrow new Error(\n\t\t\t\t`Each cdnPaths entry is a URL path prefix that starts and ends with \"/\", such as \"/blog-assets/\", not ${JSON.stringify(path)}.`,\n\t\t\t);\n\t\t}\n\t}\n}\n\n/**\n * The build side of the vercel host. After the build, it writes\n * `.vercel/output` in the Vite root, for `vercel deploy --prebuilt`:\n *\n * - `static/`: the files of Vite's `build.assetsDir` (`/assets/` by default)\n * and the other `cdnPaths`. The CDN serves them, and each file of\n * `build.assetsDir` gets a one-year immutable cache. It also holds the\n * prerendered pages that the CDN serves, with `cdnPages`.\n * - `functions/index.func/`: one Node.js function that runs the pipeline for\n * each other request, with the whole server build and the rest of the\n * client build.\n *\n * @example\n * appServer({ host: vercel() });\n */\nexport function vercel(options: VercelOptions = {}): HostBuild {\n\tcheckCdnPaths(options.cdnPaths ?? []);\n\treturn {\n\t\tname: \"vercel\",\n\t\truntimeModule: \"@ngrok/app-server/vercel\",\n\t\tentryFileName: \"app-server.js\",\n\t\toutput: (build) => {\n\t\t\twriteOutput(build, options);\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;;;;AA0DA,MAAM,YAAY;;AAGlB,MAAM,cAAc;;;;;;AAOpB,MAAM,QAAQ;;;;;;AAOd,MAAM,eAAe,cACpB,IAAI,IAAI,YAAY,IAAI,SAAS,KAA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ACd,2BAA2B;EAG3B,aAAa,GAAG,WAAW,OAAO,KAAK,IAAI,CAAC,EAAE;EAC9C,GAAI,WAAW,OAAO,CAAC,IAAI,EAAE,QAAQ;EACrC,GAAI,UAAU,OAAO,CAAC,IAAI,EAAE,OAAO;EACnC,GAAI,eAAe,OAAO,CAAC,IAAI,EAAE,YAAY;CAC9C,GACA,MACA,GACD,EAAE,GACH;CACA,cACC,KAAK,QAAQ,aAAa,GAC1B,GAAG,KAAK,UAAU;EAAE,SAAS;EAAG,QAAQ,OAAO,UAAU;GAAE;GAAY;GAAY,OAAO,MAAM;EAAI,CAAC;CAAE,GAAG,MAAM,GAAI,EAAE,GACvH;AACD;;AAGA,SAAS,cAAc,OAAgC;CACtD,KAAK,MAAM,QAAQ,OAClB,IAAI,CAAC,KAAK,WAAW,GAAG,KAAK,CAAC,KAAK,SAAS,GAAG,KAAK,SAAS,OAAO,KAAK,SAAS,IAAI,GACrF,MAAM,IAAI,MACT,wGAAwG,KAAK,UAAU,IAAI,EAAE,EAC9H;AAGH;;;;;;;;;;;;;;;;AAiBA,SAAgB,OAAO,UAAyB,CAAC,GAAc;CAC9D,cAAc,QAAQ,YAAY,CAAC,CAAC;CACpC,OAAO;EACN,MAAM;EACN,eAAe;EACf,eAAe;EACf,SAAS,UAAU;GAClB,YAAY,OAAO,OAAO;EAC3B;CACD;AACD"}
package/dist/vercel.d.ts CHANGED
@@ -1,12 +1,13 @@
1
- import { c as HostRuntime } from "./types-j29vspx_.js";
2
- import { t as AppServerEntry } from "./entry-BPrgE_6K.js";
1
+ import { c as HostRuntime } from "./types-BKJxtIuj.js";
2
+ import { t as AppServerEntry } from "./entry-CNL4OsEn.js";
3
3
  import { IncomingMessage, ServerResponse } from "node:http";
4
4
  /**
5
5
  * The vercel host: one Vercel Function on Node.js. It reads the client build
6
6
  * from the function's files and keeps `requestContext()` in
7
7
  * `AsyncLocalStorage`, as the node host does. It has no listeners and no
8
8
  * lifecycle: Vercel starts and stops the function, and {@link handler} calls
9
- * the entry's `fetch`.
9
+ * the entry's `fetch`. It reads a file that the function keeps only as a
10
+ * brotli copy through that copy (see `vercel()`).
10
11
  *
11
12
  * Why no gzip: Vercel's CDN compresses each response, with Brotli when the
12
13
  * client accepts it.
package/dist/vercel.js CHANGED
@@ -1,7 +1,8 @@
1
- import { n as flushLogs } from "./log-BP6xXXZl.js";
2
- import { i as withForwardedProto } from "./create-server-jMl2ltHD.js";
3
- import { t as host$1 } from "./node-C1qudLs_.js";
4
- import { t as requestListener } from "./response-writer-B7FoJjEE.js";
1
+ import { n as flushLogs } from "./log-C8LGQ23s.js";
2
+ import { i as withForwardedProto } from "./create-server-C_90R50y.js";
3
+ import { t as host$1 } from "./node-DFI5TjTk.js";
4
+ import { t as requestListener } from "./response-writer-5SOKsW3C.js";
5
+ import { n as brotliOnlyFiles } from "./brotli-only-DrA29Ecw.js";
5
6
 
6
7
  // src/vercel/index.ts
7
8
  /**
@@ -29,7 +30,8 @@ function withModifiedTime(files, mtimeMs) {
29
30
  * from the function's files and keeps `requestContext()` in
30
31
  * `AsyncLocalStorage`, as the node host does. It has no listeners and no
31
32
  * lifecycle: Vercel starts and stops the function, and {@link handler} calls
32
- * the entry's `fetch`.
33
+ * the entry's `fetch`. It reads a file that the function keeps only as a
34
+ * brotli copy through that copy (see `vercel()`).
33
35
  *
34
36
  * Why no gzip: Vercel's CDN compresses each response, with Brotli when the
35
37
  * client accepts it.
@@ -40,7 +42,7 @@ function withModifiedTime(files, mtimeMs) {
40
42
  const host = {
41
43
  name: "vercel",
42
44
  files: (clientDirectory) => {
43
- const files = host$1.files(clientDirectory);
45
+ const files = brotliOnlyFiles(host$1.files(clientDirectory));
44
46
  const builtAt = Number(process.env.APP_SERVER_BUILT_AT);
45
47
  return Number.isFinite(builtAt) ? withModifiedTime(files, builtAt) : files;
46
48
  },
@@ -1 +1 @@
1
- {"version":3,"file":"vercel.js","names":["nodeHost"],"sources":["../src/vercel/index.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { withForwardedProto } from \"../core/create-server.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { flushLogs } from \"../core/log.js\";\nimport type { FileInfo, HostRuntime, StaticFiles } from \"../core/types.js\";\nimport { host as nodeHost } from \"../node/index.js\";\nimport { requestListener } from \"../node/response-writer.js\";\n\n/**\n * `files` that give each file and directory the modification time\n * `mtimeMs`. Why: the deploy gives each file of the function one fixed time,\n * so a file that changes and keeps its size would keep its ETag. `vercel()`\n * sets `APP_SERVER_BUILT_AT` to the time of the build.\n */\nfunction withModifiedTime(files: StaticFiles, mtimeMs: number): StaticFiles {\n\tconst { snapshot } = files;\n\treturn {\n\t\tstat: async (path) => {\n\t\t\tconst info: FileInfo | undefined = await files.stat(path);\n\t\t\treturn info == null ? undefined : { ...info, mtimeMs };\n\t\t},\n\t\topen: files.open,\n\t\t...(snapshot == null\n\t\t\t? {}\n\t\t\t: { snapshot: async () => withModifiedTime(await snapshot(), mtimeMs) }),\n\t};\n}\n\n/**\n * The vercel host: one Vercel Function on Node.js. It reads the client build\n * from the function's files and keeps `requestContext()` in\n * `AsyncLocalStorage`, as the node host does. It has no listeners and no\n * lifecycle: Vercel starts and stops the function, and {@link handler} calls\n * the entry's `fetch`.\n *\n * Why no gzip: Vercel's CDN compresses each response, with Brotli when the\n * client accepts it.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"vercel\",\n\tfiles: (clientDirectory) => {\n\t\tconst files = nodeHost.files(clientDirectory);\n\t\tconst builtAt = Number(process.env.APP_SERVER_BUILT_AT);\n\t\treturn Number.isFinite(builtAt) ? withModifiedTime(files, builtAt) : files;\n\t},\n\t...(nodeHost.storage == null ? {} : { storage: nodeHost.storage }),\n};\n\n/**\n * The function handler for the entry of a server build. The function file\n * that `vercel()` writes exports it.\n *\n * - The scheme comes from `X-Forwarded-Proto`, and the client address from\n * `X-Real-IP`. Why trust them: Vercel sets both headers on each request,\n * and replaces a value that the client sends.\n * - The node response writer sends each response, as the node host's\n * listener does.\n * - The log lines of the request reach stdout before the handler returns.\n * Why: Vercel can freeze the function after the response, before the next\n * turn of the event loop writes them.\n *\n * @example\n * export default hostModule.handler(appServer);\n */\nexport function handler(\n\tentry: AppServerEntry,\n): (incoming: IncomingMessage, outgoing: ServerResponse) => Promise<void> {\n\tconst listener = requestListener(\n\t\tasync (request, bindings) => {\n\t\t\tconst realIp = bindings.incoming?.headers[\"x-real-ip\"];\n\t\t\treturn entry.fetch(withForwardedProto(request), {\n\t\t\t\t...bindings,\n\t\t\t\t...(typeof realIp === \"string\" ? { remoteAddress: realIp } : {}),\n\t\t\t});\n\t\t},\n\t\t{ trustForwardedProto: true },\n\t);\n\treturn async (incoming, outgoing) => {\n\t\ttry {\n\t\t\tawait listener(incoming, outgoing);\n\t\t\t// Why wait: the access log writes its line when the response closes, after the listener returns.\n\t\t\tif (!outgoing.closed) {\n\t\t\t\tawait new Promise((resolve) => {\n\t\t\t\t\toutgoing.once(\"close\", resolve);\n\t\t\t\t});\n\t\t\t}\n\t\t} finally {\n\t\t\tflushLogs();\n\t\t\t// Why wait: a full pipe keeps the rest of a write in a queue, and a frozen function does not send it.\n\t\t\tif (process.stdout.writableLength > 0) {\n\t\t\t\tawait new Promise((resolve) => {\n\t\t\t\t\tprocess.stdout.write(\"\", resolve);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;;AAcA,SAAS,iBAAiB,OAAoB,SAA8B;CAC3E,MAAM,EAAE,aAAa;CACrB,OAAO;EACN,MAAM,OAAO,SAAS;GACrB,MAAM,OAA6B,MAAM,MAAM,KAAK,IAAI;GACxD,OAAO,QAAQ,OAAO,SAAY;IAAE,GAAG;IAAM;GAAQ;EACtD;EACA,MAAM,MAAM;EACZ,GAAI,YAAY,OACb,CAAC,IACD,EAAE,UAAU,YAAY,iBAAiB,MAAM,SAAS,GAAG,OAAO,EAAE;CACxE;AACD;;;;;;;;;;;;;;AAeA,MAAa,OAAoB;CAChC,MAAM;CACN,QAAQ,oBAAoB;EAC3B,MAAM,QAAQA,OAAS,MAAM,eAAe;EAC5C,MAAM,UAAU,OAAO,QAAQ,IAAI,mBAAmB;EACtD,OAAO,OAAO,SAAS,OAAO,IAAI,iBAAiB,OAAO,OAAO,IAAI;CACtE;CACA,GAAIA,OAAS,WAAW,OAAO,CAAC,IAAI,EAAE,SAASA,OAAS,QAAQ;AACjE;;;;;;;;;;;;;;;;;AAkBA,SAAgB,QACf,OACyE;CACzE,MAAM,WAAW,gBAChB,OAAO,SAAS,aAAa;EAC5B,MAAM,SAAS,SAAS,UAAU,QAAQ;EAC1C,OAAO,MAAM,MAAM,mBAAmB,OAAO,GAAG;GAC/C,GAAG;GACH,GAAI,OAAO,WAAW,WAAW,EAAE,eAAe,OAAO,IAAI,CAAC;EAC/D,CAAC;CACF,GACA,EAAE,qBAAqB,KAAK,CAC7B;CACA,OAAO,OAAO,UAAU,aAAa;EACpC,IAAI;GACH,MAAM,SAAS,UAAU,QAAQ;GAEjC,IAAI,CAAC,SAAS,QACb,MAAM,IAAI,SAAS,YAAY;IAC9B,SAAS,KAAK,SAAS,OAAO;GAC/B,CAAC;EAEH,UAAU;GACT,UAAU;GAEV,IAAI,QAAQ,OAAO,iBAAiB,GACnC,MAAM,IAAI,SAAS,YAAY;IAC9B,QAAQ,OAAO,MAAM,IAAI,OAAO;GACjC,CAAC;EAEH;CACD;AACD"}
1
+ {"version":3,"file":"vercel.js","names":["nodeHost"],"sources":["../src/vercel/index.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { withForwardedProto } from \"../core/create-server.js\";\nimport type { AppServerEntry } from \"../core/entry.js\";\nimport { flushLogs } from \"../core/log.js\";\nimport type { FileInfo, HostRuntime, StaticFiles } from \"../core/types.js\";\nimport { host as nodeHost } from \"../node/index.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { brotliOnlyFiles } from \"./brotli-only.js\";\n\n/**\n * `files` that give each file and directory the modification time\n * `mtimeMs`. Why: the deploy gives each file of the function one fixed time,\n * so a file that changes and keeps its size would keep its ETag. `vercel()`\n * sets `APP_SERVER_BUILT_AT` to the time of the build.\n */\nfunction withModifiedTime(files: StaticFiles, mtimeMs: number): StaticFiles {\n\tconst { snapshot } = files;\n\treturn {\n\t\tstat: async (path) => {\n\t\t\tconst info: FileInfo | undefined = await files.stat(path);\n\t\t\treturn info == null ? undefined : { ...info, mtimeMs };\n\t\t},\n\t\topen: files.open,\n\t\t...(snapshot == null\n\t\t\t? {}\n\t\t\t: { snapshot: async () => withModifiedTime(await snapshot(), mtimeMs) }),\n\t};\n}\n\n/**\n * The vercel host: one Vercel Function on Node.js. It reads the client build\n * from the function's files and keeps `requestContext()` in\n * `AsyncLocalStorage`, as the node host does. It has no listeners and no\n * lifecycle: Vercel starts and stops the function, and {@link handler} calls\n * the entry's `fetch`. It reads a file that the function keeps only as a\n * brotli copy through that copy (see `vercel()`).\n *\n * Why no gzip: Vercel's CDN compresses each response, with Brotli when the\n * client accepts it.\n *\n * @example\n * export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });\n */\nexport const host: HostRuntime = {\n\tname: \"vercel\",\n\tfiles: (clientDirectory) => {\n\t\tconst files = brotliOnlyFiles(nodeHost.files(clientDirectory));\n\t\tconst builtAt = Number(process.env.APP_SERVER_BUILT_AT);\n\t\treturn Number.isFinite(builtAt) ? withModifiedTime(files, builtAt) : files;\n\t},\n\t...(nodeHost.storage == null ? {} : { storage: nodeHost.storage }),\n};\n\n/**\n * The function handler for the entry of a server build. The function file\n * that `vercel()` writes exports it.\n *\n * - The scheme comes from `X-Forwarded-Proto`, and the client address from\n * `X-Real-IP`. Why trust them: Vercel sets both headers on each request,\n * and replaces a value that the client sends.\n * - The node response writer sends each response, as the node host's\n * listener does.\n * - The log lines of the request reach stdout before the handler returns.\n * Why: Vercel can freeze the function after the response, before the next\n * turn of the event loop writes them.\n *\n * @example\n * export default hostModule.handler(appServer);\n */\nexport function handler(\n\tentry: AppServerEntry,\n): (incoming: IncomingMessage, outgoing: ServerResponse) => Promise<void> {\n\tconst listener = requestListener(\n\t\tasync (request, bindings) => {\n\t\t\tconst realIp = bindings.incoming?.headers[\"x-real-ip\"];\n\t\t\treturn entry.fetch(withForwardedProto(request), {\n\t\t\t\t...bindings,\n\t\t\t\t...(typeof realIp === \"string\" ? { remoteAddress: realIp } : {}),\n\t\t\t});\n\t\t},\n\t\t{ trustForwardedProto: true },\n\t);\n\treturn async (incoming, outgoing) => {\n\t\ttry {\n\t\t\tawait listener(incoming, outgoing);\n\t\t\t// Why wait: the access log writes its line when the response closes, after the listener returns.\n\t\t\tif (!outgoing.closed) {\n\t\t\t\tawait new Promise((resolve) => {\n\t\t\t\t\toutgoing.once(\"close\", resolve);\n\t\t\t\t});\n\t\t\t}\n\t\t} finally {\n\t\t\tflushLogs();\n\t\t\t// Why wait: a full pipe keeps the rest of a write in a queue, and a frozen function does not send it.\n\t\t\tif (process.stdout.writableLength > 0) {\n\t\t\t\tawait new Promise((resolve) => {\n\t\t\t\t\tprocess.stdout.write(\"\", resolve);\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,SAAS,iBAAiB,OAAoB,SAA8B;CAC3E,MAAM,EAAE,aAAa;CACrB,OAAO;EACN,MAAM,OAAO,SAAS;GACrB,MAAM,OAA6B,MAAM,MAAM,KAAK,IAAI;GACxD,OAAO,QAAQ,OAAO,SAAY;IAAE,GAAG;IAAM;GAAQ;EACtD;EACA,MAAM,MAAM;EACZ,GAAI,YAAY,OACb,CAAC,IACD,EAAE,UAAU,YAAY,iBAAiB,MAAM,SAAS,GAAG,OAAO,EAAE;CACxE;AACD;;;;;;;;;;;;;;;AAgBA,MAAa,OAAoB;CAChC,MAAM;CACN,QAAQ,oBAAoB;EAC3B,MAAM,QAAQ,gBAAgBA,OAAS,MAAM,eAAe,CAAC;EAC7D,MAAM,UAAU,OAAO,QAAQ,IAAI,mBAAmB;EACtD,OAAO,OAAO,SAAS,OAAO,IAAI,iBAAiB,OAAO,OAAO,IAAI;CACtE;CACA,GAAIA,OAAS,WAAW,OAAO,CAAC,IAAI,EAAE,SAASA,OAAS,QAAQ;AACjE;;;;;;;;;;;;;;;;;AAkBA,SAAgB,QACf,OACyE;CACzE,MAAM,WAAW,gBAChB,OAAO,SAAS,aAAa;EAC5B,MAAM,SAAS,SAAS,UAAU,QAAQ;EAC1C,OAAO,MAAM,MAAM,mBAAmB,OAAO,GAAG;GAC/C,GAAG;GACH,GAAI,OAAO,WAAW,WAAW,EAAE,eAAe,OAAO,IAAI,CAAC;EAC/D,CAAC;CACF,GACA,EAAE,qBAAqB,KAAK,CAC7B;CACA,OAAO,OAAO,UAAU,aAAa;EACpC,IAAI;GACH,MAAM,SAAS,UAAU,QAAQ;GAEjC,IAAI,CAAC,SAAS,QACb,MAAM,IAAI,SAAS,YAAY;IAC9B,SAAS,KAAK,SAAS,OAAO;GAC/B,CAAC;EAEH,UAAU;GACT,UAAU;GAEV,IAAI,QAAQ,OAAO,iBAAiB,GACnC,MAAM,IAAI,SAAS,YAAY;IAC9B,QAAQ,OAAO,MAAM,IAAI,OAAO;GACjC,CAAC;EAEH;CACD;AACD"}
@@ -1,7 +1,7 @@
1
1
  import { n as DEFAULT_ASSETS_PATH, r as manifestKey, t as BUILD_MANIFEST_FILE } from "./build-manifest-DBMWe3Lx.js";
2
- import { a as isCompressible, n as MIN_COMPRESS_BYTES, r as copyName } from "./compression-7_gToa8R.js";
3
- import { t as contentType } from "./static-files-Beju9riB.js";
4
- import { n as scriptHashesOf } from "./script-hashes-C6hQ5XnP.js";
2
+ import { a as isCompressible, n as MIN_COMPRESS_BYTES, r as copyName } from "./compression-CT2mWlKM.js";
3
+ import { t as contentType } from "./static-files-C2ea8KQ6.js";
4
+ import { n as scriptHashesOf } from "./script-hashes-CU7P9oZU.js";
5
5
  import { t as node } from "./vite-D4hfj3ph.js";
6
6
  import { t as reactRouterAdapter } from "./vite-B-GfswoH.js";
7
7
  import { t as tanstackStartAdapter } from "./vite-DyrhyKEr.js";
@@ -11,6 +11,7 @@ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync,
11
11
  import { basename, dirname, extname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
12
12
  import { brotliCompressSync, constants as constants$1, gzipSync } from "node:zlib";
13
13
  import { createHash } from "node:crypto";
14
+ import { nodeFileTrace } from "@vercel/nft";
14
15
 
15
16
  // src/vite/standalone.ts
16
17
  /**
@@ -128,25 +129,30 @@ function lookupDirectories(destination, target) {
128
129
  /**
129
130
  * Copies each package, whole, with the installed packages of its
130
131
  * `dependencies`, `optionalDependencies`, and `peerDependencies`, into the
131
- * `node_modules` directory `target`. Node then finds each package from a file
132
- * next to `target`, with no install. The copy follows symbolic links. A
133
- * dependency goes to the top of `target`. If another copy of that package is
134
- * nearer in the lookup path of the package that needs it, the dependency goes
135
- * into that package's own `node_modules`.
132
+ * `node_modules` directory `target`, except the packages in `omit`. Node then
133
+ * finds each package from a file next to `target`, with no install. The copy
134
+ * follows symbolic links. A dependency goes to the top of `target`. If another
135
+ * copy of that package is nearer in the lookup path of the package that needs
136
+ * it, the dependency goes into that package's own `node_modules`.
136
137
  *
137
138
  * @example
138
139
  * copyPackages(new Map([["oxc-parser", "/app/node_modules/oxc-parser"]]), "/app/build/server/node_modules");
139
140
  */
140
- function copyPackages(packages, target) {
141
- const sources = /* @__PURE__ */ new Map();
141
+ function copyPackages(packages, target, { omit = /* @__PURE__ */ new Set() } = {}) {
142
+ const copied = /* @__PURE__ */ new Map();
142
143
  const queue = [];
143
- const add = (destination, source) => {
144
- sources.set(destination, source);
145
- queue.push(destination);
144
+ const add = (destination, name, source) => {
145
+ const copy = {
146
+ name,
147
+ source,
148
+ dependencies: []
149
+ };
150
+ copied.set(destination, copy);
151
+ queue.push([destination, copy]);
146
152
  };
147
- for (const [name, source] of packages) add(join(target, name), source);
148
- for (const destination of queue) {
149
- const source = sources.get(destination) ?? "";
153
+ for (const [name, source] of packages) if (!omit.has(name)) add(join(target, name), name, source);
154
+ for (const [destination, copy] of queue) {
155
+ const { source } = copy;
150
156
  cpSync(source, destination, {
151
157
  recursive: true,
152
158
  dereference: true,
@@ -158,10 +164,104 @@ function copyPackages(packages, target) {
158
164
  "peerDependencies"
159
165
  ])) {
160
166
  const dependency = findPackage(name, source);
161
- const found = lookupDirectories(destination, target).map((directory) => join(directory, name)).find((path) => sources.has(path));
162
- if (dependency != null && (found == null || sources.get(found) !== dependency)) add(join(found == null ? target : join(destination, "node_modules"), name), dependency);
167
+ const found = lookupDirectories(destination, target).map((directory) => join(directory, name)).find((path) => copied.has(path));
168
+ if (dependency != null && !omit.has(name)) {
169
+ if (found == null || copied.get(found)?.source !== dependency) {
170
+ const placed = join(found == null ? target : join(destination, "node_modules"), name);
171
+ add(placed, name, dependency);
172
+ copy.dependencies.push(placed);
173
+ } else copy.dependencies.push(found);
174
+ }
163
175
  }
164
176
  }
177
+ return copied;
178
+ }
179
+ /** Each file under `directory`, except in a `node_modules` directory. */
180
+ function ownFiles(directory) {
181
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
182
+ const path = join(entry.parentPath, entry.name);
183
+ if (entry.isDirectory()) return entry.name === "node_modules" ? [] : ownFiles(path);
184
+ return [path];
185
+ });
186
+ }
187
+ /** Removes each empty directory in `directory`, and `directory` when it is then empty. */
188
+ function removeEmptyDirectories(directory) {
189
+ for (const entry of readdirSync(directory, { withFileTypes: true })) if (entry.isDirectory()) removeEmptyDirectories(join(directory, entry.name));
190
+ if (readdirSync(directory).length === 0) rmSync(directory, { recursive: true });
191
+ }
192
+ /**
193
+ * The export conditions of each runtime that the server runs on, besides
194
+ * `import`, `require`, and `default`. Why each: Bun and Deno take their own
195
+ * entry of a package before its `node` entry.
196
+ */
197
+ const RUNTIME_CONDITIONS = [
198
+ ["node"],
199
+ ["bun", "node"],
200
+ ["deno", "node"]
201
+ ];
202
+ /**
203
+ * A `require.resolve()` or an `import.meta.resolve()` of a string literal.
204
+ * The `source` group is the string.
205
+ */
206
+ const RESOLVE_CALL = /\b(?:require|import\.meta)\.resolve\(\s*(?<quote>["'`])(?<source>[^"'`$]+)\k<quote>/gu;
207
+ /** Code that finds a file next to its own module in a way that `@vercel/nft` does not follow. */
208
+ const UNTRACED_OWN_FILE = /import\.meta\.(?:dirname|filename)\b/u;
209
+ /** The warning of `@vercel/nft` for a module that it cannot parse, such as a TypeScript file, so it finds no import of it. */
210
+ const UNPARSED = /^Failed to parse (?<file>.+) as module:/u;
211
+ /**
212
+ * Removes each file of a package in `copied` that the server build in
213
+ * `serverDirectory` cannot load, as `@vercel/nft` traces it from each module
214
+ * of the build. A package that no traced file is in goes away whole. Each
215
+ * package for which `whole` is true, and each package that it depends on,
216
+ * keeps each file. Why: a native package can load a library through the
217
+ * system's loader, such as `sharp` loads libvips, and a trace cannot see it.
218
+ * The trace misses the files that a module loads through
219
+ * {@link UNTRACED_OWN_FILE}, the imports of a module that it cannot parse,
220
+ * and a file that {@link RESOLVE_CALL} finds through the `exports` of a
221
+ * package. So the package of such a module, or the package that it
222
+ * resolves, keeps each file, with each package that it depends on.
223
+ *
224
+ * @example
225
+ * await removeUntraced("/app/build/server", copied, (copy) => isNativePackage(copy.source));
226
+ */
227
+ async function removeUntraced(serverDirectory, copied, whole) {
228
+ const kept = /* @__PURE__ */ new Set();
229
+ const keep = (destination) => {
230
+ if (!kept.has(destination)) {
231
+ kept.add(destination);
232
+ for (const dependency of copied.get(destination)?.dependencies ?? []) keep(dependency);
233
+ }
234
+ };
235
+ for (const [destination, copy] of copied) if (whole(copy)) keep(destination);
236
+ if (kept.size === copied.size) return;
237
+ const modules = ownFiles(serverDirectory).filter((file) => /\.[cm]?js$/u.test(file));
238
+ const cache = {};
239
+ const traces = await Promise.all(RUNTIME_CONDITIONS.map(async (conditions) => nodeFileTrace(modules, {
240
+ base: serverDirectory,
241
+ mixedModules: true,
242
+ conditions,
243
+ cache
244
+ })));
245
+ const traced = new Set(traces.flatMap(({ fileList }) => [...fileList].map((file) => join(serverDirectory, file))));
246
+ const real = realpathSync(serverDirectory);
247
+ const unparsed = new Set(traces.flatMap(({ warnings }) => [...warnings].flatMap(({ message }) => {
248
+ const file = UNPARSED.exec(message)?.groups?.file;
249
+ return file == null ? [] : [join(serverDirectory, relative(real, file))];
250
+ })));
251
+ const present = [...copied.keys()].filter((destination) => existsSync(destination));
252
+ for (const destination of present.filter((each) => !kept.has(each))) {
253
+ const loaded = ownFiles(destination).filter((file) => traced.has(file));
254
+ const code = loaded.filter((file) => /\.[cm]?js$/u.test(file)).map((file) => readFileSync(file, "utf8"));
255
+ if (loaded.some((file) => unparsed.has(file)) || code.some((each) => UNTRACED_OWN_FILE.test(each))) keep(destination);
256
+ const resolved = new Set(code.flatMap((each) => [...each.matchAll(RESOLVE_CALL)].map(({ groups }) => packageName(groups?.source ?? ""))));
257
+ for (const each of [destination, ...copied.get(destination)?.dependencies ?? []]) if (resolved.has(copied.get(each)?.name ?? "")) keep(each);
258
+ }
259
+ for (const destination of present.filter((each) => !kept.has(each))) {
260
+ const files = ownFiles(destination);
261
+ const used = files.some((file) => traced.has(file));
262
+ for (const file of files) if (!traced.has(file) && !(used && basename(file) === "package.json")) rmSync(file);
263
+ }
264
+ removeEmptyDirectories(join(serverDirectory, "node_modules"));
165
265
  }
166
266
 
167
267
  // src/vite/index.ts
@@ -288,11 +388,6 @@ function outDir(config, environment) {
288
388
  function isJavaScriptFile(id) {
289
389
  return isAbsolute(id) && !id.includes("?") && JAVASCRIPT_EXTENSIONS.has(extname(id));
290
390
  }
291
- /**
292
- * A `require.resolve()` or an `import.meta.resolve()` of a string literal.
293
- * The `source` group is the string.
294
- */
295
- const RESOLVE_CALL = /\b(?:require|import\.meta)\.resolve\(\s*(?<quote>["'`])(?<source>[^"'`$]+)\k<quote>/gu;
296
391
  /** The dependency fields of the app's `package.json` that can name a package the server imports. */
297
392
  const APP_DEPENDENCY_FIELDS = [
298
393
  "dependencies",
@@ -310,11 +405,15 @@ function isServerBuild(environment) {
310
405
  * each package that reads a file next to its own module (see `readsOwnFiles`),
311
406
  * and each package that the bundle shares with a package that the app keeps
312
407
  * external: the whole package of an external subpath, and each peer, at each
313
- * level. Those stay external, so the plugin copies each one, whole, with its
314
- * dependencies, into `node_modules` in the server build. It also writes a `package.json` there, so
315
- * Node, Bun, and Deno load the build as ES modules and find that `node_modules`.
408
+ * level. Those stay external, so the plugin copies each one, with its
409
+ * dependencies, into `node_modules` in the server build, and then removes each
410
+ * file that the build cannot load (see `removeUntraced`). A package in
411
+ * `ssr.external`, and a package that the app reads at run time, such as
412
+ * through `require.resolve`, keep each file. It also writes a `package.json` there, so Node, Bun, and
413
+ * Deno load the build as ES modules and find that `node_modules`.
316
414
  */
317
- function standalone() {
415
+ function standalone({ whole = [], omit = [] } = {}) {
416
+ const readByApp = /* @__PURE__ */ new Set();
318
417
  const externals = /* @__PURE__ */ new Map();
319
418
  const shared = /* @__PURE__ */ new Set();
320
419
  const natives = /* @__PURE__ */ new Map();
@@ -365,6 +464,7 @@ function standalone() {
365
464
  buildStart() {
366
465
  if (!isServerBuild(this.environment)) return;
367
466
  externals.clear();
467
+ readByApp.clear();
368
468
  shared.clear();
369
469
  natives.clear();
370
470
  scans.clear();
@@ -377,7 +477,10 @@ function standalone() {
377
477
  const matched = patterns.length === 0 || !existsSync(join(root, "package.json")) ? [] : dependencyNames(root, APP_DEPENDENCY_FIELDS).filter((name) => patterns.some((pattern) => matchesExternal(pattern, name)));
378
478
  for (const name of names) {
379
479
  const directory = findPackage(name, root);
380
- if (directory != null) externals.set(name, directory);
480
+ if (directory != null) {
481
+ externals.set(name, directory);
482
+ readByApp.add(name);
483
+ }
381
484
  }
382
485
  for (const name of withPeers([...names, ...matched].map((dependency) => ({
383
486
  name: dependency,
@@ -422,11 +525,12 @@ function standalone() {
422
525
  const name = packageName(source);
423
526
  const directory = BARE_IMPORT.test(source) && !isBuiltin(source) && !externals.has(name) ? findPackage(name, isAbsolute(id) ? dirname(id) : this.environment.config.root) : void 0;
424
527
  if (directory != null) externals.set(name, directory);
528
+ if (BARE_IMPORT.test(source) && !isBuiltin(source)) readByApp.add(name);
425
529
  }
426
530
  return null;
427
531
  }
428
532
  },
429
- writeBundle() {
533
+ async writeBundle() {
430
534
  if (!isServerBuild(this.environment)) return;
431
535
  for (const importer of this.getModuleIds()) {
432
536
  const info = this.getModuleInfo(importer);
@@ -444,9 +548,11 @@ function standalone() {
444
548
  recursive: true,
445
549
  force: true
446
550
  });
447
- copyPackages(found, target);
551
+ const copied = copyPackages(found, target, { omit: new Set(omit) });
552
+ const kept = /* @__PURE__ */ new Set([...whole, ...readByApp]);
553
+ await removeUntraced(directory, copied, ({ name, source }) => kept.has(name) || isNative(source));
448
554
  writeFileSync(join(directory, "package.json"), `${JSON.stringify({ type: "module" })}\n`);
449
- if (found.size > 0) this.environment.logger.info(`@ngrok/app-server copied the external packages ${[...found.keys()].join(", ")}, with their dependencies, into ${target}.`);
555
+ if (found.size > 0) this.environment.logger.info(`@ngrok/app-server copied the external packages ${[...found.keys()].join(", ")}, with the files of their dependencies that the server build loads, into ${target}.`);
450
556
  }
451
557
  };
452
558
  }
@@ -756,9 +862,9 @@ function appServer(options = {}) {
756
862
  }
757
863
  }
758
864
  },
759
- standalone()
865
+ standalone(options.externals)
760
866
  ];
761
867
  }
762
868
 
763
869
  export { appServer as n, serverEntrySource as r, SERVER_ENTRY_ID as t };
764
- //# sourceMappingURL=vite-BDREIgiH.js.map
870
+ //# sourceMappingURL=vite-DPiSKHDn.js.map