@ngrok/app-server 0.1.0 → 0.2.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.
- package/README.md +77 -22
- package/dist/build-manifest-8NfD1wnO.js +45 -0
- package/dist/build-manifest-8NfD1wnO.js.map +1 -0
- package/dist/{bun-DCGnDEPn.js → bun-BCz6K_Xv.js} +12 -8
- package/dist/bun-BCz6K_Xv.js.map +1 -0
- package/dist/cli.js +15 -13
- package/dist/cli.js.map +1 -1
- package/dist/{deno-BnMfk2n1.js → deno-DNRgzHrk.js} +4 -4
- package/dist/deno-DNRgzHrk.js.map +1 -0
- package/dist/{entry-2XXp2Ukh.js → entry-BkdUub2S.js} +179 -334
- package/dist/entry-BkdUub2S.js.map +1 -0
- package/dist/index-oSE-tYRW.d.ts +88 -0
- package/dist/index.d.ts +212 -27
- package/dist/index.js +26 -14
- package/dist/index.js.map +1 -1
- package/dist/{listen-options-DHWmSWGi.js → listen-options-7TaXjyrk.js} +2 -2
- package/dist/listen-options-7TaXjyrk.js.map +1 -0
- package/dist/load-entry-C03qqmhr.js +33 -0
- package/dist/load-entry-C03qqmhr.js.map +1 -0
- package/dist/log-CsjaKM8U.js +59 -0
- package/dist/log-CsjaKM8U.js.map +1 -0
- package/dist/{node-79my3Uix.js → node-CG7qXuWZ.js} +4 -4
- package/dist/node-CG7qXuWZ.js.map +1 -0
- package/dist/node-YWPGmzAk.js +215 -0
- package/dist/node-YWPGmzAk.js.map +1 -0
- package/dist/node-ZMowKZDB.js +3 -0
- package/dist/node-vite.d.ts +10 -0
- package/dist/node-vite.js +18 -0
- package/dist/node-vite.js.map +1 -0
- package/dist/node.d.ts +67 -0
- package/dist/node.js +4 -0
- package/dist/react-router-vite.d.ts +9 -0
- package/dist/react-router-vite.js +21 -0
- package/dist/react-router-vite.js.map +1 -0
- package/dist/react-router.d.ts +11 -24
- package/dist/react-router.js +15 -25
- package/dist/react-router.js.map +1 -1
- package/dist/serve-Cleo8RMO.js +29 -0
- package/dist/serve-Cleo8RMO.js.map +1 -0
- package/dist/start-CINALHxy.js +230 -0
- package/dist/start-CINALHxy.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +11 -0
- package/dist/tanstack-start-vite.js +24 -0
- package/dist/tanstack-start-vite.js.map +1 -0
- package/dist/tanstack-start.d.ts +17 -0
- package/dist/tanstack-start.js +50 -0
- package/dist/tanstack-start.js.map +1 -0
- package/dist/tcp-C-9AmFuM.js +41 -0
- package/dist/tcp-C-9AmFuM.js.map +1 -0
- package/dist/types-BfCkS7kQ.d.ts +203 -0
- package/dist/vite-mYZ2Y69u.js +144 -0
- package/dist/vite-mYZ2Y69u.js.map +1 -0
- package/dist/vite.d.ts +2 -27
- package/dist/vite.js +2 -2
- package/package.json +28 -2
- package/dist/bun-DCGnDEPn.js.map +0 -1
- package/dist/captured-headers-ewL_t3MQ.js +0 -48
- package/dist/captured-headers-ewL_t3MQ.js.map +0 -1
- package/dist/deno-BnMfk2n1.js.map +0 -1
- package/dist/dev-DCytOhpM.js +0 -132
- package/dist/dev-DCytOhpM.js.map +0 -1
- package/dist/entry-2XXp2Ukh.js.map +0 -1
- package/dist/entry-CIpwaayZ.d.ts +0 -293
- package/dist/listen-options-DHWmSWGi.js.map +0 -1
- package/dist/node-2wWBMFeO.js +0 -3
- package/dist/node-79my3Uix.js.map +0 -1
- package/dist/start-kxw_NM4q.js +0 -16
- package/dist/start-kxw_NM4q.js.map +0 -1
- package/dist/vite-CrNqpoeK.js +0 -102
- package/dist/vite-CrNqpoeK.js.map +0 -1
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { Context, MiddlewareHandler } from "hono";
|
|
2
|
+
/** A log level the server writes. */
|
|
3
|
+
type LogLevel = "debug" | "info" | "warn" | "error";
|
|
4
|
+
/**
|
|
5
|
+
* Where the server writes log lines. Pass the app's own formatter, or use
|
|
6
|
+
* {@link jsonSink}. Attribute names are flat and dotted, such as `http.method`.
|
|
7
|
+
*/
|
|
8
|
+
type LogSink = {
|
|
9
|
+
log: (level: LogLevel, message: string, attributes: Readonly<Record<string, unknown>>) => void;
|
|
10
|
+
};
|
|
11
|
+
/** The logger for one request. Each line carries the request ID, method, and path. */
|
|
12
|
+
type RequestLogger = Record<LogLevel, (message: string, attributes?: Readonly<Record<string, unknown>>) => void>;
|
|
13
|
+
/** What {@link requestContext} gives for the request that runs. */
|
|
14
|
+
type RequestContext = {
|
|
15
|
+
/** The request ID, when the `requestId` plugin runs. */
|
|
16
|
+
requestId: string | undefined;
|
|
17
|
+
/** The request's logger. Its lines carry the request ID. */
|
|
18
|
+
logger: RequestLogger;
|
|
19
|
+
};
|
|
20
|
+
/** The server mode. */
|
|
21
|
+
type Mode = "production" | "development";
|
|
22
|
+
/**
|
|
23
|
+
* The run side of a framework adapter: the framework that answers each
|
|
24
|
+
* request that no plugin or route answers.
|
|
25
|
+
*/
|
|
26
|
+
type FrameworkRuntime = {
|
|
27
|
+
/** A name for logs and errors. */
|
|
28
|
+
name: string;
|
|
29
|
+
/** Renders one request. */
|
|
30
|
+
fetch: (request: Request, context: Context<AppServerEnv>) => Promise<Response>;
|
|
31
|
+
/**
|
|
32
|
+
* The client build, when the framework knows it. The entry that the Vite
|
|
33
|
+
* plugin generates gives it instead.
|
|
34
|
+
*/
|
|
35
|
+
clientDirectory?: string;
|
|
36
|
+
/**
|
|
37
|
+
* The URL paths that the build prerendered, when the framework knows them.
|
|
38
|
+
* Else the server reads the paths that the Vite plugin captured.
|
|
39
|
+
*/
|
|
40
|
+
prerenderedPaths?: readonly string[];
|
|
41
|
+
/** Whether a URL path is a data request, such as a React Router `.data` file. */
|
|
42
|
+
isDataRequest?: (path: string) => boolean;
|
|
43
|
+
/** Content types that `mime` does not know, by file extension, such as `{ ".data": "text/x-script" }`. */
|
|
44
|
+
contentTypes?: Readonly<Record<string, string>>;
|
|
45
|
+
};
|
|
46
|
+
/** Makes the run side of a framework adapter from the framework's server module. */
|
|
47
|
+
type FrameworkRuntimeFactory = (serverModule: unknown, info: {
|
|
48
|
+
mode: Mode;
|
|
49
|
+
}) => FrameworkRuntime;
|
|
50
|
+
/** What a host knows about a file under the client build. */
|
|
51
|
+
type FileInfo = {
|
|
52
|
+
kind: "file" | "directory";
|
|
53
|
+
/** The size in bytes. */
|
|
54
|
+
size: number;
|
|
55
|
+
mtimeMs: number;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* The files of the client build. Each path is a URL path that the static
|
|
59
|
+
* stages checked: it starts with `/`, and it has no `..`, no `//`, and no
|
|
60
|
+
* `\`.
|
|
61
|
+
*/
|
|
62
|
+
type StaticFiles = {
|
|
63
|
+
/** What is at `path`, or `undefined` when nothing is there. */
|
|
64
|
+
stat: (path: string) => Promise<FileInfo | undefined>;
|
|
65
|
+
/** The bytes of the file at `path`. */
|
|
66
|
+
open: (path: string) => Promise<ReadableStream<Uint8Array>>;
|
|
67
|
+
};
|
|
68
|
+
/** Request-scoped storage, such as `AsyncLocalStorage`. */
|
|
69
|
+
type RequestStore = {
|
|
70
|
+
/** Runs `work` with `value` as the stored value. */
|
|
71
|
+
run: <Result>(value: Context<AppServerEnv>, work: () => Result) => Result;
|
|
72
|
+
/** The stored value of the request that runs, else `undefined`. */
|
|
73
|
+
get: () => Context<AppServerEnv> | undefined;
|
|
74
|
+
};
|
|
75
|
+
/** How a long-lived host stops. A serverless host has none. */
|
|
76
|
+
type Lifecycle = {
|
|
77
|
+
/**
|
|
78
|
+
* Calls `stop` once when the host must stop, such as on `SIGTERM`. The host
|
|
79
|
+
* exits when `stop` settles.
|
|
80
|
+
*/
|
|
81
|
+
onStop: (stop: () => Promise<void>) => void;
|
|
82
|
+
};
|
|
83
|
+
/** The run side of a host adapter: where the server runs. */
|
|
84
|
+
type HostRuntime = {
|
|
85
|
+
/** A name for logs and errors. */
|
|
86
|
+
name: string;
|
|
87
|
+
/** The files of the client build at `clientDirectory`, a file path or a `file:` URL. */
|
|
88
|
+
files: (clientDirectory: string) => StaticFiles;
|
|
89
|
+
/** The listeners when the app sets none. */
|
|
90
|
+
listeners: () => readonly Listener[];
|
|
91
|
+
/** The storage for {@link requestContext}. Without it, `requestContext()` gives `undefined`. */
|
|
92
|
+
storage?: RequestStore;
|
|
93
|
+
/**
|
|
94
|
+
* Gzips a byte stream and flushes after each chunk. Without it,
|
|
95
|
+
* `streamingCompress` sends each response as it is.
|
|
96
|
+
*/
|
|
97
|
+
gzip?: (source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>;
|
|
98
|
+
lifecycle?: Lifecycle;
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* What a listener passes to the app with each request. A host can add its own
|
|
102
|
+
* values, such as Node's request and response.
|
|
103
|
+
*/
|
|
104
|
+
type ListenerBindings = {
|
|
105
|
+
/** The client's IP address, when the runtime knows it. */
|
|
106
|
+
remoteAddress?: string | undefined;
|
|
107
|
+
[binding: string]: unknown;
|
|
108
|
+
};
|
|
109
|
+
/** The Hono bindings of an app server: the listener's values and the framework. */
|
|
110
|
+
type ServerBindings = ListenerBindings & {
|
|
111
|
+
framework: FrameworkRuntime;
|
|
112
|
+
};
|
|
113
|
+
/** The Hono environment of an app server. */
|
|
114
|
+
type AppServerEnv = {
|
|
115
|
+
Bindings: ServerBindings;
|
|
116
|
+
Variables: {
|
|
117
|
+
/** The request ID, set by the `requestId` plugin. */
|
|
118
|
+
requestId?: string;
|
|
119
|
+
logger: RequestLogger;
|
|
120
|
+
/**
|
|
121
|
+
* The `etagPart` of each plugin that the request passed, in order. The
|
|
122
|
+
* static stages add them to each file's ETag. The server sets this list.
|
|
123
|
+
*/
|
|
124
|
+
etagParts?: readonly string[];
|
|
125
|
+
};
|
|
126
|
+
};
|
|
127
|
+
/** The request handler that a listener calls. */
|
|
128
|
+
type FetchHandler = (request: Request, bindings: ListenerBindings) => Response | Promise<Response>;
|
|
129
|
+
/** What a plugin learns at startup, before the first request. */
|
|
130
|
+
type SetupInfo = {
|
|
131
|
+
/** The files of the client build. */
|
|
132
|
+
files: StaticFiles;
|
|
133
|
+
/** The URL paths that the build prerendered. */
|
|
134
|
+
prerenderedPaths: readonly string[];
|
|
135
|
+
/** The headers of each prerendered file, by URL path, that the Vite plugin captured. */
|
|
136
|
+
capturedHeaders: ReadonlyMap<string, Readonly<Record<string, string>>>;
|
|
137
|
+
/** Whether a URL path is a data request of the framework. */
|
|
138
|
+
isDataRequest: (path: string) => boolean;
|
|
139
|
+
/** Content types of the framework's files that `mime` does not know, by file extension. */
|
|
140
|
+
contentTypes: Readonly<Record<string, string>>;
|
|
141
|
+
/** The host's gzip stream, when it has one. */
|
|
142
|
+
gzip: ((source: ReadableStream<Uint8Array>) => ReadableStream<Uint8Array>) | undefined;
|
|
143
|
+
logger: LogSink;
|
|
144
|
+
} & ({
|
|
145
|
+
mode: "production";
|
|
146
|
+
} | {
|
|
147
|
+
mode: "development";
|
|
148
|
+
/** The dev server as a pipeline stage. It serves source modules, HMR, and CSS. */
|
|
149
|
+
devServer: MiddlewareHandler<AppServerEnv>;
|
|
150
|
+
});
|
|
151
|
+
/**
|
|
152
|
+
* One step of the request pipeline. Plugins run in list order, so the order is
|
|
153
|
+
* the contract.
|
|
154
|
+
*
|
|
155
|
+
* @example
|
|
156
|
+
* const livez: Plugin = {
|
|
157
|
+
* name: "livez",
|
|
158
|
+
* middleware: async (c, next) => (c.req.path === "/livez" ? c.text("ok") : next()),
|
|
159
|
+
* };
|
|
160
|
+
*/
|
|
161
|
+
type Plugin = {
|
|
162
|
+
/** A name for logs and errors. */
|
|
163
|
+
name: string;
|
|
164
|
+
/** The Hono middleware for this step. */
|
|
165
|
+
middleware?: MiddlewareHandler<AppServerEnv>;
|
|
166
|
+
/** Runs once before the server takes requests. A thrown error stops startup. */
|
|
167
|
+
setup?: (info: SetupInfo) => void | Promise<void>;
|
|
168
|
+
/** Runs at shutdown while the listeners drain. The server stops waiting for it at the drain deadline. */
|
|
169
|
+
onShutdown?: () => Promise<void>;
|
|
170
|
+
/**
|
|
171
|
+
* A value that this plugin's changes to a response depend on, such as the
|
|
172
|
+
* env values it writes into each document. The server adds it to the ETag
|
|
173
|
+
* of each static file that the request reaches after this plugin, so a 304
|
|
174
|
+
* never keeps a response made with an old value. Return `undefined` when
|
|
175
|
+
* the plugin changes nothing.
|
|
176
|
+
*/
|
|
177
|
+
etagPart?: () => string | undefined;
|
|
178
|
+
};
|
|
179
|
+
/** A running listener. */
|
|
180
|
+
type StartedListener = {
|
|
181
|
+
/** The URL the listener answers on. */
|
|
182
|
+
url: string;
|
|
183
|
+
/**
|
|
184
|
+
* Stops new connections and waits for open requests. At the deadline, it
|
|
185
|
+
* closes the connections that are still open.
|
|
186
|
+
*/
|
|
187
|
+
stop: (options: {
|
|
188
|
+
deadlineMs: number;
|
|
189
|
+
}) => Promise<void>;
|
|
190
|
+
};
|
|
191
|
+
/**
|
|
192
|
+
* How the server receives connections, separate from the request pipeline.
|
|
193
|
+
*
|
|
194
|
+
* @example
|
|
195
|
+
* createServer({ listeners: [tcp({ port: 8080 })] });
|
|
196
|
+
*/
|
|
197
|
+
type Listener = {
|
|
198
|
+
/** A name for logs. */
|
|
199
|
+
name: string;
|
|
200
|
+
start: (fetch: FetchHandler) => Promise<StartedListener>;
|
|
201
|
+
};
|
|
202
|
+
export { ServerBindings as _, FrameworkRuntimeFactory as a, StaticFiles as b, Listener as c, LogSink as d, Mode as f, RequestStore as g, RequestLogger as h, FrameworkRuntime as i, ListenerBindings as l, RequestContext as m, FetchHandler as n, HostRuntime as o, Plugin as p, FileInfo as r, Lifecycle as s, AppServerEnv as t, LogLevel as u, SetupInfo as v, StartedListener as y };
|
|
203
|
+
//# sourceMappingURL=types-BfCkS7kQ.d.ts.map
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { n as manifestKey, t as BUILD_MANIFEST_FILE } from "./build-manifest-8NfD1wnO.js";
|
|
2
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
3
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
4
|
+
|
|
5
|
+
// src/vite/index.ts
|
|
6
|
+
/** The module ID of the server entry that {@link appServer} generates. */
|
|
7
|
+
const SERVER_ENTRY_ID = "virtual:@ngrok/app-server/entry";
|
|
8
|
+
const RESOLVED_SERVER_ENTRY_ID = `\0${SERVER_ENTRY_ID}`;
|
|
9
|
+
/** The Vite environment that builds the server. */
|
|
10
|
+
const SERVER_ENVIRONMENT = "ssr";
|
|
11
|
+
/** The header that turns on Node's header store for a response, so `finish` can read every header. */
|
|
12
|
+
const CAPTURE_MARKER = "x-app-server-capture";
|
|
13
|
+
/**
|
|
14
|
+
* Headers that describe one transfer, not the resource. The server sets its
|
|
15
|
+
* own, and a cookie must never replay to every visitor. `Vary` is left out
|
|
16
|
+
* because the preview server adds `Vary: Origin` to every response.
|
|
17
|
+
*/
|
|
18
|
+
const UNCAPTURED_HEADERS = /* @__PURE__ */ new Set([
|
|
19
|
+
CAPTURE_MARKER,
|
|
20
|
+
"connection",
|
|
21
|
+
"content-encoding",
|
|
22
|
+
"content-length",
|
|
23
|
+
"date",
|
|
24
|
+
"etag",
|
|
25
|
+
"keep-alive",
|
|
26
|
+
"last-modified",
|
|
27
|
+
"set-cookie",
|
|
28
|
+
"transfer-encoding",
|
|
29
|
+
"vary"
|
|
30
|
+
]);
|
|
31
|
+
/** The source of the server entry. */
|
|
32
|
+
function serverEntrySource({ framework, host, appModule, clientDirectory }) {
|
|
33
|
+
return [
|
|
34
|
+
`import * as serverModule from ${JSON.stringify(framework.serverModule)};`,
|
|
35
|
+
`import { createEntry, createServer } from "@ngrok/app-server";`,
|
|
36
|
+
`import { runtime } from ${JSON.stringify(framework.runtimeModule)};`,
|
|
37
|
+
`import { host } from ${JSON.stringify(host.runtimeModule)};`,
|
|
38
|
+
...appModule == null ? [`const app = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === "1" });`] : [`import app from ${JSON.stringify(appModule)};`],
|
|
39
|
+
`export const appServer = createEntry({`,
|
|
40
|
+
`\tapp,`,
|
|
41
|
+
`\thost,`,
|
|
42
|
+
`\tclientDirectory: ${clientDirectory},`,
|
|
43
|
+
`\tframework: (mode) => runtime(serverModule, { ${framework.runtimeOptions == null ? "" : `...${framework.runtimeOptions}, `}mode }),`,
|
|
44
|
+
`});`
|
|
45
|
+
].join("\n");
|
|
46
|
+
}
|
|
47
|
+
/** The absolute path of an environment's build output. */
|
|
48
|
+
function outDir(config, environment) {
|
|
49
|
+
return resolve(config.root, config.environments[environment]?.build.outDir ?? config.build.outDir);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Records each 2xx path and the headers of each non-document response while
|
|
53
|
+
* the framework's prerender pass runs. It writes them to `.app-server.json` in
|
|
54
|
+
* the client build when the preview server closes.
|
|
55
|
+
*/
|
|
56
|
+
function capture(server) {
|
|
57
|
+
const clientDirectory = outDir(server.config, "client");
|
|
58
|
+
const paths = /* @__PURE__ */ new Set();
|
|
59
|
+
const headers = {};
|
|
60
|
+
server.middlewares.use((request, response, next) => {
|
|
61
|
+
const { pathname } = new URL(request.url ?? "/", "http://localhost");
|
|
62
|
+
response.setHeader(CAPTURE_MARKER, "1");
|
|
63
|
+
response.once("finish", () => {
|
|
64
|
+
if (response.statusCode < 200 || response.statusCode >= 300) return;
|
|
65
|
+
const key = manifestKey(pathname);
|
|
66
|
+
paths.add(key);
|
|
67
|
+
if (String(response.getHeader("content-type") ?? "").startsWith("text/html")) return;
|
|
68
|
+
const recorded = {};
|
|
69
|
+
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);
|
|
70
|
+
headers[key] = recorded;
|
|
71
|
+
});
|
|
72
|
+
next();
|
|
73
|
+
});
|
|
74
|
+
server.httpServer.once("close", () => {
|
|
75
|
+
const manifest = {
|
|
76
|
+
prerendered: [...paths].toSorted(),
|
|
77
|
+
headers: Object.fromEntries(Object.entries(headers).toSorted(([first], [second]) => first.localeCompare(second)))
|
|
78
|
+
};
|
|
79
|
+
mkdirSync(clientDirectory, { recursive: true });
|
|
80
|
+
writeFileSync(join(clientDirectory, BUILD_MANIFEST_FILE), `${JSON.stringify(manifest, null, " ")}\n`);
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The Vite plugin for `@ngrok/app-server`. Put it next to the framework's
|
|
85
|
+
* plugin.
|
|
86
|
+
*
|
|
87
|
+
* - It adds the server entry to the server build, such as
|
|
88
|
+
* `build/server/app-server.js` on the node host. The entry bundles the app
|
|
89
|
+
* (the default export of `app`) with the framework's server module, so the
|
|
90
|
+
* server gets the app's path aliases and its one copy of the framework.
|
|
91
|
+
* The framework's own entry does not change.
|
|
92
|
+
* - During the framework's prerender pass, it records each prerendered path
|
|
93
|
+
* and the headers of each prerendered file that is not an HTML document into
|
|
94
|
+
* `.app-server.json` in the client build. The `prerendered` plugin replays
|
|
95
|
+
* the headers. A document's headers depend on its request, so they are not
|
|
96
|
+
* recorded.
|
|
97
|
+
*
|
|
98
|
+
* @example
|
|
99
|
+
* // vite.config.ts
|
|
100
|
+
* export default defineConfig({
|
|
101
|
+
* plugins: [
|
|
102
|
+
* reactRouter(),
|
|
103
|
+
* appServer({ framework: reactRouterAdapter(), host: node(), app: "./server.ts" }),
|
|
104
|
+
* ],
|
|
105
|
+
* });
|
|
106
|
+
*/
|
|
107
|
+
function appServer({ framework, host, app }) {
|
|
108
|
+
let config;
|
|
109
|
+
return {
|
|
110
|
+
name: "@ngrok/app-server",
|
|
111
|
+
configResolved: (resolved) => {
|
|
112
|
+
config = resolved;
|
|
113
|
+
framework.validate?.(resolved);
|
|
114
|
+
},
|
|
115
|
+
buildStart() {
|
|
116
|
+
if (this.environment.name === SERVER_ENVIRONMENT && this.environment.mode === "build") this.emitFile({
|
|
117
|
+
type: "chunk",
|
|
118
|
+
id: SERVER_ENTRY_ID,
|
|
119
|
+
fileName: host.entryFileName
|
|
120
|
+
});
|
|
121
|
+
},
|
|
122
|
+
renderStart(options) {
|
|
123
|
+
if (this.environment.name === SERVER_ENVIRONMENT && options.format !== "es") throw new Error(`@ngrok/app-server needs an ES module server build, and this build has the format "${options.format}".`);
|
|
124
|
+
},
|
|
125
|
+
resolveId: (id) => id === "virtual:@ngrok/app-server/entry" ? RESOLVED_SERVER_ENTRY_ID : void 0,
|
|
126
|
+
load(id) {
|
|
127
|
+
if (id !== RESOLVED_SERVER_ENTRY_ID || config == null) return null;
|
|
128
|
+
const clientDirectory = outDir(config, "client");
|
|
129
|
+
const fromEntry = relative(dirname(join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName)), clientDirectory).replaceAll("\\", "/");
|
|
130
|
+
return serverEntrySource({
|
|
131
|
+
framework,
|
|
132
|
+
host,
|
|
133
|
+
appModule: app == null ? void 0 : resolve(config.root, app),
|
|
134
|
+
clientDirectory: this.environment.mode === "build" ? `new URL(${JSON.stringify(`${fromEntry}/`)}, import.meta.url).href` : JSON.stringify(clientDirectory)
|
|
135
|
+
});
|
|
136
|
+
},
|
|
137
|
+
configurePreviewServer: (server) => {
|
|
138
|
+
if (framework.isPrerenderPass(server)) capture(server);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export { appServer as n, serverEntrySource as r, SERVER_ENTRY_ID as t };
|
|
144
|
+
//# sourceMappingURL=vite-mYZ2Y69u.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite-mYZ2Y69u.js","names":[],"sources":["../src/vite/index.ts"],"sourcesContent":["import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, relative, resolve } from \"node:path\";\nimport type { Plugin, PreviewServer, ResolvedConfig } from \"vite\";\nimport { BUILD_MANIFEST_FILE, manifestKey } from \"../core/build-manifest.js\";\nimport type { BuildManifest } from \"../core/build-manifest.js\";\n\n/** The module ID of the server entry that {@link appServer} generates. */\nexport const SERVER_ENTRY_ID = \"virtual:@ngrok/app-server/entry\";\nconst RESOLVED_SERVER_ENTRY_ID = `\\0${SERVER_ENTRY_ID}`;\n\n/** The Vite environment that builds the server. */\nconst SERVER_ENVIRONMENT = \"ssr\";\n\n/** The header that turns on Node's header store for a response, so `finish` can read every header. */\nconst CAPTURE_MARKER = \"x-app-server-capture\";\n\n/**\n * Headers that describe one transfer, not the resource. The server sets its\n * own, and a cookie must never replay to every visitor. `Vary` is left out\n * because the preview server adds `Vary: Origin` to every response.\n */\nconst UNCAPTURED_HEADERS = new Set([\n\tCAPTURE_MARKER,\n\t\"connection\",\n\t\"content-encoding\",\n\t\"content-length\",\n\t\"date\",\n\t\"etag\",\n\t\"keep-alive\",\n\t\"last-modified\",\n\t\"set-cookie\",\n\t\"transfer-encoding\",\n\t\"vary\",\n]);\n\n/**\n * The build side of a framework adapter. The Vite config imports it, such as\n * `reactRouterAdapter()` from `@ngrok/app-server/react-router/vite`.\n */\nexport type FrameworkBuild = {\n\t/** A name for logs and errors. */\n\tname: string;\n\t/** The Vite ID of the framework's server module, such as `virtual:react-router/server-build`. */\n\tserverModule: string;\n\t/**\n\t * The module whose `runtime` export makes the run side from the server\n\t * module. It has the type `FrameworkRuntimeFactory`.\n\t */\n\truntimeModule: string;\n\t/**\n\t * The source of an object literal with more options for `runtime`, such as\n\t * a build constant of the framework. The bundler replaces the constants in\n\t * it, because the source is part of the server entry.\n\t */\n\truntimeOptions?: string;\n\t/** Whether a preview server runs the framework's prerender pass. */\n\tisPrerenderPass: (server: PreviewServer) => boolean;\n\t/** Throws for a config that the adapter does not support, so the build fails, not the first request. */\n\tvalidate?: (config: ResolvedConfig) => void;\n};\n\n/**\n * The build side of a host adapter. The Vite config imports it, such as\n * `node()` from `@ngrok/app-server/node/vite`.\n */\nexport type HostBuild = {\n\t/** A name for logs and errors. */\n\tname: string;\n\t/** The module whose `host` export is the run side, a `HostRuntime`. */\n\truntimeModule: string;\n\t/** The file name of the server entry in the server build, such as `app-server.js`. */\n\tentryFileName: string;\n};\n\n/** Options for {@link appServer}. */\nexport type AppServerOptions = {\n\tframework: FrameworkBuild;\n\thost: HostBuild;\n\t/**\n\t * The module whose default export is the app from `createServer`, relative\n\t * to the Vite root. When omitted, the server uses its default plugins.\n\t */\n\tapp?: string;\n};\n\n/** What {@link serverEntrySource} needs. */\ntype EntrySource = {\n\tframework: Pick<FrameworkBuild, \"serverModule\" | \"runtimeModule\" | \"runtimeOptions\">;\n\thost: Pick<HostBuild, \"runtimeModule\">;\n\t/** The absolute path of the app module, else `undefined` for the default app. */\n\tappModule: string | undefined;\n\t/** The source of an expression that gives the client build: a path or a `file:` URL. */\n\tclientDirectory: string;\n};\n\n/** The source of the server entry. */\nexport function serverEntrySource({\n\tframework,\n\thost,\n\tappModule,\n\tclientDirectory,\n}: EntrySource): string {\n\treturn [\n\t\t`import * as serverModule from ${JSON.stringify(framework.serverModule)};`,\n\t\t// Why from the bundle: the CLI calls this export, so the server runs on the bundle's copy of\n\t\t// this package and of the framework, the same copies as the app and the routes.\n\t\t`import { createEntry, createServer } from \"@ngrok/app-server\";`,\n\t\t`import { runtime } from ${JSON.stringify(framework.runtimeModule)};`,\n\t\t`import { host } from ${JSON.stringify(host.runtimeModule)};`,\n\t\t...(appModule == null\n\t\t\t? [\n\t\t\t\t\t`const app = createServer({ trustForwardedProto: process.env.TRUST_FORWARDED_PROTO === \"1\" });`,\n\t\t\t\t]\n\t\t\t: [`import app from ${JSON.stringify(appModule)};`]),\n\t\t`export const appServer = createEntry({`,\n\t\t`\\tapp,`,\n\t\t`\\thost,`,\n\t\t`\\tclientDirectory: ${clientDirectory},`,\n\t\t`\\tframework: (mode) => runtime(serverModule, { ${framework.runtimeOptions == null ? \"\" : `...${framework.runtimeOptions}, `}mode }),`,\n\t\t`});`,\n\t].join(\"\\n\");\n}\n\n/** The absolute path of an environment's build output. */\nfunction outDir(config: ResolvedConfig, environment: string): string {\n\treturn resolve(\n\t\tconfig.root,\n\t\tconfig.environments[environment]?.build.outDir ?? config.build.outDir,\n\t);\n}\n\n/**\n * Records each 2xx path and the headers of each non-document response while\n * the framework's prerender pass runs. It writes them to `.app-server.json` in\n * the client build when the preview server closes.\n */\nfunction capture(server: PreviewServer): void {\n\tconst clientDirectory = outDir(server.config, \"client\");\n\tconst paths = new Set<string>();\n\tconst headers: BuildManifest[\"headers\"] = {};\n\tserver.middlewares.use((request, response, next) => {\n\t\tconst { pathname } = new URL(request.url ?? \"/\", \"http://localhost\");\n\t\t// Why: Node keeps the headers that `writeHead` gets readable only when a header was set first.\n\t\tresponse.setHeader(CAPTURE_MARKER, \"1\");\n\t\tresponse.once(\"finish\", () => {\n\t\t\tif (response.statusCode < 200 || response.statusCode >= 300) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst key = manifestKey(pathname);\n\t\t\tpaths.add(key);\n\t\t\t// Why skip documents: the framework sets their headers for each request (a nonce, the\n\t\t\t// host), so the headers of the build's request are wrong for every other one.\n\t\t\tif (String(response.getHeader(\"content-type\") ?? \"\").startsWith(\"text/html\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst recorded: Record<string, string> = {};\n\t\t\tfor (const [name, value] of Object.entries(response.getHeaders())) {\n\t\t\t\t// Why skip index names: after a `setHeader`, Node stores a flat header array from\n\t\t\t\t// `writeHead`, as TanStack Start's preview server sends, under its indexes too.\n\t\t\t\tif (!UNCAPTURED_HEADERS.has(name) && !/^\\d+$/u.test(name) && value != null) {\n\t\t\t\t\trecorded[name] = Array.isArray(value) ? value.join(\", \") : String(value);\n\t\t\t\t}\n\t\t\t}\n\t\t\theaders[key] = recorded;\n\t\t});\n\t\tnext();\n\t});\n\tserver.httpServer.once(\"close\", () => {\n\t\tconst manifest: BuildManifest = {\n\t\t\tprerendered: [...paths].toSorted(),\n\t\t\theaders: Object.fromEntries(\n\t\t\t\tObject.entries(headers).toSorted(([first], [second]) => first.localeCompare(second)),\n\t\t\t),\n\t\t};\n\t\tmkdirSync(clientDirectory, { recursive: true });\n\t\twriteFileSync(\n\t\t\tjoin(clientDirectory, BUILD_MANIFEST_FILE),\n\t\t\t`${JSON.stringify(manifest, null, \"\\t\")}\\n`,\n\t\t);\n\t});\n}\n\n/**\n * The Vite plugin for `@ngrok/app-server`. Put it next to the framework's\n * plugin.\n *\n * - It adds the server entry to the server build, such as\n * `build/server/app-server.js` on the node host. The entry bundles the app\n * (the default export of `app`) with the framework's server module, so the\n * server gets the app's path aliases and its one copy of the framework.\n * The framework's own entry does not change.\n * - During the framework's prerender pass, it records each prerendered path\n * and the headers of each prerendered file that is not an HTML document into\n * `.app-server.json` in the client build. The `prerendered` plugin replays\n * the headers. A document's headers depend on its request, so they are not\n * recorded.\n *\n * @example\n * // vite.config.ts\n * export default defineConfig({\n * \tplugins: [\n * \t\treactRouter(),\n * \t\tappServer({ framework: reactRouterAdapter(), host: node(), app: \"./server.ts\" }),\n * \t],\n * });\n */\nexport function appServer({ framework, host, app }: AppServerOptions): Plugin {\n\tlet config: ResolvedConfig | undefined;\n\treturn {\n\t\tname: \"@ngrok/app-server\",\n\t\tconfigResolved: (resolved) => {\n\t\t\tconfig = resolved;\n\t\t\tframework.validate?.(resolved);\n\t\t},\n\t\tbuildStart() {\n\t\t\t// Why a chunk and not an input: the framework's own entry stays the same, and its prerender\n\t\t\t// preview reads that entry.\n\t\t\tif (this.environment.name === SERVER_ENVIRONMENT && this.environment.mode === \"build\") {\n\t\t\t\tthis.emitFile({ type: \"chunk\", id: SERVER_ENTRY_ID, fileName: host.entryFileName });\n\t\t\t}\n\t\t},\n\t\trenderStart(options) {\n\t\t\t// Why: the server entry uses `import.meta.url`, and the CLI loads it as an ES module.\n\t\t\tif (this.environment.name === SERVER_ENVIRONMENT && options.format !== \"es\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`@ngrok/app-server needs an ES module server build, and this build has the format \"${options.format}\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t\tresolveId: (id) => (id === SERVER_ENTRY_ID ? RESOLVED_SERVER_ENTRY_ID : undefined),\n\t\tload(id) {\n\t\t\tif (id !== RESOLVED_SERVER_ENTRY_ID || config == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tconst clientDirectory = outDir(config, \"client\");\n\t\t\t// Why a URL in a build: the build can move, and the client build stays next to it.\n\t\t\tconst fromEntry = relative(\n\t\t\t\tdirname(join(outDir(config, SERVER_ENVIRONMENT), host.entryFileName)),\n\t\t\t\tclientDirectory,\n\t\t\t).replaceAll(\"\\\\\", \"/\");\n\t\t\treturn serverEntrySource({\n\t\t\t\tframework,\n\t\t\t\thost,\n\t\t\t\tappModule: app == null ? undefined : resolve(config.root, app),\n\t\t\t\tclientDirectory:\n\t\t\t\t\tthis.environment.mode === \"build\"\n\t\t\t\t\t\t? `new URL(${JSON.stringify(`${fromEntry}/`)}, import.meta.url).href`\n\t\t\t\t\t\t: JSON.stringify(clientDirectory),\n\t\t\t});\n\t\t},\n\t\tconfigurePreviewServer: (server) => {\n\t\t\tif (framework.isPrerenderPass(server)) {\n\t\t\t\tcapture(server);\n\t\t\t}\n\t\t},\n\t};\n}\n"],"mappings":";;;;;;AAOA,MAAa,kBAAkB;AAC/B,MAAM,2BAA2B,KAAK;;AAGtC,MAAM,qBAAqB;;AAG3B,MAAM,iBAAiB;;;;;;AAOvB,MAAM,qCAAqB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACD,CAAC;;AA+DD,SAAgB,kBAAkB,EACjC,WACA,MACA,WACA,mBACuB;CACvB,OAAO;EACN,iCAAiC,KAAK,UAAU,UAAU,YAAY,EAAE;EAGxE;EACA,2BAA2B,KAAK,UAAU,UAAU,aAAa,EAAE;EACnE,wBAAwB,KAAK,UAAU,KAAK,aAAa,EAAE;EAC3D,GAAI,aAAa,OACd,CACA,+FACD,IACC,CAAC,mBAAmB,KAAK,UAAU,SAAS,EAAE,EAAE;EACnD;EACA;EACA;EACA,sBAAsB,gBAAgB;EACtC,kDAAkD,UAAU,kBAAkB,OAAO,KAAK,MAAM,UAAU,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ual:@ngrok/app-server/entry";
|
|
4
|
-
/** The source of the server build entry. */
|
|
5
|
-
export declare function serverEntrySource(appModule: string | undefined): string;
|
|
6
|
-
/**
|
|
7
|
-
* The Vite plugin for `@ngrok/app-server`. Put it next to `reactRouter()`.
|
|
8
|
-
*
|
|
9
|
-
* - It makes `build/server/index.js` export the app's server (the default
|
|
10
|
-
* export of `appModule`) next to the React Router build, so the server is
|
|
11
|
-
* bundled with the app, its path aliases, and its one copy of `react-router`.
|
|
12
|
-
* The file stays a valid server build.
|
|
13
|
-
* - During React Router's prerender pass, it records the headers of each
|
|
14
|
-
* prerendered file that is not an HTML document (resource routes and `.data`
|
|
15
|
-
* files) into `build/client/.headers.json`. The `prerendered` plugin replays
|
|
16
|
-
* them. A document's headers depend on its request, so they are not recorded.
|
|
17
|
-
*
|
|
18
|
-
* It does not support React Router `serverBundles`.
|
|
19
|
-
*
|
|
20
|
-
* @param appModule - The module whose default export is the app from `createServer`, relative to the Vite root. When omitted, the server uses its default plugins.
|
|
21
|
-
*
|
|
22
|
-
* @example
|
|
23
|
-
* // vite.config.ts
|
|
24
|
-
* export default defineConfig({ plugins: [reactRouter(), serverEntry("./server.ts")] });
|
|
25
|
-
*/
|
|
26
|
-
export declare function serverEntry(appModule?: string): Plugin;
|
|
27
|
-
//# sourceMappingURL=vite.d.ts.map
|
|
1
|
+
import { a as appServer, i as SERVER_ENTRY_ID, n as FrameworkBuild, o as serverEntrySource, r as HostBuild, t as AppServerOptions } from "./index-oSE-tYRW.js";
|
|
2
|
+
export { AppServerOptions, FrameworkBuild, HostBuild, SERVER_ENTRY_ID, appServer, serverEntrySource };
|
package/dist/vite.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { n as
|
|
1
|
+
import { n as appServer, r as serverEntrySource, t as SERVER_ENTRY_ID } from "./vite-mYZ2Y69u.js";
|
|
2
2
|
|
|
3
|
-
export { SERVER_ENTRY_ID,
|
|
3
|
+
export { SERVER_ENTRY_ID, appServer, serverEntrySource };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ngrok/app-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "A composable Hono app server for React Router: prerendered pages, streamed compression, structured logs, and clean shutdown on Node, Bun, and Deno.",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "A composable Hono app server for React Router and TanStack Start: prerendered pages, streamed compression, structured logs, and clean shutdown on Node, Bun, and Deno.",
|
|
5
5
|
"homepage": "https://github.com/ngrok/app-server#readme",
|
|
6
6
|
"bugs": {
|
|
7
7
|
"url": "https://github.com/ngrok/app-server/issues"
|
|
@@ -25,10 +25,30 @@
|
|
|
25
25
|
"types": "./dist/index.d.ts",
|
|
26
26
|
"import": "./dist/index.js"
|
|
27
27
|
},
|
|
28
|
+
"./node": {
|
|
29
|
+
"types": "./dist/node.d.ts",
|
|
30
|
+
"import": "./dist/node.js"
|
|
31
|
+
},
|
|
32
|
+
"./node/vite": {
|
|
33
|
+
"types": "./dist/node-vite.d.ts",
|
|
34
|
+
"import": "./dist/node-vite.js"
|
|
35
|
+
},
|
|
28
36
|
"./react-router": {
|
|
29
37
|
"types": "./dist/react-router.d.ts",
|
|
30
38
|
"import": "./dist/react-router.js"
|
|
31
39
|
},
|
|
40
|
+
"./react-router/vite": {
|
|
41
|
+
"types": "./dist/react-router-vite.d.ts",
|
|
42
|
+
"import": "./dist/react-router-vite.js"
|
|
43
|
+
},
|
|
44
|
+
"./tanstack-start": {
|
|
45
|
+
"types": "./dist/tanstack-start.d.ts",
|
|
46
|
+
"import": "./dist/tanstack-start.js"
|
|
47
|
+
},
|
|
48
|
+
"./tanstack-start/vite": {
|
|
49
|
+
"types": "./dist/tanstack-start-vite.d.ts",
|
|
50
|
+
"import": "./dist/tanstack-start-vite.js"
|
|
51
|
+
},
|
|
32
52
|
"./vite": {
|
|
33
53
|
"types": "./dist/vite.d.ts",
|
|
34
54
|
"import": "./dist/vite.js"
|
|
@@ -42,10 +62,16 @@
|
|
|
42
62
|
"devDependencies": {
|
|
43
63
|
"@changesets/changelog-github": "1.0.1",
|
|
44
64
|
"@changesets/cli": "3.0.3",
|
|
65
|
+
"@react-router/dev": "8.5.1",
|
|
66
|
+
"@tanstack/react-router": "1.170.46",
|
|
67
|
+
"@tanstack/react-start": "1.169.4",
|
|
45
68
|
"@types/node": "24.19.2",
|
|
69
|
+
"@vitejs/plugin-react": "6.1.2",
|
|
46
70
|
"oxfmt": "0.75.0",
|
|
47
71
|
"oxlint": "1.90.0",
|
|
48
72
|
"oxlint-tsgolint": "7.0.2005",
|
|
73
|
+
"react": "19.3.1",
|
|
74
|
+
"react-dom": "19.3.1",
|
|
49
75
|
"react-router": "8.5.1",
|
|
50
76
|
"tsdown": "0.23.3",
|
|
51
77
|
"typescript": "7.0.2",
|
package/dist/bun-DCGnDEPn.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"bun-DCGnDEPn.js","names":[],"sources":["../src/runtimes/bun.ts"],"sourcesContent":["import type { FetchHandler, StartedListener } from \"../types.js\";\nimport { listenerUrl, 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: (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\tconst deadline = setTimeout(() => {\n\t\t\t\tvoid server.stop(true);\n\t\t\t}, deadlineMs);\n\t\t\tawait server.stop();\n\t\t\tclearTimeout(deadline);\n\t\t},\n\t};\n}\n"],"mappings":";;;;AAqBA,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,QAAQ,SAAS,cAChB,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,MAAM,WAAW,iBAAiB;IACjC,AAAK,OAAO,KAAK,IAAI;GACtB,GAAG,UAAU;GACb,MAAM,OAAO,KAAK;GAClB,aAAa,QAAQ;EACtB;CACD;AACD"}
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { readFile } from "node:fs/promises";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
|
|
4
|
-
// src/captured-headers.ts
|
|
5
|
-
/**
|
|
6
|
-
* The file under the client build that holds the headers each prerendered
|
|
7
|
-
* response had at build time. It is a dotfile, so the static stages never
|
|
8
|
-
* serve it.
|
|
9
|
-
*/
|
|
10
|
-
const CAPTURED_HEADERS_FILE = ".headers.json";
|
|
11
|
-
/**
|
|
12
|
-
* The key for a URL path in {@link CapturedHeaders}: the path with no
|
|
13
|
-
* trailing slash, so `/a/` and `/a` share headers. The root stays `/`.
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* capturedHeadersKey("/components/button/"); // => "/components/button"
|
|
17
|
-
*/
|
|
18
|
-
function capturedHeadersKey(pathname) {
|
|
19
|
-
const trimmed = pathname.replace(/\/+$/, "");
|
|
20
|
-
return trimmed === "" ? "/" : trimmed;
|
|
21
|
-
}
|
|
22
|
-
function isStringRecord(value) {
|
|
23
|
-
return typeof value === "object" && value != null && !Array.isArray(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Reads the captured headers of a client build. A build with no file has
|
|
27
|
-
* none. A file in any other shape throws, so a bad build stops startup.
|
|
28
|
-
*/
|
|
29
|
-
async function readCapturedHeaders(clientDirectory) {
|
|
30
|
-
let text;
|
|
31
|
-
try {
|
|
32
|
-
text = await readFile(join(clientDirectory, CAPTURED_HEADERS_FILE), "utf8");
|
|
33
|
-
} catch (error) {
|
|
34
|
-
if (error instanceof Error && "code" in error && error.code === "ENOENT") return /* @__PURE__ */ new Map();
|
|
35
|
-
throw error;
|
|
36
|
-
}
|
|
37
|
-
const parsed = JSON.parse(text);
|
|
38
|
-
if (typeof parsed !== "object" || parsed == null || Array.isArray(parsed)) throw new Error(`${CAPTURED_HEADERS_FILE} must hold an object of header objects.`);
|
|
39
|
-
const captured = /* @__PURE__ */ new Map();
|
|
40
|
-
for (const [path, headers] of Object.entries(parsed)) {
|
|
41
|
-
if (!isStringRecord(headers)) throw new Error(`${CAPTURED_HEADERS_FILE}: the headers for ${path} must be strings.`);
|
|
42
|
-
captured.set(path, headers);
|
|
43
|
-
}
|
|
44
|
-
return captured;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export { capturedHeadersKey as n, readCapturedHeaders as r, CAPTURED_HEADERS_FILE as t };
|
|
48
|
-
//# sourceMappingURL=captured-headers-ewL_t3MQ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"captured-headers-ewL_t3MQ.js","names":[],"sources":["../src/captured-headers.ts"],"sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/**\n * The file under the client build that holds the headers each prerendered\n * response had at build time. It is a dotfile, so the static stages never\n * serve it.\n */\nexport const CAPTURED_HEADERS_FILE = \".headers.json\";\n\n/** The headers of each prerendered URL path. */\nexport type CapturedHeaders = Record<string, Record<string, string>>;\n\n/**\n * The key for a URL path in {@link CapturedHeaders}: the path with no\n * trailing slash, so `/a/` and `/a` share headers. The root stays `/`.\n *\n * @example\n * capturedHeadersKey(\"/components/button/\"); // => \"/components/button\"\n */\nexport function capturedHeadersKey(pathname: string): string {\n\tconst trimmed = pathname.replace(/\\/+$/, \"\");\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\n/**\n * Reads the captured headers of a client build. A build with no file has\n * none. A file in any other shape throws, so a bad build stops startup.\n */\nexport async function readCapturedHeaders(\n\tclientDirectory: string,\n): Promise<ReadonlyMap<string, Record<string, string>>> {\n\tlet text: string;\n\ttry {\n\t\ttext = await readFile(join(clientDirectory, CAPTURED_HEADERS_FILE), \"utf8\");\n\t} catch (error) {\n\t\tif (error instanceof Error && \"code\" in error && error.code === \"ENOENT\") {\n\t\t\treturn new Map();\n\t\t}\n\t\tthrow error;\n\t}\n\tconst parsed: unknown = JSON.parse(text);\n\tif (typeof parsed !== \"object\" || parsed == null || Array.isArray(parsed)) {\n\t\tthrow new Error(`${CAPTURED_HEADERS_FILE} must hold an object of header objects.`);\n\t}\n\tconst captured = new Map<string, Record<string, string>>();\n\tfor (const [path, headers] of Object.entries(parsed)) {\n\t\tif (!isStringRecord(headers)) {\n\t\t\tthrow new Error(`${CAPTURED_HEADERS_FILE}: the headers for ${path} must be strings.`);\n\t\t}\n\t\tcaptured.set(path, headers);\n\t}\n\treturn captured;\n}\n"],"mappings":";;;;;;;;;AAQA,MAAa,wBAAwB;;;;;;;;AAYrC,SAAgB,mBAAmB,UAA0B;CAC5D,MAAM,UAAU,SAAS,QAAQ,QAAQ,EAAE;CAC3C,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;;;;;AAMA,eAAsB,oBACrB,iBACuD;CACvD,IAAI;CACJ,IAAI;EACH,OAAO,MAAM,SAAS,KAAK,iBAAiB,qBAAqB,GAAG,MAAM;CAC3E,SAAS,OAAO;EACf,IAAI,iBAAiB,SAAS,UAAU,SAAS,MAAM,SAAS,UAC/D,uBAAO,IAAI,IAAI;EAEhB,MAAM;CACP;CACA,MAAM,SAAkB,KAAK,MAAM,IAAI;CACvC,IAAI,OAAO,WAAW,YAAY,UAAU,QAAQ,MAAM,QAAQ,MAAM,GACvE,MAAM,IAAI,MAAM,GAAG,sBAAsB,wCAAwC;CAElF,MAAM,2BAAW,IAAI,IAAoC;CACzD,KAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,MAAM,GAAG;EACrD,IAAI,CAAC,eAAe,OAAO,GAC1B,MAAM,IAAI,MAAM,GAAG,sBAAsB,oBAAoB,KAAK,kBAAkB;EAErF,SAAS,IAAI,MAAM,OAAO;CAC3B;CACA,OAAO;AACR"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"deno-BnMfk2n1.js","names":[],"sources":["../src/runtimes/deno.ts"],"sourcesContent":["import type { FetchHandler, StartedListener } from \"../types.js\";\nimport { listenerUrl, type ListenOptions } from \"./listen-options.js\";\n\n/** The part of Deno's server that the listener uses. */\ntype DenoServer = {\n\taddr: { port: number };\n\tshutdown: () => Promise<void>;\n};\n\n/** The part of the `Deno` global that the listener uses. */\ntype DenoGlobal = {\n\tserve: (\n\t\toptions: { port: number; hostname?: string; onListen: () => void },\n\t\thandler: (\n\t\t\trequest: Request,\n\t\t\tinfo: { remoteAddr: { hostname: string } },\n\t\t) => Response | Promise<Response>,\n\t) => DenoServer;\n};\n\n/** Wraps a response body so the listener can end it at the deadline. `open` holds its closer while the body is open. */\nfunction closableResponse(response: Response, open: Set<() => void>): Response {\n\tif (response.body == null) {\n\t\treturn response;\n\t}\n\tconst reader = response.body.getReader();\n\tlet force: () => void;\n\tconst body = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tforce = () => {\n\t\t\t\topen.delete(force);\n\t\t\t\tcontroller.error(new Error(\"The shutdown deadline passed.\"));\n\t\t\t\tvoid reader.cancel();\n\t\t\t};\n\t\t\topen.add(force);\n\t\t},\n\t\tasync pull(controller) {\n\t\t\ttry {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) {\n\t\t\t\t\topen.delete(force);\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} else {\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\topen.delete(force);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\t\tcancel(reason) {\n\t\t\topen.delete(force);\n\t\t\treturn reader.cancel(reason);\n\t\t},\n\t});\n\treturn new Response(body, response);\n}\n\n/** Listens with `Deno.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 -- `Deno` is a runtime global with no types in this package.\n\tconst deno = Reflect.get(globalThis, \"Deno\") as DenoGlobal;\n\t// Why: Deno has no forced close, and `shutdown()` waits for each open request. At the\n\t// deadline, the listener answers each pending request with a 503 and ends each open body.\n\tconst open = new Set<() => void>();\n\tconst server = deno.serve(\n\t\t{\n\t\t\tport: options.port,\n\t\t\t...(options.hostname == null ? {} : { hostname: options.hostname }),\n\t\t\t// Why a no-op: the server logs its own startup line.\n\t\t\tonListen: () => {},\n\t\t},\n\t\tasync (request, info) => {\n\t\t\tconst forced = Promise.withResolvers<Response>();\n\t\t\tconst force = () => {\n\t\t\t\topen.delete(force);\n\t\t\t\tforced.resolve(new Response(null, { status: 503 }));\n\t\t\t};\n\t\t\topen.add(force);\n\t\t\tconst answer = (async () => {\n\t\t\t\ttry {\n\t\t\t\t\treturn closableResponse(\n\t\t\t\t\t\tawait fetch(request, { remoteAddress: info.remoteAddr.hostname }),\n\t\t\t\t\t\topen,\n\t\t\t\t\t);\n\t\t\t\t} finally {\n\t\t\t\t\topen.delete(force);\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn Promise.race([answer, forced.promise]);\n\t\t},\n\t);\n\treturn {\n\t\turl: listenerUrl(options.hostname, server.addr.port),\n\t\tstop: async ({ deadlineMs }) => {\n\t\t\tconst deadline = setTimeout(() => {\n\t\t\t\tfor (const force of open) {\n\t\t\t\t\tforce();\n\t\t\t\t}\n\t\t\t}, deadlineMs);\n\t\t\tawait server.shutdown();\n\t\t\tclearTimeout(deadline);\n\t\t},\n\t};\n}\n"],"mappings":";;;;AAqBA,SAAS,iBAAiB,UAAoB,MAAiC;CAC9E,IAAI,SAAS,QAAQ,MACpB,OAAO;CAER,MAAM,SAAS,SAAS,KAAK,UAAU;CACvC,IAAI;CACJ,MAAM,OAAO,IAAI,eAA2B;EAC3C,MAAM,YAAY;GACjB,cAAc;IACb,KAAK,OAA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