brumate 0.1.1 → 0.3.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 (136) hide show
  1. package/dist/{boot-DN1ZU8Hg.d.ts → boot-C25Sa6vq.d.ts} +27 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/client-BD6XT-s5.js +1968 -0
  4. package/dist/client-BD6XT-s5.js.map +1 -0
  5. package/dist/{client-DwJInP_a.d.ts → client-D0CqSxoO.d.ts} +211 -30
  6. package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
  7. package/dist/client-routes-JTbGtukf.js.map +1 -0
  8. package/dist/context-CTiSzQRc.js +27 -0
  9. package/dist/context-CTiSzQRc.js.map +1 -0
  10. package/dist/context-btHuB01Z.d.ts +42 -0
  11. package/dist/{cookies-Av5WFmcf.js → cookies-BzllthiF.js} +2 -1
  12. package/dist/cookies-BzllthiF.js.map +1 -0
  13. package/dist/defer-BbD7JQhj.js +56 -0
  14. package/dist/defer-BbD7JQhj.js.map +1 -0
  15. package/dist/devtools-CQgD7NPB.js +623 -0
  16. package/dist/devtools-CQgD7NPB.js.map +1 -0
  17. package/dist/devtools-panel-BVB-W5q4.js +1930 -0
  18. package/dist/devtools-panel-BVB-W5q4.js.map +1 -0
  19. package/dist/events-CSs7OwIC.js +85 -0
  20. package/dist/events-CSs7OwIC.js.map +1 -0
  21. package/dist/{files-DdT84mPy.js → files-BXSSrQgc.js} +34 -6
  22. package/dist/files-BXSSrQgc.js.map +1 -0
  23. package/dist/forms-Bg-CwGqX.js +406 -0
  24. package/dist/forms-Bg-CwGqX.js.map +1 -0
  25. package/dist/forms-Cl21hkHt.d.ts +281 -0
  26. package/dist/highlight.d.ts +17 -0
  27. package/dist/highlight.js +269 -0
  28. package/dist/highlight.js.map +1 -0
  29. package/dist/html-Bq1rFxX_.d.ts +92 -0
  30. package/dist/html-mNTKzaDD.js +241 -0
  31. package/dist/html-mNTKzaDD.js.map +1 -0
  32. package/dist/index.d.ts +123 -30
  33. package/dist/index.js +14 -6
  34. package/dist/index.js.map +1 -1
  35. package/dist/{inspect-BPchdWbU.js → inspect-BHpOw1LF.js} +1400 -121
  36. package/dist/inspect-BHpOw1LF.js.map +1 -0
  37. package/dist/{loader-Dc9OwY5I.js → loader-Dos_3NP0.js} +47 -11
  38. package/dist/loader-Dos_3NP0.js.map +1 -0
  39. package/dist/{navigate-CzLjnoPH.js → navigate-O78d_zGN.js} +115 -13
  40. package/dist/navigate-O78d_zGN.js.map +1 -0
  41. package/dist/produce-D0V0ICkz.d.ts +114 -0
  42. package/dist/produce-Doc91GkX.js +274 -0
  43. package/dist/produce-Doc91GkX.js.map +1 -0
  44. package/dist/routes-BZNt7DSZ.d.ts +38 -0
  45. package/dist/{rpc-9fSqL_YK.js → rpc-ygMRPmN4.js} +39 -23
  46. package/dist/rpc-ygMRPmN4.js.map +1 -0
  47. package/dist/runtime/batch.d.ts +23 -0
  48. package/dist/runtime/batch.js +69 -0
  49. package/dist/runtime/batch.js.map +1 -0
  50. package/dist/runtime/client.d.ts +5 -5
  51. package/dist/runtime/client.js +5 -1345
  52. package/dist/runtime/context.d.ts +2 -2
  53. package/dist/runtime/context.js +1 -1
  54. package/dist/runtime/devtools.d.ts +191 -5
  55. package/dist/runtime/devtools.js +1 -1
  56. package/dist/runtime/env.d.ts +44 -0
  57. package/dist/runtime/env.js +61 -0
  58. package/dist/runtime/env.js.map +1 -0
  59. package/dist/runtime/events.d.ts +42 -0
  60. package/dist/runtime/events.js +1 -0
  61. package/dist/runtime/forms.d.ts +2 -0
  62. package/dist/runtime/forms.js +1 -0
  63. package/dist/runtime/gather.d.ts +25 -0
  64. package/dist/runtime/gather.js +33 -0
  65. package/dist/runtime/gather.js.map +1 -0
  66. package/dist/runtime/hot.d.ts +1 -1
  67. package/dist/runtime/html.d.ts +2 -2
  68. package/dist/runtime/html.js +1 -1
  69. package/dist/runtime/loader.d.ts +2 -2
  70. package/dist/runtime/loader.js +2 -2
  71. package/dist/runtime/routes.d.ts +2 -21
  72. package/dist/runtime/routes.js +31 -1
  73. package/dist/runtime/routes.js.map +1 -1
  74. package/dist/runtime/server.d.ts +7 -5
  75. package/dist/runtime/server.js +6 -7
  76. package/dist/runtime/signals.d.ts +60 -3
  77. package/dist/runtime/signals.js +40 -2
  78. package/dist/runtime/signals.js.map +1 -1
  79. package/dist/runtime/static-loader.d.ts +2 -2
  80. package/dist/runtime/static-loader.js +1 -1
  81. package/dist/runtime/testing.d.ts +46 -5
  82. package/dist/runtime/testing.js +240 -33
  83. package/dist/runtime/testing.js.map +1 -1
  84. package/dist/runtime/values.d.ts +2 -0
  85. package/dist/runtime/values.js +24 -0
  86. package/dist/runtime/values.js.map +1 -0
  87. package/dist/secrets-BxagsJxJ.js +23 -0
  88. package/dist/secrets-BxagsJxJ.js.map +1 -0
  89. package/dist/server-CxVDYE_V.js +3417 -0
  90. package/dist/server-CxVDYE_V.js.map +1 -0
  91. package/dist/server-DuFYRXrd.d.ts +1460 -0
  92. package/dist/skew-FRmAy9iy.js +49 -0
  93. package/dist/skew-FRmAy9iy.js.map +1 -0
  94. package/dist/standard-schema-BNY82yX3.d.ts +63 -0
  95. package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-Drpr0AzI.d.ts} +2 -2
  96. package/dist/static-loader-nZssh66R.js +333 -0
  97. package/dist/static-loader-nZssh66R.js.map +1 -0
  98. package/dist/stream-DCYZO4IF.js +424 -0
  99. package/dist/stream-DCYZO4IF.js.map +1 -0
  100. package/dist/values-B8C7CLvG.d.ts +63 -0
  101. package/dist/vite.d.ts +49 -1
  102. package/dist/vite.js +598 -68
  103. package/dist/vite.js.map +1 -1
  104. package/forms/forms.brm.ts +141 -0
  105. package/package.json +45 -3
  106. package/types.d.ts +9 -1
  107. package/dist/client-routes-DakuM32C.js.map +0 -1
  108. package/dist/context-BG8KCF3v.js +0 -15
  109. package/dist/context-BG8KCF3v.js.map +0 -1
  110. package/dist/context-aeo9esY9.d.ts +0 -16
  111. package/dist/cookies-Av5WFmcf.js.map +0 -1
  112. package/dist/devtools-BKjnHrnv.js +0 -113
  113. package/dist/devtools-BKjnHrnv.js.map +0 -1
  114. package/dist/devtools-panel-AWOn0VK2.js +0 -434
  115. package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
  116. package/dist/files-DdT84mPy.js.map +0 -1
  117. package/dist/html-DEeoepg3.js +0 -152
  118. package/dist/html-DEeoepg3.js.map +0 -1
  119. package/dist/html-Du8jY2Cc.d.ts +0 -53
  120. package/dist/inspect-BPchdWbU.js.map +0 -1
  121. package/dist/loader-Dc9OwY5I.js.map +0 -1
  122. package/dist/navigate-CzLjnoPH.js.map +0 -1
  123. package/dist/produce-BRGHP7e0.js +0 -126
  124. package/dist/produce-BRGHP7e0.js.map +0 -1
  125. package/dist/produce-CtZ32UGG.d.ts +0 -60
  126. package/dist/rpc-9fSqL_YK.js.map +0 -1
  127. package/dist/runtime/client.js.map +0 -1
  128. package/dist/server-BxqjLUnV.d.ts +0 -753
  129. package/dist/server-DZsgnPKS.js +0 -1615
  130. package/dist/server-DZsgnPKS.js.map +0 -1
  131. package/dist/shared-CWYOd0H3.js +0 -40
  132. package/dist/shared-CWYOd0H3.js.map +0 -1
  133. package/dist/static-loader-ClNkHZGn.js +0 -185
  134. package/dist/static-loader-ClNkHZGn.js.map +0 -1
  135. package/dist/stream-bgNCMcaA.js +0 -280
  136. package/dist/stream-bgNCMcaA.js.map +0 -1
@@ -0,0 +1,424 @@
1
+ import { n as MODIFIERS } from "./events-CSs7OwIC.js";
2
+ import { _ as rawHTML, p as isRaw } from "./html-mNTKzaDD.js";
3
+ import { c as isSlotReference, f as stateValues, l as onSerialOptions, r as ElementReference, s as isBinding, u as onValuePlugin } from "./produce-Doc91GkX.js";
4
+ import { Feature, Stream, createPlugin, fromCrossJSON, toCrossJSONStream } from "seroval";
5
+ import { AbortSignalPlugin, CustomEventPlugin, DOMExceptionPlugin, EventPlugin, FormDataPlugin, HeadersPlugin, ImageDataPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLPlugin, URLSearchParamsPlugin } from "seroval-plugins/web";
6
+ //#region src/runtime/calls.ts
7
+ /**
8
+ * Client functions that the server passes on, such as function props, with
9
+ * their references. Kept under a symbol of the registry, so two copies of the
10
+ * runtime, such as a component's and the render context's, share it.
11
+ */
12
+ const functionReferences = globalThis[Symbol.for("brumate.functionReferences")] ??= /* @__PURE__ */ new WeakMap();
13
+ /**
14
+ * True for a file or a blob. One from another frame, or another DOM, is an
15
+ * instance of another `Blob` class, so its methods tell instead.
16
+ */
17
+ function isBlob(value) {
18
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
19
+ const blob = value;
20
+ return typeof blob === "object" && blob !== null && typeof blob.size === "number" && typeof blob.type === "string" && typeof blob.arrayBuffer === "function" && typeof blob.slice === "function";
21
+ }
22
+ //#endregion
23
+ //#region src/runtime/serial.ts
24
+ /**
25
+ * Returns the parse functions of a plugin. `read` returns the values of the
26
+ * node by key, and each mode parses them in that order, so the nodes match.
27
+ */
28
+ function parsers(read) {
29
+ const parse = (value, ctx) => {
30
+ const node = read(value);
31
+ for (const key in node) node[key] = ctx.parse(node[key]);
32
+ return node;
33
+ };
34
+ return {
35
+ sync: parse,
36
+ stream: parse,
37
+ async: async (value, ctx) => {
38
+ const node = read(value);
39
+ for (const key in node) node[key] = await ctx.parse(node[key]);
40
+ return node;
41
+ }
42
+ };
43
+ }
44
+ const ElementPlugin = createPlugin({
45
+ tag: "brumate/element",
46
+ skipPlainObjects: true,
47
+ test: (value) => value instanceof ElementReference,
48
+ parse: parsers((value) => ({
49
+ a: value.scope,
50
+ b: value.anchor
51
+ })),
52
+ serialize: (node, ctx) => `$b.e(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,
53
+ deserialize: (node, ctx) => stateValues.e(ctx.deserialize(node.a), ctx.deserialize(node.b))
54
+ });
55
+ const SlotPlugin = createPlugin({
56
+ tag: "brumate/slot",
57
+ skipPlainObjects: true,
58
+ test: (value) => isSlotReference(value),
59
+ parse: parsers((value) => ({
60
+ a: value.scope,
61
+ b: value.slot
62
+ })),
63
+ serialize: (node, ctx) => `$b.l(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,
64
+ deserialize: (node, ctx) => stateValues.l(ctx.deserialize(node.a), ctx.deserialize(node.b))
65
+ });
66
+ /** A binding that a rest prop holds: its value, and the scope and the slot it writes. */
67
+ const BindingPlugin = createPlugin({
68
+ tag: "brumate/binding",
69
+ skipPlainObjects: true,
70
+ test: (value) => isBinding(value),
71
+ parse: parsers((value) => {
72
+ const node = {
73
+ a: value.value,
74
+ b: value.ref.scope,
75
+ c: value.ref.slot
76
+ };
77
+ if (value.set !== void 0) node.d = value.set;
78
+ return node;
79
+ }),
80
+ serialize: (node, ctx) => `$b.b(${[
81
+ node.a,
82
+ node.b,
83
+ node.c,
84
+ node.d
85
+ ].filter((part) => part !== void 0).map((part) => ctx.serialize(part)).join(",")})`,
86
+ deserialize: (node, ctx) => stateValues.b(ctx.deserialize(node.a), ctx.deserialize(node.b), ctx.deserialize(node.c), node.d === void 0 ? void 0 : ctx.deserialize(node.d))
87
+ });
88
+ const FunctionPlugin = createPlugin({
89
+ tag: "brumate/function",
90
+ skipPlainObjects: true,
91
+ test: (value) => typeof value === "function" && functionReferences.has(value),
92
+ parse: parsers((value) => {
93
+ const reference = functionReferences.get(value);
94
+ const node = {
95
+ a: reference.ref,
96
+ b: reference.scope
97
+ };
98
+ const modifiers = value[MODIFIERS];
99
+ if (reference.args !== void 0 || modifiers) node.c = reference.args ?? null;
100
+ if (modifiers) node.d = modifiers;
101
+ return node;
102
+ }),
103
+ serialize: (node, ctx) => `$b.f(${[
104
+ node.a,
105
+ node.b,
106
+ node.c,
107
+ node.d
108
+ ].filter((part) => part !== void 0).map((part) => ctx.serialize(part)).join(",")})`,
109
+ deserialize: (node, ctx) => stateValues.f(ctx.deserialize(node.a), ctx.deserialize(node.b), node.c === void 0 ? void 0 : ctx.deserialize(node.c), node.d === void 0 ? void 0 : ctx.deserialize(node.d))
110
+ });
111
+ /** HTML, such as the `children` of a component, so the client can insert it again. */
112
+ const RawPlugin = createPlugin({
113
+ tag: "brumate/raw",
114
+ skipPlainObjects: true,
115
+ test: isRaw,
116
+ parse: parsers((value) => ({ h: rawHTML(value) })),
117
+ serialize: (node, ctx) => `$b.r(${ctx.serialize(node.h)})`,
118
+ deserialize: (node, ctx) => stateValues.r(ctx.deserialize(node.h))
119
+ });
120
+ /** A component in the page state, such as the value of a dynamic tag. See `stateValues.c`. */
121
+ const ComponentPlugin = createPlugin({
122
+ tag: "brumate/component",
123
+ skipPlainObjects: true,
124
+ test: (value) => typeof value === "function" && typeof value.brumateId === "string",
125
+ parse: parsers((value) => ({ c: value.brumateId })),
126
+ serialize: (node, ctx) => `$b.c(${ctx.serialize(node.c)})`,
127
+ deserialize: (node, ctx) => stateValues.c(ctx.deserialize(node.c))
128
+ });
129
+ /**
130
+ * Files and blobs, which go only in the arguments of a call, as parts of
131
+ * multipart form data named `file<index>`. The node holds the index. The
132
+ * call passes `sent`, which gets each blob, and the server passes the form
133
+ * that it `received`, whose files the indexes read. Without them, as in the
134
+ * page state and in the answer of a call, a blob throws.
135
+ */
136
+ function uploadPlugin(sent, received) {
137
+ return createPlugin({
138
+ tag: "brumate/upload",
139
+ skipPlainObjects: true,
140
+ test: isBlob,
141
+ parse: parsers((value) => {
142
+ if (!sent) throw new Error("A file or a blob can only be sent in the arguments of a server function");
143
+ return { i: sent.push(value) - 1 };
144
+ }),
145
+ serialize: () => {
146
+ throw new Error("A file or a blob can only be sent in the arguments of a server function");
147
+ },
148
+ deserialize: (node, ctx) => {
149
+ const file = received?.get(`file${ctx.deserialize(node.i)}`);
150
+ if (!(file instanceof Blob)) throw new TypeError("A file of the call is missing");
151
+ return file;
152
+ }
153
+ });
154
+ }
155
+ /**
156
+ * The plugin of `AbortSignal` from seroval-plugins, which sends whether the
157
+ * signal aborted and its reason. The one of seroval-plugins waits for a live
158
+ * signal to abort, so a call with one would not be sent, and a page or an
159
+ * answer with one would not end.
160
+ */
161
+ const SignalPlugin = {
162
+ ...AbortSignalPlugin,
163
+ parse: {
164
+ sync: AbortSignalPlugin.parse.sync,
165
+ stream: AbortSignalPlugin.parse.sync,
166
+ async: async (value, ctx) => value.aborted ? { reason: await ctx.parse(value.reason) } : {}
167
+ }
168
+ };
169
+ /**
170
+ * The plugin of `Request` from seroval-plugins, whose body streams in the
171
+ * stream mode. A request with a stream body needs `duplex: 'half'`, or its
172
+ * constructor throws, so the plugin adds it.
173
+ */
174
+ const BodyRequestPlugin = {
175
+ ...RequestPlugin,
176
+ serialize: (node, ctx) => `new Request(${ctx.serialize(node.url)},Object.assign(${ctx.serialize(node.options)},{duplex:"half"}))`,
177
+ deserialize: (node, ctx) => new Request(ctx.deserialize(node.url), {
178
+ ...ctx.deserialize(node.options),
179
+ duplex: "half"
180
+ })
181
+ };
182
+ /** The plugins after the plugin of uploads, which a call makes for its files. */
183
+ const valuePlugins = [
184
+ ElementPlugin,
185
+ SlotPlugin,
186
+ BindingPlugin,
187
+ FunctionPlugin,
188
+ RawPlugin,
189
+ ComponentPlugin,
190
+ SignalPlugin,
191
+ CustomEventPlugin,
192
+ DOMExceptionPlugin,
193
+ EventPlugin,
194
+ FormDataPlugin,
195
+ HeadersPlugin,
196
+ ImageDataPlugin,
197
+ ReadableStreamPlugin,
198
+ BodyRequestPlugin,
199
+ ResponsePlugin,
200
+ URLPlugin,
201
+ URLSearchParamsPlugin
202
+ ];
203
+ /**
204
+ * The plugins of a call with files: `sent` gets the files that the call
205
+ * sends, and `received` is the form that the server got them in.
206
+ */
207
+ function callPlugins(sent, received) {
208
+ return [uploadPlugin(sent, received), ...valuePlugins];
209
+ }
210
+ /** The plugins of the page state, of answers and of calls without files. */
211
+ const plugins = callPlugins();
212
+ /**
213
+ * The plugins for the sync modes, which must throw for a value that only
214
+ * streams, so the page state streams instead, and a call with a stream in
215
+ * its arguments is not shared with another. The guard comes first, so it
216
+ * takes a `ReadableStream` before the plugin of `ReadableStream`, which the
217
+ * plugins of `Request` and `Response` bring in.
218
+ */
219
+ const syncPlugins = [createPlugin({
220
+ tag: "brumate/stream-guard",
221
+ test: (value) => typeof ReadableStream !== "undefined" && value instanceof ReadableStream || typeof value === "object" && value !== null && Symbol.asyncIterator in value,
222
+ parse: { sync: () => {
223
+ throw new Error("A stream needs the async or stream mode");
224
+ } },
225
+ serialize: () => "",
226
+ deserialize: () => ({})
227
+ }), ...plugins];
228
+ /**
229
+ * The seroval plugin of a plugin of the app. The page state writes its value
230
+ * as `$b.u(tag, data)`, so the record does not need the class in scope.
231
+ */
232
+ function appPlugin(plugin) {
233
+ return createPlugin({
234
+ tag: `app:${plugin.tag}`,
235
+ test: plugin.test,
236
+ parse: parsers((value) => ({ d: plugin.toData(value) })),
237
+ serialize: (node, ctx) => `$b.u(${JSON.stringify(plugin.tag)},${ctx.serialize(node.d)})`,
238
+ deserialize: (node, ctx) => plugin.fromData(ctx.deserialize(node.d))
239
+ });
240
+ }
241
+ onValuePlugin((plugin) => {
242
+ const added = appPlugin(plugin);
243
+ valuePlugins.unshift(added);
244
+ plugins.splice(1, 0, added);
245
+ syncPlugins.splice(2, 0, added);
246
+ });
247
+ /**
248
+ * Features that are off in both directions:
249
+ *
250
+ * - Errors keep their name and message only. A stack trace would show the
251
+ * server's files and code to the browser.
252
+ * - Regular expressions are not sent. A pattern from a client could take
253
+ * the server a long time to match, and reading one is refused as well.
254
+ */
255
+ const BRUMATE_DISABLED = Feature.ErrorPrototypeStack | Feature.RegExp;
256
+ let disabledFeatures = BRUMATE_DISABLED;
257
+ let depthLimit;
258
+ /** The options of every call of seroval: the features that are off, and the depth limit of the entry. */
259
+ function serialOptions() {
260
+ return depthLimit === void 0 ? { disabledFeatures } : {
261
+ disabledFeatures,
262
+ depthLimit
263
+ };
264
+ }
265
+ onSerialOptions((options) => {
266
+ disabledFeatures = options.disabledFeatures ?? BRUMATE_DISABLED;
267
+ depthLimit = options.depthLimit;
268
+ const enabled = BRUMATE_DISABLED & ~disabledFeatures;
269
+ if (enabled !== 0) console.warn(`The serial entry turns on ${enabled & Feature.RegExp ? "RegExp" : "ErrorPrototypeStack"}, which brumate turns off: ${enabled & Feature.RegExp ? "a pattern from a client can take the server a long time to match" : "a stack shows the files and code of the server to the browser"}.`);
270
+ });
271
+ //#endregion
272
+ //#region src/runtime/stream.ts
273
+ const HEADER_SIZE = 12;
274
+ const encoder = new TextEncoder();
275
+ const decoder = new TextDecoder();
276
+ /** The content type of a stream of chunks. */
277
+ const STREAM_TYPE = "application/x-brumate-stream";
278
+ /** One chunk: its header and its data, in one array. */
279
+ function chunk(text) {
280
+ const data = encoder.encode(text);
281
+ const result = new Uint8Array(HEADER_SIZE + data.length);
282
+ encoder.encodeInto(`;0x${data.length.toString(16).padStart(8, "0")};`, result);
283
+ result.set(data, HEADER_SIZE);
284
+ return result;
285
+ }
286
+ /** Serializes a value as a stream of chunks. */
287
+ function toChunkStream(value, onCancel) {
288
+ let cancelled = false;
289
+ return new ReadableStream({
290
+ start(controller) {
291
+ toCrossJSONStream(value, {
292
+ refs: /* @__PURE__ */ new Map(),
293
+ plugins,
294
+ ...serialOptions(),
295
+ onParse(node) {
296
+ if (!cancelled) controller.enqueue(chunk(JSON.stringify(node)));
297
+ },
298
+ onDone() {
299
+ if (!cancelled) controller.close();
300
+ },
301
+ onError(error) {
302
+ if (!cancelled) controller.error(error);
303
+ }
304
+ });
305
+ },
306
+ cancel(reason) {
307
+ cancelled = true;
308
+ onCancel?.(reason);
309
+ }
310
+ });
311
+ }
312
+ /** Reads chunks of a stream, buffering only the bytes of the chunk it waits for. */
313
+ var ChunkReader = class {
314
+ reader;
315
+ pieces = [];
316
+ length = 0;
317
+ done = false;
318
+ constructor(stream) {
319
+ this.reader = stream.getReader();
320
+ }
321
+ async fill(size) {
322
+ while (this.length < size && !this.done) {
323
+ const piece = await this.reader.read();
324
+ if (piece.done) this.done = true;
325
+ else {
326
+ this.pieces.push(piece.value);
327
+ this.length += piece.value.length;
328
+ }
329
+ }
330
+ }
331
+ take(size) {
332
+ const result = new Uint8Array(size);
333
+ let offset = 0;
334
+ while (offset < size) {
335
+ const piece = this.pieces[0];
336
+ const count = Math.min(piece.length, size - offset);
337
+ result.set(piece.subarray(0, count), offset);
338
+ offset += count;
339
+ if (count === piece.length) this.pieces.shift();
340
+ else this.pieces[0] = piece.subarray(count);
341
+ }
342
+ this.length -= size;
343
+ return result;
344
+ }
345
+ /** The data of the next chunk, or undefined at the end of the stream. */
346
+ async next() {
347
+ await this.fill(HEADER_SIZE);
348
+ if (this.length === 0) return;
349
+ const head = this.length < HEADER_SIZE ? "" : decoder.decode(this.take(HEADER_SIZE));
350
+ const match = /^;0x([0-9a-f]{8});$/.exec(head);
351
+ if (!match) throw new Error("The answer of a server function is not a stream of chunks");
352
+ const size = Number.parseInt(match[1], 16);
353
+ await this.fill(size);
354
+ if (this.length < size) throw new Error("The answer of a server function ended in the middle of a chunk");
355
+ return decoder.decode(this.take(size));
356
+ }
357
+ cancel(reason) {
358
+ this.done = true;
359
+ this.reader.cancel(reason).catch(() => {});
360
+ }
361
+ };
362
+ const ignore = () => {};
363
+ /**
364
+ * The refs of a stream. A promise in the answer can fail with nothing that
365
+ * reads it, such as a field the caller ignores, so its failure is claimed
366
+ * here. Code that awaits it still sees the failure.
367
+ */
368
+ var Refs = class extends Map {
369
+ set(id, value) {
370
+ if (value instanceof Promise) value.catch(ignore);
371
+ return super.set(id, value);
372
+ }
373
+ };
374
+ /**
375
+ * Fails the promises and async iterables that still wait for a chunk, when
376
+ * the stream ends early. Failing a settled one does nothing.
377
+ */
378
+ function failPending(refs, error) {
379
+ for (const value of refs.values()) try {
380
+ if (value instanceof Stream) value.throw(error);
381
+ else if (value !== null && typeof value === "object") {
382
+ const resolver = value;
383
+ if (resolver.p instanceof Promise && typeof resolver.f === "function") {
384
+ resolver.p.catch(ignore);
385
+ resolver.f(error);
386
+ }
387
+ }
388
+ } catch {}
389
+ }
390
+ /**
391
+ * Reads the first chunk of a stream as the value, and the rest in the
392
+ * background, so the promises and async iterables in it settle as their
393
+ * chunks arrive.
394
+ */
395
+ async function fromChunkStream(stream) {
396
+ const reader = new ChunkReader(stream);
397
+ const refs = new Refs();
398
+ const read = (data) => fromCrossJSON(JSON.parse(data), {
399
+ refs,
400
+ plugins,
401
+ ...serialOptions()
402
+ });
403
+ const first = await reader.next();
404
+ if (first === void 0) throw new Error("The answer of a server function is empty");
405
+ const value = read(first);
406
+ (async () => {
407
+ try {
408
+ for (;;) {
409
+ const data = await reader.next();
410
+ if (data === void 0) break;
411
+ read(data);
412
+ }
413
+ failPending(refs, /* @__PURE__ */ new Error("The answer of a server function ended early"));
414
+ } catch (error) {
415
+ reader.cancel(error);
416
+ failPending(refs, error);
417
+ }
418
+ })();
419
+ return value;
420
+ }
421
+ //#endregion
422
+ export { plugins as a, functionReferences as c, callPlugins as i, fromChunkStream as n, serialOptions as o, toChunkStream as r, syncPlugins as s, STREAM_TYPE as t };
423
+
424
+ //# sourceMappingURL=stream-DCYZO4IF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-DCYZO4IF.js","names":[],"sources":["../src/runtime/calls.ts","../src/runtime/serial.ts","../src/runtime/stream.ts"],"sourcesContent":["// Values that only server function calls and their serialization use. They are\n// not in `shared.ts`, which the core imports, so a page's core does not hold them.\n\nimport type { FunctionReference } from './shared.ts';\n\n/**\n * Client functions that the server passes on, such as function props, with\n * their references. Kept under a symbol of the registry, so two copies of the\n * runtime, such as a component's and the render context's, share it.\n */\nexport const functionReferences: WeakMap<object, FunctionReference> = ((\n globalThis as Record<symbol, WeakMap<object, FunctionReference> | undefined>\n)[Symbol.for('brumate.functionReferences')] ??= new WeakMap());\n\n/**\n * True for a file or a blob. One from another frame, or another DOM, is an\n * instance of another `Blob` class, so its methods tell instead.\n */\nexport function isBlob(value: unknown): value is Blob {\n if (typeof Blob !== 'undefined' && value instanceof Blob) {\n return true;\n }\n const blob = value as Partial<Blob> | null;\n return (\n typeof blob === 'object' &&\n blob !== null &&\n typeof blob.size === 'number' &&\n typeof blob.type === 'string' &&\n typeof blob.arrayBuffer === 'function' &&\n typeof blob.slice === 'function'\n );\n}\n","// The seroval plugins of brumate's values. The server writes the page state\n// with them as code, and server function calls as JSON, which both sides\n// read with them. The core does not import this module: a state record\n// is code that makes its values with `stateValues`, so seroval loads in the\n// browser only with the first server function call.\n\nimport { Feature, createPlugin } from 'seroval';\nimport {\n AbortSignalPlugin,\n CustomEventPlugin,\n DOMExceptionPlugin,\n EventPlugin,\n FormDataPlugin,\n HeadersPlugin,\n ImageDataPlugin,\n ReadableStreamPlugin,\n RequestPlugin,\n ResponsePlugin,\n URLPlugin,\n URLSearchParamsPlugin,\n} from 'seroval-plugins/web';\nimport type {\n Plugin,\n SerovalNode,\n StreamParsePluginContext,\n SyncParsePluginContext,\n} from 'seroval';\nimport { isRaw, rawHTML } from './html.ts';\nimport type { Raw } from './html.ts';\nimport { functionReferences, isBlob } from './calls.ts';\nimport { MODIFIERS } from './events.ts';\nimport {\n ElementReference,\n isBinding,\n isSlotReference,\n onSerialOptions,\n onValuePlugin,\n stateValues,\n} from './shared.ts';\nimport type { ValuePlugin } from './values.ts';\nimport type { Binding, SlotReference } from './shared.ts';\nimport type { ComponentValue } from './shared.ts';\n\ntype ReferenceNode = { a: SerovalNode; b: SerovalNode; c?: SerovalNode; d?: SerovalNode };\n\n/**\n * Returns the parse functions of a plugin. `read` returns the values of the\n * node by key, and each mode parses them in that order, so the nodes match.\n */\nfunction parsers<T, K extends string>(\n read: (value: T) => Record<K, unknown>,\n): Plugin<T, Record<K, SerovalNode>>['parse'] {\n type N = Record<K, SerovalNode>;\n const parse = (value: T, ctx: SyncParsePluginContext | StreamParsePluginContext): N => {\n const node = read(value) as Record<string, unknown>;\n for (const key in node) {\n node[key] = ctx.parse(node[key]);\n }\n return node as N;\n };\n return {\n sync: parse,\n stream: parse,\n async: async (value, ctx) => {\n const node = read(value) as Record<string, unknown>;\n for (const key in node) {\n // oxlint-disable-next-line no-await-in-loop -- In order, as the other modes parse, so the IDs match.\n node[key] = await ctx.parse(node[key]);\n }\n return node as N;\n },\n };\n}\n\n// In the page state, each value is a call of `stateValues`, which the code of a record gets as `$b`.\n\n// No plugin here matches a plain object, so each one sets skipPlainObjects and seroval\n// does not run its test on object literals. Raw HTML is a class instance for this reason.\nconst ElementPlugin = createPlugin<ElementReference, ReferenceNode>({\n tag: 'brumate/element',\n skipPlainObjects: true,\n test: (value) => value instanceof ElementReference,\n parse: parsers((value) => ({ a: value.scope, b: value.anchor })),\n serialize: (node, ctx) => `$b.e(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,\n deserialize: (node, ctx) =>\n stateValues.e(ctx.deserialize<number>(node.a), ctx.deserialize<number>(node.b)),\n});\n\nconst SlotPlugin = createPlugin<SlotReference, ReferenceNode>({\n tag: 'brumate/slot',\n skipPlainObjects: true,\n test: (value) => isSlotReference(value),\n parse: parsers((value) => ({ a: value.scope, b: value.slot })),\n serialize: (node, ctx) => `$b.l(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,\n deserialize: (node, ctx) =>\n stateValues.l(ctx.deserialize<number>(node.a), ctx.deserialize<number>(node.b)),\n});\n\n/** A binding that a rest prop holds: its value, and the scope and the slot it writes. */\nconst BindingPlugin = createPlugin<Binding, ReferenceNode>({\n tag: 'brumate/binding',\n skipPlainObjects: true,\n test: (value) => isBinding(value),\n parse: parsers((value) => {\n const node: Record<string, unknown> = { a: value.value, b: value.ref.scope, c: value.ref.slot };\n // The setter of `$bind(name, fn)`.\n if (value.set !== undefined) {\n node.d = value.set;\n }\n return node as Record<'a' | 'b' | 'c' | 'd', unknown>;\n }),\n serialize: (node, ctx) =>\n `$b.b(${[node.a, node.b, node.c, node.d]\n .filter((part) => part !== undefined)\n .map((part) => ctx.serialize(part!))\n .join(',')})`,\n deserialize: (node, ctx) =>\n stateValues.b(\n ctx.deserialize(node.a),\n ctx.deserialize<number>(node.b!),\n ctx.deserialize<number>(node.c!),\n node.d === undefined ? undefined : ctx.deserialize(node.d),\n ),\n});\n\nconst FunctionPlugin = createPlugin<object, ReferenceNode>({\n tag: 'brumate/function',\n skipPlainObjects: true,\n test: (value) => typeof value === 'function' && functionReferences.has(value),\n parse: parsers((value) => {\n const reference = functionReferences.get(value)!;\n // The arguments of a handler that `$handler` made go with it.\n const node: Record<string, unknown> = { a: reference.ref, b: reference.scope };\n // The modifiers of its wrappers, so a spread in markup that the browser renders writes them.\n const modifiers = (value as { [MODIFIERS]?: string[] })[MODIFIERS];\n if (reference.args !== undefined || modifiers) {\n node.c = reference.args ?? null;\n }\n if (modifiers) {\n node.d = modifiers;\n }\n return node as Record<'a' | 'b' | 'c' | 'd', unknown>;\n }),\n serialize: (node, ctx) =>\n `$b.f(${[node.a, node.b, node.c, node.d]\n .filter((part) => part !== undefined)\n .map((part) => ctx.serialize(part!))\n .join(',')})`,\n deserialize: (node, ctx) =>\n stateValues.f(\n ctx.deserialize<string>(node.a),\n ctx.deserialize<number>(node.b),\n node.c === undefined ? undefined : ctx.deserialize<unknown[] | null>(node.c),\n node.d === undefined ? undefined : ctx.deserialize<string[]>(node.d),\n ),\n});\n\n/** HTML, such as the `children` of a component, so the client can insert it again. */\nconst RawPlugin = createPlugin<Raw, { h: SerovalNode }>({\n tag: 'brumate/raw',\n skipPlainObjects: true,\n test: isRaw,\n parse: parsers((value) => ({ h: rawHTML(value) })),\n serialize: (node, ctx) => `$b.r(${ctx.serialize(node.h)})`,\n deserialize: (node, ctx) => stateValues.r(ctx.deserialize<string>(node.h)),\n});\n\n/** A component in the page state, such as the value of a dynamic tag. See `stateValues.c`. */\nconst ComponentPlugin = createPlugin<ComponentValue, { c: SerovalNode }>({\n tag: 'brumate/component',\n skipPlainObjects: true,\n test: (value) =>\n typeof value === 'function' && typeof (value as Partial<ComponentValue>).brumateId === 'string',\n parse: parsers((value) => ({ c: value.brumateId })),\n serialize: (node, ctx) => `$b.c(${ctx.serialize(node.c)})`,\n deserialize: (node, ctx) => stateValues.c(ctx.deserialize<string>(node.c)),\n});\n\n/**\n * Files and blobs, which go only in the arguments of a call, as parts of\n * multipart form data named `file<index>`. The node holds the index. The\n * call passes `sent`, which gets each blob, and the server passes the form\n * that it `received`, whose files the indexes read. Without them, as in the\n * page state and in the answer of a call, a blob throws.\n */\nexport function uploadPlugin(sent?: Blob[], received?: FormData): Plugin<Blob, { i: SerovalNode }> {\n return createPlugin<Blob, { i: SerovalNode }>({\n tag: 'brumate/upload',\n skipPlainObjects: true,\n test: isBlob,\n parse: parsers((value) => {\n if (!sent) {\n throw new Error('A file or a blob can only be sent in the arguments of a server function');\n }\n return { i: sent.push(value) - 1 };\n }),\n serialize: () => {\n throw new Error('A file or a blob can only be sent in the arguments of a server function');\n },\n deserialize: (node, ctx) => {\n const file = received?.get(`file${ctx.deserialize<number>(node.i)}`);\n if (!(file instanceof Blob)) {\n throw new TypeError('A file of the call is missing');\n }\n return file;\n },\n });\n}\n\n/**\n * The plugin of `AbortSignal` from seroval-plugins, which sends whether the\n * signal aborted and its reason. The one of seroval-plugins waits for a live\n * signal to abort, so a call with one would not be sent, and a page or an\n * answer with one would not end.\n */\nconst SignalPlugin: typeof AbortSignalPlugin = {\n ...AbortSignalPlugin,\n parse: {\n sync: AbortSignalPlugin.parse.sync,\n stream: AbortSignalPlugin.parse.sync,\n async: async (value, ctx) => (value.aborted ? { reason: await ctx.parse(value.reason) } : {}),\n },\n};\n\n/**\n * The plugin of `Request` from seroval-plugins, whose body streams in the\n * stream mode. A request with a stream body needs `duplex: 'half'`, or its\n * constructor throws, so the plugin adds it.\n */\nconst BodyRequestPlugin: typeof RequestPlugin = {\n ...RequestPlugin,\n serialize: (node, ctx) =>\n `new Request(${ctx.serialize(node.url)},Object.assign(${ctx.serialize(node.options)},{duplex:\"half\"}))`,\n deserialize: (node, ctx) =>\n new Request(\n ctx.deserialize(node.url) as string,\n {\n ...(ctx.deserialize(node.options) as RequestInit),\n duplex: 'half',\n } as RequestInit,\n ),\n};\n\n/** The plugins after the plugin of uploads, which a call makes for its files. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nconst valuePlugins: Plugin<any, any>[] = [\n ElementPlugin,\n SlotPlugin,\n BindingPlugin,\n FunctionPlugin,\n RawPlugin,\n ComponentPlugin,\n // The web values of seroval-plugins. Requests and responses need the async or stream modes,\n // so a page state or a call result that holds one streams. The plugin of uploads takes files\n // and blobs, so those of seroval-plugins, which would put their bytes in the JSON, are left out.\n SignalPlugin,\n CustomEventPlugin,\n DOMExceptionPlugin,\n EventPlugin,\n FormDataPlugin,\n HeadersPlugin,\n ImageDataPlugin,\n ReadableStreamPlugin,\n BodyRequestPlugin,\n ResponsePlugin,\n URLPlugin,\n URLSearchParamsPlugin,\n];\n\n/**\n * The plugins of a call with files: `sent` gets the files that the call\n * sends, and `received` is the form that the server got them in.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport function callPlugins(sent?: Blob[], received?: FormData): Plugin<any, any>[] {\n return [uploadPlugin(sent, received), ...valuePlugins];\n}\n\n/** The plugins of the page state, of answers and of calls without files. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport const plugins: Plugin<any, any>[] = callPlugins();\n\n/**\n * Stops a sync mode at a value that only streams: an async iterable, such\n * as a `ReadableStream`. seroval writes one in a sync mode as a stream that\n * never gets its values, without an error.\n */\nconst StreamGuardPlugin = createPlugin<object, Record<string, never>>({\n tag: 'brumate/stream-guard',\n test: (value) =>\n (typeof ReadableStream !== 'undefined' && value instanceof ReadableStream) ||\n (typeof value === 'object' && value !== null && Symbol.asyncIterator in value),\n parse: {\n sync: () => {\n throw new Error('A stream needs the async or stream mode');\n },\n },\n serialize: () => '',\n deserialize: () => ({}),\n});\n\n/**\n * The plugins for the sync modes, which must throw for a value that only\n * streams, so the page state streams instead, and a call with a stream in\n * its arguments is not shared with another. The guard comes first, so it\n * takes a `ReadableStream` before the plugin of `ReadableStream`, which the\n * plugins of `Request` and `Response` bring in.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport const syncPlugins: Plugin<any, any>[] = [StreamGuardPlugin, ...plugins];\n\n/**\n * The seroval plugin of a plugin of the app. The page state writes its value\n * as `$b.u(tag, data)`, so the record does not need the class in scope.\n */\nfunction appPlugin(plugin: ValuePlugin): Plugin<unknown, { d: SerovalNode }> {\n return createPlugin<unknown, { d: SerovalNode }>({\n tag: `app:${plugin.tag}`,\n test: plugin.test,\n parse: parsers((value) => ({ d: plugin.toData(value) })),\n serialize: (node, ctx) => `$b.u(${JSON.stringify(plugin.tag)},${ctx.serialize(node.d)})`,\n deserialize: (node, ctx) => plugin.fromData(ctx.deserialize(node.d)),\n });\n}\n\n// The plugins of the app come before brumate's, in each list, as the entry adds them. The\n// plugin of uploads stays first in a call, and the guard of streams first in the sync modes.\nonValuePlugin((plugin) => {\n const added = appPlugin(plugin);\n valuePlugins.unshift(added);\n plugins.splice(1, 0, added);\n syncPlugins.splice(2, 0, added);\n});\n\n/**\n * Features that are off in both directions:\n *\n * - Errors keep their name and message only. A stack trace would show the\n * server's files and code to the browser.\n * - Regular expressions are not sent. A pattern from a client could take\n * the server a long time to match, and reading one is refused as well.\n */\nconst BRUMATE_DISABLED = Feature.ErrorPrototypeStack | Feature.RegExp;\n\nexport let disabledFeatures: number = BRUMATE_DISABLED;\nlet depthLimit: number | undefined;\n\n/** The options of every call of seroval: the features that are off, and the depth limit of the entry. */\nexport function serialOptions(): { disabledFeatures: number; depthLimit?: number } {\n return depthLimit === undefined ? { disabledFeatures } : { disabledFeatures, depthLimit };\n}\n\nonSerialOptions((options) => {\n disabledFeatures = options.disabledFeatures ?? BRUMATE_DISABLED;\n depthLimit = options.depthLimit;\n // oxlint-disable-next-line no-bitwise -- The features are flags.\n const enabled = BRUMATE_DISABLED & ~disabledFeatures;\n if (enabled !== 0) {\n console.warn(\n `The serial entry turns on ${enabled & Feature.RegExp ? 'RegExp' : 'ErrorPrototypeStack'}, which brumate turns off: ${enabled & Feature.RegExp ? 'a pattern from a client can take the server a long time to match' : 'a stack shows the files and code of the server to the browser'}.`,\n );\n }\n});\n","// The answer of a server function, as a stream of seroval chunks. Promises\n// and async iterables in the answer settle as their chunks arrive.\n//\n// Each chunk is a 12-byte header with the size of its data in bytes, as 8\n// hex digits, and the data: `;0x0000001f;{...}`. The reader knows how many\n// bytes to wait for, and can refuse a chunk that is too large.\n\nimport { Stream, fromCrossJSON, toCrossJSONStream } from 'seroval';\nimport type { SerovalNode } from 'seroval';\nimport { serialOptions, plugins } from './serial.ts';\n\nconst HEADER_SIZE = 12;\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/** The content type of a stream of chunks. */\nexport const STREAM_TYPE = 'application/x-brumate-stream';\n\n/** One chunk: its header and its data, in one array. */\nfunction chunk(text: string): Uint8Array {\n const data = encoder.encode(text);\n const result = new Uint8Array(HEADER_SIZE + data.length);\n encoder.encodeInto(`;0x${data.length.toString(16).padStart(8, '0')};`, result);\n result.set(data, HEADER_SIZE);\n return result;\n}\n\n/** Serializes a value as a stream of chunks. */\nexport function toChunkStream(\n value: unknown,\n onCancel?: (reason: unknown) => void,\n): ReadableStream<Uint8Array> {\n let cancelled = false;\n return new ReadableStream({\n start(controller) {\n toCrossJSONStream(value, {\n refs: new Map(),\n plugins,\n ...serialOptions(),\n onParse(node) {\n if (!cancelled) {\n controller.enqueue(chunk(JSON.stringify(node)));\n }\n },\n onDone() {\n if (!cancelled) {\n controller.close();\n }\n },\n onError(error) {\n if (!cancelled) {\n controller.error(error);\n }\n },\n });\n },\n // The reader went away, such as a browser that aborted the call.\n cancel(reason) {\n cancelled = true;\n onCancel?.(reason);\n },\n });\n}\n\n/** Reads chunks of a stream, buffering only the bytes of the chunk it waits for. */\nclass ChunkReader {\n private readonly reader: ReadableStreamDefaultReader<Uint8Array>;\n private pieces: Uint8Array[] = [];\n private length = 0;\n private done = false;\n\n constructor(stream: ReadableStream<Uint8Array>) {\n this.reader = stream.getReader();\n }\n\n private async fill(size: number): Promise<void> {\n while (this.length < size && !this.done) {\n // oxlint-disable-next-line no-await-in-loop -- Pieces arrive in order.\n const piece = await this.reader.read();\n if (piece.done) {\n this.done = true;\n } else {\n this.pieces.push(piece.value);\n this.length += piece.value.length;\n }\n }\n }\n\n private take(size: number): Uint8Array {\n const result = new Uint8Array(size);\n let offset = 0;\n while (offset < size) {\n const piece = this.pieces[0]!;\n const count = Math.min(piece.length, size - offset);\n result.set(piece.subarray(0, count), offset);\n offset += count;\n if (count === piece.length) {\n this.pieces.shift();\n } else {\n this.pieces[0] = piece.subarray(count);\n }\n }\n this.length -= size;\n return result;\n }\n\n /** The data of the next chunk, or undefined at the end of the stream. */\n async next(): Promise<string | undefined> {\n await this.fill(HEADER_SIZE);\n if (this.length === 0) {\n return undefined;\n }\n const head = this.length < HEADER_SIZE ? '' : decoder.decode(this.take(HEADER_SIZE));\n const match = /^;0x([0-9a-f]{8});$/.exec(head);\n if (!match) {\n throw new Error('The answer of a server function is not a stream of chunks');\n }\n const size = Number.parseInt(match[1]!, 16);\n await this.fill(size);\n if (this.length < size) {\n throw new Error('The answer of a server function ended in the middle of a chunk');\n }\n return decoder.decode(this.take(size));\n }\n\n cancel(reason: unknown): void {\n this.done = true;\n void this.reader.cancel(reason).catch(() => {});\n }\n}\n\nconst ignore = (): void => {};\n\n/**\n * The refs of a stream. A promise in the answer can fail with nothing that\n * reads it, such as a field the caller ignores, so its failure is claimed\n * here. Code that awaits it still sees the failure.\n */\nclass Refs extends Map<number, unknown> {\n override set(id: number, value: unknown): this {\n if (value instanceof Promise) {\n value.catch(ignore);\n }\n return super.set(id, value);\n }\n}\n\n/**\n * Fails the promises and async iterables that still wait for a chunk, when\n * the stream ends early. Failing a settled one does nothing.\n */\nfunction failPending(refs: Refs, error: unknown): void {\n for (const value of refs.values()) {\n try {\n // The deserializer makes a Stream. A LiveStream comes only from user code, and its producer fails it.\n if (value instanceof Stream) {\n value.throw(error);\n } else if (value !== null && typeof value === 'object') {\n const resolver = value as { p?: unknown; f?: unknown };\n if (resolver.p instanceof Promise && typeof resolver.f === 'function') {\n resolver.p.catch(ignore);\n (resolver.f as (error: unknown) => void)(error);\n }\n }\n } catch {\n // A value that a plugin made, which has no such methods.\n }\n }\n}\n\n/**\n * Reads the first chunk of a stream as the value, and the rest in the\n * background, so the promises and async iterables in it settle as their\n * chunks arrive.\n */\nexport async function fromChunkStream(stream: ReadableStream<Uint8Array>): Promise<unknown> {\n const reader = new ChunkReader(stream);\n const refs = new Refs();\n const read = (data: string): unknown =>\n fromCrossJSON(JSON.parse(data) as SerovalNode, { refs, plugins, ...serialOptions() });\n const first = await reader.next();\n if (first === undefined) {\n throw new Error('The answer of a server function is empty');\n }\n const value = read(first);\n void (async () => {\n try {\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n const data = await reader.next();\n if (data === undefined) {\n break;\n }\n read(data);\n }\n failPending(refs, new Error('The answer of a server function ended early'));\n } catch (error) {\n reader.cancel(error);\n failPending(refs, error);\n }\n })();\n return value;\n}\n"],"mappings":";;;;;;;;;;;AAUA,MAAa,qBAA0D,WAErE,OAAO,IAAI,4BAA4B,uBAAO,IAAI,QAAQ;;;;;AAM5D,SAAgB,OAAO,OAA+B;CACpD,IAAI,OAAO,SAAS,eAAe,iBAAiB,MAClD,OAAO;CAET,MAAM,OAAO;CACb,OACE,OAAO,SAAS,YAChB,SAAS,QACT,OAAO,KAAK,SAAS,YACrB,OAAO,KAAK,SAAS,YACrB,OAAO,KAAK,gBAAgB,cAC5B,OAAO,KAAK,UAAU;AAE1B;;;;;;;ACkBA,SAAS,QACP,MAC4C;CAE5C,MAAM,SAAS,OAAU,QAA8D;EACrF,MAAM,OAAO,KAAK,KAAK;EACvB,KAAK,MAAM,OAAO,MAChB,KAAK,OAAO,IAAI,MAAM,KAAK,IAAI;EAEjC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AC5E,SAAS,OAAO;GACd,OAAO,OAAO,KAAK;GACnB,YAAY,MAAM,KAAK;EACzB;CACF,EAAA,CAAG;CACH,OAAO;AACT"}
@@ -0,0 +1,63 @@
1
+ //#region src/runtime/values.d.ts
2
+ /**
3
+ * How a value of the app becomes data that brumate can send, and back.
4
+ * `data` can hold anything that brumate sends, such as numbers, strings,
5
+ * arrays, plain objects and dates.
6
+ */
7
+ interface ValuePlugin<T = any, D = any> {
8
+ /** A name of the plugin that no other plugin has, such as `app/money`. */
9
+ tag: string;
10
+ /** True for a value of the plugin, such as `value instanceof Money`. */
11
+ test: (value: unknown) => boolean;
12
+ /** The data of a value, such as `[money.amount, money.currency]`. */
13
+ toData: (value: T) => D;
14
+ /** Makes the value again from its data, in the browser or on the server. */
15
+ fromData: (data: D) => T;
16
+ }
17
+ /**
18
+ * Makes a plugin for a value of the app. Export it from the entry,
19
+ * `src/serial.ts`, in `plugins`:
20
+ *
21
+ * ```ts
22
+ * export const plugins = [
23
+ * definePlugin({
24
+ * tag: 'app/money',
25
+ * test: (value) => value instanceof Money,
26
+ * toData: (money: Money) => [money.amount, money.currency],
27
+ * fromData: ([amount, currency]) => new Money(amount, currency),
28
+ * }),
29
+ * ];
30
+ * ```
31
+ */
32
+ declare function definePlugin<T, D>(plugin: ValuePlugin<T, D>): ValuePlugin<T, D>;
33
+ /** The exports of the serial entry, `src/serial.ts`. Each is optional. */
34
+ interface SerialEntry {
35
+ /** Plugins for values of the app, which `definePlugin` makes. */
36
+ plugins?: readonly ValuePlugin[];
37
+ /**
38
+ * The features of seroval that are off, as its `Feature` flags. Brumate
39
+ * turns off `ErrorPrototypeStack` and `RegExp`, and warns when the entry
40
+ * turns one of them on.
41
+ */
42
+ disabledFeatures?: number;
43
+ /** How deep a value can be. Deeper values throw instead of being sent. */
44
+ depthLimit?: number;
45
+ }
46
+ /**
47
+ * The values that plugins of the app send, for the type checker. Add each
48
+ * class to it, so a signal or memo can hold one:
49
+ *
50
+ * ```ts
51
+ * declare module 'brumate/serial' {
52
+ * interface SendableValues {
53
+ * money: Money;
54
+ * }
55
+ * }
56
+ * ```
57
+ */
58
+ interface SendableValues {}
59
+ /** A value that a plugin of the app sends. */
60
+ type AppValue = SendableValues[keyof SendableValues];
61
+ //#endregion
62
+ export { definePlugin as a, ValuePlugin as i, SendableValues as n, SerialEntry as r, AppValue as t };
63
+ //# sourceMappingURL=values-B8C7CLvG.d.ts.map
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as NavigateOptions } from "./boot-DN1ZU8Hg.js";
1
+ import { n as NavigateOptions } from "./boot-C25Sa6vq.js";
2
2
  import { Plugin, ViteDevServer } from "vite";
3
3
  //#region src/report.d.ts
4
4
  /** Sizes in bytes, after gzip. */
@@ -7,6 +7,10 @@ interface Budget {
7
7
  loader?: number;
8
8
  /** The most that a route can load after its first event, with the core. */
9
9
  route?: number;
10
+ /** What the first run of one handler loads: the component's entry, its part and the updates it runs, with what they import. */
11
+ event?: number;
12
+ /** The client code of one component. */
13
+ component?: number;
10
14
  }
11
15
  interface BuildReport {
12
16
  /** The entry and its imports, which every page loads. */
@@ -24,6 +28,12 @@ interface BuildReport {
24
28
  bytes: number;
25
29
  components: number;
26
30
  }[];
31
+ /** Each handler, with what its first run loads besides the loader and the core, largest first. */
32
+ events: {
33
+ file: string;
34
+ label: string;
35
+ bytes: number;
36
+ }[];
27
37
  /** The sizes that go over the budget, as sentences. */
28
38
  overBudget: string[];
29
39
  }
@@ -90,6 +100,27 @@ export interface BrumateOptions {
90
100
  exclude?: (directory: string) => boolean;
91
101
  /** The directory of route files, relative to the root. Defaults to `src/routes`. */
92
102
  routes?: string;
103
+ /**
104
+ * The entry middleware, relative to the root. Its default export runs for
105
+ * every request: pages, endpoints, server function calls, form posts and
106
+ * `#defer` bodies. Defaults to `src/middleware.ts` when the file exists.
107
+ * `false` runs none.
108
+ */
109
+ middleware?: string | false;
110
+ /**
111
+ * The serial entry, relative to the root. It exports `plugins` for values
112
+ * of the app, such as a class, and the options of the serializer that it
113
+ * changes. The server and the browser load it. Defaults to `src/serial.ts`
114
+ * when the file exists. `false` uses none.
115
+ */
116
+ serial?: string | false;
117
+ /**
118
+ * The file of environment variables, relative to the root, which calls
119
+ * `defineEnv` from `brumate/env`. The server checks them when it starts,
120
+ * and the browser gets the file without the server variables. Defaults
121
+ * to `src/env.ts` when the file exists. `false` uses none.
122
+ */
123
+ env?: string | false;
93
124
  /**
94
125
  * The declaration file that gives `href` of `brumate/routes` the paths of
95
126
  * the routes, relative to the root. The plugin writes it when the routes
@@ -122,6 +153,23 @@ export interface BrumateOptions {
122
153
  * the pages that its links lead to.
123
154
  */
124
155
  prerender?: boolean | PrerenderOptions;
156
+ /**
157
+ * Skew protection: a page that was open before a deploy keeps working.
158
+ * Each build has an ID, which the page carries and sends with its calls.
159
+ * A call to a function that is gone, or a page of another build, makes
160
+ * the browser load the page in full. The client build writes its ID to
161
+ * `.brumate/build.json`, and the server build reads it, so build the
162
+ * client first. `BRUMATE_BUILD` in the environment names the ID for both.
163
+ *
164
+ * `keep` is how many earlier builds keep their files in the client
165
+ * output, so a page that is open still finds the code of its handlers
166
+ * after a deploy. The build then does not empty the output directory, and
167
+ * removes the files of older builds itself. Defaults to 0, which empties
168
+ * it as Vite does.
169
+ */
170
+ skew?: {
171
+ keep?: number;
172
+ };
125
173
  /**
126
174
  * Prints what the client build ships: what every page loads before its
127
175
  * first event, the core, the most that each route can load, and each