brumate 0.0.1 → 0.1.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 (81) hide show
  1. package/README.md +43 -72
  2. package/dist/boot-DN1ZU8Hg.d.ts +37 -0
  3. package/dist/cli.js +2 -2
  4. package/dist/{client-DuDTDePF.d.ts → client-DwJInP_a.d.ts} +133 -44
  5. package/dist/client-routes-DakuM32C.js +94 -0
  6. package/dist/client-routes-DakuM32C.js.map +1 -0
  7. package/dist/{cookies-rgIAc8IE.js → cookies-Av5WFmcf.js} +18 -8
  8. package/dist/cookies-Av5WFmcf.js.map +1 -0
  9. package/dist/{devtools-Bm8cS7hX.js → devtools-BKjnHrnv.js} +10 -5
  10. package/dist/devtools-BKjnHrnv.js.map +1 -0
  11. package/dist/{devtools-panel-CTbDSBBA.js → devtools-panel-AWOn0VK2.js} +23 -26
  12. package/dist/devtools-panel-AWOn0VK2.js.map +1 -0
  13. package/dist/{files-D_JUcSU5.js → files-BBLPU9JR.js} +22 -3
  14. package/dist/{files-D_JUcSU5.js.map → files-BBLPU9JR.js.map} +1 -1
  15. package/dist/{html-CxWpXngy.js → html-DEeoepg3.js} +47 -10
  16. package/dist/html-DEeoepg3.js.map +1 -0
  17. package/dist/{html-DV-Tezgq.d.ts → html-Du8jY2Cc.d.ts} +14 -2
  18. package/dist/index.d.ts +63 -6
  19. package/dist/index.js +20 -4
  20. package/dist/index.js.map +1 -1
  21. package/dist/{inspect-CGCWfaEx.js → inspect-CRZlO11T.js} +743 -163
  22. package/dist/inspect-CRZlO11T.js.map +1 -0
  23. package/dist/loader-Dc9OwY5I.js +101 -0
  24. package/dist/loader-Dc9OwY5I.js.map +1 -0
  25. package/dist/{navigate-C5dP89YL.js → navigate-CzLjnoPH.js} +112 -59
  26. package/dist/navigate-CzLjnoPH.js.map +1 -0
  27. package/dist/{produce-BjQGMpqL.d.ts → produce-CtZ32UGG.d.ts} +13 -3
  28. package/dist/{rpc-B86KKjzx.js → rpc-9fSqL_YK.js} +57 -12
  29. package/dist/rpc-9fSqL_YK.js.map +1 -0
  30. package/dist/runtime/client.d.ts +4 -4
  31. package/dist/runtime/client.js +599 -306
  32. package/dist/runtime/client.js.map +1 -1
  33. package/dist/runtime/devtools.d.ts +3 -1
  34. package/dist/runtime/devtools.js +1 -1
  35. package/dist/runtime/hot.d.ts +1 -1
  36. package/dist/runtime/hot.js +9 -5
  37. package/dist/runtime/hot.js.map +1 -1
  38. package/dist/runtime/html.d.ts +2 -2
  39. package/dist/runtime/html.js +1 -1
  40. package/dist/runtime/loader.d.ts +12 -2
  41. package/dist/runtime/loader.js +3 -1
  42. package/dist/runtime/server.d.ts +4 -4
  43. package/dist/runtime/server.js +5 -5
  44. package/dist/runtime/signals.d.ts +2 -2
  45. package/dist/runtime/signals.js +5 -5
  46. package/dist/runtime/signals.js.map +1 -1
  47. package/dist/runtime/static-loader.d.ts +3 -0
  48. package/dist/runtime/static-loader.js +1 -0
  49. package/dist/runtime/testing.d.ts +21 -2
  50. package/dist/runtime/testing.js +83 -7
  51. package/dist/runtime/testing.js.map +1 -1
  52. package/dist/{server-sQCvduOz.d.ts → server-BxqjLUnV.d.ts} +211 -20
  53. package/dist/{server-CX3JnPCs.js → server-DZsgnPKS.js} +595 -185
  54. package/dist/server-DZsgnPKS.js.map +1 -0
  55. package/dist/shared-CWYOd0H3.js +40 -0
  56. package/dist/shared-CWYOd0H3.js.map +1 -0
  57. package/dist/static-loader-BcFh4ebX.d.ts +11 -0
  58. package/dist/static-loader-ClNkHZGn.js +185 -0
  59. package/dist/static-loader-ClNkHZGn.js.map +1 -0
  60. package/dist/stream-bgNCMcaA.js +280 -0
  61. package/dist/stream-bgNCMcaA.js.map +1 -0
  62. package/dist/vite.d.ts +30 -5
  63. package/dist/vite.js +501 -62
  64. package/dist/vite.js.map +1 -1
  65. package/package.json +7 -2
  66. package/types.d.ts +5 -0
  67. package/dist/cookies-rgIAc8IE.js.map +0 -1
  68. package/dist/devtools-Bm8cS7hX.js.map +0 -1
  69. package/dist/devtools-panel-CTbDSBBA.js.map +0 -1
  70. package/dist/html-CxWpXngy.js.map +0 -1
  71. package/dist/inspect-CGCWfaEx.js.map +0 -1
  72. package/dist/loader-BUhNqDHw.d.ts +0 -30
  73. package/dist/loader-py4qu6tQ.js +0 -215
  74. package/dist/loader-py4qu6tQ.js.map +0 -1
  75. package/dist/navigate-C5dP89YL.js.map +0 -1
  76. package/dist/rpc-B86KKjzx.js.map +0 -1
  77. package/dist/server-CX3JnPCs.js.map +0 -1
  78. package/dist/shared-BE_oBSDM.js +0 -176
  79. package/dist/shared-BE_oBSDM.js.map +0 -1
  80. package/dist/stream-cvhqOzfs.js +0 -145
  81. package/dist/stream-cvhqOzfs.js.map +0 -1
@@ -1,8 +1,8 @@
1
- import { c as insertValue, d as rawHTML, f as spread, l as isRaw, n as actionAttributes, o as escape, p as styleElement, s as escapeAttribute, t as VOID_ELEMENTS } from "./html-CxWpXngy.js";
2
- import { a as functionReferences, c as replaceDeep, i as disabledFeatures, n as FunctionReference, o as isAsyncIterable, r as Upload, s as plugins, t as ElementReference } from "./shared-BE_oBSDM.js";
3
- import { r as toChunkStream, t as STREAM_TYPE } from "./stream-cvhqOzfs.js";
4
- import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-rgIAc8IE.js";
5
- import { fromJSON, toCrossJSONStream, toJSON } from "seroval";
1
+ import { c as escape, d as isRaw, h as styleElement, l as escapeAttribute, m as spread, n as actionAttributes, p as rawHTML, t as VOID_ELEMENTS, u as insertValue } from "./html-DEeoepg3.js";
2
+ import { a as plugins, c as replaceDeep, i as disabledFeatures, o as Upload, r as toChunkStream, s as functionReferences, t as STREAM_TYPE } from "./stream-bgNCMcaA.js";
3
+ import { n as FunctionReference, r as isAsyncIterable, t as ElementReference } from "./shared-CWYOd0H3.js";
4
+ import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-Av5WFmcf.js";
5
+ import { crossSerializeStream, fromJSON, toJSON } from "seroval";
6
6
  //#region src/runtime/request.ts
7
7
  /**
8
8
  * A request that the server handles: a server function call, a form post,
@@ -188,7 +188,7 @@ function key(path, file, params) {
188
188
  }
189
189
  /** Puts a view in the children slot of a layout, with its other slots. */
190
190
  function wrap(view, wrapper) {
191
- return wrapper.layout ? {
191
+ return wrapper ? {
192
192
  load: wrapper.layout,
193
193
  key: wrapper.key,
194
194
  slots: {
@@ -197,11 +197,27 @@ function wrap(view, wrapper) {
197
197
  }
198
198
  } : view;
199
199
  }
200
+ /** The layout of a folder, or undefined when it has none. */
201
+ function wrapperOf(node, segments, index, params, path) {
202
+ return node.layout ? {
203
+ layout: node.layout,
204
+ key: key(path, "_layout", params),
205
+ slots: namedSlots(node, segments, index, params, path)
206
+ } : void 0;
207
+ }
208
+ /** The `_error.brm` of a folder, inside its layout. */
209
+ function errorIn(error, wrapper, params, path) {
210
+ return wrap({
211
+ load: error,
212
+ key: key(path, ERROR_VIEW, params),
213
+ slots: {}
214
+ }, wrapper);
215
+ }
200
216
  /** The slots of a layout other than `children`, each matched against the same path. */
201
- function namedSlots(node, segments, params, path) {
217
+ function namedSlots(node, segments, index, params, path) {
202
218
  const slots = {};
203
219
  for (const [name, slot] of Object.entries(node.slots ?? {})) {
204
- const match = matchNode(slot, segments, params, `${path}/@${name}`);
220
+ const match = matchNode(slot, segments, index, params, `${path}/@${name}`);
205
221
  if (match) slots[name] = match.view;
206
222
  else if (slot.fallback) slots[name] = {
207
223
  load: slot.fallback,
@@ -213,10 +229,13 @@ function namedSlots(node, segments, params, path) {
213
229
  }
214
230
  /** The view of an `_error.brm`. Its component gets the error as a prop. */
215
231
  const ERROR_VIEW = "_error";
216
- /** `path` is the folders of `node` in the route files, such as `/todos/[id]`. */
217
- function matchNode(node, segments, params, path = "") {
232
+ /**
233
+ * Matches the segments from `index` on. `path` is the folders of `node` in
234
+ * the route files, such as `/todos/[id]`.
235
+ */
236
+ function matchNode(node, segments, index, params, path = "") {
218
237
  let inner;
219
- if (segments.length === 0) {
238
+ if (index === segments.length) {
220
239
  if (node.page || node.endpoint) inner = {
221
240
  view: {
222
241
  load: node.page ?? missingPage,
@@ -229,21 +248,21 @@ function matchNode(node, segments, params, path = "") {
229
248
  errors: []
230
249
  };
231
250
  } else {
232
- const [first, ...rest] = segments;
251
+ const first = segments[index];
233
252
  const fixed = node.static?.[first];
234
- inner = fixed && matchNode(fixed, rest, params, `${path}/${first}`);
253
+ inner = fixed && matchNode(fixed, segments, index + 1, params, `${path}/${first}`);
235
254
  if (!inner && node.dynamic) {
236
255
  const { name } = node.dynamic;
237
- inner = matchNode(node.dynamic.node, rest, {
256
+ inner = matchNode(node.dynamic.node, segments, index + 1, {
238
257
  ...params,
239
258
  [name]: first
240
259
  }, `${path}/[${name}]`);
241
260
  }
242
261
  if (!inner && node.rest) {
243
262
  const { name } = node.rest;
244
- inner = matchNode(node.rest.node, [], {
263
+ inner = matchNode(node.rest.node, segments, segments.length, {
245
264
  ...params,
246
- [name]: segments.join("/")
265
+ [name]: segments.slice(index).join("/")
247
266
  }, `${path}/[...${name}]`);
248
267
  }
249
268
  }
@@ -252,17 +271,9 @@ function matchNode(node, segments, params, path = "") {
252
271
  ...inner.view,
253
272
  loading: node.loading
254
273
  } : inner.view;
255
- const wrapper = {
256
- layout: node.layout,
257
- key: key(path, "_layout", params),
258
- slots: node.layout ? namedSlots(node, segments, params, path) : {}
259
- };
260
- const errors = inner.errors.map((view) => wrap(view, wrapper));
261
- if (node.error) errors.push(wrap({
262
- load: node.error,
263
- key: key(path, ERROR_VIEW, params),
264
- slots: {}
265
- }, wrapper));
274
+ const wrapper = wrapperOf(node, segments, index, params, path);
275
+ const errors = wrapper ? inner.errors.map((view) => wrap(view, wrapper)) : inner.errors;
276
+ if (node.error) errors.push(errorIn(node.error, wrapper, params, path));
266
277
  return {
267
278
  view: wrap(content, wrapper),
268
279
  params: inner.params,
@@ -275,30 +286,194 @@ function matchNode(node, segments, params, path = "") {
275
286
  const missingPage = () => {
276
287
  throw new Error("This path has an endpoint and no page");
277
288
  };
278
- /** Finds the route for a path. */
289
+ /** Finds the route for a path. A path with a malformed escape, such as `/%E0`, matches none. */
279
290
  function matchRoute(tree, pathname) {
280
- return matchNode(tree, pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment)), {});
291
+ let segments;
292
+ try {
293
+ segments = pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment));
294
+ } catch {
295
+ return;
296
+ }
297
+ return matchNode(tree, segments, 0, {});
281
298
  }
282
299
  /**
283
300
  * The views for a path that no route matches: the `_error.brm` of the
284
301
  * root, inside the root layout, and the root middleware.
285
302
  */
286
303
  function notFound(tree) {
287
- const wrapper = {
288
- layout: tree.layout,
289
- key: key("", "_layout", {}),
290
- slots: tree.layout ? namedSlots(tree, [], {}, "") : {}
291
- };
292
304
  return {
293
- errors: tree.error ? [wrap({
294
- load: tree.error,
295
- key: key("", ERROR_VIEW, {}),
296
- slots: {}
297
- }, wrapper)] : [],
305
+ errors: tree.error ? [errorIn(tree.error, wrapperOf(tree, [], 0, {}, ""), {}, "")] : [],
298
306
  middleware: tree.middleware ? [tree.middleware] : []
299
307
  };
300
308
  }
301
309
  //#endregion
310
+ //#region src/runtime/validate.ts
311
+ /**
312
+ * The error that `parse` throws when the value does not match. It answers
313
+ * with status 400 and its message, as any `ServerError` does. Its `issues`
314
+ * stay on the server.
315
+ */
316
+ var ValidationError = class extends ServerError {
317
+ issues;
318
+ constructor(issues) {
319
+ super(summary(issues), { status: 400 });
320
+ this.name = "ValidationError";
321
+ this.issues = issues;
322
+ }
323
+ };
324
+ /** The longest message that `parse` sends, so a long input in a message stays short. */
325
+ const MAX_MESSAGE = 300;
326
+ /** The message of a `ValidationError`: the first issue with its path, and how many others there are. */
327
+ function summary(issues) {
328
+ const first = issues[0];
329
+ if (!first) return "Invalid input";
330
+ const path = first.path?.join(".");
331
+ let message = path ? `${path}: ${first.message}` : first.message;
332
+ if (message.length > MAX_MESSAGE) message = `${message.slice(0, MAX_MESSAGE)}…`;
333
+ const more = issues.length - 1;
334
+ return more > 0 ? `${message} (${more} more ${more === 1 ? "issue" : "issues"})` : message;
335
+ }
336
+ /**
337
+ * Copies an issue as plain data. A `{ key }` segment becomes its key, and a
338
+ * symbol becomes its text, such as `Symbol(id)`. Other fields of the issue,
339
+ * which some libraries add, are left out, so the input is not sent back.
340
+ */
341
+ function plainIssue(issue) {
342
+ const plain = { message: String(issue.message) };
343
+ if (issue.path && issue.path.length > 0) plain.path = issue.path.map((segment) => {
344
+ const key = typeof segment === "object" && segment !== null ? segment.key : segment;
345
+ return typeof key === "number" ? key : String(key);
346
+ });
347
+ return plain;
348
+ }
349
+ /**
350
+ * Validates a value with a Standard Schema. Returns `{ value }` with the
351
+ * output of the schema, or `{ issues }` as plain data. It does not throw for
352
+ * a value that does not match.
353
+ */
354
+ async function safeParse(schema, value) {
355
+ const props = schema["~standard"];
356
+ if (props?.version !== 1 || typeof props.validate !== "function") throw new TypeError("The schema is not a Standard Schema of version 1");
357
+ const result = await props.validate(value);
358
+ if (result.issues) return { issues: result.issues.map(plainIssue) };
359
+ return { value: result.value };
360
+ }
361
+ /**
362
+ * Validates a value with a Standard Schema, and returns the output of the
363
+ * schema. A value that does not match throws a `ValidationError`, which
364
+ * answers with status 400 and a message built from the first issue.
365
+ *
366
+ * ```ts
367
+ * async function save(input: unknown) {
368
+ * 'use server';
369
+ * const todo = await parse(Todo, input);
370
+ * await db.todos.save(todo);
371
+ * }
372
+ * ```
373
+ */
374
+ async function parse(schema, value) {
375
+ const result = await safeParse(schema, value);
376
+ if (result.issues) throw new ValidationError(result.issues);
377
+ return result.value;
378
+ }
379
+ /** Names that would change the prototype of an object, or reach the one of its constructor. */
380
+ const FORBIDDEN = /* @__PURE__ */ new Set([
381
+ "__proto__",
382
+ "constructor",
383
+ "prototype"
384
+ ]);
385
+ /**
386
+ * Turns the entries of a form into a plain object:
387
+ *
388
+ * - A name that appears once holds its value.
389
+ * - A name that appears more than once holds an array of its values.
390
+ * - A name that ends with `[]` always holds an array, under the name without `[]`.
391
+ * - Dots nest objects: `address.city` is `{ address: { city } }`.
392
+ * - Values stay strings and files.
393
+ *
394
+ * A name with an empty part, a part such as `__proto__`, or one that needs
395
+ * an object where another field holds a value, is an issue, and the schema
396
+ * does not run.
397
+ */
398
+ function formValues(form) {
399
+ const root = {};
400
+ const objects = /* @__PURE__ */ new Set([root]);
401
+ const arrays = /* @__PURE__ */ new Set();
402
+ const issues = [];
403
+ for (const [name, value] of form) {
404
+ const list = name.endsWith("[]");
405
+ const parts = (list ? name.slice(0, -2) : name).split(".");
406
+ if (parts.some((part) => part === "" || FORBIDDEN.has(part))) {
407
+ issues.push({ message: "The form has a field name that is not allowed" });
408
+ continue;
409
+ }
410
+ let target = root;
411
+ let conflict = false;
412
+ for (const part of parts.slice(0, -1)) {
413
+ const next = Object.hasOwn(target, part) ? target[part] : void 0;
414
+ if (next === void 0) {
415
+ const child = {};
416
+ objects.add(child);
417
+ target[part] = child;
418
+ target = child;
419
+ } else if (objects.has(next)) target = next;
420
+ else {
421
+ conflict = true;
422
+ break;
423
+ }
424
+ }
425
+ const last = parts.at(-1);
426
+ const current = Object.hasOwn(target, last) ? target[last] : void 0;
427
+ if (conflict || objects.has(current)) issues.push({
428
+ message: `Field "${name}" conflicts with another field`,
429
+ path: parts
430
+ });
431
+ else if (arrays.has(current)) current.push(value);
432
+ else if (current !== void 0 || list) {
433
+ const values = current === void 0 ? [value] : [current, value];
434
+ arrays.add(values);
435
+ target[last] = values;
436
+ } else target[last] = value;
437
+ }
438
+ return issues.length > 0 ? { issues } : { value: root };
439
+ }
440
+ /**
441
+ * Validates the data of a form with a Standard Schema. The entries become a
442
+ * plain object first. Returns `{ value }` or `{ issues }`, and does not throw
443
+ * for data that does not match, so a function of `$action` can return the
444
+ * issues for the page to show.
445
+ *
446
+ * ```ts
447
+ * async function signUp(form: FormData) {
448
+ * 'use server';
449
+ * const result = await parseForm(SignUp, form);
450
+ * if (result.issues) {
451
+ * return { errors: fieldErrors(result.issues) };
452
+ * }
453
+ * }
454
+ * ```
455
+ */
456
+ async function parseForm(schema, form) {
457
+ const values = formValues(form);
458
+ if (values.issues) return { issues: values.issues };
459
+ return safeParse(schema, values.value);
460
+ }
461
+ /**
462
+ * The messages of issues by field, for a page to show next to each field.
463
+ * The key is the path joined with dots, such as `address.city`. Issues
464
+ * without a path, and a path of `__proto__`, are under the key `''`. The
465
+ * result is plain data, so a server function can return it.
466
+ */
467
+ function fieldErrors(issues) {
468
+ const errors = {};
469
+ for (const issue of issues) {
470
+ let key = plainIssue(issue).path?.join(".") ?? "";
471
+ if (key === "__proto__") key = "";
472
+ (Object.hasOwn(errors, key) ? errors[key] : errors[key] = []).push(String(issue.message));
473
+ }
474
+ return errors;
475
+ }
476
+ //#endregion
302
477
  //#region src/runtime/server.ts
303
478
  /**
304
479
  * Tracks the scopes of one render. A `#loading` body renders in a child
@@ -321,6 +496,8 @@ var Context = class Context {
321
496
  tree = /* @__PURE__ */ new Map();
322
497
  /** The scope that renders the next component, which becomes its owner. */
323
498
  owner;
499
+ /** Takes back what this context added to the page, from the newest, for `restore`. */
500
+ undo = [];
324
501
  /** The URL prefix of server function calls. */
325
502
  rpcPrefix = "/_brumate";
326
503
  /** The names of the slots of each scope, so an error can name a value that cannot be sent. */
@@ -421,6 +598,42 @@ var Context = class Context {
421
598
  peek() {
422
599
  return this.root.nextScope;
423
600
  }
601
+ /** Marks the render so far, such as before a `#try` body, for `restore`. */
602
+ mark() {
603
+ return {
604
+ scope: this.root.nextScope,
605
+ undo: this.undo.length,
606
+ owner: this.root.owner
607
+ };
608
+ }
609
+ /**
610
+ * Takes back what the render added to the page since `mark`, such as a
611
+ * `#try` body that threw, whose markup is not sent: its scopes, the
612
+ * stylesheets it counted as sent, its `#portal` and `#head` markup, its
613
+ * title, its `#loading` bodies, and its links to child components.
614
+ */
615
+ restore(mark) {
616
+ this.drop(mark.scope);
617
+ for (const undo of this.undo.splice(mark.undo).toReversed()) undo();
618
+ this.root.owner = mark.owner;
619
+ }
620
+ /**
621
+ * Forgets the scopes of this render from `from` on, such as those of a
622
+ * `#try` body that threw, so the client does not resume markup that was
623
+ * never sent. `#loading` bodies render in contexts of their own, so their
624
+ * scopes stay.
625
+ */
626
+ drop(from) {
627
+ for (const key of Object.keys(this.state)) {
628
+ const id = Number(key);
629
+ if (id >= from) {
630
+ delete this.state[id];
631
+ this.root.slotNames.delete(id);
632
+ this.root.tree.delete(id);
633
+ this.sources.delete(id);
634
+ }
635
+ }
636
+ }
424
637
  record(scope) {
425
638
  this.state[scope] ??= {};
426
639
  return this.state[scope];
@@ -429,15 +642,28 @@ var Context = class Context {
429
642
  this.record(scope).s = values;
430
643
  if (names) this.root.slotNames.set(scope, names);
431
644
  }
432
- /** Records the item of a list that can change on the client. */
433
- item(scope, value) {
645
+ /**
646
+ * The list of each list item scope whose list is a slot of an enclosing
647
+ * scope, as `[scope, slot]`. The items of a list share one array.
648
+ */
649
+ sources = /* @__PURE__ */ new Map();
650
+ /**
651
+ * Records the item of a list that can change on the client. `source` is
652
+ * the scope and slot that hold the list, when the compiler found one, so
653
+ * the client can take the item from there.
654
+ */
655
+ item(scope, value, source) {
434
656
  this.record(scope).i = value;
657
+ if (source) this.sources.set(scope, source);
435
658
  }
436
659
  /** Records the scope of a child component at an anchor of its parent. */
437
660
  link(scope, anchor, child) {
438
661
  const record = this.record(scope);
439
- record.c ??= {};
440
- record.c[anchor] = child;
662
+ const links = record.c ??= {};
663
+ links[anchor] = child;
664
+ this.undo.push(() => {
665
+ if (links[anchor] === child) delete links[anchor];
666
+ });
441
667
  }
442
668
  /** Returns the reference that a `ref` signal holds on the server. */
443
669
  element(scope, anchor) {
@@ -450,17 +676,27 @@ var Context = class Context {
450
676
  }
451
677
  /** Returns a component's stylesheet the first time the page renders the component. */
452
678
  style(id, css) {
453
- if (this.root.styles.has(id)) return "";
454
- this.root.styles.add(id);
679
+ const styles = this.root.styles;
680
+ if (styles.has(id)) return "";
681
+ styles.add(id);
682
+ this.undo.push(() => styles.delete(id));
455
683
  return styleElement(id, css);
456
684
  }
457
685
  /** Adds the markup of a `#head` block. */
458
686
  head(html) {
459
- (this.root.sent ? this : this.root).heads.push(html);
687
+ const heads = (this.root.sent ? this : this.root).heads;
688
+ heads.push(html);
689
+ this.undo.push(() => removeLast(heads, html));
460
690
  }
461
691
  /** Sets the title of the page. The last call wins. */
462
692
  title(value) {
463
- (this.root.sent ? this : this.root).pageTitle = value === null || value === void 0 ? "" : String(value);
693
+ const target = this.root.sent ? this : this.root;
694
+ const previous = target.pageTitle;
695
+ const title = value === null || value === void 0 ? "" : String(value);
696
+ target.pageTitle = title;
697
+ this.undo.push(() => {
698
+ if (target.pageTitle === title) target.pageTitle = previous;
699
+ });
464
700
  }
465
701
  /** True once the first render is done, and its head is about to be sent. */
466
702
  sent = false;
@@ -485,6 +721,7 @@ var Context = class Context {
485
721
  /** Adds the markup of a `#portal` block, which goes after the rest of the page. */
486
722
  portal(html) {
487
723
  this.portals.push(html);
724
+ this.undo.push(() => removeLast(this.portals, html));
488
725
  }
489
726
  /** Returns the ID of a new `#loading` boundary. */
490
727
  boundary() {
@@ -504,6 +741,10 @@ var Context = class Context {
504
741
  const root = this.root;
505
742
  if (root.onBoundary) root.onBoundary(boundary);
506
743
  else root.boundaries.push(boundary);
744
+ this.undo.push(() => {
745
+ boundary.cancelled = true;
746
+ removeLast(root.boundaries, boundary);
747
+ });
507
748
  }
508
749
  /** Receives every boundary, including those registered before this call. */
509
750
  watch(onBoundary) {
@@ -511,6 +752,11 @@ var Context = class Context {
511
752
  for (const boundary of this.boundaries.splice(0)) onBoundary(boundary);
512
753
  }
513
754
  };
755
+ /** Removes the last copy of a value from a list. */
756
+ function removeLast(list, value) {
757
+ const index = list.lastIndexOf(value);
758
+ if (index !== -1) list.splice(index, 1);
759
+ }
514
760
  /** Thrown when code reads a memo whose value is still loading. It carries the load. */
515
761
  var NotReady = class extends Error {
516
762
  source;
@@ -583,6 +829,18 @@ async function wait(node) {
583
829
  await error.source.catch(() => {});
584
830
  }
585
831
  }
832
+ /**
833
+ * The value of a memo when it is ready, or a promise of it while it loads.
834
+ * The render then awaits only a memo that is loading.
835
+ */
836
+ function ready(node) {
837
+ try {
838
+ return read(node);
839
+ } catch (error) {
840
+ if (error instanceof NotReady) return wait(node);
841
+ throw error;
842
+ }
843
+ }
586
844
  const LAZY = Symbol.for("brumate.lazy");
587
845
  /** Makes markup that renders where it is inserted, such as the children of a layout. */
588
846
  function lazy(renderAt) {
@@ -606,23 +864,26 @@ function actionResult(ctx, fn) {
606
864
  * Renders a value inserted in markup. `ctx` and `scope` are where it is
607
865
  * inserted, for markup that renders there.
608
866
  */
609
- async function insert(value, ctx, scope) {
610
- const resolved = await value;
611
- if (isLazy(resolved) && ctx) return resolved[LAZY](ctx, scope);
612
- if (Array.isArray(resolved)) return (await Promise.all(resolved.map((item) => insert(item, ctx, scope)))).join("");
613
- return insertValue(resolved);
867
+ function insert(value, ctx, scope) {
868
+ if (value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function") return Promise.resolve(value).then((resolved) => insert(resolved, ctx, scope));
869
+ if (isLazy(value) && ctx) return value[LAZY](ctx, scope);
870
+ if (Array.isArray(value)) {
871
+ const parts = value.map((item) => insert(item, ctx, scope));
872
+ return parts.every((part) => typeof part === "string") ? parts.join("") : Promise.all(parts).then((all) => all.join(""));
873
+ }
874
+ return insertValue(value);
614
875
  }
615
876
  /**
616
877
  * Renders a child component. With `scope` and `anchor`, records the child's
617
878
  * scope so the parent can update its props on the client.
618
879
  */
619
- async function component(Child, props, ctx, scope, anchor) {
880
+ function component(Child, props, ctx, scope, anchor) {
620
881
  if (scope !== void 0 && anchor !== void 0) ctx.link(scope, anchor, ctx.peek());
621
882
  if (scope !== void 0) ctx.own(scope);
622
883
  return Child(props, ctx);
623
884
  }
624
885
  /** Renders a dynamic tag, which can be an element name or a component. */
625
- async function dynamic(tag, attributes, children, ctx, scope) {
886
+ function dynamic(tag, attributes, children, ctx, scope) {
626
887
  if (typeof tag === "function") return component(tag, children ? {
627
888
  ...attributes,
628
889
  children
@@ -631,12 +892,6 @@ async function dynamic(tag, attributes, children, ctx, scope) {
631
892
  if (VOID_ELEMENTS.has(tag)) return open;
632
893
  return `${open}${children && isRaw(children) ? rawHTML(children) : ""}</${tag}>`;
633
894
  }
634
- /**
635
- * Serializes the page state as seroval cross-reference JSON records. The
636
- * first record holds the state, and each later record settles a promise in
637
- * it. `onRecord` receives each record as soon as it is ready. The promise
638
- * resolves when every promise in the state has settled.
639
- */
640
895
  /** True when `value` is `target`, or holds it in plain objects, arrays, maps or sets. */
641
896
  function holds(value, target, seen = /* @__PURE__ */ new Set()) {
642
897
  if (value === target) return true;
@@ -662,35 +917,161 @@ function unsendable(error, ctx) {
662
917
  }
663
918
  return error instanceof Error ? error : new Error(String(error));
664
919
  }
920
+ /** JSON that is safe in a `<script>`, with each `<` escaped. */
921
+ function scriptJSON(value) {
922
+ return JSON.stringify(value).replace(/</g, "\\u003c");
923
+ }
924
+ /** The fields that a record in a group of `PackedState` can have. */
925
+ const PACKED_FIELDS = /* @__PURE__ */ new Set([
926
+ "k",
927
+ "p",
928
+ "o",
929
+ "m",
930
+ "s",
931
+ "i",
932
+ "c"
933
+ ]);
934
+ /**
935
+ * The list that the client can take the items of a group from: the items
936
+ * are list items with the same source, the source's record is in `state`,
937
+ * and the item of the scope at each position of the group is the value at
938
+ * that position of the list. The client reads the same list, so it gets the
939
+ * same values. Otherwise the items are written.
940
+ */
941
+ function groupSource(state, sources, group) {
942
+ const source = sources.get(group.ids[0]);
943
+ if (!source || !(group.flags & 3)) return;
944
+ const value = state[source[0]]?.s?.[source[1]];
945
+ const list = Array.isArray(value) ? value : value instanceof Set ? Array.from(value) : void 0;
946
+ if (!list || list.length < group.ids.length) return;
947
+ for (let n = 0; n < group.ids.length; n++) {
948
+ const id = group.ids[n];
949
+ if (sources.get(id) !== source || !Object.is(list[n], state[id].i)) return;
950
+ }
951
+ return source;
952
+ }
953
+ /**
954
+ * Writes the records of scopes with the same kind, parent and shape, such as
955
+ * the items of a list, in groups. Each one then costs its slots and the gap
956
+ * to the ID before it. The items of a list whose list is in `sources` and in
957
+ * the state are not written. See `PackedState`.
958
+ */
959
+ function packState(state, sources) {
960
+ const result = {};
961
+ const groups = /* @__PURE__ */ new Map();
962
+ for (const [key, record] of Object.entries(state)) {
963
+ const id = Number(key);
964
+ const base = record.p ?? (record.o === void 0 ? void 0 : id - record.o);
965
+ 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))) {
966
+ result[id] = record;
967
+ continue;
968
+ }
969
+ const slots = record.s ?? [];
970
+ let flags = record.p === void 0 ? 8 : 0;
971
+ if ("i" in record) flags |= slots.length > 0 && Object.is(record.i, slots[0]) ? 1 : 2;
972
+ if (record.c) flags |= 4;
973
+ if (record.m !== void 0) flags |= 16;
974
+ const name = `${record.k}:${base}:${flags}:${slots.length}:${record.m ?? ""}`;
975
+ const group = groups.get(name);
976
+ if (group) group.ids.push(id);
977
+ else groups.set(name, {
978
+ k: record.k,
979
+ base,
980
+ flags,
981
+ count: slots.length,
982
+ m: record.m,
983
+ ids: [id]
984
+ });
985
+ }
986
+ const packed = [];
987
+ for (const group of groups.values()) {
988
+ const { ids } = group;
989
+ if (ids.length === 1) {
990
+ result[ids[0]] = state[ids[0]];
991
+ continue;
992
+ }
993
+ const source = sources && sources.size > 0 ? groupSource(state, sources, group) : void 0;
994
+ const flags = source ? group.flags | 32 : group.flags;
995
+ const values = [
996
+ group.k,
997
+ group.base,
998
+ flags,
999
+ group.count
1000
+ ];
1001
+ if (group.m !== void 0) values.push(group.m);
1002
+ if (source) values.push(source[0], source[1]);
1003
+ const from = source && flags & 1 ? 1 : 0;
1004
+ const item = !source && flags & 2;
1005
+ let last = flags & 8 ? 0 : group.base;
1006
+ for (const id of ids) {
1007
+ const record = state[id];
1008
+ values.push(id - last);
1009
+ const slots = record.s ?? [];
1010
+ for (let n = from; n < slots.length; n++) values.push(slots[n]);
1011
+ if (item) values.push(record.i);
1012
+ if (flags & 4) values.push(record.c);
1013
+ last = id;
1014
+ }
1015
+ packed.push(values);
1016
+ }
1017
+ if (packed.length > 0) result.g = packed;
1018
+ return result;
1019
+ }
1020
+ /**
1021
+ * Serializes the page state as seroval cross-reference code, one record at
1022
+ * a time. The first record holds the state, and each later record settles a
1023
+ * promise in it. Records that share `refs` can refer to each other's values.
1024
+ */
1025
+ function serializeState(state, refs, onRecord, onError, onDone, sources) {
1026
+ crossSerializeStream(packState(state, sources), {
1027
+ plugins,
1028
+ disabledFeatures,
1029
+ refs,
1030
+ onSerialize: onRecord,
1031
+ onError,
1032
+ onDone
1033
+ });
1034
+ }
1035
+ /**
1036
+ * Serializes the page state as the code of state records. `onRecord`
1037
+ * receives each record as soon as it is ready. The promise resolves when
1038
+ * every promise in the state has settled.
1039
+ */
665
1040
  function streamState(state, onRecord) {
666
1041
  return new Promise((resolve, reject) => {
667
- toCrossJSONStream(state, {
668
- plugins,
669
- disabledFeatures,
670
- onParse: (record) => onRecord(record),
671
- onError: reject,
672
- onDone: resolve
673
- });
1042
+ serializeState(state, /* @__PURE__ */ new Map(), onRecord, reject, resolve);
674
1043
  });
675
1044
  }
676
1045
  /**
677
- * Returns the script for one state record. `scopes` marks a record that
678
- * holds scopes, as opposed to one that settles a promise.
1046
+ * Defines `$bR`, which hands the code of a state record and its script to
1047
+ * the core, through `self.$brm`. The core runs the code when it starts, or
1048
+ * at once when it has started. The first record of each render defines it.
679
1049
  */
1050
+ const RECORD = "function $bR(f){(self.$brm=self.$brm||[]).push([document.currentScript,f])}";
680
1051
  /**
681
- * Returns the script of a state record. `scopes` marks a record with scopes.
682
- * `next` is above every ID so far, and `route` names the route of the page.
1052
+ * Returns the script of a state record. `scopes` marks a record with scopes,
1053
+ * as opposed to one that settles a promise. The record is code that seroval
1054
+ * wrote, as a function of the references of its render, `$R`, and of the
1055
+ * functions that make brumate's values, `$b`. seroval escapes every `<` in
1056
+ * the strings in it.
683
1057
  */
684
- function stateScript(record, scopes = false, attributes = {}) {
685
- const json = JSON.stringify(record).replace(/</g, "\\u003c");
686
- let extra = scopes ? " data-scopes" : "";
687
- if (attributes.next !== void 0) extra += ` data-next="${attributes.next}"`;
688
- if (attributes.root) extra += ` data-root="${attributes.root}"`;
689
- if (attributes.route !== void 0) extra += ` data-route="${escapeAttribute(attributes.route)}"`;
690
- return `<script type="brumate/state"${extra}>${json}<\/script>`;
691
- }
692
- const HEAD = `function $bH(i,t){var e=document.querySelector('template[data-h="'+i+'"]');e&&(document.head.append(e.content),e.remove());t!=null&&(document.title=t)}`;
693
- const SWAP = `function $bS(i){var t=document.querySelector('template[data-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()}`;
1058
+ function stateScript(code, scopes = false, attributes = {}) {
1059
+ if (code.includes("</") || code.includes("<!")) throw new Error("A state record would end its script");
1060
+ let extra = attributes.nonce === void 0 ? "" : ` nonce="${escapeAttribute(attributes.nonce)}"`;
1061
+ extra += " b-state";
1062
+ if (scopes) extra += " b-scopes";
1063
+ if (attributes.next !== void 0) extra += ` b-next="${attributes.next}"`;
1064
+ if (attributes.root) extra += ` b-root="${attributes.root}"`;
1065
+ if (attributes.route !== void 0) extra += ` b-route="${escapeAttribute(attributes.route)}"`;
1066
+ return `<script${extra}>${attributes.define ? RECORD : ""}$bR(($R,$b)=>(${code}))<\/script>`;
1067
+ }
1068
+ const HEAD = `function $bH(i,t){var e=document.querySelector('template[b-h="'+i+'"]');e&&(document.head.append(e.content),e.remove());t!=null&&(document.title=t)}`;
1069
+ 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()}`;
1070
+ /** The `pending` of a render that has nothing left to send. */
1071
+ const NOTHING_PENDING = { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({
1072
+ done: true,
1073
+ value: void 0
1074
+ }) }) };
694
1075
  /** An async iterable that a producer pushes into. */
695
1076
  function createQueue() {
696
1077
  const items = [];
@@ -740,48 +1121,55 @@ async function render(Root, props, options = {}) {
740
1121
  const rendered = await ctx.run(() => Root(props, ctx));
741
1122
  ctx.send();
742
1123
  const html = beforeBodyEnd(rendered, ctx.portals.join(""));
743
- const queue = createQueue();
1124
+ let queue;
1125
+ const pending = () => queue ??= createQueue();
744
1126
  const refs = /* @__PURE__ */ new Map();
1127
+ const { nonce, base: root } = options;
1128
+ let first = true;
745
1129
  let open = 0;
746
1130
  let swap = false;
747
1131
  let headSwap = false;
748
1132
  const finish = () => {
749
1133
  open--;
750
- if (open === 0) queue.close();
1134
+ if (open === 0) queue?.close();
751
1135
  };
752
- const serialize = (state, onScopes, route, onError = queue.fail) => {
1136
+ const serialize = ({ state, sources }, onScopes, route, onError = (error) => pending().fail(error)) => {
753
1137
  open++;
754
- toCrossJSONStream(state, {
755
- plugins,
756
- disabledFeatures,
757
- refs,
758
- onParse(record, initial) {
759
- if (initial) onScopes(stateScript(record, true, {
1138
+ serializeState(state, refs, (code, initial) => {
1139
+ if (initial) {
1140
+ onScopes(stateScript(code, true, {
760
1141
  next: ctx.next(),
761
1142
  route,
762
- root: options.base
1143
+ root,
1144
+ nonce,
1145
+ define: first
763
1146
  }));
764
- else queue.push(stateScript(record, false, { root: options.base }));
765
- },
766
- onError,
767
- onDone: finish
768
- });
1147
+ first = false;
1148
+ } else pending().push(stateScript(code, false, {
1149
+ root,
1150
+ nonce
1151
+ }));
1152
+ }, onError, finish, sources);
769
1153
  };
770
1154
  ctx.watch((boundary) => {
771
1155
  open++;
772
1156
  boundary.render.then((result) => {
773
- serialize(result.ctx.state, (script) => {
1157
+ if (boundary.cancelled) {
1158
+ finish();
1159
+ return;
1160
+ }
1161
+ serialize(result.ctx, (script) => {
774
1162
  let call = `${swap ? "" : SWAP}$bS(${boundary.id})`;
775
1163
  swap = true;
776
1164
  const late = result.ctx.lateHead();
777
1165
  let head = "";
778
1166
  if (late.html || late.title !== void 0) {
779
- head = `<template data-h="${boundary.id}">${late.html}</template>`;
780
- const title = late.title === void 0 ? "" : `,${JSON.stringify(late.title).replace(/</g, "\\u003c")}`;
1167
+ head = `<template b-h="${boundary.id}">${late.html}</template>`;
1168
+ const title = late.title === void 0 ? "" : `,${scriptJSON(late.title)}`;
781
1169
  call += `;${headSwap ? "" : HEAD}$bH(${boundary.id}${title})`;
782
1170
  headSwap = true;
783
1171
  }
784
- queue.push(`<template data-l="${boundary.id}">${result.html}</template>${head}${result.ctx.portals.join("")}${script}${scriptTag}${call}<\/script>`);
1172
+ pending().push(`<template b-l="${boundary.id}">${result.html}</template>${head}${result.ctx.portals.join("")}${scriptTag}${call}<\/script>${script}`);
785
1173
  });
786
1174
  finish();
787
1175
  }, (error) => {
@@ -791,7 +1179,7 @@ async function render(Root, props, options = {}) {
791
1179
  });
792
1180
  let state = "";
793
1181
  let failure;
794
- serialize(ctx.state, (script) => {
1182
+ serialize(ctx, (script) => {
795
1183
  state = script;
796
1184
  }, options.route, (error) => {
797
1185
  failure = error;
@@ -800,7 +1188,7 @@ async function render(Root, props, options = {}) {
800
1188
  return {
801
1189
  html,
802
1190
  state,
803
- pending: queue.iterable,
1191
+ pending: queue === void 0 && open === 0 ? NOTHING_PENDING : pending().iterable,
804
1192
  headers: event?.headers ?? new Headers(),
805
1193
  status: event?.status ?? 200,
806
1194
  next: () => ctx.next(),
@@ -808,10 +1196,12 @@ async function render(Root, props, options = {}) {
808
1196
  };
809
1197
  }
810
1198
  const HTML = /<html[\s>]/i;
811
- /** Inserts markup before `</body>`, or at the end if there is none. */
812
- function beforeBodyEnd(html, content) {
1199
+ /**
1200
+ * Inserts markup before `</body>`, or at the end if there is none. `index`
1201
+ * is where `</body>` is, when the caller found it already.
1202
+ */
1203
+ function beforeBodyEnd(html, content, index = content ? html.toLowerCase().lastIndexOf("</body>") : -1) {
813
1204
  if (!content) return html;
814
- const index = html.toLowerCase().lastIndexOf("</body>");
815
1205
  return index === -1 ? html + content : html.slice(0, index) + content + html.slice(index);
816
1206
  }
817
1207
  /**
@@ -829,13 +1219,21 @@ function firstRender(html, componentHead, state, options) {
829
1219
  let page = html.slice(match.index);
830
1220
  const lower = page.toLowerCase();
831
1221
  const headEnd = lower.indexOf("</head>");
832
- if (headEnd !== -1) page = page.slice(0, headEnd) + headContent + page.slice(headEnd);
833
- else if (headContent) {
1222
+ let bodyEnd = lower.lastIndexOf("</body>");
1223
+ let at = headEnd;
1224
+ let inserted = headContent;
1225
+ if (headEnd === -1 && headContent) {
834
1226
  const bodyStart = lower.search(/<body[\s>]/);
835
- const at = bodyStart === -1 ? page.indexOf(">") + 1 : bodyStart;
836
- page = `${page.slice(0, at)}<head>${headContent}</head>${page.slice(at)}`;
1227
+ at = bodyStart === -1 ? page.indexOf(">") + 1 : bodyStart;
1228
+ inserted = `<head>${headContent}</head>`;
1229
+ }
1230
+ if (at !== -1 && inserted) {
1231
+ page = page.slice(0, at) + inserted + page.slice(at);
1232
+ const own = inserted.toLowerCase();
1233
+ if (bodyEnd >= at) bodyEnd += own.length;
1234
+ else if (own.includes("</body>")) bodyEnd = at + own.lastIndexOf("</body>");
837
1235
  }
838
- return `<!doctype html>${beforeBodyEnd(page, tail)}`;
1236
+ return `<!doctype html>${beforeBodyEnd(page, tail, bodyEnd)}`;
839
1237
  }
840
1238
  /**
841
1239
  * Renders a component as a stream. The first chunk is the whole first
@@ -844,19 +1242,17 @@ function firstRender(html, componentHead, state, options) {
844
1242
  * renders `<html>` gets the doctype and its head.
845
1243
  */
846
1244
  function renderToStream(Root, props, options = {}) {
847
- return new ReadableStream({ async start(controller) {
848
- try {
849
- await writeParts(await render(Root, props, options), options, controller);
850
- } catch (error) {
851
- controller.error(error);
852
- }
853
- } });
1245
+ return partsStream(() => render(Root, props, options), options);
854
1246
  }
855
1247
  /** Streams the parts of a page from `render`: the first render whole, then what resolves later. */
856
1248
  function streamParts(parts, options = {}) {
1249
+ return partsStream(() => parts, options);
1250
+ }
1251
+ /** A stream of the parts of a page. An error while it gets or writes them fails the stream. */
1252
+ function partsStream(getParts, options) {
857
1253
  return new ReadableStream({ async start(controller) {
858
1254
  try {
859
- await writeParts(parts, options, controller);
1255
+ await writeParts(await getParts(), options, controller);
860
1256
  } catch (error) {
861
1257
  controller.error(error);
862
1258
  }
@@ -864,50 +1260,81 @@ function streamParts(parts, options = {}) {
864
1260
  }
865
1261
  async function writeParts(parts, options, controller) {
866
1262
  controller.enqueue(firstRender(parts.html, parts.head, parts.state, options));
867
- for await (const chunk of parts.pending) controller.enqueue(chunk);
1263
+ if (parts.pending !== NOTHING_PENDING) for await (const chunk of parts.pending) controller.enqueue(chunk);
868
1264
  controller.close();
869
1265
  }
1266
+ /**
1267
+ * The message and status that answer an error. A `ServerError` sends its
1268
+ * own. Any other error is logged, and sends `fallback` with status 500.
1269
+ */
1270
+ function errorAnswer(error, fallback) {
1271
+ if (error instanceof ServerError) return {
1272
+ message: error.message,
1273
+ status: error.status
1274
+ };
1275
+ console.error(error);
1276
+ return {
1277
+ message: fallback,
1278
+ status: 500
1279
+ };
1280
+ }
870
1281
  /** True for a request that a `<form>` sent, without client code. */
871
1282
  function isFormPost(request) {
872
1283
  const type = request.headers.get("content-type") ?? "";
873
1284
  return type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data");
874
1285
  }
1286
+ /** The answer to a call or a form post from a page of another site. See `isCrossSite`. */
1287
+ function crossSiteAnswer() {
1288
+ return new Response("Calls from other sites are not allowed", { status: 403 });
1289
+ }
1290
+ /** The answer to a call or a form post to a server function that does not exist. */
1291
+ function unknownAnswer(id) {
1292
+ return new Response(`Unknown server function "${id}"`, { status: 404 });
1293
+ }
875
1294
  /**
876
- * Calls a server function with the data of a form that the browser sent, and
877
- * sends the browser back to the page with a redirect. A `redirect` in the
878
- * function sends it there instead. An error answers with a short text page,
879
- * because there is no page to report it in.
1295
+ * Calls a server function with the data of a form that the browser sent.
1296
+ * Returns its result, or the response that answers the post instead: a
1297
+ * `redirect` in the function sends the browser there, and an error answers
1298
+ * with a short text page, because there is no page to report it in. The
1299
+ * response has `headers`. With `base`, the location of a redirect is
1300
+ * resolved against it.
880
1301
  */
881
- async function handleForm(fn, request, event) {
882
- const { headers } = event;
883
- const back = request.headers.get("referer") ?? "/";
1302
+ async function callWithForm(fn, request, event, headers, base) {
884
1303
  try {
885
1304
  const form = await request.formData();
886
- await withEvent(event, () => fn(form));
887
- headers.set("location", back);
888
- return new Response(null, {
889
- status: 303,
890
- headers
891
- });
1305
+ return { result: await withEvent(event, () => fn(form)) };
892
1306
  } catch (error) {
893
1307
  if (error instanceof Redirect) {
894
- headers.set("location", error.location);
895
- return new Response(null, {
1308
+ headers.set("location", base ? new URL(error.location, base).href : error.location);
1309
+ return { answer: new Response(null, {
896
1310
  status: error.status,
897
1311
  headers
898
- });
1312
+ }) };
899
1313
  }
900
- const known = error instanceof ServerError;
901
- if (!known) console.error(error);
1314
+ const { message, status } = errorAnswer(error, "The server function failed");
902
1315
  headers.set("content-type", "text/plain; charset=utf-8");
903
- const message = known ? error.message : "The server function failed";
904
- return new Response(message, {
905
- status: known ? error.status : 500,
1316
+ return { answer: new Response(message, {
1317
+ status,
906
1318
  headers
907
- });
1319
+ }) };
908
1320
  }
909
1321
  }
910
1322
  /**
1323
+ * Calls a server function with the data of a form that the browser sent, and
1324
+ * sends the browser back to the page with a redirect. The response has the
1325
+ * headers of the event, such as cookies that the function set.
1326
+ */
1327
+ async function handleForm(fn, request, event) {
1328
+ const { headers } = event;
1329
+ const outcome = await callWithForm(fn, request, event, headers);
1330
+ if ("answer" in outcome) return outcome.answer;
1331
+ headers.set("location", request.headers.get("referer") ?? "/");
1332
+ return new Response(null, {
1333
+ status: 303,
1334
+ headers
1335
+ });
1336
+ }
1337
+ /**
911
1338
  * The arguments of a call. They come as seroval JSON, or as multipart form
912
1339
  * data when they hold files: the JSON in `args`, and each file in
913
1340
  * `file<index>`, where an `Upload` stands in the JSON.
@@ -962,15 +1389,14 @@ function isCrossSite(request, options = {}) {
962
1389
  async function handleRequest(functions, request, prefix = "/_brumate", options = {}) {
963
1390
  const url = new URL(request.url);
964
1391
  if (request.method !== "POST" || !url.pathname.startsWith(`${prefix}/`)) return;
965
- if (isCrossSite(request, options)) return new Response("Calls from other sites are not allowed", { status: 403 });
1392
+ if (isCrossSite(request, options)) return crossSiteAnswer();
966
1393
  const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));
967
- if (!functions[id]) return new Response(`Unknown server function "${id}"`, { status: 404 });
968
- const event = new RequestEvent(request);
969
1394
  const fn = functions[id];
1395
+ if (!fn) return unknownAnswer(id);
1396
+ const event = new RequestEvent(request);
970
1397
  const invoke = (args) => withEvent(event, () => fn(...args));
971
- const call = request.headers.has("x-brumate-args");
972
- if (isFormPost(request) && !call && !request.headers.has("x-brumate-result")) return handleForm(fn, request, event);
973
- if (isFormPost(request) && !call) {
1398
+ if (isFormPost(request) && !request.headers.has("x-brumate-args")) {
1399
+ if (!request.headers.has("x-brumate-result")) return handleForm(fn, request, event);
974
1400
  const form = await request.formData();
975
1401
  return answerCall(functions, event, async () => invoke([form]));
976
1402
  }
@@ -986,8 +1412,11 @@ async function answerCall(functions, event, run) {
986
1412
  const { headers } = event;
987
1413
  try {
988
1414
  const result = await run();
989
- const refreshed = Object.keys(functions).filter((key) => event.refreshed?.has(unwrap(functions[key])));
990
- if (refreshed.length > 0) headers.set("x-brumate-refresh", refreshed.join(","));
1415
+ const { refreshed } = event;
1416
+ if (refreshed?.size) {
1417
+ const ids = Object.keys(functions).filter((key) => refreshed.has(unwrap(functions[key])));
1418
+ if (ids.length > 0) headers.set("x-brumate-refresh", ids.join(","));
1419
+ }
991
1420
  headers.set("content-type", STREAM_TYPE);
992
1421
  return new Response(toChunkStream(result), { headers });
993
1422
  } catch (error) {
@@ -998,12 +1427,10 @@ async function answerCall(functions, event, run) {
998
1427
  headers
999
1428
  });
1000
1429
  }
1001
- const known = error instanceof ServerError;
1002
- if (!known) console.error(error);
1430
+ const { message, status } = errorAnswer(error, "The server function failed");
1003
1431
  headers.set("content-type", "application/json");
1004
- const message = known ? error.message : "The server function failed";
1005
1432
  return new Response(JSON.stringify({ error: message }), {
1006
- status: known ? error.status : 500,
1433
+ status,
1007
1434
  headers
1008
1435
  });
1009
1436
  }
@@ -1053,27 +1480,15 @@ function viewComponent(view, props) {
1053
1480
  * Runs the server function that a form without scripts posted to a page, as
1054
1481
  * `?__action=<id>`. Returns its result for `$action`, or the response that
1055
1482
  * answers the post instead of the page: a redirect, or an error.
1483
+ * `handleRoute` adds the cookies of the event to that response, and no other
1484
+ * headers of the event.
1056
1485
  */
1057
1486
  async function runAction(request, id, options, event) {
1058
- if (isCrossSite(request, options)) return { answer: new Response("Calls from other sites are not allowed", { status: 403 }) };
1487
+ if (isCrossSite(request, options)) return { answer: crossSiteAnswer() };
1059
1488
  const fn = options.functions?.[id];
1060
- if (!fn) return { answer: new Response(`Unknown server function "${id}"`, { status: 404 }) };
1061
- try {
1062
- const form = await request.formData();
1063
- const result = await withEvent(event, () => fn(form));
1064
- return { actions: /* @__PURE__ */ new Map([[fn, result]]) };
1065
- } catch (error) {
1066
- if (error instanceof Redirect) return { answer: new Response(null, {
1067
- status: error.status,
1068
- headers: { location: new URL(error.location, request.url).href }
1069
- }) };
1070
- const known = error instanceof ServerError;
1071
- if (!known) console.error(error);
1072
- return { answer: new Response(known ? error.message : "The server function failed", {
1073
- status: known ? error.status : 500,
1074
- headers: { "content-type": "text/plain; charset=utf-8" }
1075
- }) };
1076
- }
1489
+ if (!fn) return { answer: unknownAnswer(id) };
1490
+ const outcome = await callWithForm(fn, request, event, new Headers(), request.url);
1491
+ return "answer" in outcome ? outcome : { actions: /* @__PURE__ */ new Map([[fn, outcome.result]]) };
1077
1492
  }
1078
1493
  /** Renders the page of a route tree, streamed, with the results of a form for `$action`. */
1079
1494
  async function renderPage(view, props, request, options, extra) {
@@ -1146,7 +1561,8 @@ function withHeaders(answer, headers) {
1146
1561
  return result;
1147
1562
  }
1148
1563
  async function routeAnswer(tree, request, options) {
1149
- const match = matchRoute(tree, new URL(request.url).pathname);
1564
+ const url = new URL(request.url);
1565
+ const match = matchRoute(tree, url.pathname);
1150
1566
  if (!match) {
1151
1567
  const missing = notFound(tree);
1152
1568
  if (missing.errors.length === 0 && missing.middleware.length === 0) return;
@@ -1157,11 +1573,10 @@ async function routeAnswer(tree, request, options) {
1157
1573
  }, {}, request, options) ?? new Response("Not found", { status: 404 });
1158
1574
  });
1159
1575
  }
1160
- return runMiddleware(match.middleware, request, options.event, () => answerRoute(match, request, options));
1576
+ return runMiddleware(match.middleware, request, options.event, () => answerRoute(match, request, url, options));
1161
1577
  }
1162
- /** Answers a request that a route matches, after its middleware. */
1163
- async function answerRoute(match, request, options) {
1164
- const url = new URL(request.url);
1578
+ /** Answers a request that a route matches, after its middleware. `url` is the URL of the request. */
1579
+ async function answerRoute(match, request, url, options) {
1165
1580
  if (match.endpoint) {
1166
1581
  const endpoint = await match.endpoint();
1167
1582
  const handler = endpoint[request.method] ?? (request.method === "HEAD" ? endpoint.GET : void 0);
@@ -1188,18 +1603,13 @@ async function answerRoute(match, request, options) {
1188
1603
  status: error.status,
1189
1604
  headers: { location: new URL(error.location, url).href }
1190
1605
  });
1191
- const known = error instanceof ServerError;
1192
- if (!known && options.dev) throw error;
1193
- if (!known) console.error(error);
1194
- const page = await renderError(match.errors, {
1195
- message: known ? error.message : "Something went wrong",
1196
- status: known ? error.status : 500
1197
- }, match.params, request, options);
1606
+ if (options.dev && !(error instanceof ServerError)) throw error;
1607
+ const page = await renderError(match.errors, errorAnswer(error, "Something went wrong"), match.params, request, options);
1198
1608
  if (page) return page;
1199
1609
  throw error;
1200
1610
  }
1201
1611
  }
1202
1612
  //#endregion
1203
- export { dedupe as C, withEvent as D, redirect as E, ServerError as S, isRedirect as T, streamParts as _, component as a, matchRoute as b, handleRoute as c, lazy as d, memo as f, stateScript as g, renderToStream as h, actionResult as i, insert as l, render as m, NotReady as n, dynamic as o, read as p, action as r, handleRequest as s, Context as t, isCrossSite as u, streamState as v, getEvent as w, RequestEvent as x, wait as y };
1613
+ export { dedupe as A, fieldErrors as C, matchRoute as D, safeParse as E, isRedirect as M, redirect as N, RequestEvent as O, withEvent as P, ValidationError as S, parseForm as T, renderToStream as _, component as a, streamState as b, handleRoute as c, lazy as d, memo as f, render as g, ready as h, actionResult as i, getEvent as j, ServerError as k, insert as l, read as m, NotReady as n, dynamic as o, packState as p, action as r, handleRequest as s, Context as t, isCrossSite as u, stateScript as v, parse as w, wait as x, streamParts as y };
1204
1614
 
1205
- //# sourceMappingURL=server-CX3JnPCs.js.map
1615
+ //# sourceMappingURL=server-DZsgnPKS.js.map