@ngrok/app-server 0.2.0 → 0.3.1
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 +652 -77
- package/dist/build-id-C6sYO9Yp.js +126 -0
- package/dist/build-id-C6sYO9Yp.js.map +1 -0
- package/dist/{build-manifest-8NfD1wnO.js → build-manifest-UDNk81Ce.js} +24 -6
- package/dist/build-manifest-UDNk81Ce.js.map +1 -0
- package/dist/cli.js +45 -25
- package/dist/cli.js.map +1 -1
- package/dist/client-browser.d.ts +12 -0
- package/dist/client-browser.js +3 -0
- package/dist/client.d.ts +21 -0
- package/dist/client.js +27 -0
- package/dist/client.js.map +1 -0
- package/dist/compression-7_gToa8R.js +97 -0
- package/dist/compression-7_gToa8R.js.map +1 -0
- package/dist/create-server-DkTeIJ8L.js +1409 -0
- package/dist/create-server-DkTeIJ8L.js.map +1 -0
- package/dist/{deno-DNRgzHrk.js → deno-aqhikNMG.js} +2 -2
- package/dist/deno-aqhikNMG.js.map +1 -0
- package/dist/entry-CM6Ma-Tv.d.ts +626 -0
- package/dist/entry-CenmvESk.js +116 -0
- package/dist/entry-CenmvESk.js.map +1 -0
- package/dist/gzip-Doi4wqjX.js +294 -0
- package/dist/gzip-Doi4wqjX.js.map +1 -0
- package/dist/header-hook-Vzw9J9BY.js +159 -0
- package/dist/header-hook-Vzw9J9BY.js.map +1 -0
- package/dist/{index-oSE-tYRW.d.ts → index-Bo5G9LuQ.d.ts} +53 -14
- package/dist/index.d.ts +99 -269
- package/dist/index.js +47 -59
- package/dist/index.js.map +1 -1
- package/dist/listen-options-7TaXjyrk.js.map +1 -1
- package/dist/{load-entry-C03qqmhr.js → load-entry-CmkdlmDX.js} +8 -4
- package/dist/{load-entry-C03qqmhr.js.map → load-entry-CmkdlmDX.js.map} +1 -1
- package/dist/log-BP6xXXZl.js +122 -0
- package/dist/log-BP6xXXZl.js.map +1 -0
- package/dist/node-BFH82eeL.js +333 -0
- package/dist/node-BFH82eeL.js.map +1 -0
- package/dist/node-tBVQPjQv.js +41 -0
- package/dist/node-tBVQPjQv.js.map +1 -0
- package/dist/node-vite.d.ts +5 -4
- package/dist/node-vite.js +2 -17
- package/dist/node.d.ts +23 -4
- package/dist/node.js +2 -2
- package/dist/react-router-vite.d.ts +4 -3
- package/dist/react-router-vite.js +2 -20
- package/dist/react-router.d.ts +1 -1
- package/dist/react-router.js +8 -7
- package/dist/react-router.js.map +1 -1
- package/dist/request-context-BtQ87VYb.js +40 -0
- package/dist/request-context-BtQ87VYb.js.map +1 -0
- package/dist/response-edge-Bc1-C_Cx.js +327 -0
- package/dist/response-edge-Bc1-C_Cx.js.map +1 -0
- package/dist/response-writer-B7FoJjEE.js +289 -0
- package/dist/response-writer-B7FoJjEE.js.map +1 -0
- package/dist/script-hashes-hqUk6kG7.js +53 -0
- package/dist/script-hashes-hqUk6kG7.js.map +1 -0
- package/dist/{serve-Cleo8RMO.js → serve-Cc-ADdhZ.js} +3 -3
- package/dist/{serve-Cleo8RMO.js.map → serve-Cc-ADdhZ.js.map} +1 -1
- package/dist/stale-build-navigation-PnMLtTF8.js +339 -0
- package/dist/stale-build-navigation-PnMLtTF8.js.map +1 -0
- package/dist/stale-build-navigation-ypV7Ow4o.d.ts +141 -0
- package/dist/{start-CINALHxy.js → start-Cb3kknlF.js} +14 -19
- package/dist/start-Cb3kknlF.js.map +1 -0
- package/dist/static-files-Beju9riB.js +302 -0
- package/dist/static-files-Beju9riB.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +6 -5
- package/dist/tanstack-start-vite.js +2 -23
- package/dist/tanstack-start.d.ts +19 -2
- package/dist/tanstack-start.js +5 -14
- package/dist/tanstack-start.js.map +1 -1
- package/dist/{tcp-C-9AmFuM.js → tcp-Dd1Mt6sN.js} +6 -5
- package/dist/{tcp-C-9AmFuM.js.map → tcp-Dd1Mt6sN.js.map} +1 -1
- package/dist/trailing-slash-DX7NB88H.d.ts +36 -0
- package/dist/types-DLYxYS6M.d.ts +392 -0
- package/dist/vercel-vite.d.ts +35 -0
- package/dist/vercel-vite.js +142 -0
- package/dist/vercel-vite.js.map +1 -0
- package/dist/vercel.d.ts +35 -0
- package/dist/vercel.js +89 -0
- package/dist/vercel.js.map +1 -0
- package/dist/vite-B-GfswoH.js +22 -0
- package/dist/vite-B-GfswoH.js.map +1 -0
- package/dist/vite-D4hfj3ph.js +19 -0
- package/dist/vite-D4hfj3ph.js.map +1 -0
- package/dist/vite-DyrhyKEr.js +25 -0
- package/dist/vite-DyrhyKEr.js.map +1 -0
- package/dist/vite-iioAoxSt.js +752 -0
- package/dist/vite-iioAoxSt.js.map +1 -0
- package/dist/vite.d.ts +2 -2
- package/dist/vite.js +1 -1
- package/package.json +25 -4
- package/dist/build-manifest-8NfD1wnO.js.map +0 -1
- package/dist/deno-DNRgzHrk.js.map +0 -1
- package/dist/entry-BkdUub2S.js +0 -638
- package/dist/entry-BkdUub2S.js.map +0 -1
- package/dist/log-CsjaKM8U.js +0 -59
- package/dist/log-CsjaKM8U.js.map +0 -1
- package/dist/node-CG7qXuWZ.js +0 -58
- package/dist/node-CG7qXuWZ.js.map +0 -1
- package/dist/node-YWPGmzAk.js +0 -215
- package/dist/node-YWPGmzAk.js.map +0 -1
- package/dist/node-ZMowKZDB.js +0 -3
- package/dist/node-vite.js.map +0 -1
- package/dist/react-router-vite.js.map +0 -1
- package/dist/start-CINALHxy.js.map +0 -1
- package/dist/tanstack-start-vite.js.map +0 -1
- package/dist/types-BfCkS7kQ.d.ts +0 -203
- package/dist/vite-mYZ2Y69u.js +0 -144
- package/dist/vite-mYZ2Y69u.js.map +0 -1
|
@@ -0,0 +1,1409 @@
|
|
|
1
|
+
import { r as withRequestContext } from "./request-context-BtQ87VYb.js";
|
|
2
|
+
import { a as replaceResponse, o as withHeaderHook, r as hookedHeaders, s as writableHeaders } from "./header-hook-Vzw9J9BY.js";
|
|
3
|
+
import { o as checkOptionPlugins, r as buildId, s as optionPlugin } from "./build-id-C6sYO9Yp.js";
|
|
4
|
+
import { i as requestLogger, r as jsonSink, t as errorAttributes } from "./log-BP6xXXZl.js";
|
|
5
|
+
import { n as finishResponse, r as onResponseSent } from "./response-edge-Bc1-C_Cx.js";
|
|
6
|
+
import { a as isCompressible, i as forbidsTransform, n as MIN_COMPRESS_BYTES, o as preferredEncoding, s as readIfQueued } from "./compression-7_gToa8R.js";
|
|
7
|
+
import { i as isFilePath$1, n as findStaticFile, o as staticResponse, s as withVary, t as contentType } from "./static-files-Beju9riB.js";
|
|
8
|
+
import { n as manifestKey } from "./build-manifest-UDNk81Ce.js";
|
|
9
|
+
import { Hono } from "hono";
|
|
10
|
+
import { HTTPException } from "hono/http-exception";
|
|
11
|
+
import { matchedRoutes } from "hono/route";
|
|
12
|
+
import { getPath } from "hono/utils/url";
|
|
13
|
+
|
|
14
|
+
// src/core/plugins/access-log.ts
|
|
15
|
+
/**
|
|
16
|
+
* A URL's path and query, with each query value replaced when `redact` is set.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* loggedUrl(new URL("https://example.com/verify?code=123"), { redact: true }); // => "/verify?code=REDACTED"
|
|
20
|
+
*/
|
|
21
|
+
function loggedUrl(url, { redact }) {
|
|
22
|
+
if (!redact || url.search === "") return `${url.pathname}${url.search}`;
|
|
23
|
+
const query = [...url.searchParams.keys()].map((key) => `${encodeURIComponent(key)}=REDACTED`).join("&");
|
|
24
|
+
return `${url.pathname}?${query}`;
|
|
25
|
+
}
|
|
26
|
+
/** A `Referer` with its query redacted like {@link loggedUrl}. A value that is not a URL is dropped. */
|
|
27
|
+
function loggedReferer(referer, { redact }) {
|
|
28
|
+
if (referer == null || !redact) return referer;
|
|
29
|
+
const url = URL.parse(referer);
|
|
30
|
+
return url == null ? void 0 : `${url.origin}${loggedUrl(url, { redact })}`;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* One log line per request, static hits included, with Datadog standard
|
|
34
|
+
* attribute names. The line goes out when the response ends or the client
|
|
35
|
+
* disconnects, so a streamed response logs its full duration and size. It
|
|
36
|
+
* logs the response that leaves the server, after each stage. A listener
|
|
37
|
+
* with an `edge`, such as the node listener, counts the bytes.
|
|
38
|
+
*
|
|
39
|
+
* @example
|
|
40
|
+
* createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
|
|
41
|
+
* // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
|
|
42
|
+
*/
|
|
43
|
+
function accessLog({ redactQuery = true, attributes, serverTiming = false } = {}) {
|
|
44
|
+
return {
|
|
45
|
+
name: "access-log",
|
|
46
|
+
middleware: async (context, next) => {
|
|
47
|
+
const started = performance.now();
|
|
48
|
+
await (serverTiming ? withHeaderHook(context, next, (headers) => {
|
|
49
|
+
if (headers.get("Content-Type")?.startsWith("text/html") ?? false) headers.append("Server-Timing", `app;dur=${(performance.now() - started).toFixed(1)}`);
|
|
50
|
+
}) : next());
|
|
51
|
+
onResponseSent(context, (sent) => {
|
|
52
|
+
const line = lineAttributes(context, sent, started);
|
|
53
|
+
try {
|
|
54
|
+
context.get("logger").info("request", attributes == null ? line : {
|
|
55
|
+
...line,
|
|
56
|
+
...attributes(context, sent)
|
|
57
|
+
});
|
|
58
|
+
} catch (error) {
|
|
59
|
+
try {
|
|
60
|
+
context.get("logger").error("access log attributes failed", {
|
|
61
|
+
...line,
|
|
62
|
+
...errorAttributes(error)
|
|
63
|
+
});
|
|
64
|
+
} catch {}
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
/** `href` as {@link loggedUrl} logs it. */
|
|
70
|
+
function requestUrl(href) {
|
|
71
|
+
const start = href.indexOf("/", href.indexOf("//") + 2);
|
|
72
|
+
if (start !== -1 && !href.includes("?", start) && !href.includes("#", start)) return href.slice(start);
|
|
73
|
+
return loggedUrl(new URL(href), { redact: redactQuery });
|
|
74
|
+
}
|
|
75
|
+
function lineAttributes(context, { status, bytes, aborted }, started) {
|
|
76
|
+
const line = {
|
|
77
|
+
"http.url": requestUrl(context.req.url),
|
|
78
|
+
"http.status_code": status,
|
|
79
|
+
"http.useragent": context.req.header("User-Agent"),
|
|
80
|
+
"http.referer": loggedReferer(context.req.header("Referer"), { redact: redactQuery }),
|
|
81
|
+
"network.client.ip": context.get("clientAddress"),
|
|
82
|
+
"network.bytes_written": bytes,
|
|
83
|
+
duration: Math.round((performance.now() - started) * 1e6)
|
|
84
|
+
};
|
|
85
|
+
if (aborted) line["http.client_aborted"] = true;
|
|
86
|
+
return line;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/core/plugins/body-limit.ts
|
|
91
|
+
const NO_BODY_METHODS = /* @__PURE__ */ new Set([
|
|
92
|
+
"GET",
|
|
93
|
+
"HEAD",
|
|
94
|
+
"CONNECT",
|
|
95
|
+
"TRACE",
|
|
96
|
+
"TRACK"
|
|
97
|
+
]);
|
|
98
|
+
/** The 413 response. */
|
|
99
|
+
function tooLarge() {
|
|
100
|
+
return new Response("Payload Too Large", { status: 413 });
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Sends a 413 for a request body that is larger than `maxBytes`. A request
|
|
104
|
+
* whose `Content-Length` is too large gets the 413 before the app reads the
|
|
105
|
+
* body, and a request whose `Content-Length` fits goes on unchanged. A
|
|
106
|
+
* streamed body with no `Content-Length` errors when it passes the limit. When the app reads the body before it answers, the response
|
|
107
|
+
* becomes a 413. When the app streams the body into its response, the
|
|
108
|
+
* response stream errors. A `maxBytes` that is not a whole number of 0 or
|
|
109
|
+
* more stops startup.
|
|
110
|
+
*
|
|
111
|
+
* Why not `hono/body-limit`: it reads a streamed body into memory before the
|
|
112
|
+
* next stage runs, so an upload cannot stream.
|
|
113
|
+
*
|
|
114
|
+
* @example
|
|
115
|
+
* createServer({ plugins: [requestId(), accessLog(), bodyLimit({ maxBytes: 1_048_576 })] });
|
|
116
|
+
*/
|
|
117
|
+
function bodyLimit({ maxBytes }) {
|
|
118
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) throw new RangeError(`bodyLimit needs a maxBytes of 0 or more whole bytes, not ${maxBytes}.`);
|
|
119
|
+
return {
|
|
120
|
+
name: "body-limit",
|
|
121
|
+
middleware: async (context, next) => {
|
|
122
|
+
const { raw } = context.req;
|
|
123
|
+
if (NO_BODY_METHODS.has(raw.method)) return next();
|
|
124
|
+
const length = context.req.header("Content-Length");
|
|
125
|
+
if (length != null && /^\d+$/u.test(length) && context.req.header("Transfer-Encoding") == null) return Number(length) > maxBytes ? tooLarge() : next();
|
|
126
|
+
let bytes = 0;
|
|
127
|
+
let exceeded = false;
|
|
128
|
+
let reader;
|
|
129
|
+
const limited = new ReadableStream({
|
|
130
|
+
async pull(controller) {
|
|
131
|
+
reader ??= raw.body?.getReader();
|
|
132
|
+
const chunk = await reader?.read();
|
|
133
|
+
if (chunk == null || chunk.done) {
|
|
134
|
+
controller.close();
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
bytes += chunk.value.byteLength;
|
|
138
|
+
if (bytes > maxBytes) {
|
|
139
|
+
exceeded = true;
|
|
140
|
+
controller.error(new HTTPException(413, { message: "The request body is larger than the body limit." }));
|
|
141
|
+
await reader?.cancel();
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
controller.enqueue(chunk.value);
|
|
145
|
+
},
|
|
146
|
+
cancel: async (reason) => (reader ?? raw.body)?.cancel(reason)
|
|
147
|
+
}, { highWaterMark: 0 });
|
|
148
|
+
const init = {
|
|
149
|
+
method: raw.method,
|
|
150
|
+
headers: raw.headers,
|
|
151
|
+
signal: raw.signal,
|
|
152
|
+
body: limited,
|
|
153
|
+
duplex: "half"
|
|
154
|
+
};
|
|
155
|
+
context.req.raw = new Request(raw.url, init);
|
|
156
|
+
await next();
|
|
157
|
+
if (exceeded) {
|
|
158
|
+
await context.res.body?.cancel();
|
|
159
|
+
replaceResponse(context, tooLarge());
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// src/core/shutdown.ts
|
|
166
|
+
let controller = new AbortController();
|
|
167
|
+
let stopping = false;
|
|
168
|
+
/**
|
|
169
|
+
* A signal that aborts when the server starts to shut down. Read it for each
|
|
170
|
+
* request: each start of a server makes a new one. A handler that
|
|
171
|
+
* holds a response open, such as an event stream, stops on it so that the
|
|
172
|
+
* drain does not wait for the deadline.
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* const timer = setInterval(sendUpdate, 1_000);
|
|
176
|
+
* shutdownSignal().addEventListener("abort", () => clearInterval(timer), { once: true });
|
|
177
|
+
*/
|
|
178
|
+
function shutdownSignal() {
|
|
179
|
+
return controller.signal;
|
|
180
|
+
}
|
|
181
|
+
/** Replaces {@link shutdownSignal} with a new one that has not aborted, and clears {@link isStopping}. */
|
|
182
|
+
function renewShutdownSignal() {
|
|
183
|
+
controller = new AbortController();
|
|
184
|
+
stopping = false;
|
|
185
|
+
}
|
|
186
|
+
/** Marks the server as stopping, before the shutdown delay and the drain. */
|
|
187
|
+
function markStopping() {
|
|
188
|
+
stopping = true;
|
|
189
|
+
}
|
|
190
|
+
/** Whether the server got a stop signal. It is true during the shutdown delay, before {@link shutdownSignal} aborts. */
|
|
191
|
+
function isStopping() {
|
|
192
|
+
return stopping;
|
|
193
|
+
}
|
|
194
|
+
/** Aborts {@link shutdownSignal}. */
|
|
195
|
+
function abortShutdownSignal() {
|
|
196
|
+
controller.abort();
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// src/core/plugins/health.ts
|
|
200
|
+
/** A probe answer that no cache keeps. */
|
|
201
|
+
function probe(text, status) {
|
|
202
|
+
return new Response(text, {
|
|
203
|
+
status,
|
|
204
|
+
headers: {
|
|
205
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
206
|
+
"Cache-Control": "no-store"
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Answers the liveness and readiness probes of a load balancer or
|
|
212
|
+
* Kubernetes. `livePath` always answers 200. `readyPath` answers 200 until
|
|
213
|
+
* the server gets a stop signal, then 503. With `shutdownDelayMs` on
|
|
214
|
+
* `createServer`, the listeners serve on for that time, so the load
|
|
215
|
+
* balancer removes the server before the drain starts.
|
|
216
|
+
*
|
|
217
|
+
* `defaultPlugins()` runs it first, so a probe skips the access log. Its
|
|
218
|
+
* `health` option takes these options, and `false` turns it off.
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* createServer({
|
|
222
|
+
* plugins: defaultPlugins({ health: { ready: async () => db.ping() } }),
|
|
223
|
+
* shutdownDelayMs: 5_000,
|
|
224
|
+
* });
|
|
225
|
+
*/
|
|
226
|
+
function health({ livePath = "/livez", readyPath = "/readyz", ready } = {}) {
|
|
227
|
+
let appFailing = false;
|
|
228
|
+
const appCheck = async (logger) => {
|
|
229
|
+
if (ready == null) return true;
|
|
230
|
+
let passed = false;
|
|
231
|
+
let failure = {};
|
|
232
|
+
try {
|
|
233
|
+
passed = await ready();
|
|
234
|
+
} catch (error) {
|
|
235
|
+
failure = errorAttributes(error);
|
|
236
|
+
}
|
|
237
|
+
if (!passed && !appFailing) logger.warn("readiness check failed", failure);
|
|
238
|
+
else if (passed && appFailing) logger.info("readiness check passed");
|
|
239
|
+
appFailing = !passed;
|
|
240
|
+
return passed;
|
|
241
|
+
};
|
|
242
|
+
const isReady = async (logger) => {
|
|
243
|
+
if (isStopping()) return false;
|
|
244
|
+
return await appCheck(logger) && !isStopping();
|
|
245
|
+
};
|
|
246
|
+
return optionPlugin("health", {
|
|
247
|
+
name: "health",
|
|
248
|
+
middleware: async (context, next) => {
|
|
249
|
+
const { method, path } = context.req;
|
|
250
|
+
if (method !== "GET" && method !== "HEAD") return next();
|
|
251
|
+
if (path === livePath) return probe("ok", 200);
|
|
252
|
+
if (path === readyPath) return await isReady(context.get("logger")) ? probe("ok", 200) : probe("not ready", 503);
|
|
253
|
+
return next();
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// src/core/plugins/noindex.ts
|
|
259
|
+
/**
|
|
260
|
+
* Sets `X-Robots-Tag: noindex, nofollow` on each response, so a search
|
|
261
|
+
* engine does not index a preview deploy. Turn it on from the environment
|
|
262
|
+
* with the `noindex` option of `defaultPlugins()`, which puts it before the
|
|
263
|
+
* static stages, so it also sees prerendered pages.
|
|
264
|
+
*
|
|
265
|
+
* @example
|
|
266
|
+
* defaultPlugins({ noindex: process.env.PREVIEW === "1" });
|
|
267
|
+
*/
|
|
268
|
+
function noindex() {
|
|
269
|
+
return optionPlugin("noindex", {
|
|
270
|
+
name: "noindex",
|
|
271
|
+
middleware: async (context, next) => withHeaderHook(context, next, (response) => {
|
|
272
|
+
response.set("X-Robots-Tag", "noindex, nofollow");
|
|
273
|
+
})
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// src/core/plugins/private-documents.ts
|
|
278
|
+
/** The data check before `setup` runs. */
|
|
279
|
+
function noDataRequests() {
|
|
280
|
+
return false;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Sets `Cache-Control: private, no-cache` on each HTML document and each
|
|
284
|
+
* framework data response, such as a React Router `.data` request, that has
|
|
285
|
+
* no `Cache-Control`. A shared cache then never keeps a page or loader data
|
|
286
|
+
* that the server rendered for one user. A response with its own
|
|
287
|
+
* `Cache-Control` keeps it. A resource route that sends per-user JSON sets
|
|
288
|
+
* its own `Cache-Control`.
|
|
289
|
+
*
|
|
290
|
+
* Put it after the static stages, so it sees only the responses of the app's
|
|
291
|
+
* routes and the framework. `defaultPlugins()` puts it last.
|
|
292
|
+
*
|
|
293
|
+
* @example
|
|
294
|
+
* createServer({ plugins: [requestId(), accessLog(), assets(), prerendered(), privateDocuments()] });
|
|
295
|
+
*/
|
|
296
|
+
function privateDocuments() {
|
|
297
|
+
let isDataRequest = noDataRequests;
|
|
298
|
+
return {
|
|
299
|
+
name: "private-documents",
|
|
300
|
+
setup: (info) => {
|
|
301
|
+
({isDataRequest} = info);
|
|
302
|
+
},
|
|
303
|
+
middleware: async (context, next) => withHeaderHook(context, next, (headers) => {
|
|
304
|
+
if (!headers.has("Cache-Control") && ((headers.get("Content-Type")?.startsWith("text/html") ?? false) || isDataRequest(context.req.path))) headers.set("Cache-Control", "private, no-cache");
|
|
305
|
+
})
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// src/core/safe-local-path.ts
|
|
310
|
+
/**
|
|
311
|
+
* Whether `value` is a safe same-origin path for a `Location` header. The
|
|
312
|
+
* value starts with one `/`, the next character is not `/` or `\`, and each
|
|
313
|
+
* character is printable ASCII (0x20 to 0x7E).
|
|
314
|
+
*
|
|
315
|
+
* The check stops these attacks:
|
|
316
|
+
*
|
|
317
|
+
* - An open redirect: `//evil.com`, `/\evil.com`, and `https://evil.com` go to
|
|
318
|
+
* another host. A browser reads `/\` as `//`.
|
|
319
|
+
* - A scheme that does not navigate, such as `javascript:` or `data:`.
|
|
320
|
+
* - A control character, such as CR or LF, that splits the response.
|
|
321
|
+
*
|
|
322
|
+
* Why strict: a short allow list is easy to audit. The check rejects some safe
|
|
323
|
+
* values, such as a path with raw UTF-8. Percent-encode the path first.
|
|
324
|
+
*
|
|
325
|
+
* Ported from the ngrok frontend `isSafeLocalPath`, with its test cases.
|
|
326
|
+
*
|
|
327
|
+
* @example
|
|
328
|
+
* isSafeLocalPath("/components/button?tab=props"); // => true
|
|
329
|
+
* isSafeLocalPath("//evil.com/foo"); // => false
|
|
330
|
+
* isSafeLocalPath("/café"); // => false
|
|
331
|
+
*/
|
|
332
|
+
function isSafeLocalPath(value) {
|
|
333
|
+
return /^\/(?![/\\])/u.test(value) && !/[^\u0020-\u007E]/u.test(value);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// src/core/plugins/trailing-slash.ts
|
|
337
|
+
/** Whether the last segment of a URL path has a dot, as a file name such as `llms.txt` or `x.data` has. */
|
|
338
|
+
function isFilePath(path) {
|
|
339
|
+
return path.slice(path.lastIndexOf("/") + 1).includes(".");
|
|
340
|
+
}
|
|
341
|
+
/** `path` with no trailing slashes. Why a scan, not `/\/+$/`: that regex takes quadratic time on a long run of slashes inside the path. */
|
|
342
|
+
function trimTrailingSlashes(path) {
|
|
343
|
+
let end = path.length;
|
|
344
|
+
while (end > 0 && path[end - 1] === "/") end -= 1;
|
|
345
|
+
return path.slice(0, end);
|
|
346
|
+
}
|
|
347
|
+
/** The URL path in `mode`, or the path unchanged when `mode` keeps it. */
|
|
348
|
+
function canonicalPath(path, mode) {
|
|
349
|
+
const trimmed = trimTrailingSlashes(path);
|
|
350
|
+
if (trimmed === "") return "/";
|
|
351
|
+
if (mode === "never") return trimmed;
|
|
352
|
+
if (mode === "always") return `${trimmed}/`;
|
|
353
|
+
return path;
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* Whether one of the app's own Hono routes matches the request. Why the
|
|
357
|
+
* path: the plugins and the framework match at `/*`, and Hono matches a
|
|
358
|
+
* route path strictly, so a redirect would move the request off its route.
|
|
359
|
+
*/
|
|
360
|
+
function hasAppRoute(context) {
|
|
361
|
+
return matchedRoutes(context).some((route) => route.path !== "/*");
|
|
362
|
+
}
|
|
363
|
+
/** Whether `path`, a decoded URL path, names a file in `files`, not a directory. */
|
|
364
|
+
async function isStaticFile(files, path) {
|
|
365
|
+
return (await findStaticFile(files, path))?.path === path;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Sends a 308 from a page URL to the same URL in `mode`, so each page has one
|
|
369
|
+
* URL. It applies to rendered and prerendered pages, because the server cannot
|
|
370
|
+
* tell which paths have a route. The redirect keeps the query string.
|
|
371
|
+
*
|
|
372
|
+
* It sends no redirect for `/`, a method other than GET or HEAD, a data
|
|
373
|
+
* request of the framework, a path that one of the app's own Hono routes
|
|
374
|
+
* matches, such as `app.get("/livez")`, or a path that already has the
|
|
375
|
+
* mode's form. `always` adds no slash to a file in the client build, such as
|
|
376
|
+
* `/LICENSE`, or to a path whose last segment has a dot, such as `/llms.txt`.
|
|
377
|
+
*
|
|
378
|
+
* Set the same mode in the framework's router when it has one. Else the two
|
|
379
|
+
* redirects loop: the server sends `/x` to `/x/`, and the router sends `/x/`
|
|
380
|
+
* back to `/x`. For TanStack Start, check the mode against the router with
|
|
381
|
+
* `RouterTrailingSlash` from `@ngrok/app-server/tanstack-start`. React Router
|
|
382
|
+
* has no trailing-slash option, so it answers both forms itself.
|
|
383
|
+
*
|
|
384
|
+
* @example
|
|
385
|
+
* createServer({ plugins: defaultPlugins({ trailingSlash: "always" }) });
|
|
386
|
+
*/
|
|
387
|
+
function trailingSlash({ mode }) {
|
|
388
|
+
let stage;
|
|
389
|
+
return {
|
|
390
|
+
name: "trailing-slash",
|
|
391
|
+
setup: (info) => {
|
|
392
|
+
if (mode === "preserve") return;
|
|
393
|
+
stage = async (context, next) => {
|
|
394
|
+
const { method } = context.req;
|
|
395
|
+
if (method !== "GET" && method !== "HEAD" || info.isDataRequest(context.req.path) || hasAppRoute(context)) return next();
|
|
396
|
+
const url = new URL(context.req.url);
|
|
397
|
+
const path = canonicalPath(url.pathname, mode);
|
|
398
|
+
const location = `${path}${url.search}`;
|
|
399
|
+
if (path === url.pathname || !isSafeLocalPath(location)) return next();
|
|
400
|
+
if (mode === "always" && (isFilePath(context.req.path) || await isStaticFile(info.files, context.req.path))) return next();
|
|
401
|
+
return context.redirect(location, 308);
|
|
402
|
+
};
|
|
403
|
+
},
|
|
404
|
+
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// src/core/plugins/redirects.ts
|
|
409
|
+
const PARAM = /^:(?<name>[A-Za-z_]\w*)$/u;
|
|
410
|
+
const TARGET_TOKEN = /:(?<name>[A-Za-z_]\w*)|\*/gu;
|
|
411
|
+
/** `path` with no trailing slashes, and `/` for the root. */
|
|
412
|
+
function matchKey(path) {
|
|
413
|
+
return trimTrailingSlashes(path) || "/";
|
|
414
|
+
}
|
|
415
|
+
/** The pattern of `from`, with a named group for each `:name` and for `*`, or `undefined` for an exact path. */
|
|
416
|
+
function compilePattern(from) {
|
|
417
|
+
const segments = matchKey(from).split("/").slice(1);
|
|
418
|
+
const names = /* @__PURE__ */ new Set();
|
|
419
|
+
const parts = segments.map((segment, index) => {
|
|
420
|
+
const name = PARAM.exec(segment)?.groups?.name;
|
|
421
|
+
if (name != null) {
|
|
422
|
+
if (names.has(name)) throw new Error(`The redirect from ${from} uses :${name} twice.`);
|
|
423
|
+
names.add(name);
|
|
424
|
+
return `/(?<${name}>[^/]+)`;
|
|
425
|
+
}
|
|
426
|
+
if (segment === "*") {
|
|
427
|
+
if (index !== segments.length - 1) throw new Error(`The redirect from ${from} has a * that is not the last segment.`);
|
|
428
|
+
names.add("*");
|
|
429
|
+
return "(?:/(?<$splat>.*))?";
|
|
430
|
+
}
|
|
431
|
+
return `/${segment.replaceAll(/[$()*+.?[\\\]^{|}]/gu, String.raw`\$&`)}`;
|
|
432
|
+
});
|
|
433
|
+
return {
|
|
434
|
+
pattern: names.size === 0 ? void 0 : new RegExp(`^${parts.join("")}$`, "u"),
|
|
435
|
+
names
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
/** Compiles a rule, and throws for a rule that is not valid, so a bad table stops startup. */
|
|
439
|
+
function compileRule({ from, to, status = 301 }, index) {
|
|
440
|
+
if (!from.startsWith("/")) throw new Error(`A redirect must be from a path that starts with "/", not ${from}.`);
|
|
441
|
+
const { pattern, names } = compilePattern(from);
|
|
442
|
+
for (const token of to.matchAll(TARGET_TOKEN)) {
|
|
443
|
+
const name = token.groups?.name ?? "*";
|
|
444
|
+
if (!names.has(name)) throw new Error(`The redirect from ${from} to ${to} uses ${token[0]}, which ${from} does not have.`);
|
|
445
|
+
}
|
|
446
|
+
if (to.startsWith("/")) {
|
|
447
|
+
if (!isSafeLocalPath(to)) throw new Error(`The redirect from ${from} goes to ${to}, which is not a safe local path.`);
|
|
448
|
+
return {
|
|
449
|
+
key: matchKey(from),
|
|
450
|
+
pattern,
|
|
451
|
+
to,
|
|
452
|
+
status,
|
|
453
|
+
origin: void 0,
|
|
454
|
+
index
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
const url = URL.parse(to);
|
|
458
|
+
if (url == null || url.protocol !== "https:" && url.protocol !== "http:") throw new Error(`A redirect must go to a local path or an http(s) URL, not ${to}.`);
|
|
459
|
+
return {
|
|
460
|
+
key: matchKey(from),
|
|
461
|
+
pattern,
|
|
462
|
+
to: url.href,
|
|
463
|
+
status,
|
|
464
|
+
origin: url.origin,
|
|
465
|
+
index
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
/** The target of `rule` for the values that its pattern matched. */
|
|
469
|
+
function fill(to, groups) {
|
|
470
|
+
const queryStart = to.indexOf("?");
|
|
471
|
+
return to.replaceAll(TARGET_TOKEN, (token, name, offset) => {
|
|
472
|
+
const value = name == null ? groups.$splat ?? "" : groups[name] ?? token;
|
|
473
|
+
return queryStart !== -1 && offset > queryStart ? value.replaceAll(/[&+=]/gu, (char) => encodeURIComponent(char)) : value;
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
/** `target` with no trailing slash on its path, as the `never` mode of `trailingSlash` wants. */
|
|
477
|
+
function withoutTrailingSlash(target) {
|
|
478
|
+
const pathEnd = target.search(/[#?]/u);
|
|
479
|
+
const path = pathEnd === -1 ? target : target.slice(0, pathEnd);
|
|
480
|
+
const rest = pathEnd === -1 ? "" : target.slice(pathEnd);
|
|
481
|
+
return `${trimTrailingSlashes(path) || "/"}${rest}`;
|
|
482
|
+
}
|
|
483
|
+
/** `target` with the query string of the request added, before the fragment of `target`. */
|
|
484
|
+
function withQuery(target, search) {
|
|
485
|
+
if (search === "") return target;
|
|
486
|
+
const hashIndex = target.indexOf("#");
|
|
487
|
+
const path = hashIndex === -1 ? target : target.slice(0, hashIndex);
|
|
488
|
+
const hash = hashIndex === -1 ? "" : target.slice(hashIndex);
|
|
489
|
+
return `${path}${path.includes("?") ? `&${search.slice(1)}` : search}${hash}`;
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Sends a redirect from each old URL path in `rules` to its new URL, with
|
|
493
|
+
* the query string. The first rule that matches wins. An exact path is a
|
|
494
|
+
* map lookup. A rule with `:name` or `*` is a pattern.
|
|
495
|
+
*
|
|
496
|
+
* The rules compile at startup, and a rule that is not valid stops startup.
|
|
497
|
+
* A local target must be a safe local path. An absolute target must keep the
|
|
498
|
+
* origin that its rule names. A request whose values break either check goes
|
|
499
|
+
* on to the next stage, and so does a request that is already at its
|
|
500
|
+
* target. It applies to GET and HEAD only.
|
|
501
|
+
*
|
|
502
|
+
* Put it before `trailingSlash`, so `/old/` gets one redirect to the final
|
|
503
|
+
* URL, and give it the same `trailingSlash` mode. In `never` mode, a local
|
|
504
|
+
* target loses its trailing slash, so `trailingSlash` does not redirect it
|
|
505
|
+
* again. `defaultPlugins({ redirects })` does both.
|
|
506
|
+
*
|
|
507
|
+
* @example
|
|
508
|
+
* redirects([
|
|
509
|
+
* { from: "/blog/:slug", to: "/articles/:slug" },
|
|
510
|
+
* { from: "/docs/*", to: "https://docs.example.com/*", status: 308 },
|
|
511
|
+
* ]);
|
|
512
|
+
*/
|
|
513
|
+
function redirects(rules, { trailingSlash = "preserve" } = {}) {
|
|
514
|
+
const compiled = rules.map((rule, index) => compileRule(rule, index));
|
|
515
|
+
const exact = /* @__PURE__ */ new Map();
|
|
516
|
+
for (const rule of compiled.toReversed()) if (rule.pattern == null) exact.set(rule.key, rule);
|
|
517
|
+
const patterns = compiled.filter((rule) => rule.pattern != null);
|
|
518
|
+
const find = (path) => {
|
|
519
|
+
const exactRule = exact.get(path);
|
|
520
|
+
for (const rule of patterns) {
|
|
521
|
+
if (exactRule != null && rule.index > exactRule.index) break;
|
|
522
|
+
const groups = rule.pattern?.exec(path)?.groups;
|
|
523
|
+
if (groups != null) return {
|
|
524
|
+
rule,
|
|
525
|
+
target: fill(rule.to, groups)
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
return exactRule == null ? void 0 : {
|
|
529
|
+
rule: exactRule,
|
|
530
|
+
target: exactRule.to
|
|
531
|
+
};
|
|
532
|
+
};
|
|
533
|
+
return {
|
|
534
|
+
name: "redirects",
|
|
535
|
+
middleware: async (context, next) => {
|
|
536
|
+
const { method } = context.req;
|
|
537
|
+
if (method !== "GET" && method !== "HEAD") return next();
|
|
538
|
+
const url = new URL(context.req.url);
|
|
539
|
+
const found = find(matchKey(url.pathname));
|
|
540
|
+
if (found == null) return next();
|
|
541
|
+
const location = withQuery(trailingSlash === "never" && found.rule.origin == null ? withoutTrailingSlash(found.target) : found.target, url.search);
|
|
542
|
+
if (new URL(location, url).href === url.href) return next();
|
|
543
|
+
return (found.rule.origin == null ? isSafeLocalPath(location) : URL.parse(location)?.origin === found.rule.origin) ? context.redirect(location, found.rule.status) : next();
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/core/plugins/security-headers.ts
|
|
549
|
+
const DEFAULT_SECURITY_HEADERS = {
|
|
550
|
+
"X-Content-Type-Options": "nosniff",
|
|
551
|
+
"Referrer-Policy": "strict-origin-when-cross-origin",
|
|
552
|
+
"Cross-Origin-Opener-Policy": "same-origin",
|
|
553
|
+
"Strict-Transport-Security": "max-age=31536000"
|
|
554
|
+
};
|
|
555
|
+
/**
|
|
556
|
+
* Sets safe default security headers on each response:
|
|
557
|
+
*
|
|
558
|
+
* - `X-Content-Type-Options: nosniff`
|
|
559
|
+
* - `Referrer-Policy: strict-origin-when-cross-origin`
|
|
560
|
+
* - `Cross-Origin-Opener-Policy: same-origin`
|
|
561
|
+
* - `Strict-Transport-Security: max-age=31536000`, on an HTTPS request only
|
|
562
|
+
*
|
|
563
|
+
* A response that has a header keeps its own value. The exception is
|
|
564
|
+
* `Content-Security-Policy`, which has no default: the plugin adds a set
|
|
565
|
+
* value as a second policy, and a browser enforces both.
|
|
566
|
+
* `defaultPlugins()` puts it before the static stages, so it also sees
|
|
567
|
+
* prerendered pages.
|
|
568
|
+
*
|
|
569
|
+
* @example
|
|
570
|
+
* defaultPlugins({
|
|
571
|
+
* securityHeaders: {
|
|
572
|
+
* headers: {
|
|
573
|
+
* "Cross-Origin-Opener-Policy": "same-origin-allow-popups",
|
|
574
|
+
* "Content-Security-Policy": "frame-ancestors 'none'",
|
|
575
|
+
* },
|
|
576
|
+
* },
|
|
577
|
+
* });
|
|
578
|
+
*/
|
|
579
|
+
function securityHeaders({ headers = {} } = {}) {
|
|
580
|
+
const values = Object.entries({
|
|
581
|
+
...DEFAULT_SECURITY_HEADERS,
|
|
582
|
+
...headers
|
|
583
|
+
}).filter((entry) => typeof entry[1] === "string").map(([name, value]) => [name, oneLine(value)]);
|
|
584
|
+
return {
|
|
585
|
+
name: "security-headers",
|
|
586
|
+
middleware: async (context, next) => {
|
|
587
|
+
const isHttps = context.req.url.startsWith("https:");
|
|
588
|
+
await withHeaderHook(context, next, (response) => {
|
|
589
|
+
for (const [name, value] of values) if (name === "Content-Security-Policy") response.append(name, value);
|
|
590
|
+
else if (!response.has(name) && (name !== "Strict-Transport-Security" || isHttps)) response.set(name, value);
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* `value` on one line. Why: a header value cannot hold a line break, and a
|
|
597
|
+
* policy written over several lines treats each run of whitespace as one space.
|
|
598
|
+
*/
|
|
599
|
+
function oneLine(value) {
|
|
600
|
+
return value.replaceAll(/\s+/gu, " ").trim();
|
|
601
|
+
}
|
|
602
|
+
/** A new random nonce: 16 bytes in base64. */
|
|
603
|
+
function randomNonce() {
|
|
604
|
+
return btoa(String.fromCodePoint(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))));
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Sets the `Content-Security-Policy` from `policy` on each HTML document. The
|
|
608
|
+
* policy trusts the document's scripts, and only them:
|
|
609
|
+
*
|
|
610
|
+
* - A rendered document gets `'nonce-…' 'strict-dynamic'` with a new nonce
|
|
611
|
+
* for each request. The app reads the nonce from `requestContext()` and
|
|
612
|
+
* gives it to the framework's render, so each inline script gets it.
|
|
613
|
+
* - A prerendered document gets `'self'` and the hash of each of its inline
|
|
614
|
+
* scripts, which the Vite plugin records. Its file has one nonce for every
|
|
615
|
+
* visitor, so a nonce protects nothing. Why no `'strict-dynamic'`: a hash,
|
|
616
|
+
* unlike a nonce, does not carry to the imports of an inline module script.
|
|
617
|
+
*
|
|
618
|
+
* The `contentSecurityPolicy` option of `defaultPlugins()` takes these
|
|
619
|
+
* options, and puts the plugin before the static stages, so it sees the
|
|
620
|
+
* prerendered documents. A response that has a `Content-Security-Policy`
|
|
621
|
+
* keeps it.
|
|
622
|
+
*
|
|
623
|
+
* @example
|
|
624
|
+
* defaultPlugins({
|
|
625
|
+
* contentSecurityPolicy: {
|
|
626
|
+
* policy: (scriptSrc) => `script-src ${scriptSrc}; object-src 'none'; base-uri 'none'`,
|
|
627
|
+
* },
|
|
628
|
+
* });
|
|
629
|
+
*/
|
|
630
|
+
function contentSecurityPolicy({ policy }) {
|
|
631
|
+
let scriptHashes = /* @__PURE__ */ new Map();
|
|
632
|
+
return optionPlugin("contentSecurityPolicy", {
|
|
633
|
+
name: "content-security-policy",
|
|
634
|
+
setup: (info) => {
|
|
635
|
+
({scriptHashes} = info);
|
|
636
|
+
},
|
|
637
|
+
middleware: async (context, next) => {
|
|
638
|
+
const nonce = randomNonce();
|
|
639
|
+
context.set("cspNonce", nonce);
|
|
640
|
+
await withHeaderHook(context, next, (headers) => {
|
|
641
|
+
const file = context.get("staticDocument");
|
|
642
|
+
const hashes = context.get("documentScriptHashes") ?? (file == null ? void 0 : scriptHashes.get(file) ?? []);
|
|
643
|
+
if (headers.has("Content-Security-Policy") || hashes == null && !(headers.get("Content-Type")?.startsWith("text/html") ?? false)) return;
|
|
644
|
+
const scriptSrc = hashes == null ? `'nonce-${nonce}' 'strict-dynamic'` : ["'self'", ...hashes.map((hash) => `'sha256-${hash}'`)].join(" ");
|
|
645
|
+
headers.set("Content-Security-Policy", oneLine(policy(scriptSrc, context)));
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// src/core/plugins/request-id.ts
|
|
652
|
+
/** An incoming request ID that the plugin keeps: up to 255 word characters, `-`, and `=`. */
|
|
653
|
+
const VALID_ID = /^[\w\-=]{1,255}$/u;
|
|
654
|
+
/** A W3C `traceparent`: version, trace ID, parent ID, and flags, in lowercase hex. */
|
|
655
|
+
const TRACEPARENT = /^(?<version>[\da-f]{2})-(?<traceId>[\da-f]{32})-(?<spanId>[\da-f]{16})-[\da-f]{2}(?<rest>-.*)?$/u;
|
|
656
|
+
/**
|
|
657
|
+
* The trace IDs of a valid W3C `traceparent` header, else `undefined`. A
|
|
658
|
+
* version `ff`, an ID of all zeros, and extra fields in version `00` are not valid.
|
|
659
|
+
*
|
|
660
|
+
* @example
|
|
661
|
+
* parseTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01");
|
|
662
|
+
* // => { traceId: "4bf92f3577b34da6a3ce929d0e0e4736", spanId: "00f067aa0ba902b7" }
|
|
663
|
+
*/
|
|
664
|
+
function parseTraceparent(header) {
|
|
665
|
+
const groups = TRACEPARENT.exec(header?.trim() ?? "")?.groups;
|
|
666
|
+
if (groups?.version == null || groups.traceId == null || groups.spanId == null || groups.version === "ff" || groups.version === "00" && groups.rest != null || /^0+$/u.test(groups.traceId) || /^0+$/u.test(groups.spanId)) return;
|
|
667
|
+
return {
|
|
668
|
+
traceId: groups.traceId,
|
|
669
|
+
spanId: groups.spanId
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
/** The log attributes for the trace IDs. */
|
|
673
|
+
function traceAttributes({ traceId, spanId }, { datadog }) {
|
|
674
|
+
return {
|
|
675
|
+
trace_id: traceId,
|
|
676
|
+
span_id: spanId,
|
|
677
|
+
...datadog ? {
|
|
678
|
+
"dd.trace_id": BigInt(`0x${traceId.slice(16)}`).toString(),
|
|
679
|
+
"dd.span_id": BigInt(`0x${spanId}`).toString()
|
|
680
|
+
} : {}
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Gives each request an ID: a valid incoming header (up to 255 word
|
|
685
|
+
* characters, `-`, and `=`), else a new UUID. The ID goes on the response, on
|
|
686
|
+
* every log line, and into the framework's context.
|
|
687
|
+
*
|
|
688
|
+
* A valid W3C `traceparent` header adds `trace_id` and `span_id` to each log
|
|
689
|
+
* line of the request.
|
|
690
|
+
*
|
|
691
|
+
* @example
|
|
692
|
+
* const app = createServer({ plugins: [requestId()] });
|
|
693
|
+
* const response = await app.request("/", { headers: { "X-Request-Id": "abc-123" } });
|
|
694
|
+
* response.headers.get("X-Request-Id"); // => "abc-123"
|
|
695
|
+
*/
|
|
696
|
+
function requestId({ headerName = "X-Request-Id", datadogTraceIds = false } = {}) {
|
|
697
|
+
return {
|
|
698
|
+
name: "request-id",
|
|
699
|
+
middleware: async (context, next) => {
|
|
700
|
+
const trace = parseTraceparent(context.req.header("traceparent"));
|
|
701
|
+
if (trace != null) context.set("logAttributes", {
|
|
702
|
+
...context.get("logAttributes"),
|
|
703
|
+
...traceAttributes(trace, { datadog: datadogTraceIds })
|
|
704
|
+
});
|
|
705
|
+
const incoming = context.req.header(headerName);
|
|
706
|
+
const id = incoming != null && VALID_ID.test(incoming) ? incoming : crypto.randomUUID();
|
|
707
|
+
context.set("requestId", id);
|
|
708
|
+
await withHeaderHook(context, next, (headers) => {
|
|
709
|
+
headers.set(headerName, id);
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// src/core/prefers-markdown.ts
|
|
716
|
+
/** A `q` value as RFC 9110 writes it: 0 to 1, with up to three decimals. */
|
|
717
|
+
const QVALUE = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;
|
|
718
|
+
/** The charset of each answer that a caller of {@link prefersMarkdown} sends. */
|
|
719
|
+
const CHARSET = "utf-8";
|
|
720
|
+
/**
|
|
721
|
+
* The parts of `value` between each `separator`. Why a scan, not `split`: a
|
|
722
|
+
* quoted parameter value can hold a `,` or a `;`.
|
|
723
|
+
*/
|
|
724
|
+
function splitOutsideQuotes(value, separator) {
|
|
725
|
+
const parts = [];
|
|
726
|
+
let part = "";
|
|
727
|
+
let quoted = false;
|
|
728
|
+
let escaped = false;
|
|
729
|
+
for (const character of value) if (!quoted && character === separator) {
|
|
730
|
+
parts.push(part);
|
|
731
|
+
part = "";
|
|
732
|
+
} else {
|
|
733
|
+
if (escaped) escaped = false;
|
|
734
|
+
else if (quoted && character === "\\") escaped = true;
|
|
735
|
+
else if (character === "\"") quoted = !quoted;
|
|
736
|
+
part += character;
|
|
737
|
+
}
|
|
738
|
+
parts.push(part);
|
|
739
|
+
return parts;
|
|
740
|
+
}
|
|
741
|
+
/** The parameters of a media range, by lowercase name, with quotes removed. */
|
|
742
|
+
function parameterMap(parameters) {
|
|
743
|
+
return new Map(parameters.map((parameter) => {
|
|
744
|
+
const index = parameter.indexOf("=");
|
|
745
|
+
const name = (index === -1 ? parameter : parameter.slice(0, index)).trim().toLowerCase();
|
|
746
|
+
const value = index === -1 ? "" : parameter.slice(index + 1).trim();
|
|
747
|
+
return [name, /^".*"$/su.test(value) ? value.slice(1, -1).replaceAll(/\\(?<character>.)/gsu, "$<character>") : value];
|
|
748
|
+
}));
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* The media ranges of an `Accept` header. A missing `q` counts as 1, the RFC
|
|
752
|
+
* 9110 default. Why a malformed `q` also counts as 1: the client still named
|
|
753
|
+
* the media type.
|
|
754
|
+
*/
|
|
755
|
+
function mediaRanges(accept) {
|
|
756
|
+
return splitOutsideQuotes(accept, ",").map((entry) => {
|
|
757
|
+
const [type = "", ...parameters] = splitOutsideQuotes(entry, ";");
|
|
758
|
+
const parameterValues = parameterMap(parameters);
|
|
759
|
+
const quality = parameterValues.get("q") ?? "1";
|
|
760
|
+
return {
|
|
761
|
+
type: type.trim().toLowerCase(),
|
|
762
|
+
quality: QVALUE.test(quality) ? Number(quality) : 1,
|
|
763
|
+
charset: parameterValues.get("charset")?.toLowerCase()
|
|
764
|
+
};
|
|
765
|
+
});
|
|
766
|
+
}
|
|
767
|
+
/**
|
|
768
|
+
* The `q` of an answer of `type` in UTF-8, from the most specific ranges with
|
|
769
|
+
* that type, or `undefined` when no range matches it. A range with
|
|
770
|
+
* `charset=utf-8` is more specific than a range with no charset. A range with
|
|
771
|
+
* another charset does not match. Other parameters, such as `variant`, do not
|
|
772
|
+
* change the match.
|
|
773
|
+
*/
|
|
774
|
+
function qualityOf(ranges, type) {
|
|
775
|
+
const matches = ranges.filter((range) => range.type === type && (range.charset == null || range.charset === CHARSET));
|
|
776
|
+
const withCharset = matches.filter((range) => range.charset === CHARSET);
|
|
777
|
+
const specific = withCharset.length > 0 ? withCharset : matches;
|
|
778
|
+
return specific.length === 0 ? void 0 : Math.max(...specific.map((range) => range.quality));
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Whether a request asks for markdown before HTML, per
|
|
782
|
+
* https://acceptmarkdown.com. Use it to choose between the HTML and the
|
|
783
|
+
* markdown answer for one URL.
|
|
784
|
+
*
|
|
785
|
+
* The rules:
|
|
786
|
+
*
|
|
787
|
+
* - Only an explicit `text/markdown` range counts for markdown. A wildcard,
|
|
788
|
+
* such as `*\/*` or `text/*`, never selects markdown, so a browser and a
|
|
789
|
+
* client with no `Accept` get HTML.
|
|
790
|
+
* - `text/markdown;q=0` refuses markdown.
|
|
791
|
+
* - The `q` of markdown must be equal to or higher than the `q` of HTML. The
|
|
792
|
+
* `q` of HTML comes from the most specific range that matches it:
|
|
793
|
+
* `text/html`, then `text/*`, then `*\/*`. A tie selects markdown, because
|
|
794
|
+
* the client named it.
|
|
795
|
+
* - Both answers are UTF-8. A range with `charset=utf-8` is more specific
|
|
796
|
+
* than a range with no charset, and a range with another charset does not
|
|
797
|
+
* match. Other parameters, such as `variant`, do not change the match.
|
|
798
|
+
* - Media types and parameter names are not case-sensitive. A quoted
|
|
799
|
+
* parameter value can hold a `,` or a `;`.
|
|
800
|
+
*
|
|
801
|
+
* When the answer for a URL depends on this function, send `Vary: Accept` on
|
|
802
|
+
* both the HTML and the markdown answer. Else a shared cache can give the
|
|
803
|
+
* markdown to a browser.
|
|
804
|
+
*
|
|
805
|
+
* @example
|
|
806
|
+
* prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/markdown" } }));
|
|
807
|
+
* // => true
|
|
808
|
+
* prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/html, text/markdown;q=0.5" } }));
|
|
809
|
+
* // => false
|
|
810
|
+
*/
|
|
811
|
+
function prefersMarkdown(request) {
|
|
812
|
+
const accept = request.headers.get("Accept");
|
|
813
|
+
if (accept == null || !/markdown/iu.test(accept)) return false;
|
|
814
|
+
const ranges = mediaRanges(accept);
|
|
815
|
+
const markdown = qualityOf(ranges, "text/markdown") ?? 0;
|
|
816
|
+
const html = qualityOf(ranges, "text/html") ?? qualityOf(ranges, "text/*") ?? qualityOf(ranges, "*/*") ?? 0;
|
|
817
|
+
return markdown > 0 && markdown >= html;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// src/core/plugins/static.ts
|
|
821
|
+
const IMMUTABLE = "public, max-age=31536000, immutable";
|
|
822
|
+
/**
|
|
823
|
+
* Serves the hashed files under `/assets/` with a one-year immutable cache.
|
|
824
|
+
* A missing asset gets a plain 404 with `Cache-Control: no-store`, not a
|
|
825
|
+
* rendered page. In development, the dev server serves the source modules,
|
|
826
|
+
* the HMR client, and the CSS here instead.
|
|
827
|
+
*
|
|
828
|
+
* @example
|
|
829
|
+
* createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
|
|
830
|
+
*/
|
|
831
|
+
function assets() {
|
|
832
|
+
let stage;
|
|
833
|
+
return {
|
|
834
|
+
name: "assets",
|
|
835
|
+
setup: (info) => {
|
|
836
|
+
if (info.mode === "development") {
|
|
837
|
+
stage = info.devServer;
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
const { files, contentTypes } = info;
|
|
841
|
+
stage = async (context, next) => {
|
|
842
|
+
const { method, path } = context.req;
|
|
843
|
+
if (!path.startsWith("/assets/") || method !== "GET" && method !== "HEAD") return next();
|
|
844
|
+
const file = await findStaticFile(files, path);
|
|
845
|
+
if (file == null) return context.text("Not Found", 404, { "Cache-Control": "no-store" });
|
|
846
|
+
return staticResponse(context, {
|
|
847
|
+
files,
|
|
848
|
+
file,
|
|
849
|
+
headers: { "Cache-Control": IMMUTABLE },
|
|
850
|
+
contentTypes
|
|
851
|
+
});
|
|
852
|
+
};
|
|
853
|
+
},
|
|
854
|
+
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
const REVALIDATE = "public, max-age=0, must-revalidate";
|
|
858
|
+
const ONE_HOUR = "public, max-age=3600, stale-while-revalidate=86400";
|
|
859
|
+
/** The default markdown twin of a page: `/docs/button.md` for `/docs/button`, and `/index.md` for `/`. */
|
|
860
|
+
function defaultTwinOf(path) {
|
|
861
|
+
return `${trimTrailingSlashes(path) || "/index"}.md`;
|
|
862
|
+
}
|
|
863
|
+
/** The file of the markdown twin of the request, or `undefined` when the page has none. */
|
|
864
|
+
async function findTwin(files, context, twinOf) {
|
|
865
|
+
const twinPath = twinOf?.(context.req.path, context);
|
|
866
|
+
const file = twinPath == null ? void 0 : await findStaticFile(files, twinPath);
|
|
867
|
+
return twinPath == null || file == null ? void 0 : {
|
|
868
|
+
path: twinPath,
|
|
869
|
+
file
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
/** Adds `Vary: Accept` to the answer for a path with a twin, so a shared cache keeps both answers. */
|
|
873
|
+
function varyOnAccept(context) {
|
|
874
|
+
const vary = withVary(context.res.headers.get("Vary"), "Accept");
|
|
875
|
+
if (vary != null) writableHeaders(context).set("Vary", vary);
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* The percent-encoded URL path for a decoded path, so it holds no space,
|
|
879
|
+
* `>`, or non-ASCII character. Why the replace: a URL removes a tab or a
|
|
880
|
+
* newline, which a file name can hold.
|
|
881
|
+
*/
|
|
882
|
+
function urlPath(path) {
|
|
883
|
+
return new URL(path.replaceAll(/[\t\n\r]/gu, (character) => encodeURIComponent(character)), "http://localhost").pathname;
|
|
884
|
+
}
|
|
885
|
+
/** Adds a `Link` to the twin at `twinPath`, so a client that does not ask for markdown can find it. */
|
|
886
|
+
function linkToTwin(context, twinPath) {
|
|
887
|
+
writableHeaders(context).append("Link", `<${urlPath(twinPath)}>; rel="alternate"; type="text/markdown"`);
|
|
888
|
+
}
|
|
889
|
+
/**
|
|
890
|
+
* The development stage of `markdownTwins`. The client build has no twins
|
|
891
|
+
* then, so a request that prefers markdown gets the framework's answer for
|
|
892
|
+
* the twin's URL: the route that prerenders the twin. A twin path that is not
|
|
893
|
+
* in `prerenderedPaths`, an error, or an answer that is not markdown sends the
|
|
894
|
+
* request on for the HTML.
|
|
895
|
+
*/
|
|
896
|
+
function developmentTwins(twinOf, skip, prerenderedPaths) {
|
|
897
|
+
return async (context, next) => {
|
|
898
|
+
const { method, path } = context.req;
|
|
899
|
+
const twinPath = (method === "GET" || method === "HEAD") && skip?.(path) !== true && prefersMarkdown(context.req.raw) ? twinOf(path, context) : void 0;
|
|
900
|
+
if (twinPath == null || prerenderedPaths != null && !prerenderedPaths.has(twinPath) || !isFilePath$1(twinPath)) return next();
|
|
901
|
+
const url = new URL(context.req.url);
|
|
902
|
+
url.pathname = urlPath(twinPath);
|
|
903
|
+
if (getPath(new Request(url)) !== twinPath) return next();
|
|
904
|
+
const { headers, signal } = context.req.raw;
|
|
905
|
+
const twin = new Request(url, {
|
|
906
|
+
method,
|
|
907
|
+
headers,
|
|
908
|
+
signal
|
|
909
|
+
});
|
|
910
|
+
const response = await context.env.framework.fetch(twin, context);
|
|
911
|
+
const markdown = response.headers.get("Content-Type")?.toLowerCase().startsWith("text/markdown") === true;
|
|
912
|
+
if (response.status !== 304 && !(response.ok && markdown)) {
|
|
913
|
+
await response.body?.cancel();
|
|
914
|
+
return next();
|
|
915
|
+
}
|
|
916
|
+
context.res = response;
|
|
917
|
+
varyOnAccept(context);
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
/** The `twinOf` function that the `markdownTwins` option selects, or `undefined` when it is off. */
|
|
921
|
+
function twinOfOption(markdownTwins) {
|
|
922
|
+
if (markdownTwins === true) return defaultTwinOf;
|
|
923
|
+
if (markdownTwins == null || markdownTwins === false) return;
|
|
924
|
+
return markdownTwins.twinOf;
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* Serves the client build: prerendered pages at their own URL with a 200,
|
|
928
|
+
* plus every other file in it. It sends no redirect. The `trailingSlash`
|
|
929
|
+
* plugin does. Each response gets
|
|
930
|
+
* the headers its loader sent at build time (the `appServer` Vite plugin
|
|
931
|
+
* captures them), a `Cache-Control` (see `cacheControl`), an ETag, and a 304
|
|
932
|
+
* for a matching `If-None-Match`. A GET with one byte range gets a 206. A path
|
|
933
|
+
* with no file goes on to the framework. In development, only
|
|
934
|
+
* `markdownTwins` runs.
|
|
935
|
+
*
|
|
936
|
+
* At startup, it warns about each prerendered path that has no file.
|
|
937
|
+
*
|
|
938
|
+
* @example
|
|
939
|
+
* prerendered({
|
|
940
|
+
* headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
|
|
941
|
+
* });
|
|
942
|
+
*/
|
|
943
|
+
function prerendered(options = {}) {
|
|
944
|
+
let stage;
|
|
945
|
+
return {
|
|
946
|
+
name: "prerendered",
|
|
947
|
+
setup: async (info) => {
|
|
948
|
+
const twinOf = twinOfOption(options.markdownTwins);
|
|
949
|
+
if (info.mode === "development") {
|
|
950
|
+
const paths = info.prerenderedPaths;
|
|
951
|
+
stage = twinOf == null ? void 0 : developmentTwins(twinOf, options.skip, paths == null ? void 0 : new Set(paths));
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
const { files, contentTypes, capturedHeaders } = info;
|
|
955
|
+
const missing = [];
|
|
956
|
+
for (const path of info.prerenderedPaths) if (await findStaticFile(files, path) == null) missing.push(path);
|
|
957
|
+
if (missing.length > 0) info.logger.log("warn", "prerendered paths with no file", { "app_server.missing_paths": missing });
|
|
958
|
+
const cacheControl = options.cacheControl ?? ((path) => {
|
|
959
|
+
const type = contentType(path, contentTypes);
|
|
960
|
+
return type.startsWith("text/html") || type.startsWith("text/markdown") || info.isDataRequest(path) ? REVALIDATE : ONE_HOUR;
|
|
961
|
+
});
|
|
962
|
+
const serve = async (context, path, file) => {
|
|
963
|
+
const value = cacheControl(file.path);
|
|
964
|
+
const headers = new Headers(value == null ? void 0 : { "Cache-Control": value });
|
|
965
|
+
for (const layer of [capturedHeaders.get(manifestKey(path)), options.headers?.(path, context)]) for (const [name, layerValue] of Object.entries(layer ?? {})) headers.set(name, layerValue);
|
|
966
|
+
return staticResponse(context, {
|
|
967
|
+
files,
|
|
968
|
+
file,
|
|
969
|
+
headers: Object.fromEntries(headers),
|
|
970
|
+
contentTypes
|
|
971
|
+
});
|
|
972
|
+
};
|
|
973
|
+
stage = async (context, next) => {
|
|
974
|
+
const { method } = context.req;
|
|
975
|
+
if (method !== "GET" && method !== "HEAD" || options.skip?.(context.req.path) === true) return next();
|
|
976
|
+
const twin = await findTwin(files, context, twinOf);
|
|
977
|
+
const preferred = twin != null && prefersMarkdown(context.req.raw) ? twin : void 0;
|
|
978
|
+
const path = preferred?.path ?? options.rewrite?.(context.req.path, context) ?? context.req.path;
|
|
979
|
+
const file = preferred?.file ?? await findStaticFile(files, path);
|
|
980
|
+
if (file == null) await next();
|
|
981
|
+
else context.res = await serve(context, path, file);
|
|
982
|
+
if (twin != null) varyOnAccept(context);
|
|
983
|
+
if (twin != null && preferred == null) linkToTwin(context, twin.path);
|
|
984
|
+
};
|
|
985
|
+
},
|
|
986
|
+
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
987
|
+
};
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
// src/core/plugins/streaming-compress.ts
|
|
991
|
+
/**
|
|
992
|
+
* The most bytes that one pull of {@link replay} joins. Why 16 KiB: a source
|
|
993
|
+
* that makes a chunk on each read looks queued, so the join can read ahead of
|
|
994
|
+
* the client by this size, the default read-ahead of a Node.js stream.
|
|
995
|
+
*/
|
|
996
|
+
const MAX_JOINED_BYTES = 16384;
|
|
997
|
+
/**
|
|
998
|
+
* Reads at most two chunks that `reader` has queued, and never waits for
|
|
999
|
+
* more. Why two: a body from a string or a buffer queues its bytes and its
|
|
1000
|
+
* end, so the plugin can see that it is small. `@hono/node-server` reads a
|
|
1001
|
+
* body the same way to find its length.
|
|
1002
|
+
*/
|
|
1003
|
+
async function readQueued(reader) {
|
|
1004
|
+
const chunks = [];
|
|
1005
|
+
for (let count = 0; count < 2; count += 1) {
|
|
1006
|
+
const next = await readIfQueued(reader);
|
|
1007
|
+
if ("pending" in next) return {
|
|
1008
|
+
chunks,
|
|
1009
|
+
done: false,
|
|
1010
|
+
pending: next.pending
|
|
1011
|
+
};
|
|
1012
|
+
if (next.result.done) return {
|
|
1013
|
+
chunks,
|
|
1014
|
+
done: true,
|
|
1015
|
+
pending: void 0
|
|
1016
|
+
};
|
|
1017
|
+
chunks.push(next.result.value);
|
|
1018
|
+
}
|
|
1019
|
+
return {
|
|
1020
|
+
chunks,
|
|
1021
|
+
done: false,
|
|
1022
|
+
pending: void 0
|
|
1023
|
+
};
|
|
1024
|
+
}
|
|
1025
|
+
function join(chunks, size) {
|
|
1026
|
+
const [first] = chunks;
|
|
1027
|
+
if (chunks.length === 1 && first != null) return first;
|
|
1028
|
+
const joined = new Uint8Array(size);
|
|
1029
|
+
let offset = 0;
|
|
1030
|
+
for (const chunk of chunks) {
|
|
1031
|
+
joined.set(chunk, offset);
|
|
1032
|
+
offset += chunk.byteLength;
|
|
1033
|
+
}
|
|
1034
|
+
return joined;
|
|
1035
|
+
}
|
|
1036
|
+
/**
|
|
1037
|
+
* The body again: the queued chunks, then the rest of `reader`. Each pull
|
|
1038
|
+
* waits for one chunk at most, and joins it with the chunks that are queued
|
|
1039
|
+
* after it, up to {@link MAX_JOINED_BYTES}. Why join: gzip flushes after each
|
|
1040
|
+
* chunk, and each flush costs more than the bytes. A renderer such as React
|
|
1041
|
+
* queues many small chunks at once. A chunk that comes later still goes out on
|
|
1042
|
+
* its own. A chunk that does not fit waits for the next pull, and an empty
|
|
1043
|
+
* chunk ends the join. When `queued` has the end, the first pull sends the
|
|
1044
|
+
* chunks and closes.
|
|
1045
|
+
*/
|
|
1046
|
+
function replay(reader, queued) {
|
|
1047
|
+
const chunks = [...queued.chunks];
|
|
1048
|
+
let { pending, done } = queued;
|
|
1049
|
+
return new ReadableStream({
|
|
1050
|
+
async pull(controller) {
|
|
1051
|
+
const parts = [];
|
|
1052
|
+
let size = 0;
|
|
1053
|
+
const fits = (chunk) => parts.length === 0 || size + chunk.byteLength <= 16384;
|
|
1054
|
+
for (let [chunk] = chunks; chunk != null && fits(chunk); [chunk] = chunks) {
|
|
1055
|
+
chunks.shift();
|
|
1056
|
+
parts.push(chunk);
|
|
1057
|
+
size += chunk.byteLength;
|
|
1058
|
+
}
|
|
1059
|
+
if (parts.length === 0) {
|
|
1060
|
+
const result = await (pending ?? reader.read());
|
|
1061
|
+
pending = void 0;
|
|
1062
|
+
if (result.done) {
|
|
1063
|
+
controller.close();
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
parts.push(result.value);
|
|
1067
|
+
size = result.value.byteLength;
|
|
1068
|
+
}
|
|
1069
|
+
while (chunks.length === 0 && pending == null && !done && size < 16384) {
|
|
1070
|
+
const next = await readIfQueued(reader);
|
|
1071
|
+
if ("pending" in next) ({pending} = next);
|
|
1072
|
+
else if (next.result.done) done = true;
|
|
1073
|
+
else if (next.result.value.byteLength === 0) break;
|
|
1074
|
+
else if (fits(next.result.value)) {
|
|
1075
|
+
parts.push(next.result.value);
|
|
1076
|
+
size += next.result.value.byteLength;
|
|
1077
|
+
} else chunks.push(next.result.value);
|
|
1078
|
+
}
|
|
1079
|
+
controller.enqueue(join(parts, size));
|
|
1080
|
+
if (done && chunks.length === 0) controller.close();
|
|
1081
|
+
},
|
|
1082
|
+
cancel: async (reason) => reader.cancel(reason)
|
|
1083
|
+
}, { highWaterMark: 0 });
|
|
1084
|
+
}
|
|
1085
|
+
/**
|
|
1086
|
+
* `response` with the gzip `body` and its headers. Why not in a header hook:
|
|
1087
|
+
* the body and its headers go together, also to the code that an outer stage
|
|
1088
|
+
* runs after its `next()`.
|
|
1089
|
+
*/
|
|
1090
|
+
function gzipped(response, body, { hasLength }) {
|
|
1091
|
+
const replacement = new Response(body, response);
|
|
1092
|
+
replacement.headers.set("Content-Encoding", "gzip");
|
|
1093
|
+
if (hasLength) replacement.headers.delete("Content-Length");
|
|
1094
|
+
replacement.headers.delete("Accept-Ranges");
|
|
1095
|
+
return replacement;
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Gzips text responses and flushes after each chunk, so a streamed page shell
|
|
1099
|
+
* or a server-sent event reaches the client at once. Chunks that the body has
|
|
1100
|
+
* queued together are one chunk, up to 16 KiB. `hono/compress` holds a
|
|
1101
|
+
* stream until it ends. Skips a response that is already encoded, a partial
|
|
1102
|
+
* response, one marked `no-transform`, and one whose `Content-Length` is
|
|
1103
|
+
* under 1 KiB. It adds `Accept-Encoding` to the `Vary` of each response that
|
|
1104
|
+
* it can gzip. The host gives the gzip stream. On a host with none, the
|
|
1105
|
+
* plugin does nothing.
|
|
1106
|
+
*
|
|
1107
|
+
* @example
|
|
1108
|
+
* createServer({ plugins: [requestId(), accessLog(), streamingCompress()] });
|
|
1109
|
+
*/
|
|
1110
|
+
function streamingCompress() {
|
|
1111
|
+
let gzip;
|
|
1112
|
+
return {
|
|
1113
|
+
name: "streaming-compress",
|
|
1114
|
+
setup: (info) => {
|
|
1115
|
+
({gzip} = info);
|
|
1116
|
+
},
|
|
1117
|
+
middleware: async (context, next) => {
|
|
1118
|
+
if (gzip == null) return next();
|
|
1119
|
+
let gzipping = false;
|
|
1120
|
+
await withHeaderHook(context, next, (headers) => {
|
|
1121
|
+
const type = headers.get("Content-Type");
|
|
1122
|
+
const vary = type == null || isCompressible(type) ? withVary(headers.get("Vary"), "Accept-Encoding") : void 0;
|
|
1123
|
+
if (vary != null) headers.set("Vary", vary);
|
|
1124
|
+
if (gzipping) headers.delete("Content-Length");
|
|
1125
|
+
});
|
|
1126
|
+
const response = context.res;
|
|
1127
|
+
const type = response.headers.get("Content-Type");
|
|
1128
|
+
if (type != null && !isCompressible(type)) return;
|
|
1129
|
+
const length = response.headers.get("Content-Length");
|
|
1130
|
+
const { body } = response;
|
|
1131
|
+
if (type == null || body == null || context.req.method === "HEAD" || length != null && Number(length) < 1024 || preferredEncoding(context.req.header("Accept-Encoding"), ["gzip"]) == null || response.headers.has("Content-Encoding") || response.headers.has("Content-Range") || forbidsTransform(response.headers.get("Cache-Control"))) return;
|
|
1132
|
+
let source = body;
|
|
1133
|
+
let compress = true;
|
|
1134
|
+
if (length == null) {
|
|
1135
|
+
const reader = body.getReader();
|
|
1136
|
+
const queued = await readQueued(reader);
|
|
1137
|
+
const size = queued.chunks.reduce((sum, chunk) => sum + chunk.byteLength, 0);
|
|
1138
|
+
compress = !queued.done || size >= 1024;
|
|
1139
|
+
source = replay(reader, queued);
|
|
1140
|
+
}
|
|
1141
|
+
if (compress) {
|
|
1142
|
+
const hooked = hookedHeaders(context, response.headers);
|
|
1143
|
+
compress = !hooked.has("Content-Encoding") && !hooked.has("Content-Range") && !forbidsTransform(hooked.get("Cache-Control"));
|
|
1144
|
+
}
|
|
1145
|
+
if (compress) {
|
|
1146
|
+
gzipping = true;
|
|
1147
|
+
replaceResponse(context, gzipped(response, gzip(source), { hasLength: length != null }));
|
|
1148
|
+
} else if (source !== body) replaceResponse(context, new Response(source, response));
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// src/core/create-server.ts
|
|
1154
|
+
/** The response for `error`, as `onError` gives it for a stage that throws. */
|
|
1155
|
+
function answerError(error, context) {
|
|
1156
|
+
if ("getResponse" in error && typeof error.getResponse === "function") {
|
|
1157
|
+
const response = error.getResponse();
|
|
1158
|
+
if (response instanceof Response) return response;
|
|
1159
|
+
}
|
|
1160
|
+
context.get("logger").error("unhandled error", errorAttributes(error));
|
|
1161
|
+
return context.text("Internal Server Error", 500);
|
|
1162
|
+
}
|
|
1163
|
+
const appInternals = /* @__PURE__ */ new WeakMap();
|
|
1164
|
+
/** Why 10 MiB: a form or an avatar upload fits, and a body cannot fill the memory. */
|
|
1165
|
+
const DEFAULT_BODY_LIMIT = 10485760;
|
|
1166
|
+
/**
|
|
1167
|
+
* The default pipeline, in order: `health`, `requestId`, `accessLog`,
|
|
1168
|
+
* `streamingCompress`, `securityHeaders`, `bodyLimit`, `noindex` (when
|
|
1169
|
+
* set), `buildId`, `contentSecurityPolicy` (when set), `env` (when set), the
|
|
1170
|
+
* `beforeStatic` plugins, `assets`, `redirects` (when the option has rules),
|
|
1171
|
+
* `trailingSlash`, `prerendered`, and `privateDocuments`. It is a plain
|
|
1172
|
+
* array, so an app can filter it or splice into it.
|
|
1173
|
+
*
|
|
1174
|
+
* @example
|
|
1175
|
+
* createServer({
|
|
1176
|
+
* plugins: defaultPlugins({ env, noindex: process.env.PREVIEW === "1", health: { ready: async () => db.ping() } }),
|
|
1177
|
+
* });
|
|
1178
|
+
*/
|
|
1179
|
+
function defaultPlugins(options = {}) {
|
|
1180
|
+
const maxBytes = options.bodyLimit ?? DEFAULT_BODY_LIMIT;
|
|
1181
|
+
return [
|
|
1182
|
+
...options.health === false ? [] : [health(options.health)],
|
|
1183
|
+
requestId(options.requestId),
|
|
1184
|
+
accessLog(options.accessLog),
|
|
1185
|
+
streamingCompress(),
|
|
1186
|
+
...options.securityHeaders === false ? [] : [securityHeaders(options.securityHeaders)],
|
|
1187
|
+
...maxBytes === false ? [] : [bodyLimit({ maxBytes })],
|
|
1188
|
+
...options.noindex === true ? [noindex()] : [],
|
|
1189
|
+
...options.buildId === false ? [] : [buildId(options.buildId)],
|
|
1190
|
+
...options.contentSecurityPolicy == null ? [] : [contentSecurityPolicy(options.contentSecurityPolicy)],
|
|
1191
|
+
...options.env == null ? [] : [options.env],
|
|
1192
|
+
...options.beforeStatic ?? [],
|
|
1193
|
+
assets(),
|
|
1194
|
+
...options.redirects == null || options.redirects.length === 0 ? [] : [redirects(options.redirects, { trailingSlash: options.trailingSlash ?? "never" })],
|
|
1195
|
+
trailingSlash({ mode: options.trailingSlash ?? "never" }),
|
|
1196
|
+
prerendered(options.prerendered),
|
|
1197
|
+
privateDocuments()
|
|
1198
|
+
];
|
|
1199
|
+
}
|
|
1200
|
+
/**
|
|
1201
|
+
* The client address in an `X-Forwarded-For` header, with `hops` trusted
|
|
1202
|
+
* proxies, or `undefined` when the header has no address.
|
|
1203
|
+
*/
|
|
1204
|
+
function forwardedClient(header, hops) {
|
|
1205
|
+
const addresses = (header ?? "").split(",").map((address) => address.trim()).filter((address) => address !== "");
|
|
1206
|
+
return addresses[Math.max(0, addresses.length - hops)];
|
|
1207
|
+
}
|
|
1208
|
+
/** Why: `setTimeout` turns a longer delay into 1 ms. */
|
|
1209
|
+
const MAX_TIMER_MS = 2147483647;
|
|
1210
|
+
/** Throws for a value that is not an integer from 0 to `max`, so a bad option stops startup. */
|
|
1211
|
+
function checkCount(name, value, max = Number.MAX_SAFE_INTEGER) {
|
|
1212
|
+
if (!Number.isInteger(value) || value < 0 || value > max) {
|
|
1213
|
+
const range = max === Number.MAX_SAFE_INTEGER ? "of 0 or more" : `from 0 to ${max}`;
|
|
1214
|
+
throw new Error(`${name} must be an integer ${range}, not ${value}.`);
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
/**
|
|
1218
|
+
* The request with the scheme from `X-Forwarded-Proto`, when that header holds one.
|
|
1219
|
+
*
|
|
1220
|
+
* @example
|
|
1221
|
+
* withForwardedProto(new Request("http://example.com/", { headers: { "X-Forwarded-Proto": "https" } })).url;
|
|
1222
|
+
* // => "https://example.com/"
|
|
1223
|
+
*/
|
|
1224
|
+
function withForwardedProto(request) {
|
|
1225
|
+
const proto = request.headers.get("X-Forwarded-Proto");
|
|
1226
|
+
if (proto !== "http" && proto !== "https" || request.url.startsWith(`${proto}:`)) return request;
|
|
1227
|
+
const url = new URL(request.url);
|
|
1228
|
+
url.protocol = `${proto}:`;
|
|
1229
|
+
const copy = new Request(url, new Request(request));
|
|
1230
|
+
if (copy.method !== request.method) Object.defineProperty(copy, "method", { value: request.method });
|
|
1231
|
+
return copy;
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* A thrown value as an `Error`. Hono sends only an `Error` to `onError`, and
|
|
1235
|
+
* rethrows any other value.
|
|
1236
|
+
*/
|
|
1237
|
+
function asError(error) {
|
|
1238
|
+
return error instanceof Error ? error : new Error(`A non-Error value was thrown: ${String(error)}`, { cause: error });
|
|
1239
|
+
}
|
|
1240
|
+
/** Whether `work` settles before `ms` pass. */
|
|
1241
|
+
async function settlesWithin(work, ms) {
|
|
1242
|
+
let timer;
|
|
1243
|
+
const settled = await Promise.race([work.then(() => true), new Promise((resolve) => {
|
|
1244
|
+
timer = setTimeout(resolve, ms, false);
|
|
1245
|
+
})]);
|
|
1246
|
+
clearTimeout(timer);
|
|
1247
|
+
return settled;
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* Builds an app server: a Hono app that runs the plugins in list order, then
|
|
1251
|
+
* the app's own routes, then the framework. It does not listen; the
|
|
1252
|
+
* `app-server` CLI starts it.
|
|
1253
|
+
*
|
|
1254
|
+
* Two plugins of one option of `defaultPlugins()`, such as two `buildId()`,
|
|
1255
|
+
* stop startup.
|
|
1256
|
+
*
|
|
1257
|
+
* @example
|
|
1258
|
+
* // server.ts
|
|
1259
|
+
* const app = createServer({ logger: slogSink, plugins: defaultPlugins({ env }) });
|
|
1260
|
+
* app.get("/api/status", (c) => c.json({ ok: true }));
|
|
1261
|
+
* export default app;
|
|
1262
|
+
*/
|
|
1263
|
+
function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listeners, trustForwardedProto = false, trustedProxyHops = 0, shutdownDelayMs = 0, shutdownDeadlineMs = 1e4 } = {}) {
|
|
1264
|
+
checkOptionPlugins(plugins);
|
|
1265
|
+
checkCount("trustedProxyHops", trustedProxyHops);
|
|
1266
|
+
checkCount("shutdownDelayMs", shutdownDelayMs, MAX_TIMER_MS);
|
|
1267
|
+
checkCount("shutdownDeadlineMs", shutdownDeadlineMs, MAX_TIMER_MS);
|
|
1268
|
+
const app = new Hono();
|
|
1269
|
+
let onError = answerError;
|
|
1270
|
+
const setOnError = app.onError.bind(app);
|
|
1271
|
+
app.onError = (handler) => {
|
|
1272
|
+
onError = handler;
|
|
1273
|
+
return setOnError(handler);
|
|
1274
|
+
};
|
|
1275
|
+
app.onError(answerError);
|
|
1276
|
+
const answerThrown = async (thrown, context) => onError(asError(thrown), context);
|
|
1277
|
+
let requestStore;
|
|
1278
|
+
if (trustForwardedProto) {
|
|
1279
|
+
const dispatch = app.fetch;
|
|
1280
|
+
app.fetch = async (request, ...rest) => dispatch(withForwardedProto(request), ...rest);
|
|
1281
|
+
}
|
|
1282
|
+
app.use(async (context, next) => {
|
|
1283
|
+
const requestLog = requestLogger(logger, context);
|
|
1284
|
+
context.set("logger", requestLog);
|
|
1285
|
+
const remoteAddress = context.env?.remoteAddress;
|
|
1286
|
+
context.set("clientAddress", trustedProxyHops === 0 ? remoteAddress : forwardedClient(context.req.header("X-Forwarded-For"), trustedProxyHops) ?? remoteAddress);
|
|
1287
|
+
const hooks = [];
|
|
1288
|
+
const reports = [];
|
|
1289
|
+
context.set("headerHooks", hooks);
|
|
1290
|
+
context.set("sentReports", reports);
|
|
1291
|
+
const given = context.env?.edge;
|
|
1292
|
+
const edge = given?.claim(requestLog) === true ? given : void 0;
|
|
1293
|
+
await withRequestContext(requestStore, context, async () => {
|
|
1294
|
+
await next();
|
|
1295
|
+
const finishing = finishResponse(context, {
|
|
1296
|
+
hooks,
|
|
1297
|
+
reports,
|
|
1298
|
+
edge,
|
|
1299
|
+
fail: answerThrown
|
|
1300
|
+
});
|
|
1301
|
+
if (finishing != null) await finishing;
|
|
1302
|
+
});
|
|
1303
|
+
if (context.req.method === "HEAD") await context.res.body?.cancel();
|
|
1304
|
+
});
|
|
1305
|
+
for (const { middleware, etagPart } of plugins) app.use(async (context, next) => {
|
|
1306
|
+
const part = etagPart?.();
|
|
1307
|
+
if (part != null) context.set("etagParts", [...context.get("etagParts") ?? [], part]);
|
|
1308
|
+
try {
|
|
1309
|
+
return await (middleware == null ? next() : middleware(context, next));
|
|
1310
|
+
} catch (error) {
|
|
1311
|
+
throw asError(error);
|
|
1312
|
+
}
|
|
1313
|
+
});
|
|
1314
|
+
app.use(async (_, next) => {
|
|
1315
|
+
try {
|
|
1316
|
+
await next();
|
|
1317
|
+
} catch (error) {
|
|
1318
|
+
throw asError(error);
|
|
1319
|
+
}
|
|
1320
|
+
});
|
|
1321
|
+
let prepared;
|
|
1322
|
+
let running;
|
|
1323
|
+
let stoppingPlugins;
|
|
1324
|
+
const internals = {
|
|
1325
|
+
logger,
|
|
1326
|
+
setRequestStore: (store) => {
|
|
1327
|
+
requestStore = store;
|
|
1328
|
+
},
|
|
1329
|
+
prepare: async (info) => {
|
|
1330
|
+
prepared ??= (async () => {
|
|
1331
|
+
for (const plugin of plugins) await plugin.setup?.(info);
|
|
1332
|
+
app.all("*", async (context) => context.env.framework.fetch(context.req.raw, context));
|
|
1333
|
+
})().catch((error) => {
|
|
1334
|
+
prepared = void 0;
|
|
1335
|
+
throw error;
|
|
1336
|
+
});
|
|
1337
|
+
return prepared;
|
|
1338
|
+
},
|
|
1339
|
+
listen: async (framework, defaultListeners) => {
|
|
1340
|
+
if (running != null) throw new Error("This app server is already listening.");
|
|
1341
|
+
const chosen = listeners ?? defaultListeners ?? [];
|
|
1342
|
+
if (chosen.length === 0) throw new Error("This app server has no listener: the app sets none, and the host has none. A serverless host calls the entry's `fetch`.");
|
|
1343
|
+
renewShutdownSignal();
|
|
1344
|
+
let deadlinePassed = false;
|
|
1345
|
+
const fetch = async (request, bindings) => {
|
|
1346
|
+
const response = await app.fetch(request, {
|
|
1347
|
+
...bindings,
|
|
1348
|
+
framework
|
|
1349
|
+
});
|
|
1350
|
+
if (deadlinePassed) await response.body?.cancel();
|
|
1351
|
+
return response;
|
|
1352
|
+
};
|
|
1353
|
+
const starts = await Promise.allSettled(chosen.map(async (listener) => listener.start(fetch, { trustForwardedProto })));
|
|
1354
|
+
const started = starts.flatMap((start) => start.status === "fulfilled" ? [start.value] : []);
|
|
1355
|
+
const failed = starts.find((start) => start.status === "rejected");
|
|
1356
|
+
if (failed != null) {
|
|
1357
|
+
await Promise.all(started.map(async (listener) => listener.stop({ deadlineMs: 0 })));
|
|
1358
|
+
throw failed.reason;
|
|
1359
|
+
}
|
|
1360
|
+
const urls = started.map((listener) => listener.url);
|
|
1361
|
+
logger.log("info", "listening", { "app_server.urls": urls });
|
|
1362
|
+
let stopping;
|
|
1363
|
+
running = {
|
|
1364
|
+
urls,
|
|
1365
|
+
shutdown: async () => {
|
|
1366
|
+
stopping ??= (async () => {
|
|
1367
|
+
markStopping();
|
|
1368
|
+
if (shutdownDelayMs > 0) {
|
|
1369
|
+
logger.log("info", "waiting before the drain", { "app_server.delay_ms": shutdownDelayMs });
|
|
1370
|
+
await new Promise((resolve) => {
|
|
1371
|
+
setTimeout(resolve, shutdownDelayMs);
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
logger.log("info", "draining", { "app_server.deadline_ms": shutdownDeadlineMs });
|
|
1375
|
+
abortShutdownSignal();
|
|
1376
|
+
const deadline = setTimeout(() => {
|
|
1377
|
+
deadlinePassed = true;
|
|
1378
|
+
}, shutdownDeadlineMs);
|
|
1379
|
+
const results = await Promise.allSettled([internals.stopPlugins(), ...started.map(async (listener) => listener.stop({ deadlineMs: shutdownDeadlineMs }))]);
|
|
1380
|
+
clearTimeout(deadline);
|
|
1381
|
+
const rejected = results.find((result) => result.status === "rejected");
|
|
1382
|
+
if (rejected != null) throw rejected.reason;
|
|
1383
|
+
logger.log("info", "stopped", {});
|
|
1384
|
+
})();
|
|
1385
|
+
return stopping;
|
|
1386
|
+
}
|
|
1387
|
+
};
|
|
1388
|
+
return running;
|
|
1389
|
+
},
|
|
1390
|
+
stopPlugins: async () => {
|
|
1391
|
+
stoppingPlugins ??= (async () => {
|
|
1392
|
+
if (!await settlesWithin((async () => {
|
|
1393
|
+
const results = await Promise.allSettled(plugins.map(async (plugin) => plugin.onShutdown?.()));
|
|
1394
|
+
for (const result of results) if (result.status === "rejected") logger.log("error", "plugin shutdown failed", errorAttributes(result.reason));
|
|
1395
|
+
})(), shutdownDeadlineMs)) logger.log("warn", "plugin shutdown passed the deadline", { "app_server.deadline_ms": shutdownDeadlineMs });
|
|
1396
|
+
})();
|
|
1397
|
+
return stoppingPlugins;
|
|
1398
|
+
}
|
|
1399
|
+
};
|
|
1400
|
+
appInternals.set(app, internals);
|
|
1401
|
+
return app;
|
|
1402
|
+
}
|
|
1403
|
+
/** The internals of an app from {@link createServer} of this copy of the package, else `undefined`. */
|
|
1404
|
+
function serverInternals(app) {
|
|
1405
|
+
return appInternals.get(app);
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
export { abortShutdownSignal as _, streamingCompress as a, accessLog as b, prefersMarkdown as c, securityHeaders as d, redirects as f, health as g, noindex as h, withForwardedProto as i, requestId as l, privateDocuments as m, defaultPlugins as n, assets as o, trailingSlash as p, serverInternals as r, prerendered as s, createServer as t, contentSecurityPolicy as u, shutdownSignal as v, bodyLimit as y };
|
|
1409
|
+
//# sourceMappingURL=create-server-DkTeIJ8L.js.map
|