@ngrok/app-server 0.3.3 → 0.3.4

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 (63) hide show
  1. package/README.md +13 -9
  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-JuJf2HaO.js +377 -0
  6. package/dist/compress-JuJf2HaO.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-BX2rH6-E.js} +45 -26
  10. package/dist/{create-server-jMl2ltHD.js.map → create-server-BX2rH6-E.js.map} +1 -1
  11. package/dist/{create-server-D4-nVOVJ.d.ts → create-server-kxyhCdhv.d.ts} +3 -3
  12. package/dist/{entry-BPrgE_6K.d.ts → entry-CNL4OsEn.d.ts} +3 -3
  13. package/dist/{entry-D9H4LA9c.js → entry-ChHgs269.js} +4 -3
  14. package/dist/{entry-D9H4LA9c.js.map → entry-ChHgs269.js.map} +1 -1
  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 +2 -2
  18. package/dist/{load-entry-D7r0mjEp.js → load-entry-BOgJPt1I.js} +4 -4
  19. package/dist/{load-entry-D7r0mjEp.js.map → load-entry-BOgJPt1I.js.map} +1 -1
  20. package/dist/{node-C1qudLs_.js → node-B0AYf_IA.js} +5 -4
  21. package/dist/{node-C1qudLs_.js.map → node-B0AYf_IA.js.map} +1 -1
  22. package/dist/{node-tBVQPjQv.js → node-C0Ad7CVL.js} +2 -2
  23. package/dist/{node-tBVQPjQv.js.map → node-C0Ad7CVL.js.map} +1 -1
  24. package/dist/node-vite.d.ts +1 -1
  25. package/dist/node.d.ts +1 -1
  26. package/dist/node.js +2 -2
  27. package/dist/react-router-vite.d.ts +1 -1
  28. package/dist/react-router.d.ts +1 -1
  29. package/dist/{response-writer-B7FoJjEE.js → response-writer-DzvUAz9x.js} +3 -3
  30. package/dist/response-writer-DzvUAz9x.js.map +1 -0
  31. package/dist/{script-hashes-C6hQ5XnP.js → script-hashes-CU7P9oZU.js} +2 -2
  32. package/dist/{script-hashes-C6hQ5XnP.js.map → script-hashes-CU7P9oZU.js.map} +1 -1
  33. package/dist/{serve-E0hSGe6_.js → serve-BUJ7ZonG.js} +2 -2
  34. package/dist/{serve-E0hSGe6_.js.map → serve-BUJ7ZonG.js.map} +1 -1
  35. package/dist/{start-CifYPRq1.js → start-DiQf9ttp.js} +6 -6
  36. package/dist/{start-CifYPRq1.js.map → start-DiQf9ttp.js.map} +1 -1
  37. package/dist/{static-files-Beju9riB.js → static-files-C2ea8KQ6.js} +11 -3
  38. package/dist/static-files-C2ea8KQ6.js.map +1 -0
  39. package/dist/tanstack-start-vite.d.ts +1 -1
  40. package/dist/tanstack-start.d.ts +2 -2
  41. package/dist/{tcp-Dd1Mt6sN.js → tcp-Bws6oEau.js} +2 -2
  42. package/dist/{tcp-Dd1Mt6sN.js.map → tcp-Bws6oEau.js.map} +1 -1
  43. package/dist/testing.d.ts +2 -2
  44. package/dist/testing.js +3 -3
  45. package/dist/{trailing-slash-CFSv_Gzx.d.ts → trailing-slash-DeOUxMYo.d.ts} +2 -2
  46. package/dist/{types-j29vspx_.d.ts → types-BKJxtIuj.d.ts} +10 -3
  47. package/dist/vercel-vite.d.ts +1 -1
  48. package/dist/vercel-vite.js +24 -4
  49. package/dist/vercel-vite.js.map +1 -1
  50. package/dist/vercel.d.ts +4 -3
  51. package/dist/vercel.js +7 -5
  52. package/dist/vercel.js.map +1 -1
  53. package/dist/{vite-BDREIgiH.js → vite-DPiSKHDn.js} +139 -33
  54. package/dist/vite-DPiSKHDn.js.map +1 -0
  55. package/dist/vite.d.ts +1 -1
  56. package/dist/vite.js +1 -1
  57. package/package.json +2 -1
  58. package/dist/compression-7_gToa8R.js.map +0 -1
  59. package/dist/gzip-Doi4wqjX.js +0 -294
  60. package/dist/gzip-Doi4wqjX.js.map +0 -1
  61. package/dist/response-writer-B7FoJjEE.js.map +0 -1
  62. package/dist/static-files-Beju9riB.js.map +0 -1
  63. package/dist/vite-BDREIgiH.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { t as contentType } from "./static-files-Beju9riB.js";
1
+ import { t as contentType } from "./static-files-C2ea8KQ6.js";
2
2
  import { readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { join, relative, resolve, sep } from "node:path";
4
4
  import { createHash } from "node:crypto";
@@ -68,4 +68,4 @@ function scriptHashesOf(clientDirectory) {
68
68
  }
69
69
 
70
70
  export { scriptHashesOf as n, publicScriptHashes as t };
71
- //# sourceMappingURL=script-hashes-C6hQ5XnP.js.map
71
+ //# sourceMappingURL=script-hashes-CU7P9oZU.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"script-hashes-C6hQ5XnP.js","names":[],"sources":["../src/node/script-hashes.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\nimport { contentType } from \"../core/static-files.js\";\n\n/**\n * An HTML comment, or a `<script>` element. The `attributes` group is the\n * script's attributes, and the `text` group is its text. Why the comment: a\n * `<script>` tag in a comment starts no element.\n */\nconst COMMENT_OR_SCRIPT =\n\t/<!--[\\s\\S]*?-->|<script(?=[\\s/>])(?<attributes>(?:[^>\"']|\"[^\"]*\"|'[^']*')*)>(?<text>[\\s\\S]*?)<\\/script(?=[\\s/>])/giu;\n\n/** An attribute value, so that a `src=` in a value is not the `src` attribute. */\nconst ATTRIBUTE_VALUE = /[=]\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/gu;\n\n/** A `src` attribute, in attributes with no values. */\nconst SRC_ATTRIBUTE = /(?:^|[\\s/])src(?:[\\s/=]|$)/iu;\n\n/**\n * The base64 `SHA-256` of each inline script in `html`, once each, in\n * document order. Why each type: a hash of a data block, such as JSON, trusts\n * no code, and a scan that skips a type that runs breaks the page. Why LF:\n * the browser changes each CRLF and CR to LF before it hashes a script.\n *\n * @example\n * inlineScriptHashes(\"<script>go()</script>\"); // => [\"…base64…\"]\n */\nexport function inlineScriptHashes(html: string): string[] {\n\tconst hashes: string[] = [];\n\tfor (const { groups } of html.replaceAll(/\\r\\n?/gu, \"\\n\").matchAll(COMMENT_OR_SCRIPT)) {\n\t\tif (\n\t\t\tgroups?.text != null &&\n\t\t\t!SRC_ATTRIBUTE.test((groups.attributes ?? \"\").replaceAll(ATTRIBUTE_VALUE, \"=\"))\n\t\t) {\n\t\t\thashes.push(createHash(\"sha256\").update(groups.text).digest(\"base64\"));\n\t\t}\n\t}\n\treturn [...new Set(hashes)];\n}\n\n/**\n * The {@link inlineScriptHashes} of the HTML file at the URL `path` in\n * `directory`, such as Vite's public directory, or `undefined` when it has no\n * such file. Why it reads the file for each call: a developer can edit it at\n * any time, and only a request for an HTML file reads it.\n *\n * @example\n * publicScriptHashes(\"/app/public\", \"/offline.html\"); // => [\"…base64…\"]\n */\nexport function publicScriptHashes(directory: string, path: string): string[] | undefined {\n\tif (directory === \"\") {\n\t\treturn undefined;\n\t}\n\t// Why one `try`: a path that does not decode, a path with a null byte, and a file that the\n\t// developer deletes or locks between the checks each throw. The middleware then answers.\n\ttry {\n\t\tconst decoded = decodeURIComponent(path);\n\t\tconst file = resolve(directory, `.${decoded}`);\n\t\t// Why: a path such as `/../secret.html` must not leave the directory.\n\t\tif (\n\t\t\t!contentType(decoded, {}).startsWith(\"text/html\") ||\n\t\t\t!file.startsWith(`${resolve(directory)}${sep}`) ||\n\t\t\tstatSync(file, { throwIfNoEntry: false })?.isFile() !== true\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn inlineScriptHashes(readFileSync(file, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * The {@link inlineScriptHashes} of each HTML file in the client build, by its URL path.\n *\n * @example\n * scriptHashesOf(\"/app/build/client\"); // => { \"/about/index.html\": [\"…base64…\"] }\n */\nexport function scriptHashesOf(clientDirectory: string): BuildManifest[\"scriptHashes\"] {\n\tconst hashes: BuildManifest[\"scriptHashes\"] = {};\n\tfor (const entry of readdirSync(clientDirectory, { recursive: true, withFileTypes: true })) {\n\t\t// Why `contentType`: the static stages send each file of an HTML type, such as `.htm`, as a document.\n\t\tif (entry.isFile() && contentType(entry.name, {}).startsWith(\"text/html\")) {\n\t\t\tconst path = join(entry.parentPath, entry.name);\n\t\t\tconst urlPath = `/${relative(clientDirectory, path).split(sep).join(\"/\")}`;\n\t\t\thashes[urlPath] = inlineScriptHashes(readFileSync(path, \"utf8\"));\n\t\t}\n\t}\n\treturn Object.fromEntries(\n\t\tObject.entries(hashes).toSorted(([first], [second]) => first.localeCompare(second)),\n\t);\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,oBACL;;AAGD,MAAM,kBAAkB;;AAGxB,MAAM,gBAAgB;;;;;;;;;;AAWtB,SAAgB,mBAAmB,MAAwB;CAC1D,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,EAAE,YAAY,KAAK,WAAW,WAAW,IAAI,CAAC,CAAC,SAAS,iBAAiB,GACnF,IACC,QAAQ,QAAQ,QAChB,CAAC,cAAc,MAAM,OAAO,cAAc,GAAE,CAAE,WAAW,iBAAiB,GAAG,CAAC,GAE9E,OAAO,KAAK,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,IAAI,CAAC,CAAC,OAAO,QAAQ,CAAC;CAGvE,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC3B;;;;;;;;;;AAWA,SAAgB,mBAAmB,WAAmB,MAAoC;CACzF,IAAI,cAAc,IACjB;CAID,IAAI;EACH,MAAM,UAAU,mBAAmB,IAAI;EACvC,MAAM,OAAO,QAAQ,WAAW,IAAI,SAAS;EAE7C,IACC,CAAC,YAAY,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,KAChD,CAAC,KAAK,WAAW,GAAG,QAAQ,SAAS,IAAI,KAAK,KAC9C,SAAS,MAAM,EAAE,gBAAgB,MAAM,CAAC,CAAC,EAAE,OAAO,MAAM,MAExD;EAED,OAAO,mBAAmB,aAAa,MAAM,MAAM,CAAC;CACrD,QAAQ;EACP;CACD;AACD;;;;;;;AAQA,SAAgB,eAAe,iBAAwD;CACtF,MAAM,SAAwC,CAAC;CAC/C,KAAK,MAAM,SAAS,YAAY,iBAAiB;EAAE,WAAW;EAAM,eAAe;CAAK,CAAC,GAExF,IAAI,MAAM,OAAO,KAAK,YAAY,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,GAAG;EAC1E,MAAM,OAAO,KAAK,MAAM,YAAY,MAAM,IAAI;EAC9C,MAAM,UAAU,IAAI,SAAS,iBAAiB,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;EACvE,OAAO,WAAW,mBAAmB,aAAa,MAAM,MAAM,CAAC;CAChE;CAED,OAAO,OAAO,YACb,OAAO,QAAQ,MAAM,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,YAAY,MAAM,cAAc,MAAM,CAAC,CACnF;AACD"}
1
+ {"version":3,"file":"script-hashes-CU7P9oZU.js","names":[],"sources":["../src/node/script-hashes.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { join, relative, resolve, sep } from \"node:path\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\nimport { contentType } from \"../core/static-files.js\";\n\n/**\n * An HTML comment, or a `<script>` element. The `attributes` group is the\n * script's attributes, and the `text` group is its text. Why the comment: a\n * `<script>` tag in a comment starts no element.\n */\nconst COMMENT_OR_SCRIPT =\n\t/<!--[\\s\\S]*?-->|<script(?=[\\s/>])(?<attributes>(?:[^>\"']|\"[^\"]*\"|'[^']*')*)>(?<text>[\\s\\S]*?)<\\/script(?=[\\s/>])/giu;\n\n/** An attribute value, so that a `src=` in a value is not the `src` attribute. */\nconst ATTRIBUTE_VALUE = /[=]\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s>]+)/gu;\n\n/** A `src` attribute, in attributes with no values. */\nconst SRC_ATTRIBUTE = /(?:^|[\\s/])src(?:[\\s/=]|$)/iu;\n\n/**\n * The base64 `SHA-256` of each inline script in `html`, once each, in\n * document order. Why each type: a hash of a data block, such as JSON, trusts\n * no code, and a scan that skips a type that runs breaks the page. Why LF:\n * the browser changes each CRLF and CR to LF before it hashes a script.\n *\n * @example\n * inlineScriptHashes(\"<script>go()</script>\"); // => [\"…base64…\"]\n */\nexport function inlineScriptHashes(html: string): string[] {\n\tconst hashes: string[] = [];\n\tfor (const { groups } of html.replaceAll(/\\r\\n?/gu, \"\\n\").matchAll(COMMENT_OR_SCRIPT)) {\n\t\tif (\n\t\t\tgroups?.text != null &&\n\t\t\t!SRC_ATTRIBUTE.test((groups.attributes ?? \"\").replaceAll(ATTRIBUTE_VALUE, \"=\"))\n\t\t) {\n\t\t\thashes.push(createHash(\"sha256\").update(groups.text).digest(\"base64\"));\n\t\t}\n\t}\n\treturn [...new Set(hashes)];\n}\n\n/**\n * The {@link inlineScriptHashes} of the HTML file at the URL `path` in\n * `directory`, such as Vite's public directory, or `undefined` when it has no\n * such file. Why it reads the file for each call: a developer can edit it at\n * any time, and only a request for an HTML file reads it.\n *\n * @example\n * publicScriptHashes(\"/app/public\", \"/offline.html\"); // => [\"…base64…\"]\n */\nexport function publicScriptHashes(directory: string, path: string): string[] | undefined {\n\tif (directory === \"\") {\n\t\treturn undefined;\n\t}\n\t// Why one `try`: a path that does not decode, a path with a null byte, and a file that the\n\t// developer deletes or locks between the checks each throw. The middleware then answers.\n\ttry {\n\t\tconst decoded = decodeURIComponent(path);\n\t\tconst file = resolve(directory, `.${decoded}`);\n\t\t// Why: a path such as `/../secret.html` must not leave the directory.\n\t\tif (\n\t\t\t!contentType(decoded, {}).startsWith(\"text/html\") ||\n\t\t\t!file.startsWith(`${resolve(directory)}${sep}`) ||\n\t\t\tstatSync(file, { throwIfNoEntry: false })?.isFile() !== true\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn inlineScriptHashes(readFileSync(file, \"utf8\"));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * The {@link inlineScriptHashes} of each HTML file in the client build, by its URL path.\n *\n * @example\n * scriptHashesOf(\"/app/build/client\"); // => { \"/about/index.html\": [\"…base64…\"] }\n */\nexport function scriptHashesOf(clientDirectory: string): BuildManifest[\"scriptHashes\"] {\n\tconst hashes: BuildManifest[\"scriptHashes\"] = {};\n\tfor (const entry of readdirSync(clientDirectory, { recursive: true, withFileTypes: true })) {\n\t\t// Why `contentType`: the static stages send each file of an HTML type, such as `.htm`, as a document.\n\t\tif (entry.isFile() && contentType(entry.name, {}).startsWith(\"text/html\")) {\n\t\t\tconst path = join(entry.parentPath, entry.name);\n\t\t\tconst urlPath = `/${relative(clientDirectory, path).split(sep).join(\"/\")}`;\n\t\t\thashes[urlPath] = inlineScriptHashes(readFileSync(path, \"utf8\"));\n\t\t}\n\t}\n\treturn Object.fromEntries(\n\t\tObject.entries(hashes).toSorted(([first], [second]) => first.localeCompare(second)),\n\t);\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,oBACL;;AAGD,MAAM,kBAAkB;;AAGxB,MAAM,gBAAgB;;;;;;;;;;AAWtB,SAAgB,mBAAmB,MAAwB;CAC1D,MAAM,SAAmB,CAAC;CAC1B,KAAK,MAAM,EAAE,YAAY,KAAK,WAAW,WAAW,IAAI,CAAC,CAAC,SAAS,iBAAiB,GACnF,IACC,QAAQ,QAAQ,QAChB,CAAC,cAAc,MAAM,OAAO,cAAc,GAAE,CAAE,WAAW,iBAAiB,GAAG,CAAC,GAE9E,OAAO,KAAK,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,IAAI,CAAC,CAAC,OAAO,QAAQ,CAAC;CAGvE,OAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC;AAC3B;;;;;;;;;;AAWA,SAAgB,mBAAmB,WAAmB,MAAoC;CACzF,IAAI,cAAc,IACjB;CAID,IAAI;EACH,MAAM,UAAU,mBAAmB,IAAI;EACvC,MAAM,OAAO,QAAQ,WAAW,IAAI,SAAS;EAE7C,IACC,CAAC,YAAY,SAAS,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,KAChD,CAAC,KAAK,WAAW,GAAG,QAAQ,SAAS,IAAI,KAAK,KAC9C,SAAS,MAAM,EAAE,gBAAgB,MAAM,CAAC,CAAC,EAAE,OAAO,MAAM,MAExD;EAED,OAAO,mBAAmB,aAAa,MAAM,MAAM,CAAC;CACrD,QAAQ;EACP;CACD;AACD;;;;;;;AAQA,SAAgB,eAAe,iBAAwD;CACtF,MAAM,SAAwC,CAAC;CAC/C,KAAK,MAAM,SAAS,YAAY,iBAAiB;EAAE,WAAW;EAAM,eAAe;CAAK,CAAC,GAExF,IAAI,MAAM,OAAO,KAAK,YAAY,MAAM,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,WAAW,GAAG;EAC1E,MAAM,OAAO,KAAK,MAAM,YAAY,MAAM,IAAI;EAC9C,MAAM,UAAU,IAAI,SAAS,iBAAiB,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;EACvE,OAAO,WAAW,mBAAmB,aAAa,MAAM,MAAM,CAAC;CAChE;CAED,OAAO,OAAO,YACb,OAAO,QAAQ,MAAM,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,YAAY,MAAM,cAAc,MAAM,CAAC,CACnF;AACD"}
@@ -1,4 +1,4 @@
1
- import { t as loadEntry } from "./load-entry-D7r0mjEp.js";
1
+ import { t as loadEntry } from "./load-entry-BOgJPt1I.js";
2
2
  import { existsSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
@@ -26,4 +26,4 @@ async function serve({ buildPath }) {
26
26
  }
27
27
 
28
28
  export { serve };
29
- //# sourceMappingURL=serve-E0hSGe6_.js.map
29
+ //# sourceMappingURL=serve-BUJ7ZonG.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"serve-E0hSGe6_.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
1
+ {"version":3,"file":"serve-BUJ7ZonG.js","names":[],"sources":["../src/cli/serve.ts"],"sourcesContent":["import { existsSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport { loadEntry } from \"./load-entry.js\";\n\n/**\n * Where `app-server serve` looks for the server build when no path is given:\n * the node host's entry in the React Router and Vite output layouts, then a\n * plain React Router build.\n */\nexport const DEFAULT_BUILD_PATHS = [\n\t\"build/server/app-server.js\",\n\t\"dist/server/app-server.js\",\n\t\"build/server/index.js\",\n];\n\n/**\n * Loads a production server build and starts it. The copy of this package in\n * the build runs the server when the build has one: see `loadEntry`.\n */\nexport async function serve({ buildPath }: { buildPath: string | undefined }): Promise<void> {\n\tconst path = buildPath ?? DEFAULT_BUILD_PATHS.find((candidate) => existsSync(candidate));\n\tif (path == null) {\n\t\tthrow new Error(\n\t\t\t`No server build found. Build the app, or pass its path. Looked for: ${DEFAULT_BUILD_PATHS.join(\", \")}.`,\n\t\t);\n\t}\n\tconst build: unknown = await import(pathToFileURL(resolve(path)).href);\n\tawait (await loadEntry(build)).start();\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,sBAAsB;CAClC;CACA;CACA;AACD;;;;;AAMA,eAAsB,MAAM,EAAE,aAA+D;CAC5F,MAAM,OAAO,aAAa,oBAAoB,MAAM,cAAc,WAAW,SAAS,CAAC;CACvF,IAAI,QAAQ,MACX,MAAM,IAAI,MACT,uEAAuE,oBAAoB,KAAK,IAAI,EAAE,EACvG;CAED,MAAM,QAAiB,MAAM,OAAO,cAAc,QAAQ,IAAI,CAAC,CAAC,CAAC;CACjE,OAAO,MAAM,UAAU,KAAK,EAAC,CAAE,MAAM;AACtC"}
@@ -1,9 +1,9 @@
1
- import { t as parsePort } from "./tcp-Dd1Mt6sN.js";
1
+ import { t as parsePort } from "./tcp-Bws6oEau.js";
2
2
  import { r as jsonSink, t as errorAttributes } from "./log-BP6xXXZl.js";
3
- import { i as exitAfterFlush, n as devServerStage } from "./node-C1qudLs_.js";
4
- import { t as requestListener } from "./response-writer-B7FoJjEE.js";
5
- import { t as SERVER_ENTRY_ID } from "./vite-BDREIgiH.js";
6
- import { t as loadEntry } from "./load-entry-D7r0mjEp.js";
3
+ import { i as exitAfterFlush, n as devServerStage } from "./node-B0AYf_IA.js";
4
+ import { t as requestListener } from "./response-writer-DzvUAz9x.js";
5
+ import { t as SERVER_ENTRY_ID } from "./vite-DPiSKHDn.js";
6
+ import { t as loadEntry } from "./load-entry-BOgJPt1I.js";
7
7
  import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
8
8
  import { createServer } from "node:http";
9
9
  import { createServer as createServer$1 } from "node:net";
@@ -250,4 +250,4 @@ function viteHostname(host) {
250
250
  }
251
251
 
252
252
  export { start };
253
- //# sourceMappingURL=start-CifYPRq1.js.map
253
+ //# sourceMappingURL=start-DiQf9ttp.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"start-CifYPRq1.js","names":["createServer","createHttpServer"],"sources":["../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import type { AppServerEntry } from \"../core/entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/** What {@link servedApps} returns. */\ntype ServedApps = {\n\t/** Runs `handle` for a request that `entry` serves. */\n\tserve: <Result>(\n\t\tentry: AppServerEntry,\n\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t) => Promise<Result>;\n\t/**\n\t * At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each\n\t * app still held. Resolves when the hooks finish or pass the deadline.\n\t */\n\tstopAll: () => Promise<void>;\n};\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps(): ServedApps {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\t// Why keep the app until its hooks settle: `stopAll` must wait for hooks that already run.\n\t// `stopPlugins` runs the hooks once, so a second call only waits.\n\tconst retire = async (app: ServedApp) => {\n\t\ttry {\n\t\t\tawait app.entry.stopPlugins();\n\t\t} finally {\n\t\t\tserved.delete(app);\n\t\t}\n\t};\n\treturn {\n\t\tserve: async (entry, handle) => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tvoid retire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tvoid retire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tstopAll: async () => {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(served, async (app) => {\n\t\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\t\tawait retire(app);\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string | undefined;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nasync function bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tfunction onError(error: Error) {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t}\n\t\tfunction onListening() {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t}\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import { createServer as createHttpServer } from \"node:http\";\nimport type { Server } from \"node:http\";\nimport type { Plugin } from \"vite\";\nimport { errorAttributes, jsonSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { loadEntry } from \"./load-entry.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { listenFromPort } from \"./start-port.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port. Vite's plugins get the CLI's HTTP server as\n * `server.httpServer`.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\t// Why `true`, not `{ server }`: Vite then adds a proxy `upgrade` listener to the server, and a\n\t\t// restart does not remove it.\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t\tplugins: [shareHttpServer(httpServer)],\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst { ssr } = viteServer.environments;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tif (!viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")) {\n\t\tawait viteServer.close();\n\t\tthrow new Error(\n\t\t\t\"`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.\",\n\t\t);\n\t}\n\tconst devServer = devServerStage(viteServer.middlewares, {\n\t\tpublicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n\t});\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = requestListener(async (request, bindings) => {\n\t\ttry {\n\t\t\treturn await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) => entry.fetchDev(request, bindings, devServer),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst hostname = process.env.HOST || viteHostname(viteServer.config.server.host);\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tconst pluginsStopped = apps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\tconst httpClosed = new Promise<void>((resolve) => {\n\t\t\t\thttpServer.close(() => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst viteClosed = viteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t\tvoid Promise.all([pluginsStopped, httpClosed, viteClosed]).finally(exitAfterFlush);\n\t\t});\n\t}\n}\n\n/**\n * A Vite plugin that sets `server.httpServer` to the CLI's HTTP server before\n * the `configureServer` hooks of the app's plugins run. Why: in middleware\n * mode, Vite sets it to `null`. Then a plugin that waits for `listening` or\n * `close` on it does nothing, with no error.\n *\n * @example\n * vite.createServer({ plugins: [shareHttpServer(httpServer)] });\n */\nfunction shareHttpServer(httpServer: Server): Plugin {\n\tconst plugin: Plugin = {\n\t\tname: \"@ngrok/app-server:http-server\",\n\t\t// Why first: Vite puts an inline plugin after the config file's plugins, so an app plugin with\n\t\t// `enforce: \"pre\"` and `order: \"pre\"` runs its `configureServer` before this one.\n\t\tconfigResolved: (config) => {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Vite sorts each hook from this array later.\n\t\t\tconst plugins = config.plugins as Plugin[];\n\t\t\tplugins.splice(plugins.indexOf(plugin), 1);\n\t\t\tplugins.unshift(plugin);\n\t\t},\n\t\tconfigureServer: {\n\t\t\torder: \"pre\",\n\t\t\thandler: (server) => {\n\t\t\t\tserver.httpServer = httpServer;\n\t\t\t},\n\t\t},\n\t};\n\treturn plugin;\n}\n\n/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */\nfunction viteHostname(host: string | boolean | undefined): string | undefined {\n\tif (host === true) {\n\t\treturn undefined;\n\t}\n\treturn typeof host === \"string\" && host !== \"\" ? host : \"localhost\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAgB,aAAyB;CACxC,IAAI;CACJ,MAAM,yBAAS,IAAI,IAAe;CAGlC,MAAM,SAAS,OAAO,QAAmB;EACxC,IAAI;GACH,MAAM,IAAI,MAAM,YAAY;EAC7B,UAAU;GACT,OAAO,OAAO,GAAG;EAClB;CACD;CACA,OAAO;EACN,OAAO,OAAO,OAAO,WAAW;GAC/B,IAAI,SAAS,MAAM,QAAQ,MAAM,KAChC,QAAQ,QAAQ;QACV;IACN,IAAI,WAAW,MAAM;KACpB,QAAQ,WAAW;KACnB,IAAI,QAAQ,YAAY,GACvB,AAAK,OAAO,OAAO;IAErB;IACA,UAAU;KAAE;KAAO,SAAS;KAAG,UAAU;IAAM;IAC/C,OAAO,IAAI,OAAO;GACnB;GACA,MAAM,MAAM;GACZ,IAAI,WAAW;GACf,IAAI;IACH,OAAO,MAAM,OAAO,KAAK;GAC1B,UAAU;IACT,IAAI,WAAW;IACf,IAAI,IAAI,YAAY,IAAI,YAAY,GACnC,AAAK,OAAO,GAAG;GAEjB;EACD;EACA,SAAS,YAAY;GACpB,MAAM,QAAQ,IACb,MAAM,KAAK,QAAQ,OAAO,QAAQ;IACjC,IAAI,MAAM,oBAAoB;IAC9B,MAAM,OAAO,GAAG;GACjB,CAAC,CACF;EACD;CACD;AACD;;;ACpEA,MAAM,WAAW;;;;;;;AAyBjB,eAAsB,eACrB,QACA,EAAE,MAAM,UAAU,YAAY,aAAa,mBACzB;CAClB,IAAI,SAAS,GAAG;EACf,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,UAAU,OAAO;GACvB,QAAQ,OAAO,QAAQ,QAAQ,MAAM,GAAG,CAAC;GACzC,QAAQ,QAAQ,MAAM;EACvB;EACA,iBAAiB;GAChB,OAAO;GACP,UAAU,WAAW;IACpB,OAAO,aAAa;GACrB;EACD;CACD;CACA,OAAO;AACR;;AAGA,SAAS,aAAa,MAAwD;CAC7E,IAAI,SAAS,MACZ;CAED,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AACzD"}
1
+ {"version":3,"file":"start-DiQf9ttp.js","names":["createServer","createHttpServer"],"sources":["../src/cli/served-apps.ts","../src/cli/start-port.ts","../src/cli/start.ts"],"sourcesContent":["import type { AppServerEntry } from \"../core/entry.js\";\n\ntype ServedApp = { entry: AppServerEntry; pending: number; replaced: boolean };\n\n/** What {@link servedApps} returns. */\ntype ServedApps = {\n\t/** Runs `handle` for a request that `entry` serves. */\n\tserve: <Result>(\n\t\tentry: AppServerEntry,\n\t\thandle: (entry: AppServerEntry) => Promise<Result>,\n\t) => Promise<Result>;\n\t/**\n\t * At exit: aborts `shutdownSignal()` and runs the `onShutdown` hooks of each\n\t * app still held. Resolves when the hooks finish or pass the deadline.\n\t */\n\tstopAll: () => Promise<void>;\n};\n\n/**\n * Tracks the apps that `app-server start` serves. An edit to `server.ts` makes a\n * new app, and the old app's plugins still hold what their `setup` opened.\n * When the last request that the old app took returns, its `onShutdown` hooks\n * run, and the tracker lets go of it. A route edit makes a new entry with the\n * same app, which keeps its plugins.\n */\nexport function servedApps(): ServedApps {\n\tlet current: ServedApp | undefined;\n\tconst served = new Set<ServedApp>();\n\t// Why keep the app until its hooks settle: `stopAll` must wait for hooks that already run.\n\t// `stopPlugins` runs the hooks once, so a second call only waits.\n\tconst retire = async (app: ServedApp) => {\n\t\ttry {\n\t\t\tawait app.entry.stopPlugins();\n\t\t} finally {\n\t\t\tserved.delete(app);\n\t\t}\n\t};\n\treturn {\n\t\tserve: async (entry, handle) => {\n\t\t\tif (current?.entry.app === entry.app) {\n\t\t\t\tcurrent.entry = entry;\n\t\t\t} else {\n\t\t\t\tif (current != null) {\n\t\t\t\t\tcurrent.replaced = true;\n\t\t\t\t\tif (current.pending === 0) {\n\t\t\t\t\t\tvoid retire(current);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrent = { entry, pending: 0, replaced: false };\n\t\t\t\tserved.add(current);\n\t\t\t}\n\t\t\tconst app = current;\n\t\t\tapp.pending += 1;\n\t\t\ttry {\n\t\t\t\treturn await handle(entry);\n\t\t\t} finally {\n\t\t\t\tapp.pending -= 1;\n\t\t\t\tif (app.replaced && app.pending === 0) {\n\t\t\t\t\tvoid retire(app);\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tstopAll: async () => {\n\t\t\tawait Promise.all(\n\t\t\t\tArray.from(served, async (app) => {\n\t\t\t\t\tapp.entry.abortShutdownSignal();\n\t\t\t\t\tawait retire(app);\n\t\t\t\t}),\n\t\t\t);\n\t\t},\n\t};\n}\n","import { createServer } from \"node:net\";\nimport type { Server } from \"node:net\";\n\nconst MAX_PORT = 65_535;\n\n/** Options for {@link listenFromPort}. */\nexport type ListenFromPortOptions = {\n\t/** The first port to try. 0 lets the OS pick one. */\n\tport: number;\n\t/** @default every interface */\n\thostname?: string | undefined;\n\t/** When true, a port in use throws and no other port is tried. */\n\tstrictPort: boolean;\n\t/** Runs for each port in use before the next port is tried. */\n\tonPortInUse?: (port: number) => void;\n\t/**\n\t * Runs when `strictPort` is true and the server listens on `hostname`, but\n\t * another server holds the port on a wildcard address.\n\t */\n\tonWildcardInUse?: (port: number) => void;\n};\n\n/**\n * Starts `server` on `port`. When the port is in use, it tries each next port\n * up to 65535, like Vite and `react-router-serve` do in development.\n *\n * @returns the port that the server listens on\n */\nexport async function listenFromPort(\n\tserver: Server,\n\t{ port, hostname, strictPort, onPortInUse, onWildcardInUse }: ListenFromPortOptions,\n): Promise<number> {\n\tif (port === 0) {\n\t\tawait bind(server, port, hostname);\n\t\treturn boundPort(server, port);\n\t}\n\tif (strictPort) {\n\t\t// Why a warning and not an error: a server on one other address also fails the wildcard\n\t\t// check, and that server does not share `hostname`. Vite warns for the same reason.\n\t\tconst freeOnWildcard = hostname == null || (await isFreeOnWildcard(port));\n\t\tawait bind(server, port, hostname);\n\t\tif (!freeOnWildcard) {\n\t\t\tonWildcardInUse?.(port);\n\t\t}\n\t\treturn port;\n\t}\n\tfor (let candidate = port; candidate <= MAX_PORT; candidate++) {\n\t\t// Why the wildcard check: a server on `::` and a server on `localhost` can share a port, and\n\t\t// then the browser can reach the other server.\n\t\tif (hostname == null || (await isFreeOnWildcard(candidate))) {\n\t\t\ttry {\n\t\t\t\tawait bind(server, candidate, hostname);\n\t\t\t\treturn candidate;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isAddressInUse(error)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tonPortInUse?.(candidate);\n\t}\n\tthrow new Error(`No open port from ${port} to ${MAX_PORT}.`);\n}\n\nasync function bind(server: Server, port: number, hostname: string | undefined): Promise<void> {\n\treturn new Promise<void>((resolve, reject) => {\n\t\tfunction onError(error: Error) {\n\t\t\tserver.off(\"listening\", onListening);\n\t\t\treject(error);\n\t\t}\n\t\tfunction onListening() {\n\t\t\tserver.off(\"error\", onError);\n\t\t\tresolve();\n\t\t}\n\t\tserver.once(\"error\", onError);\n\t\tserver.once(\"listening\", onListening);\n\t\tserver.listen(port, hostname);\n\t});\n}\n\nasync function isFreeOnWildcard(port: number): Promise<boolean> {\n\tconst probe = createServer();\n\ttry {\n\t\tawait bind(probe, port, undefined);\n\t} catch (error) {\n\t\tif (isAddressInUse(error)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n\tawait new Promise<void>((resolve) => {\n\t\tprobe.close(() => {\n\t\t\tresolve();\n\t\t});\n\t});\n\treturn true;\n}\n\nfunction boundPort(server: Server, fallback: number): number {\n\tconst address = server.address();\n\treturn typeof address === \"object\" && address != null ? address.port : fallback;\n}\n\nfunction isAddressInUse(error: unknown): boolean {\n\treturn error instanceof Error && \"code\" in error && error.code === \"EADDRINUSE\";\n}\n","import { createServer as createHttpServer } from \"node:http\";\nimport type { Server } from \"node:http\";\nimport type { Plugin } from \"vite\";\nimport { errorAttributes, jsonSink } from \"../core/log.js\";\nimport { devServerStage } from \"../node/dev-server.js\";\nimport { exitAfterFlush } from \"../node/exit.js\";\nimport { listenerUrl } from \"../node/runtimes/listen-options.js\";\nimport { requestListener } from \"../node/response-writer.js\";\nimport { parsePort } from \"../node/tcp.js\";\nimport { SERVER_ENTRY_ID } from \"../vite/index.js\";\nimport { loadEntry } from \"./load-entry.js\";\nimport { servedApps } from \"./served-apps.js\";\nimport { listenFromPort } from \"./start-port.js\";\n\n/**\n * Runs the app in development: the same pipeline as production, with Vite in\n * middleware mode inside it. Each request loads the server entry through\n * Vite's SSR runner, so an edit to a route or to the app's `server.ts` applies\n * at once. HMR shares the port. Vite's plugins get the CLI's HTTP server as\n * `server.httpServer`.\n *\n * The port is `--port`, else `PORT`, else Vite's `server.port`. When that port is in use, the\n * server tries each next port, unless Vite's `server.strictPort` is true. The\n * host is `HOST`, else Vite's `server.host`.\n */\nexport async function start(): Promise<void> {\n\tconst vite = await import(\"vite\");\n\tconst httpServer = createHttpServer();\n\tconst viteServer = await vite.createServer({\n\t\t// Why `true`, not `{ server }`: Vite then adds a proxy `upgrade` listener to the server, and a\n\t\t// restart does not remove it.\n\t\tserver: { middlewareMode: true, ws: { server: httpServer } },\n\t\tappType: \"custom\",\n\t\tplugins: [shareHttpServer(httpServer)],\n\t});\n\t// Why read it for each request: a Vite restart, such as after a config edit, replaces the environments.\n\tconst ssrRunner = () => {\n\t\tconst { ssr } = viteServer.environments;\n\t\tif (ssr == null || !vite.isRunnableDevEnvironment(ssr)) {\n\t\t\tthrow new Error(\"Vite's SSR environment cannot run modules.\");\n\t\t}\n\t\treturn ssr.runner;\n\t};\n\tssrRunner();\n\tif (!viteServer.config.plugins.some((plugin) => plugin.name === \"@ngrok/app-server\")) {\n\t\tawait viteServer.close();\n\t\tthrow new Error(\n\t\t\t\"`app-server start` needs the `appServer` plugin from @ngrok/app-server/vite in the Vite config.\",\n\t\t);\n\t}\n\tconst devServer = devServerStage(viteServer.middlewares, {\n\t\tpublicFiles: () => ({ directory: viteServer.config.publicDir, base: viteServer.config.base }),\n\t});\n\tconst sink = jsonSink();\n\tconst apps = servedApps();\n\n\tconst listener = requestListener(async (request, bindings) => {\n\t\ttry {\n\t\t\treturn await apps.serve(\n\t\t\t\tawait loadEntry(await ssrRunner().import(SERVER_ENTRY_ID)),\n\t\t\t\tasync (entry) => entry.fetchDev(request, bindings, devServer),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) {\n\t\t\t\tviteServer.ssrFixStacktrace(error);\n\t\t\t}\n\t\t\tsink.log(\"error\", \"dev request failed\", errorAttributes(error));\n\t\t\treturn new Response(error instanceof Error ? (error.stack ?? error.message) : String(error), {\n\t\t\t\tstatus: 500,\n\t\t\t\theaders: { \"Content-Type\": \"text/plain; charset=utf-8\" },\n\t\t\t});\n\t\t}\n\t});\n\thttpServer.on(\"request\", (request, response) => {\n\t\tvoid listener(request, response);\n\t});\n\n\tconst port =\n\t\tprocess.env.PORT == null ? viteServer.config.server.port : parsePort(process.env.PORT);\n\tconst hostname = process.env.HOST || viteHostname(viteServer.config.server.host);\n\tconst boundPort = await listenFromPort(httpServer, {\n\t\tport,\n\t\thostname,\n\t\tstrictPort: viteServer.config.server.strictPort,\n\t\tonPortInUse: (inUse) => {\n\t\t\tsink.log(\"info\", \"port in use, trying the next port\", { \"server.port\": inUse });\n\t\t},\n\t\tonWildcardInUse: (inUse) => {\n\t\t\tsink.log(\"warn\", \"port in use on a wildcard address\", {\n\t\t\t\t\"server.port\": inUse,\n\t\t\t\t\"server.address\": hostname,\n\t\t\t});\n\t\t},\n\t});\n\tsink.log(\"info\", \"listening\", { \"app_server.urls\": [listenerUrl(hostname, boundPort)] });\n\n\tfor (const signal of [\"SIGTERM\", \"SIGINT\"] as const) {\n\t\tprocess.once(signal, () => {\n\t\t\tconst pluginsStopped = apps.stopAll();\n\t\t\thttpServer.closeAllConnections();\n\t\t\tconst httpClosed = new Promise<void>((resolve) => {\n\t\t\t\thttpServer.close(() => {\n\t\t\t\t\tresolve();\n\t\t\t\t});\n\t\t\t});\n\t\t\tconst viteClosed = viteServer.close().catch((error: unknown) => {\n\t\t\t\tsink.log(\"error\", \"Vite close failed\", errorAttributes(error));\n\t\t\t\tprocess.exitCode = 1;\n\t\t\t});\n\t\t\tvoid Promise.all([pluginsStopped, httpClosed, viteClosed]).finally(exitAfterFlush);\n\t\t});\n\t}\n}\n\n/**\n * A Vite plugin that sets `server.httpServer` to the CLI's HTTP server before\n * the `configureServer` hooks of the app's plugins run. Why: in middleware\n * mode, Vite sets it to `null`. Then a plugin that waits for `listening` or\n * `close` on it does nothing, with no error.\n *\n * @example\n * vite.createServer({ plugins: [shareHttpServer(httpServer)] });\n */\nfunction shareHttpServer(httpServer: Server): Plugin {\n\tconst plugin: Plugin = {\n\t\tname: \"@ngrok/app-server:http-server\",\n\t\t// Why first: Vite puts an inline plugin after the config file's plugins, so an app plugin with\n\t\t// `enforce: \"pre\"` and `order: \"pre\"` runs its `configureServer` before this one.\n\t\tconfigResolved: (config) => {\n\t\t\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Vite sorts each hook from this array later.\n\t\t\tconst plugins = config.plugins as Plugin[];\n\t\t\tplugins.splice(plugins.indexOf(plugin), 1);\n\t\t\tplugins.unshift(plugin);\n\t\t},\n\t\tconfigureServer: {\n\t\t\torder: \"pre\",\n\t\t\thandler: (server) => {\n\t\t\t\tserver.httpServer = httpServer;\n\t\t\t},\n\t\t},\n\t};\n\treturn plugin;\n}\n\n/** The hostname for Vite's `server.host`: `true` is every interface, and no value is `localhost`. */\nfunction viteHostname(host: string | boolean | undefined): string | undefined {\n\tif (host === true) {\n\t\treturn undefined;\n\t}\n\treturn typ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,OAAO,OAAO,SAAS,YAAY,SAAS,KAAK,OAAO;AACzD"}
@@ -1,5 +1,5 @@
1
1
  import { r as hookedHeaders } from "./header-hook-Vzw9J9BY.js";
2
- import { i as forbidsTransform, o as preferredEncoding, r as copyName, t as COPY_ENCODINGS } from "./compression-7_gToa8R.js";
2
+ import { i as forbidsTransform, o as preferredEncoding, r as copyName, t as COPY_ENCODINGS } from "./compression-CT2mWlKM.js";
3
3
  import { getMimeType } from "hono/utils/mime";
4
4
 
5
5
  // src/core/vary.ts
@@ -19,7 +19,15 @@ function withVary(vary, name) {
19
19
 
20
20
  // src/core/static-files.ts
21
21
  /** The content types that `mime` lacks and that no framework owns. */
22
- const CORE_CONTENT_TYPES = { ".md": "text/markdown; charset=utf-8" };
22
+ const CORE_CONTENT_TYPES = {
23
+ ".atom": "application/atom+xml",
24
+ ".md": "text/markdown; charset=utf-8",
25
+ ".pem": "application/x-pem-file",
26
+ ".rss": "application/rss+xml",
27
+ ".sh": "application/x-sh",
28
+ ".yaml": "text/yaml; charset=utf-8",
29
+ ".yml": "text/yaml; charset=utf-8"
30
+ };
23
31
  /**
24
32
  * Whether a URL path names a dotfile or goes through a dot directory.
25
33
  * `/.well-known/` stays reachable.
@@ -299,4 +307,4 @@ async function staticResponse(context, { files, file, headers, contentTypes }) {
299
307
  }
300
308
 
301
309
  export { keptFiles as a, isFilePath as i, findStaticFile as n, staticResponse as o, hasDotSegment as r, withVary as s, contentType as t };
302
- //# sourceMappingURL=static-files-Beju9riB.js.map
310
+ //# sourceMappingURL=static-files-C2ea8KQ6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"static-files-C2ea8KQ6.js","names":[],"sources":["../src/core/vary.ts","../src/core/static-files.ts"],"sourcesContent":["/**\n * A `Vary` value with `name` added, or `undefined` when `vary` already covers\n * it. The existing values stay as they are.\n *\n * @example\n * withVary(\"Accept\", \"Accept-Encoding\"); // => \"Accept, Accept-Encoding\"\n * withVary(\"accept-encoding\", \"Accept-Encoding\"); // => undefined\n */\nexport function withVary(vary: string | null, name: string): string | undefined {\n\tif (vary == null || vary.trim() === \"\") {\n\t\treturn name;\n\t}\n\tconst values = new Set(vary.split(\",\").map((value) => value.trim().toLowerCase()));\n\treturn values.has(name.toLowerCase()) || values.has(\"*\") ? undefined : `${vary}, ${name}`;\n}\n","import type { Context } from \"hono\";\nimport { getMimeType } from \"hono/utils/mime\";\nimport { COPY_ENCODINGS, copyName, forbidsTransform, preferredEncoding } from \"./compression.js\";\nimport type { Encoding } from \"./compression.js\";\nimport { hookedHeaders } from \"./header-hook.js\";\nimport type { AppServerEnv, ByteRange, StaticFiles } from \"./types.js\";\nimport { withVary } from \"./vary.js\";\n\n/** A file under the client build that answers a request. */\nexport type StaticFile = {\n\t/** The URL path of the file, such as `/components/button/index.html`. */\n\tpath: string;\n\tsize: number;\n\tmtimeMs: number;\n};\n\n/** The content types that `mime` lacks and that no framework owns. */\nconst CORE_CONTENT_TYPES: Readonly<Record<string, string>> = {\n\t\".atom\": \"application/atom+xml\",\n\t\".md\": \"text/markdown; charset=utf-8\",\n\t\".pem\": \"application/x-pem-file\",\n\t\".rss\": \"application/rss+xml\",\n\t\".sh\": \"application/x-sh\",\n\t// Why `text/yaml`: a browser shows a text type, and `express.static` sends it.\n\t\".yaml\": \"text/yaml; charset=utf-8\",\n\t\".yml\": \"text/yaml; charset=utf-8\",\n};\n\n/**\n * Whether a URL path names a dotfile or goes through a dot directory.\n * `/.well-known/` stays reachable.\n *\n * @example\n * hasDotSegment(\"/assets/.private/key.json\"); // => true\n * hasDotSegment(\"/.well-known/security.txt\"); // => false\n */\nexport function hasDotSegment(path: string): boolean {\n\treturn path\n\t\t.split(\"/\")\n\t\t.some(\n\t\t\t(segment, index) => segment.startsWith(\".\") && !(index === 1 && segment === \".well-known\"),\n\t\t);\n}\n\n/**\n * Whether a decoded URL path, such as Hono's `context.req.path`, can name a\n * file of the client build. Dotfiles, paths that leave the client build, and\n * a second URL for a file, such as `/a//b` or `/a/index.html`, cannot.\n */\nexport function isFilePath(path: string): boolean {\n\treturn (\n\t\tpath.startsWith(\"/\") &&\n\t\t!path.includes(\"\\0\") &&\n\t\t!path.includes(\"\\\\\") &&\n\t\t!path.split(\"/\").includes(\"..\") &&\n\t\t!path.includes(\"//\") &&\n\t\t!path.endsWith(\"/index.html\") &&\n\t\t!hasDotSegment(path)\n\t);\n}\n\n/**\n * Finds the file in `files` that answers a decoded URL path, such as Hono's\n * `context.req.path`. A directory answers with its `index.html` and no\n * redirect, so a prerendered page keeps its URL. A path that fails\n * `isFilePath` finds nothing.\n *\n * Each file has one URL, because the headers for a file are keyed by that\n * URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes\n * the path but keeps an encoded `/` as `%2F`, so this function does not\n * decode it again.\n *\n * @example\n * await findStaticFile(files, \"/components/button\");\n * // => { path: \"/components/button/index.html\", size: 5120, mtimeMs: 1761652800000 }\n */\nexport async function findStaticFile(\n\tfiles: StaticFiles,\n\tpath: string,\n): Promise<StaticFile | undefined> {\n\tif (!isFilePath(path)) {\n\t\treturn undefined;\n\t}\n\tconst info = await files.stat(path);\n\tif (info?.kind === \"file\") {\n\t\treturn { path, size: info.size, mtimeMs: info.mtimeMs };\n\t}\n\tif (info?.kind === \"directory\") {\n\t\tconst index = `${path.replace(/\\/$/u, \"\")}/index.html`;\n\t\tconst indexInfo = await files.stat(index);\n\t\tif (indexInfo?.kind === \"file\") {\n\t\t\treturn { path: index, size: indexInfo.size, mtimeMs: indexInfo.mtimeMs };\n\t\t}\n\t}\n\treturn undefined;\n}\n\n/** The content type of a file, by its extension. `contentTypes` win over `mime`. */\nexport function contentType(path: string, contentTypes: Readonly<Record<string, string>>): string {\n\tconst extension = /\\.[^./]+$/u.exec(path)?.[0] ?? \"\";\n\treturn (\n\t\tcontentTypes[extension] ??\n\t\tCORE_CONTENT_TYPES[extension] ??\n\t\tgetMimeType(path) ??\n\t\t\"application/octet-stream\"\n\t);\n}\n\n/** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */\nfunction opaqueTag(etag: string): string {\n\treturn etag.trim().replace(/^W\\//u, \"\");\n}\n\n/** Whether an `If-None-Match` header lists an ETag. */\nfunction matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean {\n\treturn (\n\t\tifNoneMatch?.split(\",\").some((candidate) => {\n\t\t\tconst trimmed = candidate.trim();\n\t\t\treturn trimmed === \"*\" || opaqueTag(trimmed) === opaqueTag(etag);\n\t\t}) ?? false\n\t);\n}\n\n/**\n * The last `etagParts` and their hash. Why one entry: each request has the\n * same parts for the life of the process.\n */\nlet lastParts: { key: string; hash: string } | undefined;\n\n/** A short hash of the request's `etagParts`. */\nasync function partsHash(parts: readonly string[]): Promise<string> {\n\tconst key = parts.join(\"\\0\");\n\tif (lastParts?.key === key) {\n\t\treturn lastParts.hash;\n\t}\n\t// Why Web Crypto: each host has it, and the core imports no Node module.\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(key));\n\tconst hash = btoa(String.fromCodePoint(...new Uint8Array(digest)))\n\t\t.replaceAll(\"+\", \"-\")\n\t\t.replaceAll(\"/\", \"_\")\n\t\t.slice(0, 16);\n\tlastParts = { key, hash };\n\treturn hash;\n}\n\n/**\n * A weak ETag from a file's size, its modification time, the request's\n * `etagParts`, and the encoding of the body. Why the encoding: after a 304,\n * a cache that holds more than one encoding of the file picks the stored\n * response by its ETag (RFC 9111, section 4.3.4).\n */\nasync function fileEtag(\n\tfile: StaticFile,\n\tparts: readonly string[],\n\tencoding: Encoding | undefined,\n): Promise<string> {\n\tconst tag = [\n\t\tfile.size.toString(16),\n\t\tMath.trunc(file.mtimeMs).toString(16),\n\t\t...(parts.length === 0 ? [] : [await partsHash(parts)]),\n\t\t...(encoding == null ? [] : [encoding]),\n\t];\n\treturn `W/\"${tag.join(\"-\")}\"`;\n}\n\n/**\n * The byte range that a `Range` header asks for in a file of `size` bytes.\n * It gives `\"unsatisfiable\"` for a range that starts after the end of the\n * file, and `undefined` for a header to ignore: a header that is not valid,\n * or one with more than one range.\n *\n * @example\n * byteRange(\"bytes=-100\", 1000); // => { start: 900, end: 999 }\n */\nexport function byteRange(header: string, size: number): ByteRange | \"unsatisfiable\" | undefined {\n\tconst groups = /^bytes=(?<first>\\d*)-(?<last>\\d*)$/u.exec(header.trim())?.groups;\n\tconst first = groups?.first ?? \"\";\n\tconst last = groups?.last ?? \"\";\n\tif (first === \"\" && last === \"\") {\n\t\treturn undefined;\n\t}\n\tif (first === \"\") {\n\t\tconst suffix = Number(last);\n\t\treturn suffix === 0 || size === 0\n\t\t\t? \"unsatisfiable\"\n\t\t\t: { start: Math.max(0, size - suffix), end: size - 1 };\n\t}\n\tconst start = Number(first);\n\tconst end = last === \"\" ? Number.POSITIVE_INFINITY : Number(last);\n\tif (end < start) {\n\t\treturn undefined;\n\t}\n\treturn start >= size ? \"unsatisfiable\" : { start, end: Math.min(end, size - 1) };\n}\n\n/** Why these caps: they hold the hashed chunks of a typical app, and they limit the memory of each process. */\nconst KEPT_FILE_BYTES = 256 * 1024;\nconst KEPT_TOTAL_BYTES = 32 * 1024 * 1024;\n\n/**\n * `files` that keep the bytes of each small file in memory after the first\n * read, up to {@link KEPT_TOTAL_BYTES} in all. Use it only for files that\n * do not change while the server runs, such as a `StaticFiles.snapshot()`.\n *\n * @example\n * const files = keptFiles(await nodeFiles(\"build/client\").snapshot());\n */\nexport function keptFiles(files: StaticFiles): StaticFiles {\n\tconst kept = new Map<string, Promise<Uint8Array>>();\n\tlet total = 0;\n\treturn {\n\t\tstat: files.stat,\n\t\topen: async (path, range) => {\n\t\t\tlet bytes = kept.get(path);\n\t\t\tconst info = bytes == null ? await files.stat(path) : undefined;\n\t\t\t// Why again: another request can start to read the file during the `stat`.\n\t\t\tbytes ??= kept.get(path);\n\t\t\tif (bytes == null) {\n\t\t\t\tif (\n\t\t\t\t\tinfo?.kind !== \"file\" ||\n\t\t\t\t\tinfo.size > KEPT_FILE_BYTES ||\n\t\t\t\t\ttotal + info.size > KEPT_TOTAL_BYTES\n\t\t\t\t) {\n\t\t\t\t\treturn files.open(path, range);\n\t\t\t\t}\n\t\t\t\ttotal += info.size;\n\t\t\t\t// Why the size as a range: the kept bytes then match the `Content-Length` from the lookup.\n\t\t\t\tbytes = files\n\t\t\t\t\t.open(path, { start: 0, end: info.size - 1 })\n\t\t\t\t\t.then(async (stream) => new Uint8Array(await new Response(stream).arrayBuffer()));\n\t\t\t\tkept.set(path, bytes);\n\t\t\t\tbytes.catch(() => {\n\t\t\t\t\tkept.delete(path);\n\t\t\t\t\ttotal -= info.size;\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Why a copy: a later stage can change the bytes that it reads.\n\t\t\tconst chunk = (await bytes).slice(\n\t\t\t\trange?.start ?? 0,\n\t\t\t\trange == null ? undefined : range.end + 1,\n\t\t\t);\n\t\t\treturn new ReadableStream<Uint8Array>({\n\t\t\t\tstart(controller) {\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tcontroller.close();\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t};\n}\n\n/** A compressed copy of a static file that the build wrote. */\ntype Copy = StaticFile & { encoding: Encoding };\n\n/**\n * The copy of the file at `path` that the request prefers, from the copies\n * that the build wrote. When a copy exists, it adds `Accept-Encoding` to the\n * `Vary` in `headers`, also for a request that gets no copy.\n */\nasync function preferredCopy(\n\tcontext: Context<AppServerEnv>,\n\t{ files, path, headers }: { files: StaticFiles; path: string; headers: Headers },\n): Promise<Copy | undefined> {\n\t// Why not for an encoded file: the copy would encode it again, under one `Content-Encoding`.\n\tif (\n\t\theaders.has(\"Content-Encoding\") ||\n\t\t(context.get(\"rewritesHtml\") === true &&\n\t\t\t(headers.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false))\n\t) {\n\t\treturn undefined;\n\t}\n\tconst copies: Copy[] = [];\n\tfor (const encoding of COPY_ENCODINGS) {\n\t\tconst copyPath = path.replace(/[^/]*$/u, (name) => copyName(name, encoding));\n\t\t// oxlint-disable-next-line no-await-in-loop -- two lookups, and a snapshot answers each at once.\n\t\tconst info = await files.stat(copyPath);\n\t\tif (info?.kind === \"file\") {\n\t\t\tcopies.push({ path: copyPath, size: info.size, mtimeMs: info.mtimeMs, encoding });\n\t\t}\n\t}\n\tif (copies.length === 0) {\n\t\treturn undefined;\n\t}\n\tconst vary = withVary(headers.get(\"Vary\"), \"Accept-Encoding\");\n\tif (vary != null) {\n\t\theaders.set(\"Vary\", vary);\n\t}\n\tif (forbidsTransform(hookedHeaders(context, headers).get(\"Cache-Control\"))) {\n\t\treturn undefined;\n\t}\n\tconst encoding = preferredEncoding(\n\t\tcontext.req.header(\"Accept-Encoding\"),\n\t\tcopies.map((copy) => copy.encoding),\n\t);\n\treturn copies.find((copy) => copy.encoding === encoding);\n}\n\n/**\n * All bytes of a file. Why the size as a range: the body then never has more\n * bytes than its `Content-Length`, even when the file grew after `stat`, and\n * a small file reads into a small buffer.\n */\nasync function wholeFile(\n\tfiles: StaticFiles,\n\tfile: StaticFile,\n): Promise<ReadableStream<Uint8Array> | null> {\n\treturn file.size === 0 ? null : files.open(file.path, { start: 0, end: file.size - 1 });\n}\n\n/** What {@link staticResponse} needs besides the request. */\nexport type StaticResponseOptions = {\n\tfiles: StaticFiles;\n\tfile: StaticFile;\n\t/** Headers that replace the defaults, so a captured `Content-Type` wins over the one from the file name. */\n\theaders: Readonly<Record<string, string>>;\n\tcontentTypes: Readonly<Record<string, string>>;\n};\n\n/**\n * The response for a static file, with a weak ETag from its size,\n * modification time, the request's `etagParts`, and its encoding. A matching\n * `If-None-Match` gets a 304, and `HEAD` gets the headers only.\n *\n * A GET with one `bytes` range gets a 206 with those bytes, and a range\n * after the end of the file gets a 416. A request with `If-Range` gets the\n * full file. Why: the ETag is weak, and `If-Range` needs a strong match. An\n * HTML file gets no ranges.\n *\n * When the build wrote a compressed copy of the file (`.<file>.br` or\n * `.<file>.gz`), the response gets `Vary: Accept-Encoding`. A request gets\n * the copy that its `Accept-Encoding` prefers, brotli before gzip, with its\n * `Content-Encoding`, an ETag for that encoding, and no range. A response\n * marked `no-transform`, also by the header hook of an earlier stage, and a\n * response that `headers` encode, never get a copy. An HTML file gets no\n * copy when an earlier stage sets `rewritesHtml`.\n *\n * @example\n * const file = await findStaticFile(files, \"/llms.txt\");\n * if (file != null) {\n * return staticResponse(context, { files, file, headers: {}, contentTypes: {} });\n * }\n */\nexport async function staticResponse(\n\tcontext: Context<AppServerEnv>,\n\t{ files, file, headers, contentTypes }: StaticResponseOptions,\n): Promise<Response> {\n\tconst responseHeaders = new Headers({ \"Content-Type\": contentType(file.path, contentTypes) });\n\tfor (const [name, value] of Object.entries(headers)) {\n\t\tresponseHeaders.set(name, value);\n\t}\n\t// Why no ranges for HTML: a stage such as `runtimeEnv` can change the bytes of a page.\n\tconst html = responseHeaders.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false;\n\tif (html) {\n\t\tcontext.set(\"staticDocument\", file.path);\n\t}\n\t// Why before the 304: a 304 sends the `Vary` and the ETag of its 200.\n\tconst copy = await preferredCopy(context, { files, path: file.path, headers: responseHeaders });\n\t// Why the header first: `headers` can replace the ETag.\n\tconst etag =\n\t\tresponseHeaders.get(\"ETag\") ??\n\t\t(await fileEtag(file, context.get(\"etagParts\") ?? [], copy?.encoding));\n\tresponseHeaders.set(\"ETag\", etag);\n\tif (matchesEtag(context.req.header(\"If-None-Match\"), etag)) {\n\t\tresponseHeaders.delete(\"Content-Type\");\n\t\treturn new Response(null, { status: 304, headers: responseHeaders });\n\t}\n\tif (copy != null) {\n\t\t// Why no ranges: a client asks for a range of the file, not of its compressed copy.\n\t\tresponseHeaders.set(\"Content-Encoding\", copy.encoding);\n\t\tresponseHeaders.set(\"Content-Length\", String(copy.size));\n\t\tconst body = context.req.method === \"HEAD\" ? null : await wholeFile(files, copy);\n\t\treturn new Response(body, { headers: responseHeaders });\n\t}\n\tif (!html) {\n\t\tresponseHeaders.set(\"Accept-Ranges\", \"bytes\");\n\t}\n\tresponseHeaders.set(\"Content-Length\", String(file.size));\n\tif (context.req.method === \"HEAD\") {\n\t\treturn new Response(null, { headers: responseHeaders });\n\t}\n\tconst rangeHeader = context.req.header(\"Range\");\n\tconst range =\n\t\thtml || rangeHeader == null || context.req.header(\"If-Range\") != null\n\t\t\t? undefined\n\t\t\t: byteRange(rangeHeader, file.size);\n\tif (range === \"unsatisfiable\") {\n\t\tresponseHeaders.set(\"Content-Range\", `bytes */${file.size}`);\n\t\tresponseHeaders.delete(\"Content-Length\");\n\t\treturn new Response(null, { status: 416, headers: responseHeaders });\n\t}\n\tif (range != null) {\n\t\tresponseHeaders.set(\"Content-Range\", `bytes ${range.start}-${range.end}/${file.size}`);\n\t\tresponseHeaders.set(\"Content-Length\", String(range.end - range.start + 1));\n\t\treturn new Response(await files.open(file.path, range), {\n\t\t\tstatus: 206,\n\t\t\theaders: responseHeaders,\n\t\t});\n\t}\n\treturn new Response(await wholeFile(files, file), { headers: responseHeaders });\n}\n"],"mappings":";;;;;;;;;;;;;AAQA,SAAgB,SAAS,MAAqB,MAAkC;CAC/E,IAAI,QAAQ,QAAQ,KAAK,KAAK,MAAM,IACnC,OAAO;CAER,MAAM,SAAS,IAAI,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY,CAAC,CAAC;CACjF,OAAO,OAAO,IAAI,KAAK,YAAY,CAAC,KAAK,OAAO,IAAI,GAAG,IAAI,SAAY,GAAG,KAAK,IAAI;AACpF;;;;ACGA,MAAM,qBAAuD;CAC5D,SAAS;CACT,OAAO;CACP,QAAQ;CACR,QAAQ;CACR,OAAO;CAEP,SAAS;CACT,QAAQ;AACT;;;;;;;;;AAUA,SAAgB,cAAc,MAAuB;CACpD,OAAO,KACL,MAAM,GAAG,CAAC,CACV,MACC,SAAS,UAAU,QAAQ,WAAW,GAAG,KAAK,EAAE,UAAU,KAAK,YAAY,cAC7E;AACF;;;;;;AAOA,SAAgB,WAAW,MAAuB;CACjD,OACC,K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AK,GAAG;GACvD,QAAQ;GACR,SAAS;EACV,CAAC;CACF;CACA,OAAO,IAAI,SAAS,MAAM,UAAU,OAAO,IAAI,GAAG,EAAE,SAAS,gBAAgB,CAAC;AAC/E"}
@@ -1,4 +1,4 @@
1
- import { n as FrameworkBuild } from "./index-Db7dspq6.js";
1
+ import { n as FrameworkBuild } from "./index-B8LsM6Mh.js";
2
2
  /**
3
3
  * The build side of the TanStack Start adapter. `appServer` uses it when the
4
4
  * Vite config has the TanStack Start plugin, so pass it only to override that.
@@ -1,5 +1,5 @@
1
- import { a as FrameworkRuntime, h as Mode } from "./types-j29vspx_.js";
2
- import { t as TrailingSlash } from "./trailing-slash-CFSv_Gzx.js";
1
+ import { a as FrameworkRuntime, h as Mode } from "./types-BKJxtIuj.js";
2
+ import { t as TrailingSlash } from "./trailing-slash-DeOUxMYo.js";
3
3
  import { AnyRouter, RegisteredRouter } from "@tanstack/react-router";
4
4
  /**
5
5
  * The `trailingSlash` mode of a TanStack router: the app's registered router
@@ -33,10 +33,10 @@ function tcp({ port, host, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
33
33
  };
34
34
  if ("Bun" in globalThis) return (await import("./bun-BCz6K_Xv.js")).listen(fetch, options);
35
35
  if ("Deno" in globalThis) return (await import("./deno-aqhikNMG.js")).listen(fetch, options);
36
- return (await import("./node-tBVQPjQv.js")).listen(fetch, options);
36
+ return (await import("./node-C0Ad7CVL.js")).listen(fetch, options);
37
37
  }
38
38
  };
39
39
  }
40
40
 
41
41
  export { tcp as n, parsePort as t };
42
- //# sourceMappingURL=tcp-Dd1Mt6sN.js.map
42
+ //# sourceMappingURL=tcp-Bws6oEau.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tcp-Dd1Mt6sN.js","names":[],"sources":["../src/node/tcp.ts"],"sourcesContent":["import type { Listener } from \"../core/types.js\";\n\n/** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */\nconst DEFAULT_IDLE_TIMEOUT_MS = 95_000;\n\n/** Options for {@link tcp}. */\nexport type TcpOptions = {\n\t/** @default the `PORT` environment variable, else 3000 */\n\tport?: number;\n\t/** @default the `HOST` environment variable, else every interface */\n\thost?: string;\n\t/** @default 95000 */\n\tidleTimeoutMs?: number;\n};\n\n/**\n * Reads a port number. A value that is not an integer from 0 to 65535 throws,\n * so a bad `PORT` stops startup.\n *\n * @example\n * parsePort(\"8080\"); // => 8080\n */\nexport function parsePort(value: string): number {\n\tconst port = Number(value);\n\tif (value.trim() === \"\" || !Number.isInteger(port) || port < 0 || port > 65_535) {\n\t\tthrow new Error(`PORT must be an integer from 0 to 65535, not \"${value}\".`);\n\t}\n\treturn port;\n}\n\n/**\n * The default listener: a TCP port, served by the runtime's own HTTP server\n * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads\n * `PORT` and `HOST` when it starts.\n *\n * @example\n * createServer({ listeners: [tcp({ port: 8080 })] });\n */\nexport function tcp({\n\tport,\n\thost,\n\tidleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,\n}: TcpOptions = {}): Listener {\n\treturn {\n\t\tname: \"tcp\",\n\t\tstart: async (fetch, { trustForwardedProto = false } = {}) => {\n\t\t\tconst options = {\n\t\t\t\tport: port ?? (process.env.PORT == null ? 3000 : parsePort(process.env.PORT)),\n\t\t\t\thostname: host ?? (process.env.HOST || undefined),\n\t\t\t\tidleTimeoutMs,\n\t\t\t\ttrustForwardedProto,\n\t\t\t};\n\t\t\tif (\"Bun\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/bun.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\tif (\"Deno\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/deno.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\treturn (await import(\"./runtimes/node.js\")).listen(fetch, options);\n\t\t},\n\t};\n}\n"],"mappings":";;AAGA,MAAM,0BAA0B;;;;;;;;AAmBhC,SAAgB,UAAU,OAAuB;CAChD,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,MAAM,KAAK,MAAM,MAAM,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OACxE,MAAM,IAAI,MAAM,iDAAiD,MAAM,GAAG;CAE3E,OAAO;AACR;;;;;;;;;AAUA,SAAgB,IAAI,EACnB,MACA,MACA,gBAAgB,4BACD,CAAC,GAAa;CAC7B,OAAO;EACN,MAAM;EACN,OAAO,OAAO,OAAO,EAAE,sBAAsB,UAAU,CAAC,MAAM;GAC7D,MAAM,UAAU;IACf,MAAM,SAAS,QAAQ,IAAI,QAAQ,OAAO,MAAO,UAAU,QAAQ,IAAI,IAAI;IAC3E,UAAU,SAAS,QAAQ,IAAI,QAAQ;IACvC;IACA;GACD;GACA,IAAI,SAAS,YACZ,QAAQ,MAAM,OAAO,qBAAoB,CAAE,OAAO,OAAO,OAAO;GAEjE,IAAI,UAAU,YACb,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;GAElE,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;EAClE;CACD;AACD"}
1
+ {"version":3,"file":"tcp-Bws6oEau.js","names":[],"sources":["../src/node/tcp.ts"],"sourcesContent":["import type { Listener } from \"../core/types.js\";\n\n/** Above the ngrok edge's 90 s idle pool, so the edge never reuses a socket that the server is closing. */\nconst DEFAULT_IDLE_TIMEOUT_MS = 95_000;\n\n/** Options for {@link tcp}. */\nexport type TcpOptions = {\n\t/** @default the `PORT` environment variable, else 3000 */\n\tport?: number;\n\t/** @default the `HOST` environment variable, else every interface */\n\thost?: string;\n\t/** @default 95000 */\n\tidleTimeoutMs?: number;\n};\n\n/**\n * Reads a port number. A value that is not an integer from 0 to 65535 throws,\n * so a bad `PORT` stops startup.\n *\n * @example\n * parsePort(\"8080\"); // => 8080\n */\nexport function parsePort(value: string): number {\n\tconst port = Number(value);\n\tif (value.trim() === \"\" || !Number.isInteger(port) || port < 0 || port > 65_535) {\n\t\tthrow new Error(`PORT must be an integer from 0 to 65535, not \"${value}\".`);\n\t}\n\treturn port;\n}\n\n/**\n * The default listener: a TCP port, served by the runtime's own HTTP server\n * (`node:http` on Node, `Bun.serve` on Bun, `Deno.serve` on Deno). It reads\n * `PORT` and `HOST` when it starts.\n *\n * @example\n * createServer({ listeners: [tcp({ port: 8080 })] });\n */\nexport function tcp({\n\tport,\n\thost,\n\tidleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS,\n}: TcpOptions = {}): Listener {\n\treturn {\n\t\tname: \"tcp\",\n\t\tstart: async (fetch, { trustForwardedProto = false } = {}) => {\n\t\t\tconst options = {\n\t\t\t\tport: port ?? (process.env.PORT == null ? 3000 : parsePort(process.env.PORT)),\n\t\t\t\thostname: host ?? (process.env.HOST || undefined),\n\t\t\t\tidleTimeoutMs,\n\t\t\t\ttrustForwardedProto,\n\t\t\t};\n\t\t\tif (\"Bun\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/bun.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\tif (\"Deno\" in globalThis) {\n\t\t\t\treturn (await import(\"./runtimes/deno.js\")).listen(fetch, options);\n\t\t\t}\n\t\t\treturn (await import(\"./runtimes/node.js\")).listen(fetch, options);\n\t\t},\n\t};\n}\n"],"mappings":";;AAGA,MAAM,0BAA0B;;;;;;;;AAmBhC,SAAgB,UAAU,OAAuB;CAChD,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,MAAM,KAAK,MAAM,MAAM,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OACxE,MAAM,IAAI,MAAM,iDAAiD,MAAM,GAAG;CAE3E,OAAO;AACR;;;;;;;;;AAUA,SAAgB,IAAI,EACnB,MACA,MACA,gBAAgB,4BACD,CAAC,GAAa;CAC7B,OAAO;EACN,MAAM;EACN,OAAO,OAAO,OAAO,EAAE,sBAAsB,UAAU,CAAC,MAAM;GAC7D,MAAM,UAAU;IACf,MAAM,SAAS,QAAQ,IAAI,QAAQ,OAAO,MAAO,UAAU,QAAQ,IAAI,IAAI;IAC3E,UAAU,SAAS,QAAQ,IAAI,QAAQ;IACvC;IACA;GACD;GACA,IAAI,SAAS,YACZ,QAAQ,MAAM,OAAO,qBAAoB,CAAE,OAAO,OAAO,OAAO;GAEjE,IAAI,UAAU,YACb,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;GAElE,QAAQ,MAAM,OAAO,sBAAqB,CAAE,OAAO,OAAO,OAAO;EAClE;CACD;AACD"}
package/dist/testing.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { _ as RequestContext, a as FrameworkRuntime } from "./types-j29vspx_.js";
2
- import { t as AppServer } from "./create-server-D4-nVOVJ.js";
1
+ import { _ as RequestContext, a as FrameworkRuntime } from "./types-BKJxtIuj.js";
2
+ import { t as AppServer } from "./create-server-kxyhCdhv.js";
3
3
  /** Options for {@link createTestServer}. */
4
4
  export type TestServerOptions = {
5
5
  /**
package/dist/testing.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { r as withRequestContext$1 } from "./request-context-BtQ87VYb.js";
2
2
  import { i as requestLogger } from "./log-BP6xXXZl.js";
3
3
  import { t as BUILD_MANIFEST_FILE } from "./build-manifest-DBMWe3Lx.js";
4
- import { t as createEntry } from "./entry-D9H4LA9c.js";
5
- import { t as host } from "./node-C1qudLs_.js";
6
- import { n as scriptHashesOf } from "./script-hashes-C6hQ5XnP.js";
4
+ import { t as createEntry } from "./entry-ChHgs269.js";
5
+ import { t as host } from "./node-B0AYf_IA.js";
6
+ import { n as scriptHashesOf } from "./script-hashes-CU7P9oZU.js";
7
7
  import { Context } from "hono";
8
8
  import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
9
9
  import { dirname, isAbsolute, join, normalize, sep } from "node:path";
@@ -1,4 +1,4 @@
1
- import { g as Plugin } from "./types-j29vspx_.js";
1
+ import { g as Plugin } from "./types-BKJxtIuj.js";
2
2
  /**
3
3
  * How a page URL ends:
4
4
  *
@@ -33,4 +33,4 @@ type TrailingSlashOptions = {
33
33
  */
34
34
  declare function trailingSlash({ mode }: TrailingSlashOptions): Plugin;
35
35
  export { TrailingSlashOptions as n, trailingSlash as r, TrailingSlash as t };
36
- //# sourceMappingURL=trailing-slash-CFSv_Gzx.d.ts.map
36
+ //# sourceMappingURL=trailing-slash-DeOUxMYo.d.ts.map
@@ -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,YAAY,GACtB,OAAO,CAAC,KAAK;CAEd,MAAM,QAAQ,GAAG,MAAM,IAAI,GAAG,MAAM;CACpC,IAAI,QAAQ,IAAI,KAAK,GACpB,OAAO,CAAC;CAET,MAAM,SAAS,IAAI,IAAI,OAAO,CAAC,CAAC,IAAI,KAAK;CACzC,OAAO,YAAY,KAAK,WAAW,KAAK,CAAC,CAAC,CAAC,SAAS,SAC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AO,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,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;AACh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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
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";
2
+ import { i as withForwardedProto } from "./create-server-BX2rH6-E.js";
3
+ import { t as host$1 } from "./node-B0AYf_IA.js";
4
+ import { t as requestListener } from "./response-writer-DzvUAz9x.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
  },