@solidjs/web 2.0.0-experimental.8 → 2.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +22 -4
  2. package/dist/dev.cjs +1585 -225
  3. package/dist/dev.js +1510 -201
  4. package/dist/server.cjs +2642 -264
  5. package/dist/server.js +2542 -217
  6. package/dist/web.cjs +1523 -218
  7. package/dist/web.js +1448 -194
  8. package/frames/dist/client.cjs +1916 -0
  9. package/frames/dist/client.dev.cjs +1933 -0
  10. package/frames/dist/client.dev.js +1921 -0
  11. package/frames/dist/client.js +1904 -0
  12. package/frames/dist/server.cjs +3667 -0
  13. package/frames/dist/server.js +3654 -0
  14. package/frames/package.json +30 -0
  15. package/package.json +349 -37
  16. package/serialization/decode/package.json +20 -0
  17. package/serialization/dist/decode.cjs +110 -0
  18. package/serialization/dist/decode.js +104 -0
  19. package/serialization/dist/serialization.cjs +232 -0
  20. package/serialization/dist/serialization.js +215 -0
  21. package/serialization/package.json +20 -0
  22. package/serialization/types/index.d.ts +182 -0
  23. package/serialization/types/serializer-decode.d.ts +182 -0
  24. package/serialization/types-cjs/index.d.cts +182 -0
  25. package/serialization/types-cjs/package.json +3 -0
  26. package/serialization/types-cjs/serializer-decode.d.cts +182 -0
  27. package/server-functions/dist/client.cjs +646 -0
  28. package/server-functions/dist/client.js +617 -0
  29. package/server-functions/dist/rich-args.cjs +11 -0
  30. package/server-functions/dist/rich-args.js +9 -0
  31. package/server-functions/dist/server.cjs +1077 -0
  32. package/server-functions/dist/server.dev.cjs +1077 -0
  33. package/server-functions/dist/server.dev.js +1045 -0
  34. package/server-functions/dist/server.js +1045 -0
  35. package/server-functions/package.json +40 -0
  36. package/server-functions/rich-args/package.json +20 -0
  37. package/storage/package.json +8 -3
  38. package/storage/types/index.d.ts +26 -0
  39. package/storage/types-cjs/index.d.cts +28 -0
  40. package/storage/types-cjs/package.json +3 -0
  41. package/types/client.d.ts +290 -27
  42. package/types/cookies.d.ts +93 -0
  43. package/types/core.d.ts +6 -2
  44. package/types/frames/client.d.ts +36 -0
  45. package/types/frames/frame-client.d.ts +338 -0
  46. package/types/frames/frame-sink.d.ts +194 -0
  47. package/types/frames/frame-transport.d.ts +222 -0
  48. package/types/frames/serializer.d.ts +182 -0
  49. package/types/frames/server.d.ts +52 -0
  50. package/types/index.d.ts +209 -24
  51. package/types/jsx-properties.d.ts +93 -0
  52. package/types/jsx.d.ts +4150 -1
  53. package/types/response.d.ts +174 -0
  54. package/types/serializer-decode.d.ts +182 -0
  55. package/types/serializer.d.ts +182 -0
  56. package/types/server-functions/client.d.ts +201 -0
  57. package/types/server-functions/flash.d.ts +38 -0
  58. package/types/server-functions/rich-args.d.ts +10 -0
  59. package/types/server-functions/server.d.ts +588 -0
  60. package/types/server-functions/shared.d.ts +523 -0
  61. package/types/server-mock.d.ts +249 -12
  62. package/types/server.d.ts +424 -51
  63. package/types-cjs/client.d.cts +337 -0
  64. package/types-cjs/cookies.d.cts +93 -0
  65. package/types-cjs/core.d.cts +6 -0
  66. package/types-cjs/frames/client.d.cts +36 -0
  67. package/types-cjs/frames/frame-client.d.cts +338 -0
  68. package/types-cjs/frames/frame-sink.d.cts +194 -0
  69. package/types-cjs/frames/frame-transport.d.cts +222 -0
  70. package/types-cjs/frames/serializer.d.cts +182 -0
  71. package/types-cjs/frames/server.d.cts +52 -0
  72. package/types-cjs/index.d.cts +230 -0
  73. package/types-cjs/jsx-properties.d.cts +93 -0
  74. package/types-cjs/jsx.d.cts +4150 -0
  75. package/types-cjs/package.json +3 -0
  76. package/types-cjs/response.d.cts +174 -0
  77. package/types-cjs/serializer-decode.d.cts +182 -0
  78. package/types-cjs/serializer.d.cts +182 -0
  79. package/types-cjs/server-functions/client.d.cts +201 -0
  80. package/types-cjs/server-functions/flash.d.cts +38 -0
  81. package/types-cjs/server-functions/rich-args.d.cts +10 -0
  82. package/types-cjs/server-functions/server.d.cts +588 -0
  83. package/types-cjs/server-functions/shared.d.cts +523 -0
  84. package/types-cjs/server-mock.d.cts +277 -0
  85. package/types-cjs/server.d.cts +523 -0
package/dist/server.js CHANGED
@@ -1,10 +1,36 @@
1
- import { createMemo, sharedConfig, createRoot, ssrHandleError, omit } from 'solid-js';
2
- export { ErrorBoundary, For, Match, Repeat, Show, Suspense, Switch, createComponent, createRenderEffect as effect, getOwner, ssrRunInScope, untrack } from 'solid-js';
1
+ import { createRenderEffect, createMemo, sharedConfig, createRoot, getOwner, ssrHandleError, runWithOwner, inServerComponentScope, creationStamp, createComponent, omit, getNextChildId, onCleanup, getProjectionTrace } from 'solid-js';
2
+ export { Errored, For, Hydration, Loading, Match, NoHydration, Repeat, Reveal, Show, Switch, createComponent, getOwner, merge as mergeProps, ssrScope as scope, untrack } from 'solid-js';
3
3
  import { Feature, Serializer, getCrossReferenceHeader } from 'seroval';
4
4
  import { AbortSignalPlugin, CustomEventPlugin, DOMExceptionPlugin, EventPlugin, FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin } from 'seroval-plugins/web';
5
5
 
6
- const Properties = /*#__PURE__*/new Set([
7
- "value", "checked", "selected", "muted"]);
6
+ const DOMWithState = {
7
+ INPUT: {
8
+ value: 1,
9
+ defaultValue: 2,
10
+ checked: 1,
11
+ defaultChecked: 2
12
+ },
13
+ SELECT: {
14
+ value: 1
15
+ },
16
+ OPTION: {
17
+ value: 1,
18
+ selected: 1,
19
+ defaultSelected: 2
20
+ },
21
+ TEXTAREA: {
22
+ value: 1,
23
+ defaultValue: 2
24
+ },
25
+ VIDEO: {
26
+ muted: 1,
27
+ defaultMuted: 2
28
+ },
29
+ AUDIO: {
30
+ muted: 1,
31
+ defaultMuted: 2
32
+ }
33
+ };
8
34
  const ChildProperties = /*#__PURE__*/new Set(["innerHTML", "textContent", "innerText", "children"]);
9
35
  const DelegatedEvents = /*#__PURE__*/new Set(["beforeinput", "click", "dblclick", "contextmenu", "focusin", "focusout", "input", "keydown", "keyup", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "pointerdown", "pointermove", "pointerout", "pointerover", "pointerup", "touchend", "touchmove", "touchstart"]);
10
36
  const SVGElements = /*#__PURE__*/new Set([
@@ -12,52 +38,882 @@ const SVGElements = /*#__PURE__*/new Set([
12
38
  "set", "stop",
13
39
  "svg", "switch", "symbol", "text", "textPath",
14
40
  "tref", "tspan", "use", "view", "vkern"]);
15
- const SVGNamespace = {
41
+ const MathMLElements = /*#__PURE__*/new Set(["annotation", "annotation-xml", "maction", "math", "menclose", "merror", "mfenced", "mfrac", "mi", "mmultiscripts", "mn", "mo", "mover", "mpadded", "mphantom", "mprescripts", "mroot", "mrow", "ms", "mspace", "msqrt", "mstyle", "msub", "msubsup", "msup", "mtable", "mtd", "mtext", "mtr", "munder", "munderover", "semantics"]);
42
+ const Namespaces = {
43
+ svg: "http://www.w3.org/2000/svg",
44
+ mathml: "http://www.w3.org/1998/Math/MathML",
16
45
  xlink: "http://www.w3.org/1999/xlink",
17
46
  xml: "http://www.w3.org/XML/1998/namespace"
18
47
  };
19
- const DOMElements = /*#__PURE__*/new Set(["html", "base", "head", "link", "meta", "style", "title", "body", "address", "article", "aside", "footer", "header", "main", "nav", "section", "body", "blockquote", "dd", "div", "dl", "dt", "figcaption", "figure", "hr", "li", "ol", "p", "pre", "ul", "a", "abbr", "b", "bdi", "bdo", "br", "cite", "code", "data", "dfn", "em", "i", "kbd", "mark", "q", "rp", "rt", "ruby", "s", "samp", "small", "span", "strong", "sub", "sup", "time", "u", "var", "wbr", "area", "audio", "img", "map", "track", "video", "embed", "iframe", "object", "param", "picture", "portal", "source", "svg", "math", "canvas", "noscript", "script", "del", "ins", "caption", "col", "colgroup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "button", "datalist", "fieldset", "form", "input", "label", "legend", "meter", "optgroup", "option", "output", "progress", "select", "textarea", "details", "dialog", "menu", "summary", "details", "slot", "template", "acronym", "applet", "basefont", "bgsound", "big", "blink", "center", "content", "dir", "font", "frame", "frameset", "hgroup", "image", "keygen", "marquee", "menuitem", "nobr", "noembed", "noframes", "plaintext", "rb", "rtc", "shadow", "spacer", "strike", "tt", "xmp", "a", "abbr", "acronym", "address", "applet", "area", "article", "aside", "audio", "b", "base", "basefont", "bdi", "bdo", "bgsound", "big", "blink", "blockquote", "body", "br", "button", "canvas", "caption", "center", "cite", "code", "col", "colgroup", "content", "data", "datalist", "dd", "del", "details", "dfn", "dialog", "dir", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "font", "footer", "form", "frame", "frameset", "head", "header", "hgroup", "hr", "html", "i", "iframe", "image", "img", "input", "ins", "kbd", "keygen", "label", "legend", "li", "link", "main", "map", "mark", "marquee", "menu", "menuitem", "meta", "meter", "nav", "nobr", "noembed", "noframes", "noscript", "object", "ol", "optgroup", "option", "output", "p", "param", "picture", "plaintext", "portal", "pre", "progress", "q", "rb", "rp", "rt", "rtc", "ruby", "s", "samp", "script", "section", "select", "shadow", "slot", "small", "source", "spacer", "span", "strike", "strong", "style", "sub", "summary", "sup", "table", "tbody", "td", "template", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "track", "tt", "u", "ul", "var", "video", "wbr", "xmp", "input", "h1", "h2", "h3", "h4", "h5", "h6",
20
- "webview",
21
- "isindex", "listing", "multicol", "nextid", "noindex", "search"]);
48
+ const VoidElements = /*#__PURE__*/new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);
49
+ const RawTextElements = /*#__PURE__*/new Set(["style", "script", "noscript", "template", "textarea", "title"]);
50
+ const DOMElements = /*#__PURE__*/new Set(/*#__PURE__*/"a,abbr,acronym,address,applet,area,article,aside,audio,b,base,basefont,bdi,bdo,bgsound,big,blink,blockquote,body,br,button,canvas,caption,center,cite,code,col,colgroup,content,data,datalist,dd,del,details,dfn,dialog,dir,div,dl,dt,em,embed,fieldset,figcaption,figure,font,footer,form,frame,frameset,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,i,iframe,image,img,input,ins,isindex,kbd,keygen,label,legend,li,link,listing,main,map,mark,marquee,math,menu,menuitem,meta,meter,multicol,nav,nextid,nobr,noembed,noframes,noindex,noscript,object,ol,optgroup,option,output,p,param,picture,plaintext,portal,pre,progress,q,rb,rp,rt,rtc,ruby,s,samp,script,search,section,select,shadow,slot,small,source,spacer,span,strike,strong,style,sub,summary,sup,svg,table,tbody,td,template,textarea,tfoot,th,thead,time,title,tr,track,tt,u,ul,var,video,wbr,webview,xmp".split(","));
22
51
 
23
- const memo = fn => createMemo(() => fn());
52
+ const transparentOptions = {
53
+ transparent: true,
54
+ sync: true
55
+ };
56
+ const syncOptions = {
57
+ sync: true
58
+ };
59
+ const effect = (fn, effectFn, options) => createRenderEffect(fn, effectFn, options ? {
60
+ sync: true,
61
+ ...options,
62
+ transparent: !options.scope
63
+ } : transparentOptions);
64
+ const memo = fn => createMemo(() => fn(), syncOptions);
24
65
 
25
- const ES2017FLAG = Feature.AggregateError
26
- | Feature.BigIntTypedArray;
27
- const GLOBAL_IDENTIFIER = '_$HY.r';
28
- function createSerializer({
66
+ const STATE = Symbol.for("dom-expressions.container-trace-state");
67
+ const state = globalThis[STATE] || (globalThis[STATE] = {
68
+ materialized: new WeakMap(),
69
+ materializedValues: new WeakSet()
70
+ });
71
+ function setContainerTraceResolver(fn) {
72
+ state.resolveTrace = fn;
73
+ }
74
+ const TRACE = Symbol.for("dom-expressions.container-trace");
75
+ function materialize(marker) {
76
+ let value = state.materialized.get(marker.$tr);
77
+ if (value === undefined) {
78
+ value = state.materializeTrace(marker);
79
+ state.materialized.set(marker.$tr, value);
80
+ if (value !== null && typeof value === "object") state.materializedValues.add(value);
81
+ }
82
+ return value;
83
+ }
84
+ function parseTrace(value, ctx) {
85
+ const trace = value[TRACE];
86
+ return {
87
+ a: trace.array ? 1 : 0,
88
+ i: ctx.parse(trace.subscribe())
89
+ };
90
+ }
91
+ const ContainerTracePlugin = {
92
+ tag: "dom-expressions/container-trace",
93
+ test(value) {
94
+ return value != null && typeof value === "object" && TRACE in value;
95
+ },
96
+ parse: {
97
+ sync() {
98
+ throw new Error("A reactive container can only be serialized by a streaming serializer.");
99
+ },
100
+ async async(value, ctx) {
101
+ const trace = value[TRACE];
102
+ return {
103
+ a: trace.array ? 1 : 0,
104
+ i: await ctx.parse(trace.subscribe())
105
+ };
106
+ },
107
+ stream: parseTrace
108
+ },
109
+ serialize(node, ctx) {
110
+ return "{$tr:" + ctx.serialize(node.i) + ",$ta:" + node.a + "}";
111
+ },
112
+ deserialize(node, ctx) {
113
+ const iterable = ctx.deserialize(node.i);
114
+ const marker = {
115
+ $tr: iterable,
116
+ $ta: node.a
117
+ };
118
+ return state.materializeTrace ? materialize(marker) : marker;
119
+ }
120
+ };
121
+
122
+ const DEFAULT_WEB_PLUGINS = Object.freeze([AbortSignalPlugin,
123
+ CustomEventPlugin, DOMExceptionPlugin, EventPlugin,
124
+ FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin,
125
+ ContainerTracePlugin]);
126
+ function resolveSerializerPlugins(customPlugins) {
127
+ return customPlugins ? [...customPlugins, ...DEFAULT_WEB_PLUGINS] : [...DEFAULT_WEB_PLUGINS];
128
+ }
129
+ Feature.RegExp;
130
+
131
+ const DEFAULT_DISABLED_FEATURES = Feature.AggregateError | Feature.BigIntTypedArray;
132
+ const serializeOnlyDisabledFeatures = () => process.env.NODE_ENV === "development" ? 0 : Feature.ErrorPrototypeStack;
133
+ const HYDRATION_GLOBAL = "_$HY.r";
134
+ function createSerializer(options) {
135
+ return new Serializer({
136
+ ...options,
137
+ plugins: resolveSerializerPlugins(options.plugins),
138
+ disabledFeatures: (options.disabledFeatures === undefined ? DEFAULT_DISABLED_FEATURES : options.disabledFeatures) | serializeOnlyDisabledFeatures()
139
+ });
140
+ }
141
+ function createHydrationSerializer({
29
142
  onData,
30
143
  onDone,
31
144
  scopeId,
32
- onError
145
+ onError,
146
+ plugins
33
147
  }) {
34
- return new Serializer({
148
+ return createSerializer({
35
149
  scopeId,
36
- plugins: [AbortSignalPlugin,
37
- CustomEventPlugin, DOMExceptionPlugin, EventPlugin,
38
- FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin],
39
- globalIdentifier: GLOBAL_IDENTIFIER,
40
- disabledFeatures: ES2017FLAG,
150
+ plugins,
151
+ globalIdentifier: HYDRATION_GLOBAL,
41
152
  onData,
42
153
  onDone,
43
154
  onError
44
155
  });
45
156
  }
46
157
  function getLocalHeaderScript(id) {
47
- return getCrossReferenceHeader(id) + ';';
158
+ return getCrossReferenceHeader(id) + ";";
48
159
  }
49
160
 
161
+ const ENVELOPE = Symbol.for("solid.ResponseEnvelope");
162
+ // PURE-annotated factory (same convention as solid's MockPromise): the brand
163
+ const ResponseEnvelope = /* @__PURE__ */(() => {
164
+ class ResponseEnvelope {
165
+ constructor(response, value) {
166
+ this.response = response;
167
+ this.value = value;
168
+ }
169
+ }
170
+ ResponseEnvelope.prototype[ENVELOPE] = true;
171
+ return ResponseEnvelope;
172
+ })();
173
+ function isResponseEnvelope(value) {
174
+ return !!(value && typeof value === "object" && value[ENVELOPE]);
175
+ }
176
+ const HREF = Symbol.for("solid.Href");
177
+ function isHref(value) {
178
+ return !!(value && (typeof value === "object" || typeof value === "function") && value[HREF]);
179
+ }
180
+ const SAFE_ERROR = Symbol.for("solid.SafeError");
181
+ function markSafeError(error) {
182
+ if (error && (typeof error === "object" || typeof error === "function")) {
183
+ Object.defineProperty(error, SAFE_ERROR, {
184
+ value: true,
185
+ enumerable: false,
186
+ configurable: true
187
+ });
188
+ }
189
+ return error;
190
+ }
191
+ function isSafeError(value) {
192
+ return !!(value && (typeof value === "object" || typeof value === "function") && value[SAFE_ERROR]);
193
+ }
194
+ const REVALIDATE_HEADER = "X-Revalidate";
195
+ function initWithRevalidate(init) {
196
+ const {
197
+ revalidate,
198
+ ...responseInit
199
+ } = init;
200
+ let headers;
201
+ if (responseInit.headers && responseInit.headers.getSetCookie) {
202
+ headers = new Headers();
203
+ responseInit.headers.forEach((value, key) => {
204
+ if (key !== "set-cookie") headers.append(key, value);
205
+ });
206
+ for (const cookie of responseInit.headers.getSetCookie()) {
207
+ headers.append("Set-Cookie", cookie);
208
+ }
209
+ } else {
210
+ headers = new Headers(responseInit.headers);
211
+ }
212
+ revalidate !== undefined && headers.set(REVALIDATE_HEADER, revalidate.toString());
213
+ return {
214
+ responseInit,
215
+ headers
216
+ };
217
+ }
218
+ function redirect(url, init = 302) {
219
+ if (typeof url !== "string" && !isHref(url)) {
220
+ throw new TypeError("redirect() expects a string URL or an Href-branded value (Symbol.for('solid.Href')).");
221
+ }
222
+ const {
223
+ responseInit,
224
+ headers
225
+ } = initWithRevalidate(typeof init === "number" ? {
226
+ status: init
227
+ } : init);
228
+ if (responseInit.status === undefined) {
229
+ responseInit.status = 302;
230
+ }
231
+ headers.set("Location", String(url));
232
+ return new Response(null, {
233
+ ...responseInit,
234
+ headers
235
+ });
236
+ }
237
+ function reload(init = {}) {
238
+ const {
239
+ responseInit,
240
+ headers
241
+ } = initWithRevalidate(init);
242
+ return new Response(null, {
243
+ ...responseInit,
244
+ headers
245
+ });
246
+ }
247
+ function respond(value, init = {}) {
248
+ const {
249
+ responseInit,
250
+ headers
251
+ } = initWithRevalidate(init);
252
+ headers.set("Content-Type", "application/json");
253
+ return new ResponseEnvelope(new Response(JSON.stringify(value), {
254
+ ...responseInit,
255
+ headers
256
+ }), value);
257
+ }
258
+
259
+ const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
260
+ function getServerFunctionMetadata(fn) {
261
+ if (typeof fn !== "function") return undefined;
262
+ return fn[SERVER_FUNCTION_METADATA] || undefined;
263
+ }
264
+ function isServerFunction(fn) {
265
+ return typeof fn === "function" && !!fn[SERVER_FUNCTION_METADATA];
266
+ }
267
+ const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
268
+ function getServerFunctionRPC() {
269
+ return globalThis[SERVER_FUNCTION_RPC];
270
+ }
271
+
272
+ function parseCookieHeader(header) {
273
+ const cookies = {};
274
+ if (!header) return cookies;
275
+ for (const part of header.split(";")) {
276
+ const eq = part.indexOf("=");
277
+ if (eq < 0) continue;
278
+ const name = decodeSafe(part.slice(0, eq).trim());
279
+ let value = part.slice(eq + 1).trim();
280
+ if (value.length > 1 && value[0] === '"' && value[value.length - 1] === '"') {
281
+ value = value.slice(1, -1);
282
+ }
283
+ cookies[name] = decodeSafe(value);
284
+ }
285
+ return cookies;
286
+ }
287
+ function decodeSafe(text) {
288
+ try {
289
+ return decodeURIComponent(text);
290
+ } catch {
291
+ return text;
292
+ }
293
+ }
294
+ function serializeCookie(name, value, options = {}) {
295
+ let cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
296
+ cookie += `; Path=${options.path === undefined ? "/" : options.path}`;
297
+ if (options.domain) cookie += `; Domain=${options.domain}`;
298
+ if (options.maxAge !== undefined) cookie += `; Max-Age=${Math.trunc(options.maxAge)}`;
299
+ if (options.expires) cookie += `; Expires=${options.expires.toUTCString()}`;
300
+ if (options.httpOnly) cookie += "; HttpOnly";
301
+ if (options.secure) cookie += "; Secure";
302
+ if (options.sameSite) {
303
+ const sameSite = options.sameSite.toLowerCase();
304
+ cookie += `; SameSite=${sameSite === "none" ? "None" : sameSite === "strict" ? "Strict" : "Lax"}`;
305
+ }
306
+ return cookie;
307
+ }
308
+ const FLASH_COOKIE = "flash";
309
+ const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
310
+ function hasFlashCookie(cookieHeader) {
311
+ return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
312
+ }
313
+ function clearFlashCookie() {
314
+ return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
315
+ }
316
+
317
+ const ERROR_HEADER = "X-Server-Function-Error";
318
+ const BODY_FORMAT_HEADER = "X-Server-Function-Format";
319
+ const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
320
+
321
+ const HEAD_ELIGIBLE_TAGS = new Set(["title", "meta", "link", "style", "script", "base"]);
322
+ const HEAD_ATTR_NAME = /^[a-zA-Z_][a-zA-Z0-9_:.-]*$/;
323
+ const RESOURCE_LINK_RELS = new Set(["preload", "modulepreload", "prefetch", "preconnect", "dns-prefetch", "stylesheet"]);
324
+ const RESOURCE_QUALIFIERS = ["as", "crossorigin", "type", "media", "imagesrcset", "imagesizes"];
325
+ const STYLESHEET_FETCH_META = new Set(["crossorigin", "integrity", "referrerpolicy", "fetchpriority"]);
326
+ function evalHeadValue(v) {
327
+ return typeof v === "function" ? v() : v;
328
+ }
329
+ function evalHeadProps(props, presets) {
330
+ const out = {};
331
+ for (const name in props) out[name] = presets && name in presets ? presets[name] : evalHeadValue(props[name]);
332
+ return out;
333
+ }
334
+ function classifyHeadTag(desc) {
335
+ const tag = desc.tag;
336
+ if (tag === "link") {
337
+ const rel = evalHeadValue(desc.props && desc.props.rel);
338
+ return {
339
+ resource: RESOURCE_LINK_RELS.has(rel),
340
+ rel
341
+ };
342
+ }
343
+ if (tag === "style") return {
344
+ resource: !!(desc.props && "href" in desc.props)
345
+ };
346
+ if (tag === "script") return {
347
+ resource: !!(desc.props && "src" in desc.props)
348
+ };
349
+ return {
350
+ resource: false
351
+ };
352
+ }
353
+ function resourceIdentity(tag, props) {
354
+ let id = "res:" + tag + ":" + (props.rel || "") + ":" + (props.href || props.src || "");
355
+ for (let i = 0; i < RESOURCE_QUALIFIERS.length; i++) {
356
+ const q = RESOURCE_QUALIFIERS[i];
357
+ if (props[q] != null) id += ":" + q + "=" + props[q];
358
+ }
359
+ return id;
360
+ }
361
+ function replaceableIdentity(tag, props, key, unique) {
362
+ if (tag === "title") return "title";
363
+ if (tag === "base") return "base";
364
+ if (tag === "meta" && props.charset != null) return "charset";
365
+ if (key != null) return tag + ":key:" + key;
366
+ if (tag === "meta") {
367
+ for (const ns of ["name", "property", "http-equiv"]) if (props[ns] != null) return "meta:" + ns + ":" + props[ns] + (props.media != null ? ":media=" + props.media : "");
368
+ return unique;
369
+ }
370
+ if (tag === "link") {
371
+ const rel = props.rel || "";
372
+ if (rel === "icon" || rel === "apple-touch-icon") return "link:" + rel + (props.sizes != null ? ":sizes=" + props.sizes : "") + (props.type != null ? ":type=" + props.type : "");
373
+ return "link:" + rel + ":" + (props.href || "");
374
+ }
375
+ return unique;
376
+ }
377
+ function resolveHead(groups) {
378
+ const winners = new Map();
379
+ const sorted = groups.slice().sort((a, b) => a.seq - b.seq);
380
+ for (let i = 0; i < sorted.length; i++) {
381
+ const group = sorted[i];
382
+ const byIdentity = new Map();
383
+ for (let j = 0; j < group.tags.length; j++) {
384
+ const t = group.tags[j];
385
+ let list = byIdentity.get(t.identity);
386
+ if (!list) byIdentity.set(t.identity, list = []);
387
+ list.push(t);
388
+ }
389
+ for (const [identity, tags] of byIdentity) {
390
+ if (identity === "title") {
391
+ winners.set(identity, {
392
+ seq: group.seq,
393
+ tags: [tags[tags.length - 1]]
394
+ });
395
+ } else {
396
+ winners.set(identity, {
397
+ seq: group.seq,
398
+ tags
399
+ });
400
+ }
401
+ }
402
+ }
403
+ return winners;
404
+ }
405
+
406
+ function joinAssetPath(base, file) {
407
+ if (/^(?:[a-z][a-z0-9+.-]*:)?\/\//i.test(file)) return file;
408
+ if (typeof base !== "string" || !base) base = "/";
409
+ if (base[base.length - 1] !== "/") base += "/";
410
+ return base + (file[0] === "/" ? file.slice(1) : file);
411
+ }
412
+ function resolveAssets(moduleUrl, manifest) {
413
+ if (!manifest) return null;
414
+ const base = manifest._base;
415
+ const entry = manifest[moduleUrl];
416
+ if (!entry) return null;
417
+ const css = [];
418
+ const js = [];
419
+ const visited = new Set();
420
+ const walk = key => {
421
+ if (visited.has(key)) return;
422
+ visited.add(key);
423
+ const e = manifest[key];
424
+ if (!e) return;
425
+ js.push(joinAssetPath(base, e.file));
426
+ if (e.css) for (let i = 0; i < e.css.length; i++) css.push(joinAssetPath(base, e.css[i]));
427
+ if (e.imports) for (let i = 0; i < e.imports.length; i++) walk(e.imports[i]);
428
+ };
429
+ walk(moduleUrl);
430
+ return {
431
+ js,
432
+ css
433
+ };
434
+ }
435
+ function registerEntryAssets(manifest) {
436
+ if (!manifest || typeof manifest === "function" || typeof manifest.resolve === "function") return;
437
+ const ctx = sharedConfig.context;
438
+ if (!ctx?.registerAsset) return;
439
+ for (const key in manifest) {
440
+ if (manifest[key].isEntry) {
441
+ const assets = resolveAssets(key, manifest);
442
+ if (assets) {
443
+ for (let i = 0; i < assets.css.length; i++) ctx.registerAsset("style", assets.css[i]);
444
+ }
445
+ return;
446
+ }
447
+ }
448
+ }
449
+ function createAssetTracking() {
450
+ const boundaryModules = new Map();
451
+ const boundaryStyles = new Map();
452
+ const emittedAssets = new Set();
453
+ const inlineStyles = new Map();
454
+ let currentBoundaryId = null;
455
+ return {
456
+ boundaryModules,
457
+ boundaryStyles,
458
+ emittedAssets,
459
+ inlineStyles,
460
+ registerInlineStyle(desc) {
461
+ let entry = inlineStyles.get(desc.id);
462
+ if (!entry) {
463
+ entry = {
464
+ id: desc.id,
465
+ content: desc.content || "",
466
+ attrs: desc.attrs,
467
+ emitted: false
468
+ };
469
+ inlineStyles.set(desc.id, entry);
470
+ }
471
+ if (currentBoundaryId) {
472
+ let styles = boundaryStyles.get(currentBoundaryId);
473
+ if (!styles) {
474
+ styles = new Set();
475
+ boundaryStyles.set(currentBoundaryId, styles);
476
+ }
477
+ styles.add(entry);
478
+ }
479
+ return entry;
480
+ },
481
+ get currentBoundaryId() {
482
+ return currentBoundaryId;
483
+ },
484
+ set currentBoundaryId(v) {
485
+ currentBoundaryId = v;
486
+ },
487
+ registerModule(key, entryUrl) {
488
+ const id = currentBoundaryId || "";
489
+ let map = boundaryModules.get(id);
490
+ if (!map) {
491
+ map = {};
492
+ boundaryModules.set(id, map);
493
+ }
494
+ map[key] = entryUrl;
495
+ },
496
+ getBoundaryModules(id) {
497
+ return boundaryModules.get(id) || null;
498
+ },
499
+ getBoundaryStyles(id) {
500
+ return boundaryStyles.get(id) || null;
501
+ }
502
+ };
503
+ }
504
+ function warnUnresolvedModuleAssets(moduleUrl, warned) {
505
+ if (warned.has(moduleUrl)) return;
506
+ warned.add(moduleUrl);
507
+ 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.");
508
+ }
509
+ function guardResolvedAssets(moduleUrl, result, warned) {
510
+ if (result && typeof result.then === "function") {
511
+ return result.then(assets => {
512
+ if (!assets || !assets.js || !assets.js.length) warnUnresolvedModuleAssets(moduleUrl, warned);
513
+ return assets;
514
+ });
515
+ }
516
+ if (!result || !result.js || !result.js.length) warnUnresolvedModuleAssets(moduleUrl, warned);
517
+ return result;
518
+ }
519
+ function applyAssetTracking(context, tracking, manifest, noScripts) {
520
+ const warned = new Set();
521
+ const guard = noScripts ? resolve => resolve : resolve => moduleUrl => guardResolvedAssets(moduleUrl, resolve(moduleUrl), warned);
522
+ Object.defineProperty(context, "_currentBoundaryId", {
523
+ get() {
524
+ return tracking.currentBoundaryId;
525
+ },
526
+ set(v) {
527
+ tracking.currentBoundaryId = v;
528
+ },
529
+ configurable: true,
530
+ enumerable: true
531
+ });
532
+ context.registerModule = tracking.registerModule;
533
+ context.getBoundaryModules = tracking.getBoundaryModules;
534
+ if (typeof manifest === "function") {
535
+ context.resolveAssets = guard(manifest);
536
+ } else if (manifest && typeof manifest.resolve === "function") {
537
+ context.resolveAssets = guard(key => manifest.resolve(key));
538
+ if (typeof manifest.resolveSync === "function") {
539
+ context.resolveAssetsSync = key => manifest.resolveSync(key);
540
+ }
541
+ } else if (manifest) {
542
+ const resolve = moduleUrl => resolveAssets(moduleUrl, manifest);
543
+ context.resolveAssets = guard(resolve);
544
+ context.resolveAssetsSync = resolve;
545
+ }
546
+ }
547
+ function isCssUrl(url) {
548
+ const q = url.search(/[?#]/);
549
+ return (q === -1 ? url : url.slice(0, q)).endsWith(".css");
550
+ }
551
+ function createHeadRegistry() {
552
+ return {
553
+ pending: [],
554
+ committed: [],
555
+ seq: 0,
556
+ uniq: 0,
557
+ resources: new Set(),
558
+ eagerHtml: "",
559
+ flushed: null,
560
+ shellFlushed: false,
561
+ parkedResources: []
562
+ };
563
+ }
564
+ function registerHeadTags(registry, context, tracking, emitResource, nonce, tags) {
565
+ const boundary = context._currentBoundaryId || "";
566
+ if (typeof tags === "function") {
567
+ registry.pending.push({
568
+ boundary,
569
+ list: tags,
570
+ resource: (desc, rel) => emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel)
571
+ });
572
+ return;
573
+ }
574
+ if (!Array.isArray(tags)) tags = [tags];
575
+ const probe = sharedConfig.context && sharedConfig.context._loadingPhase;
576
+ let replaceable = null;
577
+ for (let i = 0; i < tags.length; i++) {
578
+ const desc = tags[i];
579
+ if (!desc || !HEAD_ELIGIBLE_TAGS.has(desc.tag)) {
580
+ continue;
581
+ }
582
+ const cls = classifyHeadTag(desc);
583
+ if (probe && !cls.resource) {
584
+ try {
585
+ evalHeadProps(desc.props || {}, cls.rel !== undefined ? {
586
+ rel: cls.rel
587
+ } : undefined);
588
+ evalHeadValue(desc.key);
589
+ } catch (err) {
590
+ if (ssrHandleError(err)) throw err;
591
+ }
592
+ }
593
+ if (cls.resource) {
594
+ emitHeadResource(registry, context, tracking, emitResource, nonce, desc, cls.rel);
595
+ } else {
596
+ (replaceable || (replaceable = [])).push(cls.rel !== undefined ? {
597
+ tag: desc.tag,
598
+ props: desc.props,
599
+ key: desc.key,
600
+ rel: cls.rel
601
+ } : desc);
602
+ }
603
+ }
604
+ if (replaceable) registry.pending.push({
605
+ boundary,
606
+ tags: replaceable
607
+ });
608
+ }
609
+ function headShellReady(registry, block) {
610
+ let ready = true;
611
+ const pends = err => {
612
+ const source = ssrHandleError(err, true);
613
+ if (!source) return false;
614
+ block(source);
615
+ ready = false;
616
+ return true;
617
+ };
618
+ const parked = registry.parkedResources;
619
+ for (let i = parked.length - 1; i >= 0; i--) {
620
+ const {
621
+ desc,
622
+ rel,
623
+ emit
624
+ } = parked[i];
625
+ try {
626
+ evalHeadProps(desc.props || {}, rel !== undefined ? {
627
+ rel
628
+ } : undefined);
629
+ } catch (err) {
630
+ if (pends(err)) continue;
631
+ parked.splice(i, 1);
632
+ continue;
633
+ }
634
+ parked.splice(i, 1);
635
+ emit();
636
+ }
637
+ for (let i = 0; i < registry.pending.length; i++) {
638
+ const reg = registry.pending[i];
639
+ if (reg.boundary !== "" || reg.list) continue;
640
+ for (let j = 0; j < reg.tags.length; j++) {
641
+ const desc = reg.tags[j];
642
+ try {
643
+ evalHeadProps(desc.props || {}, desc.rel !== undefined ? {
644
+ rel: desc.rel
645
+ } : undefined);
646
+ evalHeadValue(desc.key);
647
+ } catch (err) {
648
+ pends(err);
649
+ }
650
+ }
651
+ }
652
+ return ready;
653
+ }
654
+ function emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel) {
655
+ let props;
656
+ try {
657
+ props = evalHeadProps(desc.props || {}, rel !== undefined ? {
658
+ rel
659
+ } : undefined);
660
+ } catch (err) {
661
+ const loadingPhase = sharedConfig.context && sharedConfig.context._loadingPhase;
662
+ if (loadingPhase && ssrHandleError(err)) throw err;
663
+ if (!loadingPhase && !context._currentBoundaryId && !registry.shellFlushed && typeof context.block === "function" && ssrHandleError(err, true)) {
664
+ registry.parkedResources.push({
665
+ desc,
666
+ rel,
667
+ emit: () => emitHeadResource(registry, context, tracking, emitResource, nonce, desc, rel)
668
+ });
669
+ return;
670
+ }
671
+ return;
672
+ }
673
+ const identity = resourceIdentity(desc.tag, props);
674
+ if (registry.resources.has(identity)) return;
675
+ registry.resources.add(identity);
676
+ if (desc.tag === "link" && (rel === "stylesheet" || rel === "modulepreload")) {
677
+ let plain = true;
678
+ let gateable = rel === "stylesheet";
679
+ for (const name in props) {
680
+ if (name === "rel" || name === "href") continue;
681
+ plain = false;
682
+ if (!STYLESHEET_FETCH_META.has(name)) gateable = false;
683
+ }
684
+ if (plain && props.href != null) {
685
+ const isCss = isCssUrl(props.href);
686
+ if (rel === "stylesheet" ? isCss : !isCss) {
687
+ context.registerAsset(rel === "stylesheet" ? "style" : "module", props.href);
688
+ return;
689
+ }
690
+ }
691
+ if (gateable && props.href != null) {
692
+ const attrHtml = renderHeadAttrHtml(props);
693
+ const entry = {
694
+ href: props.href,
695
+ attrHtml,
696
+ attrs: headAttrRecord(props)
697
+ };
698
+ if (tracking.currentBoundaryId) {
699
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
700
+ if (!styles) tracking.boundaryStyles.set(tracking.currentBoundaryId, styles = new Set());
701
+ styles.add(entry);
702
+ }
703
+ const markup = `<link${attrHtml}>`;
704
+ if (emitResource) emitResource(markup, entry);else {
705
+ registry.eagerHtml += markup;
706
+ entry.emitted = true;
707
+ }
708
+ return;
709
+ }
710
+ }
711
+ const url = props.href || props.src;
712
+ if (url != null && tracking.emittedAssets.has(url)) return;
713
+ const markup = renderHeadTagMarkup(desc.tag, props, null, nonce);
714
+ if (emitResource) emitResource(markup);else registry.eagerHtml += markup;
715
+ }
716
+ function commitHeadBoundary(registry, boundary, isPendingFragment) {
717
+ const keep = [];
718
+ const groups = [];
719
+ for (let i = 0; i < registry.pending.length; i++) {
720
+ const reg = registry.pending[i];
721
+ const mine = boundary === "" ? !(isPendingFragment && reg.boundary !== "" && isPendingFragment(reg.boundary)) : reg.boundary === boundary;
722
+ if (!mine) {
723
+ keep.push(reg);
724
+ continue;
725
+ }
726
+ let descs = reg.tags;
727
+ if (reg.list) {
728
+ let resolved;
729
+ try {
730
+ resolved = reg.list();
731
+ } catch (err) {
732
+ continue;
733
+ }
734
+ if (!Array.isArray(resolved)) resolved = [resolved];
735
+ descs = [];
736
+ for (let j = 0; j < resolved.length; j++) {
737
+ const desc = resolved[j];
738
+ if (!desc || !HEAD_ELIGIBLE_TAGS.has(desc.tag)) {
739
+ continue;
740
+ }
741
+ const cls = classifyHeadTag(desc);
742
+ if (cls.resource) {
743
+ reg.resource(desc, cls.rel);
744
+ } else {
745
+ descs.push(cls.rel !== undefined ? {
746
+ tag: desc.tag,
747
+ props: desc.props,
748
+ key: desc.key,
749
+ rel: cls.rel
750
+ } : desc);
751
+ }
752
+ }
753
+ }
754
+ const tags = [];
755
+ for (let j = 0; j < descs.length; j++) {
756
+ const desc = descs[j];
757
+ let props, key;
758
+ try {
759
+ props = evalHeadProps(desc.props || {}, desc.rel !== undefined ? {
760
+ rel: desc.rel
761
+ } : undefined);
762
+ key = evalHeadValue(desc.key);
763
+ } catch (err) {
764
+ continue;
765
+ }
766
+ const identity = replaceableIdentity(desc.tag, props, key, "u:" + registry.uniq++);
767
+ if ((identity === "base" || identity === "charset") && registry.shellFlushed) {
768
+ continue;
769
+ }
770
+ tags.push({
771
+ tag: desc.tag,
772
+ props,
773
+ identity
774
+ });
775
+ }
776
+ if (tags.length) groups.push({
777
+ seq: registry.seq++,
778
+ tags
779
+ });
780
+ }
781
+ registry.pending = keep;
782
+ for (let i = 0; i < groups.length; i++) registry.committed.push(groups[i]);
783
+ return groups;
784
+ }
785
+ function adoptHeadBoundary(registry, childKey, parentKey) {
786
+ for (let i = 0; i < registry.pending.length; i++) {
787
+ if (registry.pending[i].boundary === childKey) registry.pending[i].boundary = parentKey;
788
+ }
789
+ }
790
+ function dropHeadBoundary(registry, boundary) {
791
+ registry.pending = registry.pending.filter(reg => reg.boundary !== boundary);
792
+ }
793
+ function headGroupSignature(winner) {
794
+ let sig = "" + winner.seq;
795
+ for (let i = 0; i < winner.tags.length; i++) {
796
+ const t = winner.tags[i];
797
+ sig += "|" + t.tag + JSON.stringify(t.props);
798
+ }
799
+ return sig;
800
+ }
801
+ function renderShellHead(registry, nonce, isPendingFragment) {
802
+ commitHeadBoundary(registry, "", isPendingFragment);
803
+ registry.shellFlushed = true;
804
+ const winners = resolveHead(registry.committed);
805
+ registry.flushed = new Map();
806
+ let prelude = "";
807
+ let links = "";
808
+ let metas = "";
809
+ let others = "";
810
+ let scripts = "";
811
+ for (const [identity, winner] of winners) {
812
+ registry.flushed.set(identity, headGroupSignature(winner));
813
+ for (let i = 0; i < winner.tags.length; i++) {
814
+ const t = winner.tags[i];
815
+ const markup = renderHeadTagMarkup(t.tag, t.props, identity, nonce);
816
+ 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;
817
+ }
818
+ }
819
+ return {
820
+ prelude,
821
+ html: registry.eagerHtml + links + metas + others + scripts
822
+ };
823
+ }
824
+ function flushHeadFragment(registry, boundary) {
825
+ const groups = commitHeadBoundary(registry, boundary);
826
+ if (!groups.length) return null;
827
+ const winners = resolveHead(registry.committed);
828
+ const affected = new Set();
829
+ 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);
830
+ const ops = [];
831
+ for (const identity of affected) {
832
+ const winner = winners.get(identity);
833
+ const sig = headGroupSignature(winner);
834
+ if (registry.flushed.get(identity) === sig) continue;
835
+ const existed = registry.flushed.has(identity);
836
+ registry.flushed.set(identity, sig);
837
+ if (identity === "title") {
838
+ const children = winner.tags[0].props.children;
839
+ ops.push(["t", children == null ? "" : String(children)]);
840
+ continue;
841
+ }
842
+ if (existed) ops.push(["r", identity]);
843
+ for (let i = 0; i < winner.tags.length; i++) {
844
+ const t = winner.tags[i];
845
+ const attrs = {};
846
+ for (const name in t.props) {
847
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
848
+ if (!HEAD_ATTR_NAME.test(name)) {
849
+ continue;
850
+ }
851
+ const v = t.props[name];
852
+ if (v == null || v === false) continue;
853
+ attrs[name] = v === true ? "" : String(v);
854
+ }
855
+ const children = t.props.children;
856
+ ops.push(["a", identity, t.tag, attrs, children == null ? null : String(children)]);
857
+ }
858
+ }
859
+ return ops.length ? ops : null;
860
+ }
861
+ function renderHeadAttrHtml(props) {
862
+ let attrs = "";
863
+ for (const name in props) {
864
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
865
+ if (!HEAD_ATTR_NAME.test(name)) {
866
+ continue;
867
+ }
868
+ const v = props[name];
869
+ if (v == null || v === false) continue;
870
+ attrs += v === true ? ` ${name}` : ` ${name}="${escape(String(v), true)}"`;
871
+ }
872
+ return attrs;
873
+ }
874
+ function headAttrRecord(props, skipRelHref) {
875
+ let attrs = null;
876
+ for (const name in props) {
877
+ if (name === "children" || name === "ref" || name.slice(0, 2) === "on") continue;
878
+ if ((name === "rel" || name === "href")) continue;
879
+ if (!HEAD_ATTR_NAME.test(name)) continue;
880
+ const v = props[name];
881
+ if (v == null || v === false) continue;
882
+ (attrs || (attrs = {}))[name] = v === true ? "" : String(v);
883
+ }
884
+ return attrs;
885
+ }
886
+ function renderHeadTagMarkup(tag, props, identity, nonce) {
887
+ let attrs = renderHeadAttrHtml(props);
888
+ if (identity != null) attrs += ` data-dh="${escape(identity, true)}"`;
889
+ if (nonce && (tag === "script" || tag === "style")) attrs += ` nonce="${nonce}"`;
890
+ if (tag === "meta" || tag === "link" || tag === "base") return `<${tag}${attrs}>`;
891
+ let body = props.children == null ? "" : String(props.children);
892
+ if (tag === "script") body = body.replace(/<\/(script)/gi, "<\\/$1");else if (tag === "style") body = escapeStyleContent(body);else body = escape(body);
893
+ return `<${tag}${attrs}>${body}</${tag}>`;
894
+ }
895
+ function useHead(tags) {
896
+ const ctx = sharedConfig.context;
897
+ if (!ctx || !ctx.registerHeadTags) {
898
+ return;
899
+ }
900
+ ctx.registerHeadTags(tags);
901
+ }
50
902
  const VOID_ELEMENTS = /^(?:area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr)$/i;
51
- const REPLACE_SCRIPT = `function $df(e,n,o,t){if(n=document.getElementById(e),o=document.getElementById("pl-"+e)){for(;o&&8!==o.nodeType&&o.nodeValue!=="pl-"+e;)t=o.nextSibling,o.remove(),o=t;_$HY.done?o.remove():o.replaceWith(n.content)}n.remove(),_$HY.fe(e)}`;
903
+ 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])}`;
904
+ 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)}`;
52
905
  function renderToString(code, options = {}) {
53
906
  const {
54
907
  renderId = "",
55
908
  nonce,
56
- noScripts
909
+ noScripts,
910
+ manifest,
911
+ onHead
57
912
  } = options;
58
913
  let scripts = "";
59
- const serializer = createSerializer({
914
+ const serializer = createHydrationSerializer({
60
915
  scopeId: renderId,
916
+ plugins: options.plugins,
61
917
  onData(script) {
62
918
  if (noScripts) return;
63
919
  if (!scripts) {
@@ -67,27 +923,52 @@ function renderToString(code, options = {}) {
67
923
  },
68
924
  onError: options.onError
69
925
  });
926
+ const tracking = createAssetTracking();
927
+ const headRegistry = createHeadRegistry();
70
928
  sharedConfig.context = {
71
- assets: [],
72
929
  nonce,
73
930
  escape: escape,
74
931
  resolve: resolveSSRNode,
75
932
  ssr: ssr,
933
+ registerHeadTags(tags) {
934
+ registerHeadTags(headRegistry, sharedConfig.context, tracking, null, nonce, tags);
935
+ },
76
936
  serialize(id, p) {
77
- !sharedConfig.context.noHydrate && serializer.write(id, p);
937
+ if (sharedConfig.context.noHydrate) return;
938
+ if (p != null && typeof p === "object" && (typeof p.then === "function" || typeof p[Symbol.asyncIterator] === "function")) {
939
+ throw new Error("Cannot serialize async value in renderToString (id: " + id + "). " + "Use renderToStream for async data.");
940
+ }
941
+ serializer.write(id, p);
942
+ },
943
+ registerAsset(type, value) {
944
+ if (type === "inline-style") {
945
+ tracking.registerInlineStyle(value);
946
+ return;
947
+ }
948
+ if (tracking.currentBoundaryId && type === "style") {
949
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
950
+ if (!styles) {
951
+ styles = new Set();
952
+ tracking.boundaryStyles.set(tracking.currentBoundaryId, styles);
953
+ }
954
+ styles.add(value);
955
+ }
956
+ tracking.emittedAssets.add(value);
78
957
  }
79
958
  };
959
+ applyAssetTracking(sharedConfig.context, tracking, manifest, noScripts);
960
+ registerEntryAssets(manifest);
80
961
  let html = createRoot(d => {
81
962
  setTimeout(d);
82
963
  return resolveSSRSync(escape(code()));
83
964
  }, {
84
965
  id: renderId
85
966
  });
967
+ serializeFragmentAssets("", tracking.boundaryModules, sharedConfig.context, renderId);
86
968
  sharedConfig.context.noHydrate = true;
87
969
  serializer.close();
88
- html = injectAssets(sharedConfig.context.assets, html);
89
- if (scripts.length) html = injectScripts(html, scripts, options.nonce);
90
- return html;
970
+ const head = renderShellHead(headRegistry, nonce, null);
971
+ return assembleDocument(html, tracking.emittedAssets, tracking.inlineStyles, scripts.length ? scripts : "", nonce, head, onHead);
91
972
  }
92
973
  function renderToStream(code, options = {}) {
93
974
  let {
@@ -95,18 +976,64 @@ function renderToStream(code, options = {}) {
95
976
  onCompleteShell,
96
977
  onCompleteAll,
97
978
  renderId = "",
98
- noScripts
979
+ noScripts,
980
+ manifest,
981
+ onHead
99
982
  } = options;
100
983
  let dispose;
101
- const blockingPromises = [];
984
+ let dead = false;
985
+ const abandon = () => {
986
+ if (dead) return;
987
+ dead = true;
988
+ completed = true;
989
+ buffer = {
990
+ write() {}
991
+ };
992
+ writable = {
993
+ end() {}
994
+ };
995
+ if (dispose) {
996
+ const d = dispose;
997
+ dispose = () => {};
998
+ d();
999
+ }
1000
+ };
1001
+ const failRender = err => {
1002
+ try {
1003
+ options.onError ? options.onError(err) : console.error(err);
1004
+ } catch (_) {}
1005
+ abandon();
1006
+ };
1007
+ const guardSink = w => ({
1008
+ write(payload) {
1009
+ if (dead) return;
1010
+ try {
1011
+ w.write(payload);
1012
+ } catch (_) {
1013
+ abandon();
1014
+ }
1015
+ },
1016
+ end() {
1017
+ if (dead) return;
1018
+ try {
1019
+ w.end();
1020
+ } catch (_) {
1021
+ abandon();
1022
+ }
1023
+ }
1024
+ });
1025
+ const blockingPromises = new Set();
1026
+ let headerEmitted = false;
102
1027
  const pushTask = task => {
103
1028
  if (noScripts) return;
104
- if (!tasks && !firstFlushed) {
105
- tasks = getLocalHeaderScript(renderId);
1029
+ if (!headerEmitted) {
1030
+ headerEmitted = true;
1031
+ tasks += getLocalHeaderScript(renderId);
106
1032
  }
107
1033
  tasks += task + ";";
108
1034
  if (!timer && firstFlushed) {
109
- timer = setTimeout(writeTasks);
1035
+ timer = true;
1036
+ queue(() => queue(writeTasks));
110
1037
  }
111
1038
  };
112
1039
  const onDone = () => {
@@ -121,15 +1048,72 @@ function renderToStream(code, options = {}) {
121
1048
  completed = true;
122
1049
  if (firstFlushed) dispose();
123
1050
  };
124
- const serializer = createSerializer({
1051
+ const sink = {
1052
+ data(payload) {
1053
+ pushTask(payload);
1054
+ },
1055
+ fragment(key, value, meta) {
1056
+ const deferActivation = !!meta.revealGroup;
1057
+ const styles = meta.styles;
1058
+ for (let i = 0; i < styles.inline.length; i++) {
1059
+ buffer.write(renderInlineStyle(styles.inline[i], nonce));
1060
+ }
1061
+ if (styles.links.length) {
1062
+ emitTask(`$dfs("${key}",${styles.links.length},${deferActivation ? 1 : 0})`);
1063
+ writeTasks();
1064
+ for (const entry of styles.links) {
1065
+ 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}')">`);
1066
+ }
1067
+ buffer.write(`<template id="${key}">${value}</template>`);
1068
+ } else {
1069
+ buffer.write(`<template id="${key}">${value}</template>`);
1070
+ if (!deferActivation) {
1071
+ emitTask(`$df("${key}")`);
1072
+ }
1073
+ }
1074
+ },
1075
+ reveal(keys, meta) {
1076
+ emitTask(`${meta.fallback ? "$dflj" : "$dfj"}(${JSON.stringify(keys)})`);
1077
+ },
1078
+ asset(type, value) {
1079
+ if (type === "module") {
1080
+ buffer.write(`<link rel="modulepreload" href="${value}">`);
1081
+ } else if (type === "inline-style") {
1082
+ buffer.write(renderInlineStyle(value, nonce));
1083
+ } else if (type === "head-tag") {
1084
+ buffer.write(value);
1085
+ }
1086
+ },
1087
+ shell(shellHtml, meta) {
1088
+ buffer.write(assembleDocument(shellHtml, meta.preloads, meta.inlineStyles, meta.tasks.length ? meta.tasks : "", nonce, meta.head, onHead));
1089
+ },
1090
+ ...options.sink
1091
+ };
1092
+ const serializer = (options.serializer || createHydrationSerializer)({
125
1093
  scopeId: options.renderId,
126
- onData: pushTask,
1094
+ plugins: options.plugins,
1095
+ onData: payload => sink.data(payload),
127
1096
  onDone,
128
1097
  onError: options.onError
129
1098
  });
1099
+ let rootAssetsSerialized = false;
1100
+ const serializeRootAssets = () => {
1101
+ if (rootAssetsSerialized) return;
1102
+ rootAssetsSerialized = true;
1103
+ serializeFragmentAssets("", tracking.boundaryModules, context, renderId);
1104
+ };
1105
+ let holds = 0;
130
1106
  const flushEnd = () => {
131
- if (!registry.size) {
132
- queue(() => queue(() => serializer.flush()));
1107
+ if (!registry.size && !holds) {
1108
+ serializeRootAssets();
1109
+ queue(() => queue(() => {
1110
+ if (context.live.end) {
1111
+ const end = context.live.end;
1112
+ context.live.end = null;
1113
+ end();
1114
+ }
1115
+ serializer.flush();
1116
+ }));
133
1117
  }
134
1118
  };
135
1119
  const registry = new Map();
@@ -138,7 +1122,6 @@ function renderToStream(code, options = {}) {
138
1122
  buffer.write(`<script${nonce ? ` nonce="${nonce}"` : ""}>${tasks}</script>`);
139
1123
  tasks = "";
140
1124
  }
141
- timer && clearTimeout(timer);
142
1125
  timer = null;
143
1126
  };
144
1127
  let context;
@@ -149,18 +1132,94 @@ function renderToStream(code, options = {}) {
149
1132
  let completed = false;
150
1133
  let shellCompleted = false;
151
1134
  let scriptFlushed = false;
1135
+ let headStyles;
1136
+ const revealGroups = new Map();
152
1137
  let timer = null;
1138
+ const emitTask = task => {
1139
+ pushTask(`${task}${!scriptFlushed ? ";" + REPLACE_SCRIPT : ""}`);
1140
+ scriptFlushed = true;
1141
+ };
1142
+ function resolveRevealKeys(groupOrKeys, release, consume) {
1143
+ if (Array.isArray(groupOrKeys)) return groupOrKeys.slice();
1144
+ let group = revealGroups.get(groupOrKeys);
1145
+ if (!group) {
1146
+ if (!release) return;
1147
+ group = {
1148
+ order: [],
1149
+ keys: new Set(),
1150
+ released: true
1151
+ };
1152
+ revealGroups.set(groupOrKeys, group);
1153
+ } else if (release) group.released = true;
1154
+ if (!group.order.length) return;
1155
+ const keys = group.order.slice();
1156
+ if (consume) revealGroups.delete(groupOrKeys);
1157
+ return keys;
1158
+ }
1159
+ let rootHoles = null;
1160
+ let nextHoleId = 0;
153
1161
  let buffer = {
154
1162
  write(payload) {
155
1163
  tmp += payload;
156
1164
  }
157
1165
  };
1166
+ const tracking = createAssetTracking();
1167
+ const headRegistry = createHeadRegistry();
1168
+ let headScriptFlushed = false;
1169
+ const emitHeadOps = (key, ops) => {
1170
+ const payload = JSON.stringify(ops).replace(/</g, "\\u003C");
1171
+ emitTask(`${!headScriptFlushed ? HEAD_SCRIPT : ""}(_$HY.hp=_$HY.hp||{})[${JSON.stringify(key)}]=${payload}`);
1172
+ headScriptFlushed = true;
1173
+ };
158
1174
  sharedConfig.context = context = {
159
1175
  async: true,
160
- assets: [],
161
1176
  nonce,
1177
+ live: {},
1178
+ registerHeadTags(tags) {
1179
+ registerHeadTags(headRegistry, context, tracking,
1180
+ (markup, gateEntry) => {
1181
+ if (!firstFlushed) {
1182
+ headRegistry.eagerHtml += markup;
1183
+ if (gateEntry) gateEntry.emitted = true;
1184
+ } else if (!gateEntry || !tracking.currentBoundaryId) {
1185
+ sink.asset("head-tag", markup);
1186
+ }
1187
+ }, nonce, tags);
1188
+ },
1189
+ registerAsset(type, value) {
1190
+ if (type === "inline-style") {
1191
+ const entry = tracking.registerInlineStyle(value);
1192
+ if (firstFlushed && !tracking.currentBoundaryId && !entry.emitted) {
1193
+ entry.emitted = true;
1194
+ sink.asset("inline-style", entry);
1195
+ }
1196
+ return;
1197
+ }
1198
+ if (tracking.currentBoundaryId && type === "style") {
1199
+ let styles = tracking.boundaryStyles.get(tracking.currentBoundaryId);
1200
+ if (!styles) {
1201
+ styles = new Set();
1202
+ tracking.boundaryStyles.set(tracking.currentBoundaryId, styles);
1203
+ }
1204
+ styles.add(value);
1205
+ }
1206
+ if (!tracking.emittedAssets.has(value)) {
1207
+ tracking.emittedAssets.add(value);
1208
+ if (firstFlushed) sink.asset(type, value);
1209
+ }
1210
+ },
162
1211
  block(p) {
163
- if (!firstFlushed) blockingPromises.push(p);
1212
+ if (!firstFlushed) blockingPromises.add(p);
1213
+ },
1214
+ hold() {
1215
+ holds++;
1216
+ let released = false;
1217
+ return () => {
1218
+ if (released) return;
1219
+ released = true;
1220
+ holds--;
1221
+ if (!holds) queue(flushEnd);
1222
+ };
164
1223
  },
165
1224
  replace(id, payloadFn) {
166
1225
  if (firstFlushed) return;
@@ -170,21 +1229,36 @@ function renderToStream(code, options = {}) {
170
1229
  const last = html.indexOf(`<!--!$/${id}-->`, first + placeholder.length);
171
1230
  html = html.slice(0, first) + resolveSSRSync(escape(payloadFn())) + html.slice(last + placeholder.length + 1);
172
1231
  },
173
- serialize(id, p, wait) {
174
- const serverOnly = sharedConfig.context.noHydrate;
175
- if (!firstFlushed && wait && typeof p === "object" && "then" in p) {
176
- blockingPromises.push(p);
177
- !serverOnly && p.then(d => {
178
- serializer.write(id, d);
179
- }).catch(e => {
180
- serializer.write(id, e);
181
- });
182
- } else if (!serverOnly) serializer.write(id, p);
1232
+ serialize(id, p, deferStream) {
1233
+ if (sharedConfig.context.noHydrate) return;
1234
+ if (!firstFlushed && deferStream && typeof p === "object" && "then" in p) {
1235
+ blockingPromises.add(p);
1236
+ p.then(d => serializer.write(id, d)).catch(e => serializer.write(id, e));
1237
+ } else serializer.write(id, p);
183
1238
  },
184
1239
  escape: escape,
185
1240
  resolve: resolveSSRNode,
186
1241
  ssr: ssr,
187
- registerFragment(key) {
1242
+ registerFragment(key, options) {
1243
+ const revealGroup = options && options.revealGroup;
1244
+ if (revealGroup) {
1245
+ let group = revealGroups.get(revealGroup);
1246
+ if (!group) {
1247
+ group = {
1248
+ order: [],
1249
+ keys: new Set(),
1250
+ released: false
1251
+ };
1252
+ revealGroups.set(revealGroup, group);
1253
+ }
1254
+ if (!group.keys.has(key)) {
1255
+ group.keys.add(key);
1256
+ group.order.push(key);
1257
+ }
1258
+ if (group.released) {
1259
+ throw new Error("registerFragment() for reveal group '" + revealGroup + "' was called after revealFragments(). Ensure template payload is emitted before grouped reveal.");
1260
+ }
1261
+ }
188
1262
  if (!registry.has(key)) {
189
1263
  let resolve, reject;
190
1264
  const p = new Promise((r, rej) => (resolve = r, reject = rej));
@@ -194,7 +1268,7 @@ function renderToStream(code, options = {}) {
194
1268
  queue(flushEnd);
195
1269
  }))
196
1270
  });
197
- serializer.write(key, p);
1271
+ serializer.write(key + "_fr", p);
198
1272
  }
199
1273
  return (value, error) => {
200
1274
  if (registry.has(key)) {
@@ -210,37 +1284,121 @@ function renderToStream(code, options = {}) {
210
1284
  const parent = registry.get(parentKey);
211
1285
  parent.children ||= {};
212
1286
  parent.children[key] = value !== undefined ? value : "";
1287
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
1288
+ propagateBoundaryStyles(key, parentKey, tracking);
1289
+ adoptHeadBoundary(headRegistry, key, parentKey);
213
1290
  item.resolve();
214
1291
  return;
215
1292
  }
216
1293
  if (!completed) {
1294
+ if (error) dropHeadBoundary(headRegistry, key);
217
1295
  if (!firstFlushed) {
218
1296
  queue(() => html = replacePlaceholder(html, key, value !== undefined ? value : ""));
1297
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
219
1298
  item.resolve(error);
220
1299
  } else {
221
- buffer.write(`<template id="${key}">${value !== undefined ? value : " "}</template>`);
222
- pushTask(`$df("${key}")${!scriptFlushed ? ";" + REPLACE_SCRIPT : ""}`);
1300
+ serializeFragmentAssets(key, tracking.boundaryModules, context);
1301
+ const styles = collectStreamStyles(key, tracking, headStyles);
1302
+ const headOps = error ? null : flushHeadFragment(headRegistry, key);
1303
+ if (headOps) emitHeadOps(key, headOps);
1304
+ sink.fragment(key, value !== undefined ? value : " ", {
1305
+ styles,
1306
+ revealGroup,
1307
+ error
1308
+ });
223
1309
  item.resolve(error);
224
- scriptFlushed = true;
225
1310
  }
226
1311
  }
227
1312
  }
228
1313
  return firstFlushed;
229
1314
  };
1315
+ },
1316
+ revealFragments(groupOrKeys) {
1317
+ const keys = resolveRevealKeys(groupOrKeys, true, true);
1318
+ if (!keys) return;
1319
+ sink.reveal(keys, {
1320
+ fallback: false
1321
+ });
1322
+ },
1323
+ revealFallbacks(groupOrKeys) {
1324
+ const keys = resolveRevealKeys(groupOrKeys, false, false);
1325
+ if (!keys) return;
1326
+ sink.reveal(keys, {
1327
+ fallback: true
1328
+ });
230
1329
  }
231
1330
  };
1331
+ applyAssetTracking(context, tracking, manifest, noScripts);
1332
+ context.failRender = failRender;
1333
+ registerEntryAssets(manifest);
232
1334
  let html = createRoot(d => {
233
1335
  dispose = d;
234
- return resolveSSRSync(escape(code()));
1336
+ const res = resolveSSRNode(escape(code()));
1337
+ if (!res.h.length) return res.t[0];
1338
+ rootHoles = [];
1339
+ let out = res.t[0];
1340
+ for (let i = 0; i < res.h.length; i++) {
1341
+ const id = nextHoleId++;
1342
+ rootHoles.push({
1343
+ id,
1344
+ fn: res.h[i]
1345
+ });
1346
+ out += `<!--rh${id}-->` + res.t[i + 1];
1347
+ }
1348
+ for (const p of res.p) blockingPromises.add(p);
1349
+ return out;
235
1350
  }, {
236
1351
  id: renderId
237
1352
  });
1353
+ function resolveRootHoles() {
1354
+ if (!rootHoles) return true;
1355
+ const pending = [];
1356
+ for (const {
1357
+ id,
1358
+ fn
1359
+ } of rootHoles) {
1360
+ const marker = `<!--rh${id}-->`;
1361
+ const res = resolveSSRNode(fn);
1362
+ if (!res.h.length) {
1363
+ html = html.replace(marker, res.t[0]);
1364
+ } else {
1365
+ let out = res.t[0];
1366
+ for (let j = 0; j < res.h.length; j++) {
1367
+ const newId = nextHoleId++;
1368
+ pending.push({
1369
+ id: newId,
1370
+ fn: res.h[j]
1371
+ });
1372
+ out += `<!--rh${newId}-->` + res.t[j + 1];
1373
+ }
1374
+ html = html.replace(marker, out);
1375
+ for (const p of res.p) blockingPromises.add(p);
1376
+ }
1377
+ }
1378
+ if (pending.length) {
1379
+ rootHoles = pending;
1380
+ return false;
1381
+ }
1382
+ rootHoles = null;
1383
+ return true;
1384
+ }
238
1385
  function doShell() {
239
1386
  if (shellCompleted) return;
240
1387
  sharedConfig.context = context;
241
- html = injectAssets(context.assets, html);
242
- if (tasks.length) html = injectScripts(html, tasks, nonce);
243
- buffer.write(html);
1388
+ if (!resolveRootHoles()) return;
1389
+ if (!headShellReady(headRegistry, p => blockingPromises.add(p))) return;
1390
+ headStyles = new Set();
1391
+ for (const url of tracking.emittedAssets) {
1392
+ if (isCssUrl(url)) headStyles.add(url);
1393
+ }
1394
+ serializeRootAssets();
1395
+ const head = renderShellHead(headRegistry, nonce, k => registry.has(k));
1396
+ sink.shell(html, {
1397
+ preloads: tracking.emittedAssets,
1398
+ inlineStyles: tracking.inlineStyles,
1399
+ tasks,
1400
+ head
1401
+ });
244
1402
  tasks = "";
245
1403
  onCompleteShell && onCompleteShell({
246
1404
  write(v) {
@@ -249,53 +1407,72 @@ function renderToStream(code, options = {}) {
249
1407
  });
250
1408
  shellCompleted = true;
251
1409
  }
252
- return {
253
- then(fn) {
254
- function complete() {
255
- dispose();
256
- fn(tmp);
257
- }
258
- if (onCompleteAll) {
259
- let ogComplete = onCompleteAll;
260
- onCompleteAll = options => {
261
- ogComplete(options);
262
- complete();
263
- };
264
- } else onCompleteAll = complete;
265
- queue(flushEnd);
266
- },
267
- pipe(w) {
1410
+ const MIN_DRAIN_TURNS = 8;
1411
+ let lastBlockingSize = -1;
1412
+ let lastRegistrySize = -1;
1413
+ let drainTurn = 0;
1414
+ const scheduleFlush = fn => {
1415
+ const attempt = () => {
1416
+ if (registry.size !== lastRegistrySize || drainTurn++ < MIN_DRAIN_TURNS) {
1417
+ if (registry.size !== lastRegistrySize) drainTurn = 0;
1418
+ lastRegistrySize = registry.size;
1419
+ queue(attempt);
1420
+ return;
1421
+ }
1422
+ fn();
1423
+ };
1424
+ const progressed = blockingPromises.size !== lastBlockingSize;
1425
+ lastBlockingSize = blockingPromises.size;
1426
+ lastRegistrySize = -1;
1427
+ drainTurn = 0;
1428
+ progressed ? queue(attempt) : setTimeout(attempt);
1429
+ };
1430
+ let cachedReadable;
1431
+ let consumer;
1432
+ const claimConsumer = name => {
1433
+ if (consumer && consumer !== name) {
1434
+ throw new Error(`renderToStream result was already consumed via \`${consumer}\`; cannot also consume it via \`${name}\`. Use exactly one of \`pipe\`, \`pipeTo\`, or \`readable\`.`);
1435
+ }
1436
+ consumer = name;
1437
+ };
1438
+ const pipeToImpl = w => {
1439
+ let resolve;
1440
+ const p = new Promise(r => resolve = r);
1441
+ function flush() {
268
1442
  allSettled(blockingPromises).then(() => {
269
- setTimeout(() => {
270
- doShell();
271
- buffer = writable = w;
272
- buffer.write(tmp);
273
- firstFlushed = true;
274
- if (completed) {
275
- dispose();
276
- writable.end();
277
- } else flushEnd();
278
- });
279
- });
280
- },
281
- pipeTo(w) {
282
- return allSettled(blockingPromises).then(() => {
283
- let resolve;
284
- const p = new Promise(r => resolve = r);
285
- setTimeout(() => {
286
- doShell();
1443
+ scheduleFlush(() => {
1444
+ if (dead) return resolve();
1445
+ try {
1446
+ doShell();
1447
+ } catch (err) {
1448
+ failRender(err);
1449
+ return resolve();
1450
+ }
1451
+ if (!shellCompleted) return flush();
287
1452
  const encoder = new TextEncoder();
288
1453
  const writer = w.getWriter();
1454
+ let pendingWrites = Promise.resolve();
1455
+ let ended = false;
1456
+ const failed = () => {
1457
+ if (!ended) {
1458
+ abandon();
1459
+ resolve();
1460
+ }
1461
+ };
1462
+ writer.closed && writer.closed.catch(failed);
289
1463
  writable = {
290
1464
  end() {
291
- writer.releaseLock();
292
- w.close();
293
- resolve();
1465
+ pendingWrites.then(() => {
1466
+ ended = true;
1467
+ writer.releaseLock();
1468
+ w.close().catch(() => {});
1469
+ resolve();
1470
+ });
294
1471
  }
295
1472
  };
296
1473
  buffer = {
297
1474
  write(payload) {
298
- writer.write(encoder.encode(payload));
1475
+ pendingWrites = pendingWrites.then(() => writer.write(encoder.encode(payload))).catch(failed);
299
1476
  }
300
1477
  };
301
1478
  buffer.write(tmp);
@@ -305,9 +1482,83 @@ function renderToStream(code, options = {}) {
305
1482
  writable.end();
306
1483
  } else flushEnd();
307
1484
  });
308
- return p;
309
1485
  });
310
1486
  }
1487
+ flush();
1488
+ return p;
1489
+ };
1490
+ return {
1491
+ then(onFulfilled, onRejected) {
1492
+ const p = new Promise(resolve => {
1493
+ function complete() {
1494
+ dispose();
1495
+ resolve(tmp);
1496
+ }
1497
+ if (onCompleteAll) {
1498
+ let ogComplete = onCompleteAll;
1499
+ onCompleteAll = options => {
1500
+ ogComplete(options);
1501
+ complete();
1502
+ };
1503
+ } else onCompleteAll = complete;
1504
+ function flush() {
1505
+ allSettled(blockingPromises).then(() => {
1506
+ scheduleFlush(() => {
1507
+ try {
1508
+ if (!resolveRootHoles() || !headShellReady(headRegistry, p => blockingPromises.add(p))) return flush();
1509
+ } catch (err) {
1510
+ failRender(err);
1511
+ return resolve(tmp);
1512
+ }
1513
+ queue(flushEnd);
1514
+ });
1515
+ });
1516
+ }
1517
+ flush();
1518
+ });
1519
+ return p.then(onFulfilled, onRejected);
1520
+ },
1521
+ pipe(w) {
1522
+ claimConsumer("pipe");
1523
+ function flush() {
1524
+ allSettled(blockingPromises).then(() => {
1525
+ scheduleFlush(() => {
1526
+ if (dead) return;
1527
+ try {
1528
+ doShell();
1529
+ } catch (err) {
1530
+ failRender(err);
1531
+ try {
1532
+ w.end();
1533
+ } catch (_) {}
1534
+ return;
1535
+ }
1536
+ if (!shellCompleted) return flush();
1537
+ buffer = writable = guardSink(w);
1538
+ buffer.write(tmp);
1539
+ firstFlushed = true;
1540
+ if (completed) {
1541
+ dispose();
1542
+ writable.end();
1543
+ } else flushEnd();
1544
+ });
1545
+ });
1546
+ }
1547
+ flush();
1548
+ },
1549
+ pipeTo(w) {
1550
+ claimConsumer("pipeTo");
1551
+ return pipeToImpl(w);
1552
+ },
1553
+ get readable() {
1554
+ claimConsumer("readable");
1555
+ if (!cachedReadable) {
1556
+ const t = new TransformStream();
1557
+ pipeToImpl(t.writable);
1558
+ cachedReadable = t.readable;
1559
+ }
1560
+ return cachedReadable;
1561
+ }
311
1562
  };
312
1563
  }
313
1564
  function HydrationScript(props) {
@@ -319,11 +1570,637 @@ function HydrationScript(props) {
319
1570
  ...props
320
1571
  }));
321
1572
  }
322
- function ssr(t, ...nodes) {
323
- if (nodes.length) return resolveSSR(t, nodes);
1573
+ function ssrGroup(fn, n) {
1574
+ fn.$g = n;
1575
+ return fn;
1576
+ }
1577
+ function buildAsyncWrap(err, node) {
1578
+ const p = ssrHandleError(err);
1579
+ if (!p) return null;
1580
+ if (node.$rw) return {
1581
+ fn: node,
1582
+ p
1583
+ };
1584
+ const owner = getOwner();
1585
+ const live = sharedConfig.context && sharedConfig.context.liveHoles;
1586
+ const suppress = node.$lhSuppress || live && (live.suppressed || live.sweeping);
1587
+ if (!owner) {
1588
+ if (suppress) node.$lhSuppress = true;
1589
+ return {
1590
+ fn: node,
1591
+ p
1592
+ };
1593
+ }
1594
+ const fn = () => runWithOwner(owner, node);
1595
+ fn.$rw = true;
1596
+ if (suppress) fn.$lhSuppress = true;
1597
+ if (node.$lhSkip) fn.$lhSkip = true;
1598
+ if (node.$lhBinding) fn.$lhBinding = node.$lhBinding;
324
1599
  return {
1600
+ fn,
1601
+ p
1602
+ };
1603
+ }
1604
+ function ssrFirstGroupHit(hole) {
1605
+ try {
1606
+ return hole();
1607
+ } catch (err) {
1608
+ return buildAsyncWrap(err, hole);
1609
+ }
1610
+ }
1611
+ function tryResolveFunctionHole(hole) {
1612
+ let value;
1613
+ try {
1614
+ value = hole();
1615
+ } catch (err) {
1616
+ return buildAsyncWrap(err, hole) || "";
1617
+ }
1618
+ const t = typeof value;
1619
+ if (t === "string") return value;
1620
+ if (t === "number") return "" + value;
1621
+ if (value == null || t === "boolean") return "";
1622
+ return tryResolveString(value);
1623
+ }
1624
+ function mergeTemplateInto(result, node) {
1625
+ result.t[result.t.length - 1] += node.t[0];
1626
+ if (node.t.length > 1) {
1627
+ result.t.push(...node.t.slice(1));
1628
+ result.h.push(...node.h);
1629
+ result.p.push(...node.p);
1630
+ }
1631
+ }
1632
+ function appendResolvedNode(result, node) {
1633
+ if (node.fn !== undefined) {
1634
+ result.h.push(node.fn);
1635
+ result.p.push(node.p);
1636
+ result.t.push("");
1637
+ } else if (node.merge !== undefined) mergeTemplateInto(result, node.merge);else resolveSSRNode(node.bail, result);
1638
+ }
1639
+ let _lastGroupFn = null;
1640
+ let _lastGroupArr = null;
1641
+ let _lastGroupErr = null;
1642
+ function ssrGroupSlot(fn, idx) {
1643
+ return () => {
1644
+ if (idx > 0 && _lastGroupFn === fn) {
1645
+ if (_lastGroupArr !== null) return _lastGroupArr[idx];
1646
+ throw _lastGroupErr;
1647
+ }
1648
+ _lastGroupFn = fn;
1649
+ _lastGroupArr = null;
1650
+ _lastGroupErr = null;
1651
+ try {
1652
+ _lastGroupArr = fn();
1653
+ return _lastGroupArr[idx];
1654
+ } catch (err) {
1655
+ _lastGroupErr = err;
1656
+ throw err;
1657
+ }
1658
+ };
1659
+ }
1660
+ const holePositionCache = new WeakMap();
1661
+ function holeContentPositions(t) {
1662
+ let cached = holePositionCache.get(t);
1663
+ if (cached) return cached;
1664
+ const pos = [];
1665
+ const openOff = [];
1666
+ const closeOff = [];
1667
+ let inTag = false;
1668
+ let quote = "";
1669
+ let curOpen = null;
1670
+ let scanningName = false;
1671
+ for (let i = 0; i < t.length; i++) {
1672
+ const seg = t[i];
1673
+ let close = -1;
1674
+ const openAtStart = inTag;
1675
+ let reopened = false;
1676
+ for (let j = 0; j < seg.length; j++) {
1677
+ const ch = seg[j];
1678
+ if (quote) {
1679
+ if (ch === quote) quote = "";
1680
+ } else if (inTag) {
1681
+ if (scanningName && (ch === " " || ch === "\t" || ch === "\n" || ch === ">" || ch === "/")) {
1682
+ scanningName = false;
1683
+ curOpen = {
1684
+ seg: i,
1685
+ off: j
1686
+ };
1687
+ }
1688
+ if (ch === '"' || ch === "'") quote = ch;else if (ch === ">") {
1689
+ inTag = false;
1690
+ if (openAtStart && !reopened && close === -1) close = j;
1691
+ curOpen = null;
1692
+ }
1693
+ } else if (ch === "<") {
1694
+ inTag = true;
1695
+ scanningName = true;
1696
+ reopened = true;
1697
+ curOpen = null;
1698
+ }
1699
+ }
1700
+ if (inTag && scanningName) {
1701
+ scanningName = false;
1702
+ curOpen = {
1703
+ seg: i,
1704
+ off: seg.length
1705
+ };
1706
+ }
1707
+ closeOff.push(close);
1708
+ openOff.push(inTag && curOpen && curOpen.seg === i ? curOpen.off : -1);
1709
+ if (i < t.length - 1) pos.push(!inTag);
1710
+ }
1711
+ cached = {
1712
+ pos,
1713
+ openOff,
1714
+ closeOff
1715
+ };
1716
+ holePositionCache.set(t, cached);
1717
+ return cached;
1718
+ }
1719
+ function createLiveHoles(sink, scoped) {
1720
+ let nextId = 0;
1721
+ const stamp = typeof creationStamp === "function" ? creationStamp : () => 0;
1722
+ const inScope = scoped && typeof inServerComponentScope === "function" ? inServerComponentScope : null;
1723
+ const stripMarkers = html => html.replace(/<!--lh:\/?\d+-->/g, "");
1724
+ function resolveHoleValue(hole) {
1725
+ const result = {
1726
+ t: [""],
1727
+ h: [],
1728
+ p: []
1729
+ };
1730
+ try {
1731
+ resolveSSRNode(hole(), result);
1732
+ } catch (err) {
1733
+ const wrap = buildAsyncWrap(err, hole);
1734
+ if (!wrap) throw err;
1735
+ result.h.push(wrap.fn);
1736
+ result.p.push(wrap.p);
1737
+ result.t.push("");
1738
+ }
1739
+ return result;
1740
+ }
1741
+ function closeChildren(b) {
1742
+ for (const c of b.children) {
1743
+ c.closed = true;
1744
+ if (c.key) sink.closeBinding(c.key);
1745
+ closeChildren(c);
1746
+ }
1747
+ b.children.length = 0;
1748
+ }
1749
+ const engine = {
1750
+ suppressed: 0,
1751
+ sweeping: false,
1752
+ parent: null,
1753
+ recordStamp: 0,
1754
+ gateHit: false,
1755
+ content(hole) {
1756
+ if (hole.$lhSuppress) {
1757
+ const r = {
1758
+ t: [""],
1759
+ h: [],
1760
+ p: []
1761
+ };
1762
+ engine.suppressed++;
1763
+ try {
1764
+ try {
1765
+ resolveSSRNode(hole(), r);
1766
+ } catch (err) {
1767
+ const wrap = buildAsyncWrap(err, hole);
1768
+ if (wrap) {
1769
+ r.h.push(wrap.fn);
1770
+ r.p.push(wrap.p);
1771
+ r.t.push("");
1772
+ }
1773
+ }
1774
+ } finally {
1775
+ engine.suppressed--;
1776
+ }
1777
+ const b = hole.$lhBinding;
1778
+ if (b && !b.closed && !r.h.length && !engine.sweeping) {
1779
+ b.last = stripMarkers(r.t[0]);
1780
+ }
1781
+ return r.h.length ? r : r.t[0];
1782
+ }
1783
+ if (engine.suppressed || engine.sweeping) return null;
1784
+ if (hole.$lhSkip) return null;
1785
+ if (inScope && !inScope()) return null;
1786
+ const recordsBefore = engine.recordStamp;
1787
+ const ownersBefore = stamp();
1788
+ const owner = getOwner();
1789
+ const b = {
1790
+ key: null,
1791
+ children: [],
1792
+ last: null,
1793
+ closed: false,
1794
+ sweep() {
1795
+ if (b.closed) return;
1796
+ const prevSweeping = engine.sweeping;
1797
+ engine.sweeping = true;
1798
+ engine.gateHit = false;
1799
+ const sweepOwnersBefore = stamp();
1800
+ let res;
1801
+ try {
1802
+ res = owner ? runWithOwner(owner, () => resolveHoleValue(hole)) : resolveHoleValue(hole);
1803
+ } catch (err) {
1804
+ b.closed = true;
1805
+ sink.closeBinding(b.key);
1806
+ sink.error(b.key, String(err && err.message || err));
1807
+ return;
1808
+ } finally {
1809
+ engine.sweeping = prevSweeping;
1810
+ }
1811
+ if (engine.gateHit || stamp() !== sweepOwnersBefore) {
1812
+ b.closed = true;
1813
+ sink.closeBinding(b.key);
1814
+ return;
1815
+ }
1816
+ if (res.h.length) return;
1817
+ const html = res.t[0];
1818
+ if (b.last === null || html === b.last) return;
1819
+ b.last = html;
1820
+ closeChildren(b);
1821
+ sink.hole(b.key, html);
1822
+ }
1823
+ };
1824
+ if (engine.parent) engine.parent.children.push(b);
1825
+ const prevParent = engine.parent;
1826
+ engine.parent = b;
1827
+ let value;
1828
+ let escalated = null;
1829
+ try {
1830
+ value = hole();
1831
+ } catch (err) {
1832
+ const wrap = buildAsyncWrap(err, hole);
1833
+ if (!wrap) {
1834
+ engine.parent = prevParent;
1835
+ closeChildren(b);
1836
+ return "";
1837
+ }
1838
+ escalated = wrap;
1839
+ }
1840
+ if (!escalated && (typeof value === "function" && value.$lhSkip || value !== null && typeof value === "object" && value.$slot)) {
1841
+ engine.parent = prevParent;
1842
+ const r = {
1843
+ t: [""],
1844
+ h: [],
1845
+ p: []
1846
+ };
1847
+ engine.suppressed++;
1848
+ try {
1849
+ resolveSSRNode(value, r);
1850
+ } finally {
1851
+ engine.suppressed--;
1852
+ }
1853
+ return r.h.length ? r : r.t[0];
1854
+ }
1855
+ let res;
1856
+ if (escalated) {
1857
+ closeChildren(b);
1858
+ escalated.fn.$lhSuppress = true;
1859
+ escalated.fn.$lhBinding = b;
1860
+ res = {
1861
+ t: ["", ""],
1862
+ h: [escalated.fn],
1863
+ p: [escalated.p]
1864
+ };
1865
+ } else {
1866
+ res = {
1867
+ t: [""],
1868
+ h: [],
1869
+ p: []
1870
+ };
1871
+ try {
1872
+ resolveSSRNode(value, res);
1873
+ } catch (_) {
1874
+ engine.parent = prevParent;
1875
+ closeChildren(b);
1876
+ return "";
1877
+ }
1878
+ }
1879
+ engine.parent = prevParent;
1880
+ if (engine.recordStamp !== recordsBefore || stamp() !== ownersBefore) {
1881
+ return res.h.length ? res : res.t[0];
1882
+ }
1883
+ const id = nextId++;
1884
+ const key = b.key = "lh:" + id;
1885
+ const open = `<!--lh:${id}-->`;
1886
+ const close = `<!--lh:/${id}-->`;
1887
+ if (!res.h.length) {
1888
+ b.last = stripMarkers(res.t[0]);
1889
+ sink.openBinding(key, b);
1890
+ return open + res.t[0] + close;
1891
+ }
1892
+ const t = res.t.slice();
1893
+ t[0] = open + t[0];
1894
+ t[t.length - 1] += close;
1895
+ sink.openBinding(key, b);
1896
+ return {
1897
+ t,
1898
+ h: res.h,
1899
+ p: res.p
1900
+ };
1901
+ },
1902
+ mint() {
1903
+ return nextId++;
1904
+ },
1905
+ active() {
1906
+ return !inScope || inScope();
1907
+ },
1908
+ attr(cap) {
1909
+ const owner = getOwner();
1910
+ const b = {
1911
+ key: "lha:" + cap.id,
1912
+ children: [],
1913
+ last: cap.base,
1914
+ closed: false,
1915
+ sweep() {
1916
+ if (b.closed) return;
1917
+ const prevSweeping = engine.sweeping;
1918
+ engine.sweeping = true;
1919
+ engine.gateHit = false;
1920
+ const sweepOwnersBefore = stamp();
1921
+ let html = "";
1922
+ try {
1923
+ let group = null;
1924
+ let groupVal = null;
1925
+ const run = () => {
1926
+ for (const part of cap.parts) {
1927
+ if (typeof part === "string") {
1928
+ html += part;
1929
+ continue;
1930
+ }
1931
+ let v;
1932
+ if (part.g) {
1933
+ if (group !== part.g) {
1934
+ group = part.g;
1935
+ groupVal = part.g();
1936
+ }
1937
+ v = groupVal[part.i];
1938
+ } else {
1939
+ v = part.f();
1940
+ }
1941
+ const vt = typeof v;
1942
+ if (vt === "string" || vt === "number") html += v;
1943
+ }
1944
+ };
1945
+ owner ? runWithOwner(owner, run) : run();
1946
+ } catch (err) {
1947
+ if (ssrHandleError(err, true)) return;
1948
+ b.closed = true;
1949
+ sink.closeBinding(b.key);
1950
+ sink.error("lha:" + cap.id, String(err && err.message || err));
1951
+ return;
1952
+ } finally {
1953
+ engine.sweeping = prevSweeping;
1954
+ }
1955
+ if (engine.gateHit || stamp() !== sweepOwnersBefore) {
1956
+ b.closed = true;
1957
+ sink.closeBinding(b.key);
1958
+ return;
1959
+ }
1960
+ if (html === b.last) return;
1961
+ const before = attrNames(b.last);
1962
+ const after = attrNames(html);
1963
+ const removed = before.filter(n => !after.includes(n));
1964
+ b.last = html;
1965
+ sink.attr(String(cap.id), html, removed);
1966
+ }
1967
+ };
1968
+ sink.openBinding(b.key, b);
1969
+ }
1970
+ };
1971
+ return engine;
1972
+ }
1973
+ function attrNames(text) {
1974
+ const names = [];
1975
+ const re = /(?:^|\s)([^\s=/>"']+)(?:="[^"]*")?/g;
1976
+ let m;
1977
+ while (m = re.exec(text)) names.push(m[1]);
1978
+ return names;
1979
+ }
1980
+ function ssr(t) {
1981
+ const len = arguments.length;
1982
+ if (len === 1) return {
325
1983
  t
326
1984
  };
1985
+ let s = t[0];
1986
+ let result = null;
1987
+ let lastGroup = null;
1988
+ let lastGroupVal = null;
1989
+ let lastGroupIdx = 0;
1990
+ const live = sharedConfig.context && sharedConfig.context.liveHoles;
1991
+ const hp = live ? holeContentPositions(t) : null;
1992
+ let lastOpen = null;
1993
+ let cap = null;
1994
+ if (live && hp.openOff[0] >= 0) lastOpen = {
1995
+ r: null,
1996
+ seg: -1,
1997
+ off: hp.openOff[0]
1998
+ };
1999
+ const captureStart = () => {
2000
+ if (cap) return true;
2001
+ if (!lastOpen || live.suppressed || live.sweeping || !live.active()) return false;
2002
+ if (lastOpen.r !== result || result !== null && lastOpen.seg !== result.t.length - 1) {
2003
+ return false;
2004
+ }
2005
+ const id = live.mint();
2006
+ const inject = ` data-lha="${id}"`;
2007
+ let prefix;
2008
+ if (result === null) {
2009
+ s = s.slice(0, lastOpen.off) + inject + s.slice(lastOpen.off);
2010
+ prefix = s.slice(lastOpen.off + inject.length);
2011
+ } else {
2012
+ const seg = result.t[lastOpen.seg];
2013
+ result.t[lastOpen.seg] = seg.slice(0, lastOpen.off) + inject + seg.slice(lastOpen.off);
2014
+ prefix = result.t[lastOpen.seg].slice(lastOpen.off + inject.length);
2015
+ }
2016
+ cap = {
2017
+ id,
2018
+ parts: [prefix],
2019
+ base: prefix
2020
+ };
2021
+ return true;
2022
+ };
2023
+ for (let i = 1; i < len; i++) {
2024
+ const hole = arguments[i];
2025
+ const ht = typeof hole;
2026
+ if (ht === "string") {
2027
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
2028
+ if (cap) {
2029
+ cap.parts.push(hole);
2030
+ cap.base += hole;
2031
+ }
2032
+ } else if (ht === "number") {
2033
+ if (result === null) s += hole;else result.t[result.t.length - 1] += hole;
2034
+ if (cap) {
2035
+ cap.parts.push("" + hole);
2036
+ cap.base += hole;
2037
+ }
2038
+ } else if (hole == null || ht === "boolean") ; else if (ht === "function" && hole.$g) {
2039
+ let value;
2040
+ let hasValue = false;
2041
+ if (lastGroup !== hole) {
2042
+ const r = ssrFirstGroupHit(hole);
2043
+ if (r !== null) {
2044
+ lastGroup = hole;
2045
+ lastGroupVal = r;
2046
+ lastGroupIdx = 0;
2047
+ if (!Array.isArray(r) && result === null) {
2048
+ result = {
2049
+ t: [s],
2050
+ h: [],
2051
+ p: []
2052
+ };
2053
+ s = "";
2054
+ }
2055
+ }
2056
+ }
2057
+ if (lastGroup === hole) {
2058
+ if (Array.isArray(lastGroupVal)) {
2059
+ value = lastGroupVal[lastGroupIdx++];
2060
+ hasValue = true;
2061
+ if (live && !hp.pos[i - 1] && captureStart()) {
2062
+ cap.parts.push({
2063
+ g: hole,
2064
+ i: lastGroupIdx - 1
2065
+ });
2066
+ }
2067
+ } else {
2068
+ cap = null;
2069
+ result.h.push(ssrGroupSlot(lastGroupVal.fn, lastGroupIdx++));
2070
+ result.p.push(lastGroupVal.p);
2071
+ result.t.push("");
2072
+ }
2073
+ }
2074
+ if (hasValue) {
2075
+ const vt = typeof value;
2076
+ if (vt === "string" || vt === "number") {
2077
+ if (result === null) s += value;else result.t[result.t.length - 1] += value;
2078
+ if (cap && !hp.pos[i - 1]) cap.base += value;
2079
+ } else if (value == null || vt === "boolean") ; else if (result !== null) {
2080
+ resolveSSRNode(value, result);
2081
+ } else {
2082
+ const rs = tryResolveString(value);
2083
+ if (typeof rs === "string") {
2084
+ s += rs;
2085
+ } else {
2086
+ result = {
2087
+ t: [s],
2088
+ h: [],
2089
+ p: []
2090
+ };
2091
+ s = "";
2092
+ if (rs.merge !== undefined) mergeTemplateInto(result, rs.merge);else resolveSSRNode(rs.bail, result);
2093
+ }
2094
+ }
2095
+ }
2096
+ } else if (ht === "function") {
2097
+ let liveNode = null;
2098
+ if (live && hp.pos[i - 1] && (liveNode = live.content(hole)) !== null) {
2099
+ if (typeof liveNode === "string") {
2100
+ if (result === null) s += liveNode;else result.t[result.t.length - 1] += liveNode;
2101
+ } else {
2102
+ if (result === null) {
2103
+ result = {
2104
+ t: [s],
2105
+ h: [],
2106
+ p: []
2107
+ };
2108
+ s = "";
2109
+ }
2110
+ resolveSSRNode(liveNode, result);
2111
+ }
2112
+ } else if (result !== null) {
2113
+ const inTag = live && !hp.pos[i - 1];
2114
+ const capturing = inTag && captureStart();
2115
+ const li = capturing ? result.t.length - 1 : 0;
2116
+ const before = capturing ? result.t[li].length : 0;
2117
+ if (live) live.suppressed++;
2118
+ try {
2119
+ resolveSSRNode(hole, result);
2120
+ } finally {
2121
+ if (live) live.suppressed--;
2122
+ }
2123
+ if (capturing) {
2124
+ if (result.t.length - 1 === li) {
2125
+ cap.base += result.t[li].slice(before);
2126
+ cap.parts.push({
2127
+ f: hole
2128
+ });
2129
+ } else {
2130
+ cap = null;
2131
+ }
2132
+ }
2133
+ } else {
2134
+ const capturing = live && !hp.pos[i - 1] && captureStart();
2135
+ const r = tryResolveFunctionHole(hole);
2136
+ if (typeof r === "string") {
2137
+ s += r;
2138
+ if (capturing) {
2139
+ cap.base += r;
2140
+ cap.parts.push({
2141
+ f: hole
2142
+ });
2143
+ }
2144
+ } else {
2145
+ if (capturing) cap = null;
2146
+ result = {
2147
+ t: [s],
2148
+ h: [],
2149
+ p: []
2150
+ };
2151
+ s = "";
2152
+ appendResolvedNode(result, r);
2153
+ }
2154
+ }
2155
+ } else if (result !== null) {
2156
+ resolveSSRNode(hole, result);
2157
+ } else {
2158
+ const r = tryResolveString(hole);
2159
+ if (typeof r === "string") {
2160
+ s += r;
2161
+ } else {
2162
+ result = {
2163
+ t: [s],
2164
+ h: [],
2165
+ p: []
2166
+ };
2167
+ s = "";
2168
+ appendResolvedNode(result, r);
2169
+ }
2170
+ }
2171
+ const next = t[i];
2172
+ if (live) {
2173
+ if (cap) {
2174
+ const co = hp.closeOff[i];
2175
+ if (co >= 0) {
2176
+ const tail = next.slice(0, co);
2177
+ cap.parts.push(tail);
2178
+ cap.base += tail;
2179
+ live.attr(cap);
2180
+ cap = null;
2181
+ } else {
2182
+ cap.parts.push(next);
2183
+ cap.base += next;
2184
+ }
2185
+ }
2186
+ if (hp.openOff[i] >= 0) {
2187
+ lastOpen = result === null ? {
2188
+ r: null,
2189
+ seg: -1,
2190
+ off: s.length + hp.openOff[i]
2191
+ } : {
2192
+ r: result,
2193
+ seg: result.t.length - 1,
2194
+ off: result.t[result.t.length - 1].length + hp.openOff[i]
2195
+ };
2196
+ }
2197
+ }
2198
+ if (result === null) s += next;else result.t[result.t.length - 1] += next;
2199
+ }
2200
+ if (result === null) return {
2201
+ t: s
2202
+ };
2203
+ return result;
327
2204
  }
328
2205
  function ssrClassName(value) {
329
2206
  if (!value) return "";
@@ -336,7 +2213,7 @@ function ssrClassName(value) {
336
2213
  classValue = !!value[key];
337
2214
  if (!key || key === "undefined" || !classValue) continue;
338
2215
  i && (result += " ");
339
- result += escape(key);
2216
+ result += escape(key, true);
340
2217
  }
341
2218
  return result;
342
2219
  }
@@ -346,8 +2223,8 @@ function ssrStyle(value) {
346
2223
  let result = "";
347
2224
  const k = Object.keys(value);
348
2225
  for (let i = 0; i < k.length; i++) {
349
- const s = k[i];
350
- const v = value[s];
2226
+ const s = escape(k[i], true);
2227
+ const v = value[k[i]];
351
2228
  if (v != undefined) {
352
2229
  if (i) result += ";";
353
2230
  const r = escape(v, true);
@@ -362,10 +2239,11 @@ function ssrStyleProperty(name, value) {
362
2239
  return value != null ? name + value : "";
363
2240
  }
364
2241
  function ssrElement(tag, props, children, needsId) {
2242
+ const hk = needsId ? ssrHydrationKey() : "";
365
2243
  if (props == null) props = {};else if (typeof props === "function") props = props();
366
2244
  const skipChildren = VOID_ELEMENTS.test(tag);
367
2245
  const keys = Object.keys(props);
368
- let result = `<${tag}${needsId ? ssrHydrationKey() : ""} `;
2246
+ let result = `<${tag}${hk} `;
369
2247
  for (let i = 0; i < keys.length; i++) {
370
2248
  const prop = keys[i];
371
2249
  if (ChildProperties.has(prop)) {
@@ -404,18 +2282,31 @@ function escape(s, attr) {
404
2282
  const t = typeof s;
405
2283
  if (t !== "string") {
406
2284
  if (!attr && Array.isArray(s)) {
2285
+ const joined = tryJoinPlainSSRArray(s);
2286
+ if (joined !== undefined) return joined;
407
2287
  s = s.slice();
408
2288
  for (let i = 0; i < s.length; i++) s[i] = escape(s[i]);
409
2289
  return s;
410
2290
  }
411
- if (attr && t === "boolean") return s;
2291
+ if (attr) {
2292
+ if (s == null || t === "boolean" || t === "number") return s;
2293
+ return escape(String(s), attr);
2294
+ }
412
2295
  return s;
413
2296
  }
2297
+ const i = s.search(attr ? ESCAPE_ATTR : ESCAPE_CONTENT);
2298
+ if (i < 0) return s;
2299
+ return escapeSlow(s, attr, i);
2300
+ }
2301
+ const ESCAPE_CONTENT = /[&<]/;
2302
+ const ESCAPE_ATTR = /[&"]/;
2303
+ function escapeSlow(s, attr, start) {
414
2304
  const delim = attr ? '"' : "<";
2305
+ const delimCode = attr ? 34 : 60;
415
2306
  const escDelim = attr ? "&quot;" : "&lt;";
416
- let iDelim = s.indexOf(delim);
417
- let iAmp = s.indexOf("&");
418
- if (iDelim < 0 && iAmp < 0) return s;
2307
+ const c0 = s.charCodeAt(start);
2308
+ let iDelim = c0 === delimCode ? start : s.indexOf(delim, start);
2309
+ let iAmp = c0 === 38 ? start : s.indexOf("&", start);
419
2310
  let left = 0,
420
2311
  out = "";
421
2312
  while (iDelim >= 0 && iAmp >= 0) {
@@ -446,94 +2337,142 @@ function escape(s, attr) {
446
2337
  }
447
2338
  return left < s.length ? out + s.substring(left) : out;
448
2339
  }
449
- function mergeProps(...sources) {
450
- const target = {};
451
- for (let i = 0; i < sources.length; i++) {
452
- let source = sources[i];
453
- if (typeof source === "function") source = source();
454
- if (source) {
455
- const descriptors = Object.getOwnPropertyDescriptors(source);
456
- for (const key in descriptors) {
457
- if (key in target) continue;
458
- Object.defineProperty(target, key, {
459
- enumerable: true,
460
- get() {
461
- for (let i = sources.length - 1; i >= 0; i--) {
462
- const v = (sources[i] || {})[key];
463
- if (v !== undefined) return v;
464
- }
465
- }
466
- });
467
- }
2340
+ function tryJoinPlainSSRArray(nodes) {
2341
+ if (nodes.length === 0) return undefined;
2342
+ let out = "";
2343
+ for (let i = 0, len = nodes.length; i < len; i++) {
2344
+ const node = nodes[i];
2345
+ if (node == null || typeof node !== "object" || node.h || typeof node.t !== "string") {
2346
+ return undefined;
468
2347
  }
2348
+ out += node.t;
469
2349
  }
470
- return target;
2350
+ return out;
471
2351
  }
472
2352
  function getHydrationKey() {
473
2353
  const hydrate = sharedConfig.context;
474
- return hydrate && !hydrate.noHydrate && sharedConfig.getNextContextId();
475
- }
476
- function useAssets(fn) {
477
- sharedConfig.context.assets.push(() => resolveSSRSync(escape(fn())));
2354
+ return hydrate && sharedConfig.getNextContextId();
478
2355
  }
479
- function getAssets() {
480
- const assets = sharedConfig.context.assets;
481
- let out = "";
482
- for (let i = 0, len = assets.length; i < len; i++) out += assets[i]();
483
- return out;
2356
+ function applyRef(r, element) {
2357
+ Array.isArray(r) ? r.flat(Infinity).forEach(f => f && f(element)) : r(element);
484
2358
  }
485
2359
  function generateHydrationScript({
486
2360
  eventNames = ["click", "input"],
487
2361
  nonce
488
2362
  } = {}) {
489
- return `<script${nonce ? ` nonce="${nonce}"` : ""}>window._$HY||(e=>{let t=e=>e&&e.hasAttribute&&(e.hasAttribute("_hk")?e:t(e.host&&e.host.nodeType?e.host:e.parentNode));["${eventNames.join('", "')}"].forEach((o=>document.addEventListener(o,(o=>{if(!e.events)return;let s=t(o.composedPath&&o.composedPath()[0]||o.target);s&&!e.completed.has(s)&&e.events.push([s,o])}))))})(_$HY={events:[],completed:new WeakSet,r:{},fe(){}});</script><!--xs-->`;
490
- }
491
- function Hydration(props) {
492
- if (!sharedConfig.context.noHydrate) return props.children;
493
- const context = sharedConfig.context;
494
- sharedConfig.context = {
495
- ...context,
496
- noHydrate: false
497
- };
498
- const res = props.children;
499
- sharedConfig.context = context;
500
- return res;
501
- }
502
- function NoHydration(props) {
503
- let context = sharedConfig.context;
504
- if (context) sharedConfig.context = {
505
- ...context,
506
- noHydrate: true
507
- };
508
- const res = props.children;
509
- if (context) sharedConfig.context = context;
510
- return res;
2363
+ return `<script${nonce ? ` nonce="${nonce}"` : ""}>window._$HY||(e=>{let t=e=>e&&e.hasAttribute&&(e.hasAttribute("_hk")?e:t(e.host&&e.host.nodeType?e.host:e.parentNode));["${eventNames.join('","')}"].forEach((o=>document.addEventListener(o,(o=>{if(!e.events)return;let s=t(o.composedPath&&o.composedPath()[0]||o.target);s&&!e.completed.has(s)&&e.events.push([s,o])}))))})(_$HY={events:[],completed:new WeakSet,r:{},fe(){}});</script><!--xs-->`;
511
2364
  }
512
2365
  function queue(fn) {
513
2366
  return Promise.resolve().then(fn);
514
2367
  }
515
2368
  function allSettled(promises) {
516
- let length = promises.length;
2369
+ let size = promises.size;
517
2370
  return Promise.allSettled(promises).then(() => {
518
- if (promises.length !== length) return allSettled(promises);
2371
+ if (promises.size !== size) return allSettled(promises);
519
2372
  return;
520
2373
  });
521
2374
  }
522
- function injectAssets(assets, html) {
523
- if (!assets || !assets.length) return html;
524
- let out = "";
525
- for (let i = 0, len = assets.length; i < len; i++) out += assets[i]();
526
- const index = html.indexOf("</head>");
527
- if (index === -1) return html;
528
- return html.slice(0, index) + out + html.slice(index);
2375
+ function assembleDocument(html, emittedAssets, inlineStyles, scripts, nonce, headTags, onHead) {
2376
+ const scriptTag = scripts ? `<script${nonce ? ` nonce="${nonce}"` : ""}>${scripts}</script>` : "";
2377
+ const headTagsHtml = headTags ? headTags.html : "";
2378
+ const headPrelude = headTags ? headTags.prelude : "";
2379
+ if (!onHead && !headTagsHtml && !headPrelude && !(emittedAssets && emittedAssets.size) && !(inlineStyles && inlineStyles.size)) {
2380
+ if (!scriptTag) return html;
2381
+ const xs = html.indexOf("<!--xs-->");
2382
+ return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
2383
+ }
2384
+ if (headPrelude) {
2385
+ const open = html.match(/<head(?:\s[^>]*)?>/);
2386
+ if (open) {
2387
+ const at = open.index + open[0].length;
2388
+ html = html.slice(0, at) + headPrelude + html.slice(at);
2389
+ }
2390
+ }
2391
+ const headIdx = html.indexOf("</head>");
2392
+ if (headIdx === -1) {
2393
+ if (onHead) {
2394
+ onHead(headPrelude + headTagsHtml + renderHeadAssets(emittedAssets, inlineStyles, nonce));
2395
+ }
2396
+ if (!scriptTag) return html;
2397
+ const xs = html.indexOf("<!--xs-->");
2398
+ return xs === -1 ? html + scriptTag : html.slice(0, xs) + scriptTag + html.slice(xs);
2399
+ }
2400
+ const head = headTagsHtml + renderHeadAssets(emittedAssets, inlineStyles, nonce);
2401
+ if (!scriptTag) return html.slice(0, headIdx) + head + html.slice(headIdx);
2402
+ const xsIdx = html.indexOf("<!--xs-->");
2403
+ if (xsIdx === -1) return html.slice(0, headIdx) + head + html.slice(headIdx) + scriptTag;
2404
+ 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);
2405
+ }
2406
+ function renderHeadAssets(emittedAssets, inlineStyles, nonce) {
2407
+ let head = "";
2408
+ if (emittedAssets && emittedAssets.size) {
2409
+ for (const url of emittedAssets) {
2410
+ head += isCssUrl(url) ? `<link rel="stylesheet" href="${url}">` : `<link rel="modulepreload" href="${url}">`;
2411
+ }
2412
+ }
2413
+ if (inlineStyles && inlineStyles.size) {
2414
+ for (const entry of inlineStyles.values()) {
2415
+ if (entry.emitted) continue;
2416
+ entry.emitted = true;
2417
+ head += renderInlineStyle(entry, nonce);
2418
+ }
2419
+ }
2420
+ return head;
2421
+ }
2422
+ function serializeFragmentAssets(key, boundaryModules, context, name = key) {
2423
+ const map = boundaryModules.get(key);
2424
+ if (!map || !Object.keys(map).length) return;
2425
+ context.serialize(name + "_assets", map);
2426
+ }
2427
+ function propagateBoundaryStyles(childKey, parentKey, tracking) {
2428
+ const childStyles = tracking.getBoundaryStyles(childKey);
2429
+ if (!childStyles) return;
2430
+ let parentStyles = tracking.boundaryStyles.get(parentKey);
2431
+ if (!parentStyles) {
2432
+ parentStyles = new Set();
2433
+ tracking.boundaryStyles.set(parentKey, parentStyles);
2434
+ }
2435
+ for (const url of childStyles) {
2436
+ parentStyles.add(url);
2437
+ }
2438
+ }
2439
+ function collectStreamStyles(key, tracking, headStyles) {
2440
+ const styles = tracking.getBoundaryStyles(key);
2441
+ const links = [];
2442
+ const inline = [];
2443
+ if (!styles) return {
2444
+ links,
2445
+ inline
2446
+ };
2447
+ for (const entry of styles) {
2448
+ if (typeof entry === "string") {
2449
+ if (!headStyles || !headStyles.has(entry)) links.push(entry);
2450
+ } else if (entry.emitted) {
2451
+ continue;
2452
+ } else if (entry.attrHtml !== undefined) {
2453
+ entry.emitted = true;
2454
+ links.push(entry);
2455
+ } else {
2456
+ entry.emitted = true;
2457
+ inline.push(entry);
2458
+ }
2459
+ }
2460
+ return {
2461
+ links,
2462
+ inline
2463
+ };
529
2464
  }
530
- function injectScripts(html, scripts, nonce) {
531
- const tag = `<script${nonce ? ` nonce="${nonce}"` : ""}>${scripts}</script>`;
532
- const index = html.indexOf("<!--xs-->");
533
- if (index > -1) {
534
- return html.slice(0, index) + tag + html.slice(index);
2465
+ function escapeStyleContent(content) {
2466
+ return content.replace(/<\/(style)/gi, "<\\/$1");
2467
+ }
2468
+ function renderInlineStyle(entry, nonce) {
2469
+ let attrs = "";
2470
+ if (entry.attrs) {
2471
+ for (const name in entry.attrs) {
2472
+ attrs += ` ${name}="${escape(String(entry.attrs[name]), true)}"`;
2473
+ }
535
2474
  }
536
- return html + tag;
2475
+ return `<style${nonce ? ` nonce="${nonce}"` : ""} data-asset="${escape(entry.id, true)}"${attrs}>${escapeStyleContent(entry.content)}</style>`;
537
2476
  }
538
2477
  function waitForFragments(registry, key) {
539
2478
  for (const k of [...registry.keys()].reverse()) {
@@ -563,19 +2502,48 @@ function flattenClassList(list, result) {
563
2502
  if (Array.isArray(item)) flattenClassList(item, result);else if (typeof item === "object" && item != null) Object.assign(result, item);else if (item || item === 0) result[item] = true;
564
2503
  }
565
2504
  }
566
- function resolveSSR(template, holes, result = {
567
- t: [""],
568
- h: [],
569
- p: []
570
- }) {
571
- for (let i = 0; i < holes.length; i++) {
572
- const hole = holes[i];
573
- result.t[result.t.length - 1] += template[i];
574
- if (hole == null || hole === true || hole === false) continue;
575
- resolveSSRNode(hole, result);
2505
+ function tryResolveString(node) {
2506
+ const t = typeof node;
2507
+ if (t === "string") return node;
2508
+ if (t === "number") return "" + node;
2509
+ if (node == null || t === "boolean") return "";
2510
+ if (t === "object") {
2511
+ if (Array.isArray(node)) {
2512
+ const joined = tryJoinPlainSSRArray(node);
2513
+ if (joined !== undefined) return joined;
2514
+ let s = "";
2515
+ let prevNonObj = false;
2516
+ for (let i = 0, len = node.length; i < len; i++) {
2517
+ const item = node[i];
2518
+ const itemNonObj = item !== null && typeof item !== "object";
2519
+ if (prevNonObj && itemNonObj) s += "<!--!$-->";
2520
+ prevNonObj = itemNonObj;
2521
+ const r = tryResolveString(item);
2522
+ if (typeof r !== "string") return {
2523
+ bail: node
2524
+ };
2525
+ s += r;
2526
+ }
2527
+ return s;
2528
+ }
2529
+ if (node.h && node.h.length > 0) return {
2530
+ merge: node
2531
+ };
2532
+ if (node.t === undefined) {
2533
+ return "";
2534
+ }
2535
+ return Array.isArray(node.t) ? node.t[0] : node.t;
576
2536
  }
577
- result.t[result.t.length - 1] += template[template.length - 1];
578
- return result;
2537
+ if (t === "function") {
2538
+ let v;
2539
+ try {
2540
+ v = node();
2541
+ } catch (err) {
2542
+ return buildAsyncWrap(err, node) || "";
2543
+ }
2544
+ return tryResolveString(v);
2545
+ }
2546
+ return "";
579
2547
  }
580
2548
  function resolveSSRNode(node, result = {
581
2549
  t: [""],
@@ -586,10 +2554,19 @@ function resolveSSRNode(node, result = {
586
2554
  if (t === "string" || t === "number") {
587
2555
  result.t[result.t.length - 1] += node;
588
2556
  } else if (node == null || t === "boolean") ; else if (Array.isArray(node)) {
589
- let prev = {};
590
- for (let i = 0, len = node.length; i < len; i++) {
591
- if (!top && typeof prev !== "object" && typeof node[i] !== "object") result.t[result.t.length - 1] += `<!--!$-->`;
592
- resolveSSRNode(prev = node[i], result);
2557
+ const slotLive = node.$slot && sharedConfig.context && sharedConfig.context.liveHoles;
2558
+ if (slotLive) slotLive.suppressed++;
2559
+ try {
2560
+ let prevNonObj = false;
2561
+ for (let i = 0, len = node.length; i < len; i++) {
2562
+ const item = node[i];
2563
+ const itemNonObj = item !== null && typeof item !== "object";
2564
+ if (!top && prevNonObj && itemNonObj) result.t[result.t.length - 1] += `<!--!$-->`;
2565
+ prevNonObj = itemNonObj;
2566
+ resolveSSRNode(item, result);
2567
+ }
2568
+ } finally {
2569
+ if (slotLive) slotLive.suppressed--;
593
2570
  }
594
2571
  } else if (t === "object") {
595
2572
  if (node.h) {
@@ -599,16 +2576,24 @@ function resolveSSRNode(node, result = {
599
2576
  result.h.push(...node.h);
600
2577
  result.p.push(...node.p);
601
2578
  }
602
- } else result.t[result.t.length - 1] += node.t;
2579
+ } else if (node.t !== undefined) {
2580
+ result.t[result.t.length - 1] += node.t;
2581
+ } else ;
603
2582
  } else if (t === "function") {
604
- try {
605
- resolveSSRNode(node(), result);
606
- } catch (err) {
607
- const p = ssrHandleError(err);
608
- if (p) {
609
- result.h.push(node);
610
- result.p.push(p);
611
- result.t.push("");
2583
+ const live = sharedConfig.context && sharedConfig.context.liveHoles;
2584
+ let liveNode = null;
2585
+ if (live && (liveNode = live.content(node)) !== null) {
2586
+ if (typeof liveNode === "string") result.t[result.t.length - 1] += liveNode;else resolveSSRNode(liveNode, result);
2587
+ } else {
2588
+ try {
2589
+ resolveSSRNode(node(), result);
2590
+ } catch (err) {
2591
+ const wrap = buildAsyncWrap(err, node);
2592
+ if (wrap) {
2593
+ result.h.push(wrap.fn);
2594
+ result.p.push(wrap.p);
2595
+ result.t.push("");
2596
+ }
612
2597
  }
613
2598
  }
614
2599
  }
@@ -617,36 +2602,376 @@ function resolveSSRNode(node, result = {
617
2602
  function resolveSSRSync(node) {
618
2603
  const res = resolveSSRNode(node);
619
2604
  if (!res.h.length) return res.t[0];
620
- throw new Error("This value cannot be rendered synchronously. Are you missing a Suspsense boundary?");
2605
+ throw new Error("This value cannot be rendered synchronously. Are you missing a boundary?");
621
2606
  }
622
- const RequestContext = Symbol();
2607
+ const RequestContext = Symbol.for("solid.RequestContext");
623
2608
  function getRequestEvent() {
624
- return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || sharedConfig.context && sharedConfig.context.event || console.log("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.") : undefined;
2609
+ return globalThis[RequestContext] ? globalThis[RequestContext].getStore() || sharedConfig.context && sharedConfig.context.event || console.warn("RequestEvent is missing. This is most likely due to accessing `getRequestEvent` non-managed async scope in a partially polyfilled environment. Try moving it above all `await` calls.") : undefined;
2610
+ }
2611
+ function createResponseStub() {
2612
+ return {
2613
+ status: undefined,
2614
+ statusText: undefined,
2615
+ headers: new Headers(),
2616
+ committed: false
2617
+ };
2618
+ }
2619
+ function createRequestEvent(request, init) {
2620
+ return {
2621
+ request,
2622
+ locals: {},
2623
+ response: createResponseStub(),
2624
+ ...init
2625
+ };
2626
+ }
2627
+ function reportLostHeaderWrite(method, name) {
2628
+ const message = `Response header write dropped: headers.${method}(${JSON.stringify(String(name))}) ` + "ran after the response head was sent. Write headers before the shell flushes " + "(or before the handler returns).";
2629
+ console.error(message);
2630
+ }
2631
+ function commitResponseStub(stub, {
2632
+ allowLateLocation = false
2633
+ } = {}) {
2634
+ if (!stub || stub.committed) return stub;
2635
+ stub.committed = true;
2636
+ const headers = stub.headers;
2637
+ if (!headers || typeof headers.set !== "function") return stub;
2638
+ for (const method of ["set", "append", "delete"]) {
2639
+ const original = headers[method].bind(headers);
2640
+ headers[method] = function (name, ...rest) {
2641
+ if (allowLateLocation && method === "set" && String(name).toLowerCase() === "location") {
2642
+ return original(name, ...rest);
2643
+ }
2644
+ reportLostHeaderWrite(method, name);
2645
+ };
2646
+ }
2647
+ return stub;
2648
+ }
2649
+ const validRedirectStatuses = /*#__PURE__*/new Set([301, 302, 303, 307, 308]);
2650
+ function getExpectedRedirectStatus(response) {
2651
+ if (response.status && validRedirectStatuses.has(response.status)) return response.status;
2652
+ return 302;
2653
+ }
2654
+ function mergeStubHeaders(target, stub) {
2655
+ if (!stub) return target;
2656
+ stub.headers.forEach((value, key) => {
2657
+ if (key !== "set-cookie") target.set(key, value);
2658
+ });
2659
+ const setCookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
2660
+ for (const cookie of setCookies) target.append("set-cookie", cookie);
2661
+ return target;
625
2662
  }
626
- function renderToStringAsync(code, options = {}) {
627
- return renderToStream(code, options).then(html => html);
2663
+ function copyInitHeaders(init) {
2664
+ if (!init || !init.getSetCookie) return new Headers(init);
2665
+ const headers = new Headers();
2666
+ init.forEach((value, key) => {
2667
+ if (key !== "set-cookie") headers.append(key, value);
2668
+ });
2669
+ for (const cookie of init.getSetCookie()) headers.append("Set-Cookie", cookie);
2670
+ return headers;
2671
+ }
2672
+ const STUB_GAP_FILL_EXCLUDED = /*#__PURE__*/new Set([ERROR_HEADER, BODY_FORMAT_HEADER, SINGLE_FLIGHT_HEADER, REVALIDATE_HEADER, "Location"].map(header => header.toLowerCase()));
2673
+ function fillsStubGap(key, headers, response) {
2674
+ if (key === "set-cookie" || STUB_GAP_FILL_EXCLUDED.has(key)) return false;
2675
+ if (response.body === null && (key === "content-type" || key === "content-length")) return false;
2676
+ return !headers.has(key);
2677
+ }
2678
+ function commitEventResponse(response, event = getRequestEvent()) {
2679
+ const stub = event && event.response;
2680
+ if (!stub || !stub.headers || stub.committed) return response;
2681
+ const cookies = stub.headers.getSetCookie ? stub.headers.getSetCookie() : [];
2682
+ commitResponseStub(stub);
2683
+ let hasGaps = false;
2684
+ stub.headers.forEach((value, key) => {
2685
+ if (fillsStubGap(key, response.headers, response)) hasGaps = true;
2686
+ });
2687
+ if (!cookies.length && !hasGaps) return response;
2688
+ try {
2689
+ for (const cookie of cookies) response.headers.append("Set-Cookie", cookie);
2690
+ stub.headers.forEach((value, key) => {
2691
+ if (fillsStubGap(key, response.headers, response)) response.headers.set(key, value);
2692
+ });
2693
+ return response;
2694
+ } catch {
2695
+ const headers = copyInitHeaders(response.headers);
2696
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
2697
+ stub.headers.forEach((value, key) => {
2698
+ if (fillsStubGap(key, headers, response)) headers.set(key, value);
2699
+ });
2700
+ return new Response(response.body, {
2701
+ status: response.status,
2702
+ statusText: response.statusText,
2703
+ headers
2704
+ });
2705
+ }
2706
+ }
2707
+ function deriveHead(stub, responseInit = {}) {
2708
+ const headers = mergeStubHeaders(copyInitHeaders(responseInit.headers), stub);
2709
+ const status = stub && stub.status || responseInit.status || 200;
2710
+ const statusText = stub && stub.statusText || responseInit.statusText || undefined;
2711
+ return {
2712
+ status,
2713
+ statusText,
2714
+ headers
2715
+ };
2716
+ }
2717
+ function escapeAttribute(value) {
2718
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
2719
+ }
2720
+ function createSSRResponse(result, event, options = {}) {
2721
+ const stub = event && event.response;
2722
+ const {
2723
+ responseInit,
2724
+ nonce,
2725
+ transformChunk
2726
+ } = options;
2727
+ if (typeof result === "string") {
2728
+ if (stub) commitResponseStub(stub);
2729
+ const head = deriveHead(stub, responseInit);
2730
+ if (stub && stub.headers.get("Location")) {
2731
+ return new Response(null, {
2732
+ status: getExpectedRedirectStatus(stub),
2733
+ headers: head.headers
2734
+ });
2735
+ }
2736
+ if (!head.headers.has("content-type")) {
2737
+ head.headers.set("content-type", "text/html; charset=utf-8");
2738
+ }
2739
+ return new Response(transformChunk ? transformChunk(result) : result, {
2740
+ status: head.status,
2741
+ statusText: head.statusText,
2742
+ headers: head.headers
2743
+ });
2744
+ }
2745
+ const encoder = new TextEncoder();
2746
+ return new Promise(resolve => {
2747
+ let controller;
2748
+ let closed = false;
2749
+ let flushed = false;
2750
+ const enqueue = value => {
2751
+ if (closed || !controller) return;
2752
+ try {
2753
+ controller.enqueue(encoder.encode(value));
2754
+ } catch {
2755
+ closed = true;
2756
+ }
2757
+ };
2758
+ result.pipe({
2759
+ write(chunk) {
2760
+ if (!flushed) {
2761
+ flushed = true;
2762
+ if (stub) commitResponseStub(stub, {
2763
+ allowLateLocation: true
2764
+ });
2765
+ const head = deriveHead(stub, responseInit);
2766
+ if (stub && stub.headers.get("Location")) {
2767
+ closed = true;
2768
+ resolve(new Response(null, {
2769
+ status: getExpectedRedirectStatus(stub),
2770
+ headers: head.headers
2771
+ }));
2772
+ return;
2773
+ }
2774
+ if (!head.headers.has("content-type")) {
2775
+ head.headers.set("content-type", "text/html; charset=utf-8");
2776
+ }
2777
+ resolve(new Response(new ReadableStream({
2778
+ start(c) {
2779
+ controller = c;
2780
+ },
2781
+ cancel() {
2782
+ closed = true;
2783
+ }
2784
+ }), {
2785
+ status: head.status,
2786
+ statusText: head.statusText,
2787
+ headers: head.headers
2788
+ }));
2789
+ }
2790
+ enqueue(transformChunk ? transformChunk(chunk) : chunk);
2791
+ },
2792
+ end() {
2793
+ if (closed || !controller) return;
2794
+ const location = stub && stub.headers.get("Location");
2795
+ if (location) {
2796
+ const attr = nonce ? ` nonce="${escapeAttribute(nonce)}"` : "";
2797
+ enqueue(`<script${attr}>window.location=${JSON.stringify(location).replace(/</g, "\\u003c")}</script>`);
2798
+ }
2799
+ closed = true;
2800
+ try {
2801
+ controller.close();
2802
+ } catch {}
2803
+ }
2804
+ });
2805
+ });
2806
+ }
2807
+ function composeMiddleware(middlewares) {
2808
+ return function run(request, next) {
2809
+ let index = -1;
2810
+ function dispatch(i, req) {
2811
+ if (i <= index) return Promise.reject(new Error("next() called multiple times"));
2812
+ index = i;
2813
+ if (i === middlewares.length) return Promise.resolve(next(req));
2814
+ return Promise.resolve(middlewares[i](req, override => dispatch(i + 1, override || req)));
2815
+ }
2816
+ return dispatch(0, request);
2817
+ };
2818
+ }
2819
+ function registerElementClaim() {
2820
+ return noopCleanup;
2821
+ }
2822
+ function noopCleanup() {}
2823
+ function claimElement(node) {
2824
+ return node;
2825
+ }
2826
+ function claimElementTree(root) {
2827
+ return root;
628
2828
  }
629
2829
  function notSup() {
630
2830
  throw new Error("Client-only API called on the server side. Run client-only code in onMount, or conditionally run client-only component with <Show>.");
631
2831
  }
632
2832
 
2833
+ setContainerTraceResolver(getProjectionTrace);
633
2834
  const isServer = true;
634
2835
  const isDev = false;
635
- function createDynamic(component, props) {
636
- const comp = component(),
637
- t = typeof comp;
638
- if (comp) {
639
- if (t === "function") return comp(props);else if (t === "string") {
640
- return ssrElement(comp, props, undefined, true);
641
- }
642
- }
2836
+ function dynamic(source) {
2837
+ const cached = createMemo(source, {
2838
+ serialize: false
2839
+ });
2840
+ return props => {
2841
+ return createMemo(() => {
2842
+ const c = cached();
2843
+ if (c) {
2844
+ if (typeof c === "function") return c(props);
2845
+ if (typeof c === "string") {
2846
+ return ssrElement(c, props, undefined, true);
2847
+ }
2848
+ }
2849
+ }, {
2850
+ sync: true
2851
+ });
2852
+ };
643
2853
  }
644
2854
  function Dynamic(props) {
645
- const others = omit(props, "component");
646
- return createDynamic(() => props.component, others);
2855
+ const Comp = dynamic(() => props.component);
2856
+ return createComponent(Comp, omit(props, "component"));
647
2857
  }
648
2858
  function Portal(props) {
649
- throw new Error("Portal is not supported on the server");
2859
+ const o = getOwner();
2860
+ if (o?.id != null) getNextChildId(o);
2861
+ return undefined;
2862
+ }
2863
+ function registerClientOnlyPreload(moduleUrl) {
2864
+ const ctx = sharedConfig.context;
2865
+ if (!ctx?.registerAsset || !ctx.resolveAssets) return;
2866
+ const registerAsset = ctx.registerAsset;
2867
+ const resolve = ctx.resolveAssets;
2868
+ const apply = assets => {
2869
+ if (!assets) return;
2870
+ for (let i = 0; i < assets.css.length; i++) {
2871
+ const css = assets.css[i];
2872
+ if (typeof css === "string") registerAsset("style", css);else registerAsset("inline-style", css);
2873
+ }
2874
+ for (let i = 0; i < assets.js.length; i++) registerAsset("module", assets.js[i]);
2875
+ };
2876
+ const assets = resolve(moduleUrl);
2877
+ if (assets && typeof assets.then === "function") {
2878
+ const boundary = ctx._currentBoundaryId;
2879
+ assets.then(resolved => {
2880
+ const current = ctx._currentBoundaryId;
2881
+ ctx._currentBoundaryId = boundary;
2882
+ try {
2883
+ apply(resolved);
2884
+ } finally {
2885
+ ctx._currentBoundaryId = current;
2886
+ }
2887
+ },
2888
+ () => {});
2889
+ } else {
2890
+ apply(assets);
2891
+ }
2892
+ }
2893
+ function clientOnly(_fn, _options = {}, moduleUrl) {
2894
+ return props => {
2895
+ if (moduleUrl) registerClientOnlyPreload(moduleUrl);
2896
+ return createMemo(() => props.fallback);
2897
+ };
2898
+ }
2899
+ const statusLedgers = /* @__PURE__ */new WeakMap();
2900
+ const headerLedgers = /* @__PURE__ */new WeakMap();
2901
+ function httpStatus(code, text) {
2902
+ const event = getRequestEvent();
2903
+ const response = event && event.response;
2904
+ if (response && !response.committed) {
2905
+ let ledger = statusLedgers.get(response);
2906
+ if (!ledger) {
2907
+ ledger = {
2908
+ base: {
2909
+ status: response.status,
2910
+ statusText: response.statusText
2911
+ },
2912
+ live: []
2913
+ };
2914
+ statusLedgers.set(response, ledger);
2915
+ }
2916
+ const declaration = {
2917
+ status: code,
2918
+ statusText: text
2919
+ };
2920
+ ledger.live.push(declaration);
2921
+ response.status = code;
2922
+ response.statusText = text;
2923
+ onCleanup(() => {
2924
+ if (response.committed) return;
2925
+ const index = ledger.live.indexOf(declaration);
2926
+ if (index < 0) return;
2927
+ ledger.live.splice(index, 1);
2928
+ const effective = ledger.live.length ? ledger.live[ledger.live.length - 1] : ledger.base;
2929
+ response.status = effective.status;
2930
+ response.statusText = effective.statusText;
2931
+ if (!ledger.live.length) statusLedgers.delete(response);
2932
+ });
2933
+ }
2934
+ }
2935
+ function httpHeader(name, value, options) {
2936
+ const event = getRequestEvent();
2937
+ const response = event && event.response;
2938
+ if (response && !response.committed) {
2939
+ const headers = response.headers;
2940
+ const key = name.toLowerCase();
2941
+ const setCookie = key === "set-cookie";
2942
+ let ledgers = headerLedgers.get(response);
2943
+ if (!ledgers) headerLedgers.set(response, ledgers = new Map());
2944
+ let ledger = ledgers.get(key);
2945
+ if (!ledger) {
2946
+ ledger = {
2947
+ base: setCookie ? headers.getSetCookie() : headers.get(name),
2948
+ live: []
2949
+ };
2950
+ ledgers.set(key, ledger);
2951
+ }
2952
+ const declaration = {
2953
+ value,
2954
+ append: !!(options && options.append)
2955
+ };
2956
+ ledger.live.push(declaration);
2957
+ if (declaration.append) headers.append(name, value);else headers.set(name, value);
2958
+ onCleanup(() => {
2959
+ if (response.committed) return;
2960
+ const index = ledger.live.indexOf(declaration);
2961
+ if (index < 0) return;
2962
+ ledger.live.splice(index, 1);
2963
+ headers.delete(name);
2964
+ if (setCookie) {
2965
+ for (const cookie of ledger.base) headers.append(name, cookie);
2966
+ } else if (ledger.base !== null) {
2967
+ headers.set(name, ledger.base);
2968
+ }
2969
+ for (const d of ledger.live) {
2970
+ if (d.append) headers.append(name, d.value);else headers.set(name, d.value);
2971
+ }
2972
+ if (!ledger.live.length) ledgers.delete(key);
2973
+ });
2974
+ }
650
2975
  }
651
2976
 
652
- export { ChildProperties, DOMElements, DelegatedEvents, Dynamic, Hydration, HydrationScript, NoHydration, Portal, Properties, RequestContext, SVGElements, SVGNamespace, notSup as addEventListener, notSup as assign, notSup as className, createDynamic, notSup as delegateEvents, notSup as dynamicProperty, escape, generateHydrationScript, getAssets, getHydrationKey, notSup as getNextElement, notSup as getNextMarker, notSup as getNextMatch, getRequestEvent, notSup as hydrate, notSup as insert, isDev, isServer, memo, mergeProps, notSup as render, renderToStream, renderToString, renderToStringAsync, notSup as runHydrationEvents, notSup as setAttribute, notSup as setAttributeNS, notSup as setProperty, notSup as spread, ssr, ssrAttribute, ssrClassName, ssrElement, ssrHydrationKey, ssrStyle, ssrStyleProperty, notSup as style, notSup as template, useAssets };
2977
+ export { ChildProperties, DOMElements, DOMWithState, DelegatedEvents, Dynamic, HREF, HydrationScript, MathMLElements, Namespaces, Portal, REVALIDATE_HEADER, RawTextElements, RequestContext, ResponseEnvelope, SAFE_ERROR, SVGElements, VoidElements, notSup as acquireAsset, notSup as addEvent, applyRef, notSup as assign, claimElement, claimElementTree, notSup as className, clearFlashCookie, clientOnly, commitEventResponse, commitResponseStub, composeMiddleware, createLiveHoles, createRequestEvent, createResponseStub, createSSRResponse, notSup as delegateEvents, dynamic, notSup as dynamicProperty, effect, escape, generateHydrationScript, notSup as getDelegatedRoot, getExpectedRedirectStatus, getHydrationKey, notSup as getNextElement, notSup as getNextMarker, notSup as getNextMatch, getRequestEvent, getServerFunctionMetadata, getServerFunctionRPC, hasFlashCookie, httpHeader, httpStatus, notSup as hydrate, notSup as insert, isDev, isHref, isResponseEnvelope, isSafeError, isServer, isServerFunction, markSafeError, memo, parseCookieHeader, redirect, notSup as ref, notSup as registerDelegatedContainer, notSup as registerDelegatedRoot, registerElementClaim, reload, notSup as render, renderToStream, renderToString, respond, notSup as runHydrationEvents, serializeCookie, notSup as setAttribute, notSup as setAttributeNS, notSup as setProperty, notSup as setStyleProperty, notSup as spread, ssr, ssrAttribute, ssrClassName, ssrElement, ssrGroup, ssrHydrationKey, ssrStyle, ssrStyleProperty, notSup as style, notSup as template, notSup as unregisterDelegatedContainer, notSup as unregisterDelegatedRoot, useHead };