brumate 0.8.0 → 0.9.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 (122) hide show
  1. package/dist/{boot-BkUdiYOF.d.ts → boot-ej-9NRT3.d.ts} +20 -2
  2. package/dist/cli.js +88 -82
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{client-B0FXW5Kw.js → client-B-ww-PQ7.js} +402 -63
  5. package/dist/client-B-ww-PQ7.js.map +1 -0
  6. package/dist/{client-Cq6aTiDs.d.ts → client-Do6IBIhI.d.ts} +58 -14
  7. package/dist/{defer-BMIMP4Hq.js → defer-JD2FK9mV.js} +5 -3
  8. package/dist/defer-JD2FK9mV.js.map +1 -0
  9. package/dist/{devtools-calls-DGW6nLZ2.js → devtools-calls-DCjuSkim.js} +3 -3
  10. package/dist/{devtools-calls-DGW6nLZ2.js.map → devtools-calls-DCjuSkim.js.map} +1 -1
  11. package/dist/{devtools-panel-B1nF1KB7.js → devtools-panel-DLeWTPhU.js} +4 -4
  12. package/dist/{devtools-panel-B1nF1KB7.js.map → devtools-panel-DLeWTPhU.js.map} +1 -1
  13. package/dist/{devtools-B4prrxht.js → devtools-tuq7ATGN.js} +10 -7
  14. package/dist/devtools-tuq7ATGN.js.map +1 -0
  15. package/dist/{error-catalog-DakxjSgj.js → error-catalog-BBWB7w-E.js} +11 -4
  16. package/dist/error-catalog-BBWB7w-E.js.map +1 -0
  17. package/dist/{error-catalog-VxLbz-6p.js → error-catalog-CbmQqfat.js} +1 -1
  18. package/dist/{events-LgLdp1R7.js → events-BDVITj3P.js} +3 -5
  19. package/dist/events-BDVITj3P.js.map +1 -0
  20. package/dist/{features-DwMYKBIC.js → features-Cte5aj20.js} +8 -2
  21. package/dist/features-Cte5aj20.js.map +1 -0
  22. package/dist/{files-D5GtxwEQ.js → files-Bz0lAQzD.js} +2 -2
  23. package/dist/{files-D5GtxwEQ.js.map → files-Bz0lAQzD.js.map} +1 -1
  24. package/dist/{html-Cf5uKhLs.js → html-BYuHDvxy.js} +10 -3
  25. package/dist/html-BYuHDvxy.js.map +1 -0
  26. package/dist/index.d.ts +71 -19
  27. package/dist/index.js +3 -3
  28. package/dist/{inspect-CGl5Y8q6.js → inspect-fpaBJ5pm.js} +1305 -75
  29. package/dist/inspect-fpaBJ5pm.js.map +1 -0
  30. package/dist/{loader-BsaSuIoG.js → loader-DMxuZ6He.js} +14 -6
  31. package/dist/loader-DMxuZ6He.js.map +1 -0
  32. package/dist/{navigate-BlowKvhB.js → navigate-C5PjwYMh.js} +108 -20
  33. package/dist/navigate-C5PjwYMh.js.map +1 -0
  34. package/dist/{produce-CLABZ8k2.d.ts → produce-BDkCsGH7.d.ts} +3 -3
  35. package/dist/{rpc-C1jYVNAe.js → rpc-DOdrekhP.js} +23 -13
  36. package/dist/rpc-DOdrekhP.js.map +1 -0
  37. package/dist/runtime/bundles.d.ts +3 -2
  38. package/dist/runtime/bundles.js +20 -5
  39. package/dist/runtime/bundles.js.map +1 -1
  40. package/dist/runtime/client.d.ts +4 -3
  41. package/dist/runtime/client.js +5 -5
  42. package/dist/runtime/devtools.d.ts +3 -1
  43. package/dist/runtime/devtools.js +1 -1
  44. package/dist/runtime/events.js +1 -1
  45. package/dist/runtime/hot.d.ts +1 -1
  46. package/dist/runtime/html.js +1 -1
  47. package/dist/runtime/loader.d.ts +2 -2
  48. package/dist/runtime/loader.js +2 -2
  49. package/dist/runtime/otel.d.ts +18 -0
  50. package/dist/runtime/otel.js +127 -0
  51. package/dist/runtime/otel.js.map +1 -0
  52. package/dist/runtime/server.d.ts +4 -3
  53. package/dist/runtime/server.js +5 -5
  54. package/dist/runtime/signals.d.ts +2 -2
  55. package/dist/runtime/signals.js +4 -1
  56. package/dist/runtime/signals.js.map +1 -1
  57. package/dist/runtime/static-loader.d.ts +2 -2
  58. package/dist/runtime/static-loader.js +1 -1
  59. package/dist/runtime/store.d.ts +2 -2
  60. package/dist/runtime/store.js +1 -1
  61. package/dist/runtime/testing.d.ts +2 -2
  62. package/dist/runtime/testing.js +2 -2
  63. package/dist/search-params-qGERTLi3.js +382 -0
  64. package/dist/search-params-qGERTLi3.js.map +1 -0
  65. package/dist/{serial-ribg9NAj.js → serial-B2AJ9VGx.js} +1 -1
  66. package/dist/{serial-ioa17MuY.js → serial-Cj6pDGOq.js} +6 -6
  67. package/dist/{serial-ioa17MuY.js.map → serial-Cj6pDGOq.js.map} +1 -1
  68. package/dist/{server-DesBZv5g.d.ts → server-2-LS_KFo.d.ts} +125 -9
  69. package/dist/{server-BUuf7XPZ.js → server-CRGZMWnK.js} +545 -236
  70. package/dist/server-CRGZMWnK.js.map +1 -0
  71. package/dist/{shared-CX_YacDm.js → shared-CUBWrbiM.js} +4 -4
  72. package/dist/{shared-CX_YacDm.js.map → shared-CUBWrbiM.js.map} +1 -1
  73. package/dist/sheets-B9Zr50mf.js +105 -0
  74. package/dist/sheets-B9Zr50mf.js.map +1 -0
  75. package/dist/{signals-7VVD9C_H.d.ts → signals-BgsJK-uT.d.ts} +16 -6
  76. package/dist/{static-loader-C_en-4v8.js → static-loader-BDBtWsdg.js} +107 -19
  77. package/dist/static-loader-BDBtWsdg.js.map +1 -0
  78. package/dist/{static-loader-UKnK11Em.d.ts → static-loader-CAFn6p0l.d.ts} +2 -2
  79. package/dist/{store-9_oa0HG1.d.ts → store-BwWg-Iei.d.ts} +79 -2
  80. package/dist/store-DNr24Z8L.js +950 -0
  81. package/dist/store-DNr24Z8L.js.map +1 -0
  82. package/dist/{stream-read-BTsYstJY.js → stream-read-CiLDH60b.js} +2 -2
  83. package/dist/{stream-read-BTsYstJY.js.map → stream-read-CiLDH60b.js.map} +1 -1
  84. package/dist/{stream-read-Dek3HnqO.js → stream-read-DVoregpA.js} +1 -1
  85. package/dist/trace-DT7RGRAV.d.ts +52 -0
  86. package/dist/trace-browser-C7MFMove.js +170 -0
  87. package/dist/trace-browser-C7MFMove.js.map +1 -0
  88. package/dist/trace-flag-Dy267snx.js +7 -0
  89. package/dist/trace-flag-Dy267snx.js.map +1 -0
  90. package/dist/{trusted-g_zUJbh2.js → trusted-Bmwg4_hf.js} +12 -5
  91. package/dist/trusted-Bmwg4_hf.js.map +1 -0
  92. package/dist/view-transitions-BpnVwtS4.js +141 -0
  93. package/dist/view-transitions-BpnVwtS4.js.map +1 -0
  94. package/dist/vite.d.ts +8 -1
  95. package/dist/vite.js +356 -46
  96. package/dist/vite.js.map +1 -1
  97. package/elements.d.ts +8 -0
  98. package/package.json +13 -1
  99. package/skills/brumate/SKILL.md +9 -5
  100. package/skills/brumate/references/errors.md +95 -14
  101. package/skills/brumate/references/events.md +27 -1
  102. package/skills/brumate/references/signals.md +4 -4
  103. package/skills/brumate/references/state.md +79 -4
  104. package/skills/brumate/references/syntax.md +58 -9
  105. package/dist/client-B0FXW5Kw.js.map +0 -1
  106. package/dist/defer-BMIMP4Hq.js.map +0 -1
  107. package/dist/devtools-B4prrxht.js.map +0 -1
  108. package/dist/error-catalog-DakxjSgj.js.map +0 -1
  109. package/dist/events-LgLdp1R7.js.map +0 -1
  110. package/dist/features-DwMYKBIC.js.map +0 -1
  111. package/dist/html-Cf5uKhLs.js.map +0 -1
  112. package/dist/inspect-CGl5Y8q6.js.map +0 -1
  113. package/dist/loader-BsaSuIoG.js.map +0 -1
  114. package/dist/navigate-BlowKvhB.js.map +0 -1
  115. package/dist/rpc-C1jYVNAe.js.map +0 -1
  116. package/dist/search-params-Wg-0FsMj.js +0 -148
  117. package/dist/search-params-Wg-0FsMj.js.map +0 -1
  118. package/dist/server-BUuf7XPZ.js.map +0 -1
  119. package/dist/static-loader-C_en-4v8.js.map +0 -1
  120. package/dist/store-Cy4EEyZ7.js +0 -439
  121. package/dist/store-Cy4EEyZ7.js.map +0 -1
  122. package/dist/trusted-g_zUJbh2.js.map +0 -1
@@ -1,19 +1,195 @@
1
1
  import { n as closesParagraph, r as firstTag } from "./nesting-DA5vJw9X.js";
2
- import { n as MODIFIERS } from "./events-LgLdp1R7.js";
3
- import { C as spread$1, S as rawHTML, a as attribute$1, b as ownValue, d as escapeAttribute, f as handlerEntry, g as isRaw, n as VOID_ELEMENTS, p as insertValue, r as actionAttributes, s as bindEntry, u as escape, v as onAttribute, w as styleElement } from "./html-Cf5uKhLs.js";
2
+ import { n as MODIFIERS } from "./events-BDVITj3P.js";
3
+ import { C as spread$1, S as rawHTML, a as attribute$1, b as ownValue, d as escapeAttribute, f as handlerEntry, g as isRaw, n as VOID_ELEMENTS, p as insertValue, r as actionAttributes, s as bindEntry, u as escape, v as onAttribute, w as styleElement } from "./html-BYuHDvxy.js";
4
4
  import { n as deleteCookie, o as setCookie, r as getCookies } from "./cookies-Cnbf4w-S.js";
5
- import { a as serialOptions, c as functionReferences, i as plugins, n as callPlugins, o as syncPlugins, t as BridgeDataError } from "./serial-ioa17MuY.js";
6
- import { d as isStore, h as sentForeignStore, n as Store, o as findStored, u as isForeignStore } from "./store-Cy4EEyZ7.js";
7
- import { a as FunctionReference, c as PropPromise, d as addEntryHandlers, g as isSlotReference, i as ElementReference, m as isBinding, n as CHILDREN_REF, o as MemoError, p as isAsyncIterable, r as ChildrenReference, s as PARTS, t as Binding, u as SlotReference, x as parseId } from "./shared-CX_YacDm.js";
5
+ import { a as serialOptions, c as functionReferences, i as plugins, n as callPlugins, o as syncPlugins, t as BridgeDataError } from "./serial-Cj6pDGOq.js";
6
+ import { i as Store, l as findStored, m as isStore, p as isForeignStore, x as sentForeignStore } from "./store-DNr24Z8L.js";
7
+ import { a as FunctionReference, c as PropPromise, d as addEntryHandlers, g as isSlotReference, i as ElementReference, m as isBinding, n as CHILDREN_REF, o as MemoError, p as isAsyncIterable, r as ChildrenReference, s as PARTS, t as Binding, u as SlotReference, x as parseId } from "./shared-CUBWrbiM.js";
8
8
  import { n as serverSecrets } from "./secrets-BxagsJxJ.js";
9
- import { t as ANSWER } from "./stream-read-BTsYstJY.js";
10
- import "./search-params-Wg-0FsMj.js";
9
+ import { t as ANSWER } from "./stream-read-CiLDH60b.js";
10
+ import "./search-params-qGERTLi3.js";
11
11
  import { i as missingContext } from "./context-CU4Fpn5a.js";
12
12
  import { a as applyIntent, d as formatPath, f as getAt, m as groupIssues, r as INTENT, u as formValues, v as parseIntent, y as parsePath } from "./forms-nXK7-Lv_.js";
13
13
  import { SerovalDeserializationError, SerovalMissingPluginError, SerovalPluginValidationError, fromJSON } from "seroval/read";
14
14
  import { crossSerialize, crossSerializeStream, toJSON } from "seroval/write";
15
15
  import { toWebStream } from "@seroval/transport/web";
16
16
  import { createJSONWriter } from "@seroval/transport/write";
17
+ //#region src/runtime/trace.ts
18
+ function noSpan() {}
19
+ const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/;
20
+ /** The trace and parent of a `traceparent` header, or none when it is not valid. */
21
+ function readTraceparent(header) {
22
+ const match = header ? TRACEPARENT.exec(header.trim()) : null;
23
+ if (!match || /^0+$/.test(match[1]) || /^0+$/.test(match[2])) return;
24
+ return {
25
+ traceId: match[1],
26
+ parentId: match[2]
27
+ };
28
+ }
29
+ function randomHex(bytes) {
30
+ const data = crypto.getRandomValues(new Uint8Array(bytes));
31
+ let hex = "";
32
+ for (const byte of data) hex += byte.toString(16).padStart(2, "0");
33
+ return /^0+$/.test(hex) ? randomHex(bytes) : hex;
34
+ }
35
+ function now() {
36
+ return performance.timeOrigin + performance.now();
37
+ }
38
+ /** What the spans of one request or render share. Made only when the app has an `onTrace`. */
39
+ var Tracer = class {
40
+ traceId;
41
+ /** The parent of an incoming `traceparent`. */
42
+ incoming;
43
+ /** The `spanId` of the span of the request. */
44
+ root;
45
+ /** The `spanId` of the latest render. */
46
+ render;
47
+ /** The attributes of the span of the request, which the server fills in as it learns them. */
48
+ attributes = {};
49
+ handler;
50
+ /** The spans that began and have not ended, except the request, so an aborted request can end them. */
51
+ open = /* @__PURE__ */ new Set();
52
+ /** The first error that failed a span, which a 5xx answer of the request is the sign of. */
53
+ fault;
54
+ /** True once a span ended with an answer error such as a `ServerError`, which can have a 5xx status. */
55
+ answered = false;
56
+ constructor(handler, traceparent) {
57
+ const parent = readTraceparent(traceparent);
58
+ this.handler = handler;
59
+ this.traceId = parent?.traceId ?? randomHex(16);
60
+ this.incoming = parent?.parentId;
61
+ }
62
+ };
63
+ /** Gives the span to `onTrace`. A throw or a rejection is logged and changes nothing else. */
64
+ function emit(handler, span) {
65
+ try {
66
+ const result = handler(span);
67
+ if (result && typeof result.then === "function") result.then(void 0, (error) => console.error(error));
68
+ } catch (error) {
69
+ console.error(error);
70
+ }
71
+ }
72
+ /** The classes of errors that are answers, not faults: `ServerError` and `Redirect`. `request.ts` adds them. */
73
+ const answerErrors = [];
74
+ function isAnswer(error) {
75
+ for (const type of answerErrors) if (error instanceof type) return true;
76
+ return false;
77
+ }
78
+ /** The message of an error, without its stack. */
79
+ function failure(error) {
80
+ return { message: error instanceof Error ? error.message : String(error) };
81
+ }
82
+ /**
83
+ * Starts a span and returns what ends it, which hands the span to `onTrace`.
84
+ * A span that is never ended is never handed over. Call it only when
85
+ * `source.tracer` is set.
86
+ */
87
+ function startSpan(source, name, label) {
88
+ const tracer = source.tracer;
89
+ if (!tracer) return noSpan;
90
+ const spanId = randomHex(8);
91
+ const start = now();
92
+ let parentId;
93
+ if (name === "brumate.request") {
94
+ parentId = tracer.incoming;
95
+ tracer.root = spanId;
96
+ } else if (name === "brumate.render" || name === "brumate.stream") {
97
+ parentId = tracer.root ?? tracer.incoming;
98
+ if (name === "brumate.render") tracer.render = spanId;
99
+ } else parentId = tracer.render ?? tracer.root ?? tracer.incoming;
100
+ let done = false;
101
+ const end = (failed, error) => {
102
+ if (done) return;
103
+ done = true;
104
+ tracer.open.delete(end);
105
+ let status = "ok";
106
+ if (failed && isAnswer(error)) tracer.answered = true;
107
+ else if (failed) {
108
+ status = "error";
109
+ tracer.fault ??= error ?? /* @__PURE__ */ new Error("failed");
110
+ }
111
+ const span = {
112
+ name,
113
+ label,
114
+ traceId: tracer.traceId,
115
+ spanId,
116
+ start,
117
+ end: now(),
118
+ status,
119
+ attributes: name === "brumate.request" ? { ...tracer.attributes } : {}
120
+ };
121
+ if (parentId !== void 0) span.parentId = parentId;
122
+ if (status === "error") span.error = failure(error);
123
+ emit(tracer.handler, span);
124
+ };
125
+ if (name !== "brumate.request") tracer.open.add(end);
126
+ return end;
127
+ }
128
+ /**
129
+ * Ends the span of a request when its response has been read to the end, or
130
+ * its reader left or failed, or the request aborted. Spans of the request
131
+ * that are still open, such as a `#loading` body, end as failed then.
132
+ * Returns the response to send, which has the same body.
133
+ *
134
+ * Rebuilding the response is deliberate. It happens only when `onTrace` is
135
+ * set, because the body must pass through a stream that sees its end.
136
+ */
137
+ function traceResponse(source, end, response, signal) {
138
+ const tracer = source.tracer;
139
+ tracer.attributes["http.status_code"] = response.status;
140
+ function finish(reason) {
141
+ if (reason !== void 0) {
142
+ const aborted = reason instanceof Error ? reason : /* @__PURE__ */ new Error("The request was aborted");
143
+ for (const open of tracer.open) open(true, aborted);
144
+ end(true, aborted);
145
+ return;
146
+ }
147
+ const failed = tracer.fault !== void 0 || response.status >= 500 && !tracer.answered;
148
+ end(failed, failed ? tracer.fault ?? /* @__PURE__ */ new Error(`HTTP ${response.status}`) : void 0);
149
+ }
150
+ if (!response.body) {
151
+ finish();
152
+ return response;
153
+ }
154
+ signal?.addEventListener("abort", () => finish(signal.reason ?? true), { once: true });
155
+ const body = response.body.pipeThrough(new TransformStream({
156
+ flush: () => finish(),
157
+ cancel: (reason) => finish(reason ?? true)
158
+ }));
159
+ const headers = new Headers(response.headers);
160
+ const result = new Response(body, {
161
+ status: response.status,
162
+ statusText: response.statusText,
163
+ headers
164
+ });
165
+ if (result.headers.getSetCookie().length === 0) for (const cookie of headers.getSetCookie()) result.headers.append("set-cookie", cookie);
166
+ return result;
167
+ }
168
+ /**
169
+ * Runs the work of a request inside its `brumate.request` span. The span
170
+ * ends with the response, and not at all when `run` gives none. `route` is
171
+ * the pattern of the route, never the URL.
172
+ */
173
+ async function traceRequest(event, route, kind, run) {
174
+ const tracer = event.tracer;
175
+ if (!tracer) return run();
176
+ const method = event.request.method;
177
+ tracer.attributes["http.method"] = method;
178
+ tracer.attributes["http.route"] = route;
179
+ const end = startSpan(event, "brumate.request", `${method} ${route}`);
180
+ let response;
181
+ try {
182
+ response = await run();
183
+ } catch (error) {
184
+ tracer.attributes["brumate.kind"] = kind();
185
+ tracer.attributes["http.status_code"] = 500;
186
+ end(true, error);
187
+ throw error;
188
+ }
189
+ tracer.attributes["brumate.kind"] = kind();
190
+ return response && traceResponse(event, end, response, event.signal);
191
+ }
192
+ //#endregion
17
193
  //#region src/runtime/request.ts
18
194
  /** Where the server takes the error of a `waitUntil` promise that no host keeps, in place of the log. */
19
195
  const failures = {};
@@ -24,11 +200,11 @@ function errorSink(handler) {
24
200
  handled: /* @__PURE__ */ new WeakSet()
25
201
  };
26
202
  }
27
- function noTrace() {}
203
+ const noTrace = noSpan;
28
204
  /** Ends an entry of the trace when a value settles, if it is a promise, or at once. */
29
205
  function traceValue(value, end) {
30
206
  const thenable = value;
31
- if (thenable && typeof thenable.then === "function") thenable.then(() => end(), () => end(true));
207
+ if (thenable && typeof thenable.then === "function") thenable.then(() => end(), (error) => end(true, error));
32
208
  else end();
33
209
  return value;
34
210
  }
@@ -111,19 +287,26 @@ var RequestEvent = class {
111
287
  trace;
112
288
  /** When the trace started, by `performance.now()`. */
113
289
  traceStart = 0;
114
- /** Starts an entry of the trace, when there is one, and returns what ends it. */
290
+ /** Makes the spans for `onTrace`, when the app has one. */
291
+ tracer;
292
+ /**
293
+ * Starts an entry of the trace, for the devtools in development and for
294
+ * `onTrace`, and returns what ends it. Without either it makes nothing.
295
+ */
115
296
  traced(kind, label) {
116
297
  const trace = this.trace;
117
- if (!trace) return noTrace;
298
+ const end = this.tracer ? startSpan(this, `brumate.${kind}`, label) : noTrace;
299
+ if (!trace) return end;
118
300
  const entry = {
119
301
  kind,
120
302
  label,
121
303
  start: performance.now() - this.traceStart
122
304
  };
123
305
  trace.push(entry);
124
- return (failed) => {
306
+ return (failed, error) => {
125
307
  entry.end = performance.now() - this.traceStart;
126
308
  if (failed) entry.failed = true;
309
+ end(failed, error);
127
310
  };
128
311
  }
129
312
  /**
@@ -149,6 +332,7 @@ var RequestEvent = class {
149
332
  this.address = options.address;
150
333
  this.prerender = options.prerender ?? false;
151
334
  this.errors = errorSink(options.onError);
335
+ if (options.onTrace) this.tracer = new Tracer(options.onTrace, request.headers.get("traceparent"));
152
336
  watchPersonal(request.headers, () => {
153
337
  this.personal = true;
154
338
  });
@@ -220,6 +404,7 @@ let current;
220
404
  /** The results of server function calls of the render that runs now, by function and arguments. */
221
405
  let currentCalls;
222
406
  globalThis[Symbol.for("brumate.inRequest")] = () => current !== void 0 || currentCalls !== void 0;
407
+ const RENDER = Symbol.for("brumate.render");
223
408
  /**
224
409
  * Runs a callback with an event, so `getEvent()` in its code before its first
225
410
  * `await` returns it. Returns what the callback returns, such as its promise.
@@ -228,13 +413,17 @@ globalThis[Symbol.for("brumate.inRequest")] = () => current !== void 0 || curren
228
413
  function withEvent(event, callback, calls) {
229
414
  const outer = current;
230
415
  const outerCalls = currentCalls;
416
+ const global = globalThis;
417
+ const outerRender = global[RENDER];
231
418
  current = event;
232
419
  currentCalls = calls;
420
+ global[RENDER] = calls;
233
421
  try {
234
422
  return callback();
235
423
  } finally {
236
424
  current = outer;
237
425
  currentCalls = outerCalls;
426
+ global[RENDER] = outerRender;
238
427
  }
239
428
  }
240
429
  /** The event of the request being handled, or undefined, without throwing as `getEvent` does. */
@@ -370,6 +559,7 @@ function redirect(location, status = 303) {
370
559
  function isRedirect(error) {
371
560
  return error instanceof Redirect;
372
561
  }
562
+ answerErrors.push(ServerError, Redirect);
373
563
  //#endregion
374
564
  //#region src/runtime/cache.ts
375
565
  /** Tags live longer than any result, so a result never outlives the version of its tag. */
@@ -541,6 +731,224 @@ function toChunkStream(value, onCancel, onError) {
541
731
  });
542
732
  }
543
733
  //#endregion
734
+ //#region src/runtime/route-render.ts
735
+ /** The `cache` of the page of a view: the nearest one along its `children`. */
736
+ function pageCache(view) {
737
+ const inner = view.slots.children;
738
+ return (inner && pageCache(inner)) ?? view.cache;
739
+ }
740
+ /**
741
+ * The `cache-control` of a page with `cache`. It is public only when the
742
+ * request did not read or set anything of the user, and the page is a
743
+ * success without cookies.
744
+ */
745
+ function cacheControl(cache, event, response) {
746
+ if (event?.personal || response.status !== 200 || response.headers.getSetCookie().length > 0) return "private, no-cache";
747
+ const parts = ["public", `max-age=${Math.max(0, Math.floor(cache.maxAge))}`];
748
+ if (cache.staleWhileRevalidate !== void 0) parts.push(`stale-while-revalidate=${Math.max(0, Math.floor(cache.staleWhileRevalidate))}`);
749
+ return parts.join(", ");
750
+ }
751
+ const warnedPrivate = /* @__PURE__ */ new Set();
752
+ /**
753
+ * Renders a view where its layout inserts it. A view with a loading file
754
+ * streams in after the rest of the page, as a `#loading` body does.
755
+ */
756
+ async function renderView(view, props, ctx, scope) {
757
+ if (!view.loading) return component(viewComponent(view, props), {}, ctx, scope);
758
+ const id = ctx.boundary();
759
+ const fallback = await component(view.loading, props, ctx, scope);
760
+ ctx.defer(id, (child) => component(viewComponent(view, props), {}, child, scope));
761
+ return `<!--l${id}-->${fallback}<!--/l-->`;
762
+ }
763
+ /**
764
+ * A component that renders a route, with its slots rendering where the
765
+ * layout inserts them. `props` go to every view, such as `params`.
766
+ */
767
+ /** The component IDs of a view and of the views in its slots. */
768
+ function viewIds(view) {
769
+ const id = view.component.brumateId;
770
+ const ids = id === void 0 ? [] : [id];
771
+ for (const slot of Object.values(view.slots)) ids.push(...viewIds(slot));
772
+ return ids;
773
+ }
774
+ function viewComponent(view, props) {
775
+ return (_props, ctx) => {
776
+ const own = { ...props };
777
+ for (const [name, slot] of Object.entries(view.slots)) own[name] = lazy(async (at, scope) => {
778
+ const root = at.peek();
779
+ const html = await renderView(slot, props, at, scope);
780
+ return `<!--R${scope ?? -1}:${name}:${root}:${encodeURIComponent(slot.key)}-->${html}<!--/R-->`;
781
+ });
782
+ return view.component(own, ctx);
783
+ };
784
+ }
785
+ /** Renders the page of a route tree, streamed, with the results of a form for `$action`. */
786
+ async function renderPage(view, props, request, options, extra) {
787
+ const base = Number(request.headers.get("x-brumate-base"));
788
+ const defer = deferTarget(request);
789
+ if (defer) return renderDeferred(view, props, request, options, defer, base);
790
+ const event = options.event;
791
+ if (options.dev && event) {
792
+ event.trace = [];
793
+ event.traceStart = performance.now();
794
+ }
795
+ const path = new URL(request.url).pathname;
796
+ const endRender = event?.traced("render", path) ?? (() => {});
797
+ const navigation = request.headers.has("x-brumate-base");
798
+ const wanted = navigation ? [] : [...options.hints ?? []];
799
+ const styles = /* @__PURE__ */ new Set();
800
+ for (const id of viewIds(view)) for (const url of options.bundleHints?.[id] ?? []) if (url.endsWith(".css")) {
801
+ if (!url.startsWith(".")) styles.add(url);
802
+ } else if (!navigation) wanted.push(url);
803
+ const hints = [...new Set(wanted)];
804
+ const nonce = options.nonce === void 0 ? "" : ` nonce="${escapeAttribute(options.nonce)}"`;
805
+ const links = [];
806
+ if (!nonce) for (const url of hints) links.push(`<${url}>; rel=modulepreload`);
807
+ if (links.length > 0) options.earlyHints?.(links);
808
+ let preload = "";
809
+ for (const url of hints) preload += `<link rel="modulepreload"${nonce} href="${escapeAttribute(url)}">`;
810
+ let parts;
811
+ try {
812
+ parts = await render(viewComponent(view, props), {}, {
813
+ ...options,
814
+ request,
815
+ actions: extra.actions,
816
+ route: view.key,
817
+ params: props.params,
818
+ linked: styles,
819
+ base: Number.isSafeInteger(base) && base > 0 ? base : void 0
820
+ });
821
+ } catch (error) {
822
+ endRender(true, error);
823
+ throw error;
824
+ }
825
+ endRender();
826
+ for (const url of styles) {
827
+ const needs = navigation ? void 0 : (options.bundles ?? clientBundles)?.deferred?.[url];
828
+ const href = escapeAttribute(url);
829
+ if (needs?.every((id) => parts.styled.has(id))) {
830
+ preload += `<link rel="preload" as="style" b-sheet${nonce} href="${href}">`;
831
+ preload += `<noscript b-sheet><link rel="stylesheet"${nonce} href="${href}"></noscript>`;
832
+ } else preload += `<link rel="stylesheet"${nonce} href="${href}">`;
833
+ }
834
+ const endStream = event?.traced("stream", "the rest of the page") ?? (() => {});
835
+ const headers = new Headers(parts.headers);
836
+ headers.set("content-type", "text/html; charset=utf-8");
837
+ headers.append("vary", "x-brumate-defer");
838
+ headers.append("vary", "x-brumate-base");
839
+ for (const link of links) headers.append("link", link);
840
+ let html = streamParts(parts, {
841
+ ...options,
842
+ head: preload + (options.head ?? "")
843
+ });
844
+ if (event?.trace || event?.tracer) {
845
+ const trace = event.trace;
846
+ html = html.pipeThrough(new TransformStream({ flush(controller) {
847
+ endStream();
848
+ if (trace) {
849
+ const json = JSON.stringify({
850
+ route: path,
851
+ entries: trace
852
+ }).replace(/</g, "\\u003c");
853
+ controller.enqueue(`<script type="application/json" b-trace>${json}<\/script>`);
854
+ }
855
+ } }));
856
+ }
857
+ const body = html.pipeThrough(new TextEncoderStream());
858
+ const cache = request.method === "GET" || request.method === "HEAD" ? pageCache(view) : void 0;
859
+ if (!cache) return respond(body, {
860
+ status: extra.status ?? parts.status,
861
+ headers
862
+ });
863
+ const response = respond(await new Response(body).arrayBuffer(), {
864
+ status: extra.status ?? parts.status,
865
+ headers
866
+ });
867
+ const control = cacheControl(cache, options.event, response);
868
+ if (options.dev) {
869
+ response.headers.set("cache-control", "no-cache");
870
+ response.headers.set("x-brumate-cache", control);
871
+ if (control.startsWith("private") && !warnedPrivate.has(view.key)) {
872
+ warnedPrivate.add(view.key);
873
+ console.warn(`The page ${new URL(request.url).pathname} exports cache, but it read cookies or the authorization header, or set a cookie, so it is not cached for everyone. Move what reads the user into #defer.`);
874
+ }
875
+ } else response.headers.set("cache-control", control);
876
+ return response;
877
+ }
878
+ /**
879
+ * Renders the route again and answers with the body of one `#defer` block:
880
+ * its markup in a `<template b-l>`, the script that swaps it in, and its
881
+ * state. The page renders with the base it had, so its IDs come out the
882
+ * same. When the block is not where the browser has it, such as after the
883
+ * data of the page changed, the answer is 409 and the fallback stays.
884
+ */
885
+ async function renderDeferred(view, props, request, options, defer, base) {
886
+ const bundles = options.bundles ?? clientBundles;
887
+ const parts = await render(viewComponent(view, props), {}, {
888
+ ...options,
889
+ request,
890
+ route: view.key,
891
+ params: props.params,
892
+ base: Number.isSafeInteger(base) && base > 0 ? base : void 0,
893
+ defer,
894
+ bundles: bundles && {
895
+ ...bundles,
896
+ loaded: viewIds(view)
897
+ }
898
+ });
899
+ const headers = new Headers(parts.headers);
900
+ headers.append("vary", "x-brumate-defer");
901
+ if (parts.defer !== "found") return respond(null, {
902
+ status: parts.defer === "moved" ? 409 : 404,
903
+ headers
904
+ });
905
+ headers.set("content-type", "text/html; charset=utf-8");
906
+ headers.set("x-brumate-defer", String(defer.boundary));
907
+ return respond(new ReadableStream({ async start(controller) {
908
+ try {
909
+ if (parts.pending !== NOTHING_PENDING) for await (const chunk of parts.pending) controller.enqueue(chunk);
910
+ controller.close();
911
+ } catch (error) {
912
+ controller.error(error);
913
+ }
914
+ } }).pipeThrough(new TextEncoderStream()), {
915
+ status: parts.status,
916
+ headers
917
+ });
918
+ }
919
+ /** Runs the server function that a form posted to the page, if any, and renders the page. */
920
+ async function renderRoute(match, request, url, options) {
921
+ let actions;
922
+ const event = options.event;
923
+ if (event.call) {
924
+ const outcome = await runAction(options.functions[event.call.id], event);
925
+ if ("answer" in outcome) return outcome.answer;
926
+ actions = outcome.actions;
927
+ }
928
+ const key = !event.call && !options.dev && options.pageCache !== false && event.kind === "page" && (request.method === "GET" || request.method === "HEAD") ? pageKey(url, request, options.build) : void 0;
929
+ if (key && !event.personal) {
930
+ const kept = await keptPage(key);
931
+ if (kept) return kept;
932
+ }
933
+ try {
934
+ const response = await renderPage(await resolveView(match.view), { params: match.params }, request, options, { actions });
935
+ if (key && /^\s*public\b/.test(response.headers.get("cache-control") ?? "")) await keepPage(key, response, event);
936
+ return response;
937
+ } catch (error) {
938
+ if (isRedirect(error)) return new Response(null, {
939
+ status: error.status,
940
+ headers: { location: new URL(error.location, url).href }
941
+ });
942
+ if (options.dev && !(error instanceof ServerError)) {
943
+ logError(error, options.event?.kind ?? "page", options.event?.errors, options.event);
944
+ throw error;
945
+ }
946
+ const page = await renderError(match.errors, errorAnswer(error, "Something went wrong", options.event?.kind ?? "page", options.event), match.params, request, options);
947
+ if (page) return page;
948
+ throw error;
949
+ }
950
+ }
951
+ //#endregion
544
952
  //#region src/runtime/router.ts
545
953
  function key(path, file, params) {
546
954
  return `${path}/${file} ${JSON.stringify(params)}`;
@@ -1398,6 +1806,12 @@ var Context = class Context {
1398
1806
  inTarget = false;
1399
1807
  boundaries = [];
1400
1808
  styles = /* @__PURE__ */ new Set();
1809
+ /** The `<link>` elements of the stylesheets that components asked for, in render order. */
1810
+ sheets = [];
1811
+ /** The URLs of the stylesheets that the page links already. */
1812
+ linked = /* @__PURE__ */ new Set();
1813
+ /** The bundles of the client build, for the stylesheet of each component. */
1814
+ bundles;
1401
1815
  /** Markup of `#portal` blocks, written at the end of the page. */
1402
1816
  portals = [];
1403
1817
  /** Markup of `#head` blocks. */
@@ -1438,6 +1852,8 @@ var Context = class Context {
1438
1852
  event;
1439
1853
  /** The sink of the event, or of the `onError` option of a render without a request. */
1440
1854
  errors;
1855
+ /** The spans of a render without a request, when the app has an `onTrace`. */
1856
+ tracer;
1441
1857
  /** Results of server function calls in this render, so the same call runs once. */
1442
1858
  calls = /* @__PURE__ */ new Map();
1443
1859
  /** The event of the request, or undefined when the render has none. */
@@ -1456,7 +1872,9 @@ var Context = class Context {
1456
1872
  }
1457
1873
  /** Starts an entry of the trace of the request, in development. */
1458
1874
  traced(kind, label) {
1459
- return this.root.event?.traced(kind, label);
1875
+ const { event, tracer } = this.root;
1876
+ if (event) return event.traced(kind, label);
1877
+ return tracer && startSpan(this.root, `brumate.${kind}`, label);
1460
1878
  }
1461
1879
  /** Marks the request of the page as one that depends on the user, so the page is not cached for everyone. */
1462
1880
  personal() {
@@ -2004,13 +2422,55 @@ var Context = class Context {
2004
2422
  functionReferences.set(bound, new FunctionReference(ref, scope, args));
2005
2423
  return bound;
2006
2424
  }
2007
- /** Returns a component's stylesheet the first time the page renders the component. */
2425
+ /**
2426
+ * Returns a component's stylesheet the first time the page renders the component. A build
2427
+ * passes no `css`: the page gets the CSS of the component from the bundles, as an inline
2428
+ * `<style>` in its head, or in place when the head has gone out. A component the bundles have
2429
+ * no CSS for gets a link to its stylesheet asset.
2430
+ */
2008
2431
  style(id, css) {
2009
- const styles = this.root.styles;
2432
+ const root = this.root;
2433
+ const styles = root.styles;
2010
2434
  if (styles.has(id)) return "";
2011
2435
  styles.add(id);
2012
2436
  this.undo.push(() => styles.delete(id));
2013
- return styleElement(id, css, this.root.nonce);
2437
+ if (css !== void 0) return styleElement(id, css, root.nonce);
2438
+ const inline = root.bundles?.css?.[id];
2439
+ if (inline !== void 0) {
2440
+ const element = styleElement(id, inline, root.nonce);
2441
+ if (root.sent || this.inTarget) return element;
2442
+ root.sheets.push(element);
2443
+ this.undo.push(() => removeLast(root.sheets, element));
2444
+ return "";
2445
+ }
2446
+ const nonce = root.nonce === void 0 ? "" : ` nonce="${escapeAttribute(root.nonce)}"`;
2447
+ const inPlace = root.sent || this.inTarget;
2448
+ let html = "";
2449
+ const added = [];
2450
+ for (const url of root.bundles?.components?.[id] ?? []) if (this.inTarget || !root.linked.has(url)) {
2451
+ if (!this.inTarget) {
2452
+ root.linked.add(url);
2453
+ added.push(url);
2454
+ }
2455
+ html += `<link rel="stylesheet"${nonce} href="${escapeAttribute(url)}">`;
2456
+ }
2457
+ this.undo.push(() => {
2458
+ for (const url of added) root.linked.delete(url);
2459
+ });
2460
+ if (inPlace) return html;
2461
+ if (html) {
2462
+ root.sheets.push(html);
2463
+ this.undo.push(() => removeLast(root.sheets, html));
2464
+ }
2465
+ return "";
2466
+ }
2467
+ /** The IDs of the components that the page wrote the CSS of. */
2468
+ styledIds() {
2469
+ return this.root.styles;
2470
+ }
2471
+ /** The `<link>` elements of the stylesheets that the components of the page asked for. */
2472
+ sheetHTML() {
2473
+ return this.root.sheets.join("");
2014
2474
  }
2015
2475
  /** Adds the markup of a `#head` block. */
2016
2476
  head(html) {
@@ -2133,7 +2593,7 @@ var Context = class Context {
2133
2593
  deferBlock(id, at, renderBody) {
2134
2594
  const target = this.root.target;
2135
2595
  if (!target && this.root.inOrder) {
2136
- this.register(id, renderBody, false);
2596
+ this.register(id, renderBody, false, false, "#defer");
2137
2597
  return;
2138
2598
  }
2139
2599
  if (!target || this.inTarget) return;
@@ -2147,16 +2607,16 @@ var Context = class Context {
2147
2607
  return;
2148
2608
  }
2149
2609
  target.status = "found";
2150
- this.register(id, renderBody, true);
2610
+ this.register(id, renderBody, true, false, "#defer");
2151
2611
  }
2152
- register(id, renderBody, inTarget, around = false) {
2612
+ register(id, renderBody, inTarget, around = false, block = "#loading") {
2153
2613
  const child = new Context(this.root, void 0, 0, `${id}.`);
2154
2614
  child.inTarget = inTarget;
2155
2615
  const catchers = [...this.outer, ...this.catchers];
2156
2616
  child.outer = catchers;
2157
2617
  const group = this.reveal;
2158
2618
  group?.add(id);
2159
- const end = around ? void 0 : this.traced("body", `#loading ${id}`);
2619
+ const end = around ? void 0 : this.traced("body", `${block} ${id}`);
2160
2620
  const boundary = {
2161
2621
  id,
2162
2622
  render: renderBody(child).then((html) => {
@@ -2166,7 +2626,7 @@ var Context = class Context {
2166
2626
  ctx: child
2167
2627
  };
2168
2628
  }, (error) => {
2169
- end?.(true);
2629
+ end?.(true, error);
2170
2630
  throw error;
2171
2631
  }),
2172
2632
  around,
@@ -2233,10 +2693,12 @@ function read(node) {
2233
2693
  if (value !== null && typeof value === "object" && (typeof value.then === "function" || isAsyncIterable(value))) {
2234
2694
  node.state = "pending";
2235
2695
  const end = node.ctx?.traced("memo", node.name ?? "memo");
2236
- node.load = Promise.resolve(value).then(firstValue).finally(() => end?.()).then((result) => {
2696
+ node.load = Promise.resolve(value).then(firstValue).then((result) => {
2697
+ end?.();
2237
2698
  node.state = "done";
2238
2699
  node.value = result;
2239
2700
  }, (error) => {
2701
+ end?.(true, error);
2240
2702
  node.state = "failed";
2241
2703
  node.error = error;
2242
2704
  });
@@ -2520,6 +2982,11 @@ function holds(value, target, seen = /* @__PURE__ */ new Set()) {
2520
2982
  for (const item of items) if (holds(item, target, seen)) return true;
2521
2983
  return false;
2522
2984
  }
2985
+ /** The name of the source of a memo of a module that holds `target`, in the values of its sources. */
2986
+ function sourceHolding(sources, target) {
2987
+ if (typeof sources !== "object" || sources === null) return;
2988
+ for (const [name, value] of Object.entries(sources)) if (holds(value, target)) return name;
2989
+ }
2523
2990
  /**
2524
2991
  * The error of a value in the state of a page that cannot be sent to the
2525
2992
  * browser, which names the value and its component.
@@ -2541,6 +3008,11 @@ function unsendable(error, ctx) {
2541
3008
  const name = names?.[index] ?? `slot ${index}`;
2542
3009
  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.`);
2543
3010
  const kind = target?.constructor?.name ?? typeof target;
3011
+ if (name.startsWith("$$ms_in_")) {
3012
+ const sources = record.s[index]?.s;
3013
+ const signal = sourceHolding(sources, target);
3014
+ if (signal !== void 0) return new Error(`The source "${signal}" of the module memo "${name.slice(8)}" in ${owner?.m ?? "a component"} holds a ${kind}, which cannot be sent to the browser, and the browser checks it to tell whether to load the memo again. Use it in a server function, or create it in the browser, such as in $client.`, { cause: error });
3015
+ }
2544
3016
  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 });
2545
3017
  }
2546
3018
  return error instanceof Error ? error : new Error(String(error));
@@ -2973,6 +3445,8 @@ async function render(Root, props, options = {}) {
2973
3445
  if (options.params) ctx.params = options.params;
2974
3446
  ctx.build = options.build;
2975
3447
  ctx.nonce = options.nonce;
3448
+ ctx.bundles = options.bundles ?? clientBundles;
3449
+ ctx.linked = new Set(options.linked);
2976
3450
  ctx.development = options.dev === true;
2977
3451
  if (options.defer) ctx.target = { ...options.defer };
2978
3452
  ctx.inOrder = !options.defer && rendersInOrder(options.inOrder ?? "bots", options.request ?? options.event?.request);
@@ -2981,12 +3455,23 @@ async function render(Root, props, options = {}) {
2981
3455
  waitUntil: options.waitUntil,
2982
3456
  address: options.address,
2983
3457
  prerender: options.prerender,
2984
- onError: options.onError
3458
+ onError: options.onError,
3459
+ onTrace: options.onTrace
2985
3460
  }) : void 0);
2986
3461
  if (event && options.nonce !== void 0) event.nonce = options.nonce;
2987
3462
  ctx.event = event;
2988
3463
  ctx.errors = event ? event.errors : errorSink(options.onError);
2989
- const rendered = await ctx.run(() => Root(props, ctx));
3464
+ if (!event && options.onTrace) ctx.tracer = new Tracer(options.onTrace);
3465
+ const tracing = options.event ? void 0 : event ?? ctx;
3466
+ const endRender = tracing?.tracer ? startSpan(tracing, "brumate.render", options.route ?? "render") : void 0;
3467
+ let rendered;
3468
+ try {
3469
+ rendered = await ctx.run(() => Root(props, ctx));
3470
+ } catch (error) {
3471
+ endRender?.(true, error);
3472
+ throw error;
3473
+ }
3474
+ endRender?.();
2990
3475
  ctx.send();
2991
3476
  const html = beforeBodyEnd(rendered, ctx.portals.join(""));
2992
3477
  let queue;
@@ -3132,6 +3617,8 @@ async function render(Root, props, options = {}) {
3132
3617
  status: event?.status ?? 200,
3133
3618
  next: () => ctx.next(),
3134
3619
  head: "",
3620
+ sheets: "",
3621
+ styled: /* @__PURE__ */ new Set(),
3135
3622
  defer: ctx.target.status ?? "missing"
3136
3623
  };
3137
3624
  let state = "";
@@ -3193,6 +3680,8 @@ async function render(Root, props, options = {}) {
3193
3680
  status: event?.status ?? 200,
3194
3681
  next: () => ctx.next(),
3195
3682
  head: ctx.headHTML(),
3683
+ sheets: ctx.sheetHTML(),
3684
+ styled: ctx.styledIds(),
3196
3685
  event
3197
3686
  };
3198
3687
  }
@@ -3291,11 +3780,11 @@ function beforeBodyEnd(html, content, index = content ? html.toLowerCase().lastI
3291
3780
  * doctype, its head before `</head>`, and the state and scripts before
3292
3781
  * `</body>`. Markup that resolves later is written after it.
3293
3782
  */
3294
- function firstRender(html, componentHead, state, options) {
3295
- const head = (options.head ?? "") + componentHead;
3783
+ function firstRender(html, componentHead, sheets, state, options) {
3784
+ const head = (options.head ?? "") + sheets + componentHead;
3296
3785
  const tail = state + (options.scripts ?? "");
3297
3786
  const match = HTML.exec(html);
3298
- if (!match) return (typeof options.start === "function" ? options.start(head) : options.start ?? "") + html + tail + (options.end ?? "");
3787
+ if (!match) return (typeof options.start === "function" ? options.start(head) : options.start ?? "") + (typeof options.start === "function" ? "" : sheets) + html + tail + (options.end ?? "");
3299
3788
  const headContent = html.slice(0, match.index) + head;
3300
3789
  let page = nameHtmlAttributes(html.slice(match.index));
3301
3790
  const lower = page.toLowerCase();
@@ -3353,7 +3842,7 @@ function partsStream(getParts, options) {
3353
3842
  });
3354
3843
  }
3355
3844
  async function writeParts(parts, options, controller, cancelled = () => false) {
3356
- controller.enqueue(firstRender(parts.html, parts.head, parts.state, options));
3845
+ controller.enqueue(firstRender(parts.html, parts.head, parts.sheets, parts.state, options));
3357
3846
  if (parts.pending !== NOTHING_PENDING) for await (const chunk of parts.pending) {
3358
3847
  if (cancelled()) return;
3359
3848
  controller.enqueue(chunk);
@@ -3512,6 +4001,17 @@ async function callWithForm(invoke, headers, event, base) {
3512
4001
  return { answer: formFailure(error, headers, event, base) };
3513
4002
  }
3514
4003
  }
4004
+ /** Runs a server function that the browser called, as a `brumate.call` span. */
4005
+ function tracedCall(event, id, fn, args) {
4006
+ if (!event.tracer && !event.trace) return withEvent(event, () => fn(...args));
4007
+ const end = event.traced("call", id);
4008
+ try {
4009
+ return traceValue(withEvent(event, () => fn(...args)), end);
4010
+ } catch (error) {
4011
+ end(true, error);
4012
+ throw error;
4013
+ }
4014
+ }
3515
4015
  /** The answer to a form post whose server function threw, or whose data could not be read. */
3516
4016
  function formFailure(error, headers, event, base) {
3517
4017
  if (error instanceof Redirect) {
@@ -3623,7 +4123,8 @@ async function handleRequest(functions, request, prefix = "/_brumate", options =
3623
4123
  waitUntil: options.waitUntil,
3624
4124
  address: options.address,
3625
4125
  prerender: options.prerender,
3626
- onError: options.onError
4126
+ onError: options.onError,
4127
+ onTrace: options.onTrace
3627
4128
  });
3628
4129
  let args;
3629
4130
  try {
@@ -3636,9 +4137,13 @@ async function handleRequest(functions, request, prefix = "/_brumate", options =
3636
4137
  args
3637
4138
  };
3638
4139
  function invoke() {
3639
- return withEvent(event, () => fn(...args));
4140
+ return tracedCall(event, id, fn, args);
3640
4141
  }
3641
- return runEntry(options.middleware, event, () => runEntry(options.fileMiddleware?.[id], event, () => posted ? handleForm(invoke, event) : answerCall(functions, event, async () => invoke())));
4142
+ function answer() {
4143
+ return runEntry(options.middleware, event, () => runEntry(options.fileMiddleware?.[id], event, () => posted ? handleForm(invoke, event) : answerCall(functions, event, async () => invoke())));
4144
+ }
4145
+ if (!event.tracer) return answer();
4146
+ return traceRequest(event, `${prefix}/${id}`, () => posted ? "form" : "call", answer);
3642
4147
  }
3643
4148
  /**
3644
4149
  * Answers a server function call with its result as a stream of seroval
@@ -3722,23 +4227,6 @@ async function keepPage(key, response, event) {
3722
4227
  };
3723
4228
  await cacheStore().set(key, JSON.stringify(page), maxAge);
3724
4229
  }
3725
- /** The `cache` of the page of a view: the nearest one along its `children`. */
3726
- function pageCache(view) {
3727
- const inner = view.slots.children;
3728
- return (inner && pageCache(inner)) ?? view.cache;
3729
- }
3730
- /**
3731
- * The `cache-control` of a page with `cache`. It is public only when the
3732
- * request did not read or set anything of the user, and the page is a
3733
- * success without cookies.
3734
- */
3735
- function cacheControl(cache, event, response) {
3736
- if (event?.personal || response.status !== 200 || response.headers.getSetCookie().length > 0) return "private, no-cache";
3737
- const parts = ["public", `max-age=${Math.max(0, Math.floor(cache.maxAge))}`];
3738
- if (cache.staleWhileRevalidate !== void 0) parts.push(`stale-while-revalidate=${Math.max(0, Math.floor(cache.staleWhileRevalidate))}`);
3739
- return parts.join(", ");
3740
- }
3741
- const warnedPrivate = /* @__PURE__ */ new Set();
3742
4230
  /** Imports every module of a matched route before it renders. */
3743
4231
  async function resolveView(view) {
3744
4232
  const names = Object.keys(view.slots);
@@ -3760,39 +4248,6 @@ async function resolveView(view) {
3760
4248
  };
3761
4249
  }
3762
4250
  /**
3763
- * Renders a view where its layout inserts it. A view with a loading file
3764
- * streams in after the rest of the page, as a `#loading` body does.
3765
- */
3766
- async function renderView(view, props, ctx, scope) {
3767
- if (!view.loading) return component(viewComponent(view, props), {}, ctx, scope);
3768
- const id = ctx.boundary();
3769
- const fallback = await component(view.loading, props, ctx, scope);
3770
- ctx.defer(id, (child) => component(viewComponent(view, props), {}, child, scope));
3771
- return `<!--l${id}-->${fallback}<!--/l-->`;
3772
- }
3773
- /**
3774
- * A component that renders a route, with its slots rendering where the
3775
- * layout inserts them. `props` go to every view, such as `params`.
3776
- */
3777
- /** The component IDs of a view and of the views in its slots. */
3778
- function viewIds(view) {
3779
- const id = view.component.brumateId;
3780
- const ids = id === void 0 ? [] : [id];
3781
- for (const slot of Object.values(view.slots)) ids.push(...viewIds(slot));
3782
- return ids;
3783
- }
3784
- function viewComponent(view, props) {
3785
- return (_props, ctx) => {
3786
- const own = { ...props };
3787
- for (const [name, slot] of Object.entries(view.slots)) own[name] = lazy(async (at, scope) => {
3788
- const root = at.peek();
3789
- const html = await renderView(slot, props, at, scope);
3790
- return `<!--R${scope ?? -1}:${name}:${root}:${encodeURIComponent(slot.key)}-->${html}<!--/R-->`;
3791
- });
3792
- return view.component(own, ctx);
3793
- };
3794
- }
3795
- /**
3796
4251
  * Runs the server function that a form without scripts posted to a page, as
3797
4252
  * `?__action=<id>`. Returns its result for `$action`, or the response that
3798
4253
  * answers the post instead of the page: a redirect, or an error.
@@ -3802,7 +4257,7 @@ function viewComponent(view, props) {
3802
4257
  async function runAction(fn, event) {
3803
4258
  const { request } = event;
3804
4259
  const args = event.call.args;
3805
- const outcome = await callWithForm(() => withEvent(event, () => fn(...args)), new Headers(), event, request.url);
4260
+ const outcome = await callWithForm(() => tracedCall(event, event.call.id, fn, args), new Headers(), event, request.url);
3806
4261
  return "answer" in outcome ? outcome : { actions: /* @__PURE__ */ new Map([[fn, outcome.result]]) };
3807
4262
  }
3808
4263
  /**
@@ -3826,83 +4281,6 @@ async function readAction(url, event, options) {
3826
4281
  return formFailure(error, new Headers(), event, request.url);
3827
4282
  }
3828
4283
  }
3829
- /** Renders the page of a route tree, streamed, with the results of a form for `$action`. */
3830
- async function renderPage(view, props, request, options, extra) {
3831
- const base = Number(request.headers.get("x-brumate-base"));
3832
- const defer = deferTarget(request);
3833
- if (defer) return renderDeferred(view, props, request, options, defer, base);
3834
- const event = options.event;
3835
- if (options.dev && event) {
3836
- event.trace = [];
3837
- event.traceStart = performance.now();
3838
- }
3839
- const path = new URL(request.url).pathname;
3840
- const endRender = event?.traced("render", path) ?? (() => {});
3841
- const navigation = request.headers.has("x-brumate-base");
3842
- const wanted = navigation ? [] : [...options.hints ?? []];
3843
- const styles = /* @__PURE__ */ new Set();
3844
- for (const id of viewIds(view)) for (const url of options.bundleHints?.[id] ?? []) if (url.endsWith(".css")) {
3845
- if (!url.startsWith(".")) styles.add(url);
3846
- } else if (!navigation) wanted.push(url);
3847
- const hints = [...new Set(wanted)];
3848
- const nonce = options.nonce === void 0 ? "" : ` nonce="${escapeAttribute(options.nonce)}"`;
3849
- const links = [];
3850
- if (!nonce) for (const url of hints) links.push(`<${url}>; rel=modulepreload`);
3851
- if (links.length > 0) options.earlyHints?.(links);
3852
- let preload = "";
3853
- for (const url of hints) preload += `<link rel="modulepreload"${nonce} href="${escapeAttribute(url)}">`;
3854
- for (const url of styles) preload += `<link rel="stylesheet"${nonce} href="${escapeAttribute(url)}">`;
3855
- const parts = await render(viewComponent(view, props), {}, {
3856
- ...options,
3857
- request,
3858
- actions: extra.actions,
3859
- route: view.key,
3860
- params: props.params,
3861
- base: Number.isSafeInteger(base) && base > 0 ? base : void 0
3862
- });
3863
- endRender();
3864
- const endStream = event?.traced("stream", "the rest of the page") ?? (() => {});
3865
- const headers = new Headers(parts.headers);
3866
- headers.set("content-type", "text/html; charset=utf-8");
3867
- headers.append("vary", "x-brumate-defer");
3868
- headers.append("vary", "x-brumate-base");
3869
- for (const link of links) headers.append("link", link);
3870
- let html = streamParts(parts, {
3871
- ...options,
3872
- head: preload + (options.head ?? "")
3873
- });
3874
- if (event?.trace) {
3875
- const trace = event.trace;
3876
- html = html.pipeThrough(new TransformStream({ flush(controller) {
3877
- endStream();
3878
- const json = JSON.stringify({
3879
- route: path,
3880
- entries: trace
3881
- }).replace(/</g, "\\u003c");
3882
- controller.enqueue(`<script type="application/json" b-trace>${json}<\/script>`);
3883
- } }));
3884
- }
3885
- const body = html.pipeThrough(new TextEncoderStream());
3886
- const cache = request.method === "GET" || request.method === "HEAD" ? pageCache(view) : void 0;
3887
- if (!cache) return respond(body, {
3888
- status: extra.status ?? parts.status,
3889
- headers
3890
- });
3891
- const response = respond(await new Response(body).arrayBuffer(), {
3892
- status: extra.status ?? parts.status,
3893
- headers
3894
- });
3895
- const control = cacheControl(cache, options.event, response);
3896
- if (options.dev) {
3897
- response.headers.set("cache-control", "no-cache");
3898
- response.headers.set("x-brumate-cache", control);
3899
- if (control.startsWith("private") && !warnedPrivate.has(view.key)) {
3900
- warnedPrivate.add(view.key);
3901
- console.warn(`The page ${new URL(request.url).pathname} exports cache, but it read cookies or the authorization header, or set a cookie, so it is not cached for everyone. Move what reads the user into #defer.`);
3902
- }
3903
- } else response.headers.set("cache-control", control);
3904
- return response;
3905
- }
3906
4284
  /**
3907
4285
  * The `#defer` block that a request asks for, from `x-brumate-defer:
3908
4286
  * <boundary> <scope>:<anchor>`, which the browser sends when the block's
@@ -3916,47 +4294,6 @@ function deferTarget(request) {
3916
4294
  } : void 0;
3917
4295
  }
3918
4296
  /**
3919
- * Renders the route again and answers with the body of one `#defer` block:
3920
- * its markup in a `<template b-l>`, the script that swaps it in, and its
3921
- * state. The page renders with the base it had, so its IDs come out the
3922
- * same. When the block is not where the browser has it, such as after the
3923
- * data of the page changed, the answer is 409 and the fallback stays.
3924
- */
3925
- async function renderDeferred(view, props, request, options, defer, base) {
3926
- const bundles = options.bundles ?? clientBundles;
3927
- const parts = await render(viewComponent(view, props), {}, {
3928
- ...options,
3929
- request,
3930
- route: view.key,
3931
- params: props.params,
3932
- base: Number.isSafeInteger(base) && base > 0 ? base : void 0,
3933
- defer,
3934
- bundles: bundles && {
3935
- ...bundles,
3936
- loaded: viewIds(view)
3937
- }
3938
- });
3939
- const headers = new Headers(parts.headers);
3940
- headers.append("vary", "x-brumate-defer");
3941
- if (parts.defer !== "found") return respond(null, {
3942
- status: parts.defer === "moved" ? 409 : 404,
3943
- headers
3944
- });
3945
- headers.set("content-type", "text/html; charset=utf-8");
3946
- headers.set("x-brumate-defer", String(defer.boundary));
3947
- return respond(new ReadableStream({ async start(controller) {
3948
- try {
3949
- if (parts.pending !== NOTHING_PENDING) for await (const chunk of parts.pending) controller.enqueue(chunk);
3950
- controller.close();
3951
- } catch (error) {
3952
- controller.error(error);
3953
- }
3954
- } }).pipeThrough(new TextEncoderStream()), {
3955
- status: parts.status,
3956
- headers
3957
- });
3958
- }
3959
- /**
3960
4297
  * Renders the first `_error.brm` that renders, from the innermost. Its
3961
4298
  * component gets `error`, with the message and the status.
3962
4299
  */
@@ -4000,11 +4337,15 @@ async function handleRoute(tree, request, options = {}) {
4000
4337
  waitUntil: options.waitUntil,
4001
4338
  address: options.address,
4002
4339
  prerender: options.prerender,
4003
- onError: options.onError
4340
+ onError: options.onError,
4341
+ onTrace: options.onTrace
4004
4342
  });
4005
4343
  if (options.nonce !== void 0) event.nonce = options.nonce;
4006
4344
  event.route = match?.route;
4007
- const answer = await routeAnswer(tree, match, url, {
4345
+ const answer = event.tracer ? await traceRequest(event, match?.route ?? "unmatched", () => event.call ? "form" : event.kind, () => routeAnswer(tree, match, url, {
4346
+ ...options,
4347
+ event
4348
+ })) : await routeAnswer(tree, match, url, {
4008
4349
  ...options,
4009
4350
  event
4010
4351
  });
@@ -4130,38 +4471,6 @@ async function answerRoute(match, request, url, options) {
4130
4471
  const call = event.call;
4131
4472
  return runEntry(call && options.fileMiddleware?.[call.id], event, () => renderRoute(match, request, url, options));
4132
4473
  }
4133
- /** Runs the server function that a form posted to the page, if any, and renders the page. */
4134
- async function renderRoute(match, request, url, options) {
4135
- let actions;
4136
- const event = options.event;
4137
- if (event.call) {
4138
- const outcome = await runAction(options.functions[event.call.id], event);
4139
- if ("answer" in outcome) return outcome.answer;
4140
- actions = outcome.actions;
4141
- }
4142
- const key = !event.call && !options.dev && options.pageCache !== false && event.kind === "page" && (request.method === "GET" || request.method === "HEAD") ? pageKey(url, request, options.build) : void 0;
4143
- if (key && !event.personal) {
4144
- const kept = await keptPage(key);
4145
- if (kept) return kept;
4146
- }
4147
- try {
4148
- const response = await renderPage(await resolveView(match.view), { params: match.params }, request, options, { actions });
4149
- if (key && /^\s*public\b/.test(response.headers.get("cache-control") ?? "")) await keepPage(key, response, event);
4150
- return response;
4151
- } catch (error) {
4152
- if (isRedirect(error)) return new Response(null, {
4153
- status: error.status,
4154
- headers: { location: new URL(error.location, url).href }
4155
- });
4156
- if (options.dev && !(error instanceof ServerError)) {
4157
- logError(error, options.event?.kind ?? "page", options.event?.errors, options.event);
4158
- throw error;
4159
- }
4160
- const page = await renderError(match.errors, errorAnswer(error, "Something went wrong", options.event?.kind ?? "page", options.event), match.params, request, options);
4161
- if (page) return page;
4162
- throw error;
4163
- }
4164
- }
4165
4474
  /**
4166
4475
  * Renders an object of attributes. A handler in it, such as an `onClick`
4167
4476
  * that a component passes on with `...rest`, goes into `on` as a `b-on`
@@ -4201,6 +4510,6 @@ function spread(attributes, on, names) {
4201
4510
  return spread$1(attributes, names);
4202
4511
  }
4203
4512
  //#endregion
4204
- export { dedupe as $, streamParts as A, ValidationError as B, setClientBundles as C, start as D, spread as E, RateLimitError as F, matchRoute as G, parse as H, clientAddress as I, revalidate as J, cached as K, configureRateLimit as L, wait as M, waitAll as N, stateScript as O, idempotent as P, ServerError as Q, rateLimit as R, renderToStream as S, spacerTag as T, parseForm as U, fieldErrors as V, safeParse as W, storageStore as X, setCacheStore as Y, RequestEvent as Z, memo as _, attribute as a, ready as b, children as c, handleRequest as d, defineMiddleware as et, handleRoute as f, lazy as g, isCrossSite as h, actionResult as i, withEvent as it, streamState as j, stateValue as k, component as l, insert as m, NotReady as n, isRedirect as nt, binding as o, inlineBodies as p, memoryStore as q, action as r, redirect as rt, caught as s, Context as t, getEvent as tt, dynamic as u, packState as v, settled as w, render as x, read as y, parseSubmission as z };
4513
+ export { fieldErrors as $, renderError as A, stateScript as B, logError as C, read as D, pageKey as E, setClientBundles as F, waitAll as G, streamParts as H, settled as I, clientAddress as J, idempotent as K, spacerTag as L, resolveView as M, respond as N, ready as O, runAction as P, ValidationError as Q, spread as R, lazy as S, packState as T, streamState as U, stateValue as V, wait as W, rateLimit as X, configureRateLimit as Y, parseSubmission as Z, inlineBodies as _, actionResult as a, memoryStore as at, keepPage as b, caught as c, storageStore as ct, component as d, dedupe as dt, parse as et, deferTarget as f, defineMiddleware as ft, handleRoute as g, withEvent as gt, handleRequest as h, redirect as ht, action as i, cached as it, renderToStream as j, render as k, children as l, RequestEvent as lt, errorAnswer as m, isRedirect as mt, NOTHING_PENDING as n, safeParse as nt, attribute as o, revalidate as ot, dynamic as p, getEvent as pt, RateLimitError as q, NotReady as r, matchRoute as rt, binding as s, setCacheStore as st, Context as t, parseForm as tt, clientBundles as u, ServerError as ut, insert as v, memo as w, keptPage as x, isCrossSite as y, start as z };
4205
4514
 
4206
- //# sourceMappingURL=server-BUuf7XPZ.js.map
4515
+ //# sourceMappingURL=server-CRGZMWnK.js.map