@ngrok/app-server 0.1.1 → 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 +75 -20
- 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 +6 -6
- 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-ChjmFwX5.js → entry-BkdUub2S.js} +179 -296
- 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 -15
- 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-BVMb8Pyt.js → start-CINALHxy.js} +92 -72
- 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-Dau_IONd.js → tcp-C-9AmFuM.js} +5 -5
- 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/entry-CIpwaayZ.d.ts +0 -293
- package/dist/entry-ChjmFwX5.js.map +0 -1
- 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/serve-ByeedcRB.js +0 -16
- package/dist/serve-ByeedcRB.js.map +0 -1
- package/dist/start-BVMb8Pyt.js.map +0 -1
- package/dist/tcp-Dau_IONd.js.map +0 -1
- package/dist/vite-CrNqpoeK.js +0 -102
- package/dist/vite-CrNqpoeK.js.map +0 -1
|
@@ -1,73 +1,11 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import { n as
|
|
1
|
+
import { n as jsonSink, r as requestLogger, t as errorAttributes } from "./log-CsjaKM8U.js";
|
|
2
|
+
import { n as manifestKey, r as readBuildManifest } from "./build-manifest-8NfD1wnO.js";
|
|
3
3
|
import { Hono } from "hono";
|
|
4
4
|
import { requestId } from "hono/request-id";
|
|
5
|
-
import { RESPONSE_ALREADY_SENT } from "@hono/node-server/utils/response";
|
|
6
|
-
import { open, stat } from "node:fs/promises";
|
|
7
|
-
import { join, sep } from "node:path";
|
|
8
|
-
import { createHash } from "node:crypto";
|
|
9
5
|
import { getMimeType } from "hono/utils/mime";
|
|
10
6
|
import { accepts } from "hono/accepts";
|
|
11
|
-
import { constants, createGzip } from "node:zlib";
|
|
12
7
|
|
|
13
|
-
// src/log.ts
|
|
14
|
-
/**
|
|
15
|
-
* A log sink that writes one JSON object per line. Each line has `time`,
|
|
16
|
-
* `level`, `message`, and the flat attributes, which Datadog reads as its
|
|
17
|
-
* standard attributes.
|
|
18
|
-
*
|
|
19
|
-
* @param write - Where each line goes. Defaults to stdout.
|
|
20
|
-
*
|
|
21
|
-
* @example
|
|
22
|
-
* createServer({ logger: jsonSink() });
|
|
23
|
-
* // {"time":"2026-10-28T12:00:00.000Z","level":"info","message":"request","http.status_code":200}
|
|
24
|
-
*/
|
|
25
|
-
function jsonSink(write = (line) => {
|
|
26
|
-
process.stdout.write(line);
|
|
27
|
-
}) {
|
|
28
|
-
return { log: (level, message, attributes) => {
|
|
29
|
-
write(`${JSON.stringify({
|
|
30
|
-
time: (/* @__PURE__ */ new Date()).toISOString(),
|
|
31
|
-
level,
|
|
32
|
-
message,
|
|
33
|
-
...attributes
|
|
34
|
-
})}\n`);
|
|
35
|
-
} };
|
|
36
|
-
}
|
|
37
|
-
/** Flat `error.*` attributes for a thrown value. */
|
|
38
|
-
function errorAttributes(error) {
|
|
39
|
-
if (error instanceof Error) return {
|
|
40
|
-
"error.kind": error.name,
|
|
41
|
-
"error.message": error.message,
|
|
42
|
-
"error.stack": error.stack
|
|
43
|
-
};
|
|
44
|
-
return { "error.message": String(error) };
|
|
45
|
-
}
|
|
46
|
-
/** A logger that writes to `sink`, with the attributes from `base` first on each line. */
|
|
47
|
-
function sinkLogger(sink, base = () => ({})) {
|
|
48
|
-
const line = (level) => (message, attributes = {}) => {
|
|
49
|
-
sink.log(level, message, {
|
|
50
|
-
...base(),
|
|
51
|
-
...attributes
|
|
52
|
-
});
|
|
53
|
-
};
|
|
54
|
-
return {
|
|
55
|
-
debug: line("debug"),
|
|
56
|
-
info: line("info"),
|
|
57
|
-
warn: line("warn"),
|
|
58
|
-
error: line("error")
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
/** A logger whose lines carry the request's ID, method, and path. */
|
|
62
|
-
function requestLogger(sink, context) {
|
|
63
|
-
return sinkLogger(sink, () => ({
|
|
64
|
-
"http.request_id": context.get("requestId"),
|
|
65
|
-
"http.method": context.req.method,
|
|
66
|
-
"http.url_details.path": context.req.path
|
|
67
|
-
}));
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
// src/plugins/access-log.ts
|
|
8
|
+
// src/core/plugins/access-log.ts
|
|
71
9
|
/**
|
|
72
10
|
* A URL's path and query, with each query value replaced when `redact` is set.
|
|
73
11
|
*
|
|
@@ -76,7 +14,7 @@ function requestLogger(sink, context) {
|
|
|
76
14
|
*/
|
|
77
15
|
function loggedUrl(url, { redact }) {
|
|
78
16
|
if (!redact || url.search === "") return `${url.pathname}${url.search}`;
|
|
79
|
-
const query =
|
|
17
|
+
const query = [...url.searchParams.keys()].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&");
|
|
80
18
|
return `${url.pathname}?${query}`;
|
|
81
19
|
}
|
|
82
20
|
/** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */
|
|
@@ -173,7 +111,7 @@ function accessLog({ redactQuery = true } = {}) {
|
|
|
173
111
|
}
|
|
174
112
|
}
|
|
175
113
|
|
|
176
|
-
// src/plugins/request-id.ts
|
|
114
|
+
// src/core/plugins/request-id.ts
|
|
177
115
|
/**
|
|
178
116
|
* Gives each request an ID: a valid incoming header (up to 255 word
|
|
179
117
|
* characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
|
|
@@ -196,7 +134,9 @@ function requestId$1({ headerName = "X-Request-Id" } = {}) {
|
|
|
196
134
|
};
|
|
197
135
|
}
|
|
198
136
|
|
|
199
|
-
// src/static-files.ts
|
|
137
|
+
// src/core/static-files.ts
|
|
138
|
+
/** The content types that `mime` lacks and that no framework owns. */
|
|
139
|
+
const CORE_CONTENT_TYPES = { ".md": "text/markdown; charset=utf-8" };
|
|
200
140
|
/**
|
|
201
141
|
* Whether a URL path names a dotfile or goes through a dot directory.
|
|
202
142
|
* `/.well-known/` stays reachable.
|
|
@@ -204,18 +144,11 @@ function requestId$1({ headerName = "X-Request-Id" } = {}) {
|
|
|
204
144
|
function hasDotSegment(path) {
|
|
205
145
|
return path.split("/").some((segment, index) => segment.startsWith(".") && !(index === 1 && segment === ".well-known"));
|
|
206
146
|
}
|
|
207
|
-
async function fileStats(path) {
|
|
208
|
-
try {
|
|
209
|
-
return await stat(path);
|
|
210
|
-
} catch {
|
|
211
|
-
return;
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
147
|
/**
|
|
215
|
-
* Finds the file
|
|
216
|
-
*
|
|
217
|
-
* redirect, so a prerendered page keeps its URL. Dotfiles and paths
|
|
218
|
-
*
|
|
148
|
+
* Finds the file in `files` that answers a decoded URL path, such as Hono's
|
|
149
|
+
* `context.req.path`. A directory answers with its `index.html` and no
|
|
150
|
+
* redirect, so a prerendered page keeps its URL. Dotfiles and paths that
|
|
151
|
+
* leave the client build find nothing.
|
|
219
152
|
*
|
|
220
153
|
* Each file has one URL, because the headers for a file are keyed by that
|
|
221
154
|
* URL. So `/a//b`, `/a/index.html`, and `/a%2Fb` find nothing. Hono decodes
|
|
@@ -223,59 +156,35 @@ async function fileStats(path) {
|
|
|
223
156
|
* decode it again.
|
|
224
157
|
*
|
|
225
158
|
* @example
|
|
226
|
-
* await findStaticFile(
|
|
227
|
-
* // => { path: "/
|
|
159
|
+
* await findStaticFile(files, "/components/button");
|
|
160
|
+
* // => { path: "/components/button/index.html", size: 5120, mtimeMs: 1761652800000 }
|
|
228
161
|
*/
|
|
229
|
-
async function findStaticFile(
|
|
230
|
-
if (path.includes("\0") || path.includes("\\") || path.split("/").includes("..") || path.includes("//") || path.endsWith("/index.html") || hasDotSegment(path)) return;
|
|
231
|
-
const
|
|
232
|
-
if (
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
size: stats.size,
|
|
237
|
-
mtimeMs: stats.mtimeMs
|
|
162
|
+
async function findStaticFile(files, path) {
|
|
163
|
+
if (!path.startsWith("/") || path.includes("\0") || path.includes("\\") || path.split("/").includes("..") || path.includes("//") || path.endsWith("/index.html") || hasDotSegment(path)) return;
|
|
164
|
+
const info = await files.stat(path);
|
|
165
|
+
if (info?.kind === "file") return {
|
|
166
|
+
path,
|
|
167
|
+
size: info.size,
|
|
168
|
+
mtimeMs: info.mtimeMs
|
|
238
169
|
};
|
|
239
|
-
if (
|
|
240
|
-
const index =
|
|
241
|
-
const
|
|
242
|
-
if (
|
|
170
|
+
if (info?.kind === "directory") {
|
|
171
|
+
const index = `${path.replace(/\/$/u, "")}/index.html`;
|
|
172
|
+
const indexInfo = await files.stat(index);
|
|
173
|
+
if (indexInfo?.kind === "file") return {
|
|
243
174
|
path: index,
|
|
244
|
-
size:
|
|
245
|
-
mtimeMs:
|
|
175
|
+
size: indexInfo.size,
|
|
176
|
+
mtimeMs: indexInfo.mtimeMs
|
|
246
177
|
};
|
|
247
178
|
}
|
|
248
179
|
}
|
|
249
|
-
/**
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
function fileStream(handle) {
|
|
254
|
-
return new ReadableStream({
|
|
255
|
-
async pull(controller) {
|
|
256
|
-
try {
|
|
257
|
-
const { bytesRead, buffer } = await handle.read({ buffer: /* @__PURE__ */ new Uint8Array(65536) });
|
|
258
|
-
if (bytesRead === 0) {
|
|
259
|
-
await handle.close();
|
|
260
|
-
controller.close();
|
|
261
|
-
} else controller.enqueue(buffer.subarray(0, bytesRead));
|
|
262
|
-
} catch (error) {
|
|
263
|
-
await handle.close();
|
|
264
|
-
throw error;
|
|
265
|
-
}
|
|
266
|
-
},
|
|
267
|
-
cancel: () => handle.close()
|
|
268
|
-
});
|
|
269
|
-
}
|
|
270
|
-
/** The content type of a file, with the React Router and markdown types that `mime` lacks. */
|
|
271
|
-
function contentType(path) {
|
|
272
|
-
if (path.endsWith(".md")) return "text/markdown; charset=utf-8";
|
|
273
|
-
if (path.endsWith(".data")) return "text/x-script";
|
|
274
|
-
return getMimeType(path) ?? "application/octet-stream";
|
|
180
|
+
/** The content type of a file, by its extension. `contentTypes` win over `mime`. */
|
|
181
|
+
function contentType(path, contentTypes) {
|
|
182
|
+
const extension = /\.[^./]+$/u.exec(path)?.[0] ?? "";
|
|
183
|
+
return contentTypes[extension] ?? CORE_CONTENT_TYPES[extension] ?? getMimeType(path) ?? "application/octet-stream";
|
|
275
184
|
}
|
|
276
185
|
/** An ETag without its weak prefix, for the weak comparison that `If-None-Match` uses. */
|
|
277
186
|
function opaqueTag(etag) {
|
|
278
|
-
return etag.trim().replace(/^W
|
|
187
|
+
return etag.trim().replace(/^W\//u, "");
|
|
279
188
|
}
|
|
280
189
|
/** Whether an `If-None-Match` header lists an ETag. */
|
|
281
190
|
function matchesEtag(ifNoneMatch, etag) {
|
|
@@ -285,22 +194,21 @@ function matchesEtag(ifNoneMatch, etag) {
|
|
|
285
194
|
}) ?? false;
|
|
286
195
|
}
|
|
287
196
|
/** A weak ETag from a file's size, its modification time, and the request's `etagParts`. */
|
|
288
|
-
function fileEtag(file, parts) {
|
|
197
|
+
async function fileEtag(file, parts) {
|
|
289
198
|
const base = `${file.size.toString(16)}-${Math.trunc(file.mtimeMs).toString(16)}`;
|
|
290
199
|
if (parts.length === 0) return `W/"${base}"`;
|
|
291
|
-
|
|
200
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\0")));
|
|
201
|
+
return `W/"${base}-${btoa(String.fromCodePoint(...new Uint8Array(digest))).replaceAll("+", "-").replaceAll("/", "_").slice(0, 16)}"`;
|
|
292
202
|
}
|
|
293
203
|
/**
|
|
294
204
|
* The response for a static file, with a weak ETag from its size,
|
|
295
205
|
* modification time, and the request's `etagParts`. A matching
|
|
296
|
-
* `If-None-Match` gets a 304, and `HEAD` gets the headers only.
|
|
297
|
-
* replace the defaults, so a captured `Content-Type` wins over the one from
|
|
298
|
-
* the file name.
|
|
206
|
+
* `If-None-Match` gets a 304, and `HEAD` gets the headers only.
|
|
299
207
|
*/
|
|
300
|
-
async function staticResponse(context, file, headers) {
|
|
301
|
-
const etag = fileEtag(file, context.get("etagParts") ?? []);
|
|
208
|
+
async function staticResponse(context, { files, file, headers, contentTypes }) {
|
|
209
|
+
const etag = await fileEtag(file, context.get("etagParts") ?? []);
|
|
302
210
|
const responseHeaders = new Headers({
|
|
303
|
-
"Content-Type": contentType(file.path),
|
|
211
|
+
"Content-Type": contentType(file.path, contentTypes),
|
|
304
212
|
ETag: etag
|
|
305
213
|
});
|
|
306
214
|
for (const [name, value] of Object.entries(headers)) responseHeaders.set(name, value);
|
|
@@ -311,48 +219,18 @@ async function staticResponse(context, file, headers) {
|
|
|
311
219
|
headers: responseHeaders
|
|
312
220
|
});
|
|
313
221
|
}
|
|
314
|
-
if (context.req.method === "HEAD") {
|
|
315
|
-
responseHeaders.set("Content-Length", String(file.size));
|
|
316
|
-
return new Response(null, { headers: responseHeaders });
|
|
317
|
-
}
|
|
318
222
|
responseHeaders.set("Content-Length", String(file.size));
|
|
319
|
-
return new Response(
|
|
223
|
+
if (context.req.method === "HEAD") return new Response(null, { headers: responseHeaders });
|
|
224
|
+
return new Response(await files.open(file.path), { headers: responseHeaders });
|
|
320
225
|
}
|
|
321
226
|
|
|
322
|
-
// src/plugins/static.ts
|
|
227
|
+
// src/core/plugins/static.ts
|
|
323
228
|
const IMMUTABLE = "public, max-age=31536000, immutable";
|
|
324
|
-
/** Runs Vite's middleware inside the pipeline. Vite answers or calls `next`. */
|
|
325
|
-
function viteStage(viteMiddleware) {
|
|
326
|
-
return async (context, next) => {
|
|
327
|
-
const { incoming, outgoing } = context.env;
|
|
328
|
-
if (incoming == null || outgoing == null) return next();
|
|
329
|
-
for (const [name, value] of context.res.headers) outgoing.appendHeader(name, value);
|
|
330
|
-
if (await new Promise((resolve, reject) => {
|
|
331
|
-
const onFinish = () => {
|
|
332
|
-
resolve(true);
|
|
333
|
-
};
|
|
334
|
-
outgoing.once("finish", onFinish);
|
|
335
|
-
viteMiddleware(incoming, outgoing, (error) => {
|
|
336
|
-
outgoing.off("finish", onFinish);
|
|
337
|
-
if (error == null) resolve(false);
|
|
338
|
-
else reject(new Error("Vite middleware failed", { cause: error }));
|
|
339
|
-
});
|
|
340
|
-
})) {
|
|
341
|
-
const headers = new Headers(RESPONSE_ALREADY_SENT.headers);
|
|
342
|
-
const length = outgoing.getHeader("Content-Length");
|
|
343
|
-
if (length != null) headers.set("Content-Length", String(length));
|
|
344
|
-
return new Response(null, {
|
|
345
|
-
status: outgoing.statusCode,
|
|
346
|
-
headers
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
return next();
|
|
350
|
-
};
|
|
351
|
-
}
|
|
352
229
|
/**
|
|
353
230
|
* Serves the hashed files under `/assets/` with a one-year immutable cache.
|
|
354
231
|
* A missing asset gets a plain 404, not a rendered page. In development,
|
|
355
|
-
*
|
|
232
|
+
* the dev server serves the source modules, the HMR client, and the CSS here
|
|
233
|
+
* instead.
|
|
356
234
|
*
|
|
357
235
|
* @example
|
|
358
236
|
* createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
|
|
@@ -363,25 +241,30 @@ function assets() {
|
|
|
363
241
|
name: "assets",
|
|
364
242
|
setup: (info) => {
|
|
365
243
|
if (info.mode === "development") {
|
|
366
|
-
stage =
|
|
244
|
+
stage = info.devServer;
|
|
367
245
|
return;
|
|
368
246
|
}
|
|
369
|
-
const
|
|
247
|
+
const { files, contentTypes } = info;
|
|
370
248
|
stage = async (context, next) => {
|
|
371
249
|
const { method, path } = context.req;
|
|
372
250
|
if (!path.startsWith("/assets/") || method !== "GET" && method !== "HEAD") return next();
|
|
373
|
-
const file = await findStaticFile(
|
|
251
|
+
const file = await findStaticFile(files, path);
|
|
374
252
|
if (file == null) return context.text("Not Found", 404);
|
|
375
|
-
return staticResponse(context,
|
|
253
|
+
return staticResponse(context, {
|
|
254
|
+
files,
|
|
255
|
+
file,
|
|
256
|
+
headers: { "Cache-Control": IMMUTABLE },
|
|
257
|
+
contentTypes
|
|
258
|
+
});
|
|
376
259
|
};
|
|
377
260
|
},
|
|
378
|
-
middleware: (context, next) => stage == null ? next() : stage(context, next)
|
|
261
|
+
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
379
262
|
};
|
|
380
263
|
}
|
|
381
264
|
/**
|
|
382
265
|
* Serves the client build: prerendered pages at their own URL with a 200 and
|
|
383
266
|
* no trailing-slash redirect, plus every other file in it. Each response gets
|
|
384
|
-
* the headers its loader sent at build time (the `
|
|
267
|
+
* the headers its loader sent at build time (the `appServer` Vite plugin
|
|
385
268
|
* captures them), an ETag, and a 304 for a matching `If-None-Match`. A path
|
|
386
269
|
* with no file goes on to the framework. Off in development.
|
|
387
270
|
*
|
|
@@ -398,104 +281,101 @@ function prerendered(options = {}) {
|
|
|
398
281
|
name: "prerendered",
|
|
399
282
|
setup: async (info) => {
|
|
400
283
|
if (info.mode === "development") return;
|
|
401
|
-
const
|
|
402
|
-
const captured = await readCapturedHeaders(root);
|
|
284
|
+
const { files, contentTypes, capturedHeaders } = info;
|
|
403
285
|
const missing = [];
|
|
404
|
-
for (const path of info.prerenderedPaths) if (await findStaticFile(
|
|
286
|
+
for (const path of info.prerenderedPaths) if (await findStaticFile(files, path) == null) missing.push(path);
|
|
405
287
|
if (missing.length > 0) info.logger.log("warn", "prerendered paths with no file", { "app_server.missing_paths": missing });
|
|
406
288
|
stage = async (context, next) => {
|
|
407
289
|
const { method } = context.req;
|
|
408
290
|
if (method !== "GET" && method !== "HEAD") return next();
|
|
409
291
|
const path = options.rewrite?.(context.req.path, context) ?? context.req.path;
|
|
410
|
-
const file = await findStaticFile(
|
|
292
|
+
const file = await findStaticFile(files, path);
|
|
411
293
|
if (file == null) return next();
|
|
412
|
-
return staticResponse(context,
|
|
413
|
-
|
|
414
|
-
|
|
294
|
+
return staticResponse(context, {
|
|
295
|
+
files,
|
|
296
|
+
file,
|
|
297
|
+
headers: {
|
|
298
|
+
...capturedHeaders.get(manifestKey(path)),
|
|
299
|
+
...options.headers?.(path, context)
|
|
300
|
+
},
|
|
301
|
+
contentTypes
|
|
415
302
|
});
|
|
416
303
|
};
|
|
417
304
|
},
|
|
418
|
-
middleware: (context, next) => stage == null ? next() : stage(context, next)
|
|
305
|
+
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
419
306
|
};
|
|
420
307
|
}
|
|
421
308
|
|
|
422
|
-
// src/plugins/streaming-compress.ts
|
|
423
|
-
const COMPRESSIBLE = /^(text\/|application\/(json|javascript|xml|schema\+json|manifest\+json|x-ndjson|connect\+json)|image\/svg\+xml)
|
|
424
|
-
/**
|
|
425
|
-
* Gzips a byte stream. `Z_SYNC_FLUSH` makes each written chunk readable at
|
|
426
|
-
* once. It reads the next source chunk only when the consumer pulls, so a slow
|
|
427
|
-
* client holds back the source.
|
|
428
|
-
*/
|
|
429
|
-
function gzipStream(source) {
|
|
430
|
-
const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });
|
|
431
|
-
const reader = source.getReader();
|
|
432
|
-
return new ReadableStream({
|
|
433
|
-
start(controller) {
|
|
434
|
-
gzip.on("data", (chunk) => {
|
|
435
|
-
controller.enqueue(new Uint8Array(chunk));
|
|
436
|
-
});
|
|
437
|
-
gzip.on("end", () => {
|
|
438
|
-
controller.close();
|
|
439
|
-
});
|
|
440
|
-
gzip.on("error", (error) => {
|
|
441
|
-
controller.error(error);
|
|
442
|
-
});
|
|
443
|
-
},
|
|
444
|
-
async pull() {
|
|
445
|
-
try {
|
|
446
|
-
let chunk = await reader.read();
|
|
447
|
-
while (!chunk.done && chunk.value.byteLength === 0) chunk = await reader.read();
|
|
448
|
-
if (chunk.done) {
|
|
449
|
-
gzip.end();
|
|
450
|
-
return;
|
|
451
|
-
}
|
|
452
|
-
const { value } = chunk;
|
|
453
|
-
await new Promise((resolve, reject) => {
|
|
454
|
-
gzip.write(value, (error) => {
|
|
455
|
-
if (error == null) resolve();
|
|
456
|
-
else reject(error);
|
|
457
|
-
});
|
|
458
|
-
});
|
|
459
|
-
} catch (error) {
|
|
460
|
-
gzip.destroy();
|
|
461
|
-
throw error;
|
|
462
|
-
}
|
|
463
|
-
},
|
|
464
|
-
cancel(reason) {
|
|
465
|
-
gzip.destroy();
|
|
466
|
-
return reader.cancel(reason);
|
|
467
|
-
}
|
|
468
|
-
});
|
|
469
|
-
}
|
|
309
|
+
// src/core/plugins/streaming-compress.ts
|
|
310
|
+
const COMPRESSIBLE = /^(?:text\/|application\/(?:json|javascript|xml|schema\+json|manifest\+json|x-ndjson|connect\+json)|image\/svg\+xml)/u;
|
|
470
311
|
/**
|
|
471
312
|
* Gzips text responses and flushes after each chunk, so a streamed page shell
|
|
472
313
|
* or a server-sent event reaches the client at once. `hono/compress` holds a
|
|
473
314
|
* stream until it ends. Skips a response that is already encoded, a partial
|
|
474
|
-
* response, and one marked `no-transform`.
|
|
315
|
+
* response, and one marked `no-transform`. It sets `Vary: Accept-Encoding` on
|
|
316
|
+
* each response. The host gives the gzip stream. On a host with none, the
|
|
317
|
+
* plugin does nothing.
|
|
475
318
|
*
|
|
476
319
|
* @example
|
|
477
320
|
* createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
|
|
478
321
|
*/
|
|
479
322
|
function streamingCompress() {
|
|
323
|
+
let gzip;
|
|
480
324
|
return {
|
|
481
325
|
name: "streaming-compress",
|
|
326
|
+
setup: (info) => {
|
|
327
|
+
({gzip} = info);
|
|
328
|
+
},
|
|
482
329
|
middleware: async (context, next) => {
|
|
483
330
|
await next();
|
|
331
|
+
if (gzip == null) return;
|
|
484
332
|
context.header("Vary", "Accept-Encoding", { append: true });
|
|
485
333
|
const response = context.res;
|
|
486
334
|
if (response.body == null || context.req.method === "HEAD" || accepts(context, {
|
|
487
335
|
header: "Accept-Encoding",
|
|
488
336
|
supports: ["gzip"],
|
|
489
337
|
default: "identity"
|
|
490
|
-
}) !== "gzip" || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || /\bno-transform\b
|
|
491
|
-
context.res = new Response(
|
|
338
|
+
}) !== "gzip" || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || /\bno-transform\b/u.test(response.headers.get("Cache-Control") ?? "") || !COMPRESSIBLE.test(response.headers.get("Content-Type") ?? "")) return;
|
|
339
|
+
context.res = new Response(gzip(response.body), response);
|
|
492
340
|
context.res.headers.set("Content-Encoding", "gzip");
|
|
493
341
|
context.res.headers.delete("Content-Length");
|
|
494
342
|
}
|
|
495
343
|
};
|
|
496
344
|
}
|
|
497
345
|
|
|
498
|
-
// src/
|
|
346
|
+
// src/core/request-context.ts
|
|
347
|
+
/**
|
|
348
|
+
* Each store that a request ran in. Why a set: two entries in one process can
|
|
349
|
+
* have two hosts, and each request uses the store of its own app.
|
|
350
|
+
*/
|
|
351
|
+
const stores = /* @__PURE__ */ new Set();
|
|
352
|
+
/** Runs `work` in `store` with `context` as the request that {@link requestContext} reads. */
|
|
353
|
+
async function withRequestContext(store, context, work) {
|
|
354
|
+
if (store == null) return work();
|
|
355
|
+
stores.add(store);
|
|
356
|
+
return store.run(context, work);
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* The request ID and logger of the request that runs. It gives `undefined`
|
|
360
|
+
* outside a server request, such as in a prerender pass, or on a host with no
|
|
361
|
+
* request storage.
|
|
362
|
+
*
|
|
363
|
+
* @example
|
|
364
|
+
* export async function loader() {
|
|
365
|
+
* requestContext()?.logger.info("loading the dashboard");
|
|
366
|
+
* }
|
|
367
|
+
*/
|
|
368
|
+
function requestContext() {
|
|
369
|
+
for (const store of stores) {
|
|
370
|
+
const context = store.get();
|
|
371
|
+
if (context != null) return {
|
|
372
|
+
requestId: context.get("requestId"),
|
|
373
|
+
logger: context.var.logger
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// src/core/shutdown.ts
|
|
499
379
|
let controller = new AbortController();
|
|
500
380
|
/**
|
|
501
381
|
* A signal that aborts when the server starts to shut down. Read it for each
|
|
@@ -519,7 +399,7 @@ function abortShutdownSignal() {
|
|
|
519
399
|
controller.abort();
|
|
520
400
|
}
|
|
521
401
|
|
|
522
|
-
// src/create-server.ts
|
|
402
|
+
// src/core/create-server.ts
|
|
523
403
|
const appInternals = /* @__PURE__ */ new WeakMap();
|
|
524
404
|
/**
|
|
525
405
|
* The default pipeline, in order: `requestId`, `accessLog`,
|
|
@@ -578,23 +458,24 @@ async function settlesWithin(work, ms) {
|
|
|
578
458
|
* app.get("/livez", (c) => c.text("ok"));
|
|
579
459
|
* export default app;
|
|
580
460
|
*/
|
|
581
|
-
function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listeners
|
|
461
|
+
function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listeners, trustForwardedProto = false, shutdownDeadlineMs = 1e4 } = {}) {
|
|
582
462
|
const app = new Hono();
|
|
463
|
+
let requestStore;
|
|
583
464
|
if (trustForwardedProto) {
|
|
584
465
|
const dispatch = app.fetch;
|
|
585
|
-
app.fetch = (request, ...rest) => dispatch(withForwardedProto(request), ...rest);
|
|
466
|
+
app.fetch = async (request, ...rest) => dispatch(withForwardedProto(request), ...rest);
|
|
586
467
|
}
|
|
587
468
|
app.use(async (context, next) => {
|
|
588
469
|
context.set("logger", requestLogger(logger, context));
|
|
589
|
-
await next
|
|
470
|
+
await withRequestContext(requestStore, context, next);
|
|
590
471
|
if (context.req.method === "HEAD") await context.res.body?.cancel();
|
|
591
472
|
});
|
|
592
|
-
for (const { middleware, etagPart } of plugins) app.use((context, next) => {
|
|
473
|
+
for (const { middleware, etagPart } of plugins) app.use(async (context, next) => {
|
|
593
474
|
const part = etagPart?.();
|
|
594
475
|
if (part != null) context.set("etagParts", [...context.get("etagParts") ?? [], part]);
|
|
595
476
|
return asError(async () => middleware == null ? next() : middleware(context, next));
|
|
596
477
|
});
|
|
597
|
-
app.use((_, next) => asError(next));
|
|
478
|
+
app.use(async (_, next) => asError(next));
|
|
598
479
|
app.onError((error, context) => {
|
|
599
480
|
if ("getResponse" in error && typeof error.getResponse === "function") {
|
|
600
481
|
const response = error.getResponse();
|
|
@@ -608,14 +489,17 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
|
|
|
608
489
|
let stoppingPlugins;
|
|
609
490
|
const internals = {
|
|
610
491
|
logger,
|
|
611
|
-
|
|
492
|
+
setRequestStore: (store) => {
|
|
493
|
+
requestStore = store;
|
|
494
|
+
},
|
|
495
|
+
prepare: async (info) => {
|
|
612
496
|
prepared ??= (async () => {
|
|
613
497
|
for (const plugin of plugins) await plugin.setup?.(info);
|
|
614
|
-
app.all("*", (context) => context.env.framework.fetch(context.req.raw, context));
|
|
498
|
+
app.all("*", async (context) => context.env.framework.fetch(context.req.raw, context));
|
|
615
499
|
})();
|
|
616
500
|
return prepared;
|
|
617
501
|
},
|
|
618
|
-
listen: async (framework) => {
|
|
502
|
+
listen: async (framework, defaultListeners) => {
|
|
619
503
|
if (running != null) throw new Error("This app server is already listening.");
|
|
620
504
|
renewShutdownSignal();
|
|
621
505
|
let deadlinePassed = false;
|
|
@@ -627,11 +511,11 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
|
|
|
627
511
|
if (deadlinePassed) await response.body?.cancel();
|
|
628
512
|
return response;
|
|
629
513
|
};
|
|
630
|
-
const starts = await Promise.allSettled(listeners.map((listener) => listener.start(fetch)));
|
|
514
|
+
const starts = await Promise.allSettled((listeners ?? defaultListeners).map(async (listener) => listener.start(fetch)));
|
|
631
515
|
const started = starts.flatMap((start) => start.status === "fulfilled" ? [start.value] : []);
|
|
632
516
|
const failed = starts.find((start) => start.status === "rejected");
|
|
633
517
|
if (failed != null) {
|
|
634
|
-
await Promise.all(started.map((listener) => listener.stop({ deadlineMs: 0 })));
|
|
518
|
+
await Promise.all(started.map(async (listener) => listener.stop({ deadlineMs: 0 })));
|
|
635
519
|
throw failed.reason;
|
|
636
520
|
}
|
|
637
521
|
const urls = started.map((listener) => listener.url);
|
|
@@ -639,15 +523,17 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
|
|
|
639
523
|
let stopping;
|
|
640
524
|
running = {
|
|
641
525
|
urls,
|
|
642
|
-
shutdown: () => {
|
|
526
|
+
shutdown: async () => {
|
|
643
527
|
stopping ??= (async () => {
|
|
644
528
|
logger.log("info", "draining", { "app_server.deadline_ms": shutdownDeadlineMs });
|
|
645
529
|
abortShutdownSignal();
|
|
646
530
|
const deadline = setTimeout(() => {
|
|
647
531
|
deadlinePassed = true;
|
|
648
532
|
}, shutdownDeadlineMs);
|
|
649
|
-
await Promise.
|
|
533
|
+
const results = await Promise.allSettled([internals.stopPlugins(), ...started.map(async (listener) => listener.stop({ deadlineMs: shutdownDeadlineMs }))]);
|
|
650
534
|
clearTimeout(deadline);
|
|
535
|
+
const rejected = results.find((result) => result.status === "rejected");
|
|
536
|
+
if (rejected != null) throw rejected.reason;
|
|
651
537
|
logger.log("info", "stopped", {});
|
|
652
538
|
})();
|
|
653
539
|
return stopping;
|
|
@@ -655,7 +541,7 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
|
|
|
655
541
|
};
|
|
656
542
|
return running;
|
|
657
543
|
},
|
|
658
|
-
stopPlugins: () => {
|
|
544
|
+
stopPlugins: async () => {
|
|
659
545
|
stoppingPlugins ??= (async () => {
|
|
660
546
|
if (!await settlesWithin((async () => {
|
|
661
547
|
const results = await Promise.allSettled(plugins.map(async (plugin) => plugin.onShutdown?.()));
|
|
@@ -673,48 +559,61 @@ function serverInternals(app) {
|
|
|
673
559
|
return appInternals.get(app);
|
|
674
560
|
}
|
|
675
561
|
|
|
676
|
-
// src/entry.ts
|
|
562
|
+
// src/core/entry.ts
|
|
677
563
|
/** The version of the contract between the CLI and the `appServer` export of a build. */
|
|
678
|
-
const ENTRY_PROTOCOL =
|
|
564
|
+
const ENTRY_PROTOCOL = 2;
|
|
679
565
|
/**
|
|
680
|
-
* The `appServer` export of a server build: an app from `createServer
|
|
681
|
-
* the framework adapter for each mode. The `
|
|
682
|
-
* this export for a
|
|
566
|
+
* The `appServer` export of a server build: an app from `createServer`, the
|
|
567
|
+
* host, and the framework adapter for each mode. The `appServer` Vite plugin
|
|
568
|
+
* generates this export. Call this for a build without the plugin.
|
|
683
569
|
*
|
|
684
570
|
* @example
|
|
685
|
-
* export const appServer = createEntry({ app, framework: (mode) =>
|
|
571
|
+
* export const appServer = createEntry({ app, host, framework: (mode) => runtime(build, { mode }) });
|
|
686
572
|
*/
|
|
687
|
-
function createEntry({ app, framework }) {
|
|
573
|
+
function createEntry({ app, host, framework, clientDirectory }) {
|
|
688
574
|
const internals = serverInternals(app);
|
|
689
575
|
if (internals == null) throw new Error("The app is not from `createServer()` of the copy of @ngrok/app-server in this build.");
|
|
576
|
+
internals.setRequestStore(host.storage);
|
|
577
|
+
const setupInfo = async (runtime) => {
|
|
578
|
+
const directory = clientDirectory ?? runtime.clientDirectory;
|
|
579
|
+
if (directory == null) throw new Error(`Give createEntry a clientDirectory: the ${runtime.name} adapter does not know the client build.`);
|
|
580
|
+
return {
|
|
581
|
+
files: host.files(directory),
|
|
582
|
+
isDataRequest: runtime.isDataRequest ?? (() => false),
|
|
583
|
+
contentTypes: runtime.contentTypes ?? {},
|
|
584
|
+
gzip: host.gzip,
|
|
585
|
+
logger: internals.logger
|
|
586
|
+
};
|
|
587
|
+
};
|
|
690
588
|
let development;
|
|
691
589
|
return {
|
|
692
|
-
protocol:
|
|
590
|
+
protocol: 2,
|
|
693
591
|
app,
|
|
694
592
|
start: async () => {
|
|
695
|
-
const
|
|
696
|
-
await
|
|
593
|
+
const runtime = framework("production");
|
|
594
|
+
const shared = await setupInfo(runtime);
|
|
595
|
+
const { prerendered, headers } = await readBuildManifest(shared.files);
|
|
596
|
+
const info = {
|
|
597
|
+
...shared,
|
|
697
598
|
mode: "production",
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
const server = await internals.listen(
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
});
|
|
708
|
-
});
|
|
599
|
+
prerenderedPaths: runtime.prerenderedPaths ?? prerendered,
|
|
600
|
+
capturedHeaders: new Map(Object.entries(headers))
|
|
601
|
+
};
|
|
602
|
+
await internals.prepare(info);
|
|
603
|
+
const server = await internals.listen(runtime, host.listeners());
|
|
604
|
+
host.lifecycle?.onStop(async () => server.shutdown().catch((error) => {
|
|
605
|
+
internals.logger.log("error", "shutdown failed", errorAttributes(error));
|
|
606
|
+
throw error;
|
|
607
|
+
}));
|
|
709
608
|
},
|
|
710
|
-
fetchDev: async (request, bindings,
|
|
609
|
+
fetchDev: async (request, bindings, devServer) => {
|
|
711
610
|
development ??= framework("development");
|
|
712
611
|
await internals.prepare({
|
|
612
|
+
...await setupInfo(development),
|
|
713
613
|
mode: "development",
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
logger: internals.logger
|
|
614
|
+
devServer,
|
|
615
|
+
prerenderedPaths: development.prerenderedPaths ?? [],
|
|
616
|
+
capturedHeaders: /* @__PURE__ */ new Map()
|
|
718
617
|
});
|
|
719
618
|
return app.fetch(request, {
|
|
720
619
|
...bindings,
|
|
@@ -725,31 +624,15 @@ function createEntry({ app, framework }) {
|
|
|
725
624
|
abortShutdownSignal
|
|
726
625
|
};
|
|
727
626
|
}
|
|
728
|
-
function isAppServerEntry(value) {
|
|
729
|
-
return typeof value === "object" && value != null && "protocol" in value && value.protocol === 1;
|
|
730
|
-
}
|
|
731
|
-
/** Entries that this copy made for plain React Router builds, by build module. */
|
|
732
|
-
const plainEntries = /* @__PURE__ */ new WeakMap();
|
|
733
627
|
/**
|
|
734
|
-
*
|
|
735
|
-
*
|
|
736
|
-
*
|
|
628
|
+
* Whether a value is an entry of this protocol version.
|
|
629
|
+
*
|
|
630
|
+
* @example
|
|
631
|
+
* isAppServerEntry((await import("./build/server/app-server.js")).appServer); // => true
|
|
737
632
|
*/
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
const exported = Reflect.get(build, "appServer");
|
|
741
|
-
if (exported != null) {
|
|
742
|
-
if (!isAppServerEntry(exported)) throw new Error(`The build's @ngrok/app-server does not use entry protocol ${1}. Install the same version of @ngrok/app-server that the build uses.`);
|
|
743
|
-
return exported;
|
|
744
|
-
}
|
|
745
|
-
const known = plainEntries.get(build);
|
|
746
|
-
if (known != null) return known;
|
|
747
|
-
const { appServerEntry, isServerBuild } = await import("./react-router.js");
|
|
748
|
-
if (!isServerBuild(build)) throw new Error("The server build entry is not a React Router server build.");
|
|
749
|
-
const entry = appServerEntry(build);
|
|
750
|
-
plainEntries.set(build, entry);
|
|
751
|
-
return entry;
|
|
633
|
+
function isAppServerEntry(value) {
|
|
634
|
+
return typeof value === "object" && value != null && "protocol" in value && value.protocol === 2;
|
|
752
635
|
}
|
|
753
636
|
|
|
754
|
-
export { shutdownSignal as a,
|
|
755
|
-
//# sourceMappingURL=entry-
|
|
637
|
+
export { shutdownSignal as a, assets as c, accessLog as d, defaultPlugins as i, prerendered as l, isAppServerEntry as n, requestContext as o, createServer as r, streamingCompress as s, createEntry as t, requestId$1 as u };
|
|
638
|
+
//# sourceMappingURL=entry-BkdUub2S.js.map
|