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