brumate 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/dist/{boot-DN1ZU8Hg.d.ts → boot-D-IdPy7B.d.ts} +24 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/client-C0UCNL3J.js +1643 -0
  4. package/dist/client-C0UCNL3J.js.map +1 -0
  5. package/dist/{client-DwJInP_a.d.ts → client-MD0ZmcFR.d.ts} +101 -26
  6. package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
  7. package/dist/client-routes-JTbGtukf.js.map +1 -0
  8. package/dist/context-CTiSzQRc.js +27 -0
  9. package/dist/context-CTiSzQRc.js.map +1 -0
  10. package/dist/context-btHuB01Z.d.ts +42 -0
  11. package/dist/defer-D0bo1Gqx.js +52 -0
  12. package/dist/defer-D0bo1Gqx.js.map +1 -0
  13. package/dist/{devtools-BKjnHrnv.js → devtools-C50VH8gZ.js} +2 -2
  14. package/dist/devtools-C50VH8gZ.js.map +1 -0
  15. package/dist/{devtools-panel-AWOn0VK2.js → devtools-panel-AYjfwPhj.js} +4 -3
  16. package/dist/devtools-panel-AYjfwPhj.js.map +1 -0
  17. package/dist/events-BKWRqtMg.js +52 -0
  18. package/dist/events-BKWRqtMg.js.map +1 -0
  19. package/dist/{files-DdT84mPy.js → files-Bnn1JqHx.js} +18 -3
  20. package/dist/files-Bnn1JqHx.js.map +1 -0
  21. package/dist/{html-DEeoepg3.js → html-bHZbkK-h.js} +26 -8
  22. package/dist/html-bHZbkK-h.js.map +1 -0
  23. package/dist/{html-Du8jY2Cc.d.ts → html-y1q7-t7D.d.ts} +12 -5
  24. package/dist/index.d.ts +77 -29
  25. package/dist/index.js +12 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/{inspect-BPchdWbU.js → inspect-BJtACnQp.js} +784 -82
  28. package/dist/inspect-BJtACnQp.js.map +1 -0
  29. package/dist/{loader-Dc9OwY5I.js → loader-B18i3_-T.js} +46 -11
  30. package/dist/loader-B18i3_-T.js.map +1 -0
  31. package/dist/{navigate-CzLjnoPH.js → navigate-BwuZveDF.js} +71 -12
  32. package/dist/navigate-BwuZveDF.js.map +1 -0
  33. package/dist/{produce-BRGHP7e0.js → produce-CWfJ4byV.js} +43 -2
  34. package/dist/produce-CWfJ4byV.js.map +1 -0
  35. package/dist/{produce-CtZ32UGG.d.ts → produce-D4K7qpaL.d.ts} +23 -11
  36. package/dist/routes-BZNt7DSZ.d.ts +38 -0
  37. package/dist/{rpc-9fSqL_YK.js → rpc-B-Zkn6Ch.js} +24 -18
  38. package/dist/rpc-B-Zkn6Ch.js.map +1 -0
  39. package/dist/runtime/batch.d.ts +23 -0
  40. package/dist/runtime/batch.js +69 -0
  41. package/dist/runtime/batch.js.map +1 -0
  42. package/dist/runtime/client.d.ts +5 -5
  43. package/dist/runtime/client.js +5 -1345
  44. package/dist/runtime/context.d.ts +2 -2
  45. package/dist/runtime/context.js +1 -1
  46. package/dist/runtime/devtools.d.ts +5 -4
  47. package/dist/runtime/devtools.js +1 -1
  48. package/dist/runtime/env.d.ts +44 -0
  49. package/dist/runtime/env.js +61 -0
  50. package/dist/runtime/env.js.map +1 -0
  51. package/dist/runtime/events.d.ts +27 -0
  52. package/dist/runtime/events.js +1 -0
  53. package/dist/runtime/hot.d.ts +1 -1
  54. package/dist/runtime/html.d.ts +2 -2
  55. package/dist/runtime/html.js +1 -1
  56. package/dist/runtime/loader.d.ts +2 -2
  57. package/dist/runtime/loader.js +2 -2
  58. package/dist/runtime/routes.d.ts +2 -21
  59. package/dist/runtime/routes.js +31 -1
  60. package/dist/runtime/routes.js.map +1 -1
  61. package/dist/runtime/server.d.ts +6 -5
  62. package/dist/runtime/server.js +5 -6
  63. package/dist/runtime/signals.d.ts +22 -1
  64. package/dist/runtime/signals.js +29 -1
  65. package/dist/runtime/signals.js.map +1 -1
  66. package/dist/runtime/static-loader.d.ts +2 -2
  67. package/dist/runtime/static-loader.js +1 -1
  68. package/dist/runtime/testing.d.ts +46 -5
  69. package/dist/runtime/testing.js +240 -33
  70. package/dist/runtime/testing.js.map +1 -1
  71. package/dist/secrets-BxagsJxJ.js +23 -0
  72. package/dist/secrets-BxagsJxJ.js.map +1 -0
  73. package/dist/{server-BxqjLUnV.d.ts → server-BA9SJ2Vm.d.ts} +544 -106
  74. package/dist/server-BqfM95r1.js +2762 -0
  75. package/dist/server-BqfM95r1.js.map +1 -0
  76. package/dist/skew-FRmAy9iy.js +49 -0
  77. package/dist/skew-FRmAy9iy.js.map +1 -0
  78. package/dist/standard-schema-BNY82yX3.d.ts +63 -0
  79. package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-BzE9SRaj.d.ts} +2 -2
  80. package/dist/{static-loader-ClNkHZGn.js → static-loader-DOygOFj5.js} +52 -21
  81. package/dist/static-loader-DOygOFj5.js.map +1 -0
  82. package/dist/{stream-bgNCMcaA.js → stream-JaMHMdBD.js} +126 -61
  83. package/dist/stream-JaMHMdBD.js.map +1 -0
  84. package/dist/vite.d.ts +42 -1
  85. package/dist/vite.js +435 -55
  86. package/dist/vite.js.map +1 -1
  87. package/package.json +15 -2
  88. package/types.d.ts +9 -1
  89. package/dist/client-routes-DakuM32C.js.map +0 -1
  90. package/dist/context-BG8KCF3v.js +0 -15
  91. package/dist/context-BG8KCF3v.js.map +0 -1
  92. package/dist/context-aeo9esY9.d.ts +0 -16
  93. package/dist/devtools-BKjnHrnv.js.map +0 -1
  94. package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
  95. package/dist/files-DdT84mPy.js.map +0 -1
  96. package/dist/html-DEeoepg3.js.map +0 -1
  97. package/dist/inspect-BPchdWbU.js.map +0 -1
  98. package/dist/loader-Dc9OwY5I.js.map +0 -1
  99. package/dist/navigate-CzLjnoPH.js.map +0 -1
  100. package/dist/produce-BRGHP7e0.js.map +0 -1
  101. package/dist/rpc-9fSqL_YK.js.map +0 -1
  102. package/dist/runtime/client.js.map +0 -1
  103. package/dist/server-DZsgnPKS.js +0 -1615
  104. package/dist/server-DZsgnPKS.js.map +0 -1
  105. package/dist/shared-CWYOd0H3.js +0 -40
  106. package/dist/shared-CWYOd0H3.js.map +0 -1
  107. package/dist/static-loader-ClNkHZGn.js.map +0 -1
  108. package/dist/stream-bgNCMcaA.js.map +0 -1
@@ -0,0 +1,2762 @@
1
+ import { n as MODIFIERS } from "./events-BKWRqtMg.js";
2
+ import { c as escape, d as isRaw, g as styleElement, h as spread$1, l as escapeAttribute, m as rawHTML, n as actionAttributes, t as VOID_ELEMENTS, u as insertValue } from "./html-bHZbkK-h.js";
3
+ import { a as disabledFeatures, c as functionReferences, i as callPlugins, o as plugins, r as toChunkStream, s as syncPlugins, t as STREAM_TYPE } from "./stream-JaMHMdBD.js";
4
+ import { a as parseId, i as isAsyncIterable, n as ElementReference, r as FunctionReference } from "./produce-CWfJ4byV.js";
5
+ import { n as serverSecrets } from "./secrets-BxagsJxJ.js";
6
+ import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-Av5WFmcf.js";
7
+ import "./context-CTiSzQRc.js";
8
+ import { crossSerialize, crossSerializeStream, fromJSON, toJSON } from "seroval";
9
+ //#region src/runtime/request.ts
10
+ /**
11
+ * A request that the server handles: a server function call, a form post,
12
+ * a page render, or a call of middleware or an endpoint. Its methods read
13
+ * the request and change the response. Get it with `getEvent()`.
14
+ */
15
+ var RequestEvent = class {
16
+ request;
17
+ /** What the request is for. */
18
+ kind;
19
+ /** For a call, and a page that a form posted to, the server function and its arguments. */
20
+ call;
21
+ /** Values for this request, which middleware writes and the rest of the request reads. */
22
+ locals = {};
23
+ /** The address of the client as the server saw it, when the server passed it. */
24
+ address;
25
+ /** True while the build prerenders the page. */
26
+ prerender;
27
+ /**
28
+ * The pattern of the route files that matched the path, such as
29
+ * `/todos/[id]`. `handleRoute` sets it. Undefined for a path that no route
30
+ * matches.
31
+ */
32
+ route;
33
+ /** Headers to add to the response, such as `cache-control`. */
34
+ headers = new Headers();
35
+ /** The status that `setStatus` set. */
36
+ status;
37
+ /** Server functions that `refresh` named, whose memos the client loads again. */
38
+ refreshed;
39
+ /** Cookies that this request set, or deleted with undefined, so later reads see them. */
40
+ cookies;
41
+ controller = new AbortController();
42
+ /**
43
+ * Aborts when the request no longer needs an answer: the request's own
44
+ * signal aborts, or the reader of the response went away, such as a
45
+ * browser that left the page while it streamed. Pass it on, such as to
46
+ * `fetch(url, { signal })`, so work that nobody waits for stops.
47
+ */
48
+ signal = this.controller.signal;
49
+ keepGoing;
50
+ constructor(request, options = {}) {
51
+ this.request = request;
52
+ this.kind = options.kind ?? "page";
53
+ this.keepGoing = options.waitUntil;
54
+ this.address = options.address;
55
+ this.prerender = options.prerender ?? false;
56
+ const outer = request.signal;
57
+ if (outer?.aborted) this.controller.abort(outer.reason);
58
+ else outer?.addEventListener("abort", () => this.abort(outer.reason), { once: true });
59
+ }
60
+ /** Aborts `signal`, such as when the response's reader went away. The server calls it. */
61
+ abort(reason) {
62
+ if (!this.signal.aborted) this.controller.abort(reason);
63
+ }
64
+ /**
65
+ * Keeps work going after the response ends, such as a log line or
66
+ * analytics. On a host that stops a function when its response ends, the
67
+ * server passes the promise to the host, through the `waitUntil` option.
68
+ * Elsewhere the promise runs on its own, and its error is logged.
69
+ */
70
+ waitUntil(promise) {
71
+ if (this.keepGoing) this.keepGoing(promise);
72
+ else promise.catch((error) => console.error(error));
73
+ }
74
+ /**
75
+ * Sets the status of the page response, such as 404 for a page that shows
76
+ * that nothing was found. It works while the first render of a page runs.
77
+ * Markup that streams later, such as a `#loading` body, cannot change it,
78
+ * because the response has started by then.
79
+ */
80
+ setStatus(status) {
81
+ this.status = status;
82
+ }
83
+ /**
84
+ * Asks the client to load again the memos that call a server function, such
85
+ * as a list after a server function adds to it. The compiler gives those
86
+ * memos client code, so they can load.
87
+ */
88
+ refresh(fn) {
89
+ this.refreshed ??= /* @__PURE__ */ new Set();
90
+ this.refreshed.add(unwrap(fn));
91
+ }
92
+ /** The cookies of the request, with the ones that this request set or deleted. */
93
+ getCookies() {
94
+ return getCookies(this);
95
+ }
96
+ /** A cookie of the request, or the value that this request set. */
97
+ getCookie(name) {
98
+ return getCookies(this)[name];
99
+ }
100
+ /**
101
+ * Sets a cookie on the response. It is `HttpOnly`, `SameSite=Lax` and on
102
+ * the path `/` unless the options say otherwise, and `Secure` on HTTPS.
103
+ * Markup that streams later, such as a `#loading` body, cannot set cookies,
104
+ * because the response has started.
105
+ */
106
+ setCookie(name, value, options = {}) {
107
+ setCookie(this, name, value, options);
108
+ }
109
+ /** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */
110
+ deleteCookie(name, options = {}) {
111
+ deleteCookie(this, name, options);
112
+ }
113
+ };
114
+ /**
115
+ * The event of the code that runs now. The runtime sets it while it calls a
116
+ * server function, middleware, an endpoint or a memo, and clears it as soon
117
+ * as the call returns, which is at its first `await`. One request at a time
118
+ * runs until an `await`, so it is never the event of another request.
119
+ */
120
+ let current;
121
+ /** The results of server function calls of the render that runs now, by function and arguments. */
122
+ let currentCalls;
123
+ globalThis[Symbol.for("brumate.inRequest")] = () => current !== void 0 || currentCalls !== void 0;
124
+ /**
125
+ * Runs a callback with an event, so `getEvent()` in its code before its first
126
+ * `await` returns it. Returns what the callback returns, such as its promise.
127
+ * `calls`, while a page renders, lets calls with the same arguments share a result.
128
+ */
129
+ function withEvent(event, callback, calls) {
130
+ const outer = current;
131
+ const outerCalls = currentCalls;
132
+ current = event;
133
+ currentCalls = calls;
134
+ try {
135
+ return callback();
136
+ } finally {
137
+ current = outer;
138
+ currentCalls = outerCalls;
139
+ }
140
+ }
141
+ /**
142
+ * Returns the event of the request that the server handles: in a server
143
+ * function, middleware or an endpoint, or while a component renders.
144
+ *
145
+ * Call it before the first `await` of the function, and keep it in a
146
+ * variable. After an `await`, other requests may have run, so it throws.
147
+ *
148
+ * ```ts
149
+ * async function save(todo: Todo) {
150
+ * 'use server';
151
+ * const event = getEvent();
152
+ * await db.save(todo);
153
+ * event.setCookie('saved', todo.id);
154
+ * }
155
+ * ```
156
+ */
157
+ function getEvent() {
158
+ if (!current) throw new Error("getEvent() works in server functions, middleware and endpoints before their first await, and while a component renders. Call it at the start of the function, keep the event in a variable, and pass it to helpers");
159
+ return current;
160
+ }
161
+ /**
162
+ * Types the middleware of the entry file, `src/middleware.ts`, which the
163
+ * Vite plugin runs for every request:
164
+ *
165
+ * ```ts
166
+ * export default defineMiddleware(async (event, next) => {
167
+ * event.locals.user = await readUser(event);
168
+ * return next();
169
+ * });
170
+ * ```
171
+ */
172
+ function defineMiddleware(middleware) {
173
+ return middleware;
174
+ }
175
+ /**
176
+ * Runs the middleware of the entry, when there is one, around an answer.
177
+ * `getEvent()` works in the middleware before its first `await`.
178
+ */
179
+ function runEntry(middleware, event, answer) {
180
+ if (!middleware) return answer();
181
+ return Promise.resolve(withEvent(event, () => middleware(event, answer)));
182
+ }
183
+ /**
184
+ * Wraps a server function, so its calls while a page renders share a result
185
+ * when their arguments are the same. Calls from the browser, which are
186
+ * requests of their own, always run, so a function that changes something
187
+ * runs each time.
188
+ */
189
+ function dedupe(fn, id) {
190
+ const wrapper = ((...args) => {
191
+ const cache = currentCalls;
192
+ if (!cache) return fn(...args);
193
+ let key;
194
+ try {
195
+ key = `${id} ${JSON.stringify(toJSON(args, {
196
+ plugins: syncPlugins,
197
+ disabledFeatures
198
+ }))}`;
199
+ } catch {
200
+ return fn(...args);
201
+ }
202
+ if (!cache.has(key)) cache.set(key, fn(...args));
203
+ return cache.get(key);
204
+ });
205
+ Object.defineProperty(wrapper, ORIGINAL, { value: fn });
206
+ return wrapper;
207
+ }
208
+ /**
209
+ * The function that `dedupe` wrapped, on its wrapper. A symbol of the
210
+ * registry, so two copies of the runtime agree on it.
211
+ */
212
+ const ORIGINAL = Symbol.for("brumate.original");
213
+ /**
214
+ * The server function itself, for a wrapper that `dedupe` made. `refresh`
215
+ * and `$action` compare server functions, and the registry holds them unwrapped.
216
+ */
217
+ function unwrap(fn) {
218
+ return fn?.[ORIGINAL] ?? fn;
219
+ }
220
+ /**
221
+ * An error whose message reaches the client. A server function call that
222
+ * throws it rejects with the message, and the response has its status.
223
+ * Other errors reach the client as a generic message, so server details stay
224
+ * on the server.
225
+ */
226
+ var ServerError = class extends Error {
227
+ status;
228
+ constructor(message, options = {}) {
229
+ super(message);
230
+ this.name = "ServerError";
231
+ this.status = options.status ?? 400;
232
+ }
233
+ };
234
+ /** Thrown by `redirect`. */
235
+ var Redirect = class extends Error {
236
+ location;
237
+ status;
238
+ constructor(location, status) {
239
+ super(`Redirect to ${location}`);
240
+ this.name = "Redirect";
241
+ this.location = location;
242
+ this.status = status;
243
+ }
244
+ };
245
+ /**
246
+ * Stops a server function and sends the browser to another page. While a
247
+ * page renders, the error reaches the caller of `render`, which can
248
+ * answer with a redirect.
249
+ */
250
+ function redirect(location, status = 303) {
251
+ throw new Redirect(location, status);
252
+ }
253
+ function isRedirect(error) {
254
+ return error instanceof Redirect;
255
+ }
256
+ //#endregion
257
+ //#region src/runtime/router.ts
258
+ function key(path, file, params) {
259
+ return `${path}/${file} ${JSON.stringify(params)}`;
260
+ }
261
+ /** Puts a view in the children slot of a layout, with its other slots. */
262
+ function wrap(view, wrapper) {
263
+ return wrapper ? {
264
+ load: wrapper.layout,
265
+ key: wrapper.key,
266
+ slots: {
267
+ ...wrapper.slots,
268
+ children: view
269
+ }
270
+ } : view;
271
+ }
272
+ /** The layout of a folder, or undefined when it has none. */
273
+ function wrapperOf(node, segments, index, params, path) {
274
+ return node.layout ? {
275
+ layout: node.layout,
276
+ key: key(path, "_layout", params),
277
+ slots: namedSlots(node, segments, index, params, path)
278
+ } : void 0;
279
+ }
280
+ /** The `_error.brm` of a folder, inside its layout. */
281
+ function errorIn(error, wrapper, params, path) {
282
+ return wrap({
283
+ load: error,
284
+ key: key(path, ERROR_VIEW, params),
285
+ slots: {}
286
+ }, wrapper);
287
+ }
288
+ /** The slots of a layout other than `children`, each matched against the same path. */
289
+ function namedSlots(node, segments, index, params, path) {
290
+ const slots = {};
291
+ for (const [name, slot] of Object.entries(node.slots ?? {})) {
292
+ const match = matchNode(slot, segments, index, params, `${path}/@${name}`);
293
+ if (match) slots[name] = match.view;
294
+ else if (slot.fallback) slots[name] = {
295
+ load: slot.fallback,
296
+ key: key(`${path}/@${name}`, "_default", params),
297
+ slots: {}
298
+ };
299
+ }
300
+ return slots;
301
+ }
302
+ /** The view of an `_error.brm`. Its component gets the error as a prop. */
303
+ const ERROR_VIEW = "_error";
304
+ /**
305
+ * Matches the segments from `index` on. `path` is the folders of `node` in
306
+ * the route files, such as `/todos/[id]`.
307
+ */
308
+ function matchNode(node, segments, index, params, path = "") {
309
+ let inner;
310
+ if (index === segments.length) {
311
+ if (node.page || node.endpoint) inner = {
312
+ view: {
313
+ load: node.page ?? missingPage,
314
+ key: key(path, "index", params),
315
+ slots: {}
316
+ },
317
+ params,
318
+ route: path || "/",
319
+ endpoint: node.endpoint,
320
+ middleware: [],
321
+ errors: []
322
+ };
323
+ } else {
324
+ const first = segments[index];
325
+ const fixed = node.static?.[first];
326
+ inner = fixed && matchNode(fixed, segments, index + 1, params, `${path}/${first}`);
327
+ if (!inner && node.dynamic) {
328
+ const { name } = node.dynamic;
329
+ inner = matchNode(node.dynamic.node, segments, index + 1, {
330
+ ...params,
331
+ [name]: first
332
+ }, `${path}/[${name}]`);
333
+ }
334
+ if (!inner && node.rest) {
335
+ const { name } = node.rest;
336
+ inner = matchNode(node.rest.node, segments, segments.length, {
337
+ ...params,
338
+ [name]: segments.slice(index).join("/")
339
+ }, `${path}/[...${name}]`);
340
+ }
341
+ }
342
+ if (!inner) return;
343
+ const content = node.loading ? {
344
+ ...inner.view,
345
+ loading: node.loading
346
+ } : inner.view;
347
+ const wrapper = wrapperOf(node, segments, index, params, path);
348
+ const errors = wrapper ? inner.errors.map((view) => wrap(view, wrapper)) : inner.errors;
349
+ if (node.error) errors.push(errorIn(node.error, wrapper, params, path));
350
+ return {
351
+ view: wrap(content, wrapper),
352
+ params: inner.params,
353
+ route: inner.route,
354
+ endpoint: inner.endpoint,
355
+ middleware: node.middleware ? [node.middleware, ...inner.middleware] : inner.middleware,
356
+ errors
357
+ };
358
+ }
359
+ /** An endpoint without a page: a GET that it does not answer has no page either. */
360
+ const missingPage = () => {
361
+ throw new Error("This path has an endpoint and no page");
362
+ };
363
+ /** Finds the route for a path. A path with a malformed escape, such as `/%E0`, matches none. */
364
+ function matchRoute(tree, pathname) {
365
+ let segments;
366
+ try {
367
+ segments = pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment));
368
+ } catch {
369
+ return;
370
+ }
371
+ return matchNode(tree, segments, 0, {});
372
+ }
373
+ /**
374
+ * The views for a path that no route matches: the `_error.brm` of the
375
+ * root, inside the root layout, and the root middleware.
376
+ */
377
+ function notFound(tree) {
378
+ return {
379
+ errors: tree.error ? [errorIn(tree.error, wrapperOf(tree, [], 0, {}, ""), {}, "")] : [],
380
+ middleware: tree.middleware ? [tree.middleware] : []
381
+ };
382
+ }
383
+ //#endregion
384
+ //#region src/runtime/validate.ts
385
+ /**
386
+ * The error that `parse` throws when the value does not match. It answers
387
+ * with status 400 and its message, as any `ServerError` does. Its `issues`
388
+ * stay on the server.
389
+ */
390
+ var ValidationError = class extends ServerError {
391
+ issues;
392
+ constructor(issues) {
393
+ super(summary(issues), { status: 400 });
394
+ this.name = "ValidationError";
395
+ this.issues = issues;
396
+ }
397
+ };
398
+ /** The longest message that `parse` sends, so a long input in a message stays short. */
399
+ const MAX_MESSAGE = 300;
400
+ /** The message of a `ValidationError`: the first issue with its path, and how many others there are. */
401
+ function summary(issues) {
402
+ const first = issues[0];
403
+ if (!first) return "Invalid input";
404
+ const path = first.path?.join(".");
405
+ let message = path ? `${path}: ${first.message}` : first.message;
406
+ if (message.length > MAX_MESSAGE) message = `${message.slice(0, MAX_MESSAGE)}…`;
407
+ const more = issues.length - 1;
408
+ return more > 0 ? `${message} (${more} more ${more === 1 ? "issue" : "issues"})` : message;
409
+ }
410
+ /**
411
+ * Copies an issue as plain data. A `{ key }` segment becomes its key, and a
412
+ * symbol becomes its text, such as `Symbol(id)`. Other fields of the issue,
413
+ * which some libraries add, are left out, so the input is not sent back.
414
+ */
415
+ function plainIssue(issue) {
416
+ const plain = { message: String(issue.message) };
417
+ if (issue.path && issue.path.length > 0) plain.path = issue.path.map((segment) => {
418
+ const key = typeof segment === "object" && segment !== null ? segment.key : segment;
419
+ return typeof key === "number" ? key : String(key);
420
+ });
421
+ return plain;
422
+ }
423
+ /**
424
+ * Validates a value with a Standard Schema. Returns `{ value }` with the
425
+ * output of the schema, or `{ issues }` as plain data. It does not throw for
426
+ * a value that does not match.
427
+ */
428
+ async function safeParse(schema, value) {
429
+ const props = schema["~standard"];
430
+ if (props?.version !== 1 || typeof props.validate !== "function") throw new TypeError("The schema is not a Standard Schema of version 1");
431
+ const result = await props.validate(value);
432
+ if (result.issues) return { issues: result.issues.map(plainIssue) };
433
+ return { value: result.value };
434
+ }
435
+ /**
436
+ * Validates a value with a Standard Schema, and returns the output of the
437
+ * schema. A value that does not match throws a `ValidationError`, which
438
+ * answers with status 400 and a message built from the first issue.
439
+ *
440
+ * ```ts
441
+ * async function save(input: unknown) {
442
+ * 'use server';
443
+ * const todo = await parse(Todo, input);
444
+ * await db.todos.save(todo);
445
+ * }
446
+ * ```
447
+ */
448
+ async function parse(schema, value) {
449
+ const result = await safeParse(schema, value);
450
+ if (result.issues) throw new ValidationError(result.issues);
451
+ return result.value;
452
+ }
453
+ /** Names that would change the prototype of an object, or reach the one of its constructor. */
454
+ const FORBIDDEN = /* @__PURE__ */ new Set([
455
+ "__proto__",
456
+ "constructor",
457
+ "prototype"
458
+ ]);
459
+ /**
460
+ * Turns the entries of a form into a plain object:
461
+ *
462
+ * - A name that appears once holds its value.
463
+ * - A name that appears more than once holds an array of its values.
464
+ * - A name that ends with `[]` always holds an array, under the name without `[]`.
465
+ * - Dots nest objects: `address.city` is `{ address: { city } }`.
466
+ * - Values stay strings and files.
467
+ *
468
+ * A name with an empty part, a part such as `__proto__`, or one that needs
469
+ * an object where another field holds a value, is an issue, and the schema
470
+ * does not run.
471
+ */
472
+ function formValues(form) {
473
+ const root = {};
474
+ const objects = /* @__PURE__ */ new Set([root]);
475
+ const arrays = /* @__PURE__ */ new Set();
476
+ const issues = [];
477
+ for (const [name, value] of form) {
478
+ const list = name.endsWith("[]");
479
+ const parts = (list ? name.slice(0, -2) : name).split(".");
480
+ if (parts.some((part) => part === "" || FORBIDDEN.has(part))) {
481
+ issues.push({ message: "The form has a field name that is not allowed" });
482
+ continue;
483
+ }
484
+ let target = root;
485
+ let conflict = false;
486
+ for (const part of parts.slice(0, -1)) {
487
+ const next = Object.hasOwn(target, part) ? target[part] : void 0;
488
+ if (next === void 0) {
489
+ const child = {};
490
+ objects.add(child);
491
+ target[part] = child;
492
+ target = child;
493
+ } else if (objects.has(next)) target = next;
494
+ else {
495
+ conflict = true;
496
+ break;
497
+ }
498
+ }
499
+ const last = parts.at(-1);
500
+ const current = Object.hasOwn(target, last) ? target[last] : void 0;
501
+ if (conflict || objects.has(current)) issues.push({
502
+ message: `Field "${name}" conflicts with another field`,
503
+ path: parts
504
+ });
505
+ else if (arrays.has(current)) current.push(value);
506
+ else if (current !== void 0 || list) {
507
+ const values = current === void 0 ? [value] : [current, value];
508
+ arrays.add(values);
509
+ target[last] = values;
510
+ } else target[last] = value;
511
+ }
512
+ return issues.length > 0 ? { issues } : { value: root };
513
+ }
514
+ /**
515
+ * Validates the data of a form with a Standard Schema. The entries become a
516
+ * plain object first. Returns `{ value }` or `{ issues }`, and does not throw
517
+ * for data that does not match, so a function of `$action` can return the
518
+ * issues for the page to show.
519
+ *
520
+ * ```ts
521
+ * async function signUp(form: FormData) {
522
+ * 'use server';
523
+ * const result = await parseForm(SignUp, form);
524
+ * if (result.issues) {
525
+ * return { errors: fieldErrors(result.issues) };
526
+ * }
527
+ * }
528
+ * ```
529
+ */
530
+ async function parseForm(schema, form) {
531
+ const values = formValues(form);
532
+ if (values.issues) return { issues: values.issues };
533
+ return safeParse(schema, values.value);
534
+ }
535
+ /**
536
+ * The messages of issues by field, for a page to show next to each field.
537
+ * The key is the path joined with dots, such as `address.city`. Issues
538
+ * without a path, and a path of `__proto__`, are under the key `''`. The
539
+ * result is plain data, so a server function can return it.
540
+ */
541
+ function fieldErrors(issues) {
542
+ const errors = {};
543
+ for (const issue of issues) {
544
+ let key = plainIssue(issue).path?.join(".") ?? "";
545
+ if (key === "__proto__") key = "";
546
+ (Object.hasOwn(errors, key) ? errors[key] : errors[key] = []).push(String(issue.message));
547
+ }
548
+ return errors;
549
+ }
550
+ //#endregion
551
+ //#region src/runtime/rate-limit.ts
552
+ /**
553
+ * The error of a request over its limit. Its status is 429, and
554
+ * `retryAfter` is how many seconds to wait. In the browser, the call rejects
555
+ * with it, and `retryAfter` comes from the `Retry-After` header.
556
+ */
557
+ var RateLimitError = class extends ServerError {
558
+ retryAfter;
559
+ constructor(retryAfter) {
560
+ super(`Too many requests. Try again in ${retryAfter} ${retryAfter === 1 ? "second" : "seconds"}`, { status: 429 });
561
+ this.name = "RateLimitError";
562
+ this.retryAfter = retryAfter;
563
+ }
564
+ };
565
+ const UNITS = {
566
+ ms: 1,
567
+ s: 1e3,
568
+ m: 6e4,
569
+ h: 36e5,
570
+ d: 864e5
571
+ };
572
+ /** The length of a window in milliseconds. */
573
+ function windowMs(window) {
574
+ if (typeof window === "number") return window;
575
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(window);
576
+ if (!match) throw new TypeError(`The window "${window}" is not a length such as "10s", "1m" or "1h"`);
577
+ return Number(match[1]) * UNITS[match[2]];
578
+ }
579
+ /** Counts in memory, per process. Expired keys go when they are read, and in a sweep now and then. */
580
+ function createMemoryStore(now = Date.now) {
581
+ const counts = /* @__PURE__ */ new Map();
582
+ let sweeps = 0;
583
+ const sweep = () => {
584
+ if (++sweeps % 1e3 !== 0) return;
585
+ const time = now();
586
+ for (const [key, entry] of counts) if (entry.expires <= time) counts.delete(key);
587
+ };
588
+ return {
589
+ increment(key, ttl) {
590
+ sweep();
591
+ const time = now();
592
+ const entry = counts.get(key);
593
+ if (!entry || entry.expires <= time) {
594
+ counts.set(key, {
595
+ count: 1,
596
+ expires: time + ttl
597
+ });
598
+ return 1;
599
+ }
600
+ entry.count++;
601
+ return entry.count;
602
+ },
603
+ get(key) {
604
+ const entry = counts.get(key);
605
+ return entry && entry.expires > now() ? entry.count : void 0;
606
+ }
607
+ };
608
+ }
609
+ const config = {};
610
+ let memory;
611
+ let warned = false;
612
+ /** The clock, which tests replace. */
613
+ let clock = Date.now;
614
+ /** Sets the defaults of every limit: the store, the trusted proxies, and whether limits count. */
615
+ function configureRateLimit(options) {
616
+ for (const range of options.proxies ?? []) parseRange(range);
617
+ Object.assign(config, options);
618
+ }
619
+ /** True in development and in tests, from `NODE_ENV`. A runtime without it is production. */
620
+ function isDevelopment() {
621
+ const mode = globalThis.process?.env?.NODE_ENV;
622
+ return mode === "development" || mode === "test";
623
+ }
624
+ /**
625
+ * What a limit counts per: the server function, the pattern of the route,
626
+ * such as `/api/[id]`, or one count for every path that no route matches.
627
+ */
628
+ function targetOf(event) {
629
+ return event.call?.id ?? event.route ?? "(no route)";
630
+ }
631
+ /**
632
+ * The key of a request: the key of the app, or the address of the client.
633
+ * Without either, callers would share one count, and one client could use
634
+ * up the limit of all. So it throws in production. In development it warns
635
+ * once and returns undefined, and the limit does not count.
636
+ */
637
+ async function keyOf(event, options) {
638
+ const key = await options.key?.(event, event.call?.args ?? []) ?? clientAddress(event);
639
+ if (key !== void 0) return key;
640
+ const message = `rateLimit: the request to "${targetOf(event)}" has no key, because the server did not pass the address of the client. Pass \`address\` to the handler of the server, or set \`key\` on the limit.`;
641
+ if (!isDevelopment()) throw new Error(message);
642
+ if (!warned) {
643
+ warned = true;
644
+ console.warn(`${message} Until then, the limit does not count in development.`);
645
+ }
646
+ }
647
+ /**
648
+ * Counts a request, and throws a `RateLimitError` when its key has made
649
+ * more than `max` requests in the window.
650
+ */
651
+ async function check(event, options) {
652
+ if (event.prerender || !(options.enabled ?? config.enabled ?? true)) return;
653
+ const key = await keyOf(event, options);
654
+ if (key === void 0) return;
655
+ const name = `${key} ${targetOf(event)}`;
656
+ const store = options.store ?? config.store ?? (memory ??= createMemoryStore(clock));
657
+ const window = windowMs(options.window);
658
+ const now = clock();
659
+ const bucket = Math.floor(now / window);
660
+ const elapsed = now - bucket * window;
661
+ const [current, previous = 0] = await Promise.all([store.increment(`${name} ${bucket}`, window * 2), store.get(`${name} ${bucket - 1}`)]);
662
+ if (current + previous * (1 - elapsed / window) <= options.max) return;
663
+ const room = options.max - current - 1;
664
+ const wait = room >= 0 && previous > 0 ? window * (1 - room / previous) - elapsed : window - elapsed + (current > options.max - 1 ? window * (1 - (options.max - 1) / current) : 0);
665
+ const retryAfter = Math.max(1, Math.ceil(wait / 1e3));
666
+ event.headers.set("retry-after", String(retryAfter));
667
+ throw new RateLimitError(retryAfter);
668
+ }
669
+ /**
670
+ * Limits how often a key, such as the user or the address of the client,
671
+ * can call a server function. Call it first thing in the function, before
672
+ * its first `await`, as `getEvent()`:
673
+ *
674
+ * ```ts
675
+ * async function signIn(email: string, password: string) {
676
+ * 'use server';
677
+ * await rateLimit({ ...rateLimit.strict, key: () => email.toLowerCase() });
678
+ * // …
679
+ * }
680
+ * ```
681
+ *
682
+ * The fourth call in 10 seconds for one email rejects with a
683
+ * `RateLimitError`, with status 429 and `Retry-After`, and the rest of the
684
+ * function does not run. Without a `key`, the limit counts by the address
685
+ * of the client, which the server passes to its handler as `address`. In
686
+ * production, a limit with neither throws. `rateLimit.middleware(options)`
687
+ * limits every request under a folder of routes, or of the whole app from
688
+ * the entry.
689
+ */
690
+ const rateLimit = Object.assign((options) => {
691
+ return check(options.event ?? getEvent(), options);
692
+ }, {
693
+ middleware: (options) => async (target, next) => {
694
+ const event = target instanceof RequestEvent ? target : options.event ?? getEvent();
695
+ try {
696
+ await check(event, options);
697
+ } catch (error) {
698
+ if (error instanceof RateLimitError) return new Response(error.message, {
699
+ status: 429,
700
+ headers: {
701
+ "retry-after": String(error.retryAfter),
702
+ "content-type": "text/plain"
703
+ }
704
+ });
705
+ throw error;
706
+ }
707
+ return next();
708
+ },
709
+ strict: {
710
+ max: 3,
711
+ window: "10s"
712
+ }
713
+ });
714
+ /** The 16 bytes of an address, or undefined for text that is not one. */
715
+ function parseAddress(text) {
716
+ const value = text.trim().replace(/^\[|\]$/g, "");
717
+ if (value.includes(":")) return parseIPv6(value);
718
+ const parts = value.split(".");
719
+ if (parts.length !== 4 || !parts.every((part) => /^\d{1,3}$/.test(part) && Number(part) < 256)) return;
720
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
721
+ bytes[10] = 255;
722
+ bytes[11] = 255;
723
+ parts.forEach((part, index) => {
724
+ bytes[12 + index] = Number(part);
725
+ });
726
+ return bytes;
727
+ }
728
+ function parseIPv6(value) {
729
+ const tail = /^(.*:)(\d+\.\d+\.\d+\.\d+)$/.exec(value);
730
+ let text = value;
731
+ if (tail) {
732
+ const v4 = parseAddress(tail[2]);
733
+ if (!v4) return;
734
+ text = `${tail[1]}${(v4[12] << 8 | v4[13]).toString(16)}:${(v4[14] << 8 | v4[15]).toString(16)}`;
735
+ }
736
+ const halves = text.split("::");
737
+ if (halves.length > 2) return;
738
+ const head = halves[0] ? halves[0].split(":") : [];
739
+ const rest = halves[1] ? halves[1].split(":") : [];
740
+ const missing = 8 - head.length - rest.length;
741
+ if (missing < 0 || halves.length === 1 && missing !== 0) return;
742
+ const groups = [
743
+ ...head,
744
+ ...Array(missing).fill("0"),
745
+ ...rest
746
+ ];
747
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
748
+ for (const [index, group] of groups.entries()) {
749
+ if (!/^[\da-f]{1,4}$/i.test(group)) return;
750
+ const number = Number.parseInt(group, 16);
751
+ bytes[index * 2] = number >> 8;
752
+ bytes[index * 2 + 1] = number & 255;
753
+ }
754
+ return bytes;
755
+ }
756
+ function isIPv4(bytes) {
757
+ return bytes.slice(0, 10).every((byte) => byte === 0) && bytes[10] === 255 && bytes[11] === 255;
758
+ }
759
+ /**
760
+ * Reads a range: an address, or a CIDR such as `10.0.0.0/8` or `fd00::/8`.
761
+ * Throws for anything else, such as `10.0.0.0/` or `10.0.0.0/33`, since a
762
+ * range that matched every address would trust any `X-Forwarded-For`.
763
+ */
764
+ function parseRange(range) {
765
+ const [text, length, ...extra] = range.split("/");
766
+ const base = parseAddress(text);
767
+ const v4 = base !== void 0 && isIPv4(base);
768
+ if (!base || extra.length > 0 || length !== void 0 && (!/^\d{1,3}$/.test(length) || Number(length) > (v4 ? 32 : 128))) throw new TypeError(`The proxy range "${range}" is not an address, or an address and a prefix length such as "10.0.0.0/8"`);
769
+ return {
770
+ base,
771
+ bits: length === void 0 ? 128 : Number(length) + (v4 ? 96 : 0)
772
+ };
773
+ }
774
+ function inParsedRange(address, { base, bits }) {
775
+ if (isIPv4(base) !== isIPv4(address)) return false;
776
+ for (let bit = 0; bit < bits; bit++) {
777
+ const mask = 128 >> bit % 8;
778
+ if (((address[bit >> 3] ^ base[bit >> 3]) & mask) !== 0) return false;
779
+ }
780
+ return true;
781
+ }
782
+ /** The text of an address. An IPv6 address counts by its /64, since one client often holds a whole subnet. */
783
+ function formatAddress(bytes) {
784
+ if (isIPv4(bytes)) return bytes.slice(12).join(".");
785
+ const groups = [];
786
+ for (let index = 0; index < 8; index++) groups.push(index < 4 ? (bytes[index * 2] << 8 | bytes[index * 2 + 1]).toString(16) : "0");
787
+ return groups.join(":");
788
+ }
789
+ /**
790
+ * The address of the client of a request. It is the address that the server
791
+ * saw, which the handler of the server passes as `address`. When that
792
+ * address is one of the proxies that `configureRateLimit({ proxies })`
793
+ * names, it comes from `X-Forwarded-For`: the header is read from the right,
794
+ * past the trusted proxies, because a client can write anything at its
795
+ * left. An IPv6 address counts by its /64.
796
+ *
797
+ * Undefined when the server passed no address, whatever the headers say,
798
+ * since nothing then shows that the header comes from a proxy. Undefined too
799
+ * when the first hop past the proxies is not an address.
800
+ */
801
+ function clientAddress(event, proxies = config.proxies ?? []) {
802
+ const seen = event.address === void 0 ? void 0 : parseAddress(event.address);
803
+ if (!seen) return;
804
+ const ranges = proxies.map(parseRange);
805
+ const trusted = (address) => ranges.some((range) => inParsedRange(address, range));
806
+ if (!trusted(seen)) return formatAddress(seen);
807
+ const hops = (event.request.headers.get("x-forwarded-for") ?? "").split(",").filter((hop) => hop.trim() !== "");
808
+ let client = seen;
809
+ for (let index = hops.length - 1; index >= 0; index--) {
810
+ const address = parseAddress(hops[index]);
811
+ if (!address) return;
812
+ client = address;
813
+ if (!trusted(address)) break;
814
+ }
815
+ return formatAddress(client);
816
+ }
817
+ //#endregion
818
+ //#region src/runtime/server.ts
819
+ /** True if a boundary holds `target`, whose ID starts with the boundary's ID and a dot. */
820
+ function holdsBoundary(id, target) {
821
+ return typeof target === "string" && target.startsWith(`${id}.`);
822
+ }
823
+ function spaceId(space, n) {
824
+ return space.prefix ? `${space.prefix}${n}` : n;
825
+ }
826
+ /**
827
+ * True for an ID that a render made after `mark`: a scope of the same space
828
+ * from its counter on, or a scope inside a block or boundary from then on.
829
+ */
830
+ function madeAfter(mark, id) {
831
+ const text = String(id);
832
+ if (!text.startsWith(mark.prefix)) return false;
833
+ const rest = text.slice(mark.prefix.length);
834
+ const dot = rest.indexOf(".");
835
+ return dot === -1 ? Number(rest) >= mark.scope : Number(rest.slice(0, dot)) >= mark.boundary;
836
+ }
837
+ /**
838
+ * Tracks the scopes of one render. A `#loading` body renders in a child
839
+ * context, so its scopes are written with its markup.
840
+ */
841
+ var Context = class Context {
842
+ /**
843
+ * The scopes of this render, in the order it made them, with their
844
+ * records. A record that this render adds to a scope of another render,
845
+ * such as a link from a `#loading` body to a scope of the page, is here
846
+ * too, as a scope of its own.
847
+ */
848
+ scopes = [];
849
+ /**
850
+ * Every ID space of the page, across the renders of `#loading` bodies, on
851
+ * the root context. A scope is found by its ID in the entries of its space.
852
+ * The spaces are put in a map by prefix only when a scope is looked up
853
+ * outside the blocks that are open, since a render makes many and looks
854
+ * up few, and each string key costs a hash.
855
+ */
856
+ made = [];
857
+ byPrefix;
858
+ indexed = 0;
859
+ /** The records that this render adds to scopes of other renders, by ID. */
860
+ partials;
861
+ /** The scope that the render used last, since it uses one a few times in a row. */
862
+ last;
863
+ root;
864
+ /** The ID spaces of the blocks that the render is in, from the outside in. */
865
+ spaces;
866
+ baseId;
867
+ /** The `#defer` body to render, in the request for it. The rest of the page renders no body. */
868
+ target;
869
+ /** True in the context of the target body and the bodies inside it. */
870
+ inTarget = false;
871
+ boundaries = [];
872
+ styles = /* @__PURE__ */ new Set();
873
+ /** Markup of `#portal` blocks, written at the end of the page. */
874
+ portals = [];
875
+ /** Markup of `#head` blocks. */
876
+ heads = [];
877
+ pageTitle;
878
+ /** The titles that this render set, and whether they all came from a `<title>` in `#head`. */
879
+ titles = {
880
+ count: 0,
881
+ markup: true
882
+ };
883
+ onBoundary;
884
+ /** The scope that renders the next component, which becomes its owner. */
885
+ owner;
886
+ /**
887
+ * Children that render where they are inserted: the scope of the markup
888
+ * that wrote them, and the scope where they are, for their contexts.
889
+ */
890
+ inserted = [];
891
+ /** Takes back what this context added to the page, from the newest, for `restore`. */
892
+ undo = [];
893
+ /** The URL prefix of server function calls. */
894
+ rpcPrefix = "/_brumate";
895
+ /** The ID of the build, for forms that post to server functions. See `RenderOptions`. */
896
+ build;
897
+ /** Results of server functions that a form posted to this page, for `$action`. */
898
+ actions = /* @__PURE__ */ new Map();
899
+ /** The params of the route of the page, for `$route`. */
900
+ params = {};
901
+ /** The request of the page, when it renders with one. */
902
+ event;
903
+ /** Results of server function calls in this render, so the same call runs once. */
904
+ calls = /* @__PURE__ */ new Map();
905
+ /** The event of the page, for `getEvent()` in a component, which the compiler rewrites to this. */
906
+ getEvent() {
907
+ const event = this.root.event;
908
+ if (!event) throw new Error("getEvent() works while a page renders with a request, such as in a route");
909
+ return event;
910
+ }
911
+ /** Runs code of the render with its event and its call results, such as a memo's compute. */
912
+ run(callback) {
913
+ return withEvent(this.root.event, callback, this.root.calls);
914
+ }
915
+ /** The result of a server function that a form posted to this page. */
916
+ actionResult(fn) {
917
+ return this.root.actions.get(unwrap(fn));
918
+ }
919
+ /** `prefix` is the boundary ID and a dot, for the context of a `#loading` body. */
920
+ constructor(root, rpc, base = 0, prefix = "") {
921
+ this.root = root ?? this;
922
+ if (rpc) this.rpcPrefix = rpc;
923
+ const first = prefix ? 0 : base;
924
+ this.spaces = [{
925
+ prefix,
926
+ scope: first,
927
+ boundary: first,
928
+ first,
929
+ entries: []
930
+ }];
931
+ this.root.made.push(this.spaces[0]);
932
+ this.baseId = base;
933
+ }
934
+ /** The base of the render, which the browser sends back to ask for a `#defer` body. */
935
+ base() {
936
+ return this.root.baseId;
937
+ }
938
+ /** True in a request for a `#defer` body, outside the body, once the body has started. */
939
+ past() {
940
+ return this.root.target?.status === "found" && !this.inTarget;
941
+ }
942
+ /**
943
+ * A number above every scope and boundary ID of the page so far, so a
944
+ * later render can start there. The IDs inside boundaries start with one.
945
+ */
946
+ next() {
947
+ const space = this.root.spaces[0];
948
+ return Math.max(space.scope, space.boundary);
949
+ }
950
+ /** The space that the next IDs come from. */
951
+ get space() {
952
+ return this.spaces.at(-1);
953
+ }
954
+ /**
955
+ * Starts a block whose shape depends on data, such as an `#if` or a
956
+ * `#for`. The scopes of its bodies are numbered after one ID that the
957
+ * block takes, until `leave`. A `#loading` body that renders in place
958
+ * passes the ID of its boundary, so its scopes get the IDs that they
959
+ * would get in a stream.
960
+ */
961
+ enter(id = spaceId(this.space, this.space.boundary++)) {
962
+ const space = {
963
+ prefix: `${id}.`,
964
+ scope: 0,
965
+ boundary: 0,
966
+ first: 0,
967
+ entries: []
968
+ };
969
+ this.spaces.push(space);
970
+ this.root.made.push(space);
971
+ }
972
+ /** Ends the block that `enter` started. */
973
+ leave() {
974
+ this.spaces.pop();
975
+ }
976
+ /** Returns the URL prefix of server function calls. */
977
+ rpc() {
978
+ return this.root.rpcPrefix;
979
+ }
980
+ /** Returns the ID of the build, when the render has one. */
981
+ buildId() {
982
+ return this.root.build;
983
+ }
984
+ /**
985
+ * Returns a new scope ID. `kind` is the scope's ID in the compiled
986
+ * component, `parent` is the scope that contains it, and `module` is the
987
+ * component ID of a component's root scope.
988
+ */
989
+ scope(kind, parent, module) {
990
+ const root = this.root;
991
+ const space = this.space;
992
+ const n = space.scope++;
993
+ const id = space.prefix ? `${space.prefix}${n}` : n;
994
+ const record = {};
995
+ record.k = kind;
996
+ if (parent !== void 0) record.p = parent;
997
+ let up = parent;
998
+ if (module !== void 0) {
999
+ record.m = module;
1000
+ if (root.owner !== void 0) {
1001
+ record.o = root.owner;
1002
+ up = root.owner;
1003
+ root.owner = void 0;
1004
+ }
1005
+ }
1006
+ const inserted = root.inserted.findLast((entry) => entry.from === up);
1007
+ if (inserted) {
1008
+ up = inserted.at;
1009
+ record.t = inserted.at;
1010
+ }
1011
+ const entry = {
1012
+ id,
1013
+ prefix: space.prefix,
1014
+ n,
1015
+ record,
1016
+ ctx: this,
1017
+ parent: up,
1018
+ space
1019
+ };
1020
+ this.scopes.push(entry);
1021
+ space.entries.push(entry);
1022
+ this.last = entry;
1023
+ return id;
1024
+ }
1025
+ /** The scope of the page with an ID, from any render. */
1026
+ find(id) {
1027
+ const root = this.root;
1028
+ if (typeof id === "number") {
1029
+ const page = root.made[0];
1030
+ return page.entries[id - page.first];
1031
+ }
1032
+ const dot = id.lastIndexOf(".");
1033
+ let n = 0;
1034
+ for (let i = dot + 1; i < id.length; i++) n = n * 10 + id.charCodeAt(i) - 48;
1035
+ for (let i = this.spaces.length - 1; i >= 0; i--) {
1036
+ const space = this.spaces[i];
1037
+ if (space.prefix.length === dot + 1 && id.startsWith(space.prefix)) return space.entries[n - space.first];
1038
+ }
1039
+ const byPrefix = root.byPrefix ??= /* @__PURE__ */ new Map();
1040
+ for (; root.indexed < root.made.length; root.indexed++) {
1041
+ const space = root.made[root.indexed];
1042
+ byPrefix.set(space.prefix, space);
1043
+ }
1044
+ const space = byPrefix.get(id.slice(0, dot + 1));
1045
+ return space?.entries[n - space.first];
1046
+ }
1047
+ /**
1048
+ * Renders children where a component inserts them, at `at`. Their scopes
1049
+ * keep `from`, the scope of the markup that wrote them, for their values,
1050
+ * and find their contexts from `at`.
1051
+ */
1052
+ async children(from, at, renderBody) {
1053
+ const entry = {
1054
+ from,
1055
+ at
1056
+ };
1057
+ const { inserted } = this.root;
1058
+ inserted.push(entry);
1059
+ try {
1060
+ return await renderBody();
1061
+ } finally {
1062
+ inserted.splice(inserted.indexOf(entry), 1);
1063
+ }
1064
+ }
1065
+ /**
1066
+ * The ID that `$id()` makes: the scope's ID and the position of the call.
1067
+ * A dot in a scope ID inside a `#loading` body becomes `_`, so the ID also
1068
+ * works as a CSS selector, such as `#b5_1-0`.
1069
+ */
1070
+ id(scope, index) {
1071
+ return `b${String(scope).replace(/\./g, "_")}-${index}`;
1072
+ }
1073
+ /** Sets the owner of the next component's root scope. */
1074
+ own(scope) {
1075
+ this.root.owner = scope;
1076
+ }
1077
+ /** Provides a value of a context to the scopes inside `scope`. */
1078
+ provide(context, value, scope) {
1079
+ const node = this.find(scope);
1080
+ node.values ??= /* @__PURE__ */ new Map();
1081
+ node.values.set(context.key, value);
1082
+ const record = this.record(scope);
1083
+ record.v ??= {};
1084
+ record.v[context.key] = value;
1085
+ }
1086
+ /**
1087
+ * Reads a context from the nearest scope that provides it, starting at
1088
+ * `scope`. With `slot`, records which slot holds it, so the client can
1089
+ * update it when the provided value changes.
1090
+ */
1091
+ consume(context, scope, slot) {
1092
+ if (slot !== void 0) {
1093
+ const record = this.record(scope);
1094
+ record.x ??= {};
1095
+ record.x[context.key] = slot;
1096
+ }
1097
+ for (let id = scope; id !== void 0;) {
1098
+ const node = this.find(id);
1099
+ if (node?.values?.has(context.key)) return node.values.get(context.key);
1100
+ id = node?.parent;
1101
+ }
1102
+ if (context.key === "brumate.route") {
1103
+ const url = new URL(this.root.event?.request.url ?? "http://localhost/");
1104
+ return {
1105
+ url,
1106
+ search: url.searchParams,
1107
+ params: this.root.params
1108
+ };
1109
+ }
1110
+ return context.defaultValue;
1111
+ }
1112
+ /** The ID that the next call to `scope()` returns. */
1113
+ peek() {
1114
+ return spaceId(this.space, this.space.scope);
1115
+ }
1116
+ /** Marks the render so far, such as before a `#try` body, for `restore`. */
1117
+ mark() {
1118
+ const { prefix, scope, boundary } = this.space;
1119
+ return {
1120
+ prefix,
1121
+ scope,
1122
+ boundary,
1123
+ depth: this.spaces.length,
1124
+ undo: this.undo.length,
1125
+ owner: this.root.owner
1126
+ };
1127
+ }
1128
+ /**
1129
+ * Takes back what the render added to the page since `mark`, such as a
1130
+ * `#try` body that threw, whose markup is not sent: its scopes, the
1131
+ * stylesheets it counted as sent, its `#portal` and `#head` markup, its
1132
+ * title, its `#loading` bodies, and its links to child components.
1133
+ */
1134
+ restore(mark) {
1135
+ this.drop(mark);
1136
+ this.spaces.length = mark.depth;
1137
+ for (const undo of this.undo.splice(mark.undo).toReversed()) undo();
1138
+ this.root.owner = mark.owner;
1139
+ }
1140
+ /**
1141
+ * Forgets the scopes of this render from `from` on, such as those of a
1142
+ * `#try` body that threw, so the client does not resume markup that was
1143
+ * never sent. `#loading` bodies render in contexts of their own, so their
1144
+ * scopes stay.
1145
+ */
1146
+ drop(mark) {
1147
+ this.last = void 0;
1148
+ const { scopes } = this;
1149
+ let kept = 0;
1150
+ for (const entry of scopes) {
1151
+ if (!madeAfter(mark, entry.id)) {
1152
+ scopes[kept++] = entry;
1153
+ continue;
1154
+ }
1155
+ const { space } = entry;
1156
+ if (space?.entries[entry.n - space.first] === entry) space.entries[entry.n - space.first] = void 0;
1157
+ this.partials?.delete(entry.id);
1158
+ }
1159
+ scopes.length = kept;
1160
+ }
1161
+ /** The scope of this render with an ID, or the record that this render adds to another's. */
1162
+ entry(scope) {
1163
+ const last = this.last;
1164
+ if (last && last.id === scope) return last;
1165
+ let entry = this.find(scope);
1166
+ if (entry?.ctx !== this) {
1167
+ this.partials ??= /* @__PURE__ */ new Map();
1168
+ entry = this.partials.get(scope);
1169
+ if (!entry) {
1170
+ const [prefix, n] = splitId(scope);
1171
+ entry = {
1172
+ id: scope,
1173
+ prefix,
1174
+ n,
1175
+ record: {},
1176
+ ctx: this
1177
+ };
1178
+ this.partials.set(scope, entry);
1179
+ this.scopes.push(entry);
1180
+ }
1181
+ }
1182
+ this.last = entry;
1183
+ return entry;
1184
+ }
1185
+ record(scope) {
1186
+ return this.entry(scope).record;
1187
+ }
1188
+ /** The record of a scope in the state of this render, if it is there. */
1189
+ ownRecord(scope) {
1190
+ const entry = this.find(scope);
1191
+ return entry?.ctx === this ? entry.record : this.partials?.get(scope)?.record;
1192
+ }
1193
+ /** The records of the scopes of this render, by ID, in the order the render made them. */
1194
+ get state() {
1195
+ return new Map(this.scopes.map((entry) => [entry.id, entry.record]));
1196
+ }
1197
+ /**
1198
+ * The list of each list item scope whose list is a slot of an enclosing
1199
+ * scope, as `[scope, slot]`. The items of a list share one array.
1200
+ */
1201
+ get sources() {
1202
+ return new Map(this.scopes.flatMap((entry) => entry.source ? [[entry.id, entry.source]] : []));
1203
+ }
1204
+ slots(scope, values, names) {
1205
+ const entry = this.entry(scope);
1206
+ entry.record.s = values;
1207
+ if (names) entry.names = names;
1208
+ }
1209
+ /**
1210
+ * Records the item of a list that can change on the client. `source` is
1211
+ * the scope and slot that hold the list, when the compiler found one, so
1212
+ * the client can take the item from there.
1213
+ */
1214
+ item(scope, value, source) {
1215
+ const entry = this.entry(scope);
1216
+ entry.record.i = value;
1217
+ if (source) entry.source = source;
1218
+ }
1219
+ /** Records the scope of a child component at an anchor of its parent. */
1220
+ link(scope, anchor, child) {
1221
+ const record = this.record(scope);
1222
+ const links = record.c ??= {};
1223
+ links[anchor] = child;
1224
+ this.undo.push(() => {
1225
+ if (links[anchor] === child) delete links[anchor];
1226
+ });
1227
+ }
1228
+ /** Returns the reference that a `ref` signal holds on the server. */
1229
+ element(scope, anchor) {
1230
+ return new ElementReference(scope, anchor);
1231
+ }
1232
+ /** Marks a function as a client function, so it serializes as a reference. */
1233
+ fn(value, ref, scope) {
1234
+ if (typeof value === "function") functionReferences.set(value, new FunctionReference(ref, scope));
1235
+ return value;
1236
+ }
1237
+ /** Returns a component's stylesheet the first time the page renders the component. */
1238
+ style(id, css) {
1239
+ const styles = this.root.styles;
1240
+ if (styles.has(id)) return "";
1241
+ styles.add(id);
1242
+ this.undo.push(() => styles.delete(id));
1243
+ return styleElement(id, css);
1244
+ }
1245
+ /** Adds the markup of a `#head` block. */
1246
+ head(html) {
1247
+ const heads = (this.root.sent ? this : this.root).heads;
1248
+ heads.push(html);
1249
+ this.undo.push(() => removeLast(heads, html));
1250
+ }
1251
+ /**
1252
+ * Sets the title of the page. The last call wins. `markup` is true for a
1253
+ * `<title>` in `#head`, which is in the head already.
1254
+ */
1255
+ title(value, markup = false) {
1256
+ const target = this.root.sent ? this : this.root;
1257
+ const previous = target.pageTitle;
1258
+ const titles = { ...target.titles };
1259
+ const title = value === null || value === void 0 ? "" : String(value);
1260
+ target.pageTitle = title;
1261
+ target.titles = {
1262
+ count: titles.count + 1,
1263
+ markup: titles.markup && markup
1264
+ };
1265
+ this.undo.push(() => {
1266
+ if (target.pageTitle === title) {
1267
+ target.pageTitle = previous;
1268
+ target.titles = titles;
1269
+ }
1270
+ });
1271
+ }
1272
+ /** True once the first render is done, and its head is about to be sent. */
1273
+ sent = false;
1274
+ /** Marks the first render as done. Head markup after it streams with its `#loading` body. */
1275
+ send() {
1276
+ this.root.sent = true;
1277
+ }
1278
+ /**
1279
+ * The head markup and the title that a `#loading` body set, after the
1280
+ * head was sent. The title is undefined if the body set none.
1281
+ */
1282
+ lateHead() {
1283
+ return {
1284
+ html: this.heads.join(""),
1285
+ title: this.pageTitle
1286
+ };
1287
+ }
1288
+ /** The markup for the document's head: the title and the `#head` blocks. */
1289
+ headHTML() {
1290
+ const { count, markup } = this.root.titles;
1291
+ return (this.root.pageTitle === void 0 || count === 1 && markup ? "" : `<title>${escape(this.root.pageTitle)}</title>`) + this.root.heads.join("");
1292
+ }
1293
+ /** Adds the markup of a `#portal` block, which goes after the rest of the page. */
1294
+ portal(html) {
1295
+ this.portals.push(html);
1296
+ this.undo.push(() => removeLast(this.portals, html));
1297
+ }
1298
+ /** Adds the head markup and the title of a body that renders in place, to the head of the page. */
1299
+ adoptHead(late) {
1300
+ if (late.html) this.root.heads.push(late.html);
1301
+ if (late.title !== void 0) this.root.pageTitle = late.title;
1302
+ }
1303
+ /** True when the bodies of `#defer` blocks render in place, for a page that renders in order. */
1304
+ inOrder = false;
1305
+ /** Returns the ID of a new `#loading` boundary. */
1306
+ boundary() {
1307
+ return spaceId(this.space, this.space.boundary++);
1308
+ }
1309
+ /** Renders a `#loading` body after the rest of the page, in its own context and ID space. */
1310
+ defer(id, renderBody) {
1311
+ const target = this.root.target;
1312
+ if (!target || this.inTarget) this.register(id, renderBody, this.inTarget);
1313
+ else if (holdsBoundary(id, target.boundary)) this.register(id, renderBody, false, true);
1314
+ }
1315
+ /**
1316
+ * Renders the body of a `#defer` block, in the request for it. `at` is
1317
+ * the scope and the anchor of the block. A page renders only the
1318
+ * fallback, so it does nothing then.
1319
+ */
1320
+ deferBlock(id, at, renderBody) {
1321
+ const target = this.root.target;
1322
+ if (!target && this.root.inOrder) {
1323
+ this.register(id, renderBody, false);
1324
+ return;
1325
+ }
1326
+ if (!target || this.inTarget) return;
1327
+ if (holdsBoundary(id, target.boundary)) {
1328
+ this.register(id, renderBody, false, true);
1329
+ return;
1330
+ }
1331
+ if (id !== target.boundary) return;
1332
+ if (at !== target.at) {
1333
+ target.status = "moved";
1334
+ return;
1335
+ }
1336
+ target.status = "found";
1337
+ this.register(id, renderBody, true);
1338
+ }
1339
+ register(id, renderBody, inTarget, around = false) {
1340
+ const child = new Context(this.root, void 0, 0, `${id}.`);
1341
+ child.inTarget = inTarget;
1342
+ const boundary = {
1343
+ id,
1344
+ render: renderBody(child).then((html) => ({
1345
+ html,
1346
+ ctx: child
1347
+ })),
1348
+ around
1349
+ };
1350
+ boundary.render.catch(() => {});
1351
+ const root = this.root;
1352
+ if (root.onBoundary) root.onBoundary(boundary);
1353
+ else root.boundaries.push(boundary);
1354
+ this.undo.push(() => {
1355
+ boundary.cancelled = true;
1356
+ removeLast(root.boundaries, boundary);
1357
+ });
1358
+ }
1359
+ /** Receives every boundary, including those registered before this call. */
1360
+ watch(onBoundary) {
1361
+ this.onBoundary = onBoundary;
1362
+ for (const boundary of this.boundaries.splice(0)) onBoundary(boundary);
1363
+ }
1364
+ };
1365
+ /** Removes the last copy of a value from a list. */
1366
+ function removeLast(list, value) {
1367
+ const index = list.lastIndexOf(value);
1368
+ if (index !== -1) list.splice(index, 1);
1369
+ }
1370
+ /** Thrown when code reads a memo whose value is still loading. It carries the load. */
1371
+ var NotReady = class extends Error {
1372
+ source;
1373
+ constructor(source) {
1374
+ super("The value is still loading");
1375
+ this.name = "NotReady";
1376
+ this.source = source;
1377
+ }
1378
+ };
1379
+ /** Declares a memo. Its value is computed when it is first read. */
1380
+ function memo(compute, ctx) {
1381
+ return {
1382
+ compute,
1383
+ ctx,
1384
+ state: "idle"
1385
+ };
1386
+ }
1387
+ /**
1388
+ * Reads a memo. A value that is still loading throws `NotReady` with its
1389
+ * load, and a memo that read such a value stays unread, so it computes
1390
+ * again when it is read after the load settles.
1391
+ */
1392
+ function read(node) {
1393
+ if (node.state === "done") return node.value;
1394
+ if (node.state === "failed") throw node.error;
1395
+ if (node.state === "pending") throw new NotReady(node.load);
1396
+ let value;
1397
+ try {
1398
+ value = node.ctx ? node.ctx.run(node.compute) : node.compute();
1399
+ } catch (error) {
1400
+ if (!(error instanceof NotReady)) {
1401
+ node.state = "failed";
1402
+ node.error = error;
1403
+ }
1404
+ throw error;
1405
+ }
1406
+ if (value !== null && typeof value === "object" && (typeof value.then === "function" || isAsyncIterable(value))) {
1407
+ node.state = "pending";
1408
+ node.load = Promise.resolve(value).then(firstValue).then((result) => {
1409
+ node.state = "done";
1410
+ node.value = result;
1411
+ }, (error) => {
1412
+ node.state = "failed";
1413
+ node.error = error;
1414
+ });
1415
+ throw new NotReady(node.load);
1416
+ }
1417
+ node.state = "done";
1418
+ node.value = value;
1419
+ return value;
1420
+ }
1421
+ /**
1422
+ * The first value of an async iterable, such as a server function that
1423
+ * streams. A page renders once, so the server stops reading after it. Other
1424
+ * values are themselves.
1425
+ */
1426
+ async function firstValue(value) {
1427
+ if (!isAsyncIterable(value)) return value;
1428
+ const iterator = value[Symbol.asyncIterator]();
1429
+ const first = await iterator.next();
1430
+ await iterator.return?.();
1431
+ return first.value;
1432
+ }
1433
+ /** Waits for the value of a memo, through every load it reads. */
1434
+ async function wait(node) {
1435
+ for (;;) try {
1436
+ return read(node);
1437
+ } catch (error) {
1438
+ if (!(error instanceof NotReady)) throw error;
1439
+ await error.source.catch(() => {});
1440
+ }
1441
+ }
1442
+ /**
1443
+ * The value of a memo when it is ready, or a promise of it while it loads.
1444
+ * The render then awaits only a memo that is loading.
1445
+ */
1446
+ function ready(node) {
1447
+ try {
1448
+ return read(node);
1449
+ } catch (error) {
1450
+ if (error instanceof NotReady) return wait(node);
1451
+ throw error;
1452
+ }
1453
+ }
1454
+ /**
1455
+ * The value of a memo for the page state: its value when it is ready, or
1456
+ * a promise of it while it loads. A memo that fails gives a rejected
1457
+ * promise either way, so the page renders and the failure reaches the
1458
+ * browser as the load that failed.
1459
+ */
1460
+ function stateValue(node) {
1461
+ try {
1462
+ return read(node);
1463
+ } catch (error) {
1464
+ return error instanceof NotReady ? wait(node) : Promise.reject(error);
1465
+ }
1466
+ }
1467
+ /**
1468
+ * Starts every memo of a run of declarations that the render waits for,
1469
+ * so they load at the same time. Returns a promise that settles when all
1470
+ * of them have, or undefined when none is loading. A memo that fails
1471
+ * throws here, or rejects the promise.
1472
+ */
1473
+ function waitAll(nodes) {
1474
+ const loads = [];
1475
+ for (const node of nodes) {
1476
+ const value = ready(node);
1477
+ if (value instanceof Promise) loads.push(value);
1478
+ }
1479
+ return loads.length === 0 ? void 0 : Promise.all(loads);
1480
+ }
1481
+ /**
1482
+ * True when every memo has its value, so a `#loading` body that reads them
1483
+ * can render in place. A memo that is not computed yet computes here, so
1484
+ * the loads of the memos that are not ready start now, and the body that
1485
+ * streams later finds them loading. A memo that failed counts as not ready:
1486
+ * the body streams, and throws where it reads the memo.
1487
+ */
1488
+ function settled(nodes) {
1489
+ let result = true;
1490
+ for (const node of nodes) try {
1491
+ read(node);
1492
+ } catch {
1493
+ result = false;
1494
+ }
1495
+ return result;
1496
+ }
1497
+ const LAZY = Symbol.for("brumate.lazy");
1498
+ /**
1499
+ * The children of a component, which render where the component inserts
1500
+ * them, so they read the contexts that the component provides. `from` is the
1501
+ * scope of the markup that wrote them.
1502
+ */
1503
+ function children(from, renderBody) {
1504
+ return new Children(from, renderBody);
1505
+ }
1506
+ /** The symbol of raw HTML. See `html.ts`. */
1507
+ const RAW = Symbol.for("brumate.raw");
1508
+ /**
1509
+ * Children of a component. The first render keeps its HTML as raw HTML, so
1510
+ * the page state sends it for the browser to insert, such as when a block
1511
+ * that holds the children opens. A class, since the serializer tests only
1512
+ * class instances.
1513
+ */
1514
+ var Children = class {
1515
+ [LAZY];
1516
+ /** The HTML of the first render, under the symbol of raw HTML. */
1517
+ [RAW];
1518
+ constructor(from, renderBody) {
1519
+ this[LAZY] = async (ctx, at) => {
1520
+ const html = await (at === void 0 ? renderBody(ctx) : ctx.children(from, at, () => renderBody(ctx)));
1521
+ this[RAW] ??= html;
1522
+ return html;
1523
+ };
1524
+ }
1525
+ };
1526
+ /** Makes markup that renders where it is inserted, such as the children of a layout. */
1527
+ function lazy(renderAt) {
1528
+ return { [LAZY]: renderAt };
1529
+ }
1530
+ function isLazy(value) {
1531
+ return typeof value === "object" && value !== null && LAZY in value;
1532
+ }
1533
+ /** Renders the attributes of a form or button that posts to a server function. */
1534
+ function action(ctx, name, id, method, result) {
1535
+ return actionAttributes(ctx.rpc(), name, id, method, result, ctx.buildId());
1536
+ }
1537
+ /**
1538
+ * The result of a server function that a form posted to this page, for
1539
+ * `$action`, or undefined when the page was not rendered for a post.
1540
+ */
1541
+ function actionResult(ctx, fn) {
1542
+ return ctx.actionResult(fn);
1543
+ }
1544
+ /**
1545
+ * Renders a value inserted in markup. `ctx` and `scope` are where it is
1546
+ * inserted, for markup that renders there.
1547
+ */
1548
+ function insert(value, ctx, scope) {
1549
+ if (value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function") return Promise.resolve(value).then((resolved) => insert(resolved, ctx, scope));
1550
+ if (isLazy(value) && ctx) return value[LAZY](ctx, scope);
1551
+ if (Array.isArray(value)) {
1552
+ const parts = value.map((item) => insert(item, ctx, scope));
1553
+ return parts.every((part) => typeof part === "string") ? parts.join("") : Promise.all(parts).then((all) => all.join(""));
1554
+ }
1555
+ return insertValue(value);
1556
+ }
1557
+ /**
1558
+ * Renders a child component. With `scope` and `anchor`, records the child's
1559
+ * scope so the parent can update its props on the client.
1560
+ */
1561
+ function component(Child, props, ctx, scope, anchor) {
1562
+ if (ctx.past()) return Promise.resolve("");
1563
+ if (scope !== void 0 && anchor !== void 0) ctx.link(scope, anchor, ctx.peek());
1564
+ if (scope !== void 0) ctx.own(scope);
1565
+ const given = props?.children;
1566
+ if (!(given instanceof Children)) return Child(props, ctx);
1567
+ const root = ctx.peek();
1568
+ return Child(props, ctx).then(async (html) => {
1569
+ if (given[RAW] === void 0) await given[LAZY](ctx, root);
1570
+ return html;
1571
+ });
1572
+ }
1573
+ /** Renders a dynamic tag, which can be an element name or a component. */
1574
+ function dynamic(tag, attributes, content, ctx, scope) {
1575
+ if (typeof tag === "function") {
1576
+ const entries = attributes["b-on"];
1577
+ const props = typeof entries === "string" && scope !== void 0 ? {
1578
+ ...attributes,
1579
+ "b-on": entries.split(" ").map((entry) => entry.includes("@") ? entry : `${entry}@${scope}`).join(" ")
1580
+ } : attributes;
1581
+ return component(tag, content ? {
1582
+ ...props,
1583
+ children: content
1584
+ } : props, ctx, scope);
1585
+ }
1586
+ const on = [];
1587
+ const open = `<${tag}${spread(attributes, on)}${onAttribute(on, "")}>`;
1588
+ if (VOID_ELEMENTS.has(tag)) return open;
1589
+ if (isLazy(content)) return Promise.resolve(content[LAZY](ctx, scope)).then((html) => `${open}${html}</${tag}>`);
1590
+ return `${open}${content && isRaw(content) ? rawHTML(content) : ""}</${tag}>`;
1591
+ }
1592
+ /** True when `value` is `target`, or holds it in plain objects, arrays, maps or sets. */
1593
+ function holds(value, target, seen = /* @__PURE__ */ new Set()) {
1594
+ if (value === target) return true;
1595
+ if (typeof value !== "object" || value === null || seen.has(value)) return false;
1596
+ seen.add(value);
1597
+ return (value instanceof Map ? [...value.keys(), ...value.values()] : value instanceof Set ? [...value] : Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype ? Object.values(value) : []).some((item) => holds(item, target, seen));
1598
+ }
1599
+ /**
1600
+ * The error of a value in the state of a page that cannot be sent to the
1601
+ * browser, which names the value and its component.
1602
+ */
1603
+ function unsendable(error, ctx) {
1604
+ const secret = secretErrors.get(error);
1605
+ const target = secret ?? error.value;
1606
+ if (target === void 0) return error instanceof Error ? error : new Error(String(error));
1607
+ for (const { record, names } of ctx.scopes) {
1608
+ const index = (record.s ?? []).findIndex((value) => holds(value, target));
1609
+ if (index === -1) continue;
1610
+ let owner = record;
1611
+ while (owner && owner.m === void 0 && owner.p !== void 0) owner = ctx.ownRecord(owner.p);
1612
+ const name = names?.[index] ?? `slot ${index}`;
1613
+ if (secret !== void 0) return /* @__PURE__ */ new Error(`The value of "${name}" in ${owner?.m ?? "a component"} is the value of a server environment variable, and code that runs in the browser reads it. Read the variable in a server function, and send the browser only what it needs.`);
1614
+ const kind = target?.constructor?.name ?? typeof target;
1615
+ return new Error(`The value of "${name}" in ${owner?.m ?? "a component"} holds a ${kind}, which cannot be sent to the browser, and code that runs in the browser reads it. Use it in a server function, or create it in the browser, such as in $client.`, { cause: error });
1616
+ }
1617
+ return error instanceof Error ? error : new Error(String(error));
1618
+ }
1619
+ /** The secret that each error of `secretError` found. The error does not hold it, so a log does not show it. */
1620
+ const secretErrors = /* @__PURE__ */ new WeakMap();
1621
+ /** The code of each secret as seroval writes a string: in double quotes, escaped. */
1622
+ const secretCode = /* @__PURE__ */ new Map();
1623
+ /**
1624
+ * An error for a record of the page state that holds the value of a server
1625
+ * environment variable as a string, or undefined. A record holds a string
1626
+ * as its code in quotes, so this is one search of the code per secret.
1627
+ */
1628
+ function secretError(code) {
1629
+ for (const secret of serverSecrets()) {
1630
+ let literal = secretCode.get(secret);
1631
+ if (literal === void 0) {
1632
+ literal = crossSerialize(secret);
1633
+ secretCode.set(secret, literal);
1634
+ }
1635
+ if (code.includes(literal)) {
1636
+ const error = /* @__PURE__ */ new Error("The page state holds the value of a server environment variable, which is not sent to the browser");
1637
+ secretErrors.set(error, secret);
1638
+ return error;
1639
+ }
1640
+ }
1641
+ }
1642
+ /** JSON that is safe in a `<script>`, with each `<` escaped. */
1643
+ function scriptJSON(value) {
1644
+ return JSON.stringify(value).replace(/</g, "\\u003c");
1645
+ }
1646
+ /** The fields that a record in a group of `PackedState` can have. */
1647
+ const PACKED_FIELDS = /* @__PURE__ */ new Set([
1648
+ "k",
1649
+ "p",
1650
+ "o",
1651
+ "m",
1652
+ "s",
1653
+ "i",
1654
+ "c"
1655
+ ]);
1656
+ /** A group of `PackedState` while `packState` collects it. */
1657
+ /** How many of the last groups `packState` compares a record with, before it looks up its name. */
1658
+ const RECENT_GROUPS = 4;
1659
+ /** The prefix of an ID and its number after it, such as `['', 3]` or `['5.', 1]`. */
1660
+ function splitId(id) {
1661
+ if (typeof id === "number") return ["", id];
1662
+ const dot = id.lastIndexOf(".");
1663
+ return [id.slice(0, dot + 1), Number(id.slice(dot + 1))];
1664
+ }
1665
+ /** The records of a state as a map, for a state written as an object, such as in tests. */
1666
+ function toStateMap(state) {
1667
+ if (state instanceof Map) return state;
1668
+ return new Map(Object.entries(state).map(([key, record]) => [parseId(key), record]));
1669
+ }
1670
+ /**
1671
+ * Visits the scopes of a state in the order of the keys of an object: number
1672
+ * IDs ascending, then string IDs in the order they were made. A render makes
1673
+ * its number IDs in order, so the scopes are only copied to sort them when
1674
+ * they are not.
1675
+ */
1676
+ function visitOrdered(entries, visit) {
1677
+ let numbers = entries;
1678
+ let last = -Infinity;
1679
+ for (const entry of entries) if (typeof entry.id === "number") {
1680
+ if (entry.id < last) {
1681
+ numbers = entries.filter((item) => typeof item.id === "number").toSorted((a, b) => a.id - b.id);
1682
+ break;
1683
+ }
1684
+ last = entry.id;
1685
+ }
1686
+ for (const entry of numbers) if (typeof entry.id === "number") visit(entry);
1687
+ for (const entry of entries) if (typeof entry.id !== "number") visit(entry);
1688
+ }
1689
+ /**
1690
+ * The list that the client can take the items of a group from: the items
1691
+ * are list items with the same source, the source's record is in `state`,
1692
+ * and the item of the scope at each position of the group is the value at
1693
+ * that position of the list. The client reads the same list, so it gets the
1694
+ * same values. Otherwise the items are written.
1695
+ */
1696
+ function groupSource(record, group) {
1697
+ const { entries } = group;
1698
+ const source = entries[0].source;
1699
+ if (!source || !(group.flags & 3)) return;
1700
+ const value = record(source[0])?.s?.[source[1]];
1701
+ const list = Array.isArray(value) ? value : value instanceof Set ? Array.from(value) : void 0;
1702
+ if (!list || list.length < entries.length) return;
1703
+ for (let n = 0; n < entries.length; n++) {
1704
+ const entry = entries[n];
1705
+ if (entry.source !== source || !Object.is(list[n], entry.record.i)) return;
1706
+ }
1707
+ return source;
1708
+ }
1709
+ /**
1710
+ * Writes the records of scopes with the same kind, parent and shape, such as
1711
+ * the items of a list, in groups. Each one then costs its slots and the gap
1712
+ * to the ID before it. The items of a list whose list is in `sources` and in
1713
+ * the state are not written. See `PackedState`.
1714
+ */
1715
+ function packState(input, sources) {
1716
+ const state = toStateMap(input);
1717
+ return packEntries(Array.from(state, ([id, record]) => {
1718
+ const [prefix, n] = splitId(id);
1719
+ return {
1720
+ id,
1721
+ prefix,
1722
+ n,
1723
+ record,
1724
+ ctx: void 0,
1725
+ source: sources?.get(id)
1726
+ };
1727
+ }), (id) => state.get(id));
1728
+ }
1729
+ /** Packs the scopes of a render. `lookup` finds the record of a scope in the same state. */
1730
+ function packEntries(scopes, lookup) {
1731
+ const result = {};
1732
+ const groups = /* @__PURE__ */ new Map();
1733
+ const recent = [];
1734
+ visitOrdered(scopes, (entry) => {
1735
+ const { id, record, prefix, n } = entry;
1736
+ let base = record.p;
1737
+ if (base === void 0 && record.o !== void 0) {
1738
+ const [ownerPrefix, owner] = splitId(record.o);
1739
+ base = ownerPrefix === prefix ? n - owner : void 0;
1740
+ }
1741
+ if (record.k === void 0 || base === void 0 || record.p !== void 0 && record.o !== void 0 || !Object.keys(record).every((field) => PACKED_FIELDS.has(field))) {
1742
+ result[id] = record;
1743
+ return;
1744
+ }
1745
+ const slots = record.s ?? [];
1746
+ let flags = record.p === void 0 ? 8 : 0;
1747
+ if ("i" in record) flags |= slots.length > 0 && Object.is(record.i, slots[0]) ? 1 : 2;
1748
+ if (record.c) flags |= 4;
1749
+ if (record.m !== void 0) flags |= 16;
1750
+ let group = recent.find((item) => item.k === record.k && item.base === base && item.flags === flags && item.count === slots.length && item.m === record.m && item.prefix === prefix);
1751
+ if (!group) {
1752
+ const name = `${prefix}:${record.k}:${base}:${flags}:${slots.length}:${record.m ?? ""}`;
1753
+ group = groups.get(name);
1754
+ if (!group) {
1755
+ group = {
1756
+ k: record.k,
1757
+ base,
1758
+ flags,
1759
+ count: slots.length,
1760
+ m: record.m,
1761
+ prefix,
1762
+ entries: []
1763
+ };
1764
+ groups.set(name, group);
1765
+ }
1766
+ recent.unshift(group);
1767
+ if (recent.length > RECENT_GROUPS) recent.pop();
1768
+ }
1769
+ group.entries.push(entry);
1770
+ });
1771
+ const packed = [];
1772
+ for (const group of groups.values()) {
1773
+ const { entries } = group;
1774
+ if (entries.length === 1) {
1775
+ result[entries[0].id] = entries[0].record;
1776
+ continue;
1777
+ }
1778
+ const source = groupSource(lookup, group);
1779
+ let flags = source ? group.flags | 32 : group.flags;
1780
+ if (group.prefix) flags |= 64;
1781
+ const values = [
1782
+ group.k,
1783
+ group.base,
1784
+ flags,
1785
+ group.count
1786
+ ];
1787
+ if (group.m !== void 0) values.push(group.m);
1788
+ if (source) values.push(source[0], source[1]);
1789
+ if (group.prefix) values.push(group.prefix);
1790
+ const from = source && flags & 1 ? 1 : 0;
1791
+ const item = !source && flags & 2;
1792
+ let last = flags & 72 ? 0 : group.base;
1793
+ for (const { n: number, record: scope } of entries) {
1794
+ values.push(number - last);
1795
+ const slots = scope.s ?? [];
1796
+ for (let n = from; n < slots.length; n++) values.push(slots[n]);
1797
+ if (item) values.push(scope.i);
1798
+ if (flags & 4) values.push(scope.c);
1799
+ last = number;
1800
+ }
1801
+ packed.push(values);
1802
+ }
1803
+ if (packed.length > 0) result.g = packed;
1804
+ return result;
1805
+ }
1806
+ /**
1807
+ * Serializes the page state as seroval cross-reference code, one record at
1808
+ * a time. The first record holds the state, and each later record settles a
1809
+ * promise in it. Records that share `refs` can refer to each other's values.
1810
+ *
1811
+ * With `last`, no later record of the render reads this one, so a state
1812
+ * without promises is one record that assigns only the references that it
1813
+ * uses twice. That record is smaller, and faster to write. A state with a
1814
+ * promise makes `crossSerialize` throw, and then it streams as usual.
1815
+ */
1816
+ function serializeState(state, refs, onRecord, onError, onDone, sources, last = false) {
1817
+ const packed = state instanceof Context ? packEntries(state.scopes, (id) => state.ownRecord(id)) : packState(state, sources);
1818
+ let leaked = false;
1819
+ const send = (code, initial) => {
1820
+ const error = leaked ? void 0 : secretError(code);
1821
+ if (error) {
1822
+ leaked = true;
1823
+ onError(error);
1824
+ } else if (!leaked) onRecord(code, initial);
1825
+ };
1826
+ if (last) {
1827
+ let code;
1828
+ try {
1829
+ code = crossSerialize(packed, {
1830
+ plugins: syncPlugins,
1831
+ disabledFeatures,
1832
+ refs,
1833
+ assignSharedRefsOnly: true
1834
+ });
1835
+ } catch {
1836
+ refs.clear();
1837
+ }
1838
+ if (code !== void 0) {
1839
+ send(code, true);
1840
+ onDone();
1841
+ return;
1842
+ }
1843
+ }
1844
+ crossSerializeStream(packed, {
1845
+ plugins,
1846
+ disabledFeatures,
1847
+ refs,
1848
+ onSerialize: send,
1849
+ onError,
1850
+ onDone
1851
+ });
1852
+ }
1853
+ /**
1854
+ * Serializes the page state as the code of state records. `onRecord`
1855
+ * receives each record as soon as it is ready. The promise resolves when
1856
+ * every promise in the state has settled.
1857
+ */
1858
+ function streamState(state, onRecord) {
1859
+ return new Promise((resolve, reject) => {
1860
+ serializeState(state, /* @__PURE__ */ new Map(), onRecord, reject, resolve);
1861
+ });
1862
+ }
1863
+ /**
1864
+ * Defines `$bR`, which hands the code of a state record and its script to
1865
+ * the core, through `self.$brm`. The core runs the code when it starts, or
1866
+ * at once when it has started. The first record of each render defines it.
1867
+ */
1868
+ const RECORD = "function $bR(f){(self.$brm=self.$brm||[]).push([document.currentScript,f])}";
1869
+ /**
1870
+ * Returns the script of a state record. `scopes` marks a record with scopes,
1871
+ * as opposed to one that settles a promise. The record is code that seroval
1872
+ * wrote, as a function of the references of its render, `$R`, and of the
1873
+ * functions that make brumate's values, `$b`. seroval escapes every `<` in
1874
+ * the strings in it.
1875
+ */
1876
+ function stateScript(code, scopes = false, attributes = {}) {
1877
+ if (code.includes("</") || code.includes("<!")) throw new Error("A state record would end its script");
1878
+ let extra = attributes.nonce === void 0 ? "" : ` nonce="${escapeAttribute(attributes.nonce)}"`;
1879
+ extra += " b-state";
1880
+ if (scopes) extra += " b-scopes";
1881
+ if (attributes.next !== void 0) extra += ` b-next="${attributes.next}"`;
1882
+ if (attributes.root) extra += ` b-root="${attributes.root}"`;
1883
+ if (attributes.route !== void 0) extra += ` b-route="${escapeAttribute(attributes.route)}"`;
1884
+ if (attributes.params !== void 0) extra += ` b-params="${escapeAttribute(JSON.stringify(attributes.params))}"`;
1885
+ if (attributes.build !== void 0) extra += ` b-build="${escapeAttribute(attributes.build)}"`;
1886
+ return `<script${extra}>${attributes.define ? RECORD : ""}$bR(($R,$b)=>(${code}))<\/script>`;
1887
+ }
1888
+ const HEAD = `function $bH(i,t){var e=document.querySelector('template[b-h="'+i+'"]'),h=document.head;e&&(h.append(e.content),e.remove());t!=null&&(h.querySelector('title:not([b-t])')||h.prepend(document.createElement('title')),document.title=t)}`;
1889
+ const SWAP = `function $bS(i){var t=document.querySelector('template[b-l="'+i+'"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode;for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\d/.test(n.data))d++}var x=n.nextSibling;p.removeChild(n);n=x}p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;
1890
+ /** The `pending` of a render that has nothing left to send. */
1891
+ const NOTHING_PENDING = { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({
1892
+ done: true,
1893
+ value: void 0
1894
+ }) }) };
1895
+ /** An async iterable that a producer pushes into. */
1896
+ function createQueue() {
1897
+ const items = [];
1898
+ let wake;
1899
+ let closed = false;
1900
+ let failure;
1901
+ const notify = () => {
1902
+ wake?.();
1903
+ wake = void 0;
1904
+ };
1905
+ return {
1906
+ push(item) {
1907
+ items.push(item);
1908
+ notify();
1909
+ },
1910
+ close() {
1911
+ closed = true;
1912
+ notify();
1913
+ },
1914
+ fail(error) {
1915
+ failure = { error };
1916
+ notify();
1917
+ },
1918
+ iterable: { async *[Symbol.asyncIterator]() {
1919
+ for (;;) if (items.length > 0) yield items.shift();
1920
+ else if (failure) throw failure.error;
1921
+ else if (closed) return;
1922
+ else await new Promise((resolve) => {
1923
+ wake = resolve;
1924
+ });
1925
+ } }
1926
+ };
1927
+ }
1928
+ /**
1929
+ * Renders the parts of a page. It returns as soon as the markup is rendered.
1930
+ * `#loading` bodies and promises in the state do not hold it up: they come
1931
+ * later, from `pending`. `renderToStream` puts the parts together. Use this
1932
+ * directly to send the response headers that server functions set before
1933
+ * the stream starts.
1934
+ */
1935
+ async function render(Root, props, options = {}) {
1936
+ const scriptTag = options.nonce === void 0 ? "<script>" : `<script nonce="${escapeAttribute(options.nonce)}">`;
1937
+ const ctx = new Context(void 0, options.rpc, options.base);
1938
+ if (options.actions) ctx.actions = options.actions;
1939
+ if (options.params) ctx.params = options.params;
1940
+ ctx.build = options.build;
1941
+ if (options.defer) ctx.target = { ...options.defer };
1942
+ ctx.inOrder = !options.defer && rendersInOrder(options.inOrder ?? "bots", options.request ?? options.event?.request);
1943
+ const event = options.event ?? (options.request ? new RequestEvent(options.request, {
1944
+ kind: options.defer ? "defer" : "page",
1945
+ waitUntil: options.waitUntil,
1946
+ address: options.address,
1947
+ prerender: options.prerender
1948
+ }) : void 0);
1949
+ ctx.event = event;
1950
+ const rendered = await ctx.run(() => Root(props, ctx));
1951
+ ctx.send();
1952
+ const html = beforeBodyEnd(rendered, ctx.portals.join(""));
1953
+ let queue;
1954
+ const pending = () => queue ??= createQueue();
1955
+ const refs = /* @__PURE__ */ new Map();
1956
+ const { nonce } = options;
1957
+ const root = options.defer ? `d${options.defer.boundary}` : options.base;
1958
+ let first = true;
1959
+ let open = 0;
1960
+ let swap = false;
1961
+ let headSwap = false;
1962
+ const finish = () => {
1963
+ open--;
1964
+ if (open === 0) queue?.close();
1965
+ };
1966
+ let boundaries = 0;
1967
+ const serialize = (target, onScopes, route, onError = (error) => pending().fail(unsendable(error, target)), last = false) => {
1968
+ open++;
1969
+ serializeState(target, refs, (code, initial) => {
1970
+ if (initial) {
1971
+ onScopes(stateScript(code, true, {
1972
+ next: ctx.next(),
1973
+ route,
1974
+ root,
1975
+ nonce,
1976
+ define: first,
1977
+ params: route === void 0 ? void 0 : options.params,
1978
+ build: first ? options.build : void 0
1979
+ }));
1980
+ first = false;
1981
+ } else pending().push(stateScript(code, false, {
1982
+ root,
1983
+ nonce
1984
+ }));
1985
+ }, onError, finish, void 0, last);
1986
+ };
1987
+ const inOrder = ctx.inOrder ? [] : void 0;
1988
+ const stopped = () => event?.signal.aborted === true;
1989
+ event?.signal.addEventListener("abort", () => queue?.close(), { once: true });
1990
+ ctx.watch((boundary) => {
1991
+ if (inOrder) {
1992
+ inOrder.push(boundary);
1993
+ return;
1994
+ }
1995
+ boundaries++;
1996
+ open++;
1997
+ boundary.render.then((result) => {
1998
+ if (boundary.cancelled || boundary.around || stopped()) {
1999
+ finish();
2000
+ return;
2001
+ }
2002
+ serialize(result.ctx, (script) => {
2003
+ const id = scriptJSON(boundary.id);
2004
+ let call = `${swap ? "" : SWAP}$bS(${id})`;
2005
+ swap = true;
2006
+ const late = result.ctx.lateHead();
2007
+ let head = "";
2008
+ if (late.html || late.title !== void 0) {
2009
+ head = `<template b-h="${boundary.id}">${late.html}</template>`;
2010
+ const title = late.title === void 0 ? "" : `,${scriptJSON(late.title)}`;
2011
+ call += `;${headSwap ? "" : HEAD}$bH(${id}${title})`;
2012
+ headSwap = true;
2013
+ }
2014
+ pending().push(`<template b-l="${boundary.id}">${result.html}</template>${head}${result.ctx.portals.join("")}${scriptTag}${call}<\/script>${script}`);
2015
+ });
2016
+ finish();
2017
+ }, (error) => {
2018
+ console.error(error);
2019
+ finish();
2020
+ });
2021
+ });
2022
+ if (options.defer) return {
2023
+ html: "",
2024
+ state: "",
2025
+ pending: queue === void 0 && open === 0 ? NOTHING_PENDING : pending().iterable,
2026
+ headers: event?.headers ?? new Headers(),
2027
+ status: event?.status ?? 200,
2028
+ next: () => ctx.next(),
2029
+ head: "",
2030
+ defer: ctx.target.status ?? "missing"
2031
+ };
2032
+ let state = "";
2033
+ let failure;
2034
+ serialize(ctx, (script) => {
2035
+ state = script;
2036
+ }, options.route, (error) => {
2037
+ failure = error;
2038
+ }, boundaries === 0 && (inOrder === void 0 || inOrder.length === 0));
2039
+ if (failure !== void 0) throw unsendable(failure, ctx);
2040
+ let page = html;
2041
+ if (inOrder) {
2042
+ const bodies = /* @__PURE__ */ new Map();
2043
+ const portals = [];
2044
+ for (let index = 0; index < inOrder.length; index++) {
2045
+ const boundary = inOrder[index];
2046
+ let result;
2047
+ try {
2048
+ result = await boundary.render;
2049
+ } catch (error) {
2050
+ console.error(error);
2051
+ continue;
2052
+ }
2053
+ if (boundary.cancelled || boundary.around) continue;
2054
+ bodies.set(String(boundary.id), result.html);
2055
+ portals.push(...result.ctx.portals);
2056
+ ctx.adoptHead(result.ctx.lateHead());
2057
+ serialize(result.ctx, (script) => {
2058
+ state += script;
2059
+ }, void 0, (error) => {
2060
+ failure = error;
2061
+ }, index === inOrder.length - 1);
2062
+ if (failure !== void 0) throw unsendable(failure, result.ctx);
2063
+ }
2064
+ page = beforeBodyEnd(inlineBodies(rendered, bodies), [...ctx.portals, ...portals].join(""));
2065
+ }
2066
+ return {
2067
+ html: page,
2068
+ state,
2069
+ pending: queue === void 0 && open === 0 ? NOTHING_PENDING : pending().iterable,
2070
+ headers: event?.headers ?? new Headers(),
2071
+ status: event?.status ?? 200,
2072
+ next: () => ctx.next(),
2073
+ head: ctx.headHTML(),
2074
+ event
2075
+ };
2076
+ }
2077
+ /** Crawlers and link previews, which read the page without running its scripts. */
2078
+ const BOTS = /bot\b|bot\/|crawl|spider|slurp|bingpreview|facebookexternalhit|embedly|quora link preview|outbrain|pinterest|vkshare|w3c_validator|whatsapp|lighthouse|google-inspectiontool|headlesschrome/i;
2079
+ /** True if a render with these options writes its bodies in place. */
2080
+ function rendersInOrder(option, request) {
2081
+ if (typeof option === "boolean") return option;
2082
+ if (!request) return false;
2083
+ if (typeof option === "function") return option(request);
2084
+ return BOTS.test(request.headers.get("user-agent") ?? "");
2085
+ }
2086
+ const BOUNDARY_MARKER = /<!--(l[\d.]+|\/l)-->/g;
2087
+ /**
2088
+ * Puts the bodies of boundaries in place of their fallbacks, with the bodies
2089
+ * inside them, as the swap script would in the browser. A `#defer` block
2090
+ * loses its `<template>` too, so the browser does not ask for a body that
2091
+ * is there. A boundary without a body keeps its fallback.
2092
+ */
2093
+ function inlineBodies(html, bodies) {
2094
+ let result = "";
2095
+ let position = 0;
2096
+ BOUNDARY_MARKER.lastIndex = 0;
2097
+ for (let match = BOUNDARY_MARKER.exec(html); match; match = BOUNDARY_MARKER.exec(html)) {
2098
+ if (match[1] === "/l") continue;
2099
+ const id = match[1].slice(1);
2100
+ let depth = 0;
2101
+ let end = -1;
2102
+ for (let inner = BOUNDARY_MARKER.exec(html); inner; inner = BOUNDARY_MARKER.exec(html)) if (inner[1] !== "/l") depth++;
2103
+ else if (depth === 0) {
2104
+ end = inner.index + inner[0].length;
2105
+ break;
2106
+ } else depth--;
2107
+ if (end === -1) break;
2108
+ const body = bodies.get(id);
2109
+ if (body === void 0) continue;
2110
+ let before = html.slice(position, match.index);
2111
+ before = before.replace(new RegExp(`<template b-b="[^"]*" b-defer="[^":]*:${id.replace(/\./g, "\\.")}:[^"]*"></template>$`), "");
2112
+ result += before + inlineBodies(body, bodies);
2113
+ position = end;
2114
+ BOUNDARY_MARKER.lastIndex = end;
2115
+ }
2116
+ return result + html.slice(position);
2117
+ }
2118
+ const HTML = /<html[\s>]/i;
2119
+ /**
2120
+ * Inserts markup before `</body>`, or at the end if there is none. `index`
2121
+ * is where `</body>` is, when the caller found it already.
2122
+ */
2123
+ function beforeBodyEnd(html, content, index = content ? html.toLowerCase().lastIndexOf("</body>") : -1) {
2124
+ if (!content) return html;
2125
+ return index === -1 ? html + content : html.slice(0, index) + content + html.slice(index);
2126
+ }
2127
+ /**
2128
+ * Builds the first chunk of a page: the whole rendered document, with the
2129
+ * page state and the scripts. A component that renders `<html>` gets the
2130
+ * doctype, its head before `</head>`, and the state and scripts before
2131
+ * `</body>`. Markup that resolves later is written after it.
2132
+ */
2133
+ function firstRender(html, componentHead, state, options) {
2134
+ const head = (options.head ?? "") + componentHead;
2135
+ const tail = state + (options.scripts ?? "");
2136
+ const match = HTML.exec(html);
2137
+ if (!match) return (typeof options.start === "function" ? options.start(head) : options.start ?? "") + html + tail + (options.end ?? "");
2138
+ const headContent = html.slice(0, match.index) + head;
2139
+ let page = html.slice(match.index);
2140
+ const lower = page.toLowerCase();
2141
+ const headEnd = lower.indexOf("</head>");
2142
+ let bodyEnd = lower.lastIndexOf("</body>");
2143
+ let at = headEnd;
2144
+ let inserted = headContent;
2145
+ if (headEnd === -1 && headContent) {
2146
+ const bodyStart = lower.search(/<body[\s>]/);
2147
+ at = bodyStart === -1 ? page.indexOf(">") + 1 : bodyStart;
2148
+ inserted = `<head>${headContent}</head>`;
2149
+ }
2150
+ if (at !== -1 && inserted) {
2151
+ page = page.slice(0, at) + inserted + page.slice(at);
2152
+ const own = inserted.toLowerCase();
2153
+ if (bodyEnd >= at) bodyEnd += own.length;
2154
+ else if (own.includes("</body>")) bodyEnd = at + own.lastIndexOf("</body>");
2155
+ }
2156
+ return `<!doctype html>${beforeBodyEnd(page, tail, bodyEnd)}`;
2157
+ }
2158
+ /**
2159
+ * Renders a component as a stream. The first chunk is the whole first
2160
+ * render, sent as soon as it is ready. Each `#loading` body and each state
2161
+ * record that settles a promise follows it as it resolves. A component that
2162
+ * renders `<html>` gets the doctype and its head.
2163
+ */
2164
+ function renderToStream(Root, props, options = {}) {
2165
+ return partsStream(() => render(Root, props, options), options);
2166
+ }
2167
+ /** Streams the parts of a page from `render`: the first render whole, then what resolves later. */
2168
+ function streamParts(parts, options = {}) {
2169
+ return partsStream(() => parts, options);
2170
+ }
2171
+ /** A stream of the parts of a page. An error while it gets or writes them fails the stream. */
2172
+ function partsStream(getParts, options) {
2173
+ let parts;
2174
+ let cancelled = false;
2175
+ return new ReadableStream({
2176
+ async start(controller) {
2177
+ try {
2178
+ parts = await getParts();
2179
+ if (cancelled) {
2180
+ parts.event?.abort();
2181
+ return;
2182
+ }
2183
+ await writeParts(parts, options, controller, () => cancelled);
2184
+ } catch (error) {
2185
+ if (!cancelled) controller.error(error);
2186
+ }
2187
+ },
2188
+ cancel(reason) {
2189
+ cancelled = true;
2190
+ parts?.event?.abort(reason);
2191
+ }
2192
+ });
2193
+ }
2194
+ async function writeParts(parts, options, controller, cancelled = () => false) {
2195
+ controller.enqueue(firstRender(parts.html, parts.head, parts.state, options));
2196
+ if (parts.pending !== NOTHING_PENDING) for await (const chunk of parts.pending) {
2197
+ if (cancelled()) return;
2198
+ controller.enqueue(chunk);
2199
+ }
2200
+ if (!cancelled()) controller.close();
2201
+ }
2202
+ /**
2203
+ * The message and status that answer an error. A `ServerError` sends its
2204
+ * own. Any other error is logged, and sends `fallback` with status 500.
2205
+ */
2206
+ function errorAnswer(error, fallback) {
2207
+ if (error instanceof ServerError) return {
2208
+ message: error.message,
2209
+ status: error.status
2210
+ };
2211
+ console.error(error);
2212
+ return {
2213
+ message: fallback,
2214
+ status: 500
2215
+ };
2216
+ }
2217
+ /** True for a request that a `<form>` sent, without client code. */
2218
+ function isFormPost(request) {
2219
+ const type = request.headers.get("content-type") ?? "";
2220
+ return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
2221
+ }
2222
+ /** The answer to a call or a form post from a page of another site. See `isCrossSite`. */
2223
+ function crossSiteAnswer() {
2224
+ return new Response("Calls from other sites are not allowed", { status: 403 });
2225
+ }
2226
+ /** The answer to a call or a form post to a server function that does not exist. */
2227
+ function unknownAnswer(id) {
2228
+ return new Response(`Unknown server function "${id}"`, { status: 404 });
2229
+ }
2230
+ /**
2231
+ * A response with `init`. A DOM environment such as happy-dom drops
2232
+ * `set-cookie` from the headers that a response is made with, but keeps the
2233
+ * ones added after, so a page in `brumate/testing` keeps its cookies.
2234
+ */
2235
+ function respond(body, init) {
2236
+ const result = new Response(body, init);
2237
+ if (result.headers.getSetCookie().length === 0) for (const cookie of init.headers.getSetCookie()) result.headers.append("set-cookie", cookie);
2238
+ return result;
2239
+ }
2240
+ /**
2241
+ * True when a request names a build other than the server's, so its page is
2242
+ * from before a deploy. Calls send the build in `x-brumate-build`, and forms
2243
+ * without scripts in `__build` of their URL.
2244
+ */
2245
+ function isSkewed(request, build) {
2246
+ const sent = request.headers.get("x-brumate-build") ?? new URL(request.url).searchParams.get("__build");
2247
+ return build !== void 0 && sent !== null && sent !== build;
2248
+ }
2249
+ /**
2250
+ * The answer to a form without scripts, from a page of another build, that
2251
+ * posts to a function that is gone. It goes back to its page, which loads
2252
+ * with the new build, or to `/` when the page is on another site.
2253
+ */
2254
+ function backAnswer(request) {
2255
+ let location = "/";
2256
+ const referer = request.headers.get("referer");
2257
+ if (referer) try {
2258
+ const page = new URL(referer);
2259
+ if (page.origin === new URL(request.url).origin) location = `${page.pathname}${page.search}`;
2260
+ } catch {}
2261
+ return new Response(null, {
2262
+ status: 303,
2263
+ headers: { location }
2264
+ });
2265
+ }
2266
+ /** The answer to a request from a page of another build that the server cannot serve. */
2267
+ function skewAnswer(build) {
2268
+ return new Response(JSON.stringify({ error: "The site changed. Load the page again" }), {
2269
+ status: 409,
2270
+ headers: {
2271
+ "content-type": "application/json",
2272
+ "x-brumate-build": build
2273
+ }
2274
+ });
2275
+ }
2276
+ /**
2277
+ * Calls a server function with the data of a form that the browser sent.
2278
+ * Returns its result, or the response that answers the post instead: a
2279
+ * `redirect` in the function sends the browser there, and an error answers
2280
+ * with a short text page, because there is no page to report it in. The
2281
+ * response has `headers`. With `base`, the location of a redirect is
2282
+ * resolved against it.
2283
+ */
2284
+ async function callWithForm(invoke, headers, base) {
2285
+ try {
2286
+ return { result: await invoke() };
2287
+ } catch (error) {
2288
+ return { answer: formFailure(error, headers, base) };
2289
+ }
2290
+ }
2291
+ /** The answer to a form post whose server function threw, or whose data could not be read. */
2292
+ function formFailure(error, headers, base) {
2293
+ if (error instanceof Redirect) {
2294
+ headers.set("location", base ? new URL(error.location, base).href : error.location);
2295
+ return respond(null, {
2296
+ status: error.status,
2297
+ headers
2298
+ });
2299
+ }
2300
+ const { message, status } = errorAnswer(error, "The server function failed");
2301
+ headers.set("content-type", "text/plain; charset=utf-8");
2302
+ return respond(message, {
2303
+ status,
2304
+ headers
2305
+ });
2306
+ }
2307
+ /**
2308
+ * Calls a server function with the data of a form that the browser sent, and
2309
+ * sends the browser back to the page with a redirect. The response has the
2310
+ * headers of the event, such as cookies that the function set.
2311
+ */
2312
+ async function handleForm(invoke, event) {
2313
+ const { headers } = event;
2314
+ const outcome = await callWithForm(invoke, headers);
2315
+ if ("answer" in outcome) return outcome.answer;
2316
+ headers.set("location", event.request.headers.get("referer") ?? "/");
2317
+ return respond(null, {
2318
+ status: 303,
2319
+ headers
2320
+ });
2321
+ }
2322
+ /**
2323
+ * The arguments of a call. They come as seroval JSON, or as multipart form
2324
+ * data when they hold files: the JSON in `args`, and each file in
2325
+ * `file<index>`, whose index stands in the JSON.
2326
+ */
2327
+ async function readArgs(request) {
2328
+ if (!request.headers.has("x-brumate-args")) return fromJSON(await request.json(), {
2329
+ plugins,
2330
+ disabledFeatures
2331
+ });
2332
+ const form = await request.formData();
2333
+ return fromJSON(JSON.parse(String(form.get("args"))), {
2334
+ plugins: callPlugins(void 0, form),
2335
+ disabledFeatures
2336
+ });
2337
+ }
2338
+ /**
2339
+ * True when a request comes from a page of another site. Server function
2340
+ * calls and form posts send the cookies of the user, so another site must
2341
+ * not be able to make them.
2342
+ *
2343
+ * The browser sends `Origin` with every call and post. Without it, an older
2344
+ * browser's `Sec-Fetch-Site` decides. A request with neither does not come
2345
+ * from a page in a browser, so it is allowed.
2346
+ */
2347
+ function isCrossSite(request, options = {}) {
2348
+ const origin = request.headers.get("origin");
2349
+ if (origin === null) {
2350
+ const site = request.headers.get("sec-fetch-site");
2351
+ return site === "cross-site" || site === "same-site";
2352
+ }
2353
+ if (origin === "null") return true;
2354
+ if (options.origins?.includes(origin)) return false;
2355
+ let host;
2356
+ try {
2357
+ host = new URL(origin).host;
2358
+ } catch {
2359
+ return true;
2360
+ }
2361
+ return ![
2362
+ new URL(request.url).host,
2363
+ request.headers.get("host"),
2364
+ request.headers.get("x-forwarded-host")
2365
+ ].includes(host);
2366
+ }
2367
+ /**
2368
+ * Answers a server function call from `brumate/client`. Returns undefined
2369
+ * when the request is not a call, so other handlers can answer it. Server
2370
+ * functions read the request with `getEvent()`. A call from a page of
2371
+ * another site answers 403. See `isCrossSite`.
2372
+ */
2373
+ async function handleRequest(functions, request, prefix = "/_brumate", options = {}) {
2374
+ const url = new URL(request.url);
2375
+ if (request.method !== "POST" || !url.pathname.startsWith(`${prefix}/`)) return;
2376
+ if (isCrossSite(request, options)) return crossSiteAnswer();
2377
+ const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));
2378
+ if (id === "") {
2379
+ const headers = options.build === void 0 ? {} : { "x-brumate-build": options.build };
2380
+ return new Response(null, {
2381
+ status: 204,
2382
+ headers
2383
+ });
2384
+ }
2385
+ const form = isFormPost(request) && !request.headers.has("x-brumate-args");
2386
+ const posted = form && !request.headers.has("x-brumate-result");
2387
+ const fn = functions[id];
2388
+ if (!fn) {
2389
+ if (!isSkewed(request, options.build)) return unknownAnswer(id);
2390
+ return posted ? backAnswer(request) : skewAnswer(options.build);
2391
+ }
2392
+ const event = new RequestEvent(request, {
2393
+ kind: "call",
2394
+ waitUntil: options.waitUntil,
2395
+ address: options.address,
2396
+ prerender: options.prerender
2397
+ });
2398
+ let args;
2399
+ try {
2400
+ args = form ? [await request.formData()] : await readArgs(request);
2401
+ } catch (error) {
2402
+ return posted ? formFailure(error, event.headers) : callFailure(error, event.headers);
2403
+ }
2404
+ event.call = {
2405
+ id,
2406
+ args
2407
+ };
2408
+ const invoke = () => withEvent(event, () => fn(...args));
2409
+ return runEntry(options.middleware, event, () => runEntry(options.fileMiddleware?.[id], event, () => posted ? handleForm(invoke, event) : answerCall(functions, event, async () => invoke())));
2410
+ }
2411
+ /**
2412
+ * Answers a server function call with its result as a stream of seroval
2413
+ * chunks, so promises and async iterables in it stream as they settle. A
2414
+ * redirect is sent as a header, so the client can follow it. An error
2415
+ * answers with a message that the client throws.
2416
+ */
2417
+ async function answerCall(functions, event, run) {
2418
+ const { headers } = event;
2419
+ try {
2420
+ const result = await run();
2421
+ const { refreshed } = event;
2422
+ if (refreshed?.size) {
2423
+ const ids = Object.keys(functions).filter((key) => refreshed.has(unwrap(functions[key])));
2424
+ if (ids.length > 0) headers.set("x-brumate-refresh", ids.join(","));
2425
+ }
2426
+ headers.set("content-type", STREAM_TYPE);
2427
+ return respond(toChunkStream(result, (reason) => event.abort(reason)), { headers });
2428
+ } catch (error) {
2429
+ return callFailure(error, headers);
2430
+ }
2431
+ }
2432
+ /** The answer to a call whose server function threw, or whose arguments could not be read. */
2433
+ function callFailure(error, headers) {
2434
+ if (error instanceof Redirect) {
2435
+ headers.set("x-brumate-redirect", error.location);
2436
+ return respond(null, {
2437
+ status: 204,
2438
+ headers
2439
+ });
2440
+ }
2441
+ const { message, status } = errorAnswer(error, "The server function failed");
2442
+ headers.set("content-type", "application/json");
2443
+ return respond(JSON.stringify({ error: message }), {
2444
+ status,
2445
+ headers
2446
+ });
2447
+ }
2448
+ /** Imports every module of a matched route before it renders. */
2449
+ async function resolveView(view) {
2450
+ const [module, loading, ...slots] = await Promise.all([
2451
+ view.load(),
2452
+ view.loading?.(),
2453
+ ...Object.values(view.slots).map(resolveView)
2454
+ ]);
2455
+ const names = Object.keys(view.slots);
2456
+ return {
2457
+ key: view.key,
2458
+ component: module.default,
2459
+ loading: loading?.default,
2460
+ slots: Object.fromEntries(names.map((name, index) => [name, slots[index]]))
2461
+ };
2462
+ }
2463
+ /**
2464
+ * Renders a view where its layout inserts it. A view with a loading file
2465
+ * streams in after the rest of the page, as a `#loading` body does.
2466
+ */
2467
+ async function renderView(view, props, ctx, scope) {
2468
+ if (!view.loading) return component(viewComponent(view, props), {}, ctx, scope);
2469
+ const id = ctx.boundary();
2470
+ const fallback = await component(view.loading, props, ctx, scope);
2471
+ ctx.defer(id, (child) => component(viewComponent(view, props), {}, child, scope));
2472
+ return `<!--l${id}-->${fallback}<!--/l-->`;
2473
+ }
2474
+ /**
2475
+ * A component that renders a route, with its slots rendering where the
2476
+ * layout inserts them. `props` go to every view, such as `params`.
2477
+ */
2478
+ function viewComponent(view, props) {
2479
+ return (_props, ctx) => {
2480
+ const own = { ...props };
2481
+ for (const [name, slot] of Object.entries(view.slots)) own[name] = lazy(async (at, scope) => {
2482
+ const root = at.peek();
2483
+ const html = await renderView(slot, props, at, scope);
2484
+ return `<!--R${scope ?? -1}:${name}:${root}:${encodeURIComponent(slot.key)}-->${html}<!--/R-->`;
2485
+ });
2486
+ return view.component(own, ctx);
2487
+ };
2488
+ }
2489
+ /**
2490
+ * Runs the server function that a form without scripts posted to a page, as
2491
+ * `?__action=<id>`. Returns its result for `$action`, or the response that
2492
+ * answers the post instead of the page: a redirect, or an error.
2493
+ * `handleRoute` adds the cookies of the event to that response, and no other
2494
+ * headers of the event.
2495
+ */
2496
+ async function runAction(fn, event) {
2497
+ const { request } = event;
2498
+ const args = event.call.args;
2499
+ const outcome = await callWithForm(() => withEvent(event, () => fn(...args)), new Headers(), request.url);
2500
+ return "answer" in outcome ? outcome : { actions: /* @__PURE__ */ new Map([[fn, outcome.result]]) };
2501
+ }
2502
+ /**
2503
+ * Reads the server function that a form without scripts posted to a page,
2504
+ * as `?__action=<id>`, into `event.call`, before any middleware runs.
2505
+ * Returns the response that answers the post instead of the page: a post
2506
+ * from another site, an unknown function, or a form that cannot be read.
2507
+ */
2508
+ async function readAction(url, event, options) {
2509
+ const { request } = event;
2510
+ const id = url.searchParams.get("__action");
2511
+ if (request.method !== "POST" || id === null) return;
2512
+ if (isCrossSite(request, options)) return crossSiteAnswer();
2513
+ if (!options.functions?.[id]) return isSkewed(request, options.build) ? backAnswer(request) : unknownAnswer(id);
2514
+ try {
2515
+ event.call = {
2516
+ id,
2517
+ args: [await request.formData()]
2518
+ };
2519
+ } catch (error) {
2520
+ return formFailure(error, new Headers(), request.url);
2521
+ }
2522
+ }
2523
+ /** Renders the page of a route tree, streamed, with the results of a form for `$action`. */
2524
+ async function renderPage(view, props, request, options, extra) {
2525
+ const base = Number(request.headers.get("x-brumate-base"));
2526
+ const defer = deferTarget(request);
2527
+ if (defer) return renderDeferred(view, props, request, options, defer, base);
2528
+ const hints = request.headers.has("x-brumate-base") ? [] : options.hints ?? [];
2529
+ const links = hints.map((url) => `<${url}>; rel=modulepreload`);
2530
+ if (links.length > 0) options.earlyHints?.(links);
2531
+ const preload = hints.map((url) => `<link rel="modulepreload" href="${escapeAttribute(url)}">`).join("");
2532
+ const parts = await render(viewComponent(view, props), {}, {
2533
+ ...options,
2534
+ request,
2535
+ actions: extra.actions,
2536
+ route: view.key,
2537
+ params: props.params,
2538
+ base: Number.isSafeInteger(base) && base > 0 ? base : void 0
2539
+ });
2540
+ const headers = new Headers(parts.headers);
2541
+ headers.set("content-type", "text/html; charset=utf-8");
2542
+ headers.append("vary", "x-brumate-defer");
2543
+ headers.append("vary", "x-brumate-base");
2544
+ for (const link of links) headers.append("link", link);
2545
+ return respond(streamParts(parts, {
2546
+ ...options,
2547
+ head: preload + (options.head ?? "")
2548
+ }).pipeThrough(new TextEncoderStream()), {
2549
+ status: extra.status ?? parts.status,
2550
+ headers
2551
+ });
2552
+ }
2553
+ /**
2554
+ * The `#defer` block that a request asks for, from `x-brumate-defer:
2555
+ * <boundary> <scope>:<anchor>`, which the browser sends when the block's
2556
+ * trigger fires.
2557
+ */
2558
+ function deferTarget(request) {
2559
+ const match = /^([\d.]+) (-?[\d.]+:\d+)$/.exec(request.headers.get("x-brumate-defer") ?? "");
2560
+ return match ? {
2561
+ boundary: parseId(match[1]),
2562
+ at: match[2]
2563
+ } : void 0;
2564
+ }
2565
+ /**
2566
+ * Renders the route again and answers with the body of one `#defer` block:
2567
+ * its markup in a `<template b-l>`, the script that swaps it in, and its
2568
+ * state. The page renders with the base it had, so its IDs come out the
2569
+ * same. When the block is not where the browser has it, such as after the
2570
+ * data of the page changed, the answer is 409 and the fallback stays.
2571
+ */
2572
+ async function renderDeferred(view, props, request, options, defer, base) {
2573
+ const parts = await render(viewComponent(view, props), {}, {
2574
+ ...options,
2575
+ request,
2576
+ route: view.key,
2577
+ params: props.params,
2578
+ base: Number.isSafeInteger(base) && base > 0 ? base : void 0,
2579
+ defer
2580
+ });
2581
+ const headers = new Headers(parts.headers);
2582
+ headers.append("vary", "x-brumate-defer");
2583
+ if (parts.defer !== "found") return respond(null, {
2584
+ status: parts.defer === "moved" ? 409 : 404,
2585
+ headers
2586
+ });
2587
+ headers.set("content-type", "text/html; charset=utf-8");
2588
+ headers.set("x-brumate-defer", String(defer.boundary));
2589
+ return respond(new ReadableStream({ async start(controller) {
2590
+ try {
2591
+ if (parts.pending !== NOTHING_PENDING) for await (const chunk of parts.pending) controller.enqueue(chunk);
2592
+ controller.close();
2593
+ } catch (error) {
2594
+ controller.error(error);
2595
+ }
2596
+ } }).pipeThrough(new TextEncoderStream()), {
2597
+ status: parts.status,
2598
+ headers
2599
+ });
2600
+ }
2601
+ /**
2602
+ * Renders the first `_error.brm` that renders, from the innermost. Its
2603
+ * component gets `error`, with the message and the status.
2604
+ */
2605
+ async function renderError(views, error, params, request, options) {
2606
+ for (const view of views) try {
2607
+ return await renderPage(await resolveView(view), {
2608
+ params,
2609
+ error
2610
+ }, request, options, { status: error.status });
2611
+ } catch (failure) {
2612
+ console.error(failure);
2613
+ }
2614
+ }
2615
+ /** Runs the middleware of the folders on the path, from the outside in, around the answer. */
2616
+ async function runMiddleware(loaders, request, event, answer) {
2617
+ const [first, ...rest] = loaders;
2618
+ if (!first) return answer();
2619
+ const { middleware } = await first();
2620
+ return withEvent(event, () => middleware(request, () => runMiddleware(rest, request, event, answer)));
2621
+ }
2622
+ /**
2623
+ * Answers a request with the route that matches its path, streamed:
2624
+ *
2625
+ * - The `_middleware.ts` of each folder on the path runs first, from the outside in.
2626
+ * - An endpoint at the path answers the methods that it exports.
2627
+ * - A form without scripts that posts to the page with `?__action=<id>`
2628
+ * runs that server function first, and the page renders with its result
2629
+ * for `$action`.
2630
+ * - A route that throws renders the nearest `_error.brm`, and a path that
2631
+ * no route matches renders the `_error.brm` of the root with status 404.
2632
+ *
2633
+ * Returns undefined when no route matches and the root has no error file or
2634
+ * middleware. A `redirect` while the page renders answers with a redirect.
2635
+ */
2636
+ async function handleRoute(tree, request, options = {}) {
2637
+ const url = new URL(request.url);
2638
+ const match = matchRoute(tree, url.pathname);
2639
+ const event = options.event ?? new RequestEvent(request, {
2640
+ kind: await requestKind(request, match),
2641
+ waitUntil: options.waitUntil,
2642
+ address: options.address,
2643
+ prerender: options.prerender
2644
+ });
2645
+ event.route = match?.route;
2646
+ const answer = await routeAnswer(tree, match, url, {
2647
+ ...options,
2648
+ event
2649
+ });
2650
+ return answer && withHeaders(answer, event.headers);
2651
+ }
2652
+ /**
2653
+ * What a request to a route is for: the body of a `#defer` block, an
2654
+ * endpoint when the folder has one that answers the method, or a page. A
2655
+ * path that no route matches is a page, the 404 page.
2656
+ */
2657
+ async function requestKind(request, match) {
2658
+ if (deferTarget(request)) return "defer";
2659
+ if (match?.endpoint) {
2660
+ if ((await match.endpoint())[request.method === "HEAD" ? "GET" : request.method] || request.method !== "GET") return "endpoint";
2661
+ }
2662
+ return "page";
2663
+ }
2664
+ /** A response with more headers, such as cookies that middleware set. */
2665
+ function withHeaders(answer, headers) {
2666
+ const sent = new Set(answer.headers.getSetCookie());
2667
+ const cookies = headers.getSetCookie().filter((cookie) => !sent.has(cookie));
2668
+ if (cookies.length === 0) return answer;
2669
+ const result = respond(answer.body, answer);
2670
+ for (const cookie of cookies) result.headers.append("set-cookie", cookie);
2671
+ return result;
2672
+ }
2673
+ async function routeAnswer(tree, match, url, options) {
2674
+ const event = options.event;
2675
+ const { request } = event;
2676
+ if (deferTarget(request) && isSkewed(request, options.build)) return skewAnswer(options.build);
2677
+ if (!match) {
2678
+ const missing = notFound(tree);
2679
+ if (missing.errors.length === 0 && missing.middleware.length === 0 && !options.middleware) return;
2680
+ return runEntry(options.middleware, event, () => runMiddleware(missing.middleware, request, event, async () => {
2681
+ return await renderError(missing.errors, {
2682
+ message: "Not found",
2683
+ status: 404
2684
+ }, {}, request, options) ?? new Response("Not found", { status: 404 });
2685
+ }));
2686
+ }
2687
+ const refused = await readAction(url, event, options);
2688
+ if (refused) return refused;
2689
+ return runEntry(options.middleware, event, () => runMiddleware(match.middleware, request, event, () => answerRoute(match, request, url, options)));
2690
+ }
2691
+ /** Answers a request that a route matches, after its middleware. `url` is the URL of the request. */
2692
+ async function answerRoute(match, request, url, options) {
2693
+ if (match.endpoint) {
2694
+ const endpoint = await match.endpoint();
2695
+ const handler = endpoint[request.method] ?? (request.method === "HEAD" ? endpoint.GET : void 0);
2696
+ if (handler) return withEvent(options.event, () => handler(request, match.params));
2697
+ if (match.view.load === missingPage || request.method !== "GET") {
2698
+ const allow = Object.keys(endpoint).filter((name) => /^[A-Z]+$/.test(name));
2699
+ return new Response("Method not allowed", {
2700
+ status: 405,
2701
+ headers: { allow: allow.join(", ") }
2702
+ });
2703
+ }
2704
+ }
2705
+ const event = options.event;
2706
+ const call = event.call;
2707
+ return runEntry(call && options.fileMiddleware?.[call.id], event, () => renderRoute(match, request, url, options));
2708
+ }
2709
+ /** Runs the server function that a form posted to the page, if any, and renders the page. */
2710
+ async function renderRoute(match, request, url, options) {
2711
+ let actions;
2712
+ const event = options.event;
2713
+ if (event.call) {
2714
+ const outcome = await runAction(options.functions[event.call.id], event);
2715
+ if ("answer" in outcome) return outcome.answer;
2716
+ actions = outcome.actions;
2717
+ }
2718
+ try {
2719
+ return await renderPage(await resolveView(match.view), { params: match.params }, request, options, { actions });
2720
+ } catch (error) {
2721
+ if (isRedirect(error)) return new Response(null, {
2722
+ status: error.status,
2723
+ headers: { location: new URL(error.location, url).href }
2724
+ });
2725
+ if (options.dev && !(error instanceof ServerError)) throw error;
2726
+ const page = await renderError(match.errors, errorAnswer(error, "Something went wrong"), match.params, request, options);
2727
+ if (page) return page;
2728
+ throw error;
2729
+ }
2730
+ }
2731
+ /**
2732
+ * Renders an object of attributes. A handler in it, such as an `onClick`
2733
+ * that a component passes on with `...rest`, goes into `on` as a `b-on`
2734
+ * entry: the client function that it refers to, with the scope that the
2735
+ * function belongs to and the modifiers of its wrappers. A function that
2736
+ * refers to nothing in the browser is left out.
2737
+ */
2738
+ function spread(attributes, on) {
2739
+ const entries = on && attributes["b-on"];
2740
+ if (typeof entries === "string") {
2741
+ on.unshift(entries);
2742
+ const { "b-on": _, ...rest } = attributes;
2743
+ return spread(rest, on);
2744
+ }
2745
+ for (const [name, value] of Object.entries(attributes)) {
2746
+ const reference = on && /^on[A-Z]/.test(name) && typeof value === "function" ? functionReferences.get(value) : void 0;
2747
+ if (reference) {
2748
+ const modifiers = value[MODIFIERS] ?? [];
2749
+ on.push(`${[name.slice(2).toLowerCase(), ...modifiers].join(":")}=${reference.ref}@${reference.scope}`);
2750
+ }
2751
+ }
2752
+ return spread$1(attributes);
2753
+ }
2754
+ /** The `b-on` attribute of an element with spreads: its own handlers, then those of its spreads. */
2755
+ function onAttribute(on, own) {
2756
+ const value = [own, ...on].filter(Boolean).join(" ");
2757
+ return value ? ` b-on="${escapeAttribute(value)}"` : "";
2758
+ }
2759
+ //#endregion
2760
+ export { clientAddress as A, ServerError as B, stateScript as C, wait as D, streamState as E, parse as F, redirect as G, defineMiddleware as H, parseForm as I, withEvent as K, safeParse as L, rateLimit as M, ValidationError as N, waitAll as O, fieldErrors as P, matchRoute as R, spread as S, streamParts as T, getEvent as U, dedupe as V, isRedirect as W, read as _, children as a, renderToStream as b, handleRequest as c, insert as d, isCrossSite as f, packState as g, onAttribute as h, actionResult as i, configureRateLimit as j, RateLimitError as k, handleRoute as l, memo as m, NotReady as n, component as o, lazy as p, action as r, dynamic as s, Context as t, inlineBodies as u, ready as v, stateValue as w, settled as x, render as y, RequestEvent as z };
2761
+
2762
+ //# sourceMappingURL=server-BqfM95r1.js.map