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

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