@ngrok/app-server 0.2.0 → 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 (103) hide show
  1. package/README.md +610 -76
  2. package/dist/build-id-C6sYO9Yp.js +126 -0
  3. package/dist/build-id-C6sYO9Yp.js.map +1 -0
  4. package/dist/{build-manifest-8NfD1wnO.js → build-manifest-UDNk81Ce.js} +24 -6
  5. package/dist/build-manifest-UDNk81Ce.js.map +1 -0
  6. package/dist/cli.js +45 -25
  7. package/dist/cli.js.map +1 -1
  8. package/dist/client.d.ts +141 -0
  9. package/dist/client.js +326 -0
  10. package/dist/client.js.map +1 -0
  11. package/dist/compression-7_gToa8R.js +97 -0
  12. package/dist/compression-7_gToa8R.js.map +1 -0
  13. package/dist/create-server-iE1-s6Bi.js +1409 -0
  14. package/dist/create-server-iE1-s6Bi.js.map +1 -0
  15. package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
  16. package/dist/deno-aqhikNMG.js.map +1 -0
  17. package/dist/entry-DZ3qo7qF.js +116 -0
  18. package/dist/entry-DZ3qo7qF.js.map +1 -0
  19. package/dist/entry-DmJEqVfd.d.ts +622 -0
  20. package/dist/gzip-Doi4wqjX.js +294 -0
  21. package/dist/gzip-Doi4wqjX.js.map +1 -0
  22. package/dist/header-hook-Vzw9J9BY.js +159 -0
  23. package/dist/header-hook-Vzw9J9BY.js.map +1 -0
  24. package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
  25. package/dist/index.d.ts +99 -269
  26. package/dist/index.js +47 -59
  27. package/dist/index.js.map +1 -1
  28. package/dist/listen-options-7TaXjyrk.js.map +1 -1
  29. package/dist/{load-entry-C03qqmhr.js → load-entry-AfYS_zS9.js} +8 -4
  30. package/dist/{load-entry-C03qqmhr.js.map → load-entry-AfYS_zS9.js.map} +1 -1
  31. package/dist/log-BP6xXXZl.js +122 -0
  32. package/dist/log-BP6xXXZl.js.map +1 -0
  33. package/dist/node-BFH82eeL.js +333 -0
  34. package/dist/node-BFH82eeL.js.map +1 -0
  35. package/dist/node-tBVQPjQv.js +41 -0
  36. package/dist/node-tBVQPjQv.js.map +1 -0
  37. package/dist/node-vite.d.ts +5 -4
  38. package/dist/node-vite.js +2 -17
  39. package/dist/node.d.ts +23 -4
  40. package/dist/node.js +2 -2
  41. package/dist/react-router-vite.d.ts +4 -3
  42. package/dist/react-router-vite.js +2 -20
  43. package/dist/react-router.d.ts +1 -1
  44. package/dist/react-router.js +8 -7
  45. package/dist/react-router.js.map +1 -1
  46. package/dist/request-context-BtQ87VYb.js +40 -0
  47. package/dist/request-context-BtQ87VYb.js.map +1 -0
  48. package/dist/response-edge-Bc1-C_Cx.js +327 -0
  49. package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
  50. package/dist/response-writer-B7FoJjEE.js +289 -0
  51. package/dist/response-writer-B7FoJjEE.js.map +1 -0
  52. package/dist/script-hashes-hqUk6kG7.js +53 -0
  53. package/dist/script-hashes-hqUk6kG7.js.map +1 -0
  54. package/dist/{serve-Cleo8RMO.js → serve-CDNgThjk.js} +3 -3
  55. package/dist/{serve-Cleo8RMO.js.map → serve-CDNgThjk.js.map} +1 -1
  56. package/dist/{start-CINALHxy.js → start-TLIprD74.js} +14 -19
  57. package/dist/start-TLIprD74.js.map +1 -0
  58. package/dist/static-files-Beju9riB.js +302 -0
  59. package/dist/static-files-Beju9riB.js.map +1 -0
  60. package/dist/tanstack-start-vite.d.ts +6 -5
  61. package/dist/tanstack-start-vite.js +2 -23
  62. package/dist/tanstack-start.d.ts +19 -2
  63. package/dist/tanstack-start.js +5 -14
  64. package/dist/tanstack-start.js.map +1 -1
  65. package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
  66. package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
  67. package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
  68. package/dist/types-DLYxYS6M.d.ts +392 -0
  69. package/dist/vercel-vite.d.ts +35 -0
  70. package/dist/vercel-vite.js +142 -0
  71. package/dist/vercel-vite.js.map +1 -0
  72. package/dist/vercel.d.ts +35 -0
  73. package/dist/vercel.js +89 -0
  74. package/dist/vercel.js.map +1 -0
  75. package/dist/vite-B-GfswoH.js +22 -0
  76. package/dist/vite-B-GfswoH.js.map +1 -0
  77. package/dist/vite-D4hfj3ph.js +19 -0
  78. package/dist/vite-D4hfj3ph.js.map +1 -0
  79. package/dist/vite-DyrhyKEr.js +25 -0
  80. package/dist/vite-DyrhyKEr.js.map +1 -0
  81. package/dist/vite-iioAoxSt.js +752 -0
  82. package/dist/vite-iioAoxSt.js.map +1 -0
  83. package/dist/vite.d.ts +2 -2
  84. package/dist/vite.js +1 -1
  85. package/package.json +24 -4
  86. package/dist/build-manifest-8NfD1wnO.js.map +0 -1
  87. package/dist/deno-DNRgzHrk.js.map +0 -1
  88. package/dist/entry-BkdUub2S.js +0 -638
  89. package/dist/entry-BkdUub2S.js.map +0 -1
  90. package/dist/log-CsjaKM8U.js +0 -59
  91. package/dist/log-CsjaKM8U.js.map +0 -1
  92. package/dist/node-CG7qXuWZ.js +0 -58
  93. package/dist/node-CG7qXuWZ.js.map +0 -1
  94. package/dist/node-YWPGmzAk.js +0 -215
  95. package/dist/node-YWPGmzAk.js.map +0 -1
  96. package/dist/node-ZMowKZDB.js +0 -3
  97. package/dist/node-vite.js.map +0 -1
  98. package/dist/react-router-vite.js.map +0 -1
  99. package/dist/start-CINALHxy.js.map +0 -1
  100. package/dist/tanstack-start-vite.js.map +0 -1
  101. package/dist/types-BfCkS7kQ.d.ts +0 -203
  102. package/dist/vite-mYZ2Y69u.js +0 -144
  103. package/dist/vite-mYZ2Y69u.js.map +0 -1
@@ -0,0 +1,752 @@
1
+ import { a as isCompressible, n as MIN_COMPRESS_BYTES, r as copyName } from "./compression-7_gToa8R.js";
2
+ import { t as contentType } from "./static-files-Beju9riB.js";
3
+ import { n as manifestKey, t as BUILD_MANIFEST_FILE } from "./build-manifest-UDNk81Ce.js";
4
+ import { t as inlineScriptHashes } from "./script-hashes-hqUk6kG7.js";
5
+ import { t as node } from "./vite-D4hfj3ph.js";
6
+ import { t as reactRouterAdapter } from "./vite-B-GfswoH.js";
7
+ import { t as tanstackStartAdapter } from "./vite-DyrhyKEr.js";
8
+ import { isBuiltin } from "node:module";
9
+ import { getPath } from "hono/utils/url";
10
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
11
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
12
+ import { brotliCompressSync, constants as constants$1, gzipSync } from "node:zlib";
13
+ import { createHash } from "node:crypto";
14
+
15
+ // src/vite/standalone.ts
16
+ /**
17
+ * A package name: an optional scope and a name, each with no `/` or `\` and
18
+ * no `.` at the start. Why: a name such as `..` or `../x` in a manifest must
19
+ * not move a copy out of `node_modules`.
20
+ */
21
+ const PACKAGE_NAME = /^(?:@[^./\\][^/\\]*\/)?[^./\\][^/\\]*$/u;
22
+ /**
23
+ * The package names in the dependency `fields` of the `package.json` in
24
+ * `directory`. It skips a key that is not a package name.
25
+ *
26
+ * @example
27
+ * dependencyNames("/app/node_modules/react-dom", ["peerDependencies"]); // => ["react"]
28
+ */
29
+ function dependencyNames(directory, fields) {
30
+ const manifest = JSON.parse(readFileSync(join(directory, "package.json"), "utf8"));
31
+ const names = fields.flatMap((field) => {
32
+ const value = typeof manifest === "object" && manifest != null ? Reflect.get(manifest, field) : void 0;
33
+ return typeof value === "object" && value != null ? Object.keys(value).filter((name) => PACKAGE_NAME.test(name)) : [];
34
+ });
35
+ return [...new Set(names)];
36
+ }
37
+ /**
38
+ * The package name of a bare import.
39
+ *
40
+ * @example
41
+ * packageName("@scope/name/sub/path"); // => "@scope/name"
42
+ */
43
+ function packageName(specifier) {
44
+ return specifier.split("/").slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
45
+ }
46
+ /**
47
+ * Code that finds a file next to its own module: a relative `new URL()` on
48
+ * `import.meta.url`, `fileURLToPath(import.meta.url)`, or
49
+ * `import.meta.dirname`.
50
+ */
51
+ const OWN_FILE = /new\s+URL\(\s*(?<quote>["'`])\.{1,2}\/[^"'`]*\k<quote>\s*,\s*import\.meta\.url\s*\)|fileURLToPath\(\s*import\.meta\.url\s*\)|import\.meta\.(?:dirname|filename)\b/u;
52
+ /**
53
+ * Whether the module `file` finds a file next to itself, such as
54
+ * `@vercel/og`, which reads `resvg.wasm` through
55
+ * `new URL("./resvg.wasm", import.meta.url)`. Why: in the bundle,
56
+ * `import.meta.url` is the URL of the bundle, so the file is not there.
57
+ *
58
+ * @example
59
+ * readsOwnFiles("/app/node_modules/@vercel/og/dist/index.node.js"); // => true
60
+ */
61
+ function readsOwnFiles(file) {
62
+ return OWN_FILE.test(readFileSync(file, "utf8"));
63
+ }
64
+ /**
65
+ * The real path of the directory of package `name`, as Node finds it from the
66
+ * directory `from`: in each `node_modules` directory above `from`. Else
67
+ * `undefined`. The real path follows the symbolic links of pnpm's layout.
68
+ *
69
+ * @example
70
+ * findPackage("react", "/app/build/server"); // => "/app/node_modules/.pnpm/react@19.3.1/node_modules/react"
71
+ */
72
+ function findPackage(name, from) {
73
+ for (let directory = from;; directory = dirname(directory)) {
74
+ const candidate = join(directory, "node_modules", name);
75
+ if (basename(directory) !== "node_modules" && existsSync(join(candidate, "package.json"))) return realpathSync(candidate);
76
+ if (dirname(directory) === directory) return;
77
+ }
78
+ }
79
+ /**
80
+ * The directory of package `name` that holds `file`: the nearest directory
81
+ * above `file` at `node_modules/<name>`. Else `undefined`, such as for a file
82
+ * of a linked workspace package.
83
+ *
84
+ * @example
85
+ * packageDirectoryOf("/app/node_modules/react/cjs/react.js", "react"); // => "/app/node_modules/react"
86
+ */
87
+ function packageDirectoryOf(file, name) {
88
+ for (let directory = dirname(file); directory !== dirname(directory); directory = dirname(directory)) if (directory.endsWith(`${sep}${join("node_modules", name)}`)) return realpathSync(directory);
89
+ }
90
+ /** Whether a `.node` file is in `directory`, outside its `node_modules`. */
91
+ function hasNodeFile(directory) {
92
+ return readdirSync(directory, { withFileTypes: true }).some((entry) => entry.isDirectory() ? entry.name !== "node_modules" && hasNodeFile(join(entry.parentPath, entry.name)) : entry.name.endsWith(".node"));
93
+ }
94
+ /**
95
+ * Whether the package in `directory` loads a native addon: a `.node` file is
96
+ * in the package, or in a package of its `dependencies` or
97
+ * `optionalDependencies`. The second case finds a package that gets its addon
98
+ * from a package for each platform, such as `oxc-parser` from
99
+ * `@oxc-parser/binding-darwin-arm64`. Only the installed platform package is
100
+ * there. `scans` keeps the result for each directory that the function
101
+ * searched, so a call with the same map does not search a directory again.
102
+ *
103
+ * @example
104
+ * isNativePackage("/app/node_modules/better-sqlite3"); // => true
105
+ */
106
+ function isNativePackage(directory, scans = /* @__PURE__ */ new Map()) {
107
+ const scan = (path) => {
108
+ const found = scans.get(path) ?? hasNodeFile(path);
109
+ scans.set(path, found);
110
+ return found;
111
+ };
112
+ return scan(directory) || dependencyNames(directory, ["dependencies", "optionalDependencies"]).some((name) => {
113
+ const dependency = findPackage(name, directory);
114
+ return dependency != null && scan(dependency);
115
+ });
116
+ }
117
+ /**
118
+ * The `node_modules` directories where Node looks for a package that the
119
+ * package at `destination` imports, nearest first, down to `target`.
120
+ */
121
+ function lookupDirectories(destination, target) {
122
+ const directories = [];
123
+ for (let directory = destination;; directory = dirname(directory)) {
124
+ if (basename(directory) !== "node_modules") directories.push(join(directory, "node_modules"));
125
+ if (directory === dirname(target)) return directories;
126
+ }
127
+ }
128
+ /**
129
+ * Copies each package, whole, with the installed packages of its
130
+ * `dependencies`, `optionalDependencies`, and `peerDependencies`, into the
131
+ * `node_modules` directory `target`. Node then finds each package from a file
132
+ * next to `target`, with no install. The copy follows symbolic links. A
133
+ * dependency goes to the top of `target`. If another copy of that package is
134
+ * nearer in the lookup path of the package that needs it, the dependency goes
135
+ * into that package's own `node_modules`.
136
+ *
137
+ * @example
138
+ * copyPackages(new Map([["oxc-parser", "/app/node_modules/oxc-parser"]]), "/app/build/server/node_modules");
139
+ */
140
+ function copyPackages(packages, target) {
141
+ const sources = /* @__PURE__ */ new Map();
142
+ const queue = [];
143
+ const add = (destination, source) => {
144
+ sources.set(destination, source);
145
+ queue.push(destination);
146
+ };
147
+ for (const [name, source] of packages) add(join(target, name), source);
148
+ for (const destination of queue) {
149
+ const source = sources.get(destination) ?? "";
150
+ cpSync(source, destination, {
151
+ recursive: true,
152
+ dereference: true,
153
+ filter: (path) => path !== join(source, "node_modules")
154
+ });
155
+ for (const name of dependencyNames(source, [
156
+ "dependencies",
157
+ "optionalDependencies",
158
+ "peerDependencies"
159
+ ])) {
160
+ const dependency = findPackage(name, source);
161
+ const found = lookupDirectories(destination, target).map((directory) => join(directory, name)).find((path) => sources.has(path));
162
+ if (dependency != null && (found == null || sources.get(found) !== dependency)) add(join(found == null ? target : join(destination, "node_modules"), name), dependency);
163
+ }
164
+ }
165
+ }
166
+
167
+ // src/vite/index.ts
168
+ /** The module ID of the server entry that {@link appServer} generates. */
169
+ const SERVER_ENTRY_ID = "virtual:@ngrok/app-server/entry";
170
+ const RESOLVED_SERVER_ENTRY_ID = `\0${SERVER_ENTRY_ID}`;
171
+ /** The Vite environment that builds the server. */
172
+ const SERVER_ENVIRONMENT = "ssr";
173
+ /** A bare import, such as `react` or `@scope/name/path`: not a path, a `\0` ID, or a `node:` or `virtual:` ID. */
174
+ const BARE_IMPORT = /^[\w@][^:]*$/u;
175
+ /** The file extensions of a module that Node imports as it is, with no transform by Vite. */
176
+ const JAVASCRIPT_EXTENSIONS = /* @__PURE__ */ new Set([
177
+ "",
178
+ ".js",
179
+ ".mjs",
180
+ ".cjs"
181
+ ]);
182
+ /** The header that turns on Node's header store for a response, so `finish` can read every header. */
183
+ const CAPTURE_MARKER = "x-app-server-capture";
184
+ /**
185
+ * Headers that describe one transfer, not the resource. The server sets its
186
+ * own, and a cookie must never replay to every visitor. `Vary` is left out
187
+ * because the preview server adds `Vary: Origin` to every response.
188
+ */
189
+ const UNCAPTURED_HEADERS = /* @__PURE__ */ new Set([
190
+ CAPTURE_MARKER,
191
+ "connection",
192
+ "content-encoding",
193
+ "content-length",
194
+ "date",
195
+ "etag",
196
+ "keep-alive",
197
+ "last-modified",
198
+ "set-cookie",
199
+ "transfer-encoding",
200
+ "vary"
201
+ ]);
202
+ /** The built-in framework adapters, each with the name of the Vite plugin that marks its framework. */
203
+ const FRAMEWORKS = [{
204
+ plugin: "react-router:virtual-modules",
205
+ adapter: reactRouterAdapter
206
+ }, {
207
+ plugin: "tanstack-react-start:config",
208
+ adapter: tanstackStartAdapter
209
+ }];
210
+ /** The adapter of the one built-in framework whose plugin is in the Vite config. */
211
+ function detectFramework(plugins) {
212
+ const names = new Set(plugins.map((plugin) => plugin.name));
213
+ const [found, ...others] = FRAMEWORKS.filter(({ plugin }) => names.has(plugin));
214
+ if (found == null) throw new Error("@ngrok/app-server found no React Router or TanStack Start plugin in the Vite config. Add the framework's plugin, or pass `framework` to `appServer`.");
215
+ if (others.length > 0) throw new Error("@ngrok/app-server found the React Router and the TanStack Start plugins in the Vite config. Pass `framework` to `appServer`.");
216
+ return found.adapter();
217
+ }
218
+ /** The absolute path of `server.ts` or `server.js` in `root`, else `undefined` for the default app. */
219
+ function defaultApp(root) {
220
+ return ["server.ts", "server.js"].map((name) => join(root, name)).find((path) => existsSync(path));
221
+ }
222
+ /**
223
+ * The source of the server entry. When a runtime runs the file as its main
224
+ * module, such as `node build/server/app-server.js`, the entry starts the
225
+ * server. When the CLI imports it, the CLI starts the server.
226
+ */
227
+ function serverEntrySource({ framework, host, appModule, clientDirectory }) {
228
+ const modules = [
229
+ framework.serverModule,
230
+ "@ngrok/app-server",
231
+ framework.runtimeModule,
232
+ host.runtimeModule,
233
+ ...appModule == null ? [] : [appModule]
234
+ ];
235
+ return [
236
+ "if (import.meta.main) {",
237
+ " process.env.NODE_ENV ??= \"production\";",
238
+ " if (typeof process.setSourceMapsEnabled === \"function\") {",
239
+ " process.setSourceMapsEnabled(true);",
240
+ " }",
241
+ "}",
242
+ `const [serverModule, { createEntry, createServer }, { runtime }, hostModule${appModule == null ? "" : ", { default: app }"}] = await Promise.all([`,
243
+ ...modules.map((module) => `\timport(${JSON.stringify(module)}),`),
244
+ "]);",
245
+ ...appModule == null ? [`const app = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1", trustedProxyHops: Number(process.env.TRUSTED_PROXY_HOPS ?? 0) });`] : [],
246
+ `export const appServer = createEntry({`,
247
+ `\tapp,`,
248
+ `\thost: hostModule.host,`,
249
+ `\tclientDirectory: ${clientDirectory},`,
250
+ `\tframework: (mode) => runtime(serverModule, { ${framework.runtimeOptions == null ? "" : `...${framework.runtimeOptions}, `}mode }),`,
251
+ `});`,
252
+ "export { hostModule };",
253
+ "if (import.meta.main) {",
254
+ " await appServer.start();",
255
+ "}"
256
+ ].join("\n");
257
+ }
258
+ /** The paths of the build that a host's `output` gets. */
259
+ function hostOutput(config, host) {
260
+ return {
261
+ root: config.root,
262
+ clientDirectory: outDir(config, "client"),
263
+ entryFile: join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName)
264
+ };
265
+ }
266
+ /** The absolute path of an environment's build output. */
267
+ function outDir(config, environment) {
268
+ return resolve(config.root, config.environments[environment]?.build.outDir ?? config.build.outDir);
269
+ }
270
+ /**
271
+ * Whether `id` is a JavaScript file, which Node imports from `node_modules`
272
+ * as it is. Why: a plugin can resolve a bare import to a virtual module, and
273
+ * Vite transforms a JSON file or an asset, such as `?raw` on a file with no
274
+ * extension.
275
+ */
276
+ function isJavaScriptFile(id) {
277
+ return isAbsolute(id) && !id.includes("?") && JAVASCRIPT_EXTENSIONS.has(extname(id));
278
+ }
279
+ /**
280
+ * A `require.resolve()` or an `import.meta.resolve()` of a string literal.
281
+ * The `source` group is the string.
282
+ */
283
+ const RESOLVE_CALL = /\b(?:require|import\.meta)\.resolve\(\s*(?<quote>["'`])(?<source>[^"'`$]+)\k<quote>/gu;
284
+ /** The dependency fields of the app's `package.json` that can name a package the server imports. */
285
+ const APP_DEPENDENCY_FIELDS = [
286
+ "dependencies",
287
+ "optionalDependencies",
288
+ "devDependencies"
289
+ ];
290
+ /** Whether `environment` builds the server. */
291
+ function isServerBuild(environment) {
292
+ return environment.name === SERVER_ENVIRONMENT && environment.mode === "build";
293
+ }
294
+ /**
295
+ * Makes the server build run with no install. The build bundles each
296
+ * dependency, except the packages that the app keeps external (`ssr.external`
297
+ * or the bundler's `external`), each native package (see `isNativePackage`),
298
+ * each package that reads a file next to its own module (see `readsOwnFiles`),
299
+ * and each package that the bundle shares with a package that the app keeps
300
+ * external: the whole package of an external subpath, and each peer, at each
301
+ * level. Those stay external, so the plugin copies each one, whole, with its
302
+ * dependencies, into `node_modules` in the server build. It also writes a `package.json` there, so
303
+ * Node, Bun, and Deno load the build as ES modules and find that `node_modules`.
304
+ */
305
+ function standalone() {
306
+ const externals = /* @__PURE__ */ new Map();
307
+ const shared = /* @__PURE__ */ new Set();
308
+ const natives = /* @__PURE__ */ new Map();
309
+ const scans = /* @__PURE__ */ new Map();
310
+ const isNative = (directory) => {
311
+ const native = natives.get(directory) ?? isNativePackage(directory, scans);
312
+ natives.set(directory, native);
313
+ return native;
314
+ };
315
+ const ownFiles = /* @__PURE__ */ new Map();
316
+ const readsOwnFile = (file) => {
317
+ const reads = ownFiles.get(file) ?? (existsSync(file) && readsOwnFiles(file));
318
+ ownFiles.set(file, reads);
319
+ return reads;
320
+ };
321
+ const inBundle = /* @__PURE__ */ new Set();
322
+ /**
323
+ * Whether the bundled module `file` of package `name` must stay external:
324
+ * the package is native, or `file` reads a file next to it. Then the
325
+ * package and each of its peers stay external, so the bundle shares them.
326
+ */
327
+ const staysExternal = ({ name, file, directory }, logger) => {
328
+ const native = directory != null && isNative(directory);
329
+ if (directory == null || !native && !readsOwnFile(file)) {
330
+ inBundle.add(name);
331
+ return false;
332
+ }
333
+ const group = withPeers([{
334
+ name,
335
+ from: directory
336
+ }]);
337
+ const held = [...group].find((peer) => inBundle.has(peer));
338
+ if (held != null && !native) {
339
+ logger.warn(`@ngrok/app-server bundles "${name}", but it reads a file next to its own module, so the server can fail when it reads that file. The bundle already holds "${held}", so "${name}" cannot stay external alone. Add "${name}" to \`ssr.external\`.`);
340
+ inBundle.add(name);
341
+ return false;
342
+ }
343
+ for (const peer of group) shared.add(peer);
344
+ return true;
345
+ };
346
+ return {
347
+ name: "@ngrok/app-server:standalone",
348
+ enforce: "pre",
349
+ config: (config, { command }) => {
350
+ const ssr = config.environments?.[SERVER_ENVIRONMENT]?.resolve;
351
+ return command === "build" && config.ssr?.noExternal == null && ssr?.noExternal == null && config.ssr?.external !== true && ssr?.external !== true ? { ssr: { noExternal: true } } : void 0;
352
+ },
353
+ buildStart() {
354
+ if (!isServerBuild(this.environment)) return;
355
+ externals.clear();
356
+ shared.clear();
357
+ natives.clear();
358
+ scans.clear();
359
+ ownFiles.clear();
360
+ inBundle.clear();
361
+ const { resolve: resolveOptions, build, root } = this.environment.config;
362
+ const kept = [...resolveOptions.external === true ? [] : resolveOptions.external, ...[build.rolldownOptions.external].flat()];
363
+ const names = kept.flatMap((id) => typeof id === "string" && BARE_IMPORT.test(id) ? [packageName(id)] : []);
364
+ const patterns = kept.filter((id) => id != null && typeof id !== "string");
365
+ const matched = patterns.length === 0 || !existsSync(join(root, "package.json")) ? [] : dependencyNames(root, APP_DEPENDENCY_FIELDS).filter((name) => patterns.some((pattern) => matchesExternal(pattern, name)));
366
+ for (const name of names) {
367
+ const directory = findPackage(name, root);
368
+ if (directory != null) externals.set(name, directory);
369
+ }
370
+ for (const name of withPeers([...names, ...matched].map((dependency) => ({
371
+ name: dependency,
372
+ from: root
373
+ })))) shared.add(name);
374
+ },
375
+ resolveId: {
376
+ filter: { id: BARE_IMPORT },
377
+ async handler(source, importer, options) {
378
+ if (!isServerBuild(this.environment) || isBuiltin(source)) return null;
379
+ const resolved = await this.resolve(source, importer, {
380
+ ...options,
381
+ skipSelf: true
382
+ });
383
+ const bundled = resolved?.external === false;
384
+ if (resolved == null || bundled && !isJavaScriptFile(resolved.id)) return resolved;
385
+ const name = packageName(source);
386
+ const directory = (bundled ? packageDirectoryOf(resolved.id, name) : void 0) ?? findPackage(name, importer != null && isAbsolute(importer) ? dirname(importer) : this.environment.config.root);
387
+ if (bundled && !shared.has(name) && !staysExternal({
388
+ name,
389
+ file: resolved.id,
390
+ directory
391
+ }, this.environment.logger)) return resolved;
392
+ const known = externals.get(name);
393
+ if (known != null && directory != null && known !== directory) throw new Error(`@ngrok/app-server found two copies of "${name}" that stay external, and the server build can hold one: ${known} and ${directory}. Install one version of "${name}".`);
394
+ externals.set(name, known ?? directory);
395
+ return bundled ? {
396
+ id: source,
397
+ external: true
398
+ } : resolved;
399
+ }
400
+ },
401
+ transform: {
402
+ filter: {
403
+ id: { exclude: /[\\/]node_modules[\\/]/u },
404
+ code: /\b(?:require|import\.meta)\.resolve\(/u
405
+ },
406
+ handler(code, id) {
407
+ if (!isServerBuild(this.environment)) return null;
408
+ for (const { groups } of code.matchAll(RESOLVE_CALL)) {
409
+ const source = groups?.source ?? "";
410
+ const name = packageName(source);
411
+ const directory = BARE_IMPORT.test(source) && !isBuiltin(source) && !externals.has(name) ? findPackage(name, isAbsolute(id) ? dirname(id) : this.environment.config.root) : void 0;
412
+ if (directory != null) externals.set(name, directory);
413
+ }
414
+ return null;
415
+ }
416
+ },
417
+ writeBundle() {
418
+ if (!isServerBuild(this.environment)) return;
419
+ for (const importer of this.getModuleIds()) {
420
+ const info = this.getModuleInfo(importer);
421
+ for (const id of [...info?.importedIds ?? [], ...info?.dynamicallyImportedIds ?? []]) {
422
+ const name = packageName(id);
423
+ if (BARE_IMPORT.test(id) && !isBuiltin(id) && !externals.has(name)) externals.set(name, findPackage(name, isAbsolute(importer) ? dirname(importer) : this.environment.config.root));
424
+ }
425
+ }
426
+ const directory = outDir(this.environment.getTopLevelConfig(), SERVER_ENVIRONMENT);
427
+ const found = /* @__PURE__ */ new Map();
428
+ for (const [name, source] of externals) if (source == null) this.environment.logger.warn(`@ngrok/app-server cannot find "${name}", which stays external, so the server build does not hold it. The server fails if it imports "${name}".`);
429
+ else found.set(name, source);
430
+ const target = join(directory, "node_modules");
431
+ rmSync(target, {
432
+ recursive: true,
433
+ force: true
434
+ });
435
+ copyPackages(found, target);
436
+ writeFileSync(join(directory, "package.json"), `${JSON.stringify({ type: "module" })}\n`);
437
+ if (found.size > 0) this.environment.logger.info(`@ngrok/app-server copied the external packages ${[...found.keys()].join(", ")}, with their dependencies, into ${target}.`);
438
+ }
439
+ };
440
+ }
441
+ /**
442
+ * Whether the app's `RegExp` or function external keeps the package `name`
443
+ * external. Why `false` when the function throws: the build calls it with no
444
+ * importer, and a function that reads the importer can throw.
445
+ */
446
+ function matchesExternal(pattern, name) {
447
+ if (typeof pattern !== "function") return name.search(pattern) !== -1;
448
+ try {
449
+ return pattern(name, void 0, false) === true;
450
+ } catch {
451
+ return false;
452
+ }
453
+ }
454
+ /**
455
+ * Each package of `start` and each of its peers, at each level. Why each
456
+ * level: a peer can have peers, such as `react` for `react-router`.
457
+ */
458
+ function withPeers(start) {
459
+ const names = /* @__PURE__ */ new Set();
460
+ const queue = [...start];
461
+ for (const { name, from } of queue) {
462
+ const directory = names.has(name) ? void 0 : findPackage(name, from);
463
+ names.add(name);
464
+ if (directory != null) for (const peer of dependencyNames(directory, ["peerDependencies"])) queue.push({
465
+ name: peer,
466
+ from: directory
467
+ });
468
+ }
469
+ return names;
470
+ }
471
+ /** The {@link inlineScriptHashes} of each HTML file in the client build, by its URL path. */
472
+ function scriptHashesOf(clientDirectory) {
473
+ const hashes = {};
474
+ for (const entry of readdirSync(clientDirectory, {
475
+ recursive: true,
476
+ withFileTypes: true
477
+ })) if (entry.isFile() && contentType(entry.name, {}).startsWith("text/html")) {
478
+ const path = join(entry.parentPath, entry.name);
479
+ const urlPath = `/${relative(clientDirectory, path).split(sep).join("/")}`;
480
+ hashes[urlPath] = inlineScriptHashes(readFileSync(path, "utf8"));
481
+ }
482
+ return Object.fromEntries(Object.entries(hashes).toSorted(([first], [second]) => first.localeCompare(second)));
483
+ }
484
+ /** Writes `.app-server.json` into the client build. */
485
+ function writeBuildManifest(clientDirectory, manifest) {
486
+ mkdirSync(clientDirectory, { recursive: true });
487
+ writeFileSync(join(clientDirectory, BUILD_MANIFEST_FILE), `${JSON.stringify(manifest, null, " ")}\n`);
488
+ }
489
+ /**
490
+ * Writes the build ID and the script hashes of the client build
491
+ * ({@link scriptHashesOf}) into `.app-server.json`, and keeps the rest of the
492
+ * file. Why after the build too: a build with no prerender pass can have HTML
493
+ * files, such as `public/offline.html`.
494
+ */
495
+ function completeBuildManifest(clientDirectory, buildId) {
496
+ if (!existsSync(clientDirectory)) return;
497
+ const path = join(clientDirectory, BUILD_MANIFEST_FILE);
498
+ const recorded = existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : void 0;
499
+ writeBuildManifest(clientDirectory, {
500
+ prerendered: [],
501
+ headers: {},
502
+ ...typeof recorded === "object" && recorded != null ? recorded : {},
503
+ ...buildId == null ? {} : { buildId },
504
+ scriptHashes: scriptHashesOf(clientDirectory)
505
+ });
506
+ }
507
+ /**
508
+ * The ID of a client build: a hash of the name and the content of each file
509
+ * in its bundle. Why the bundle: it is the code that an open tab runs, so the
510
+ * ID changes when that code changes, and not for a change to the server, a
511
+ * `public/` file, or a prerendered page. Why the content, not the file
512
+ * names: a name has a content hash only when the output names ask for one.
513
+ */
514
+ function bundleBuildId(bundle) {
515
+ const hash = createHash("sha256");
516
+ for (const file of Object.values(bundle).toSorted((first, second) => first.fileName < second.fileName ? -1 : 1)) {
517
+ hash.update(`${file.fileName}\0`);
518
+ hash.update(file.type === "chunk" ? file.code : file.source);
519
+ hash.update("\0");
520
+ }
521
+ return hash.digest("hex").slice(0, 16);
522
+ }
523
+ /** The path of each file under `directory` that is not a dotfile, in code unit order. */
524
+ function filesIn(directory) {
525
+ if (!existsSync(directory)) return [];
526
+ return readdirSync(directory, {
527
+ recursive: true,
528
+ withFileTypes: true
529
+ }).filter((entry) => entry.isFile() && !entry.name.startsWith(".")).map((entry) => relative(directory, join(entry.parentPath, entry.name)).split(sep).join("/")).toSorted();
530
+ }
531
+ /**
532
+ * The ID of the whole build: the {@link bundleBuildId} of the client bundle,
533
+ * with the name and the content of each file that a later build step added to
534
+ * the assets directory. Why: React Router writes its route manifest
535
+ * (`assets/manifest-*.js`) during the server build, and a route change, such
536
+ * as a new path for one module, can keep the client bundle the same.
537
+ */
538
+ function appBuildId({ bundleId, assetsDirectory, assets }) {
539
+ const added = filesIn(assetsDirectory).filter((file) => !assets.has(file));
540
+ if (added.length === 0) return bundleId;
541
+ const hash = createHash("sha256").update(bundleId);
542
+ for (const file of added) {
543
+ hash.update(`\0${file}\0`);
544
+ hash.update(readFileSync(join(assetsDirectory, file)));
545
+ }
546
+ return hash.digest("hex").slice(0, 16);
547
+ }
548
+ /** The `buildId` of the build manifest that the client build wrote, if any. */
549
+ function writtenBuildId(clientDirectory) {
550
+ const path = join(clientDirectory, BUILD_MANIFEST_FILE);
551
+ if (!existsSync(path)) return;
552
+ const manifest = JSON.parse(readFileSync(path, "utf8"));
553
+ return typeof manifest === "object" && manifest != null && "buildId" in manifest && typeof manifest.buildId === "string" ? manifest.buildId : void 0;
554
+ }
555
+ /**
556
+ * Records each 2xx path and the headers of each non-document response while
557
+ * the framework's prerender pass runs. It writes them to `.app-server.json` in
558
+ * the client build when the preview server closes, with the script hashes of
559
+ * each HTML file.
560
+ */
561
+ function capture(server, afterPass) {
562
+ const clientDirectory = outDir(server.config, "client");
563
+ const started = Date.now();
564
+ const paths = /* @__PURE__ */ new Set();
565
+ const headers = {};
566
+ server.middlewares.use((request, response, next) => {
567
+ const pathname = getPath(new Request(new URL(request.url ?? "/", "http://localhost")));
568
+ response.setHeader(CAPTURE_MARKER, "1");
569
+ response.once("finish", () => {
570
+ if (response.statusCode < 200 || response.statusCode >= 300) return;
571
+ const key = manifestKey(pathname);
572
+ paths.add(key);
573
+ if (String(response.getHeader("content-type") ?? "").startsWith("text/html")) return;
574
+ const recorded = {};
575
+ for (const [name, value] of Object.entries(response.getHeaders())) if (!UNCAPTURED_HEADERS.has(name) && !/^\d+$/u.test(name) && value != null) recorded[name] = Array.isArray(value) ? value.join(", ") : String(value);
576
+ headers[key] = recorded;
577
+ });
578
+ next();
579
+ });
580
+ server.httpServer.once("close", () => {
581
+ const buildId = writtenBuildId(clientDirectory);
582
+ writeBuildManifest(clientDirectory, {
583
+ ...buildId == null ? {} : { buildId },
584
+ prerendered: [...paths].toSorted(),
585
+ headers: Object.fromEntries(Object.entries(headers).toSorted(([first], [second]) => first.localeCompare(second))),
586
+ scriptHashes: scriptHashesOf(clientDirectory)
587
+ });
588
+ writeAllCopies(clientDirectory, { changedSince: started - 2e3 });
589
+ afterPass();
590
+ });
591
+ }
592
+ /**
593
+ * The brotli quality of the copies. Why 9, not the highest (11): on a docs
594
+ * build with 70 MB of text, 11 adds 46 s to the build and 9 adds 0.6 s. The
595
+ * copies of 9 are 9% larger, and still 25% smaller than the gzip copies.
596
+ */
597
+ const BROTLI_QUALITY = 9;
598
+ /**
599
+ * Writes the compressed copies (`.<file>.gz` and `.<file>.br`) of the file at
600
+ * `path` when the server compresses the file: a compressible type of 1 KiB
601
+ * or more. It writes a copy only when it is smaller: the gzip copy than the
602
+ * file, and the brotli copy than the gzip copy. Else it removes an old copy,
603
+ * so a copy from an earlier build never replaces a changed file.
604
+ */
605
+ function writeCopies(path) {
606
+ const bytes = isCompressible(contentType(path, {})) && statSync(path, { throwIfNoEntry: false })?.isFile() === true ? readFileSync(path) : void 0;
607
+ const gzip = bytes == null || bytes.byteLength < 1024 ? void 0 : gzipSync(bytes, { level: constants$1.Z_BEST_COMPRESSION });
608
+ const gzipCopy = gzip != null && bytes != null && gzip.byteLength < bytes.byteLength ? gzip : void 0;
609
+ const brotli = gzipCopy == null || bytes == null ? void 0 : brotliCompressSync(bytes, { params: {
610
+ [constants$1.BROTLI_PARAM_MODE]: constants$1.BROTLI_MODE_TEXT,
611
+ [constants$1.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY,
612
+ [constants$1.BROTLI_PARAM_SIZE_HINT]: bytes.byteLength
613
+ } });
614
+ const brotliCopy = brotli != null && gzipCopy != null && brotli.byteLength < gzipCopy.byteLength ? brotli : void 0;
615
+ const copies = [["gzip", gzipCopy], ["br", brotliCopy]];
616
+ for (const [encoding, copy] of copies) {
617
+ const copyPath = join(dirname(path), copyName(basename(path), encoding));
618
+ if (copy == null) rmSync(copyPath, { force: true });
619
+ else writeFileSync(copyPath, copy);
620
+ }
621
+ }
622
+ /**
623
+ * Runs {@link writeCopies} for each file in the client build, except dotfiles
624
+ * such as the copies. With `changedSince`, only for a file that changed at or
625
+ * after that time, in milliseconds since the epoch.
626
+ */
627
+ function writeAllCopies(clientDirectory, { changedSince } = {}) {
628
+ if (!existsSync(clientDirectory)) return;
629
+ for (const entry of readdirSync(clientDirectory, {
630
+ recursive: true,
631
+ withFileTypes: true
632
+ })) {
633
+ const path = join(entry.parentPath, entry.name);
634
+ if (entry.isFile() && !entry.name.startsWith(".") && (changedSince == null || (statSync(path, { throwIfNoEntry: false })?.mtimeMs ?? 0) >= changedSince)) writeCopies(path);
635
+ }
636
+ }
637
+ /**
638
+ * The Vite plugin for `@ngrok/app-server`. Put it next to the framework's
639
+ * plugin.
640
+ *
641
+ * - It adds the server entry to the server build, such as
642
+ * `build/server/app-server.js` on the node host. The entry bundles the app
643
+ * (the default export of `app`) with the framework's server module, so the
644
+ * server gets the app's path aliases and its one copy of the framework.
645
+ * The framework's own entry does not change. When a runtime runs the entry
646
+ * as its main module, the entry starts the server.
647
+ * - In a build, it bundles each dependency into the server build. It copies
648
+ * each package that stays external into `node_modules` in the server build.
649
+ * So the build directory runs with no install.
650
+ * - After the client build, it writes `.app-server.json` in the client
651
+ * build with the build ID: a hash of the client bundle. After the build,
652
+ * it adds the files that the server build wrote to the client's assets
653
+ * directory, such as React Router's route manifest. The `buildId` plugin
654
+ * sends the ID.
655
+ * - During the framework's prerender pass, it records each prerendered path
656
+ * and the headers of each prerendered file that is not an HTML document into
657
+ * `.app-server.json` in the client build. The `prerendered` plugin replays
658
+ * the headers. A document's headers depend on its request, so they are not
659
+ * recorded.
660
+ * - After the build and after the prerender pass, it records the hash of each
661
+ * inline script of each HTML file in `.app-server.json`, for the
662
+ * `contentSecurityPolicy` plugin. It also writes a gzip copy (`.<file>.gz`)
663
+ * and a brotli copy (`.<file>.br`) next to each text file of 1 KiB or more
664
+ * in the client build, HTML included. The static stages send a copy, so the
665
+ * server does not compress these files for each request.
666
+ *
667
+ * @example
668
+ * // vite.config.ts
669
+ * export default defineConfig({ plugins: [reactRouter(), appServer()] });
670
+ */
671
+ function appServer(options = {}) {
672
+ const host = options.host ?? node();
673
+ let resolved;
674
+ let clientBuild;
675
+ return [
676
+ {
677
+ name: "@ngrok/app-server",
678
+ configResolved: (config) => {
679
+ const framework = options.framework ?? detectFramework(config.plugins);
680
+ framework.validate?.(config);
681
+ resolved = {
682
+ config,
683
+ framework,
684
+ appModule: options.app == null ? defaultApp(config.root) : resolve(config.root, options.app)
685
+ };
686
+ },
687
+ buildStart() {
688
+ if (isServerBuild(this.environment)) this.emitFile({
689
+ type: "chunk",
690
+ id: SERVER_ENTRY_ID,
691
+ fileName: host.entryFileName
692
+ });
693
+ },
694
+ writeBundle(output, bundle) {
695
+ if (this.environment.name === "client") {
696
+ const directory = output.dir ?? outDir(this.environment.config, "client");
697
+ const assetsDirectory = join(directory, this.environment.config.build.assetsDir);
698
+ clientBuild = {
699
+ bundleId: bundleBuildId(bundle),
700
+ assetsDirectory,
701
+ assets: new Set(filesIn(assetsDirectory))
702
+ };
703
+ writeBuildManifest(directory, {
704
+ buildId: clientBuild.bundleId,
705
+ prerendered: [],
706
+ headers: {},
707
+ scriptHashes: {}
708
+ });
709
+ }
710
+ },
711
+ renderStart(output) {
712
+ if (this.environment.name === SERVER_ENVIRONMENT && output.format !== "es") throw new Error(`@ngrok/app-server needs an ES module server build, and this build has the format "${output.format}".`);
713
+ },
714
+ resolveId: (id) => id === "virtual:@ngrok/app-server/entry" ? RESOLVED_SERVER_ENTRY_ID : void 0,
715
+ load(id) {
716
+ if (id !== RESOLVED_SERVER_ENTRY_ID || resolved == null) return null;
717
+ const { config, framework, appModule } = resolved;
718
+ const clientDirectory = outDir(config, "client");
719
+ const serverDirectory = outDir(config, SERVER_ENVIRONMENT);
720
+ const fromClient = relative(clientDirectory, serverDirectory);
721
+ if (this.environment.mode === "build" && !fromClient.startsWith("..") && !isAbsolute(fromClient)) throw new Error(`@ngrok/app-server needs the server build outside the client build, and both are in ${clientDirectory}.`);
722
+ const fromEntry = relative(dirname(join(serverDirectory, host.entryFileName)), clientDirectory).replaceAll("\\", "/");
723
+ return serverEntrySource({
724
+ framework,
725
+ host,
726
+ appModule,
727
+ clientDirectory: this.environment.mode === "build" ? `new URL(${JSON.stringify(`${fromEntry}/`)}, import.meta.url).href` : JSON.stringify(clientDirectory)
728
+ });
729
+ },
730
+ configurePreviewServer: (server) => {
731
+ if (resolved?.framework.isPrerenderPass(server) === true) capture(server, () => host.output?.(hostOutput(server.config, host)));
732
+ }
733
+ },
734
+ {
735
+ name: "@ngrok/app-server:compressed-copies",
736
+ enforce: "post",
737
+ buildApp: {
738
+ order: "post",
739
+ handler: async (builder) => {
740
+ const clientDirectory = outDir(builder.config, "client");
741
+ completeBuildManifest(clientDirectory, clientBuild == null ? void 0 : appBuildId(clientBuild));
742
+ writeAllCopies(clientDirectory);
743
+ host.output?.(hostOutput(builder.config, host));
744
+ }
745
+ }
746
+ },
747
+ standalone()
748
+ ];
749
+ }
750
+
751
+ export { appServer as n, serverEntrySource as r, SERVER_ENTRY_ID as t };
752
+ //# sourceMappingURL=vite-iioAoxSt.js.map