@ngrok/app-server 0.3.1 → 0.3.3
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 +83 -27
- package/dist/{build-id-C6sYO9Yp.js → build-id-B0448vZH.js} +27 -2
- package/dist/build-id-B0448vZH.js.map +1 -0
- package/dist/{build-manifest-UDNk81Ce.js → build-manifest-DBMWe3Lx.js} +12 -2
- package/dist/build-manifest-DBMWe3Lx.js.map +1 -0
- package/dist/cli.js +2 -2
- package/dist/client-browser.js +1 -1
- package/dist/client.js +1 -1
- package/dist/{entry-CM6Ma-Tv.d.ts → create-server-D4-nVOVJ.d.ts} +56 -70
- package/dist/{create-server-DkTeIJ8L.js → create-server-jMl2ltHD.js} +454 -394
- package/dist/create-server-jMl2ltHD.js.map +1 -0
- package/dist/entry-BPrgE_6K.d.ts +94 -0
- package/dist/entry-D9H4LA9c.js +351 -0
- package/dist/entry-D9H4LA9c.js.map +1 -0
- package/dist/{index-Bo5G9LuQ.d.ts → index-Db7dspq6.d.ts} +6 -1
- package/dist/index.d.ts +5 -14
- package/dist/index.js +3 -3
- package/dist/{load-entry-CmkdlmDX.js → load-entry-D7r0mjEp.js} +4 -4
- package/dist/{load-entry-CmkdlmDX.js.map → load-entry-D7r0mjEp.js.map} +1 -1
- package/dist/{node-BFH82eeL.js → node-C1qudLs_.js} +2 -2
- package/dist/{node-BFH82eeL.js.map → node-C1qudLs_.js.map} +1 -1
- package/dist/node-vite.d.ts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/dist/react-router-vite.d.ts +1 -1
- package/dist/react-router.d.ts +3 -2
- package/dist/react-router.js +31 -2
- package/dist/react-router.js.map +1 -1
- package/dist/request-context-BtQ87VYb.js.map +1 -1
- package/dist/{script-hashes-hqUk6kG7.js → script-hashes-C6hQ5XnP.js} +22 -4
- package/dist/script-hashes-C6hQ5XnP.js.map +1 -0
- package/dist/{serve-Cc-ADdhZ.js → serve-E0hSGe6_.js} +2 -2
- package/dist/{serve-Cc-ADdhZ.js.map → serve-E0hSGe6_.js.map} +1 -1
- package/dist/{stale-build-navigation-PnMLtTF8.js → stale-build-navigation-rg5xxmTr.js} +2 -2
- package/dist/{stale-build-navigation-PnMLtTF8.js.map → stale-build-navigation-rg5xxmTr.js.map} +1 -1
- package/dist/{start-Cb3kknlF.js → start-CifYPRq1.js} +34 -6
- package/dist/start-CifYPRq1.js.map +1 -0
- package/dist/tanstack-start-vite.d.ts +1 -1
- package/dist/tanstack-start.d.ts +2 -2
- package/dist/testing.d.ts +56 -0
- package/dist/testing.js +114 -0
- package/dist/testing.js.map +1 -0
- package/dist/{trailing-slash-DX7NB88H.d.ts → trailing-slash-CFSv_Gzx.d.ts} +2 -2
- package/dist/{types-DLYxYS6M.d.ts → types-j29vspx_.d.ts} +16 -2
- package/dist/vercel-pages.d.ts +32 -0
- package/dist/vercel-pages.js +54 -0
- package/dist/vercel-pages.js.map +1 -0
- package/dist/vercel-vite.d.ts +30 -9
- package/dist/vercel-vite.js +160 -17
- package/dist/vercel-vite.js.map +1 -1
- package/dist/vercel.d.ts +2 -2
- package/dist/vercel.js +2 -2
- package/dist/{vite-iioAoxSt.js → vite-BDREIgiH.js} +45 -33
- package/dist/vite-BDREIgiH.js.map +1 -0
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/package.json +5 -1
- package/dist/build-id-C6sYO9Yp.js.map +0 -1
- package/dist/build-manifest-UDNk81Ce.js.map +0 -1
- package/dist/create-server-DkTeIJ8L.js.map +0 -1
- package/dist/entry-CenmvESk.js +0 -116
- package/dist/entry-CenmvESk.js.map +0 -1
- package/dist/script-hashes-hqUk6kG7.js.map +0 -1
- package/dist/start-Cb3kknlF.js.map +0 -1
- package/dist/vite-iioAoxSt.js.map +0 -1
|
@@ -1,15 +1,424 @@
|
|
|
1
1
|
import { r as withRequestContext } from "./request-context-BtQ87VYb.js";
|
|
2
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-
|
|
3
|
+
import { c as presenceHeaders, l as presenceHeadersOf, o as checkOptionPlugins, r as buildId, s as optionPlugin } from "./build-id-B0448vZH.js";
|
|
4
4
|
import { i as requestLogger, r as jsonSink, t as errorAttributes } from "./log-BP6xXXZl.js";
|
|
5
5
|
import { n as finishResponse, r as onResponseSent } from "./response-edge-Bc1-C_Cx.js";
|
|
6
|
+
import { r as manifestKey } from "./build-manifest-DBMWe3Lx.js";
|
|
6
7
|
import { a as isCompressible, i as forbidsTransform, n as MIN_COMPRESS_BYTES, o as preferredEncoding, s as readIfQueued } from "./compression-7_gToa8R.js";
|
|
7
8
|
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
9
|
import { Hono } from "hono";
|
|
10
|
-
import { HTTPException } from "hono/http-exception";
|
|
11
|
-
import { matchedRoutes } from "hono/route";
|
|
12
10
|
import { getPath } from "hono/utils/url";
|
|
11
|
+
import { matchedRoutes } from "hono/route";
|
|
12
|
+
import { HTTPException } from "hono/http-exception";
|
|
13
|
+
|
|
14
|
+
// src/core/prefers-markdown.ts
|
|
15
|
+
/** A `q` value as RFC 9110 writes it: 0 to 1, with up to three decimals. */
|
|
16
|
+
const QVALUE = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;
|
|
17
|
+
/** The charset of each answer that a caller of {@link prefersMarkdown} sends. */
|
|
18
|
+
const CHARSET = "utf-8";
|
|
19
|
+
/**
|
|
20
|
+
* The parts of `value` between each `separator`. Why a scan, not `split`: a
|
|
21
|
+
* quoted parameter value can hold a `,` or a `;`.
|
|
22
|
+
*/
|
|
23
|
+
function splitOutsideQuotes(value, separator) {
|
|
24
|
+
const parts = [];
|
|
25
|
+
let part = "";
|
|
26
|
+
let quoted = false;
|
|
27
|
+
let escaped = false;
|
|
28
|
+
for (const character of value) if (!quoted && character === separator) {
|
|
29
|
+
parts.push(part);
|
|
30
|
+
part = "";
|
|
31
|
+
} else {
|
|
32
|
+
if (escaped) escaped = false;
|
|
33
|
+
else if (quoted && character === "\\") escaped = true;
|
|
34
|
+
else if (character === "\"") quoted = !quoted;
|
|
35
|
+
part += character;
|
|
36
|
+
}
|
|
37
|
+
parts.push(part);
|
|
38
|
+
return parts;
|
|
39
|
+
}
|
|
40
|
+
/** The parameters of a media range, by lowercase name, with quotes removed. */
|
|
41
|
+
function parameterMap(parameters) {
|
|
42
|
+
return new Map(parameters.map((parameter) => {
|
|
43
|
+
const index = parameter.indexOf("=");
|
|
44
|
+
const name = (index === -1 ? parameter : parameter.slice(0, index)).trim().toLowerCase();
|
|
45
|
+
const value = index === -1 ? "" : parameter.slice(index + 1).trim();
|
|
46
|
+
return [name, /^".*"$/su.test(value) ? value.slice(1, -1).replaceAll(/\\(?<character>.)/gsu, "$<character>") : value];
|
|
47
|
+
}));
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The media ranges of an `Accept` header. A missing `q` counts as 1, the RFC
|
|
51
|
+
* 9110 default. Why a malformed `q` also counts as 1: the client still named
|
|
52
|
+
* the media type.
|
|
53
|
+
*/
|
|
54
|
+
function mediaRanges(accept) {
|
|
55
|
+
return splitOutsideQuotes(accept, ",").map((entry) => {
|
|
56
|
+
const [type = "", ...parameters] = splitOutsideQuotes(entry, ";");
|
|
57
|
+
const parameterValues = parameterMap(parameters);
|
|
58
|
+
const quality = parameterValues.get("q") ?? "1";
|
|
59
|
+
return {
|
|
60
|
+
type: type.trim().toLowerCase(),
|
|
61
|
+
quality: QVALUE.test(quality) ? Number(quality) : 1,
|
|
62
|
+
charset: parameterValues.get("charset")?.toLowerCase()
|
|
63
|
+
};
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* The `q` of an answer of `type` in UTF-8, from the most specific ranges with
|
|
68
|
+
* that type, or `undefined` when no range matches it. A range with
|
|
69
|
+
* `charset=utf-8` is more specific than a range with no charset. A range with
|
|
70
|
+
* another charset does not match. Other parameters, such as `variant`, do not
|
|
71
|
+
* change the match.
|
|
72
|
+
*/
|
|
73
|
+
function qualityOf(ranges, type) {
|
|
74
|
+
const matches = ranges.filter((range) => range.type === type && (range.charset == null || range.charset === CHARSET));
|
|
75
|
+
const withCharset = matches.filter((range) => range.charset === CHARSET);
|
|
76
|
+
const specific = withCharset.length > 0 ? withCharset : matches;
|
|
77
|
+
return specific.length === 0 ? void 0 : Math.max(...specific.map((range) => range.quality));
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Whether a request asks for markdown before HTML, per
|
|
81
|
+
* https://acceptmarkdown.com. Use it to choose between the HTML and the
|
|
82
|
+
* markdown answer for one URL.
|
|
83
|
+
*
|
|
84
|
+
* The rules:
|
|
85
|
+
*
|
|
86
|
+
* - Only an explicit `text/markdown` range counts for markdown. A wildcard,
|
|
87
|
+
* such as `*\/*` or `text/*`, never selects markdown, so a browser and a
|
|
88
|
+
* client with no `Accept` get HTML.
|
|
89
|
+
* - `text/markdown;q=0` refuses markdown.
|
|
90
|
+
* - The `q` of markdown must be equal to or higher than the `q` of HTML. The
|
|
91
|
+
* `q` of HTML comes from the most specific range that matches it:
|
|
92
|
+
* `text/html`, then `text/*`, then `*\/*`. A tie selects markdown, because
|
|
93
|
+
* the client named it.
|
|
94
|
+
* - Both answers are UTF-8. A range with `charset=utf-8` is more specific
|
|
95
|
+
* than a range with no charset, and a range with another charset does not
|
|
96
|
+
* match. Other parameters, such as `variant`, do not change the match.
|
|
97
|
+
* - Media types and parameter names are not case-sensitive. A quoted
|
|
98
|
+
* parameter value can hold a `,` or a `;`.
|
|
99
|
+
*
|
|
100
|
+
* When the answer for a URL depends on this function, send `Vary: Accept` on
|
|
101
|
+
* both the HTML and the markdown answer. Else a shared cache can give the
|
|
102
|
+
* markdown to a browser.
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/markdown" } }));
|
|
106
|
+
* // => true
|
|
107
|
+
* prefersMarkdown(new Request("https://example.com/", { headers: { Accept: "text/html, text/markdown;q=0.5" } }));
|
|
108
|
+
* // => false
|
|
109
|
+
*/
|
|
110
|
+
function prefersMarkdown(request) {
|
|
111
|
+
const accept = request.headers.get("Accept");
|
|
112
|
+
if (accept == null || !/markdown/iu.test(accept)) return false;
|
|
113
|
+
const ranges = mediaRanges(accept);
|
|
114
|
+
const markdown = qualityOf(ranges, "text/markdown") ?? 0;
|
|
115
|
+
const html = qualityOf(ranges, "text/html") ?? qualityOf(ranges, "text/*") ?? qualityOf(ranges, "*/*") ?? 0;
|
|
116
|
+
return markdown > 0 && markdown >= html;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/core/safe-local-path.ts
|
|
120
|
+
/**
|
|
121
|
+
* Whether `value` is a safe same-origin path for a `Location` header. The
|
|
122
|
+
* value starts with one `/`, the next character is not `/` or `\`, and each
|
|
123
|
+
* character is printable ASCII (0x20 to 0x7E).
|
|
124
|
+
*
|
|
125
|
+
* The check stops these attacks:
|
|
126
|
+
*
|
|
127
|
+
* - An open redirect: `//evil.com`, `/\evil.com`, and `https://evil.com` go to
|
|
128
|
+
* another host. A browser reads `/\` as `//`.
|
|
129
|
+
* - A scheme that does not navigate, such as `javascript:` or `data:`.
|
|
130
|
+
* - A control character, such as CR or LF, that splits the response.
|
|
131
|
+
*
|
|
132
|
+
* Why strict: a short allow list is easy to audit. The check rejects some safe
|
|
133
|
+
* values, such as a path with raw UTF-8. Percent-encode the path first.
|
|
134
|
+
*
|
|
135
|
+
* Ported from the ngrok frontend `isSafeLocalPath`, with its test cases.
|
|
136
|
+
*
|
|
137
|
+
* @example
|
|
138
|
+
* isSafeLocalPath("/components/button?tab=props"); // => true
|
|
139
|
+
* isSafeLocalPath("//evil.com/foo"); // => false
|
|
140
|
+
* isSafeLocalPath("/café"); // => false
|
|
141
|
+
*/
|
|
142
|
+
function isSafeLocalPath(value) {
|
|
143
|
+
return /^\/(?![/\\])/u.test(value) && !/[^\u0020-\u007E]/u.test(value);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// src/core/plugins/trailing-slash.ts
|
|
147
|
+
/** Whether the last segment of a URL path has a dot, as a file name such as `llms.txt` or `x.data` has. */
|
|
148
|
+
function isFilePath(path) {
|
|
149
|
+
return path.slice(path.lastIndexOf("/") + 1).includes(".");
|
|
150
|
+
}
|
|
151
|
+
/** `path` with no trailing slashes. Why a scan, not `/\/+$/`: that regex takes quadratic time on a long run of slashes inside the path. */
|
|
152
|
+
function trimTrailingSlashes(path) {
|
|
153
|
+
let end = path.length;
|
|
154
|
+
while (end > 0 && path[end - 1] === "/") end -= 1;
|
|
155
|
+
return path.slice(0, end);
|
|
156
|
+
}
|
|
157
|
+
/** The URL path in `mode`, or the path unchanged when `mode` keeps it. */
|
|
158
|
+
function canonicalPath(path, mode) {
|
|
159
|
+
const trimmed = trimTrailingSlashes(path);
|
|
160
|
+
if (trimmed === "") return "/";
|
|
161
|
+
if (mode === "never") return trimmed;
|
|
162
|
+
if (mode === "always") return `${trimmed}/`;
|
|
163
|
+
return path;
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Whether one of the app's own Hono routes matches the request. Why the
|
|
167
|
+
* path: the plugins and the framework match at `/*`, and Hono matches a
|
|
168
|
+
* route path strictly, so a redirect would move the request off its route.
|
|
169
|
+
*/
|
|
170
|
+
function hasAppRoute(context) {
|
|
171
|
+
return matchedRoutes(context).some((route) => route.path !== "/*");
|
|
172
|
+
}
|
|
173
|
+
/** Whether `path`, a decoded URL path, names a file in `files`, not a directory. */
|
|
174
|
+
async function isStaticFile(files, path) {
|
|
175
|
+
return (await findStaticFile(files, path))?.path === path;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Sends a 308 from a page URL to the same URL in `mode`, so each page has one
|
|
179
|
+
* URL. It applies to rendered and prerendered pages, because the server cannot
|
|
180
|
+
* tell which paths have a route. The redirect keeps the query string.
|
|
181
|
+
*
|
|
182
|
+
* It sends no redirect for `/`, a method other than GET or HEAD, a data
|
|
183
|
+
* request of the framework, a path that one of the app's own Hono routes
|
|
184
|
+
* matches, such as `app.get("/livez")`, or a path that already has the
|
|
185
|
+
* mode's form. `always` adds no slash to a file in the client build, such as
|
|
186
|
+
* `/LICENSE`, or to a path whose last segment has a dot, such as `/llms.txt`.
|
|
187
|
+
*
|
|
188
|
+
* Set the same mode in the framework's router when it has one. Else the two
|
|
189
|
+
* redirects loop: the server sends `/x` to `/x/`, and the router sends `/x/`
|
|
190
|
+
* back to `/x`. For TanStack Start, check the mode against the router with
|
|
191
|
+
* `RouterTrailingSlash` from `@ngrok/app-server/tanstack-start`. React Router
|
|
192
|
+
* has no trailing-slash option, so it answers both forms itself.
|
|
193
|
+
*
|
|
194
|
+
* @example
|
|
195
|
+
* createServer({ plugins: defaultPlugins({ trailingSlash: "always" }) });
|
|
196
|
+
*/
|
|
197
|
+
function trailingSlash({ mode }) {
|
|
198
|
+
let stage;
|
|
199
|
+
return {
|
|
200
|
+
name: "trailing-slash",
|
|
201
|
+
setup: (info) => {
|
|
202
|
+
if (mode === "preserve") return;
|
|
203
|
+
stage = async (context, next) => {
|
|
204
|
+
const { method } = context.req;
|
|
205
|
+
if (method !== "GET" && method !== "HEAD" || info.isDataRequest(context.req.path) || hasAppRoute(context)) return next();
|
|
206
|
+
const url = new URL(context.req.url);
|
|
207
|
+
const path = canonicalPath(url.pathname, mode);
|
|
208
|
+
const location = `${path}${url.search}`;
|
|
209
|
+
if (path === url.pathname || !isSafeLocalPath(location)) return next();
|
|
210
|
+
if (mode === "always" && (isFilePath(context.req.path) || await isStaticFile(info.files, context.req.path))) return next();
|
|
211
|
+
return context.redirect(location, 308);
|
|
212
|
+
};
|
|
213
|
+
},
|
|
214
|
+
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// src/core/plugins/static.ts
|
|
219
|
+
const IMMUTABLE = "public, max-age=31536000, immutable";
|
|
220
|
+
/** The requests that the dev server answered. */
|
|
221
|
+
const devServerAnswers = /* @__PURE__ */ new WeakSet();
|
|
222
|
+
/**
|
|
223
|
+
* Whether the dev server answered the request, such as for a source module.
|
|
224
|
+
* Why: the access log writes no line for such a request, because one page
|
|
225
|
+
* load in development makes hundreds of them.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* await next();
|
|
229
|
+
* if (answeredByDevServer(context)) return;
|
|
230
|
+
*/
|
|
231
|
+
function answeredByDevServer(context) {
|
|
232
|
+
return devServerAnswers.has(context);
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Serves the hashed files under Vite's `build.assetsDir`, `/assets/` by
|
|
236
|
+
* default, with a one-year immutable cache. The `appServer` Vite plugin
|
|
237
|
+
* records the directory. A missing asset gets a plain 404 with
|
|
238
|
+
* `Cache-Control: no-store`, not a rendered page. In development, the dev
|
|
239
|
+
* server serves the source modules, the HMR client, and the CSS here instead.
|
|
240
|
+
*
|
|
241
|
+
* @example
|
|
242
|
+
* createServer({ plugins: [requestId(), accessLog(), streamingCompress(), assets(), prerendered()] });
|
|
243
|
+
*/
|
|
244
|
+
function assets() {
|
|
245
|
+
let stage;
|
|
246
|
+
return {
|
|
247
|
+
name: "assets",
|
|
248
|
+
setup: (info) => {
|
|
249
|
+
if (info.mode === "development") {
|
|
250
|
+
const { devServer } = info;
|
|
251
|
+
stage = async (context, next) => {
|
|
252
|
+
let passed = false;
|
|
253
|
+
const answer = await devServer(context, async () => {
|
|
254
|
+
passed = true;
|
|
255
|
+
await next();
|
|
256
|
+
});
|
|
257
|
+
if (!passed) devServerAnswers.add(context);
|
|
258
|
+
return answer;
|
|
259
|
+
};
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
const { files, contentTypes, assetsPath } = info;
|
|
263
|
+
stage = async (context, next) => {
|
|
264
|
+
const { method, path } = context.req;
|
|
265
|
+
if (!path.startsWith(assetsPath) || method !== "GET" && method !== "HEAD") return next();
|
|
266
|
+
const file = await findStaticFile(files, path);
|
|
267
|
+
if (file == null) return context.text("Not Found", 404, { "Cache-Control": "no-store" });
|
|
268
|
+
return staticResponse(context, {
|
|
269
|
+
files,
|
|
270
|
+
file,
|
|
271
|
+
headers: { "Cache-Control": IMMUTABLE },
|
|
272
|
+
contentTypes
|
|
273
|
+
});
|
|
274
|
+
};
|
|
275
|
+
},
|
|
276
|
+
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
const REVALIDATE = "public, max-age=0, must-revalidate";
|
|
280
|
+
const ONE_HOUR = "public, max-age=3600, stale-while-revalidate=86400";
|
|
281
|
+
/**
|
|
282
|
+
* The default markdown twin of a page: `/docs/button.md` for `/docs/button`,
|
|
283
|
+
* and `/index.md` for `/`. Why none for a rewritten request: `rewrite` sends
|
|
284
|
+
* it to another file or to the framework, so the page's twin does not match
|
|
285
|
+
* its answer.
|
|
286
|
+
*/
|
|
287
|
+
function defaultTwinOf(path, rewritten) {
|
|
288
|
+
return rewritten === path ? `${trimTrailingSlashes(path) || "/index"}.md` : void 0;
|
|
289
|
+
}
|
|
290
|
+
/** The file of the markdown twin of the request, or `undefined` when the page has none. */
|
|
291
|
+
async function findTwin(files, context, { twinOf, rewritten }) {
|
|
292
|
+
const twinPath = twinOf?.(context.req.path, rewritten, context);
|
|
293
|
+
const file = twinPath == null ? void 0 : await findStaticFile(files, twinPath);
|
|
294
|
+
return twinPath == null || file == null ? void 0 : {
|
|
295
|
+
path: twinPath,
|
|
296
|
+
file
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
/** Adds `Vary: Accept` to the answer for a path with a twin, so a shared cache keeps both answers. */
|
|
300
|
+
function varyOnAccept(context) {
|
|
301
|
+
const vary = withVary(context.res.headers.get("Vary"), "Accept");
|
|
302
|
+
if (vary != null) writableHeaders(context).set("Vary", vary);
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* The percent-encoded URL path for a decoded path, so it holds no space,
|
|
306
|
+
* `>`, or non-ASCII character. Why the replace: a URL removes a tab or a
|
|
307
|
+
* newline, which a file name can hold.
|
|
308
|
+
*/
|
|
309
|
+
function urlPath(path) {
|
|
310
|
+
return new URL(path.replaceAll(/[\t\n\r]/gu, (character) => encodeURIComponent(character)), "http://localhost").pathname;
|
|
311
|
+
}
|
|
312
|
+
/** Adds a `Link` to the twin at `twinPath`, so a client that does not ask for markdown can find it. */
|
|
313
|
+
function linkToTwin(context, twinPath) {
|
|
314
|
+
writableHeaders(context).append("Link", `<${urlPath(twinPath)}>; rel="alternate"; type="text/markdown"`);
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* The development stage of `markdownTwins`. The client build has no twins
|
|
318
|
+
* then, so a request that prefers markdown gets the framework's answer for
|
|
319
|
+
* the twin's URL: the route that prerenders the twin. A twin path that is not
|
|
320
|
+
* in `prerenderedPaths`, an error, or an answer that is not markdown sends the
|
|
321
|
+
* request on for the HTML.
|
|
322
|
+
*/
|
|
323
|
+
function developmentTwins(twinOf, { rewrite, skip }, prerenderedPaths) {
|
|
324
|
+
return async (context, next) => {
|
|
325
|
+
const { method, path } = context.req;
|
|
326
|
+
const twinPath = (method === "GET" || method === "HEAD") && skip?.(path) !== true && prefersMarkdown(context.req.raw) ? twinOf(path, rewrite?.(path, context) ?? path, context) : void 0;
|
|
327
|
+
if (twinPath == null || prerenderedPaths != null && !prerenderedPaths.has(twinPath) || !isFilePath$1(twinPath)) return next();
|
|
328
|
+
const url = new URL(context.req.url);
|
|
329
|
+
url.pathname = urlPath(twinPath);
|
|
330
|
+
if (getPath(new Request(url)) !== twinPath) return next();
|
|
331
|
+
const { headers, signal } = context.req.raw;
|
|
332
|
+
const twin = new Request(url, {
|
|
333
|
+
method,
|
|
334
|
+
headers,
|
|
335
|
+
signal
|
|
336
|
+
});
|
|
337
|
+
const response = await context.env.framework.fetch(twin, context);
|
|
338
|
+
const markdown = response.headers.get("Content-Type")?.toLowerCase().startsWith("text/markdown") === true;
|
|
339
|
+
if (response.status !== 304 && !(response.ok && markdown)) {
|
|
340
|
+
await response.body?.cancel();
|
|
341
|
+
return next();
|
|
342
|
+
}
|
|
343
|
+
context.res = response;
|
|
344
|
+
varyOnAccept(context);
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
/** The twin lookup that the `markdownTwins` option selects, or `undefined` when it is off. */
|
|
348
|
+
function twinOfOption(markdownTwins) {
|
|
349
|
+
if (markdownTwins === true) return defaultTwinOf;
|
|
350
|
+
if (markdownTwins == null || markdownTwins === false) return;
|
|
351
|
+
const { twinOf } = markdownTwins;
|
|
352
|
+
return (path, _rewritten, context) => twinOf(path, context);
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Serves the client build: prerendered pages at their own URL with a 200,
|
|
356
|
+
* plus every other file in it. It sends no redirect. The `trailingSlash`
|
|
357
|
+
* plugin does. Each response gets
|
|
358
|
+
* the headers its loader sent at build time (the `appServer` Vite plugin
|
|
359
|
+
* captures them), a `Cache-Control` (see `cacheControl`), an ETag, and a 304
|
|
360
|
+
* for a matching `If-None-Match`. A GET with one byte range gets a 206. A path
|
|
361
|
+
* with no file goes on to the framework. In development, only
|
|
362
|
+
* `markdownTwins` runs.
|
|
363
|
+
*
|
|
364
|
+
* At startup, it warns about each prerendered path that has no file.
|
|
365
|
+
*
|
|
366
|
+
* @example
|
|
367
|
+
* prerendered({
|
|
368
|
+
* headers: (path) => (path.startsWith("/api/") ? { "Access-Control-Allow-Origin": "*" } : undefined),
|
|
369
|
+
* });
|
|
370
|
+
*/
|
|
371
|
+
function prerendered(options = {}) {
|
|
372
|
+
let stage;
|
|
373
|
+
return {
|
|
374
|
+
name: "prerendered",
|
|
375
|
+
setup: async (info) => {
|
|
376
|
+
const twinOf = twinOfOption(options.markdownTwins);
|
|
377
|
+
if (info.mode === "development") {
|
|
378
|
+
const paths = info.prerenderedPaths;
|
|
379
|
+
stage = twinOf == null ? void 0 : developmentTwins(twinOf, options, paths == null ? void 0 : new Set(paths));
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
const { files, contentTypes, capturedHeaders } = info;
|
|
383
|
+
const missing = [];
|
|
384
|
+
for (const path of info.prerenderedPaths) if (await findStaticFile(files, path) == null) missing.push(path);
|
|
385
|
+
if (missing.length > 0) info.logger.log("warn", "prerendered paths with no file", { "app_server.missing_paths": missing });
|
|
386
|
+
const cacheControl = options.cacheControl ?? ((path) => {
|
|
387
|
+
const type = contentType(path, contentTypes);
|
|
388
|
+
return type.startsWith("text/html") || type.startsWith("text/markdown") || info.isDataRequest(path) ? REVALIDATE : ONE_HOUR;
|
|
389
|
+
});
|
|
390
|
+
const serve = async (context, path, file) => {
|
|
391
|
+
context.env.onServedFile?.(file.path);
|
|
392
|
+
const value = cacheControl(file.path);
|
|
393
|
+
const headers = new Headers(value == null ? void 0 : { "Cache-Control": value });
|
|
394
|
+
for (const layer of [capturedHeaders.get(manifestKey(path)), options.headers?.(path, context)]) for (const [name, layerValue] of Object.entries(layer ?? {})) headers.set(name, layerValue);
|
|
395
|
+
return staticResponse(context, {
|
|
396
|
+
files,
|
|
397
|
+
file,
|
|
398
|
+
headers: Object.fromEntries(headers),
|
|
399
|
+
contentTypes
|
|
400
|
+
});
|
|
401
|
+
};
|
|
402
|
+
stage = async (context, next) => {
|
|
403
|
+
const { method } = context.req;
|
|
404
|
+
if (method !== "GET" && method !== "HEAD" || options.skip?.(context.req.path) === true) return next();
|
|
405
|
+
const rewritten = options.rewrite?.(context.req.path, context) ?? context.req.path;
|
|
406
|
+
const twin = await findTwin(files, context, {
|
|
407
|
+
twinOf,
|
|
408
|
+
rewritten
|
|
409
|
+
});
|
|
410
|
+
const preferred = twin != null && prefersMarkdown(context.req.raw) ? twin : void 0;
|
|
411
|
+
const path = preferred?.path ?? rewritten;
|
|
412
|
+
const file = preferred?.file ?? await findStaticFile(files, path);
|
|
413
|
+
if (file == null) await next();
|
|
414
|
+
else context.res = await serve(context, path, file);
|
|
415
|
+
if (twin != null) varyOnAccept(context);
|
|
416
|
+
if (twin != null && preferred == null) linkToTwin(context, twin.path);
|
|
417
|
+
};
|
|
418
|
+
},
|
|
419
|
+
middleware: async (context, next) => stage == null ? next() : stage(context, next)
|
|
420
|
+
};
|
|
421
|
+
}
|
|
13
422
|
|
|
14
423
|
// src/core/plugins/access-log.ts
|
|
15
424
|
/**
|
|
@@ -36,6 +445,13 @@ function loggedReferer(referer, { redact }) {
|
|
|
36
445
|
* logs the response that leaves the server, after each stage. A listener
|
|
37
446
|
* with an `edge`, such as the node listener, counts the bytes.
|
|
38
447
|
*
|
|
448
|
+
* - A 5xx line has the level `error`, and each other line has the level `info`.
|
|
449
|
+
* - A line has `http.route` when the framework adapter gives the route
|
|
450
|
+
* pattern that it matched, such as `/domains/:domainId`.
|
|
451
|
+
* - In development, a request that Vite answers, such as a source module,
|
|
452
|
+
* gets no line.
|
|
453
|
+
* - A request of the build's check of the CDN pages gets no line.
|
|
454
|
+
*
|
|
39
455
|
* @example
|
|
40
456
|
* createServer({ plugins: [requestId(), accessLog({ redactQuery: false })] });
|
|
41
457
|
* // {"level":"info","message":"request","http.status_code":200,"network.bytes_written":5120,"duration":1830000,...}
|
|
@@ -48,10 +464,11 @@ function accessLog({ redactQuery = true, attributes, serverTiming = false } = {}
|
|
|
48
464
|
await (serverTiming ? withHeaderHook(context, next, (headers) => {
|
|
49
465
|
if (headers.get("Content-Type")?.startsWith("text/html") ?? false) headers.append("Server-Timing", `app;dur=${(performance.now() - started).toFixed(1)}`);
|
|
50
466
|
}) : next());
|
|
467
|
+
if (answeredByDevServer(context) || context.env?.onServedFile != null) return;
|
|
51
468
|
onResponseSent(context, (sent) => {
|
|
52
469
|
const line = lineAttributes(context, sent, started);
|
|
53
470
|
try {
|
|
54
|
-
context.get("logger").info("request", attributes == null ? line : {
|
|
471
|
+
context.get("logger")[sent.status >= 500 ? "error" : "info"]("request", attributes == null ? line : {
|
|
55
472
|
...line,
|
|
56
473
|
...attributes(context, sent)
|
|
57
474
|
});
|
|
@@ -82,6 +499,8 @@ function accessLog({ redactQuery = true, attributes, serverTiming = false } = {}
|
|
|
82
499
|
"network.bytes_written": bytes,
|
|
83
500
|
duration: Math.round((performance.now() - started) * 1e6)
|
|
84
501
|
};
|
|
502
|
+
const route = context.get("routePattern");
|
|
503
|
+
if (route != null) line["http.route"] = route;
|
|
85
504
|
if (aborted) line["http.client_aborted"] = true;
|
|
86
505
|
return line;
|
|
87
506
|
}
|
|
@@ -257,21 +676,33 @@ function health({ livePath = "/livez", readyPath = "/readyz", ready } = {}) {
|
|
|
257
676
|
|
|
258
677
|
// src/core/plugins/noindex.ts
|
|
259
678
|
/**
|
|
260
|
-
* Sets `X-Robots-Tag: noindex, nofollow` on each response,
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
679
|
+
* Sets `X-Robots-Tag: noindex, nofollow` on each response, or on each
|
|
680
|
+
* response to a request with no `unlessHeader`, so a search engine does not
|
|
681
|
+
* index a preview deploy.
|
|
682
|
+
*
|
|
683
|
+
* The `noindex` option of `defaultPlugins()` puts it
|
|
684
|
+
* before the static stages, so it also sees prerendered pages.
|
|
264
685
|
*
|
|
265
686
|
* @example
|
|
266
687
|
* defaultPlugins({ noindex: process.env.PREVIEW === "1" });
|
|
688
|
+
* defaultPlugins({ noindex: { unlessHeader: "x-ngrok-edge" } });
|
|
267
689
|
*/
|
|
268
|
-
function noindex() {
|
|
269
|
-
|
|
690
|
+
function noindex(options) {
|
|
691
|
+
const unlessHeader = options?.unlessHeader;
|
|
692
|
+
const plugin = optionPlugin("noindex", {
|
|
270
693
|
name: "noindex",
|
|
271
|
-
middleware: async (context, next) =>
|
|
272
|
-
|
|
273
|
-
|
|
694
|
+
middleware: async (context, next) => {
|
|
695
|
+
const hidden = unlessHeader == null || context.req.header(unlessHeader) == null;
|
|
696
|
+
await withHeaderHook(context, next, (response) => {
|
|
697
|
+
if (hidden) response.set("X-Robots-Tag", "noindex, nofollow");
|
|
698
|
+
if (unlessHeader != null) {
|
|
699
|
+
const vary = withVary(response.get("Vary"), unlessHeader);
|
|
700
|
+
if (vary != null) response.set("Vary", vary);
|
|
701
|
+
}
|
|
702
|
+
});
|
|
703
|
+
}
|
|
274
704
|
});
|
|
705
|
+
return unlessHeader == null ? plugin : presenceHeaders([unlessHeader], plugin);
|
|
275
706
|
}
|
|
276
707
|
|
|
277
708
|
// src/core/plugins/private-documents.ts
|
|
@@ -306,105 +737,6 @@ function privateDocuments() {
|
|
|
306
737
|
};
|
|
307
738
|
}
|
|
308
739
|
|
|
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
740
|
// src/core/plugins/redirects.ts
|
|
409
741
|
const PARAM = /^:(?<name>[A-Za-z_]\w*)$/u;
|
|
410
742
|
const TARGET_TOKEN = /:(?<name>[A-Za-z_]\w*)|\*/gu;
|
|
@@ -560,9 +892,10 @@ const DEFAULT_SECURITY_HEADERS = {
|
|
|
560
892
|
* - `Cross-Origin-Opener-Policy: same-origin`
|
|
561
893
|
* - `Strict-Transport-Security: max-age=31536000`, on an HTTPS request only
|
|
562
894
|
*
|
|
563
|
-
*
|
|
564
|
-
*
|
|
565
|
-
* value as a second policy,
|
|
895
|
+
* `Content-Security-Policy` and `Permissions-Policy` have no default. A
|
|
896
|
+
* response that has a header keeps its own value. The exception is
|
|
897
|
+
* `Content-Security-Policy`: the plugin adds a set value as a second policy,
|
|
898
|
+
* and a browser enforces both.
|
|
566
899
|
* `defaultPlugins()` puts it before the static stages, so it also sees
|
|
567
900
|
* prerendered pages.
|
|
568
901
|
*
|
|
@@ -572,6 +905,7 @@ const DEFAULT_SECURITY_HEADERS = {
|
|
|
572
905
|
* headers: {
|
|
573
906
|
* "Cross-Origin-Opener-Policy": "same-origin-allow-popups",
|
|
574
907
|
* "Content-Security-Policy": "frame-ancestors 'none'",
|
|
908
|
+
* "Permissions-Policy": "camera=(), microphone=(), geolocation=()",
|
|
575
909
|
* },
|
|
576
910
|
* },
|
|
577
911
|
* });
|
|
@@ -712,281 +1046,6 @@ function requestId({ headerName = "X-Request-Id", datadogTraceIds = false } = {}
|
|
|
712
1046
|
};
|
|
713
1047
|
}
|
|
714
1048
|
|
|
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
1049
|
// src/core/plugins/streaming-compress.ts
|
|
991
1050
|
/**
|
|
992
1051
|
* The most bytes that one pull of {@link replay} joins. Why 16 KiB: a source
|
|
@@ -1185,7 +1244,7 @@ function defaultPlugins(options = {}) {
|
|
|
1185
1244
|
streamingCompress(),
|
|
1186
1245
|
...options.securityHeaders === false ? [] : [securityHeaders(options.securityHeaders)],
|
|
1187
1246
|
...maxBytes === false ? [] : [bodyLimit({ maxBytes })],
|
|
1188
|
-
...options.noindex ===
|
|
1247
|
+
...options.noindex == null || options.noindex === false ? [] : [options.noindex === true ? noindex() : noindex(options.noindex)],
|
|
1189
1248
|
...options.buildId === false ? [] : [buildId(options.buildId)],
|
|
1190
1249
|
...options.contentSecurityPolicy == null ? [] : [contentSecurityPolicy(options.contentSecurityPolicy)],
|
|
1191
1250
|
...options.env == null ? [] : [options.env],
|
|
@@ -1323,6 +1382,7 @@ function createServer({ plugins = defaultPlugins(), logger = jsonSink(), listene
|
|
|
1323
1382
|
let stoppingPlugins;
|
|
1324
1383
|
const internals = {
|
|
1325
1384
|
logger,
|
|
1385
|
+
presenceHeaders: presenceHeadersOf(plugins),
|
|
1326
1386
|
setRequestStore: (store) => {
|
|
1327
1387
|
requestStore = store;
|
|
1328
1388
|
},
|
|
@@ -1405,5 +1465,5 @@ function serverInternals(app) {
|
|
|
1405
1465
|
return appInternals.get(app);
|
|
1406
1466
|
}
|
|
1407
1467
|
|
|
1408
|
-
export {
|
|
1409
|
-
//# sourceMappingURL=create-server-
|
|
1468
|
+
export { assets as _, streamingCompress as a, prefersMarkdown as b, securityHeaders as c, noindex as d, health as f, accessLog as g, bodyLimit as h, withForwardedProto as i, redirects as l, shutdownSignal as m, defaultPlugins as n, requestId as o, abortShutdownSignal as p, serverInternals as r, contentSecurityPolicy as s, createServer as t, privateDocuments as u, prerendered as v, trailingSlash as y };
|
|
1469
|
+
//# sourceMappingURL=create-server-jMl2ltHD.js.map
|