@solidjs/web 2.0.0-beta.3 → 2.0.0-beta.30

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 (73) hide show
  1. package/README.md +27 -4
  2. package/dist/dev.cjs +1211 -205
  3. package/dist/dev.js +1175 -199
  4. package/dist/server.cjs +1342 -234
  5. package/dist/server.js +1304 -231
  6. package/dist/web.cjs +1195 -196
  7. package/dist/web.js +1159 -190
  8. package/frames/dist/client.cjs +1746 -0
  9. package/frames/dist/client.dev.cjs +1759 -0
  10. package/frames/dist/client.dev.js +1747 -0
  11. package/frames/dist/client.js +1734 -0
  12. package/frames/dist/server.cjs +2426 -0
  13. package/frames/dist/server.js +2414 -0
  14. package/frames/package.json +30 -0
  15. package/package.json +287 -38
  16. package/serialization/dist/serialization.cjs +169 -0
  17. package/serialization/dist/serialization.js +159 -0
  18. package/serialization/package.json +20 -0
  19. package/serialization/types/index.d.ts +157 -0
  20. package/serialization/types-cjs/index.d.cts +157 -0
  21. package/serialization/types-cjs/package.json +3 -0
  22. package/server-functions/dist/client.cjs +613 -0
  23. package/server-functions/dist/client.js +585 -0
  24. package/server-functions/dist/server.cjs +904 -0
  25. package/server-functions/dist/server.js +875 -0
  26. package/server-functions/package.json +30 -0
  27. package/storage/package.json +8 -3
  28. package/storage/types/index.d.ts +26 -0
  29. package/storage/types-cjs/index.d.cts +28 -0
  30. package/storage/types-cjs/package.json +3 -0
  31. package/types/client.d.ts +125 -21
  32. package/types/core.d.ts +4 -3
  33. package/types/frames/client.d.ts +20 -0
  34. package/types/frames/frame-client.d.ts +270 -0
  35. package/types/frames/frame-sink.d.ts +168 -0
  36. package/types/frames/frame-transport.d.ts +196 -0
  37. package/types/frames/serializer.d.ts +157 -0
  38. package/types/frames/server.d.ts +30 -0
  39. package/types/index.d.ts +211 -26
  40. package/types/jsx-properties.d.ts +93 -0
  41. package/types/jsx.d.ts +4150 -1
  42. package/types/response.d.ts +129 -0
  43. package/types/serializer.d.ts +157 -0
  44. package/types/server-functions/client.d.ts +200 -0
  45. package/types/server-functions/flash.d.ts +38 -0
  46. package/types/server-functions/server.d.ts +490 -0
  47. package/types/server-functions/shared.d.ts +445 -0
  48. package/types/server-mock.d.ts +93 -0
  49. package/types/server.d.ts +221 -28
  50. package/types-cjs/client.d.cts +192 -0
  51. package/types-cjs/core.d.cts +4 -0
  52. package/types-cjs/frames/client.d.cts +20 -0
  53. package/types-cjs/frames/frame-client.d.cts +270 -0
  54. package/types-cjs/frames/frame-sink.d.cts +168 -0
  55. package/types-cjs/frames/frame-transport.d.cts +196 -0
  56. package/types-cjs/frames/serializer.d.cts +157 -0
  57. package/types-cjs/frames/server.d.cts +30 -0
  58. package/types-cjs/index.d.cts +231 -0
  59. package/types-cjs/jsx-properties.d.cts +93 -0
  60. package/types-cjs/jsx.d.cts +4150 -0
  61. package/types-cjs/package.json +3 -0
  62. package/types-cjs/response.d.cts +129 -0
  63. package/types-cjs/serializer.d.cts +157 -0
  64. package/types-cjs/server-functions/client.d.cts +200 -0
  65. package/types-cjs/server-functions/flash.d.cts +38 -0
  66. package/types-cjs/server-functions/server.d.cts +490 -0
  67. package/types-cjs/server-functions/shared.d.cts +445 -0
  68. package/types-cjs/server-mock.d.cts +165 -0
  69. package/types-cjs/server.d.cts +349 -0
  70. package/storage/types/src/client.d.ts +0 -1
  71. package/storage/types/src/index.d.ts +0 -46
  72. package/storage/types/src/server-mock.d.ts +0 -72
  73. package/storage/types/storage/src/index.d.ts +0 -2
@@ -0,0 +1,2426 @@
1
+ 'use strict';
2
+
3
+ var solidJs = require('solid-js');
4
+ var seroval = require('seroval');
5
+ var web = require('seroval-plugins/web');
6
+
7
+ const runWithHydrationScope = (id, fn) => solidJs.runWithOwner(solidJs.createOwner({
8
+ id
9
+ }), fn);
10
+
11
+ const DEFAULT_DISABLED_FEATURES = seroval.Feature.AggregateError | seroval.Feature.BigIntTypedArray;
12
+ const serializeOnlyDisabledFeatures = () => process.env.NODE_ENV === "development" ? 0 : seroval.Feature.ErrorPrototypeStack;
13
+ const HYDRATION_GLOBAL = "_$HY.r";
14
+ const DEFAULT_WEB_PLUGINS = Object.freeze([web.AbortSignalPlugin,
15
+ web.CustomEventPlugin, web.DOMExceptionPlugin, web.EventPlugin,
16
+ web.FormDataPlugin, web.HeadersPlugin, web.ReadableStreamPlugin, web.RequestPlugin, web.ResponsePlugin, web.URLSearchParamsPlugin, web.URLPlugin]);
17
+ function resolveSerializerPlugins(customPlugins) {
18
+ return customPlugins ? [...customPlugins, ...DEFAULT_WEB_PLUGINS] : [...DEFAULT_WEB_PLUGINS];
19
+ }
20
+ function createSerializer(options) {
21
+ return new seroval.Serializer({
22
+ ...options,
23
+ plugins: resolveSerializerPlugins(options.plugins),
24
+ disabledFeatures: (options.disabledFeatures === undefined ? DEFAULT_DISABLED_FEATURES : options.disabledFeatures) | serializeOnlyDisabledFeatures()
25
+ });
26
+ }
27
+ function createHydrationSerializer({
28
+ onData,
29
+ onDone,
30
+ scopeId,
31
+ onError,
32
+ plugins
33
+ }) {
34
+ return createSerializer({
35
+ scopeId,
36
+ plugins,
37
+ globalIdentifier: HYDRATION_GLOBAL,
38
+ onData,
39
+ onDone,
40
+ onError
41
+ });
42
+ }
43
+ function getLocalHeaderScript(id) {
44
+ return seroval.getCrossReferenceHeader(id) + ";";
45
+ }
46
+ const JSON_CODEC_DISABLED_FEATURES = seroval.Feature.RegExp;
47
+ const JSON_CODEC_DEPTH_LIMIT = 64;
48
+ function resolveCodecOptions({
49
+ plugins,
50
+ disabledFeatures,
51
+ depthLimit
52
+ } = {}) {
53
+ return {
54
+ plugins: resolveSerializerPlugins(plugins),
55
+ disabledFeatures: disabledFeatures === undefined ? JSON_CODEC_DISABLED_FEATURES : disabledFeatures,
56
+ depthLimit: depthLimit === undefined ? JSON_CODEC_DEPTH_LIMIT : depthLimit
57
+ };
58
+ }
59
+ function serializeJSON(value, {
60
+ onParse,
61
+ onDone,
62
+ onError,
63
+ ...codecOptions
64
+ }) {
65
+ const resolved = resolveCodecOptions(codecOptions);
66
+ return seroval.toCrossJSONStream(value, {
67
+ onParse,
68
+ onDone,
69
+ onError,
70
+ ...resolved,
71
+ disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures()
72
+ });
73
+ }
74
+ function createJSONSerializer({
75
+ onData,
76
+ onDone,
77
+ onError,
78
+ plugins,
79
+ disabledFeatures,
80
+ depthLimit
81
+ }) {
82
+ const resolved = resolveCodecOptions({
83
+ plugins,
84
+ disabledFeatures,
85
+ depthLimit
86
+ });
87
+ const refs = new Map();
88
+ const cancels = new Set();
89
+ let pendingWrites = 0;
90
+ let flushed = false;
91
+ let done = false;
92
+ const maybeDone = () => {
93
+ if (flushed && pendingWrites === 0 && !done) {
94
+ done = true;
95
+ onDone && onDone();
96
+ }
97
+ };
98
+ return {
99
+ write(key, value) {
100
+ if (flushed) return;
101
+ pendingWrites++;
102
+ let settled = false;
103
+ let cancel = null;
104
+ const stream = seroval.toCrossJSONStream(value, {
105
+ refs,
106
+ plugins: resolved.plugins,
107
+ disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures(),
108
+ onParse(node, initial) {
109
+ onData({
110
+ key,
111
+ node,
112
+ initial
113
+ });
114
+ },
115
+ onError,
116
+ onDone() {
117
+ settled = true;
118
+ if (cancel) cancels.delete(cancel);
119
+ pendingWrites--;
120
+ maybeDone();
121
+ }
122
+ });
123
+ if (!settled) {
124
+ cancel = stream;
125
+ cancels.add(cancel);
126
+ }
127
+ },
128
+ flush() {
129
+ flushed = true;
130
+ maybeDone();
131
+ },
132
+ close() {
133
+ flushed = true;
134
+ for (const cancel of cancels) cancel();
135
+ cancels.clear();
136
+ }
137
+ };
138
+ }
139
+
140
+ const HEAD_ELIGIBLE_TAGS = new Set(["title", "meta", "link", "style", "script", "base"]);
141
+ const HEAD_ATTR_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;
142
+ const RESOURCE_LINK_RELS = new Set(["preload", "modulepreload", "prefetch", "preconnect", "dns-prefetch", "icon", "stylesheet"]);
143
+ const RESOURCE_QUALIFIERS = ["as", "crossorigin", "type", "media", "imagesrcset", "imagesizes"];
144
+ const STYLESHEET_FETCH_META = new Set(["crossorigin", "integrity", "referrerpolicy", "fetchpriority"]);
145
+ function evalHeadValue(v) {
146
+ return typeof v === "function" ? v() : v;
147
+ }
148
+ function evalHeadProps(props, presets) {
149
+ const out = {};
150
+ for (const name in props) out[name] = presets && name in presets ? presets[name] : evalHeadValue(props[name]);
151
+ return out;
152
+ }
153
+ function classifyHeadTag(desc) {
154
+ const tag = desc.tag;
155
+ if (tag === "link") {
156
+ const rel = evalHeadValue(desc.props && desc.props.rel);
157
+ return {
158
+ resource: RESOURCE_LINK_RELS.has(rel),
159
+ rel
160
+ };
161
+ }
162
+ if (tag === "style") return {
163
+ resource: !!(desc.props && "href" in desc.props)
164
+ };
165
+ if (tag === "script") return {
166
+ resource: !!(desc.props && "src" in desc.props)
167
+ };
168
+ return {
169
+ resource: false
170
+ };
171
+ }
172
+ function resourceIdentity(tag, props) {
173
+ let id = "res:" + tag + ":" + (props.rel || "") + ":" + (props.href || props.src || "");
174
+ for (let i = 0; i < RESOURCE_QUALIFIERS.length; i++) {
175
+ const q = RESOURCE_QUALIFIERS[i];
176
+ if (props[q] != null) id += ":" + q + "=" + props[q];
177
+ }
178
+ return id;
179
+ }
180
+ function replaceableIdentity(tag, props, key, unique) {
181
+ if (tag === "title") return "title";
182
+ if (tag === "base") return "base";
183
+ if (tag === "meta" && props.charset != null) return "charset";
184
+ if (key != null) return tag + ":key:" + key;
185
+ if (tag === "meta") {
186
+ if (props.name != null) return "meta:name:" + props.name;
187
+ if (props.property != null) return "meta:property:" + props.property;
188
+ if (props["http-equiv"] != null) return "meta:http-equiv:" + props["http-equiv"];
189
+ return unique;
190
+ }
191
+ if (tag === "link") return "link:" + (props.rel || "") + ":" + (props.href || "");
192
+ return unique;
193
+ }
194
+ function resolveHead(groups) {
195
+ const winners = new Map();
196
+ const sorted = groups.slice().sort((a, b) => a.seq - b.seq);
197
+ for (let i = 0; i < sorted.length; i++) {
198
+ const group = sorted[i];
199
+ const byIdentity = new Map();
200
+ for (let j = 0; j < group.tags.length; j++) {
201
+ const t = group.tags[j];
202
+ let list = byIdentity.get(t.identity);
203
+ if (!list) byIdentity.set(t.identity, list = []);
204
+ list.push(t);
205
+ }
206
+ for (const [identity, tags] of byIdentity) {
207
+ if (identity === "title") {
208
+ if (tags.length > 1) console.warn("Multiple <title> tags in one head group; the last one wins.");
209
+ winners.set(identity, {
210
+ seq: group.seq,
211
+ tags: [tags[tags.length - 1]]
212
+ });
213
+ } else {
214
+ winners.set(identity, {
215
+ seq: group.seq,
216
+ tags
217
+ });
218
+ }
219
+ }
220
+ }
221
+ return winners;
222
+ }
223
+
224
+ function joinAssetPath(base, file) {
225
+ if (/^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(file)) return file;
226
+ if (typeof base !== "string" || !base) base = "/";
227
+ if (base[base.length - 1] !== "/") base += "/";
228
+ return base + (file[0] === "/" ? file.slice(1) : file);
229
+ }
230
+ function resolveAssets(moduleUrl, manifest) {
231
+ if (!manifest) return null;
232
+ const base = manifest._base;
233
+ const entry = manifest[moduleUrl];
234
+ if (!entry) return null;
235
+ const css = [];
236
+ const js = [];
237
+ const visited = new Set();
238
+ const walk = key => {
239
+ if (visited.has(key)) return;
240
+ visited.add(key);
241
+ const e = manifest[key];
242
+ if (!e) return;
243
+ js.push(joinAssetPath(base, e.file));
244
+ if (e.css) for (let i = 0; i < e.css.length; i++) css.push(joinAssetPath(base, e.css[i]));
245
+ if (e.imports) for (let i = 0; i < e.imports.length; i++) walk(e.imports[i]);
246
+ };
247
+ walk(moduleUrl);
248
+ return {
249
+ js,
250
+ css
251
+ };
252
+ }
253
+ function registerEntryAssets(manifest) {
254
+ if (!manifest || typeof manifest === "function" || typeof manifest.resolve === "function") return;
255
+ const ctx = solidJs.sharedConfig.context;
256
+ if (!ctx?.registerAsset) return;
257
+ for (const key in manifest) {
258
+ if (manifest[key].isEntry) {
259
+ const assets = resolveAssets(key, manifest);
260
+ if (assets) {
261
+ for (let i = 0; i < assets.css.length; i++) ctx.registerAsset("style", assets.css[i]);
262
+ }
263
+ return;
264
+ }
265
+ }
266
+ }
267
+ function createAssetTracking() {
268
+ const boundaryModules = new Map();
269
+ const boundaryStyles = new Map();
270
+ const emittedAssets = new Set();
271
+ const inlineStyles = new Map();
272
+ let currentBoundaryId = null;
273
+ return {
274
+ boundaryModules,
275
+ boundaryStyles,
276
+ emittedAssets,
277
+ inlineStyles,
278
+ registerInlineStyle(desc) {
279
+ let entry = inlineStyles.get(desc.id);
280
+ if (!entry) {
281
+ entry = {
282
+ id: desc.id,
283
+ content: desc.content || "",
284
+ attrs: desc.attrs,
285
+ emitted: false
286
+ };
287
+ inlineStyles.set(desc.id, entry);
288
+ }
289
+ if (currentBoundaryId) {
290
+ let styles = boundaryStyles.get(currentBoundaryId);
291
+ if (!styles) {
292
+ styles = new Set();
293
+ boundaryStyles.set(currentBoundaryId, styles);
294
+ }
295
+ styles.add(entry);
296
+ }
297
+ return entry;
298
+ },
299
+ get currentBoundaryId() {
300
+ return currentBoundaryId;
301
+ },
302
+ set currentBoundaryId(v) {
303
+ currentBoundaryId = v;
304
+ },
305
+ registerModule(key, entryUrl) {
306
+ const id = currentBoundaryId || "";
307
+ let map = boundaryModules.get(id);
308
+ if (!map) {
309
+ map = {};
310
+ boundaryModules.set(id, map);
311
+ }
312
+ map[key] = entryUrl;
313
+ },
314
+ getBoundaryModules(id) {
315
+ return boundaryModules.get(id) || null;
316
+ },
317
+ getBoundaryStyles(id) {
318
+ return boundaryStyles.get(id) || null;
319
+ }
320
+ };
321
+ }
322
+ function warnUnresolvedModuleAssets(moduleUrl, warned) {
323
+ if (warned.has(moduleUrl)) return;
324
+ warned.add(moduleUrl);
325
+ console.error(`Asset manifest returned no client assets for module "${moduleUrl}". ` + "If this module is a server-rendered lazy() component, its entry will be missing from " + "the serialized hydration asset map, the client will be unable to preload it, and " + "hydration will fail with 'lazy() module \"…\" was not preloaded before hydration'. " + "This means the integration's asset resolver (dev manifest bridge or build client " + "manifest) failed to answer for this module — check the integration's server logs, " + "restart the dev server, or verify the module is included in the client build.");
326
+ }
327
+ function guardResolvedAssets(moduleUrl, result, warned) {
328
+ if (result && typeof result.then === "function") {
329
+ return result.then(assets => {
330
+ if (!assets || !assets.js || !assets.js.length) warnUnresolvedModuleAssets(moduleUrl, warned);
331
+ return assets;
332
+ });
333
+ }
334
+ if (!result || !result.js || !result.js.length) warnUnresolvedModuleAssets(moduleUrl, warned);
335
+ return result;
336
+ }
337
+ function applyAssetTracking(context, tracking, manifest, noScripts) {
338
+ const warned = new Set();
339
+ const guard = noScripts ? resolve => resolve : resolve => moduleUrl => guardResolvedAssets(moduleUrl, resolve(moduleUrl), warned);
340
+ Object.defineProperty(context, "_currentBoundaryId", {
341
+ get() {
342
+ return tracking.currentBoundaryId;
343
+ },
344
+ set(v) {
345
+ tracking.currentBoundaryId = v;
346
+ },
347
+ configurable: true,
348
+ enumerable: true
349
+ });
350
+ context.registerModule = tracking.registerModule;
351
+ context.getBoundaryModules = tracking.getBoundaryModules;
352
+ if (typeof manifest === "function") {
353
+ context.resolveAssets = guard(manifest);
354
+ } else if (manifest && typeof manifest.resolve === "function") {
355
+ context.resolveAssets = guard(key => manifest.resolve(key));
356
+ if (typeof manifest.resolveSync === "function") {
357
+ context.resolveAssetsSync = key => manifest.resolveSync(key);
358
+ }
359
+ } else if (manifest) {
360
+ const resolve = moduleUrl => resolveAssets(moduleUrl, manifest);
361
+ context.resolveAssets = guard(resolve);
362
+ context.resolveAssetsSync = resolve;
363
+ }
364
+ }
365
+ function isCssUrl(url) {
366
+ const q = url.search(/[?#]/);
367
+ return (q === -1 ? url : url.slice(0, q)).endsWith(".css");
368
+ }
369
+ function createHeadRegistry() {
370
+ return {
371
+ pending: [],
372
+ committed: [],
373
+ seq: 0,
374
+ uniq: 0,
375
+ resources: new Set(),
376
+ eagerHtml: "",
377
+ flushed: null,
378
+ shellFlushed: false
379
+ };
380
+ }
381
+ function registerHeadTags(registry, context, tracking, emitResource, nonce, tags) {
382
+ const boundary = context._currentBoundaryId || "";
383
+ let replaceable = null;
384
+ for (let i = 0; i < tags.length; i++) {
385
+ const desc = tags[i];
386
+ if (!desc || !HEAD_ELIGIBLE_TAGS.has(desc.tag)) {
387
+ console.warn(`useHead: ignoring non-head tag`, desc);
388
+ continue;
389
+ }
390
+ const cls = classifyHeadTag(desc);
391
+ if (cls.resource) {
392
+ emitHeadResource(registry, context, tracking, emitResource, nonce, desc, cls.rel);
393
+ } else {
394
+ (replaceable || (replaceable = [])).push(cls.rel !== undefined ? {
395
+ tag: desc.tag,
396
+ props: desc.props,
397
+ key: desc.key,
398
+ rel: cls.rel
399
+ } : desc);
400
+ }
401
+ }
402
+ if (replaceable) registry.pending.push({
403
+ boundary,
404
+ tags: replaceable
405
+ });
406
+ }
407
+ function emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel) {
408
+ let props;
409
+ try {
410
+ props = evalHeadProps(desc.props || {}, rel !== undefined ? {
411
+ rel
412
+ } : undefined);
413
+ } catch (err) {
414
+ console.warn(`useHead: error evaluating resource tag props`, err);
415
+ return;
416
+ }
417
+ const identity = resourceIdentity(desc.tag, props);
418
+ if (registry.resources.has(identity)) return;
419
+ registry.resources.add(identity);
420
+ if (desc.tag === "link" && (rel === "stylesheet" || rel === "modulepreload")) {
421
+ let plain = true;
422
+ let gateable = rel === "stylesheet";
423
+ for (const name in props) {
424
+ if (name === "rel" || name === "href") continue;
425
+ plain = false;
426
+ if (!STYLESHEET_FETCH_META.has(name)) gateable = false;
427
+ }
428
+ if (plain && props.href != null) {
429
+ const isCss = isCssUrl(props.href);
430
+ if (rel === "stylesheet" ? isCss : !isCss) {
431
+ context.registerAsset(rel === "stylesheet" ? "style" : "module", props.href);
432
+ return;
433
+ }
434
+ }
435
+ if (gateable && props.href != null) {
436
+ const attrHtml = renderHeadAttrHtml(props);
437
+ const entry = {
438
+ href: props.href,
439
+ attrHtml,
440
+ attrs: headAttrRecord(props)
441
+ };
442
+ if (tracking.currentBoundaryId) {
443
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
444
+ if (!styles) tracking.boundaryStyles.set(tracking.currentBoundaryId, styles = new Set());
445
+ styles.add(entry);
446
+ }
447
+ const markup = `<link${attrHtml}>`;
448
+ if (emitResource) emitResource(markup, entry);else {
449
+ registry.eagerHtml += markup;
450
+ entry.emitted = true;
451
+ }
452
+ return;
453
+ }
454
+ }
455
+ const url = props.href || props.src;
456
+ if (url != null && tracking.emittedAssets.has(url)) return;
457
+ const markup = renderHeadTagMarkup(desc.tag, props, null, nonce);
458
+ if (emitResource) emitResource(markup);else registry.eagerHtml += markup;
459
+ }
460
+ function commitHeadBoundary(registry, boundary, isPendingFragment) {
461
+ const keep = [];
462
+ const groups = [];
463
+ for (let i = 0; i < registry.pending.length; i++) {
464
+ const reg = registry.pending[i];
465
+ const mine = boundary === "" ? !(isPendingFragment && reg.boundary !== "" && isPendingFragment(reg.boundary)) : reg.boundary === boundary;
466
+ if (!mine) {
467
+ keep.push(reg);
468
+ continue;
469
+ }
470
+ const tags = [];
471
+ for (let j = 0; j < reg.tags.length; j++) {
472
+ const desc = reg.tags[j];
473
+ let props, key;
474
+ try {
475
+ props = evalHeadProps(desc.props || {}, desc.rel !== undefined ? {
476
+ rel: desc.rel
477
+ } : undefined);
478
+ key = evalHeadValue(desc.key);
479
+ } catch (err) {
480
+ console.warn(`useHead: error evaluating tag props`, err);
481
+ continue;
482
+ }
483
+ const identity = replaceableIdentity(desc.tag, props, key, "u:" + registry.uniq++);
484
+ if ((identity === "base" || identity === "charset") && registry.shellFlushed) {
485
+ console.warn(`useHead: <${desc.tag}> (${identity}) registered after shell flush is ignored`);
486
+ continue;
487
+ }
488
+ tags.push({
489
+ tag: desc.tag,
490
+ props,
491
+ identity
492
+ });
493
+ }
494
+ if (tags.length) groups.push({
495
+ seq: registry.seq++,
496
+ tags
497
+ });
498
+ }
499
+ registry.pending = keep;
500
+ for (let i = 0; i < groups.length; i++) registry.committed.push(groups[i]);
501
+ return groups;
502
+ }
503
+ function adoptHeadBoundary(registry, childKey, parentKey) {
504
+ for (let i = 0; i < registry.pending.length; i++) {
505
+ if (registry.pending[i].boundary === childKey) registry.pending[i].boundary = parentKey;
506
+ }
507
+ }
508
+ function dropHeadBoundary(registry, boundary) {
509
+ registry.pending = registry.pending.filter(reg => reg.boundary !== boundary);
510
+ }
511
+ function headGroupSignature(winner) {
512
+ let sig = "" + winner.seq;
513
+ for (let i = 0; i < winner.tags.length; i++) {
514
+ const t = winner.tags[i];
515
+ sig += "|" + t.tag + JSON.stringify(t.props);
516
+ }
517
+ return sig;
518
+ }
519
+ function renderShellHead(registry, nonce, isPendingFragment) {
520
+ commitHeadBoundary(registry, "", isPendingFragment);
521
+ registry.shellFlushed = true;
522
+ const winners = resolveHead(registry.committed);
523
+ registry.flushed = new Map();
524
+ let prelude = "";
525
+ let links = "";
526
+ let metas = "";
527
+ let others = "";
528
+ let scripts = "";
529
+ for (const [identity, winner] of winners) {
530
+ registry.flushed.set(identity, headGroupSignature(winner));
531
+ for (let i = 0; i < winner.tags.length; i++) {
532
+ const t = winner.tags[i];
533
+ const markup = renderHeadTagMarkup(t.tag, t.props, identity, nonce);
534
+ if (identity === "charset" || identity === "base") prelude += markup;else if (t.tag === "link" || t.tag === "style") links += markup;else if (t.tag === "meta") metas += markup;else if (t.tag === "script") scripts += markup;else others += markup;
535
+ }
536
+ }
537
+ return {
538
+ prelude,
539
+ html: registry.eagerHtml + links + metas + others + scripts
540
+ };
541
+ }
542
+ function flushHeadFragment(registry, boundary) {
543
+ const groups = commitHeadBoundary(registry, boundary);
544
+ if (!groups.length) return null;
545
+ const winners = resolveHead(registry.committed);
546
+ const affected = new Set();
547
+ for (let i = 0; i < groups.length; i++) for (let j = 0; j < groups[i].tags.length; j++) affected.add(groups[i].tags[j].identity);
548
+ const ops = [];
549
+ for (const identity of affected) {
550
+ const winner = winners.get(identity);
551
+ const sig = headGroupSignature(winner);
552
+ if (registry.flushed.get(identity) === sig) continue;
553
+ const existed = registry.flushed.has(identity);
554
+ registry.flushed.set(identity, sig);
555
+ if (identity === "title") {
556
+ const children = winner.tags[0].props.children;
557
+ ops.push(["t", children == null ? "" : String(children)]);
558
+ continue;
559
+ }
560
+ if (existed) ops.push(["r", identity]);
561
+ for (let i = 0; i < winner.tags.length; i++) {
562
+ const t = winner.tags[i];
563
+ const attrs = {};
564
+ for (const name in t.props) {
565
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
566
+ if (!HEAD_ATTR_NAME.test(name)) {
567
+ console.warn(`useHead: ignoring invalid attribute name "${name}"`);
568
+ continue;
569
+ }
570
+ const v = t.props[name];
571
+ if (v == null || v === false) continue;
572
+ attrs[name] = v === true ? "" : String(v);
573
+ }
574
+ const children = t.props.children;
575
+ ops.push(["a", identity, t.tag, attrs, children == null ? null : String(children)]);
576
+ }
577
+ }
578
+ return ops.length ? ops : null;
579
+ }
580
+ function renderHeadAttrHtml(props) {
581
+ let attrs = "";
582
+ for (const name in props) {
583
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
584
+ if (!HEAD_ATTR_NAME.test(name)) {
585
+ console.warn(`useHead: ignoring invalid attribute name "${name}"`);
586
+ continue;
587
+ }
588
+ const v = props[name];
589
+ if (v == null || v === false) continue;
590
+ attrs += v === true ? ` ${name}` : ` ${name}="${escape(String(v), true)}"`;
591
+ }
592
+ return attrs;
593
+ }
594
+ function headAttrRecord(props, skipRelHref) {
595
+ let attrs = null;
596
+ for (const name in props) {
597
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
598
+ if ((name === "rel" || name === "href")) continue;
599
+ if (!HEAD_ATTR_NAME.test(name)) continue;
600
+ const v = props[name];
601
+ if (v == null || v === false) continue;
602
+ (attrs || (attrs = {}))[name] = v === true ? "" : String(v);
603
+ }
604
+ return attrs;
605
+ }
606
+ function renderHeadTagMarkup(tag, props, identity, nonce) {
607
+ let attrs = renderHeadAttrHtml(props);
608
+ if (identity != null) attrs += ` data-dh="${escape(identity, true)}"`;
609
+ if (nonce && (tag === "script" || tag === "style")) attrs += ` nonce="${nonce}"`;
610
+ if (tag === "meta" || tag === "link" || tag === "base") return `<${tag}${attrs}>`;
611
+ let body = props.children == null ? "" : String(props.children);
612
+ if (tag === "script") body = body.replace(/<\/(script)/gi, "<\\/$1");else if (tag === "style") body = escapeStyleContent(body);else body = escape(body);
613
+ return `<${tag}${attrs}>${body}</${tag}>`;
614
+ }
615
+ const REPLACE_SCRIPT = `function $df(e){return _$HY.f?_$HY.f(e):$dfr(e)}function $dfr(e,n,o,t){if(!(n=document.getElementById(e)))return 0;if(!(o=document.getElementById("pl-"+e)))return(_$HY.dq=_$HY.dq||{})[e]=1,0;for(;o&&(8!==o.nodeType||o.nodeValue!=="pl-"+e);)t=o.nextSibling,o.remove(),o=t;t=o.parentNode,o.replaceWith(n.content),n.remove(),_$HY.fe(e,t),_$HY.hp&&_$HY.hp[e]&&($dh(_$HY.hp[e]),delete _$HY.hp[e]),$dfd();return 1}function $dfl(e,o,n){if(!(o=document.getElementById("pl-"+e)))return(_$HY.dlq=_$HY.dlq||{})[e]=1,0;if(o._$fl)return 1;for(n=o.nextSibling;n;){if(8===n.nodeType&&n.nodeValue==="pl-"+e){o.parentNode&&o.parentNode.insertBefore(o.content.cloneNode(!0),n),o._$fl=1,$dfd();return 1}n=n.nextSibling}return 0}function $dflj(e,i){for(i=0;i<e.length;i++)$dfl(e[i])}function $dfd(e,i){if(e=_$HY.dq){_$HY.dq=0;for(i in e)$df(i)}if(e=_$HY.dlq){_$HY.dlq=0;for(i in e)$dfl(i)}}function $dfs(e,c,d){(_$HY.sc=_$HY.sc||{})[e]=c,d&&((_$HY.sd=_$HY.sd||{})[e]=1)}function $dfg(e,g,i,k){if(!(g=_$HY.sg&&_$HY.sg[e]))return;for(i=0;i<g.length;i++)if(_$HY.sc&&_$HY.sc[g[i]]>0)return;for(i=0;i<g.length;i++)k=g[i],delete _$HY.sg[k],$df(k)}function $dfc(e){if(--_$HY.sc[e]<=0){delete _$HY.sc[e],_$HY.sg&&_$HY.sg[e]?$dfg(e):!(_$HY.sd&&_$HY.sd[e])&&$df(e);_$HY.sd&&delete _$HY.sd[e]}}function $dfj(e,i,n){for(i=0;i<e.length;i++)if(_$HY.sc&&_$HY.sc[e[i]]>0){for(n=0;n<e.length;n++)(_$HY.sg=_$HY.sg||{})[e[n]]=e;return}for(i=0;i<e.length;i++)$df(e[i])}`;
616
+ const HEAD_SCRIPT = `function $dha(o,i,e,n){for(i=0;i<o.length;i++)e=o[i],"t"==e[0]?((n=document.querySelector("title"))||(n=document.createElement("title"),document.head.appendChild(n)),n.textContent=e[1],n.setAttribute("data-dh","title")):"r"==e[0]?$dhr(e[1]):(n=document.createElement(e[2]),Object.keys(e[3]).forEach(function(a){n.setAttribute(a,e[3][a])}),null!=e[4]&&(n.textContent=e[4]),n.setAttribute("data-dh",e[1]),document.head.appendChild(n))}function $dhr(v,l,i){for(l=document.head.querySelectorAll("[data-dh]"),i=0;i<l.length;i++)l[i].getAttribute("data-dh")==v&&l[i].remove()}function $dh(o){_$HY.h?_$HY.h(o):$dha(o)}`;
617
+ function renderToStream(code, options = {}) {
618
+ let {
619
+ nonce,
620
+ onCompleteShell,
621
+ onCompleteAll,
622
+ renderId = "",
623
+ noScripts,
624
+ manifest,
625
+ onHead
626
+ } = options;
627
+ let dispose;
628
+ const blockingPromises = new Set();
629
+ let headerEmitted = false;
630
+ const pushTask = task => {
631
+ if (noScripts) return;
632
+ if (!headerEmitted) {
633
+ headerEmitted = true;
634
+ tasks += getLocalHeaderScript(renderId);
635
+ }
636
+ tasks += task + ";";
637
+ if (!timer && firstFlushed) {
638
+ timer = true;
639
+ queue(() => queue(writeTasks));
640
+ }
641
+ };
642
+ const onDone = () => {
643
+ writeTasks();
644
+ doShell();
645
+ onCompleteAll && onCompleteAll({
646
+ write(v) {
647
+ !completed && buffer.write(v);
648
+ }
649
+ });
650
+ writable && writable.end();
651
+ completed = true;
652
+ if (firstFlushed) dispose();
653
+ };
654
+ const sink = {
655
+ data(payload) {
656
+ pushTask(payload);
657
+ },
658
+ fragment(key, value, meta) {
659
+ const deferActivation = !!meta.revealGroup;
660
+ const styles = meta.styles;
661
+ for (let i = 0; i < styles.inline.length; i++) {
662
+ buffer.write(renderInlineStyle(styles.inline[i], nonce));
663
+ }
664
+ if (styles.links.length) {
665
+ emitTask(`$dfs("${key}",${styles.links.length},${deferActivation ? 1 : 0})`);
666
+ writeTasks();
667
+ for (const entry of styles.links) {
668
+ buffer.write(typeof entry === "string" ? `<link rel="stylesheet" href="${entry}" onload="$dfc('${key}')" onerror="$dfc('${key}')">` : `<link${entry.attrHtml} onload="$dfc('${key}')" onerror="$dfc('${key}')">`);
669
+ }
670
+ buffer.write(`<template id="${key}">${value}</template>`);
671
+ } else {
672
+ buffer.write(`<template id="${key}">${value}</template>`);
673
+ if (!deferActivation) {
674
+ emitTask(`$df("${key}")`);
675
+ }
676
+ }
677
+ },
678
+ reveal(keys, meta) {
679
+ emitTask(`${meta.fallback ? "$dflj" : "$dfj"}(${JSON.stringify(keys)})`);
680
+ },
681
+ asset(type, value) {
682
+ if (type === "module") {
683
+ buffer.write(`<link rel="modulepreload" href="${value}">`);
684
+ } else if (type === "inline-style") {
685
+ buffer.write(renderInlineStyle(value, nonce));
686
+ } else if (type === "head-tag") {
687
+ buffer.write(value);
688
+ }
689
+ },
690
+ shell(shellHtml, meta) {
691
+ buffer.write(assembleDocument(shellHtml, meta.assets, meta.preloads, meta.inlineStyles, meta.tasks.length ? meta.tasks : "", nonce, meta.head, onHead));
692
+ },
693
+ ...options.sink
694
+ };
695
+ const serializer = (options.serializer || createHydrationSerializer)({
696
+ scopeId: options.renderId,
697
+ plugins: options.plugins,
698
+ onData: payload => sink.data(payload),
699
+ onDone,
700
+ onError: options.onError
701
+ });
702
+ let rootAssetsSerialized = false;
703
+ const serializeRootAssets = () => {
704
+ if (rootAssetsSerialized) return;
705
+ rootAssetsSerialized = true;
706
+ serializeFragmentAssets("", tracking.boundaryModules, context);
707
+ };
708
+ const flushEnd = () => {
709
+ if (!registry.size) {
710
+ serializeRootAssets();
711
+ queue(() => queue(() => serializer.flush()));
712
+ }
713
+ };
714
+ const registry = new Map();
715
+ const writeTasks = () => {
716
+ if (tasks.length && !completed && firstFlushed) {
717
+ buffer.write(`<script${nonce ? ` nonce="${nonce}"` : ""}>${tasks}</script>`);
718
+ tasks = "";
719
+ }
720
+ timer = null;
721
+ };
722
+ let context;
723
+ let writable;
724
+ let tmp = "";
725
+ let tasks = "";
726
+ let firstFlushed = false;
727
+ let completed = false;
728
+ let shellCompleted = false;
729
+ let scriptFlushed = false;
730
+ let headStyles;
731
+ const revealGroups = new Map();
732
+ let timer = null;
733
+ const emitTask = task => {
734
+ pushTask(`${task}${!scriptFlushed ? ";" + REPLACE_SCRIPT : ""}`);
735
+ scriptFlushed = true;
736
+ };
737
+ function resolveRevealKeys(groupOrKeys, release, consume) {
738
+ if (Array.isArray(groupOrKeys)) return groupOrKeys.slice();
739
+ let group = revealGroups.get(groupOrKeys);
740
+ if (!group) {
741
+ if (!release) return;
742
+ group = {
743
+ order: [],
744
+ keys: new Set(),
745
+ released: true
746
+ };
747
+ revealGroups.set(groupOrKeys, group);
748
+ } else if (release) group.released = true;
749
+ if (!group.order.length) return;
750
+ const keys = group.order.slice();
751
+ if (consume) revealGroups.delete(groupOrKeys);
752
+ return keys;
753
+ }
754
+ let rootHoles = null;
755
+ let nextHoleId = 0;
756
+ let buffer = {
757
+ write(payload) {
758
+ tmp += payload;
759
+ }
760
+ };
761
+ const tracking = createAssetTracking();
762
+ const headRegistry = createHeadRegistry();
763
+ let headScriptFlushed = false;
764
+ const emitHeadOps = (key, ops) => {
765
+ const payload = JSON.stringify(ops).replace(/</g, "\\u003C");
766
+ emitTask(`${!headScriptFlushed ? HEAD_SCRIPT : ""}(_$HY.hp=_$HY.hp||{})[${JSON.stringify(key)}]=${payload}`);
767
+ headScriptFlushed = true;
768
+ };
769
+ solidJs.sharedConfig.context = context = {
770
+ async: true,
771
+ assets: [],
772
+ nonce,
773
+ registerHeadTags(tags) {
774
+ registerHeadTags(headRegistry, context, tracking,
775
+ (markup, gateEntry) => {
776
+ if (!firstFlushed) {
777
+ headRegistry.eagerHtml += markup;
778
+ if (gateEntry) gateEntry.emitted = true;
779
+ } else if (!gateEntry || !tracking.currentBoundaryId) {
780
+ sink.asset("head-tag", markup);
781
+ }
782
+ }, nonce, tags);
783
+ },
784
+ registerAsset(type, value) {
785
+ if (type === "inline-style") {
786
+ const entry = tracking.registerInlineStyle(value);
787
+ if (firstFlushed && !tracking.currentBoundaryId && !entry.emitted) {
788
+ entry.emitted = true;
789
+ sink.asset("inline-style", entry);
790
+ }
791
+ return;
792
+ }
793
+ if (tracking.currentBoundaryId && type === "style") {
794
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
795
+ if (!styles) {
796
+ styles = new Set();
797
+ tracking.boundaryStyles.set(tracking.currentBoundaryId, styles);
798
+ }
799
+ styles.add(value);
800
+ }
801
+ if (!tracking.emittedAssets.has(value)) {
802
+ tracking.emittedAssets.add(value);
803
+ if (firstFlushed) sink.asset(type, value);
804
+ }
805
+ },
806
+ block(p) {
807
+ if (!firstFlushed) blockingPromises.add(p);
808
+ },
809
+ replace(id, payloadFn) {
810
+ if (firstFlushed) return;
811
+ const placeholder = `<!--!$${id}-->`;
812
+ const first = html.indexOf(placeholder);
813
+ if (first === -1) return;
814
+ const last = html.indexOf(`<!--!$/${id}-->`, first + placeholder.length);
815
+ html = html.slice(0, first) + resolveSSRSync(escape(payloadFn())) + html.slice(last + placeholder.length + 1);
816
+ },
817
+ serialize(id, p, deferStream) {
818
+ if (solidJs.sharedConfig.context.noHydrate) return;
819
+ if (!firstFlushed && deferStream && typeof p === "object" && "then" in p) {
820
+ blockingPromises.add(p);
821
+ p.then(d => serializer.write(id, d)).catch(e => serializer.write(id, e));
822
+ } else serializer.write(id, p);
823
+ },
824
+ escape: escape,
825
+ resolve: resolveSSRNode,
826
+ ssr: ssr,
827
+ registerFragment(key, options) {
828
+ const revealGroup = options && options.revealGroup;
829
+ if (revealGroup) {
830
+ let group = revealGroups.get(revealGroup);
831
+ if (!group) {
832
+ group = {
833
+ order: [],
834
+ keys: new Set(),
835
+ released: false
836
+ };
837
+ revealGroups.set(revealGroup, group);
838
+ }
839
+ if (!group.keys.has(key)) {
840
+ group.keys.add(key);
841
+ group.order.push(key);
842
+ }
843
+ if (group.released) {
844
+ throw new Error("registerFragment() for reveal group '" + revealGroup + "' was called after revealFragments(). Ensure template payload is emitted before grouped reveal.");
845
+ }
846
+ }
847
+ if (!registry.has(key)) {
848
+ let resolve, reject;
849
+ const p = new Promise((r, rej) => (resolve = r, reject = rej));
850
+ registry.set(key, {
851
+ resolve: err => queue(() => queue(() => {
852
+ err ? reject(err) : resolve(true);
853
+ queue(flushEnd);
854
+ }))
855
+ });
856
+ serializer.write(key + "_fr", p);
857
+ }
858
+ return (value, error) => {
859
+ if (registry.has(key)) {
860
+ const item = registry.get(key);
861
+ registry.delete(key);
862
+ if (item.children) {
863
+ for (const k in item.children) {
864
+ value = replacePlaceholder(value, k, item.children[k]);
865
+ }
866
+ }
867
+ const parentKey = waitForFragments(registry, key);
868
+ if (parentKey) {
869
+ const parent = registry.get(parentKey);
870
+ parent.children ||= {};
871
+ parent.children[key] = value !== undefined ? value : "";
872
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
873
+ propagateBoundaryStyles(key, parentKey, tracking);
874
+ adoptHeadBoundary(headRegistry, key, parentKey);
875
+ item.resolve();
876
+ return;
877
+ }
878
+ if (!completed) {
879
+ if (error) dropHeadBoundary(headRegistry, key);
880
+ if (!firstFlushed) {
881
+ queue(() => html = replacePlaceholder(html, key, value !== undefined ? value : ""));
882
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
883
+ item.resolve(error);
884
+ } else {
885
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
886
+ const styles = collectStreamStyles(key, tracking, headStyles);
887
+ const headOps = error ? null : flushHeadFragment(headRegistry, key);
888
+ if (headOps) emitHeadOps(key, headOps);
889
+ sink.fragment(key, value !== undefined ? value : " ", {
890
+ styles,
891
+ revealGroup,
892
+ error
893
+ });
894
+ item.resolve(error);
895
+ }
896
+ }
897
+ }
898
+ return firstFlushed;
899
+ };
900
+ },
901
+ revealFragments(groupOrKeys) {
902
+ const keys = resolveRevealKeys(groupOrKeys, true, true);
903
+ if (!keys) return;
904
+ sink.reveal(keys, {
905
+ fallback: false
906
+ });
907
+ },
908
+ revealFallbacks(groupOrKeys) {
909
+ const keys = resolveRevealKeys(groupOrKeys, false, false);
910
+ if (!keys) return;
911
+ sink.reveal(keys, {
912
+ fallback: true
913
+ });
914
+ }
915
+ };
916
+ applyAssetTracking(context, tracking, manifest, noScripts);
917
+ registerEntryAssets(manifest);
918
+ let html = solidJs.createRoot(d => {
919
+ dispose = d;
920
+ const res = resolveSSRNode(escape(code()));
921
+ if (!res.h.length) return res.t[0];
922
+ rootHoles = [];
923
+ let out = res.t[0];
924
+ for (let i = 0; i < res.h.length; i++) {
925
+ const id = nextHoleId++;
926
+ rootHoles.push({
927
+ id,
928
+ fn: res.h[i]
929
+ });
930
+ out += `<!--rh${id}-->` + res.t[i + 1];
931
+ }
932
+ for (const p of res.p) blockingPromises.add(p);
933
+ return out;
934
+ }, {
935
+ id: renderId
936
+ });
937
+ function resolveRootHoles() {
938
+ if (!rootHoles) return true;
939
+ const pending = [];
940
+ for (const {
941
+ id,
942
+ fn
943
+ } of rootHoles) {
944
+ const marker = `<!--rh${id}-->`;
945
+ const res = resolveSSRNode(fn);
946
+ if (!res.h.length) {
947
+ html = html.replace(marker, res.t[0]);
948
+ } else {
949
+ let out = res.t[0];
950
+ for (let j = 0; j < res.h.length; j++) {
951
+ const newId = nextHoleId++;
952
+ pending.push({
953
+ id: newId,
954
+ fn: res.h[j]
955
+ });
956
+ out += `<!--rh${newId}-->` + res.t[j + 1];
957
+ }
958
+ html = html.replace(marker, out);
959
+ for (const p of res.p) blockingPromises.add(p);
960
+ }
961
+ }
962
+ if (pending.length) {
963
+ rootHoles = pending;
964
+ return false;
965
+ }
966
+ rootHoles = null;
967
+ return true;
968
+ }
969
+ function doShell() {
970
+ if (shellCompleted) return;
971
+ if (!resolveRootHoles()) return;
972
+ solidJs.sharedConfig.context = context;
973
+ const assetsHtml = resolveAssetsHtml(context.assets);
974
+ headStyles = new Set();
975
+ for (const url of tracking.emittedAssets) {
976
+ if (isCssUrl(url)) headStyles.add(url);
977
+ }
978
+ serializeRootAssets();
979
+ const head = renderShellHead(headRegistry, nonce, k => registry.has(k));
980
+ sink.shell(html, {
981
+ assets: assetsHtml,
982
+ preloads: tracking.emittedAssets,
983
+ inlineStyles: tracking.inlineStyles,
984
+ tasks,
985
+ head
986
+ });
987
+ tasks = "";
988
+ onCompleteShell && onCompleteShell({
989
+ write(v) {
990
+ !completed && buffer.write(v);
991
+ }
992
+ });
993
+ shellCompleted = true;
994
+ }
995
+ const MIN_DRAIN_TURNS = 8;
996
+ let lastBlockingSize = -1;
997
+ let lastRegistrySize = -1;
998
+ let drainTurn = 0;
999
+ const scheduleFlush = fn => {
1000
+ const attempt = () => {
1001
+ if (registry.size !== lastRegistrySize || drainTurn++ < MIN_DRAIN_TURNS) {
1002
+ if (registry.size !== lastRegistrySize) drainTurn = 0;
1003
+ lastRegistrySize = registry.size;
1004
+ queue(attempt);
1005
+ return;
1006
+ }
1007
+ fn();
1008
+ };
1009
+ const progressed = blockingPromises.size !== lastBlockingSize;
1010
+ lastBlockingSize = blockingPromises.size;
1011
+ lastRegistrySize = -1;
1012
+ drainTurn = 0;
1013
+ progressed ? queue(attempt) : setTimeout(attempt);
1014
+ };
1015
+ let cachedReadable;
1016
+ let consumer;
1017
+ const claimConsumer = name => {
1018
+ if (consumer && consumer !== name) {
1019
+ throw new Error(`renderToStream result was already consumed via \`${consumer}\`; cannot also consume it via \`${name}\`. Use exactly one of \`pipe\`, \`pipeTo\`, or \`readable\`.`);
1020
+ }
1021
+ consumer = name;
1022
+ };
1023
+ const pipeToImpl = w => {
1024
+ let resolve;
1025
+ const p = new Promise(r => resolve = r);
1026
+ function flush() {
1027
+ allSettled(blockingPromises).then(() => {
1028
+ scheduleFlush(() => {
1029
+ doShell();
1030
+ if (!shellCompleted) return flush();
1031
+ const encoder = new TextEncoder();
1032
+ const writer = w.getWriter();
1033
+ let pendingWrites = Promise.resolve();
1034
+ writable = {
1035
+ end() {
1036
+ pendingWrites.then(() => {
1037
+ writer.releaseLock();
1038
+ w.close().catch(() => {});
1039
+ resolve();
1040
+ });
1041
+ }
1042
+ };
1043
+ buffer = {
1044
+ write(payload) {
1045
+ pendingWrites = pendingWrites.then(() => writer.write(encoder.encode(payload))).catch(() => {});
1046
+ }
1047
+ };
1048
+ buffer.write(tmp);
1049
+ firstFlushed = true;
1050
+ if (completed) {
1051
+ dispose();
1052
+ writable.end();
1053
+ } else flushEnd();
1054
+ });
1055
+ });
1056
+ }
1057
+ flush();
1058
+ return p;
1059
+ };
1060
+ return {
1061
+ then(fn) {
1062
+ function complete() {
1063
+ dispose();
1064
+ fn(tmp);
1065
+ }
1066
+ if (onCompleteAll) {
1067
+ let ogComplete = onCompleteAll;
1068
+ onCompleteAll = options => {
1069
+ ogComplete(options);
1070
+ complete();
1071
+ };
1072
+ } else onCompleteAll = complete;
1073
+ function flush() {
1074
+ allSettled(blockingPromises).then(() => {
1075
+ scheduleFlush(() => {
1076
+ if (!resolveRootHoles()) return flush();
1077
+ queue(flushEnd);
1078
+ });
1079
+ });
1080
+ }
1081
+ flush();
1082
+ },
1083
+ pipe(w) {
1084
+ claimConsumer("pipe");
1085
+ function flush() {
1086
+ allSettled(blockingPromises).then(() => {
1087
+ scheduleFlush(() => {
1088
+ doShell();
1089
+ if (!shellCompleted) return flush();
1090
+ buffer = writable = w;
1091
+ buffer.write(tmp);
1092
+ firstFlushed = true;
1093
+ if (completed) {
1094
+ dispose();
1095
+ writable.end();
1096
+ } else flushEnd();
1097
+ });
1098
+ });
1099
+ }
1100
+ flush();
1101
+ },
1102
+ pipeTo(w) {
1103
+ claimConsumer("pipeTo");
1104
+ return pipeToImpl(w);
1105
+ },
1106
+ get readable() {
1107
+ claimConsumer("readable");
1108
+ if (!cachedReadable) {
1109
+ const t = new TransformStream();
1110
+ pipeToImpl(t.writable);
1111
+ cachedReadable = t.readable;
1112
+ }
1113
+ return cachedReadable;
1114
+ }
1115
+ };
1116
+ }
1117
+ function buildAsyncWrap(err, node) {
1118
+ const p = solidJs.ssrHandleError(err);
1119
+ if (!p) return null;
1120
+ const owner = solidJs.getOwner();
1121
+ return {
1122
+ fn: owner ? () => solidJs.runWithOwner(owner, node) : node,
1123
+ p
1124
+ };
1125
+ }
1126
+ function ssrFirstGroupHit(hole) {
1127
+ try {
1128
+ return hole();
1129
+ } catch (err) {
1130
+ return buildAsyncWrap(err, hole);
1131
+ }
1132
+ }
1133
+ function tryResolveFunctionHole(hole) {
1134
+ let value;
1135
+ try {
1136
+ value = hole();
1137
+ } catch (err) {
1138
+ return buildAsyncWrap(err, hole) || "";
1139
+ }
1140
+ const t = typeof value;
1141
+ if (t === "string") return value;
1142
+ if (t === "number") return "" + value;
1143
+ if (value == null || t === "boolean") return "";
1144
+ return tryResolveString(value);
1145
+ }
1146
+ function mergeTemplateInto(result, node) {
1147
+ result.t[result.t.length - 1] += node.t[0];
1148
+ if (node.t.length > 1) {
1149
+ result.t.push(...node.t.slice(1));
1150
+ result.h.push(...node.h);
1151
+ result.p.push(...node.p);
1152
+ }
1153
+ }
1154
+ function appendResolvedNode(result, node) {
1155
+ if (node.fn !== undefined) {
1156
+ result.h.push(node.fn);
1157
+ result.p.push(node.p);
1158
+ result.t.push("");
1159
+ } else if (node.merge !== undefined) mergeTemplateInto(result, node.merge);else resolveSSRNode(node.bail, result);
1160
+ }
1161
+ let _lastGroupFn = null;
1162
+ let _lastGroupArr = null;
1163
+ let _lastGroupErr = null;
1164
+ function ssrGroupSlot(fn, idx) {
1165
+ return () => {
1166
+ if (idx > 0 && _lastGroupFn === fn) {
1167
+ if (_lastGroupArr !== null) return _lastGroupArr[idx];
1168
+ throw _lastGroupErr;
1169
+ }
1170
+ _lastGroupFn = fn;
1171
+ _lastGroupArr = null;
1172
+ _lastGroupErr = null;
1173
+ try {
1174
+ _lastGroupArr = fn();
1175
+ return _lastGroupArr[idx];
1176
+ } catch (err) {
1177
+ _lastGroupErr = err;
1178
+ throw err;
1179
+ }
1180
+ };
1181
+ }
1182
+ function ssr(t) {
1183
+ const len = arguments.length;
1184
+ if (len === 1) return {
1185
+ t
1186
+ };
1187
+ let s = t[0];
1188
+ let result = null;
1189
+ let lastGroup = null;
1190
+ let lastGroupVal = null;
1191
+ let lastGroupIdx = 0;
1192
+ for (let i = 1; i < len; i++) {
1193
+ const hole = arguments[i];
1194
+ const ht = typeof hole;
1195
+ if (ht === "string") {
1196
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
1197
+ } else if (ht === "number") {
1198
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
1199
+ } else if (hole == null || ht === "boolean") ; else if (ht === "function" && hole.$g) {
1200
+ let value;
1201
+ let hasValue = false;
1202
+ if (lastGroup !== hole) {
1203
+ const r = ssrFirstGroupHit(hole);
1204
+ if (r !== null) {
1205
+ lastGroup = hole;
1206
+ lastGroupVal = r;
1207
+ lastGroupIdx = 0;
1208
+ if (!Array.isArray(r) && result === null) {
1209
+ result = {
1210
+ t: [s],
1211
+ h: [],
1212
+ p: []
1213
+ };
1214
+ s = "";
1215
+ }
1216
+ }
1217
+ }
1218
+ if (lastGroup === hole) {
1219
+ if (Array.isArray(lastGroupVal)) {
1220
+ value = lastGroupVal[lastGroupIdx++];
1221
+ hasValue = true;
1222
+ } else {
1223
+ result.h.push(ssrGroupSlot(lastGroupVal.fn, lastGroupIdx++));
1224
+ result.p.push(lastGroupVal.p);
1225
+ result.t.push("");
1226
+ }
1227
+ }
1228
+ if (hasValue) {
1229
+ const vt = typeof value;
1230
+ if (vt === "string" || vt === "number") {
1231
+ if (result === null) s += value;else result.t[result.t.length - 1] += value;
1232
+ } else if (value == null || vt === "boolean") ; else if (result !== null) {
1233
+ resolveSSRNode(value, result);
1234
+ } else {
1235
+ const rs = tryResolveString(value);
1236
+ if (typeof rs === "string") {
1237
+ s += rs;
1238
+ } else {
1239
+ result = {
1240
+ t: [s],
1241
+ h: [],
1242
+ p: []
1243
+ };
1244
+ s = "";
1245
+ if (rs.merge !== undefined) mergeTemplateInto(result, rs.merge);else resolveSSRNode(rs.bail, result);
1246
+ }
1247
+ }
1248
+ }
1249
+ } else if (result !== null) {
1250
+ resolveSSRNode(hole, result);
1251
+ } else if (ht === "function") {
1252
+ const r = tryResolveFunctionHole(hole);
1253
+ if (typeof r === "string") s += r;else {
1254
+ result = {
1255
+ t: [s],
1256
+ h: [],
1257
+ p: []
1258
+ };
1259
+ s = "";
1260
+ appendResolvedNode(result, r);
1261
+ }
1262
+ } else {
1263
+ const r = tryResolveString(hole);
1264
+ if (typeof r === "string") {
1265
+ s += r;
1266
+ } else {
1267
+ result = {
1268
+ t: [s],
1269
+ h: [],
1270
+ p: []
1271
+ };
1272
+ s = "";
1273
+ appendResolvedNode(result, r);
1274
+ }
1275
+ }
1276
+ const next = t[i];
1277
+ if (result === null) s += next;else result.t[result.t.length - 1] += next;
1278
+ }
1279
+ if (result === null) return {
1280
+ t: s
1281
+ };
1282
+ return result;
1283
+ }
1284
+ function escape(s, attr) {
1285
+ const t = typeof s;
1286
+ if (t !== "string") {
1287
+ if (!attr && Array.isArray(s)) {
1288
+ const joined = tryJoinPlainSSRArray(s);
1289
+ if (joined !== undefined) return joined;
1290
+ s = s.slice();
1291
+ for (let i = 0; i < s.length; i++) s[i] = escape(s[i]);
1292
+ return s;
1293
+ }
1294
+ if (attr) {
1295
+ if (s == null || t === "boolean" || t === "number") return s;
1296
+ return escape(String(s), attr);
1297
+ }
1298
+ return s;
1299
+ }
1300
+ const i = s.search(attr ? ESCAPE_ATTR : ESCAPE_CONTENT);
1301
+ if (i < 0) return s;
1302
+ return escapeSlow(s, attr, i);
1303
+ }
1304
+ const ESCAPE_CONTENT = /[&<]/;
1305
+ const ESCAPE_ATTR = /[&"]/;
1306
+ function escapeSlow(s, attr, start) {
1307
+ const delim = attr ? '"' : "<";
1308
+ const delimCode = attr ? 34 : 60;
1309
+ const escDelim = attr ? "&quot;" : "&lt;";
1310
+ const c0 = s.charCodeAt(start);
1311
+ let iDelim = c0 === delimCode ? start : s.indexOf(delim, start);
1312
+ let iAmp = c0 === 38 ? start : s.indexOf("&", start);
1313
+ let left = 0,
1314
+ out = "";
1315
+ while (iDelim >= 0 && iAmp >= 0) {
1316
+ if (iDelim < iAmp) {
1317
+ if (left < iDelim) out += s.substring(left, iDelim);
1318
+ out += escDelim;
1319
+ left = iDelim + 1;
1320
+ iDelim = s.indexOf(delim, left);
1321
+ } else {
1322
+ if (left < iAmp) out += s.substring(left, iAmp);
1323
+ out += "&amp;";
1324
+ left = iAmp + 1;
1325
+ iAmp = s.indexOf("&", left);
1326
+ }
1327
+ }
1328
+ if (iDelim >= 0) {
1329
+ do {
1330
+ if (left < iDelim) out += s.substring(left, iDelim);
1331
+ out += escDelim;
1332
+ left = iDelim + 1;
1333
+ iDelim = s.indexOf(delim, left);
1334
+ } while (iDelim >= 0);
1335
+ } else while (iAmp >= 0) {
1336
+ if (left < iAmp) out += s.substring(left, iAmp);
1337
+ out += "&amp;";
1338
+ left = iAmp + 1;
1339
+ iAmp = s.indexOf("&", left);
1340
+ }
1341
+ return left < s.length ? out + s.substring(left) : out;
1342
+ }
1343
+ function tryJoinPlainSSRArray(nodes) {
1344
+ if (nodes.length === 0) return undefined;
1345
+ let out = "";
1346
+ for (let i = 0, len = nodes.length; i < len; i++) {
1347
+ const node = nodes[i];
1348
+ if (node == null || typeof node !== "object" || node.h || typeof node.t !== "string") {
1349
+ return undefined;
1350
+ }
1351
+ out += node.t;
1352
+ }
1353
+ return out;
1354
+ }
1355
+ function queue(fn) {
1356
+ return Promise.resolve().then(fn);
1357
+ }
1358
+ function allSettled(promises) {
1359
+ let size = promises.size;
1360
+ return Promise.allSettled(promises).then(() => {
1361
+ if (promises.size !== size) return allSettled(promises);
1362
+ return;
1363
+ });
1364
+ }
1365
+ function resolveAssetsHtml(assets) {
1366
+ if (!assets || !assets.length) return "";
1367
+ let out = "";
1368
+ for (let i = 0, len = assets.length; i < len; i++) out += assets[i]();
1369
+ return out;
1370
+ }
1371
+ function assembleDocument(html, assetsHtml, emittedAssets, inlineStyles, scripts, nonce, headTags, onHead) {
1372
+ const scriptTag = scripts ? `<script${nonce ? ` nonce="${nonce}"` : ""}>${scripts}</script>` : "";
1373
+ const headTagsHtml = headTags ? headTags.html : "";
1374
+ const headPrelude = headTags ? headTags.prelude : "";
1375
+ if (!onHead && !assetsHtml && !headTagsHtml && !headPrelude && !(emittedAssets && emittedAssets.size) && !(inlineStyles && inlineStyles.size)) {
1376
+ if (!scriptTag) return html;
1377
+ const xs = html.indexOf("<!--xs-->");
1378
+ return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
1379
+ }
1380
+ if (headPrelude) {
1381
+ const open = html.match(/<head(?:\s[^>]*)?>/);
1382
+ if (open) {
1383
+ const at = open.index + open[0].length;
1384
+ html = html.slice(0, at) + headPrelude + html.slice(at);
1385
+ }
1386
+ }
1387
+ const headIdx = html.indexOf("</head>");
1388
+ if (headIdx === -1) {
1389
+ if (onHead) {
1390
+ onHead(headPrelude + headTagsHtml + (assetsHtml || "") + renderHeadAssets(emittedAssets, inlineStyles, nonce));
1391
+ }
1392
+ if (!scriptTag) return html;
1393
+ const xs = html.indexOf("<!--xs-->");
1394
+ return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
1395
+ }
1396
+ const head = headTagsHtml + (assetsHtml || "") + renderHeadAssets(emittedAssets, inlineStyles, nonce);
1397
+ if (!scriptTag) return html.slice(0, headIdx) + head + html.slice(headIdx);
1398
+ const xsIdx = html.indexOf("<!--xs-->");
1399
+ if (xsIdx === -1) return html.slice(0, headIdx) + head + html.slice(headIdx) + scriptTag;
1400
+ return xsIdx < headIdx ? html.slice(0, xsIdx) + scriptTag + html.slice(xsIdx, headIdx) + head + html.slice(headIdx) : html.slice(0, headIdx) + head + html.slice(headIdx, xsIdx) + scriptTag + html.slice(xsIdx);
1401
+ }
1402
+ function renderHeadAssets(emittedAssets, inlineStyles, nonce) {
1403
+ let head = "";
1404
+ if (emittedAssets && emittedAssets.size) {
1405
+ for (const url of emittedAssets) {
1406
+ head += isCssUrl(url) ? `<link rel="stylesheet" href="${url}">` : `<link rel="modulepreload" href="${url}">`;
1407
+ }
1408
+ }
1409
+ if (inlineStyles && inlineStyles.size) {
1410
+ for (const entry of inlineStyles.values()) {
1411
+ if (entry.emitted) continue;
1412
+ entry.emitted = true;
1413
+ head += renderInlineStyle(entry, nonce);
1414
+ }
1415
+ }
1416
+ return head;
1417
+ }
1418
+ function serializeFragmentAssets(key, boundaryModules, context) {
1419
+ const map = boundaryModules.get(key);
1420
+ if (!map || !Object.keys(map).length) return;
1421
+ context.serialize(key + "_assets", map);
1422
+ }
1423
+ function propagateBoundaryStyles(childKey, parentKey, tracking) {
1424
+ const childStyles = tracking.getBoundaryStyles(childKey);
1425
+ if (!childStyles) return;
1426
+ let parentStyles = tracking.boundaryStyles.get(parentKey);
1427
+ if (!parentStyles) {
1428
+ parentStyles = new Set();
1429
+ tracking.boundaryStyles.set(parentKey, parentStyles);
1430
+ }
1431
+ for (const url of childStyles) {
1432
+ parentStyles.add(url);
1433
+ }
1434
+ }
1435
+ function collectStreamStyles(key, tracking, headStyles) {
1436
+ const styles = tracking.getBoundaryStyles(key);
1437
+ const links = [];
1438
+ const inline = [];
1439
+ if (!styles) return {
1440
+ links,
1441
+ inline
1442
+ };
1443
+ for (const entry of styles) {
1444
+ if (typeof entry === "string") {
1445
+ if (!headStyles || !headStyles.has(entry)) links.push(entry);
1446
+ } else if (entry.emitted) {
1447
+ continue;
1448
+ } else if (entry.attrHtml !== undefined) {
1449
+ entry.emitted = true;
1450
+ links.push(entry);
1451
+ } else {
1452
+ entry.emitted = true;
1453
+ inline.push(entry);
1454
+ }
1455
+ }
1456
+ return {
1457
+ links,
1458
+ inline
1459
+ };
1460
+ }
1461
+ function escapeStyleContent(content) {
1462
+ return content.replace(/<\/(style)/gi, "<\\/$1");
1463
+ }
1464
+ function renderInlineStyle(entry, nonce) {
1465
+ let attrs = "";
1466
+ if (entry.attrs) {
1467
+ for (const name in entry.attrs) {
1468
+ attrs += ` ${name}="${escape(String(entry.attrs[name]), true)}"`;
1469
+ }
1470
+ }
1471
+ return `<style${nonce ? ` nonce="${nonce}"` : ""} data-asset="${escape(entry.id, true)}"${attrs}>${escapeStyleContent(entry.content)}</style>`;
1472
+ }
1473
+ function waitForFragments(registry, key) {
1474
+ for (const k of [...registry.keys()].reverse()) {
1475
+ if (key.startsWith(k)) return k;
1476
+ }
1477
+ return false;
1478
+ }
1479
+ function replacePlaceholder(html, key, value) {
1480
+ const marker = `<template id="pl-${key}">`;
1481
+ const close = `<!--pl-${key}-->`;
1482
+ const first = html.indexOf(marker);
1483
+ if (first === -1) return html;
1484
+ const last = html.indexOf(close, first + marker.length);
1485
+ return html.slice(0, first) + value + html.slice(last + close.length);
1486
+ }
1487
+ function tryResolveString(node) {
1488
+ const t = typeof node;
1489
+ if (t === "string") return node;
1490
+ if (t === "number") return "" + node;
1491
+ if (node == null || t === "boolean") return "";
1492
+ if (t === "object") {
1493
+ if (Array.isArray(node)) {
1494
+ const joined = tryJoinPlainSSRArray(node);
1495
+ if (joined !== undefined) return joined;
1496
+ let s = "";
1497
+ let prevNonObj = false;
1498
+ for (let i = 0, len = node.length; i < len; i++) {
1499
+ const item = node[i];
1500
+ const itemNonObj = item !== null && typeof item !== "object";
1501
+ if (prevNonObj && itemNonObj) s += "<!--!$-->";
1502
+ prevNonObj = itemNonObj;
1503
+ const r = tryResolveString(item);
1504
+ if (typeof r !== "string") return {
1505
+ bail: node
1506
+ };
1507
+ s += r;
1508
+ }
1509
+ return s;
1510
+ }
1511
+ if (node.h && node.h.length > 0) return {
1512
+ merge: node
1513
+ };
1514
+ if (node.t === undefined) {
1515
+ console.warn(`Unrecognized value. Skipped inserting`, node);
1516
+ return "";
1517
+ }
1518
+ return Array.isArray(node.t) ? node.t[0] : node.t;
1519
+ }
1520
+ if (t === "function") {
1521
+ let v;
1522
+ try {
1523
+ v = node();
1524
+ } catch (err) {
1525
+ return buildAsyncWrap(err, node) || "";
1526
+ }
1527
+ return tryResolveString(v);
1528
+ }
1529
+ return "";
1530
+ }
1531
+ function resolveSSRNode(node, result = {
1532
+ t: [""],
1533
+ h: [],
1534
+ p: []
1535
+ }, top) {
1536
+ const t = typeof node;
1537
+ if (t === "string" || t === "number") {
1538
+ result.t[result.t.length - 1] += node;
1539
+ } else if (node == null || t === "boolean") ; else if (Array.isArray(node)) {
1540
+ let prevNonObj = false;
1541
+ for (let i = 0, len = node.length; i < len; i++) {
1542
+ const item = node[i];
1543
+ const itemNonObj = item !== null && typeof item !== "object";
1544
+ if (!top && prevNonObj && itemNonObj) result.t[result.t.length - 1] += `<!--!$-->`;
1545
+ prevNonObj = itemNonObj;
1546
+ resolveSSRNode(item, result);
1547
+ }
1548
+ } else if (t === "object") {
1549
+ if (node.h) {
1550
+ result.t[result.t.length - 1] += node.t[0];
1551
+ if (node.t.length > 1) {
1552
+ result.t.push(...node.t.slice(1));
1553
+ result.h.push(...node.h);
1554
+ result.p.push(...node.p);
1555
+ }
1556
+ } else if (node.t !== undefined) {
1557
+ result.t[result.t.length - 1] += node.t;
1558
+ } else console.warn(`Unrecognized value. Skipped inserting`, node);
1559
+ } else if (t === "function") {
1560
+ try {
1561
+ resolveSSRNode(node(), result);
1562
+ } catch (err) {
1563
+ const wrap = buildAsyncWrap(err, node);
1564
+ if (wrap) {
1565
+ result.h.push(wrap.fn);
1566
+ result.p.push(wrap.p);
1567
+ result.t.push("");
1568
+ }
1569
+ }
1570
+ }
1571
+ return result;
1572
+ }
1573
+ function resolveSSRSync(node) {
1574
+ const res = resolveSSRNode(node);
1575
+ if (!res.h.length) return res.t[0];
1576
+ throw new Error("This value cannot be rendered synchronously. Are you missing a boundary?");
1577
+ }
1578
+
1579
+ function frameAddress(id, args) {
1580
+ return args && args.length ? id + ":" + hashArguments(args) : id;
1581
+ }
1582
+ function hashArguments(args) {
1583
+ let hash = 0;
1584
+ const text = stableString(args);
1585
+ for (let i = 0; i < text.length; i++) {
1586
+ hash = (hash << 5) - hash + text.charCodeAt(i);
1587
+ hash |= 0;
1588
+ }
1589
+ return (hash >>> 0).toString(36);
1590
+ }
1591
+ function stableString(value, seen) {
1592
+ if (value === null || typeof value !== "object") {
1593
+ return typeof value === "bigint" ? value + "n" : String(value);
1594
+ }
1595
+ if (value instanceof Date) return "Date:" + value.getTime();
1596
+ seen || (seen = new Set());
1597
+ if (seen.has(value)) return "~";
1598
+ seen.add(value);
1599
+ if (value instanceof Map) {
1600
+ const entries = [];
1601
+ for (const [k, v] of value) {
1602
+ entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
1603
+ }
1604
+ return "Map{" + entries.sort().join(",") + "}";
1605
+ }
1606
+ if (value instanceof Set) {
1607
+ const members = [];
1608
+ for (const v of value) members.push(stableString(v, seen));
1609
+ return "Set{" + members.sort().join(",") + "}";
1610
+ }
1611
+ if (Array.isArray(value)) {
1612
+ let out = "[";
1613
+ for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
1614
+ return out + "]";
1615
+ }
1616
+ const keys = Object.keys(value).sort();
1617
+ let out = "{";
1618
+ for (let i = 0; i < keys.length; i++) {
1619
+ out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
1620
+ }
1621
+ return out + "}";
1622
+ }
1623
+ const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
1624
+ function createChunk(data) {
1625
+ const encodeData = new TextEncoder().encode(data);
1626
+ const bytes = encodeData.length;
1627
+ const baseHex = bytes.toString(16);
1628
+ const totalHex = "00000000".substring(0, 8 - baseHex.length) + baseHex;
1629
+ const head = new TextEncoder().encode(`;0x${totalHex};`);
1630
+ const chunk = new Uint8Array(12 + bytes);
1631
+ chunk.set(head);
1632
+ chunk.set(encodeData, 12);
1633
+ return chunk;
1634
+ }
1635
+ class ChunkReader {
1636
+ constructor(stream) {
1637
+ this.reader = stream.getReader();
1638
+ this.buffer = new Uint8Array(0);
1639
+ this.done = false;
1640
+ }
1641
+ async readChunk() {
1642
+ const chunk = await this.reader.read();
1643
+ if (!chunk.done) {
1644
+ const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
1645
+ newBuffer.set(this.buffer);
1646
+ newBuffer.set(chunk.value, this.buffer.length);
1647
+ this.buffer = newBuffer;
1648
+ } else {
1649
+ this.done = true;
1650
+ }
1651
+ }
1652
+ async next() {
1653
+ while (this.buffer.length < 12) {
1654
+ if (this.done) {
1655
+ if (this.buffer.length === 0) return {
1656
+ done: true,
1657
+ value: undefined
1658
+ };
1659
+ throw new Error("Malformed server function stream.");
1660
+ }
1661
+ await this.readChunk();
1662
+ }
1663
+ const head = new TextDecoder().decode(this.buffer.subarray(1, 11));
1664
+ const bytes = Number.parseInt(head, 16);
1665
+ if (Number.isNaN(bytes)) {
1666
+ throw new Error("Malformed server function stream.");
1667
+ }
1668
+ while (bytes > this.buffer.length - 12) {
1669
+ if (this.done) {
1670
+ throw new Error("Malformed server function stream.");
1671
+ }
1672
+ await this.readChunk();
1673
+ }
1674
+ const partial = new TextDecoder().decode(this.buffer.subarray(12, 12 + bytes));
1675
+ this.buffer = this.buffer.subarray(12 + bytes);
1676
+ return {
1677
+ done: false,
1678
+ value: partial
1679
+ };
1680
+ }
1681
+ async drain(interpret) {
1682
+ while (true) {
1683
+ const result = await this.next();
1684
+ if (result.done) {
1685
+ break;
1686
+ }
1687
+ interpret(result.value);
1688
+ }
1689
+ }
1690
+ }
1691
+ function serializeStream(value, codecOptions) {
1692
+ return new ReadableStream({
1693
+ start(controller) {
1694
+ serializeJSON(value, {
1695
+ ...codecOptions,
1696
+ onParse(node) {
1697
+ controller.enqueue(createChunk(JSON.stringify(node)));
1698
+ },
1699
+ onDone() {
1700
+ controller.close();
1701
+ },
1702
+ onError(error) {
1703
+ controller.error(error);
1704
+ }
1705
+ });
1706
+ }
1707
+ });
1708
+ }
1709
+
1710
+ const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
1711
+ function isResponseEnvelope(value) {
1712
+ return !!(value && typeof value === "object" && value[ENVELOPE]);
1713
+ }
1714
+
1715
+ const INVOCATIONS = new WeakMap();
1716
+ function getEventServerFunctionInvocation(event) {
1717
+ return event && INVOCATIONS.get(event);
1718
+ }
1719
+
1720
+ const FRAME_STREAM_HEADER = "X-Frame-Stream";
1721
+ function isFrameStreamResponse(response) {
1722
+ return response.headers.has(FRAME_STREAM_HEADER);
1723
+ }
1724
+ const SERVER_COMPONENT = /*#__PURE__*/Symbol.for("dom-expressions.server-component");
1725
+ const SERVER_COMPONENT_SOURCE = /*#__PURE__*/Symbol.for("dom-expressions.server-component-source");
1726
+ const SERVER_COMPONENT_ADDRESS = /*#__PURE__*/Symbol.for("dom-expressions.server-component-address");
1727
+ function parseServerComponent(value, ctx) {
1728
+ return {
1729
+ id: ctx.parse(value[SERVER_COMPONENT]),
1730
+ address: ctx.parse(value[SERVER_COMPONENT_ADDRESS])
1731
+ };
1732
+ }
1733
+ const ServerComponentPlugin = /*#__PURE__*/seroval.createPlugin({
1734
+ tag: "dom-expressions/server-component",
1735
+ test(value) {
1736
+ return typeof value === "function" && SERVER_COMPONENT in value;
1737
+ },
1738
+ parse: {
1739
+ sync: parseServerComponent,
1740
+ async async(value, ctx) {
1741
+ return {
1742
+ id: await ctx.parse(value[SERVER_COMPONENT]),
1743
+ address: await ctx.parse(value[SERVER_COMPONENT_ADDRESS])
1744
+ };
1745
+ },
1746
+ stream: parseServerComponent
1747
+ },
1748
+ serialize(node, ctx) {
1749
+ return "self._$SC.r(" + ctx.serialize(node.id) + "," + ctx.serialize(node.address) + ")";
1750
+ },
1751
+ deserialize(node, ctx) {
1752
+ const id = ctx.deserialize(node.id);
1753
+ ctx.deserialize(node.address);
1754
+ return globalThis._$SC.r(id);
1755
+ }
1756
+ });
1757
+ function flightCodec(codec) {
1758
+ const plugins = codec && codec.plugins || [];
1759
+ for (const plugin of plugins) {
1760
+ if (plugin && plugin.tag === "dom-expressions/server-component") return codec;
1761
+ }
1762
+ return {
1763
+ ...codec,
1764
+ plugins: [...plugins, ServerComponentPlugin]
1765
+ };
1766
+ }
1767
+
1768
+ function serverOwned(render) {
1769
+ return solidJs.NoHydration ? solidJs.NoHydration({
1770
+ get children() {
1771
+ return render();
1772
+ }
1773
+ }) : render();
1774
+ }
1775
+ function serverComponentScope(render) {
1776
+ return solidJs.runInServerComponentScope ? solidJs.runInServerComponentScope(render) : render();
1777
+ }
1778
+ function createFrameSink(emit, frame) {
1779
+ const {
1780
+ id,
1781
+ version
1782
+ } = frame;
1783
+ const styledKeys = new Set();
1784
+ const regionKeys = new Map();
1785
+ const frameOf = key => regionKeys.get(key) || id;
1786
+ return {
1787
+ tagRegion(key, childId) {
1788
+ if (!regionKeys.has(key)) regionKeys.set(key, childId);
1789
+ },
1790
+ shell(html, meta = {}) {
1791
+ if (meta.preloads && meta.preloads.size) {
1792
+ const styles = [];
1793
+ const modules = [];
1794
+ for (const url of meta.preloads) {
1795
+ (url.endsWith(".css") ? styles : modules).push(url);
1796
+ }
1797
+ const chunk = {
1798
+ type: "assets",
1799
+ id,
1800
+ version,
1801
+ key: ""
1802
+ };
1803
+ if (styles.length) chunk.styles = styles;
1804
+ if (modules.length) chunk.modules = modules;
1805
+ emit(chunk);
1806
+ }
1807
+ emit({
1808
+ type: "html",
1809
+ id,
1810
+ version,
1811
+ html
1812
+ });
1813
+ },
1814
+ data(record) {
1815
+ if (record && typeof record.key === "string" && (record.key.endsWith("_fr") || /^\d+$/.test(record.key))) {
1816
+ return;
1817
+ }
1818
+ if (typeof record === "string") {
1819
+ emit({
1820
+ type: "data",
1821
+ id,
1822
+ version,
1823
+ payload: record
1824
+ });
1825
+ } else {
1826
+ emit({
1827
+ type: "data",
1828
+ id,
1829
+ version,
1830
+ key: record.key,
1831
+ node: record.node,
1832
+ initial: record.initial
1833
+ });
1834
+ }
1835
+ },
1836
+ fragment(key, value, meta = {}) {
1837
+ const fid = frameOf(key);
1838
+ const links = meta.styles && meta.styles.links || [];
1839
+ const inline = meta.styles && meta.styles.inline || [];
1840
+ if (links.length || inline.length) {
1841
+ if (links.length) styledKeys.add(key);
1842
+ const chunk = {
1843
+ type: "assets",
1844
+ id: fid,
1845
+ version,
1846
+ key
1847
+ };
1848
+ if (links.length) {
1849
+ chunk.styles = links.map(e => typeof e === "string" ? e : e.attrs ? {
1850
+ href: e.href,
1851
+ attrs: e.attrs
1852
+ } : e.href);
1853
+ }
1854
+ if (inline.length) {
1855
+ chunk.inlineStyles = inline.map(e => ({
1856
+ id: e.id,
1857
+ content: e.content,
1858
+ attrs: e.attrs
1859
+ }));
1860
+ }
1861
+ emit(chunk);
1862
+ }
1863
+ emit({
1864
+ type: "fragment",
1865
+ id: fid,
1866
+ version,
1867
+ key,
1868
+ html: value
1869
+ });
1870
+ if (meta.error) {
1871
+ emit({
1872
+ type: "error",
1873
+ id: fid,
1874
+ version,
1875
+ key,
1876
+ error: {
1877
+ message: String(meta.error && meta.error.message || meta.error)
1878
+ }
1879
+ });
1880
+ }
1881
+ if (!meta.revealGroup) {
1882
+ emit({
1883
+ type: "reveal",
1884
+ id: fid,
1885
+ version,
1886
+ keys: [key],
1887
+ waitForStyles: !!links.length
1888
+ });
1889
+ }
1890
+ },
1891
+ reveal(keys, meta = {}) {
1892
+ const byFrame = new Map();
1893
+ for (const key of keys) {
1894
+ const fid = frameOf(key);
1895
+ let group = byFrame.get(fid);
1896
+ if (!group) byFrame.set(fid, group = []);
1897
+ group.push(key);
1898
+ }
1899
+ for (const [fid, groupKeys] of byFrame) {
1900
+ let waitForStyles = false;
1901
+ for (const key of groupKeys) if (styledKeys.has(key)) waitForStyles = true;
1902
+ const chunk = {
1903
+ type: "reveal",
1904
+ id: fid,
1905
+ version,
1906
+ keys: groupKeys,
1907
+ waitForStyles
1908
+ };
1909
+ if (meta.fallback) chunk.fallback = true;
1910
+ emit(chunk);
1911
+ }
1912
+ },
1913
+ asset(type, url) {
1914
+ if (type !== "module") return;
1915
+ emit({
1916
+ type: "assets",
1917
+ id,
1918
+ version,
1919
+ key: "",
1920
+ modules: [url]
1921
+ });
1922
+ },
1923
+ end() {
1924
+ emit({
1925
+ type: "complete",
1926
+ id,
1927
+ version
1928
+ });
1929
+ },
1930
+ error(errorId, error) {
1931
+ emit({
1932
+ type: "error",
1933
+ id,
1934
+ version,
1935
+ key: errorId,
1936
+ error
1937
+ });
1938
+ },
1939
+ slot(key, args) {
1940
+ emit({
1941
+ type: "slot",
1942
+ id,
1943
+ version,
1944
+ key,
1945
+ args
1946
+ });
1947
+ },
1948
+ region(childId, html) {
1949
+ emit({
1950
+ type: "html",
1951
+ id: childId,
1952
+ version,
1953
+ html
1954
+ });
1955
+ }
1956
+ };
1957
+ }
1958
+ function renderToFrameStream(code, options = {}) {
1959
+ return frameStream(() => code, options);
1960
+ }
1961
+ function renderServerComponent(component, options = {}) {
1962
+ return frameStream((sink, frame) => {
1963
+ const props = createSlotProps(sink, frame);
1964
+ return () => serverComponentScope(() => component(props));
1965
+ }, options);
1966
+ }
1967
+ function frameStream(makeCode, options) {
1968
+ const {
1969
+ id = "",
1970
+ version = 1
1971
+ } = options.frame || {};
1972
+ const frame = {
1973
+ id,
1974
+ version
1975
+ };
1976
+ function stream(w) {
1977
+ const emit = chunk => w.write(chunk);
1978
+ const sink = createFrameSink(emit, frame);
1979
+ emit({
1980
+ type: "start",
1981
+ id,
1982
+ version
1983
+ });
1984
+ const code = makeCode(sink, frame);
1985
+ try {
1986
+ renderToStream(() => serverOwned(code), {
1987
+ serializer: createJSONSerializer,
1988
+ ...options,
1989
+ sink
1990
+ }).pipe({
1991
+ write() {},
1992
+ end() {
1993
+ sink.end();
1994
+ w.end && w.end();
1995
+ }
1996
+ });
1997
+ } catch (err) {
1998
+ sink.error("", err instanceof Error ? err.message : String(err));
1999
+ sink.end();
2000
+ w.end && w.end();
2001
+ }
2002
+ }
2003
+ return {
2004
+ pipe: stream,
2005
+ then(onFulfilled, onRejected) {
2006
+ return new Promise((resolve, reject) => {
2007
+ const chunks = [];
2008
+ try {
2009
+ stream({
2010
+ write: chunk => chunks.push(chunk),
2011
+ end: () => resolve(chunks)
2012
+ });
2013
+ } catch (err) {
2014
+ reject(err);
2015
+ }
2016
+ }).then(onFulfilled, onRejected);
2017
+ }
2018
+ };
2019
+ }
2020
+ function slotRange(occurrence) {
2021
+ return {
2022
+ t: `<!--slot:${occurrence}:start--><!--slot:${occurrence}:end-->`
2023
+ };
2024
+ }
2025
+ const OCCURRENCE_UNSAFE = /[^A-Za-z0-9_.-]/g;
2026
+ function encodeOccurrenceKey(key) {
2027
+ return String(key).replace(OCCURRENCE_UNSAFE, c => {
2028
+ const code = c.codePointAt(0);
2029
+ return "%" + (code < 16 ? "0" : "") + code.toString(16);
2030
+ });
2031
+ }
2032
+ function occurrenceId(prop, raw, counts) {
2033
+ const k = raw.$key;
2034
+ if (typeof k === "string" || typeof k === "number") {
2035
+ return `${prop}#${encodeOccurrenceKey(k)}`;
2036
+ }
2037
+ const n = counts[prop] || 0;
2038
+ counts[prop] = n + 1;
2039
+ return `${prop}#${n}`;
2040
+ }
2041
+ function createDocumentSlotProps(clientProps, frameId) {
2042
+ const counts = Object.create(null);
2043
+ const getters = new Map();
2044
+ const range = (occurrence, content) => [{
2045
+ t: `<!--slot:${occurrence}:start-->`
2046
+ }, content, {
2047
+ t: `<!--slot:${occurrence}:end-->`
2048
+ }];
2049
+ const zoneOwner = solidJs.getOwner ? solidJs.getOwner() : null;
2050
+ const scoped = (occurrence, render) => {
2051
+ const id = `sc-${frameId}-${occurrence}-`;
2052
+ const run = () => solidJs.Hydration ? solidJs.Hydration({
2053
+ id,
2054
+ get children() {
2055
+ return render();
2056
+ }
2057
+ }) : runWithHydrationScope(id, render);
2058
+ return zoneOwner ? solidJs.runWithOwner(zoneOwner, run) : run();
2059
+ };
2060
+ return new Proxy(Object.create(null), {
2061
+ has() {
2062
+ return true;
2063
+ },
2064
+ get(_, prop) {
2065
+ if (typeof prop !== "string") return undefined;
2066
+ if (prop === "then") return undefined;
2067
+ let fn = getters.get(prop);
2068
+ if (!fn) {
2069
+ fn = (...callArgs) => {
2070
+ if (callArgs.length === 0 || callArgs[0] === undefined) {
2071
+ return scoped(prop, () => {
2072
+ const value = clientProps[prop];
2073
+ return range(prop, typeof value === "function" ? value() : value);
2074
+ });
2075
+ }
2076
+ const raw = callArgs[0];
2077
+ const occurrence = occurrenceId(prop, raw, counts);
2078
+ const slot = clientProps[prop];
2079
+ if (typeof slot !== "function") return range(occurrence, undefined);
2080
+ const resolved = {};
2081
+ const vals = {};
2082
+ for (const key of Object.keys(raw)) {
2083
+ if (key === "$key") continue;
2084
+ let value = raw[key];
2085
+ for (let d = 0; typeof value === "function" && d < 16; d++) value = value();
2086
+ vals[key] = value;
2087
+ }
2088
+ const regions = [];
2089
+ for (const key of Object.keys(vals)) {
2090
+ const value = vals[key];
2091
+ if (isServerContent(value)) {
2092
+ const childId = `${frameId}.${occurrence}.${key}`;
2093
+ const region = {
2094
+ key,
2095
+ childId,
2096
+ value,
2097
+ used: false,
2098
+ locked: false
2099
+ };
2100
+ regions.push(region);
2101
+ resolved[key] = () => {
2102
+ if (region.locked) return [];
2103
+ region.used = true;
2104
+ return [{
2105
+ t: frameElementOpen(childId)
2106
+ }, value, {
2107
+ t: FRAME_ELEMENT_CLOSE
2108
+ }];
2109
+ };
2110
+ } else {
2111
+ resolved[key] = value;
2112
+ }
2113
+ }
2114
+ const out = scoped(occurrence, () => range(occurrence, slot(resolved)));
2115
+ const unused = regions.filter(r => !r.used);
2116
+ if (solidJs.sharedConfig.context) {
2117
+ const args = {};
2118
+ let any = false;
2119
+ for (const key of Object.keys(vals)) {
2120
+ const value = vals[key];
2121
+ const region = regions.find(r => r.key === key);
2122
+ if (region) {
2123
+ if (!region.used) {
2124
+ args[key] = {
2125
+ $frame: region.childId
2126
+ };
2127
+ any = true;
2128
+ }
2129
+ continue;
2130
+ }
2131
+ if (isServerContent(value)) continue;
2132
+ args[key] = value;
2133
+ any = true;
2134
+ }
2135
+ if (any) solidJs.sharedConfig.context.serialize(`sc:slot:${frameId}:${occurrence}`, args);
2136
+ for (const region of unused) {
2137
+ region.locked = true;
2138
+ solidJs.sharedConfig.context.serialize(`sc:region:${region.childId}`, resolveRegionHtml(solidJs.sharedConfig.context, region.value));
2139
+ }
2140
+ }
2141
+ return out;
2142
+ };
2143
+ getters.set(prop, fn);
2144
+ }
2145
+ return fn;
2146
+ }
2147
+ });
2148
+ }
2149
+ const FRAME_TAG = "dx-frame";
2150
+ const FRAME_ID_ATTR = "data-fid";
2151
+ function frameElementOpen(id) {
2152
+ const escaped = solidJs.sharedConfig.context ? solidJs.sharedConfig.context.escape(String(id), true) : String(id);
2153
+ return `<${FRAME_TAG} ${FRAME_ID_ATTR}="${escaped}" style="display:contents">`;
2154
+ }
2155
+ const FRAME_ELEMENT_CLOSE = `</${FRAME_TAG}>`;
2156
+ function frameTransformDirectResult(value, {
2157
+ id,
2158
+ args
2159
+ }) {
2160
+ if (typeof value !== "function") return value;
2161
+ const component = value;
2162
+ const wrapped = props => [{
2163
+ t: frameElementOpen(id)
2164
+ },
2165
+ serverOwned(() => {
2166
+ const slotProps = createDocumentSlotProps(props, id);
2167
+ return serverComponentScope(() => component(slotProps));
2168
+ }), {
2169
+ t: FRAME_ELEMENT_CLOSE
2170
+ }];
2171
+ wrapped[SERVER_COMPONENT] = id;
2172
+ wrapped[SERVER_COMPONENT_SOURCE] = component;
2173
+ wrapped[SERVER_COMPONENT_ADDRESS] = frameAddress(id, args);
2174
+ return wrapped;
2175
+ }
2176
+ function resolveRegionHtml(ctx, node) {
2177
+ const res = ctx.resolve(node);
2178
+ if (!res || !res.t) return String(res ?? "");
2179
+ if (!res.h || !res.h.length) return res.t[0];
2180
+ return Promise.all(res.p).then(() => {
2181
+ let out = Promise.resolve(res.t[0]);
2182
+ for (let i = 0; i < res.h.length; i++) {
2183
+ const hole = res.h[i];
2184
+ const tail = res.t[i + 1];
2185
+ out = out.then(acc => Promise.resolve(resolveRegionHtml(ctx, hole)).then(part => acc + part + tail));
2186
+ }
2187
+ return out;
2188
+ });
2189
+ }
2190
+ const SERVER_COMPONENT_BOOTSTRAP = "self._$SC={c:{},a:{},r(i,a){a&&(this.a[a]=i,this.reg&&this.reg(a,i));return this.c[i]||(this.c[i]=(p)=>self._$SC.impl(i,p))}};";
2191
+ function isServerContent(value) {
2192
+ if (value && typeof value === "object") {
2193
+ if ("t" in value) return true;
2194
+ if (Array.isArray(value) && value.length > 0) {
2195
+ for (const item of value) {
2196
+ if (!(item && typeof item === "object" && "t" in item)) return false;
2197
+ }
2198
+ return true;
2199
+ }
2200
+ }
2201
+ return false;
2202
+ }
2203
+ function createSlotProps(sink, frame) {
2204
+ const counts = Object.create(null);
2205
+ const getters = new Map();
2206
+ return new Proxy(Object.create(null), {
2207
+ has() {
2208
+ return true;
2209
+ },
2210
+ get(_, prop) {
2211
+ if (typeof prop !== "string") return undefined;
2212
+ if (prop === "then") return undefined;
2213
+ let fn = getters.get(prop);
2214
+ if (!fn) {
2215
+ fn = (...callArgs) => {
2216
+ if (callArgs.length === 0 || callArgs[0] === undefined) {
2217
+ return slotRange(prop);
2218
+ }
2219
+ const raw = callArgs[0];
2220
+ const occurrence = occurrenceId(prop, raw, counts);
2221
+ const args = {};
2222
+ for (const key of Object.keys(raw)) {
2223
+ if (key === "$key") continue;
2224
+ const childId = `${frame.id}.${occurrence}.${key}`;
2225
+ const ctx = solidJs.sharedConfig.context;
2226
+ const origRegister = ctx.registerFragment;
2227
+ ctx.registerFragment = (fragKey, fragOptions) => {
2228
+ sink.tagRegion(fragKey, childId);
2229
+ return origRegister.call(ctx, fragKey, fragOptions);
2230
+ };
2231
+ try {
2232
+ let value = raw[key];
2233
+ for (let d = 0; typeof value === "function" && d < 16; d++) value = value();
2234
+ const t = typeof value;
2235
+ if (value == null || t === "string" || t === "number" || t === "boolean") {
2236
+ args[key] = value;
2237
+ } else if (isServerContent(value)) {
2238
+ const resolved = ctx.resolve(value);
2239
+ if (resolved.h.length) {
2240
+ throw new Error("Async server content in a slot arg needs a boundary (arg '" + key + "' of " + occurrence + "). Wrap the async read in a <Suspense>, or move it above the slot.");
2241
+ }
2242
+ sink.region(childId, resolved.t[0]);
2243
+ args[key] = {
2244
+ $frame: childId
2245
+ };
2246
+ } else {
2247
+ const ref = `arg:${occurrence}:${key}`;
2248
+ ctx.serialize(ref, value);
2249
+ args[key] = {
2250
+ $ref: ref
2251
+ };
2252
+ }
2253
+ } finally {
2254
+ ctx.registerFragment = origRegister;
2255
+ }
2256
+ }
2257
+ sink.slot(occurrence, args);
2258
+ return slotRange(occurrence);
2259
+ };
2260
+ getters.set(prop, fn);
2261
+ }
2262
+ return fn;
2263
+ }
2264
+ });
2265
+ }
2266
+ function serverComponentResponse(component, options = {}, init = {}) {
2267
+ const {
2268
+ id = "",
2269
+ version = 1
2270
+ } = options.frame || {};
2271
+ const headers = new Headers(init.headers);
2272
+ headers.set("Content-Type", "application/x-frame-stream");
2273
+ headers.set(FRAME_STREAM_HEADER, id);
2274
+ headers.set("X-Content-Raw", "1");
2275
+ const stream = renderServerComponent(component, {
2276
+ ...options,
2277
+ frame: {
2278
+ id,
2279
+ version
2280
+ }
2281
+ });
2282
+ const body = new ReadableStream({
2283
+ start(controller) {
2284
+ stream.pipe({
2285
+ write(chunk) {
2286
+ controller.enqueue(createChunk(JSON.stringify(chunk)));
2287
+ },
2288
+ end() {
2289
+ controller.close();
2290
+ }
2291
+ });
2292
+ }
2293
+ });
2294
+ return new Response(body, {
2295
+ status: init.status || 200,
2296
+ headers
2297
+ });
2298
+ }
2299
+ function frameTransformResult(event, result, context) {
2300
+ let init;
2301
+ if (isResponseEnvelope(result)) {
2302
+ const {
2303
+ response,
2304
+ value
2305
+ } = result;
2306
+ if (typeof value !== "function") return result;
2307
+ init = response ? {
2308
+ headers: response.headers,
2309
+ status: response.status
2310
+ } : undefined;
2311
+ result = value;
2312
+ }
2313
+ if (typeof result !== "function") return result;
2314
+ if (context && context.collectsFlight) return init ? {
2315
+ response: init,
2316
+ value: result
2317
+ } : result;
2318
+ const invocation = getEventServerFunctionInvocation(event);
2319
+ return serverComponentResponse(result, {
2320
+ frame: {
2321
+ id: invocation && invocation.id || ""
2322
+ }
2323
+ }, init);
2324
+ }
2325
+ async function frameTransformFlightResult(event, outcome, context) {
2326
+ const {
2327
+ value,
2328
+ data
2329
+ } = outcome;
2330
+ const regions = [];
2331
+ let serialized = data;
2332
+ if (data && typeof data === "object") {
2333
+ serialized = {};
2334
+ const keys = Object.keys(data);
2335
+ const values = await Promise.all(keys.map(key => data[key]));
2336
+ for (let i = 0; i < keys.length; i++) {
2337
+ const entry = values[i];
2338
+ serialized[keys[i]] = entry;
2339
+ if (typeof entry === "function") {
2340
+ regions.push({
2341
+ id: entry[SERVER_COMPONENT_ADDRESS] || keys[i],
2342
+ component: entry[SERVER_COMPONENT_SOURCE] || entry
2343
+ });
2344
+ }
2345
+ }
2346
+ }
2347
+ const invocation = getEventServerFunctionInvocation(event);
2348
+ const primary = typeof value === "function" ? {
2349
+ id: invocation && invocation.id || "",
2350
+ component: value
2351
+ } : undefined;
2352
+ if (!primary && !regions.length) return undefined;
2353
+ return frameFlightResponse({
2354
+ primary,
2355
+ regions,
2356
+ outcome: {
2357
+ value: primary ? undefined : value,
2358
+ data: serialized
2359
+ },
2360
+ codec: context && context.codec
2361
+ });
2362
+ }
2363
+ function frameFlightResponse({
2364
+ primary,
2365
+ regions = [],
2366
+ outcome,
2367
+ codec
2368
+ }, init = {}) {
2369
+ const frames = primary ? [primary, ...regions] : regions;
2370
+ const headers = new Headers(init.headers);
2371
+ headers.set("Content-Type", "application/x-frame-stream");
2372
+ headers.set(FRAME_STREAM_HEADER, primary ? primary.id : "");
2373
+ headers.set("X-Content-Raw", "1");
2374
+ headers.set(SINGLE_FLIGHT_HEADER, "true");
2375
+ const body = new ReadableStream({
2376
+ async start(controller) {
2377
+ const write = chunk => controller.enqueue(createChunk(JSON.stringify(chunk)));
2378
+ try {
2379
+ for (const {
2380
+ id,
2381
+ component
2382
+ } of frames) {
2383
+ await new Promise(resolve => {
2384
+ renderServerComponent(component, {
2385
+ frame: {
2386
+ id,
2387
+ version: 1
2388
+ }
2389
+ }).pipe({
2390
+ write,
2391
+ end: resolve
2392
+ });
2393
+ });
2394
+ }
2395
+ if (outcome) {
2396
+ const reader = new ChunkReader(serializeStream(outcome, flightCodec(codec)));
2397
+ for (let node = await reader.next(); !node.done; node = await reader.next()) {
2398
+ write({
2399
+ type: "outcome",
2400
+ payload: node.value
2401
+ });
2402
+ }
2403
+ }
2404
+ controller.close();
2405
+ } catch (err) {
2406
+ controller.error(err);
2407
+ }
2408
+ }
2409
+ });
2410
+ return new Response(body, {
2411
+ status: init.status || 200,
2412
+ headers
2413
+ });
2414
+ }
2415
+
2416
+ exports.FRAME_STREAM_HEADER = FRAME_STREAM_HEADER;
2417
+ exports.SERVER_COMPONENT_BOOTSTRAP = SERVER_COMPONENT_BOOTSTRAP;
2418
+ exports.ServerComponentPlugin = ServerComponentPlugin;
2419
+ exports.createFrameSink = createFrameSink;
2420
+ exports.frameTransformDirectResult = frameTransformDirectResult;
2421
+ exports.frameTransformFlightResult = frameTransformFlightResult;
2422
+ exports.frameTransformResult = frameTransformResult;
2423
+ exports.isFrameStreamResponse = isFrameStreamResponse;
2424
+ exports.renderServerComponent = renderServerComponent;
2425
+ exports.renderToFrameStream = renderToFrameStream;
2426
+ exports.serverComponentResponse = serverComponentResponse;