@ngrok/app-server 0.1.1 → 0.3.0

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 (105) hide show
  1. package/README.md +659 -70
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/build-manifest-UDNk81Ce.js +63 -0
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/{bun-DCGnDEPn.js → bun-BCz6K_Xv.js} +12 -8
  7. package/dist/bun-BCz6K_Xv.js.map +1 -0
  8. package/dist/cli.js +47 -27
  9. package/dist/cli.js.map +1 -1
  10. package/dist/client.d.ts +141 -0
  11. package/dist/client.js +326 -0
  12. package/dist/client.js.map +1 -0
  13. package/dist/compression-7_gToa8R.js +97 -0
  14. package/dist/compression-7_gToa8R.js.map +1 -0
  15. package/dist/create-server-iE1-s6Bi.js +1409 -0
  16. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  17. package/dist/{deno-BnMfk2n1.js → deno-aqhikNMG.js} +5 -5
  18. package/dist/deno-aqhikNMG.js.map +1 -0
  19. package/dist/entry-DZ3qo7qF.js +116 -0
  20. package/dist/entry-DZ3qo7qF.js.map +1 -0
  21. package/dist/entry-DmJEqVfd.d.ts +622 -0
  22. package/dist/gzip-Doi4wqjX.js +294 -0
  23. package/dist/gzip-Doi4wqjX.js.map +1 -0
  24. package/dist/header-hook-Vzw9J9BY.js +159 -0
  25. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  26. package/dist/index-Bo5G9LuQ.d.ts +127 -0
  27. package/dist/index.d.ts +110 -95
  28. package/dist/index.js +56 -57
  29. package/dist/index.js.map +1 -1
  30. package/dist/{listen-options-DHWmSWGi.js → listen-options-7TaXjyrk.js} +2 -2
  31. package/dist/listen-options-7TaXjyrk.js.map +1 -0
  32. package/dist/load-entry-AfYS_zS9.js +37 -0
  33. package/dist/load-entry-AfYS_zS9.js.map +1 -0
  34. package/dist/log-BP6xXXZl.js +122 -0
  35. package/dist/log-BP6xXXZl.js.map +1 -0
  36. package/dist/node-BFH82eeL.js +333 -0
  37. package/dist/node-BFH82eeL.js.map +1 -0
  38. package/dist/node-tBVQPjQv.js +41 -0
  39. package/dist/node-tBVQPjQv.js.map +1 -0
  40. package/dist/node-vite.d.ts +11 -0
  41. package/dist/node-vite.js +3 -0
  42. package/dist/node.d.ts +86 -0
  43. package/dist/node.js +4 -0
  44. package/dist/react-router-vite.d.ts +10 -0
  45. package/dist/react-router-vite.js +3 -0
  46. package/dist/react-router.d.ts +11 -24
  47. package/dist/react-router.js +21 -30
  48. package/dist/react-router.js.map +1 -1
  49. package/dist/request-context-BtQ87VYb.js +40 -0
  50. package/dist/request-context-BtQ87VYb.js.map +1 -0
  51. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  52. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  53. package/dist/response-writer-B7FoJjEE.js +289 -0
  54. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  55. package/dist/script-hashes-hqUk6kG7.js +53 -0
  56. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  57. package/dist/serve-CDNgThjk.js +29 -0
  58. package/dist/serve-CDNgThjk.js.map +1 -0
  59. package/dist/{start-BVMb8Pyt.js → start-TLIprD74.js} +96 -81
  60. package/dist/start-TLIprD74.js.map +1 -0
  61. package/dist/static-files-Beju9riB.js +302 -0
  62. package/dist/static-files-Beju9riB.js.map +1 -0
  63. package/dist/tanstack-start-vite.d.ts +12 -0
  64. package/dist/tanstack-start-vite.js +3 -0
  65. package/dist/tanstack-start.d.ts +34 -0
  66. package/dist/tanstack-start.js +41 -0
  67. package/dist/tanstack-start.js.map +1 -0
  68. package/dist/{tcp-Dau_IONd.js → tcp-Dd1Mt6sN.js} +8 -7
  69. package/dist/tcp-Dd1Mt6sN.js.map +1 -0
  70. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  71. package/dist/types-DLYxYS6M.d.ts +392 -0
  72. package/dist/vercel-vite.d.ts +35 -0
  73. package/dist/vercel-vite.js +142 -0
  74. package/dist/vercel-vite.js.map +1 -0
  75. package/dist/vercel.d.ts +35 -0
  76. package/dist/vercel.js +89 -0
  77. package/dist/vercel.js.map +1 -0
  78. package/dist/vite-B-GfswoH.js +22 -0
  79. package/dist/vite-B-GfswoH.js.map +1 -0
  80. package/dist/vite-D4hfj3ph.js +19 -0
  81. package/dist/vite-D4hfj3ph.js.map +1 -0
  82. package/dist/vite-DyrhyKEr.js +25 -0
  83. package/dist/vite-DyrhyKEr.js.map +1 -0
  84. package/dist/vite-iioAoxSt.js +752 -0
  85. package/dist/vite-iioAoxSt.js.map +1 -0
  86. package/dist/vite.d.ts +2 -27
  87. package/dist/vite.js +2 -2
  88. package/package.json +50 -4
  89. package/dist/bun-DCGnDEPn.js.map +0 -1
  90. package/dist/captured-headers-ewL_t3MQ.js +0 -48
  91. package/dist/captured-headers-ewL_t3MQ.js.map +0 -1
  92. package/dist/deno-BnMfk2n1.js.map +0 -1
  93. package/dist/entry-CIpwaayZ.d.ts +0 -293
  94. package/dist/entry-ChjmFwX5.js +0 -755
  95. package/dist/entry-ChjmFwX5.js.map +0 -1
  96. package/dist/listen-options-DHWmSWGi.js.map +0 -1
  97. package/dist/node-2wWBMFeO.js +0 -3
  98. package/dist/node-79my3Uix.js +0 -58
  99. package/dist/node-79my3Uix.js.map +0 -1
  100. package/dist/serve-ByeedcRB.js +0 -16
  101. package/dist/serve-ByeedcRB.js.map +0 -1
  102. package/dist/start-BVMb8Pyt.js.map +0 -1
  103. package/dist/tcp-Dau_IONd.js.map +0 -1
  104. package/dist/vite-CrNqpoeK.js +0 -102
  105. package/dist/vite-CrNqpoeK.js.map +0 -1
@@ -0,0 +1,126 @@
1
+ import { o as withHeaderHook } from "./header-hook-Vzw9J9BY.js";
2
+
3
+ // src/core/plugin-options.ts
4
+ /**
5
+ * The option of `defaultPlugins()` that places each plugin, by plugin
6
+ * object. Why the object, not the name: an app plugin can have any name.
7
+ */
8
+ const options = /* @__PURE__ */ new WeakMap();
9
+ /**
10
+ * Marks `plugin` as the plugin of the `option` of `defaultPlugins()`, so
11
+ * `createServer` finds it in the plugin list.
12
+ *
13
+ * @example
14
+ * return optionPlugin("noindex", { name: "noindex", middleware });
15
+ */
16
+ function optionPlugin(option, plugin) {
17
+ options.set(plugin, option);
18
+ return plugin;
19
+ }
20
+ /**
21
+ * Stops startup when `plugins` has two plugins of one option of
22
+ * `defaultPlugins()`, such as two `buildId()`. Why: two copies do not fail.
23
+ * One sets its headers over the other, so a value that the app gave is lost.
24
+ *
25
+ * @example
26
+ * checkOptionPlugins([...defaultPlugins(), buildId({ value: "v42" })]); // throws
27
+ */
28
+ function checkOptionPlugins(plugins) {
29
+ const seen = /* @__PURE__ */ new Set();
30
+ for (const plugin of plugins) {
31
+ const option = options.get(plugin);
32
+ if (option != null && seen.has(option)) throw new Error(`The plugin list has the ${plugin.name} plugin two times, so one replaces the other. Keep one: set the "${option}" option of defaultPlugins(), and do not also add the plugin.`);
33
+ if (option != null) seen.add(option);
34
+ }
35
+ }
36
+
37
+ // src/core/plugins/build-id.ts
38
+ /** The header that {@link buildId} sets by default. */
39
+ const BUILD_ID_HEADER = "X-Build-Id";
40
+ /**
41
+ * The `Server-Timing` metric that holds the build of a response. Why
42
+ * `Server-Timing`: a script can read it from the performance entries, with no
43
+ * request and no change to the document's HTML.
44
+ */
45
+ const BUILD_ID_METRIC = "build";
46
+ /**
47
+ * Whether a cache can use the response again without the server: it has a
48
+ * fresh time, a stale time, or a date that a cache can guess a fresh time from.
49
+ */
50
+ function isReusable(response) {
51
+ const cacheControl = response.get("Cache-Control") ?? "";
52
+ if (/\b(?:no-store|no-cache)\b/iu.test(cacheControl)) return false;
53
+ return /\b(?:max-age|s-maxage|stale-while-revalidate|stale-if-error)\s*=\s*"?0*[1-9]/iu.test(cacheControl) || /\bpublic\b/iu.test(cacheControl) || Date.parse(response.get("Expires") ?? "") > Date.now() || response.has("Last-Modified");
54
+ }
55
+ /** The metrics of a `Server-Timing` header, such as `build;desc="v42"`. */
56
+ function serverTimingMetrics(header) {
57
+ return (header?.match(/(?:[^",]|"(?:[^"\\]|\\.)*")+/gu) ?? []).map((metric) => metric.trim()).filter((metric) => metric !== "");
58
+ }
59
+ /** Whether a `Server-Timing` metric is a build. */
60
+ function isBuildMetric(metric) {
61
+ return metric.split(";")[0]?.trim().toLowerCase() === BUILD_ID_METRIC;
62
+ }
63
+ /** The `Server-Timing` metrics of `header` that are not a build. */
64
+ function otherMetrics(header) {
65
+ return serverTimingMetrics(header).filter((metric) => !isBuildMetric(metric));
66
+ }
67
+ /** The data check before `setup` runs. */
68
+ function noDataRequests() {
69
+ return false;
70
+ }
71
+ /** A `Server-Timing` quoted string with the characters of `value`. */
72
+ function quoted(value) {
73
+ return `"${value.replaceAll(/["\\]/gu, String.raw`\$&`)}"`;
74
+ }
75
+ /** The `build` metric of `value`, or `undefined` for no build. */
76
+ function buildMetric(value) {
77
+ return value == null ? void 0 : `${BUILD_ID_METRIC};desc=${quoted(value)}`;
78
+ }
79
+ /**
80
+ * Sets a build ID header on documents and on the framework's data responses,
81
+ * such as React Router `.data` files, so a client can see that a deploy
82
+ * happened under it. Each of them also gets the build as
83
+ * `Server-Timing: build;desc="<value>"`. The `paths` option adds the metric
84
+ * to more routes, such as API proxy routes. The plugin removes the build
85
+ * header and the `build` metric of an upstream API from each other
86
+ * response, so the client reads only this app's build.
87
+ * `staleBuildReactRouter()` and `staleBuildTanStack()` from `@ngrok/app-server/client` read the metric
88
+ * from the document, and from a response that the browser fetches with no
89
+ * script, such as a prefetch.
90
+ *
91
+ * With no `value`, it sends the build ID that the `appServer` Vite plugin
92
+ * derives from the client build. Development and a build with no
93
+ * `.app-server.json` then get no build.
94
+ *
95
+ * @example
96
+ * buildId({ value: process.env.IMAGE_TAG });
97
+ */
98
+ function buildId({ header = BUILD_ID_HEADER, value: given, paths } = {}) {
99
+ const explicit = given === "" ? void 0 : given;
100
+ let value = explicit;
101
+ let timing = buildMetric(value);
102
+ let isDataRequest = noDataRequests;
103
+ return optionPlugin("buildId", {
104
+ name: "build-id",
105
+ setup: (info) => {
106
+ ({isDataRequest} = info);
107
+ value = explicit ?? info.buildId;
108
+ timing = buildMetric(value);
109
+ },
110
+ etagPart: () => value,
111
+ middleware: async (context, next) => withHeaderHook(context, next, (response) => {
112
+ const { path } = context.req;
113
+ const isRouter = (response.get("Content-Type")?.startsWith("text/html") ?? false) || isDataRequest(path);
114
+ const isStamped = isRouter || paths?.(path) === true && !isReusable(response);
115
+ const before = response.get("Server-Timing");
116
+ const metrics = [...otherMetrics(before), ...isStamped && timing != null ? [timing] : []].join(", ");
117
+ if (metrics === "") response.delete("Server-Timing");
118
+ else if (metrics !== before) response.set("Server-Timing", metrics);
119
+ if (isRouter && value != null) response.set(header, value);
120
+ else response.delete(header);
121
+ })
122
+ });
123
+ }
124
+
125
+ export { serverTimingMetrics as a, isBuildMetric as i, BUILD_ID_METRIC as n, checkOptionPlugins as o, buildId as r, optionPlugin as s, BUILD_ID_HEADER as t };
126
+ //# sourceMappingURL=build-id-C6sYO9Yp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-id-C6sYO9Yp.js","names":[],"sources":["../src/core/plugin-options.ts","../src/core/plugins/build-id.ts"],"sourcesContent":["import type { Plugin } from \"./types.js\";\n\n/**\n * The option of `defaultPlugins()` that places each plugin, by plugin\n * object. Why the object, not the name: an app plugin can have any name.\n */\nconst options = new WeakMap<Plugin, string>();\n\n/**\n * Marks `plugin` as the plugin of the `option` of `defaultPlugins()`, so\n * `createServer` finds it in the plugin list.\n *\n * @example\n * return optionPlugin(\"noindex\", { name: \"noindex\", middleware });\n */\nexport function optionPlugin<P extends Plugin>(option: string, plugin: P): P {\n\toptions.set(plugin, option);\n\treturn plugin;\n}\n\n/**\n * Stops startup when `plugins` has two plugins of one option of\n * `defaultPlugins()`, such as two `buildId()`. Why: two copies do not fail.\n * One sets its headers over the other, so a value that the app gave is lost.\n *\n * @example\n * checkOptionPlugins([...defaultPlugins(), buildId({ value: \"v42\" })]); // throws\n */\nexport function checkOptionPlugins(plugins: readonly Plugin[]): void {\n\tconst seen = new Set<string>();\n\tfor (const plugin of plugins) {\n\t\tconst option = options.get(plugin);\n\t\tif (option != null && seen.has(option)) {\n\t\t\tthrow new Error(\n\t\t\t\t`The plugin list has the ${plugin.name} plugin two times, so one replaces the other. Keep one: set the \"${option}\" option of defaultPlugins(), and do not also add the plugin.`,\n\t\t\t);\n\t\t}\n\t\tif (option != null) {\n\t\t\tseen.add(option);\n\t\t}\n\t}\n}\n","import { withHeaderHook } from \"../header-hook.js\";\nimport { optionPlugin } from \"../plugin-options.js\";\nimport type { Plugin, ResponseHeaders, SetupInfo } from \"../types.js\";\n\n/** The header that {@link buildId} sets by default. */\nexport const BUILD_ID_HEADER = \"X-Build-Id\";\n\n/**\n * The `Server-Timing` metric that holds the build of a response. Why\n * `Server-Timing`: a script can read it from the performance entries, with no\n * request and no change to the document's HTML.\n */\nexport const BUILD_ID_METRIC = \"build\";\n\n/** Options for {@link buildId}. */\nexport type BuildIdOptions = {\n\t/** @default \"X-Build-Id\" */\n\theader?: string;\n\t/**\n\t * The deployed build, such as the image tag. With no value or `\"\"`, the\n\t * plugin sends the ID that the `appServer` Vite plugin derives from the\n\t * client build. In development, it then sends no build.\n\t * @default the `buildId` of `.app-server.json` in the client build\n\t */\n\tvalue?: string | undefined;\n\t/**\n\t * More request paths whose responses carry the build in `Server-Timing`,\n\t * such as the app's proxy routes to its API. A tab then finds a new build\n\t * in the requests that it already sends. They get no build header, because\n\t * the header marks the router's own responses. A response that a cache can\n\t * use again without the server gets no build, so a cached copy never\n\t * reports an old build. It runs in a header hook, so it can run more than\n\t * once for one request.\n\t *\n\t * @example\n\t * buildId({ paths: (path) => path.startsWith(\"/api/\") });\n\t */\n\tpaths?: (path: string) => boolean;\n};\n\n/**\n * Whether a cache can use the response again without the server: it has a\n * fresh time, a stale time, or a date that a cache can guess a fresh time from.\n */\nfunction isReusable(response: ResponseHeaders): boolean {\n\tconst cacheControl = response.get(\"Cache-Control\") ?? \"\";\n\tif (/\\b(?:no-store|no-cache)\\b/iu.test(cacheControl)) {\n\t\treturn false;\n\t}\n\treturn (\n\t\t/\\b(?:max-age|s-maxage|stale-while-revalidate|stale-if-error)\\s*=\\s*\"?0*[1-9]/iu.test(\n\t\t\tcacheControl,\n\t\t) ||\n\t\t/\\bpublic\\b/iu.test(cacheControl) ||\n\t\tDate.parse(response.get(\"Expires\") ?? \"\") > Date.now() ||\n\t\tresponse.has(\"Last-Modified\")\n\t);\n}\n\n/** The metrics of a `Server-Timing` header, such as `build;desc=\"v42\"`. */\nexport function serverTimingMetrics(header: string | null): string[] {\n\t// Why match the quoted strings: a comma or an escaped quote in a description does not end a metric.\n\treturn (header?.match(/(?:[^\",]|\"(?:[^\"\\\\]|\\\\.)*\")+/gu) ?? [])\n\t\t.map((metric) => metric.trim())\n\t\t.filter((metric) => metric !== \"\");\n}\n\n/** Whether a `Server-Timing` metric is a build. */\nexport function isBuildMetric(metric: string): boolean {\n\treturn metric.split(\";\")[0]?.trim().toLowerCase() === BUILD_ID_METRIC;\n}\n\n/** The `Server-Timing` metrics of `header` that are not a build. */\nfunction otherMetrics(header: string | null): string[] {\n\treturn serverTimingMetrics(header).filter((metric) => !isBuildMetric(metric));\n}\n\n/** The data check before `setup` runs. */\nfunction noDataRequests(): boolean {\n\treturn false;\n}\n\n/** A `Server-Timing` quoted string with the characters of `value`. */\nfunction quoted(value: string): string {\n\treturn `\"${value.replaceAll(/[\"\\\\]/gu, String.raw`\\$&`)}\"`;\n}\n\n/** The `build` metric of `value`, or `undefined` for no build. */\nfunction buildMetric(value: string | undefined): string | undefined {\n\treturn value == null ? undefined : `${BUILD_ID_METRIC};desc=${quoted(value)}`;\n}\n\n/**\n * Sets a build ID header on documents and on the framework's data responses,\n * such as React Router `.data` files, so a client can see that a deploy\n * happened under it. Each of them also gets the build as\n * `Server-Timing: build;desc=\"<value>\"`. The `paths` option adds the metric\n * to more routes, such as API proxy routes. The plugin removes the build\n * header and the `build` metric of an upstream API from each other\n * response, so the client reads only this app's build.\n * `staleBuildReactRouter()` and `staleBuildTanStack()` from `@ngrok/app-server/client` read the metric\n * from the document, and from a response that the browser fetches with no\n * script, such as a prefetch.\n *\n * With no `value`, it sends the build ID that the `appServer` Vite plugin\n * derives from the client build. Development and a build with no\n * `.app-server.json` then get no build.\n *\n * @example\n * buildId({ value: process.env.IMAGE_TAG });\n */\nexport function buildId({\n\theader = BUILD_ID_HEADER,\n\tvalue: given,\n\tpaths,\n}: BuildIdOptions = {}): Plugin {\n\t// Why `\"\"` too: a deploy can set the variable with no value, such as `IMAGE_TAG=`.\n\tconst explicit = given === \"\" ? undefined : given;\n\tlet value = explicit;\n\tlet timing = buildMetric(value);\n\tlet isDataRequest: SetupInfo[\"isDataRequest\"] = noDataRequests;\n\treturn optionPlugin(\"buildId\", {\n\t\tname: \"build-id\",\n\t\tsetup: (info) => {\n\t\t\t({ isDataRequest } = info);\n\t\t\tvalue = explicit ?? info.buildId;\n\t\t\ttiming = buildMetric(value);\n\t\t},\n\t\t// Why: a 304 has no `Content-Type`, so a document that did not change on disk must still\n\t\t// answer 200 when the build ID changes.\n\t\tetagPart: () => value,\n\t\tmiddleware: async (context, next) =>\n\t\t\twithHeaderHook(context, next, (response) => {\n\t\t\t\tconst { path } = context.req;\n\t\t\t\tconst isRouter =\n\t\t\t\t\t(response.get(\"Content-Type\")?.startsWith(\"text/html\") ?? false) || isDataRequest(path);\n\t\t\t\tconst isStamped = isRouter || (paths?.(path) === true && !isReusable(response));\n\t\t\t\t// Why remove the build of an upstream API: the client must read only this app's build.\n\t\t\t\tconst before = response.get(\"Server-Timing\");\n\t\t\t\tconst metrics = [\n\t\t\t\t\t...otherMetrics(before),\n\t\t\t\t\t...(isStamped && timing != null ? [timing] : []),\n\t\t\t\t].join(\", \");\n\t\t\t\tif (metrics === \"\") {\n\t\t\t\t\tresponse.delete(\"Server-Timing\");\n\t\t\t\t} else if (metrics !== before) {\n\t\t\t\t\tresponse.set(\"Server-Timing\", metrics);\n\t\t\t\t}\n\t\t\t\tif (isRouter && value != null) {\n\t\t\t\t\tresponse.set(header, value);\n\t\t\t\t} else {\n\t\t\t\t\tresponse.delete(header);\n\t\t\t\t}\n\t\t\t}),\n\t});\n}\n"],"mappings":";;;;;;;AAMA,MAAM,0BAAU,IAAI,QAAwB;;;;;;;;AAS5C,SAAgB,aAA+B,QAAgB,QAAc;CAC5E,QAAQ,IAAI,QAAQ,MAAM;CAC1B,OAAO;AACR;;;;;;;;;AAUA,SAAgB,mBAAmB,SAAkC;CACpE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,UAAU,SAAS;EAC7B,MAAM,SAAS,QAAQ,IAAI,MAAM;EACjC,IAAI,UAAU,QAAQ,KAAK,IAAI,MAAM,GACpC,MAAM,IAAI,MACT,2BAA2B,OAAO,KAAK,mEAAmE,OAAO,8DAClH;EAED,IAAI,UAAU,MACb,KAAK,IAAI,MAAM;CAEjB;AACD;;;;ACpCA,MAAa,kBAAkB;;;;;;AAO/B,MAAa,kBAAkB;;;;;AAgC/B,SAAS,WAAW,UAAoC;CACvD,MAAM,eAAe,SAAS,IAAI,eAAe,KAAK;CACtD,IAAI,8BAA8B,KAAK,YAAY,GAClD,OAAO;CAER,OACC,iFAAiF,KAChF,YACD,KACA,eAAe,KAAK,YAAY,KAChC,KAAK,MAAM,SAAS,IAAI,SAAS,KAAK,EAAE,IAAI,KAAK,IAAI,KACrD,SAAS,IAAI,eAAe;AAE9B;;AAGA,SAAgB,oBAAoB,QAAiC;CAEpE,QAAQ,QAAQ,MAAM,gCAAgC,KAAK,CAAC,EAAC,CAC3D,KAAK,WAAW,OAAO,KAAK,CAAC,CAAC,CAC9B,QAAQ,WAAW,WAAW,EAAE;AACnC;;AAGA,SAAgB,cAAc,QAAyB;CACtD,OAAO,OAAO,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,YAAY,MAAM;AACvD;;AAGA,SAAS,aAAa,QAAiC;CACtD,OAAO,oBAAoB,MAAM,CAAC,CAAC,QAAQ,WAAW,CAAC,cAAc,MAAM,CAAC;AAC7E;;AAGA,SAAS,iBAA0B;CAClC,OAAO;AACR;;AAGA,SAAS,OAAO,OAAuB;CACtC,OAAO,IAAI,MAAM,WAAW,WAAW,OAAO,GAAG,KAAK,EAAE;AACzD;;AAGA,SAAS,YAAY,OAA+C;CACnE,OAAO,SAAS,OAAO,SAAY,GAAG,gBAAgB,QAAQ,OAAO,KAAK;AAC3E;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,QAAQ,EACvB,SAAS,iBACT,OAAO,OACP,UACmB,CAAC,GAAW;CAE/B,MAAM,WAAW,UAAU,KAAK,SAAY;CAC5C,IAAI,QAAQ;CACZ,IAAI,SAAS,YAAY,KAAK;CAC9B,IAAI,gBAA4C;CAChD,OAAO,aAAa,WAAW;EAC9B,MAAM;EACN,QAAQ,SAAS;GAChB,CAAC,CAAE,iBAAkB;GACrB,QAAQ,YAAY,KAAK;GACzB,SAAS,YAAY,KAAK;EAC3B;EAGA,gBAAgB;EAChB,YAAY,OAAO,SAAS,SAC3B,eAAe,SAAS,OAAO,aAAa;GAC3C,MAAM,EAAE,SAAS,QAAQ;GACzB,MAAM,YACJ,SAAS,IAAI,cAAc,CAAC,EAAE,WAAW,WAAW,KAAK,UAAU,cAAc,IAAI;GACvF,MAAM,YAAY,YAAa,QAAQ,IAAI,MAAM,QAAQ,CAAC,WAAW,QAAQ;GAE7E,MAAM,SAAS,SAAS,IAAI,eAAe;GAC3C,MAAM,UAAU,CACf,GAAG,aAAa,MAAM,GACtB,GAAI,aAAa,UAAU,OAAO,CAAC,MAAM,IAAI,CAAC,CAC/C,CAAC,CAAC,KAAK,IAAI;GACX,IAAI,YAAY,IACf,SAAS,OAAO,eAAe;QACzB,IAAI,YAAY,QACtB,SAAS,IAAI,iBAAiB,OAAO;GAEtC,IAAI,YAAY,SAAS,MACxB,SAAS,IAAI,QAAQ,KAAK;QAE1B,SAAS,OAAO,MAAM;EAExB,CAAC;CACH,CAAC;AACF"}
@@ -0,0 +1,63 @@
1
+ // src/core/build-manifest.ts
2
+ /**
3
+ * The file under the client build that the Vite plugin writes after the
4
+ * client build and again after the prerender pass. It is a dotfile, so the
5
+ * static stages never serve it.
6
+ */
7
+ const BUILD_MANIFEST_FILE = ".app-server.json";
8
+ /**
9
+ * The key for a URL path in {@link BuildManifest}: the path with no trailing
10
+ * slash, so `/a/` and `/a` share headers. The root stays `/`.
11
+ *
12
+ * @example
13
+ * manifestKey("/components/button/"); // => "/components/button"
14
+ */
15
+ function manifestKey(pathname) {
16
+ const trimmed = pathname.replace(/\/+$/u, "");
17
+ return trimmed === "" ? "/" : trimmed;
18
+ }
19
+ function isStringRecord(value) {
20
+ return typeof value === "object" && value != null && !Array.isArray(value) && Object.values(value).every((entry) => typeof entry === "string");
21
+ }
22
+ function isStringList(value) {
23
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
24
+ }
25
+ /** The `buildId` of a parsed manifest, which can have none. A value that is not a string throws. */
26
+ function buildIdOf(manifest) {
27
+ if (!("buildId" in manifest)) return {};
28
+ if (typeof manifest.buildId !== "string") throw new TypeError(`${BUILD_MANIFEST_FILE}: the "buildId" must be a string.`);
29
+ return { buildId: manifest.buildId };
30
+ }
31
+ /**
32
+ * Reads the build manifest of a client build. A build with no file has an
33
+ * empty one. A file in any other shape throws, so a bad build stops startup.
34
+ */
35
+ async function readBuildManifest(files) {
36
+ const path = `/${BUILD_MANIFEST_FILE}`;
37
+ if ((await files.stat(path))?.kind !== "file") return {
38
+ prerendered: [],
39
+ headers: {},
40
+ scriptHashes: {}
41
+ };
42
+ const parsed = await new Response(await files.open(path)).json();
43
+ if (typeof parsed !== "object" || parsed == null || !("prerendered" in parsed) || !isStringList(parsed.prerendered) || !("headers" in parsed) || typeof parsed.headers !== "object" || parsed.headers == null || !("scriptHashes" in parsed) || typeof parsed.scriptHashes !== "object" || parsed.scriptHashes == null) throw new Error(`${BUILD_MANIFEST_FILE} must hold a "prerendered" list and the "headers" and "scriptHashes" objects.`);
44
+ const headers = {};
45
+ for (const [key, value] of Object.entries(parsed.headers)) {
46
+ if (!isStringRecord(value)) throw new Error(`${BUILD_MANIFEST_FILE}: the headers for ${key} must be strings.`);
47
+ headers[key] = value;
48
+ }
49
+ const scriptHashes = {};
50
+ for (const [key, value] of Object.entries(parsed.scriptHashes)) {
51
+ if (!isStringList(value)) throw new Error(`${BUILD_MANIFEST_FILE}: the script hashes for ${key} must be strings.`);
52
+ scriptHashes[key] = value;
53
+ }
54
+ return {
55
+ ...buildIdOf(parsed),
56
+ prerendered: parsed.prerendered,
57
+ headers,
58
+ scriptHashes
59
+ };
60
+ }
61
+
62
+ export { manifestKey as n, readBuildManifest as r, BUILD_MANIFEST_FILE as t };
63
+ //# sourceMappingURL=build-manifest-UDNk81Ce.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build-manifest-UDNk81Ce.js","names":[],"sources":["../src/core/build-manifest.ts"],"sourcesContent":["import type { StaticFiles } from \"./types.js\";\n\n/**\n * The file under the client build that the Vite plugin writes after the\n * client build and again after the prerender pass. It is a dotfile, so the\n * static stages never serve it.\n */\nexport const BUILD_MANIFEST_FILE = \".app-server.json\";\n\n/** What the Vite plugin records about the client build. */\nexport type BuildManifest = {\n\t/**\n\t * The ID of the client build: a hash of the files that the client build\n\t * writes. The `buildId` plugin sends it by default.\n\t */\n\tbuildId?: string;\n\t/** The URL paths that answered with a 2xx, sorted. */\n\tprerendered: string[];\n\t/** The headers of each prerendered file that is not an HTML document, by URL path. */\n\theaders: Record<string, Record<string, string>>;\n\t/**\n\t * The base64 `SHA-256` of each inline script of each HTML file in the client\n\t * build, by the file's URL path, such as `/about/index.html`. A CSP trusts\n\t * the scripts of a prerendered page by these hashes.\n\t */\n\tscriptHashes: Record<string, string[]>;\n};\n\n/**\n * The key for a URL path in {@link BuildManifest}: the path with no trailing\n * slash, so `/a/` and `/a` share headers. The root stays `/`.\n *\n * @example\n * manifestKey(\"/components/button/\"); // => \"/components/button\"\n */\nexport function manifestKey(pathname: string): string {\n\tconst trimmed = pathname.replace(/\\/+$/u, \"\");\n\treturn trimmed === \"\" ? \"/\" : trimmed;\n}\n\nfunction isStringRecord(value: unknown): value is Record<string, string> {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue != null &&\n\t\t!Array.isArray(value) &&\n\t\tObject.values(value).every((entry) => typeof entry === \"string\")\n\t);\n}\n\nfunction isStringList(value: unknown): value is string[] {\n\treturn Array.isArray(value) && value.every((entry) => typeof entry === \"string\");\n}\n\n/** The `buildId` of a parsed manifest, which can have none. A value that is not a string throws. */\nfunction buildIdOf(manifest: object): Pick<BuildManifest, \"buildId\"> {\n\tif (!(\"buildId\" in manifest)) {\n\t\treturn {};\n\t}\n\tif (typeof manifest.buildId !== \"string\") {\n\t\tthrow new TypeError(`${BUILD_MANIFEST_FILE}: the \"buildId\" must be a string.`);\n\t}\n\treturn { buildId: manifest.buildId };\n}\n\n/**\n * Reads the build manifest of a client build. A build with no file has an\n * empty one. A file in any other shape throws, so a bad build stops startup.\n */\nexport async function readBuildManifest(files: StaticFiles): Promise<BuildManifest> {\n\tconst path = `/${BUILD_MANIFEST_FILE}`;\n\tif ((await files.stat(path))?.kind !== \"file\") {\n\t\treturn { prerendered: [], headers: {}, scriptHashes: {} };\n\t}\n\tconst parsed: unknown = await new Response(await files.open(path)).json();\n\tif (\n\t\ttypeof parsed !== \"object\" ||\n\t\tparsed == null ||\n\t\t!(\"prerendered\" in parsed) ||\n\t\t!isStringList(parsed.prerendered) ||\n\t\t!(\"headers\" in parsed) ||\n\t\ttypeof parsed.headers !== \"object\" ||\n\t\tparsed.headers == null ||\n\t\t!(\"scriptHashes\" in parsed) ||\n\t\ttypeof parsed.scriptHashes !== \"object\" ||\n\t\tparsed.scriptHashes == null\n\t) {\n\t\tthrow new Error(\n\t\t\t`${BUILD_MANIFEST_FILE} must hold a \"prerendered\" list and the \"headers\" and \"scriptHashes\" objects.`,\n\t\t);\n\t}\n\tconst headers: Record<string, Record<string, string>> = {};\n\tfor (const [key, value] of Object.entries(parsed.headers)) {\n\t\tif (!isStringRecord(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the headers for ${key} must be strings.`);\n\t\t}\n\t\theaders[key] = value;\n\t}\n\tconst scriptHashes: Record<string, string[]> = {};\n\tfor (const [key, value] of Object.entries(parsed.scriptHashes)) {\n\t\tif (!isStringList(value)) {\n\t\t\tthrow new Error(`${BUILD_MANIFEST_FILE}: the script hashes for ${key} must be strings.`);\n\t\t}\n\t\tscriptHashes[key] = value;\n\t}\n\treturn {\n\t\t...buildIdOf(parsed),\n\t\tprerendered: parsed.prerendered,\n\t\theaders,\n\t\tscriptHashes,\n\t};\n}\n"],"mappings":";;;;;;AAOA,MAAa,sBAAsB;;;;;;;;AA4BnC,SAAgB,YAAY,UAA0B;CACrD,MAAM,UAAU,SAAS,QAAQ,SAAS,EAAE;CAC5C,OAAO,YAAY,KAAK,MAAM;AAC/B;AAEA,SAAS,eAAe,OAAiD;CACxE,OACC,OAAO,UAAU,YACjB,SAAS,QACT,CAAC,MAAM,QAAQ,KAAK,KACpB,OAAO,OAAO,KAAK,CAAC,CAAC,OAAO,UAAU,OAAO,UAAU,QAAQ;AAEjE;AAEA,SAAS,aAAa,OAAmC;CACxD,OAAO,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,UAAU,OAAO,UAAU,QAAQ;AAChF;;AAGA,SAAS,UAAU,UAAkD;CACpE,IAAI,EAAE,aAAa,WAClB,OAAO,CAAC;CAET,IAAI,OAAO,SAAS,YAAY,UAC/B,MAAM,IAAI,UAAU,GAAG,oBAAoB,kCAAkC;CAE9E,OAAO,EAAE,SAAS,SAAS,QAAQ;AACpC;;;;;AAMA,eAAsB,kBAAkB,OAA4C;CACnF,MAAM,OAAO,IAAI;CACjB,KAAK,MAAM,MAAM,KAAK,IAAI,EAAC,EAAG,SAAS,QACtC,OAAO;EAAE,aAAa,CAAC;EAAG,SAAS,CAAC;EAAG,cAAc,CAAC;CAAE;CAEzD,MAAM,SAAkB,MAAM,IAAI,SAAS,MAAM,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,KAAK;CACxE,IACC,OAAO,WAAW,YAClB,UAAU,QACV,EAAE,iBAAiB,WACnB,CAAC,aAAa,OAAO,WAAW,KAChC,EAAE,aAAa,WACf,OAAO,OAAO,YAAY,YAC1B,OAAO,WAAW,QAClB,EAAE,kBAAkB,WACpB,OAAO,OAAO,iBAAiB,YAC/B,OAAO,gBAAgB,MAEvB,MAAM,IAAI,MACT,GAAG,oBAAoB,8EACxB;CAED,MAAM,UAAkD,CAAC;CACzD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,OAAO,GAAG;EAC1D,IAAI,CAAC,eAAe,KAAK,GACxB,MAAM,IAAI,MAAM,GAAG,oBAAoB,oBAAoB,IAAI,kBAAkB;EAElF,QAAQ,OAAO;CAChB;CACA,MAAM,eAAyC,CAAC;CAChD,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,YAAY,GAAG;EAC/D,IAAI,CAAC,aAAa,KAAK,GACtB,MAAM,IAAI,MAAM,GAAG,oBAAoB,0BAA0B,IAAI,kBAAkB;EAExF,aAAa,OAAO;CACrB;CACA,OAAO;EACN,GAAG,UAAU,MAAM;EACnB,aAAa,OAAO;EACpB;EACA;CACD;AACD"}
@@ -1,6 +1,6 @@
1
- import { t as listenerUrl } from "./listen-options-DHWmSWGi.js";
1
+ import { t as listenerUrl } from "./listen-options-7TaXjyrk.js";
2
2
 
3
- // src/runtimes/bun.ts
3
+ // src/node/runtimes/bun.ts
4
4
  /** Bun's largest `idleTimeout`, in seconds. */
5
5
  const BUN_MAX_IDLE_TIMEOUT_S = 255;
6
6
  /** Listens with `Bun.serve`. */
@@ -9,19 +9,23 @@ async function listen(fetch, options) {
9
9
  port: options.port,
10
10
  ...options.hostname == null ? {} : { hostname: options.hostname },
11
11
  idleTimeout: Math.min(BUN_MAX_IDLE_TIMEOUT_S, Math.ceil(options.idleTimeoutMs / 1e3)),
12
- fetch: (request, bunServer) => fetch(request, { remoteAddress: bunServer.requestIP(request)?.address })
12
+ fetch: async (request, bunServer) => fetch(request, { remoteAddress: bunServer.requestIP(request)?.address })
13
13
  });
14
14
  return {
15
15
  url: listenerUrl(options.hostname, server.port),
16
16
  stop: async ({ deadlineMs }) => {
17
- const deadline = setTimeout(() => {
18
- server.stop(true);
19
- }, deadlineMs);
20
- await server.stop();
17
+ let deadline;
18
+ const deadlinePassed = new Promise((resolve) => {
19
+ deadline = setTimeout(() => {
20
+ server.stop(true);
21
+ resolve();
22
+ }, deadlineMs);
23
+ });
24
+ await Promise.race([server.stop(), deadlinePassed]);
21
25
  clearTimeout(deadline);
22
26
  }
23
27
  };
24
28
  }
25
29
 
26
30
  export { listen };
27
- //# sourceMappingURL=bun-DCGnDEPn.js.map
31
+ //# sourceMappingURL=bun-BCz6K_Xv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bun-BCz6K_Xv.js","names":[],"sources":["../src/node/runtimes/bun.ts"],"sourcesContent":["import type { FetchHandler, StartedListener } from \"../../core/types.js\";\nimport { listenerUrl } from \"./listen-options.js\";\nimport type { ListenOptions } from \"./listen-options.js\";\n\n/** The part of Bun's server that the listener uses. */\ntype BunServer = {\n\tport: number;\n\trequestIP: (request: Request) => { address: string } | null;\n\tstop: (closeActiveConnections?: boolean) => Promise<void>;\n};\n\n/** The part of the `Bun` global that the listener uses. */\ntype BunGlobal = {\n\tserve: (options: {\n\t\tport: number;\n\t\thostname?: string;\n\t\tidleTimeout: number;\n\t\tfetch: (request: Request, server: BunServer) => Response | Promise<Response>;\n\t}) => BunServer;\n};\n\n/** Bun's largest `idleTimeout`, in seconds. */\nconst BUN_MAX_IDLE_TIMEOUT_S = 255;\n\n/** Listens with `Bun.serve`. */\nexport async function listen(\n\tfetch: FetchHandler,\n\toptions: ListenOptions,\n): Promise<StartedListener> {\n\t// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `Bun` is a runtime global with no types in this package.\n\tconst bun = Reflect.get(globalThis, \"Bun\") as BunGlobal;\n\tconst server = bun.serve({\n\t\tport: options.port,\n\t\t...(options.hostname == null ? {} : { hostname: options.hostname }),\n\t\t// Why: Bun's 10 s default also closes a quiet event stream.\n\t\tidleTimeout: Math.min(BUN_MAX_IDLE_TIMEOUT_S, Math.ceil(options.idleTimeoutMs / 1_000)),\n\t\tfetch: async (request, bunServer) =>\n\t\t\tfetch(request, { remoteAddress: bunServer.requestIP(request)?.address }),\n\t});\n\treturn {\n\t\turl: listenerUrl(options.hostname, server.port),\n\t\tstop: async ({ deadlineMs }) => {\n\t\t\tlet deadline: ReturnType<typeof setTimeout> | undefined;\n\t\t\tconst deadlinePassed = new Promise<void>((resolve) => {\n\t\t\t\tdeadline = setTimeout(() => {\n\t\t\t\t\tvoid server.stop(true);\n\t\t\t\t\tresolve();\n\t\t\t\t}, deadlineMs);\n\t\t\t});\n\t\t\t// Why a race: on Bun 1.3, a response body that stays open keeps both stop promises\n\t\t\t// pending, and `stop(true)` leaves its connection open. The exit after shutdown closes it.\n\t\t\tawait Promise.race([server.stop(), deadlinePassed]);\n\t\t\tclearTimeout(deadline);\n\t\t},\n\t};\n}\n"],"mappings":";;;;AAsBA,MAAM,yBAAyB;;AAG/B,eAAsB,OACrB,OACA,SAC2B;CAG3B,MAAM,SADM,QAAQ,IAAI,YAAY,KACnB,CAAC,CAAC,MAAM;EACxB,MAAM,QAAQ;EACd,GAAI,QAAQ,YAAY,OAAO,CAAC,IAAI,EAAE,UAAU,QAAQ,SAAS;EAEjE,aAAa,KAAK,IAAI,wBAAwB,KAAK,KAAK,QAAQ,gBAAgB,GAAK,CAAC;EACtF,OAAO,OAAO,SAAS,cACtB,MAAM,SAAS,EAAE,eAAe,UAAU,UAAU,OAAO,CAAC,EAAE,QAAQ,CAAC;CACzE,CAAC;CACD,OAAO;EACN,KAAK,YAAY,QAAQ,UAAU,OAAO,IAAI;EAC9C,MAAM,OAAO,EAAE,iBAAiB;GAC/B,IAAI;GACJ,MAAM,iBAAiB,IAAI,SAAe,YAAY;IACrD,WAAW,iBAAiB;KAC3B,AAAK,OAAO,KAAK,IAAI;KACrB,QAAQ;IACT,GAAG,UAAU;GACd,CAAC;GAGD,MAAM,QAAQ,KAAK,CAAC,OAAO,KAAK,GAAG,cAAc,CAAC;GAClD,aAAa,QAAQ;EACtB;CACD;AACD"}
package/dist/cli.js CHANGED
@@ -1,35 +1,55 @@
1
1
  #!/usr/bin/env node
2
- import { t as parsePort } from "./tcp-Dau_IONd.js";
2
+ import { t as parsePort } from "./tcp-Dd1Mt6sN.js";
3
3
  import process from "node:process";
4
4
  import { parseArgs } from "node:util";
5
5
 
6
- // src/cli.ts
7
- const USAGE = "Usage: app-server start [--port <port>] | app-server serve [--port <port>] [build/server/index.js]";
8
- const { positionals, values } = parseArgs({
9
- allowPositionals: true,
10
- strict: true,
11
- options: { port: { type: "string" } }
12
- });
13
- const [command, buildPath = "build/server/index.js"] = positionals;
14
- if (values.port != null) process.env.PORT = String(parsePort(values.port));
15
- switch (command) {
16
- case "start": {
17
- process.env.NODE_ENV ??= "development";
18
- const { start } = await import("./start-BVMb8Pyt.js");
19
- await start();
20
- break;
21
- }
22
- case "serve": {
23
- process.env.NODE_ENV ??= "production";
24
- if (typeof process.setSourceMapsEnabled === "function") process.setSourceMapsEnabled(true);
25
- const { serve } = await import("./serve-ByeedcRB.js");
26
- await serve({ buildPath });
27
- break;
28
- }
29
- default:
30
- process.stderr.write(`${USAGE}\n`);
31
- process.exitCode = 1;
6
+ // src/cli/cli.ts
7
+ const USAGE = "Usage: app-server start [--port <port>] | app-server serve [--port <port>] [build/server/app-server.js]";
8
+ /** Writes `message` and the usage to stderr, and sets a failed exit code. */
9
+ function fail(message) {
10
+ process.stderr.write(`${message}\n${USAGE}\n`);
11
+ process.exitCode = 1;
32
12
  }
13
+ /** The parsed arguments. A bad argument throws. */
14
+ function parse() {
15
+ const { positionals, values } = parseArgs({
16
+ allowPositionals: true,
17
+ strict: true,
18
+ options: {
19
+ port: {
20
+ type: "string",
21
+ short: "p"
22
+ },
23
+ help: {
24
+ type: "boolean",
25
+ short: "h"
26
+ }
27
+ }
28
+ });
29
+ if (values.port != null) process.env.PORT = String(parsePort(values.port));
30
+ return {
31
+ command: positionals[0],
32
+ buildPath: positionals[1],
33
+ help: values.help === true
34
+ };
35
+ }
36
+ let args;
37
+ try {
38
+ args = parse();
39
+ } catch (error) {
40
+ fail(String(error instanceof Error ? error.message : error).replace(/^PORT\b/u, "--port"));
41
+ }
42
+ if (args?.help === true) process.stdout.write(`${USAGE}\n`);
43
+ else if (args?.command === "start") {
44
+ process.env.NODE_ENV ??= "development";
45
+ const { start } = await import("./start-TLIprD74.js");
46
+ await start();
47
+ } else if (args?.command === "serve") {
48
+ process.env.NODE_ENV ??= "production";
49
+ if (typeof process.setSourceMapsEnabled === "function") process.setSourceMapsEnabled(true);
50
+ const { serve } = await import("./serve-CDNgThjk.js");
51
+ await serve({ buildPath: args.buildPath });
52
+ } else if (args != null) fail(args.command == null ? "Give a command." : `Unknown command: ${args.command}.`);
33
53
 
34
54
  export { };
35
55
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n// The `app-server` command: `app-server start` or `app-server serve [build/server/index.js]`, each\n// with an optional `--port`.\nimport process from \"node:process\";\nimport { parseArgs } from \"node:util\";\nimport { parsePort } from \"./tcp.js\";\n\nconst USAGE =\n\t\"Usage: app-server start [--port <port>] | app-server serve [--port <port>] [build/server/index.js]\";\n\nconst { positionals, values } = parseArgs({\n\tallowPositionals: true,\n\tstrict: true,\n\toptions: { port: { type: \"string\" } },\n});\nconst [command, buildPath = \"build/server/index.js\"] = positionals;\n\n// Why set `PORT`: the copy of this package in the build reads it, so the flag needs no change to\n// the entry protocol.\nif (values.port != null) {\n\tprocess.env.PORT = String(parsePort(values.port));\n}\n\n// Why dynamic imports: React reads `NODE_ENV` when it loads, and a static import runs first.\nswitch (command) {\n\tcase \"start\": {\n\t\tprocess.env.NODE_ENV ??= \"development\";\n\t\tconst { start } = await import(\"./start.js\");\n\t\tawait start();\n\t\tbreak;\n\t}\n\tcase \"serve\": {\n\t\tprocess.env.NODE_ENV ??= \"production\";\n\t\tif (typeof process.setSourceMapsEnabled === \"function\") {\n\t\t\tprocess.setSourceMapsEnabled(true);\n\t\t}\n\t\tconst { serve } = await import(\"./serve.js\");\n\t\tawait serve({ buildPath });\n\t\tbreak;\n\t}\n\tdefault: {\n\t\tprocess.stderr.write(`${USAGE}\\n`);\n\t\tprocess.exitCode = 1;\n\t}\n}\n"],"mappings":";;;;;;AAOA,MAAM,QACL;AAED,MAAM,EAAE,aAAa,WAAW,UAAU;CACzC,kBAAkB;CAClB,QAAQ;CACR,SAAS,EAAE,MAAM,EAAE,MAAM,SAAS,EAAE;AACrC,CAAC;AACD,MAAM,CAAC,SAAS,YAAY,2BAA2B;AAIvD,IAAI,OAAO,QAAQ,MAClB,QAAQ,IAAI,OAAO,OAAO,UAAU,OAAO,IAAI,CAAC;AAIjD,QAAQ,SAAR;CACC,KAAK,SAAS;EACb,QAAQ,IAAI,aAAa;EACzB,MAAM,EAAE,UAAU,MAAM,OAAO;EAC/B,MAAM,MAAM;EACZ;CACD;CACA,KAAK,SAAS;EACb,QAAQ,IAAI,aAAa;EACzB,IAAI,OAAO,QAAQ,yBAAyB,YAC3C,QAAQ,qBAAqB,IAAI;EAElC,MAAM,EAAE,UAAU,MAAM,OAAO;EAC/B,MAAM,MAAM,EAAE,UAAU,CAAC;EACzB;CACD;CACA;EACC,QAAQ,OAAO,MAAM,GAAG,MAAM,GAAG;EACjC,QAAQ,WAAW;AAErB"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n// The `app-server` command: `app-server start` or `app-server serve [build/server/app-server.js]`,\n// each with an optional `--port`.\nimport process from \"node:process\";\nimport { parseArgs } from \"node:util\";\nimport { parsePort } from \"../node/tcp.js\";\n\nconst USAGE =\n\t\"Usage: app-server start [--port <port>] | app-server serve [--port <port>] [build/server/app-server.js]\";\n\n/** Writes `message` and the usage to stderr, and sets a failed exit code. */\nfunction fail(message: string): void {\n\tprocess.stderr.write(`${message}\\n${USAGE}\\n`);\n\tprocess.exitCode = 1;\n}\n\n/** The parsed arguments. A bad argument throws. */\nfunction parse() {\n\tconst { positionals, values } = parseArgs({\n\t\tallowPositionals: true,\n\t\tstrict: true,\n\t\toptions: { port: { type: \"string\", short: \"p\" }, help: { type: \"boolean\", short: \"h\" } },\n\t});\n\t// Why set `PORT`: the copy of this package in the build reads it, so the flag needs no change to\n\t// the entry protocol.\n\tif (values.port != null) {\n\t\tprocess.env.PORT = String(parsePort(values.port));\n\t}\n\treturn { command: positionals[0], buildPath: positionals[1], help: values.help === true };\n}\n\nlet args: ReturnType<typeof parse> | undefined;\ntry {\n\targs = parse();\n} catch (error) {\n\t// Why no stack: a bad argument is a usage error, not a crash.\n\tfail(String(error instanceof Error ? error.message : error).replace(/^PORT\\b/u, \"--port\"));\n}\n\n// Why dynamic imports: React reads `NODE_ENV` when it loads, and a static import runs first.\nif (args?.help === true) {\n\tprocess.stdout.write(`${USAGE}\\n`);\n} else if (args?.command === \"start\") {\n\tprocess.env.NODE_ENV ??= \"development\";\n\tconst { start } = await import(\"./start.js\");\n\tawait start();\n} else if (args?.command === \"serve\") {\n\tprocess.env.NODE_ENV ??= \"production\";\n\tif (typeof process.setSourceMapsEnabled === \"function\") {\n\t\tprocess.setSourceMapsEnabled(true);\n\t}\n\tconst { serve } = await import(\"./serve.js\");\n\tawait serve({ buildPath: args.buildPath });\n} else if (args != null) {\n\tfail(args.command == null ? \"Give a command.\" : `Unknown command: ${args.command}.`);\n}\n"],"mappings":";;;;;;AAOA,MAAM,QACL;;AAGD,SAAS,KAAK,SAAuB;CACpC,QAAQ,OAAO,MAAM,GAAG,QAAQ,IAAI,MAAM,GAAG;CAC7C,QAAQ,WAAW;AACpB;;AAGA,SAAS,QAAQ;CAChB,MAAM,EAAE,aAAa,WAAW,UAAU;EACzC,kBAAkB;EAClB,QAAQ;EACR,SAAS;GAAE,MAAM;IAAE,MAAM;IAAU,OAAO;GAAI;GAAG,MAAM;IAAE,MAAM;IAAW,OAAO;GAAI;EAAE;CACxF,CAAC;CAGD,IAAI,OAAO,QAAQ,MAClB,QAAQ,IAAI,OAAO,OAAO,UAAU,OAAO,IAAI,CAAC;CAEjD,OAAO;EAAE,SAAS,YAAY;EAAI,WAAW,YAAY;EAAI,MAAM,OAAO,SAAS;CAAK;AACzF;AAEA,IAAI;AACJ,IAAI;CACH,OAAO,MAAM;AACd,SAAS,OAAO;CAEf,KAAK,OAAO,iBAAiB,QAAQ,MAAM,UAAU,KAAK,CAAC,CAAC,QAAQ,YAAY,QAAQ,CAAC;AAC1F;AAGA,IAAI,MAAM,SAAS,MAClB,QAAQ,OAAO,MAAM,GAAG,MAAM,GAAG;KAC3B,IAAI,MAAM,YAAY,SAAS;CACrC,QAAQ,IAAI,aAAa;CACzB,MAAM,EAAE,UAAU,MAAM,OAAO;CAC/B,MAAM,MAAM;AACb,OAAO,IAAI,MAAM,YAAY,SAAS;CACrC,QAAQ,IAAI,aAAa;CACzB,IAAI,OAAO,QAAQ,yBAAyB,YAC3C,QAAQ,qBAAqB,IAAI;CAElC,MAAM,EAAE,UAAU,MAAM,OAAO;CAC/B,MAAM,MAAM,EAAE,WAAW,KAAK,UAAU,CAAC;AAC1C,OAAO,IAAI,QAAQ,MAClB,KAAK,KAAK,WAAW,OAAO,oBAAoB,oBAAoB,KAAK,QAAQ,EAAE"}
@@ -0,0 +1,141 @@
1
+ /** Options for {@link staleBuildReactRouter} and {@link staleBuildTanStack}. */
2
+ type StaleBuildOptions = {
3
+ /**
4
+ * The header that `buildId()` sets on data responses.
5
+ * @default "X-Build-Id"
6
+ */
7
+ header?: string;
8
+ /**
9
+ * The build that this document runs. Set it only when the server does not
10
+ * send it.
11
+ * @default the `build` metric of the document's `Server-Timing`, which `buildId()` sends
12
+ */
13
+ build?: string;
14
+ /**
15
+ * Runs once, when the tab first sees a response from another build. Use
16
+ * it to count stale tabs in the app's RUM tool.
17
+ */
18
+ onNewBuild?: (served: string) => void;
19
+ };
20
+ /** The context that React Router gives `unstable_fetch` with each request. */
21
+ type RouterFetchContext = {
22
+ /** `"navigation"` for the data request of a navigation that the router started. */
23
+ type: string;
24
+ /** `"PUSH"`, `"REPLACE"`, or `"POP"` for a navigation. */
25
+ navigationType?: string | null;
26
+ /** The fetcher that sends the request, also in a navigation that revalidates it. */
27
+ fetcherKey?: string | null;
28
+ };
29
+ /** The location in a TanStack Router event. */
30
+ type EventLocation = {
31
+ pathname: string;
32
+ searchStr: string;
33
+ };
34
+ /** The part of a TanStack Router that {@link staleBuildTanStack} reads. */
35
+ type NavigationEvents = {
36
+ history: {
37
+ flush: () => void;
38
+ };
39
+ clearCache: () => void;
40
+ subscribe: (type: "onBeforeNavigate" | "onResolved", listener: (event: {
41
+ fromLocation?: EventLocation;
42
+ toLocation: EventLocation;
43
+ }) => void) => () => void;
44
+ };
45
+ /** The `navigate` call of a React Router instrumentation. */
46
+ type NavigateInfo = {
47
+ to: string | number;
48
+ formMethod?: string;
49
+ };
50
+ /** The router instrumentations that {@link staleBuildReactRouter} adds. */
51
+ type RouterInstrumentations = {
52
+ navigate: (handler: () => Promise<unknown>, info: NavigateInfo) => Promise<void>;
53
+ };
54
+ /** The hooks that {@link staleBuildReactRouter} gives to React Router. */
55
+ type StaleBuildReactRouter = {
56
+ /** Give it to `HydratedRouter` as `unstable_fetch`. */
57
+ fetch: (request: Request, context: RouterFetchContext) => Promise<Response>;
58
+ /** Give it to `HydratedRouter` in `instrumentations`. */
59
+ instrumentation: {
60
+ router: (router: {
61
+ instrument: (instrumentations: RouterInstrumentations) => void;
62
+ }) => void;
63
+ };
64
+ /** Export it from `app/root.tsx` in `clientMiddleware`. */
65
+ middleware: <Result>(args: {
66
+ request: Request;
67
+ }, next: () => Promise<Result>) => Promise<Result>;
68
+ };
69
+ /**
70
+ * Moves an open React Router tab to a new build at a navigation, so the old
71
+ * client code never renders data from the new server, and the page that the
72
+ * visitor reads never reloads. Create it in a module that the client entry
73
+ * and `app/root.tsx` both import. It reads no browser state until React
74
+ * Router calls it, so the server can import it.
75
+ *
76
+ * - When the data request of a navigation gets a response from a new build,
77
+ * the browser loads the target URL as a document.
78
+ * - When the tab already knows of a new build, a `navigate` call, such as a
79
+ * link click, loads its target as a document before the router renders it
80
+ * or sends a data request. The root middleware does this also for a route
81
+ * with no loader.
82
+ * - A revalidation, a fetcher, an action, and the loaders after an action
83
+ * get their response. They only mark the tab, so the page that the visitor
84
+ * reads never reloads.
85
+ * - The router's blockers run first, and a canceled navigation never loads
86
+ * its target.
87
+ *
88
+ * It sends no request of its own and adds no wait. It needs `buildId()` in
89
+ * the server's pipeline, and it does nothing on a document with no build.
90
+ *
91
+ * @example
92
+ * // app/stale-build.ts
93
+ * export const staleBuild = staleBuildReactRouter();
94
+ *
95
+ * // app/root.tsx
96
+ * export const clientMiddleware = [staleBuild.middleware];
97
+ *
98
+ * // app/entry.client.tsx
99
+ * startTransition(() => {
100
+ * hydrateRoot(
101
+ * document,
102
+ * <HydratedRouter
103
+ * unstable_fetch={staleBuild.fetch}
104
+ * instrumentations={[staleBuild.instrumentation]}
105
+ * />,
106
+ * );
107
+ * });
108
+ */
109
+ export declare function staleBuildReactRouter(options?: StaleBuildOptions): StaleBuildReactRouter;
110
+ /**
111
+ * Moves an open TanStack Router tab to a new build at a navigation, so the
112
+ * old client code never renders data from the new server, and the page that
113
+ * the visitor reads never reloads. Call it with the router on the client.
114
+ *
115
+ * - A navigation runs from `onBeforeNavigate` to `onResolved`. The router
116
+ * moves history and runs its blockers before it.
117
+ * - When a GET response from a new build comes back while a navigation
118
+ * runs, such as from a server function in a loader, the browser loads the
119
+ * page as a document.
120
+ * - When the tab already knows of a new build, a navigation to a new path or
121
+ * query clears the router cache and loads the page as a document.
122
+ * - A request outside a navigation gets its response, and only marks the tab.
123
+ *
124
+ * It sends no request of its own and adds no wait. It needs `buildId()` in
125
+ * the server's pipeline, and it does nothing on a document with no build.
126
+ * It returns a function that stops it and gives back `fetch`. If the app
127
+ * wrapped `fetch` after it, the wrapper stays, and each request passes on.
128
+ *
129
+ * @example
130
+ * // src/router.tsx
131
+ * export function getRouter() {
132
+ * const router = createRouter({ routeTree });
133
+ * if (!router.isServer) {
134
+ * staleBuildTanStack(router);
135
+ * }
136
+ * return router;
137
+ * }
138
+ */
139
+ export declare function staleBuildTanStack(router: NavigationEvents, options?: StaleBuildOptions): () => void;
140
+ export type { NavigationEvents, RouterFetchContext, StaleBuildOptions, StaleBuildReactRouter };
141
+ //# sourceMappingURL=client.d.ts.map