@bgub/fig-server 0.1.0-alpha.5 → 0.1.0-alpha.7

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.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { i as escapeText, n as escapeScriptJson, t as escapeAttribute } from "./escaping-DAot8sFu.js";
2
- import { a as componentStack, c as nonceAttribute, d as withContextValue, i as cloneContextValues, l as streamFlowBlocked, n as suppressesImagePreloads, o as createStaticDispatcher, r as STREAMED_METADATA_ATTRIBUTE, s as deferred, t as imagePreloadFromHostProps, u as streamHighWaterMark } from "./image-preloads-BIFcrqm9.js";
1
+ import { i as escapeText, n as escapeScriptJson, t as escapeAttribute } from "./escaping-C2DNLoj9.js";
2
+ import { a as createStaticDispatcher, c as nonceAttribute, d as streamFlowBlocked, f as streamHighWaterMark, i as cloneContextValues, l as noop, n as suppressesImagePreloads, o as deferred, p as withContextValue, r as STREAMED_METADATA_ATTRIBUTE, s as noLane, t as imagePreloadFromHostProps, u as serverErrorPayload } from "./image-preloads-CWbCdmNa.js";
3
3
  import { Fragment, createElement, isValidElement } from "@bgub/fig";
4
- import { ACTIVITY_TEMPLATE_ATTRIBUTE, EARLY_EVENT_HANDLER_PROPERTY, EARLY_EVENT_QUEUE_PROPERTY, HYDRATION_SKIP_ATTRIBUTE, REPLAYABLE_EVENT_TYPES, SUSPENSE_CLIENT_MARKER, SUSPENSE_COMPLETED_MARKER, SUSPENSE_END_MARKER, SUSPENSE_MARKER_PREFIX, SUSPENSE_PENDING_PREFIX, TEXT_SEPARATOR_DATA, VIEW_TRANSITION_CLASS_ATTRIBUTE, VIEW_TRANSITION_NAME_ATTRIBUTE, VIEW_TRANSITION_PENDING_PROPERTY, VIEW_TRANSITION_TIMEOUT_MS, assetResourceFromHostProps, assetResourceHostAttributes, assetResourceKey, attachDataStore, collectChildren, createRendererDataStore, invalidChildError, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPortal, isSuspense, isThenable, isViewTransition, readThenable, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
4
+ import { ACTIVITY_TEMPLATE_ATTRIBUTE, EARLY_EVENT_HANDLER_PROPERTY, EARLY_EVENT_QUEUE_PROPERTY, HYDRATION_SKIP_ATTRIBUTE, REPLAYABLE_EVENT_TYPES, SUSPENSE_CLIENT_MARKER, SUSPENSE_COMPLETED_MARKER, SUSPENSE_END_MARKER, SUSPENSE_MARKER_PREFIX, SUSPENSE_PENDING_PREFIX, TEXT_SEPARATOR_DATA, VIEW_TRANSITION_CLASS_ATTRIBUTE, VIEW_TRANSITION_NAME_ATTRIBUTE, VIEW_TRANSITION_PENDING_PROPERTY, VIEW_TRANSITION_TIMEOUT_MS, assetResourceFromHostProps, assetResourceHostProps, assetResourceKey, attachDataStore, collectChildren, createRendererDataStore, invalidChildError, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPortal, isSuspense, isThenable, isViewTransition, readThenable, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
5
5
  //#region src/html.ts
6
6
  const voidElements = /* @__PURE__ */ new Set([
7
7
  "area",
@@ -19,12 +19,19 @@ const voidElements = /* @__PURE__ */ new Set([
19
19
  "track",
20
20
  "wbr"
21
21
  ]);
22
+ const attributeNamePattern = /[\s"'<>/=]/;
23
+ const eventPropPattern = /^on[A-Z]/;
24
+ const styleNamePattern = /[A-Z]/g;
25
+ const tagNamePattern = /^[A-Za-z][A-Za-z0-9:._-]*$/;
26
+ function hyphenateStyleLetter(letter) {
27
+ return `-${letter.toLowerCase()}`;
28
+ }
22
29
  function writeText(value, sink) {
23
30
  sink.write(escapeText(value));
24
31
  }
25
- function writeElementStart(type, props, sink, inheritedProps = {}) {
32
+ function writeElementStart(type, props, sink, selectProps = null) {
26
33
  validateTagName(type);
27
- sink.write(`<${type}${serializeAttributes(type, props, inheritedProps)}>`);
34
+ sink.write(`<${type}${serializeAttributes(type, props, selectProps)}>`);
28
35
  }
29
36
  function writeElementEnd(type, sink) {
30
37
  sink.write(`</${type}>`);
@@ -35,7 +42,7 @@ function isVoidElement(type) {
35
42
  function hasRenderableChild(node) {
36
43
  if (Array.isArray(node)) return node.some(hasRenderableChild);
37
44
  if (isPortal(node)) return false;
38
- return !emptyChild(node);
45
+ return node !== null && node !== void 0 && typeof node !== "boolean";
39
46
  }
40
47
  function formTextContent(type, props) {
41
48
  if (type !== "textarea") return null;
@@ -47,7 +54,7 @@ function unsafeHTMLContent(props) {
47
54
  if (typeof value === "string") return value;
48
55
  throw new Error("The unsafeHTML prop must be a string during server render.");
49
56
  }
50
- function serializeAttributes(type, props, inheritedProps) {
57
+ function serializeAttributes(type, props, selectProps) {
51
58
  let attributes = "";
52
59
  for (const name of Object.keys(props)) {
53
60
  const value = props[name];
@@ -61,14 +68,15 @@ function serializeAttributes(type, props, inheritedProps) {
61
68
  }
62
69
  attributes += serializeProp(type, name, value);
63
70
  }
64
- if (type === "option" && props.selected === void 0 && optionSelected(optionValue(props), inheritedProps)) attributes += " selected";
71
+ if (type === "option" && props.selected === void 0 && optionSelected(optionValue(props), selectProps)) attributes += " selected";
65
72
  return attributes;
66
73
  }
67
74
  function serializeProp(type, name, value) {
68
- if ((type === "textarea" || type === "select") && valueProp(name)) return "";
75
+ const isValueProp = name === "value" || name === "defaultValue";
76
+ if ((type === "textarea" || type === "select") && isValueProp) return "";
69
77
  let attributeName = name;
70
78
  let attributeValue = value;
71
- if (valueProp(name)) {
79
+ if (isValueProp) {
72
80
  attributeName = "value";
73
81
  if (serializableAttributeValue(value)) attributeValue = String(value);
74
82
  } else if (name === "defaultChecked") {
@@ -82,11 +90,14 @@ function serializeProp(type, name, value) {
82
90
  throw new Error(`Cannot serialize prop "${name}" to HTML.`);
83
91
  }
84
92
  function optionSelected(value, selectProps) {
93
+ if (selectProps === null) return false;
85
94
  const selectValue = selectProps.value !== void 0 ? selectProps.value : selectProps.defaultValue;
86
95
  if (emptyValue(selectValue)) return false;
87
96
  const optionValue = formString(value);
88
97
  if (optionValue === null) return false;
89
- return selectedValueSet(selectValue).has(optionValue);
98
+ if (!Array.isArray(selectValue)) return String(selectValue) === optionValue;
99
+ for (const selectedValue of selectValue) if (String(selectedValue) === optionValue) return true;
100
+ return false;
90
101
  }
91
102
  function optionValue(props) {
92
103
  return props.value === void 0 ? optionTextValue(props.children) : formString(props.value);
@@ -109,26 +120,22 @@ function formString(value) {
109
120
  if (serializableAttributeValue(value)) return String(value);
110
121
  return null;
111
122
  }
112
- function selectedValueSet(value) {
113
- return new Set(Array.isArray(value) ? value.map(String) : [String(value)]);
114
- }
115
123
  function serializableAttributeValue(value) {
116
124
  return value === true || typeof value === "string" || typeof value === "number" || typeof value === "bigint";
117
125
  }
118
126
  function emptyValue(value) {
119
127
  return value === null || value === void 0 || value === false;
120
128
  }
121
- function emptyChild(value) {
122
- return value === null || value === void 0 || typeof value === "boolean";
123
- }
124
129
  function serializeAttribute(name, value) {
125
130
  return ` ${name}="${escapeAttribute(value)}"`;
126
131
  }
127
132
  function serializeStyle(value) {
128
133
  if (emptyValue(value)) return "";
129
134
  if (typeof value !== "object" || value === null) throw new Error("The style prop must be an object during server render.");
135
+ const styles = value;
130
136
  let serialized = "";
131
- for (const [name, item] of Object.entries(value)) {
137
+ for (const name of Object.keys(styles)) {
138
+ const item = styles[name];
132
139
  if (emptyValue(item)) continue;
133
140
  if (typeof item !== "string" && typeof item !== "number" && typeof item !== "bigint") throw new Error(`Cannot serialize style property "${name}" to HTML.`);
134
141
  if (serialized !== "") serialized += ";";
@@ -137,20 +144,17 @@ function serializeStyle(value) {
137
144
  return serialized;
138
145
  }
139
146
  function reservedProp(name) {
140
- return name === "children" || name === "key" || name === "mix" || name === "bind" || name === "suppressHydrationWarning" || name === "unsafeHTML" || /^on[A-Z]/.test(name);
141
- }
142
- function valueProp(name) {
143
- return name === "value" || name === "defaultValue";
147
+ return name === "children" || name === "key" || name === "mix" || name === "bind" || name === "suppressHydrationWarning" || name === "unsafeHTML" || eventPropPattern.test(name);
144
148
  }
145
149
  function styleName(name) {
146
150
  if (name.startsWith("--")) return name;
147
- return name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
151
+ return name.replace(styleNamePattern, hyphenateStyleLetter);
148
152
  }
149
153
  function validateTagName(name) {
150
- if (!/^[A-Za-z][A-Za-z0-9:._-]*$/.test(name)) throw new Error(`Invalid HTML tag name "${name}".`);
154
+ if (!tagNamePattern.test(name)) throw new Error(`Invalid HTML tag name "${name}".`);
151
155
  }
152
156
  function validateAttributeName(name) {
153
- if (/[\s"'<>/=]/.test(name)) throw new Error(`Invalid HTML attribute name "${name}".`);
157
+ if (attributeNamePattern.test(name)) throw new Error(`Invalid HTML attribute name "${name}".`);
154
158
  }
155
159
  //#endregion
156
160
  //#region src/preload-header.ts
@@ -158,23 +162,30 @@ const DEFAULT_LENGTH = 2e3;
158
162
  const HEX_ESCAPE = /^[0-9A-Fa-f]{2}$/;
159
163
  const PARAMETER_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
160
164
  const URI_REFERENCE_PUNCTUATION = "-._~:/?#[]@!$&'()*+,;=";
161
- function createPreloadHeaderEntries(resources, isEarlyImage) {
165
+ function createPreloadHeaderEntries(resources) {
166
+ const entries = [];
167
+ for (const resource of resources) {
168
+ if (!isServerPreloadHeaderResource(resource)) continue;
169
+ const value = preloadHeaderValue(resource);
170
+ if (value !== null) entries.push({
171
+ resource,
172
+ value
173
+ });
174
+ }
175
+ return entries;
176
+ }
177
+ function snapshotPreloadHeaderResources(resources, isEarlyImage) {
162
178
  const preconnects = [];
163
179
  const criticalPreloads = [];
164
180
  const stylesheets = [];
165
181
  const remaining = [];
166
182
  for (const resource of resources) {
167
183
  if (!isServerPreloadHeaderResource(resource)) continue;
168
- const value = preloadHeaderValue(resource);
169
- if (value === null) continue;
170
- const entry = {
171
- resource,
172
- value
173
- };
174
- if (resource.kind === "preconnect") preconnects.push(entry);
175
- else if (resource.kind === "font" || resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || isEarlyImage?.(resource) === true))) criticalPreloads.push(entry);
176
- else if (resource.kind === "stylesheet") stylesheets.push(entry);
177
- else remaining.push(entry);
184
+ const snapshot = { ...resource };
185
+ if (resource.kind === "preconnect") preconnects.push(snapshot);
186
+ else if (resource.kind === "font" || resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || isEarlyImage?.(resource) === true))) criticalPreloads.push(snapshot);
187
+ else if (resource.kind === "stylesheet") stylesheets.push(snapshot);
188
+ else remaining.push(snapshot);
178
189
  }
179
190
  return [
180
191
  ...preconnects,
@@ -308,18 +319,17 @@ var AssetResourceRegistry = class {
308
319
  }
309
320
  register(resource) {
310
321
  if (isMetadataResource(resource)) return;
311
- this.canonical(resource);
322
+ this.canonical(assetResourceKey(resource), resource);
312
323
  }
313
324
  registerAutomaticImage(resource) {
314
- const { key, resource: current } = this.canonical(resource);
325
+ const key = assetResourceKey(resource);
326
+ const current = this.canonical(key, resource);
315
327
  if (this.earlyImageKeys.size < 10 || current.kind === "preload" && current.as === "image" && current.fetchpriority === "high") this.earlyImageKeys.add(key);
316
328
  }
317
- isEarlyImage(resource) {
318
- return this.earlyImageKeys.has(assetResourceKey(resource));
319
- }
320
329
  activateMetadata(owner, resources) {
321
- const metadata = resources.filter(isMetadataResource);
322
- if (metadata.length === 0) {
330
+ let metadata = null;
331
+ for (const resource of resources) if (isMetadataResource(resource)) (metadata ??= []).push(resource);
332
+ if (metadata === null) {
323
333
  this.metadataByOwner.delete(owner);
324
334
  return;
325
335
  }
@@ -330,13 +340,33 @@ var AssetResourceRegistry = class {
330
340
  }
331
341
  write(resource, sink) {
332
342
  if (isMetadataResource(resource)) return null;
333
- const { key, resource: current } = this.canonical(resource);
343
+ const key = assetResourceKey(resource);
344
+ const current = this.canonical(key, resource);
334
345
  const id = this.revealBlockerId(key, current);
335
346
  if (this.emittedResources.has(key)) return id;
336
347
  this.emittedResources.add(key);
337
348
  writeAssetTag(sink, current, id);
338
349
  return id;
339
350
  }
351
+ writeDocumentHead(resources, metadata, sink) {
352
+ const preconnects = [];
353
+ const criticalPreloads = [];
354
+ const stylesheets = [];
355
+ const afterMetadata = [];
356
+ for (const resource of resources) {
357
+ if (isMetadataResource(resource)) continue;
358
+ if (resource.kind === "preconnect") preconnects.push(resource);
359
+ else if (resource.kind === "font" || resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || this.isEarlyImage(resource)))) criticalPreloads.push(resource);
360
+ else if (resource.kind === "stylesheet") stylesheets.push(resource);
361
+ else afterMetadata.push(resource);
362
+ }
363
+ sink.write(metadata.preamble);
364
+ for (const resource of preconnects) this.write(resource, sink);
365
+ for (const resource of criticalPreloads) this.write(resource, sink);
366
+ for (const resource of stylesheets) this.write(resource, sink);
367
+ sink.write(metadata.metadata);
368
+ for (const resource of afterMetadata) this.write(resource, sink);
369
+ }
340
370
  headHtml(nonce, streamMetadata = false) {
341
371
  const { preamble, metadata } = this.headMetadataHtml(nonce, streamMetadata);
342
372
  return preamble + metadata;
@@ -357,11 +387,7 @@ var AssetResourceRegistry = class {
357
387
  }, resource, null);
358
388
  }
359
389
  return {
360
- preamble: [
361
- ...buckets.charset,
362
- ...buckets.parser,
363
- ...buckets.viewport
364
- ].join(""),
390
+ preamble: buckets.charset.join("") + buckets.parser.join("") + buckets.viewport.join(""),
365
391
  metadata: buckets.metadata.join("")
366
392
  };
367
393
  }
@@ -379,37 +405,30 @@ var AssetResourceRegistry = class {
379
405
  ]);
380
406
  return snapshot;
381
407
  }
382
- preloadHeaderEntries() {
383
- return createPreloadHeaderEntries(this.deliveryResources.values(), (resource) => this.isEarlyImage(resource));
408
+ preloadHeaderResources() {
409
+ return snapshotPreloadHeaderResources(this.deliveryResources.values(), (resource) => this.isEarlyImage(resource));
410
+ }
411
+ isEarlyImage(resource) {
412
+ return this.earlyImageKeys.has(assetResourceKey(resource));
384
413
  }
385
414
  visibleMetadata() {
386
415
  const visible = /* @__PURE__ */ new Map();
387
416
  for (const metadata of this.metadataByOwner.values()) for (const resource of metadata) visible.set(assetResourceKey(resource), resource);
388
417
  return visible;
389
418
  }
390
- canonical(resource) {
391
- const key = assetResourceKey(resource);
419
+ canonical(key, resource) {
392
420
  const current = this.deliveryResources.get(key);
393
421
  if (current !== void 0) {
394
422
  if (assetSignature(current) !== assetSignature(resource)) {
395
423
  const promoted = promoteCompatibleImagePreload(current, resource);
396
424
  if (promoted === null) throw new AssetResourceConflictError(key, current, resource);
397
425
  this.deliveryResources.set(key, promoted);
398
- return {
399
- key,
400
- resource: promoted
401
- };
426
+ return promoted;
402
427
  }
403
- return {
404
- key,
405
- resource: current
406
- };
428
+ return current;
407
429
  }
408
430
  this.deliveryResources.set(key, resource);
409
- return {
410
- key,
411
- resource
412
- };
431
+ return resource;
413
432
  }
414
433
  revealBlockerId(key, resource) {
415
434
  if (resource.kind !== "stylesheet") return null;
@@ -453,13 +472,11 @@ function writeAssetTag(sink, resource, id) {
453
472
  }, sink);
454
473
  return;
455
474
  default: {
456
- const props = {
457
- [HYDRATION_SKIP_ATTRIBUTE]: true,
458
- ...Object.fromEntries(assetResourceHostAttributes(resource))
459
- };
475
+ const props = assetResourceHostProps(resource, { [HYDRATION_SKIP_ATTRIBUTE]: true });
460
476
  if (resource.kind === "stylesheet" && id !== null) props.id = id;
477
+ if (sink.nonce !== void 0) props.nonce = sink.nonce;
461
478
  const tag = resource.kind === "script" ? "script" : "link";
462
- writeElementStart(tag, withNonce(sink, props), sink);
479
+ writeElementStart(tag, props, sink);
463
480
  if (tag === "script") writeElementEnd("script", sink);
464
481
  }
465
482
  }
@@ -487,12 +504,6 @@ function metadataAttributes(resource) {
487
504
  ["data-fig-resource-key", resource.key]
488
505
  ].filter((entry) => entry[1] !== void 0);
489
506
  }
490
- function withNonce(sink, props) {
491
- return sink.nonce === void 0 ? props : {
492
- ...props,
493
- nonce: sink.nonce
494
- };
495
- }
496
507
  function assetSignature(resource) {
497
508
  switch (resource.kind) {
498
509
  case "stylesheet": return signature(resource.kind, resource.href, resource.media ?? "", resource.precedence ?? "", resource.crossorigin ?? "", resource.blocking ?? "reveal");
@@ -531,20 +542,27 @@ function signature(...values) {
531
542
  }
532
543
  //#endregion
533
544
  //#region src/protocol.ts
534
- function serverRuntimeCodeFor(runtimeName) {
545
+ function buildServerRuntimeCode(runtimeName) {
535
546
  return `globalThis[${jsString(runtimeName)}]??={r(a,f){let n=0,d=()=>{--n||f()};for(let i of a){let e=document.getElementById(i);if(e&&e.tagName==='LINK'&&e.rel==='stylesheet'&&!e.sheet){n++;e.addEventListener('load',d,{once:true});e.addEventListener('error',d,{once:true})}}n||f()},q(e,a){if(e&&e.nodeType===1){if(e.hasAttribute&&e.hasAttribute('${VIEW_TRANSITION_NAME_ATTRIBUTE}'))a.push([e,e.getAttribute('${VIEW_TRANSITION_NAME_ATTRIBUTE}'),e.getAttribute('${VIEW_TRANSITION_CLASS_ATTRIBUTE}')]);if(e.querySelectorAll)for(let x of e.querySelectorAll('[${VIEW_TRANSITION_NAME_ATTRIBUTE}]'))a.push([x,x.getAttribute('${VIEW_TRANSITION_NAME_ATTRIBUTE}'),x.getAttribute('${VIEW_TRANSITION_CLASS_ATTRIBUTE}')])}},g(r){let a=[];this.q(r,a);return a},h(b){let a=[],d=0;for(let e=b;e;){if(e.nodeType===8){if(e.data.indexOf('${SUSPENSE_MARKER_PREFIX}')===0)d++;else if(e.data==='${SUSPENSE_END_MARKER}'){if(d===0)break;d--}}else this.q(e,a);e=e.nextSibling}return a},a(l){for(let x of l){let e=x[0],s=e.style;x[3]=s.viewTransitionName;x[4]=s.viewTransitionClass;s.viewTransitionName=x[1];if(x[2])s.viewTransitionClass=x[2]}},u(l){for(let x of l){let e=x[0],s=e.style;s.viewTransitionName=x[3]||'';s.viewTransitionClass=x[4]||'';!(e.getAttribute&&e.getAttribute('style'))&&e.removeAttribute&&e.removeAttribute('style')}},z(l){for(let f of l)f()},j(t,r){let p=t&&(t.ready||t.finished);p&&p.then?p.then(r,()=>{let f=t&&t.finished;f&&f.then?f.then(r,r):r()}):r()},v(b,s,f){let o=this.h(b),n=this.g(s);if(!o.length&&!n.length){f();return}let d=document,w=d.startViewTransition;if(typeof w!='function'){f();return}let p=d.${VIEW_TRANSITION_PENDING_PROPERTY},pw=p&&(p.finished||p.ready);if(pw&&pw.then){let q=0,i,g=()=>{if(q)return;q=1;clearTimeout(i);d.${VIEW_TRANSITION_PENDING_PROPERTY}===p&&(d.${VIEW_TRANSITION_PENDING_PROPERTY}=null);this.v(b,s,f)};i=setTimeout(g,${VIEW_TRANSITION_TIMEOUT_MS});pw.then(g,g);return}this.a(o);let m=0,l=[],r=()=>{this.u(o);this.u(n);this.z(l)};try{let t=w.call(d,()=>{m=1;f(l);this.a(n)});if(t){d.${VIEW_TRANSITION_PENDING_PROPERTY}=t;let c=()=>{d.${VIEW_TRANSITION_PENDING_PROPERTY}===t&&(d.${VIEW_TRANSITION_PENDING_PROPERTY}=null)},cw=t.finished||t.ready;cw&&cw.then?cw.then(c,c):c()}this.j(t,r)}catch(e){r();if(m)throw e;f()}},m(a){let h=document.head,e=new Map;for(let n of h.querySelectorAll('[${STREAMED_METADATA_ATTRIBUTE}]'))e.set(n.getAttribute('${STREAMED_METADATA_ATTRIBUTE}'),n);for(let d of a){let k=d[0],t=d[1],v=d[2],n=e.get(k);if(!n||n.tagName.toLowerCase()!==t){n&&n.remove();n=document.createElement(t);n.setAttribute('${STREAMED_METADATA_ATTRIBUTE}',k);n.setAttribute('${HYDRATION_SKIP_ATTRIBUTE}','');h.appendChild(n)}e.delete(k);if(t==='title')n.textContent=v;else{for(let x of Array.from(n.attributes))if(x.name!=='${STREAMED_METADATA_ATTRIBUTE}'&&x.name!=='${HYDRATION_SKIP_ATTRIBUTE}')n.removeAttribute(x.name);for(let x of v)n.setAttribute(x[0],x[1])}}for(let n of e.values())n.remove()},s(p,s){p=document.getElementById(p);s=document.getElementById(s);if(!p||!s)return;this.v(p,s,()=>{while(s.firstChild)p.parentNode.insertBefore(s.firstChild,p);p.remove();s.remove()})},f(r,i){if(!r)return null;if(r.id===i)return r;for(let e of r.querySelectorAll?r.querySelectorAll('[id]'):[])if(e.id===i)return e;return null},b(t,b){let e=document.getElementById(t),r=e&&(e.content||e);return this.f(r,b)||document.getElementById(b)},c(b,s,m){let x=document.getElementById(b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r,m))},o(b,s,l,m){if(!b||!s)return;let a=b.previousSibling||b,p=a.parentNode,c=s.content||s;if(!p)return;let r=a.nodeType===8&&a.__figRetry;if(!r&&m)this.m(m);while(c.firstChild)p.insertBefore(c.firstChild,b);for(let e=b,d=0;e;){if(e.nodeType===8){if(e.data.indexOf('${SUSPENSE_MARKER_PREFIX}')===0)d++;else if(e.data==='${SUSPENSE_END_MARKER}'){if(d===0)break;d--}}let x=e.nextSibling;e.remove();e=x}s.remove();if(a.nodeType===8){a.data='${SUSPENSE_COMPLETED_MARKER}';if(r){if(l)l.push(r);else r()}}},x(b,d,m){this.y(document.getElementById(b),d,m)},y(b,d,m){if(!b)return;let s=b.previousSibling;if(s&&s.nodeType===8){s.data='${SUSPENSE_CLIENT_MARKER}';if(d)b.dataset.dgst=d;if(m)b.dataset.msg=m;s.__figRetry&&s.__figRetry()}},ac(t,b,s,m){let x=this.b(t,b),y=document.getElementById(s);this.v(x,y,r=>this.o(x,y,r,m))},ax(t,b,d,m){this.y(this.b(t,b),d,m)}}`;
536
547
  }
537
- function writeRuntime$1(request, write) {
548
+ const RUNTIME_CODE_PREFIX = "globalThis[";
549
+ const EMPTY_RUNTIME_REFERENCE = `${RUNTIME_CODE_PREFIX}${jsString("")}`;
550
+ const SERVER_RUNTIME_SUFFIX = buildServerRuntimeCode("").slice(EMPTY_RUNTIME_REFERENCE.length);
551
+ function serverRuntimeCodeFor(runtimeName) {
552
+ return `${RUNTIME_CODE_PREFIX}${jsString(runtimeName)}${SERVER_RUNTIME_SUFFIX}`;
553
+ }
554
+ function writeRuntime(request) {
538
555
  if (request.runtimeWritten) return;
539
556
  request.runtimeWritten = true;
540
- writeScript$1(request, serverRuntimeCodeFor(request.runtimeName), write);
557
+ writeScript$1(request, serverRuntimeCodeFor(request.runtimeName));
541
558
  }
542
- function writeScript$1(request, code, write) {
543
- write(`<script ${HYDRATION_SKIP_ATTRIBUTE}=""${nonceAttribute(request.nonce)}>${code}<\/script>`);
559
+ function writeScript$1(request, code) {
560
+ request.write(`<script ${HYDRATION_SKIP_ATTRIBUTE}=""${nonceAttribute(request.nonce)}>${code}<\/script>`);
544
561
  }
545
562
  function earlyEventCaptureCode() {
546
- return `(d=>{if(d.${EARLY_EVENT_QUEUE_PROPERTY})return;let q=d.${EARLY_EVENT_QUEUE_PROPERTY}=[],h=d.${EARLY_EVENT_HANDLER_PROPERTY}=e=>{q.push(e)};for(let t of [${REPLAYABLE_EVENT_TYPES.map((type) => `'${type}'`).join(",")}])d.addEventListener(t,h,!0)})(document)`;
563
+ return EARLY_EVENT_CAPTURE_CODE;
547
564
  }
565
+ const EARLY_EVENT_CAPTURE_CODE = `(d=>{if(d.${EARLY_EVENT_QUEUE_PROPERTY})return;let q=d.${EARLY_EVENT_QUEUE_PROPERTY}=[],h=d.${EARLY_EVENT_HANDLER_PROPERTY}=e=>{q.push(e)};for(let t of [${REPLAYABLE_EVENT_TYPES.map((type) => `'${type}'`).join(",")}])d.addEventListener(t,h,!0)})(document)`;
548
566
  function earlyEventCaptureMarkup(request) {
549
567
  return `<script ${HYDRATION_SKIP_ATTRIBUTE}=""${nonceAttribute(request.nonce)}>${earlyEventCaptureCode()}<\/script>`;
550
568
  }
@@ -588,14 +606,13 @@ const textEncoder = new TextEncoder();
588
606
  function flushCompletedQueues(request) {
589
607
  if (request.controller === null || request.status === "closed") return;
590
608
  if (request.pendingRootTasks > 0) return;
591
- if (request.prerender && request.pendingTasks > 0) return;
609
+ if (request.prerender && request.abortableTasks.size > 0) return;
592
610
  if (request.flushing) return;
593
611
  request.flushing = true;
594
612
  try {
595
613
  sealHead(request);
596
- if (request.completedRootSegment !== null) {
597
- flushSegment(request, request.completedRootSegment);
598
- request.completedRootSegment = null;
614
+ if (request.rootSegment.status !== "flushed") {
615
+ flushSegment(request, request.rootSegment);
599
616
  flushWriteBuffer(request);
600
617
  }
601
618
  if (!drainBoundaryQueue(request, request.clientRenderedBoundaries, flushClientRenderedBoundary) && !drainBoundaryQueue(request, request.completedBoundaries, flushCompletedBoundary)) drainBoundaryQueue(request, request.partialBoundaries, flushPartialBoundary);
@@ -603,20 +620,20 @@ function flushCompletedQueues(request) {
603
620
  } finally {
604
621
  request.flushing = false;
605
622
  }
606
- if (request.pendingTasks === 0 && request.completedBoundaries.size === 0 && request.clientRenderedBoundaries.size === 0 && request.partialBoundaries.size === 0) {
607
- request.cleanupAbortListener();
623
+ if (request.abortableTasks.size === 0 && request.completedBoundaries.size === 0 && request.clientRenderedBoundaries.size === 0 && request.partialBoundaries.size === 0) {
608
624
  request.status = "closed";
609
- request.dataStore.dispose();
625
+ request.dispose();
610
626
  request.controller.close();
611
627
  }
612
628
  }
613
629
  function sealHead(request) {
614
630
  if (request.headSnapshot !== null) return;
615
631
  activateVisibleMetadata(request, request.rootSegment);
616
- const metadata = request.assetRegistry.headMetadataHtml(request.nonce, !request.prerender && request.pendingTasks > 0);
632
+ const metadata = request.assetRegistry.headMetadataHtml(request.nonce, !request.prerender && request.abortableTasks.size > 0);
617
633
  request.headSnapshot = {
618
634
  ...metadata,
619
- preloadHeaderEntries: request.assetRegistry.preloadHeaderEntries()
635
+ preloadHeaderEntries: null,
636
+ preloadHeaderResources: request.assetRegistry.preloadHeaderResources()
620
637
  };
621
638
  request.headReady.resolve(metadata.preamble + metadata.metadata);
622
639
  }
@@ -636,21 +653,24 @@ function flushSubtree(request, segment) {
636
653
  }
637
654
  if (segment.status === "flushed") return;
638
655
  segment.status = "flushed";
639
- if (request.document === null || segment !== request.rootSegment) flushSegmentAssets(request, segment);
656
+ if (request.documentHasHead === null || segment !== request.rootSegment) collectSegmentAssets(request, segment, null);
640
657
  let chunkIndex = 0;
641
658
  for (const child of segment.children) {
642
659
  for (; chunkIndex < child.index; chunkIndex += 1) writeChunk(request, segment.chunks[chunkIndex], segment);
643
660
  flushSegment(request, child);
644
661
  }
645
662
  for (; chunkIndex < segment.chunks.length; chunkIndex += 1) writeChunk(request, segment.chunks[chunkIndex], segment);
663
+ segment.chunks.length = 0;
646
664
  }
647
665
  function flushSuspenseBoundary(request, segment, boundary) {
648
666
  boundary.parentFlushed = true;
649
667
  if (boundary.status === "completed") {
650
668
  request.write(`<!--${SUSPENSE_COMPLETED_MARKER}-->`);
651
- flushBoundaryContent(request, boundary);
669
+ for (const completedSegment of boundary.completedSegments) flushSegment(request, completedSegment);
670
+ boundary.completedSegments.length = 0;
652
671
  request.write(`<!--${SUSPENSE_END_MARKER}-->`);
653
672
  segment.status = "flushed";
673
+ segment.chunks.length = 0;
654
674
  return;
655
675
  }
656
676
  if (request.prerender && boundary.status === "client-rendered") {
@@ -661,7 +681,7 @@ function flushSuspenseBoundary(request, segment, boundary) {
661
681
  return;
662
682
  }
663
683
  const boundaryIdValue = ensureBoundaryId(request, boundary);
664
- flushSegmentAssets(request, boundary.contentSegment);
684
+ collectSegmentAssets(request, boundary.contentSegment, null);
665
685
  request.write(`<!--${SUSPENSE_PENDING_PREFIX}${boundaryIdValue}-->`);
666
686
  request.write(boundaryPlaceholderMarkup(request, boundaryIdValue));
667
687
  flushSubtree(request, segment);
@@ -669,10 +689,6 @@ function flushSuspenseBoundary(request, segment, boundary) {
669
689
  if (boundary.status === "client-rendered") request.clientRenderedBoundaries.add(boundary);
670
690
  else if (boundary.completedSegments.length > 0) request.partialBoundaries.add(boundary);
671
691
  }
672
- function flushBoundaryContent(request, boundary) {
673
- for (const segment of boundary.completedSegments) flushSegment(request, segment);
674
- boundary.completedSegments = [];
675
- }
676
692
  function clientRenderedBoundaryPlaceholderMarkup(request, boundary) {
677
693
  const id = escapeAttribute(boundaryId(request, ensureBoundaryId(request, boundary)));
678
694
  const digest = boundary.error?.digest;
@@ -685,11 +701,17 @@ function flushCompletedBoundary(request, boundary) {
685
701
  }
686
702
  function flushPartialBoundary(request, boundary) {
687
703
  for (const segment of boundary.completedSegments) flushBoundarySegment(request, boundary, segment);
688
- boundary.completedSegments = [];
704
+ boundary.completedSegments.length = 0;
689
705
  }
690
706
  function flushBoundarySegment(request, boundary, segment) {
691
707
  ensureBoundaryId(request, boundary);
692
- const blockingIds = flushSegmentContainer(request, segment);
708
+ let blockingIds = "";
709
+ if (segment.status !== "flushed") {
710
+ blockingIds = flushSegmentAssets(request, segment);
711
+ request.write(segmentContainerStartMarkup(request, ensureSegmentId(request, segment)));
712
+ flushSegment(request, segment);
713
+ request.write("</div>");
714
+ }
693
715
  if (segment !== boundary.contentSegment) writeSegmentRevealScript(request, segment, blockingIds);
694
716
  }
695
717
  function writeSegmentRevealScript(request, segment, blockingIds) {
@@ -739,32 +761,26 @@ function deactivateMetadataTree(request, segment) {
739
761
  boundary.metadataVisible = false;
740
762
  deactivateMetadataTree(request, boundary.contentSegment);
741
763
  }
742
- function flushSegmentContainer(request, segment) {
743
- if (segment.status === "flushed") return [];
744
- const blockingIds = flushSegmentAssets(request, segment);
745
- request.write(segmentContainerStartMarkup(request, ensureSegmentId(request, segment)));
746
- flushSegment(request, segment);
747
- request.write("</div>");
748
- return blockingIds;
749
- }
750
764
  function flushSegmentAssets(request, segment) {
751
765
  const blockingIds = /* @__PURE__ */ new Set();
752
766
  collectSegmentAssets(request, segment, blockingIds);
753
- return [...blockingIds];
767
+ let serialized = "";
768
+ for (const id of blockingIds) {
769
+ if (serialized !== "") serialized += ",";
770
+ serialized += jsString(id);
771
+ }
772
+ return serialized;
754
773
  }
755
774
  function collectSegmentAssets(request, segment, blockingIds) {
756
- if (segment.status !== "pending" && segment.status !== "rendering") flushAssetList(request, segment.assetResources, blockingIds);
757
- for (const child of segment.children) collectSegmentAssets(request, child, blockingIds);
758
- }
759
- function flushAssetList(request, resources, blockingIds) {
760
- for (const resource of resources) {
775
+ if (segment.status !== "pending" && segment.status !== "rendering") for (const resource of segment.assetResources) {
761
776
  const id = request.assetRegistry.write(resource, request);
762
- if (id !== null) blockingIds.add(id);
777
+ if (id !== null) blockingIds?.add(id);
763
778
  }
779
+ for (const child of segment.children) collectSegmentAssets(request, child, blockingIds);
764
780
  }
765
781
  function withAssetGate(blockingIds, call) {
766
- if (blockingIds.length === 0) return call;
767
- return `${RUNTIME_REF}.r([${blockingIds.map(jsString).join(",")}],()=>{${call}})`;
782
+ if (blockingIds === "") return call;
783
+ return `${RUNTIME_REF}.r([${blockingIds}],()=>{${call}})`;
768
784
  }
769
785
  function flushClientRenderedBoundary(request, boundary) {
770
786
  if (boundary.id === null) return;
@@ -784,11 +800,8 @@ function drainBoundaryQueue(request, queue, flush) {
784
800
  flushWriteBuffer(request);
785
801
  }
786
802
  }
787
- function writeRuntime(request) {
788
- writeRuntime$1(request, (chunk) => request.write(chunk));
789
- }
790
803
  function writeScript(request, code) {
791
- writeScript$1(request, `(__figSSR=>{${code}})(globalThis[${jsString(request.runtimeName)}])`, (chunk) => request.write(chunk));
804
+ writeScript$1(request, `(__figSSR=>{${code}})(globalThis[${jsString(request.runtimeName)}])`);
792
805
  }
793
806
  function writeChunk(request, chunk, segment) {
794
807
  if (chunk === leadingNewlineStartMarker) {
@@ -807,34 +820,14 @@ function writeChunk(request, chunk, segment) {
807
820
  request.write(chunk);
808
821
  return;
809
822
  }
810
- if (request.document === null) return;
823
+ if (request.documentHasHead === null) return;
811
824
  const metadata = request.headSnapshot ?? request.assetRegistry.headMetadataHtml(request.nonce);
812
- const [beforeMetadata, afterMetadata] = partitionHeadAssets(request, segment.assetResources);
813
- const blockingIds = /* @__PURE__ */ new Set();
814
- request.write(metadata.preamble);
815
- flushAssetList(request, beforeMetadata, blockingIds);
816
- request.write(metadata.metadata);
817
- flushAssetList(request, afterMetadata, blockingIds);
818
- }
819
- function partitionHeadAssets(request, resources) {
820
- const preconnects = [];
821
- const criticalPreloads = [];
822
- const stylesheets = [];
823
- const afterMetadata = [];
824
- for (const resource of resources) if (resource.kind === "preconnect") preconnects.push(resource);
825
- else if (resource.kind === "font" || resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || request.assetRegistry.isEarlyImage(resource)))) criticalPreloads.push(resource);
826
- else if (resource.kind === "stylesheet") stylesheets.push(resource);
827
- else afterMetadata.push(resource);
828
- return [[
829
- ...preconnects,
830
- ...criticalPreloads,
831
- ...stylesheets
832
- ], afterMetadata];
825
+ request.assetRegistry.writeDocumentHead(segment.assetResources, metadata, request);
833
826
  }
834
827
  function flushWriteBuffer(request) {
835
- if (request.writeBuffer.length === 0 || request.controller === null) return;
836
- request.controller.enqueue(textEncoder.encode(request.writeBuffer.join("")));
837
- request.writeBuffer = [];
828
+ if (request.writeBuffer === "" || request.controller === null) return;
829
+ request.controller.enqueue(textEncoder.encode(request.writeBuffer));
830
+ request.writeBuffer = "";
838
831
  }
839
832
  function ensureSegmentId(request, segment) {
840
833
  segment.id ??= request.nextSegmentId++;
@@ -849,31 +842,32 @@ function ensureBoundaryId(request, boundary) {
849
842
  const errorStacks = /* @__PURE__ */ new WeakMap();
850
843
  const TEXT_SEPARATOR = `<!--${TEXT_SEPARATOR_DATA}-->`;
851
844
  let nextRuntimeId = 0;
852
- function createServerRenderRequest(node, options = {}, mode = {}) {
845
+ function createServerRenderRequest(node, options, mode) {
853
846
  throwIfAborted(options.signal);
847
+ const identifierPrefix = options.identifierPrefix ?? "";
854
848
  const shellReady = deferred();
855
849
  const headReady = deferred();
856
850
  const allReady = deferred();
857
- shellReady.promise.catch(() => void 0);
858
- headReady.promise.catch(() => void 0);
859
- allReady.promise.catch(() => void 0);
860
- const rootSegment = createSegment(0, null);
851
+ shellReady.promise.catch(noop);
852
+ headReady.promise.catch(noop);
853
+ allReady.promise.catch(noop);
854
+ const rootSegment = createSegment(0);
861
855
  const dataStoreHost = {
862
- getLane: () => null,
856
+ getLane: noLane,
863
857
  partition: options.dataPartition,
864
- schedule: () => void 0
858
+ schedule: noop
865
859
  };
866
860
  const dataStore = options.dataStore === void 0 ? createRendererDataStore(dataStoreHost) : attachDataStore(options.dataStore, dataStoreHost, options.initialData);
867
861
  const request = {
868
862
  abortableTasks: /* @__PURE__ */ new Set(),
869
863
  allReady,
870
- cleanupAbortListener: () => void 0,
864
+ cleanupAbortListener: null,
871
865
  completedBoundaries: /* @__PURE__ */ new Set(),
872
- completedRootSegment: null,
873
866
  controller: null,
874
867
  dataStore,
875
- fatalError: null,
876
- identifierPrefix: options.identifierPrefix ?? "",
868
+ dispose: disposeRequest,
869
+ abortReason: null,
870
+ identifierPrefix,
877
871
  leadingNewlineStack: [],
878
872
  nextBoundaryId: 0,
879
873
  nextSegmentId: 0,
@@ -882,10 +876,9 @@ function createServerRenderRequest(node, options = {}, mode = {}) {
882
876
  nonce: options.nonce,
883
877
  onError: options.onError,
884
878
  pendingRootTasks: 0,
885
- pendingTasks: 0,
886
879
  pingedTasks: [],
887
880
  rootSegment,
888
- runtimeName: createRuntimeName(options.identifierPrefix),
881
+ runtimeName: createRuntimeName(identifierPrefix),
889
882
  runtimeWritten: false,
890
883
  headReady,
891
884
  headSnapshot: null,
@@ -894,37 +887,37 @@ function createServerRenderRequest(node, options = {}, mode = {}) {
894
887
  clientRenderedBoundaries: /* @__PURE__ */ new Set(),
895
888
  clientReferenceFallback: options.clientReferenceFallback,
896
889
  partialBoundaries: /* @__PURE__ */ new Set(),
897
- prerender: mode.prerender === true,
890
+ prerender: mode?.prerender === true,
898
891
  componentAssets: options.assets,
899
- document: mode.document === true ? { hasHead: false } : null,
900
- assetRegistry: new AssetResourceRegistry(options.identifierPrefix ?? ""),
892
+ documentHasHead: mode?.document === true ? false : null,
893
+ assetRegistry: new AssetResourceRegistry(identifierPrefix),
901
894
  resolveAssetKey: options.resolveAssetKey,
902
- workScheduled: false,
903
895
  flushing: false,
904
- writeBuffer: [],
905
- write(chunk) {
906
- if (chunk !== "" && this.leadingNewlineStack.length > 0) this.leadingNewlineStack[this.leadingNewlineStack.length - 1] = true;
907
- this.writeBuffer.push(chunk);
908
- }
896
+ writeBuffer: "",
897
+ write: writeRequestChunk
909
898
  };
910
899
  if (options.dataStore === void 0 && options.initialData !== void 0) request.dataStore.hydrate(options.initialData);
911
900
  rootSegment.parentFlushed = true;
912
- const rootTask = createTask(request, node, rootSegment, {
913
- abortSet: request.abortableTasks,
901
+ pingTask(createTask(node, {
914
902
  boundary: null,
915
903
  contextValues: /* @__PURE__ */ new Map(),
904
+ dispatcher: null,
905
+ fallbackTasks: null,
916
906
  hiddenActivityId: null,
917
907
  hostAncestors: [],
918
908
  hostNamespace: "html",
919
909
  imagePreloadsSuppressed: false,
920
- idPath: "",
910
+ idPath: [],
911
+ idPathString: null,
912
+ localIdCounter: 0,
921
913
  pendingLeadingNewline: false,
914
+ request,
922
915
  selectProps: null,
916
+ segment: rootSegment,
923
917
  stack: null,
924
918
  treeParent: options.renderTree?.tree ?? null,
925
919
  viewTransition: null
926
- });
927
- request.pingedTasks.push(rootTask);
920
+ }));
928
921
  const stream = new ReadableStream({
929
922
  start(streamController) {
930
923
  request.controller = streamController;
@@ -935,7 +928,7 @@ function createServerRenderRequest(node, options = {}, mode = {}) {
935
928
  },
936
929
  cancel(reason) {
937
930
  request.controller = null;
938
- request.writeBuffer = [];
931
+ request.writeBuffer = "";
939
932
  abort(request, reason);
940
933
  request.status = "closed";
941
934
  }
@@ -946,21 +939,28 @@ function createServerRenderRequest(node, options = {}, mode = {}) {
946
939
  signal.addEventListener("abort", abortListener, { once: true });
947
940
  request.cleanupAbortListener = () => {
948
941
  signal.removeEventListener("abort", abortListener);
949
- request.cleanupAbortListener = () => void 0;
942
+ request.cleanupAbortListener = null;
950
943
  };
951
944
  }
952
- request.workScheduled = true;
953
- queueMicrotask(() => {
954
- request.workScheduled = false;
955
- performWork(request);
956
- });
957
945
  return {
958
946
  abort: (reason) => abort(request, reason),
959
947
  allReady: allReady.promise,
960
948
  contentType: "text/html; charset=utf-8",
961
949
  data: request.dataStore,
962
950
  getData: () => request.dataStore.snapshot(),
963
- getPreloadHeader: (headerOptions) => request.headSnapshot === null ? void 0 : formatPreloadHeader(request.headSnapshot.preloadHeaderEntries, headerOptions),
951
+ getPreloadHeader: (headerOptions) => {
952
+ const snapshot = request.headSnapshot;
953
+ if (snapshot === null) return void 0;
954
+ let entries = snapshot.preloadHeaderEntries;
955
+ if (entries === null) {
956
+ const resources = snapshot.preloadHeaderResources;
957
+ if (resources === null) throw new Error("Missing preload-header resource snapshot.");
958
+ entries = createPreloadHeaderEntries(resources);
959
+ snapshot.preloadHeaderEntries = entries;
960
+ snapshot.preloadHeaderResources = null;
961
+ }
962
+ return formatPreloadHeader(entries, headerOptions);
963
+ },
964
964
  getHead: () => {
965
965
  const snapshot = request.headSnapshot;
966
966
  return snapshot === null ? request.assetRegistry.headHtml(request.nonce) : snapshot.preamble + snapshot.metadata;
@@ -970,105 +970,91 @@ function createServerRenderRequest(node, options = {}, mode = {}) {
970
970
  stream
971
971
  };
972
972
  }
973
- function createTask(request, node, segment, scope, childIndexBase = 0) {
974
- request.pendingTasks += 1;
975
- if (scope.boundary === null) request.pendingRootTasks += 1;
976
- else scope.boundary.pendingTasks += 1;
973
+ function createTask(node, frame, childIndexBase = 0) {
974
+ const { request } = frame;
975
+ if (frame.boundary === null) request.pendingRootTasks += 1;
976
+ else frame.boundary.pendingTasks += 1;
977
977
  const task = {
978
- ...scope,
979
978
  childIndexBase,
980
- node,
981
- segment
979
+ frame,
980
+ node
982
981
  };
983
982
  request.abortableTasks.add(task);
984
- scope.abortSet.add(task);
983
+ frame.fallbackTasks?.add(task);
985
984
  return task;
986
985
  }
987
- function forkScope(scope) {
986
+ function forkFrame(frame, segment, boundary = frame.boundary, fallbackTasks = frame.fallbackTasks) {
988
987
  return {
989
- abortSet: scope.abortSet,
990
- boundary: scope.boundary,
991
- contextValues: cloneContextValues(scope.contextValues),
992
- hiddenActivityId: scope.hiddenActivityId,
993
- hostAncestors: scope.hostAncestors,
994
- hostNamespace: scope.hostNamespace,
995
- imagePreloadsSuppressed: scope.imagePreloadsSuppressed,
996
- idPath: scope.idPath,
997
- pendingLeadingNewline: scope.pendingLeadingNewline,
998
- selectProps: scope.selectProps,
999
- stack: scope.stack,
1000
- treeParent: scope.treeParent,
1001
- viewTransition: scope.viewTransition === null ? null : { ...scope.viewTransition }
988
+ boundary,
989
+ contextValues: cloneContextValues(frame.contextValues),
990
+ dispatcher: null,
991
+ fallbackTasks,
992
+ hiddenActivityId: frame.hiddenActivityId,
993
+ hostAncestors: frame.hostAncestors,
994
+ hostNamespace: frame.hostNamespace,
995
+ imagePreloadsSuppressed: frame.imagePreloadsSuppressed,
996
+ idPath: [...frame.idPath],
997
+ idPathString: null,
998
+ localIdCounter: 0,
999
+ pendingLeadingNewline: frame.pendingLeadingNewline,
1000
+ request: frame.request,
1001
+ selectProps: frame.selectProps,
1002
+ segment,
1003
+ stack: frame.stack,
1004
+ treeParent: frame.treeParent,
1005
+ viewTransition: frame.viewTransition === null ? null : { ...frame.viewTransition }
1002
1006
  };
1003
1007
  }
1004
- function createSegment(index, boundary, textSeams = {
1005
- lastPushedText: false,
1006
- textEmbedded: false
1007
- }) {
1008
+ function createSegment(index, boundary = null) {
1008
1009
  return {
1009
1010
  boundary,
1010
1011
  children: [],
1011
1012
  chunks: [],
1012
1013
  id: null,
1013
1014
  index,
1014
- lastPushedText: textSeams.lastPushedText,
1015
+ lastPushedText: false,
1015
1016
  parentFlushed: false,
1016
1017
  assetResources: [],
1017
1018
  status: "pending",
1018
- textEmbedded: textSeams.textEmbedded,
1019
- write(chunk) {
1020
- this.lastPushedText = false;
1021
- this.chunks.push(chunk);
1022
- }
1019
+ textEmbedded: false,
1020
+ write: writeSegmentChunk
1023
1021
  };
1024
1022
  }
1025
- function createBoundary(fallbackAbortableTasks, contentSegment) {
1026
- return {
1027
- activityId: null,
1028
- completedSegments: [],
1029
- contentSegment,
1030
- error: null,
1031
- fallbackSegment: null,
1032
- fallbackAbortableTasks,
1033
- id: null,
1034
- parentFlushed: false,
1035
- pendingTasks: 0,
1036
- status: "pending",
1037
- metadataVisible: false
1038
- };
1023
+ function writeRequestChunk(chunk) {
1024
+ if (chunk !== "" && this.leadingNewlineStack.length > 0) this.leadingNewlineStack[this.leadingNewlineStack.length - 1] = true;
1025
+ this.writeBuffer += chunk;
1026
+ }
1027
+ function disposeRequest() {
1028
+ this.cleanupAbortListener?.();
1029
+ this.dataStore.dispose();
1030
+ }
1031
+ function writeSegmentChunk(chunk) {
1032
+ this.lastPushedText = false;
1033
+ this.chunks.push(chunk);
1039
1034
  }
1040
1035
  function performWork(request) {
1041
1036
  if (request.status === "closed") return;
1042
1037
  const tasks = request.pingedTasks;
1043
1038
  request.pingedTasks = [];
1044
- for (const task of tasks) retryTask(request, task);
1039
+ for (const task of tasks) retryTask(task);
1045
1040
  flushCompletedQueues(request);
1046
1041
  }
1047
- function retryTask(request, task) {
1048
- if (task.segment.status !== "pending") return;
1049
- task.segment.status = "rendering";
1050
- const frame = createRenderFrame(request, task.segment, forkScope(task));
1042
+ function retryTask(task) {
1043
+ const { frame } = task;
1044
+ if (frame.segment.status !== "pending") return;
1045
+ frame.segment.status = "rendering";
1051
1046
  try {
1052
- renderChildSequence(collectChildren(task.node), frame, task.childIndexBase);
1053
- completeSegmentText(task.segment);
1054
- task.segment.status = "completed";
1055
- detachTask(request, task);
1056
- finishedTask(request, task);
1047
+ renderChildren(task.node, frame, task.childIndexBase);
1048
+ completeSegmentText(frame.segment);
1049
+ frame.segment.status = "completed";
1050
+ detachTask(task);
1051
+ settleTask(task, "completed");
1057
1052
  } catch (error) {
1058
- detachTask(request, task);
1059
- task.segment.status = "completed";
1060
- erroredTask(request, task, error);
1053
+ detachTask(task);
1054
+ frame.segment.status = "completed";
1055
+ settleTask(task, "errored", error);
1061
1056
  }
1062
1057
  }
1063
- function createRenderFrame(request, segment, scope) {
1064
- return {
1065
- ...scope,
1066
- dispatcher: null,
1067
- localIdCounter: 0,
1068
- request,
1069
- segment
1070
- };
1071
- }
1072
1058
  function createServerDispatcher(frame) {
1073
1059
  return createStaticDispatcher({
1074
1060
  contextValues: frame.contextValues,
@@ -1086,7 +1072,8 @@ function createServerDispatcher(frame) {
1086
1072
  frame.request.dataStore.preloadData(resource, ...args);
1087
1073
  },
1088
1074
  useId() {
1089
- const id = `${frame.request.identifierPrefix}fig-${frame.idPath}-${frame.localIdCounter.toString(32)}`;
1075
+ frame.idPathString ??= formatIdPath(frame.idPath);
1076
+ const id = `${frame.request.identifierPrefix}fig-${frame.idPathString}-${frame.localIdCounter.toString(32)}`;
1090
1077
  frame.localIdCounter += 1;
1091
1078
  return id;
1092
1079
  },
@@ -1094,14 +1081,9 @@ function createServerDispatcher(frame) {
1094
1081
  });
1095
1082
  }
1096
1083
  function renderNode(node, frame) {
1097
- if (Array.isArray(node)) {
1098
- renderChildren(node, frame);
1099
- return;
1100
- }
1101
- if (node === null || node === void 0 || typeof node === "boolean") return;
1102
1084
  if (typeof node === "string" || typeof node === "number") {
1103
1085
  const text = String(node);
1104
- if (frame.request.document !== null && !frame.request.document.hasHead) {
1086
+ if (frame.request.documentHasHead === false) {
1105
1087
  if (text.trim() !== "") throw invalidDocumentShellError();
1106
1088
  }
1107
1089
  if (text !== "") {
@@ -1113,7 +1095,7 @@ function renderNode(node, frame) {
1113
1095
  props: { nodeValue: text }
1114
1096
  });
1115
1097
  if (frame.segment.lastPushedText) frame.segment.write(TEXT_SEPARATOR);
1116
- if (consumePendingLeadingNewline(frame)) writeLeadingNewlineText(text, frame.segment);
1098
+ if (consumePendingLeadingNewline(frame)) frame.segment.write({ value: escapeText(text) });
1117
1099
  else writeText(text, frame.segment);
1118
1100
  frame.segment.lastPushedText = true;
1119
1101
  }
@@ -1130,36 +1112,44 @@ function renderNode(node, frame) {
1130
1112
  }
1131
1113
  throw invalidChildError(node);
1132
1114
  }
1133
- function renderChildren(node, frame) {
1134
- renderChildSequence(collectChildren(node), frame);
1115
+ function renderChildren(node, frame, indexBase = 0) {
1116
+ if (Array.isArray(node)) {
1117
+ const children = collectChildren(node);
1118
+ for (let index = 0; index < children.length; index += 1) renderChildAtIndex(children[index], frame, indexBase + index);
1119
+ return;
1120
+ }
1121
+ if (node === null || node === void 0 || typeof node === "boolean" || node === "") return;
1122
+ renderChildAtIndex(node, frame, indexBase);
1135
1123
  }
1136
- function renderChildSequence(children, frame, indexBase = 0) {
1137
- for (let index = 0; index < children.length; index += 1) {
1138
- const child = children[index];
1139
- try {
1140
- withIdSegment(frame, indexBase + index, () => renderNode(child, frame));
1141
- } catch (error) {
1142
- if (isThenable(error)) {
1143
- spawnSuspendedTask(frame, child, error, indexBase + index);
1144
- continue;
1145
- }
1146
- throw error;
1124
+ function renderChildAtIndex(child, frame, index) {
1125
+ const previousIdPathString = frame.idPathString;
1126
+ frame.idPath.push(index);
1127
+ frame.idPathString = null;
1128
+ try {
1129
+ renderNode(child, frame);
1130
+ } catch (error) {
1131
+ frame.idPath.pop();
1132
+ frame.idPathString = previousIdPathString;
1133
+ if (isThenable(error)) {
1134
+ spawnSuspendedTask(frame, child, error, index);
1135
+ return;
1147
1136
  }
1137
+ throw error;
1148
1138
  }
1139
+ frame.idPath.pop();
1140
+ frame.idPathString = previousIdPathString;
1141
+ }
1142
+ function formatIdPath(path) {
1143
+ let value = "";
1144
+ for (let index = 0; index < path.length; index += 1) {
1145
+ if (index > 0) value += "-";
1146
+ value += path[index].toString(32);
1147
+ }
1148
+ return value;
1149
1149
  }
1150
1150
  function completeSegmentText(segment) {
1151
1151
  if (segment.textEmbedded && segment.lastPushedText) segment.write(TEXT_SEPARATOR);
1152
1152
  }
1153
- function withIdSegment(frame, index, callback) {
1154
- const previousIdPath = frame.idPath;
1155
- const segment = index.toString(32);
1156
- frame.idPath = previousIdPath === "" ? segment : `${previousIdPath}-${segment}`;
1157
- try {
1158
- return callback();
1159
- } finally {
1160
- frame.idPath = previousIdPath;
1161
- }
1162
- }
1163
1153
  function renderElement(element, frame) {
1164
1154
  if (frame.treeParent === null) {
1165
1155
  renderElementKind(element, frame);
@@ -1249,7 +1239,7 @@ function renderFunctionComponent(type, props, frame) {
1249
1239
  const previousDataStore = setCurrentDataStore(frame.request.dataStore);
1250
1240
  const previousStack = frame.stack;
1251
1241
  const previousLocalIdCounter = frame.localIdCounter;
1252
- frame.stack = {
1242
+ if (frame.request.onError !== void 0) frame.stack = {
1253
1243
  name: type.name || "Anonymous",
1254
1244
  parent: previousStack
1255
1245
  };
@@ -1294,16 +1284,18 @@ function renderAssets(props, frame) {
1294
1284
  }
1295
1285
  function renderAssetValue(value, frame) {
1296
1286
  if (value === void 0 || value === null || value === false) return;
1297
- for (const resource of Array.isArray(value) ? value : [value]) {
1298
- if (!isFigAssetResource(resource)) throw new Error("The assets prop must contain Fig asset resources.");
1299
- try {
1300
- frame.request.assetRegistry.register(resource);
1301
- } catch (error) {
1302
- recordErrorStack(error, frame.stack);
1303
- throw error;
1304
- }
1305
- frame.segment.assetResources.push(resource);
1287
+ if (Array.isArray(value)) for (const resource of value) renderAssetResource(resource, frame);
1288
+ else renderAssetResource(value, frame);
1289
+ }
1290
+ function renderAssetResource(resource, frame) {
1291
+ if (!isFigAssetResource(resource)) throw new Error("The assets prop must contain Fig asset resources.");
1292
+ try {
1293
+ frame.request.assetRegistry.register(resource);
1294
+ } catch (error) {
1295
+ recordErrorStack(error, frame.stack);
1296
+ throw error;
1306
1297
  }
1298
+ frame.segment.assetResources.push(resource);
1307
1299
  }
1308
1300
  function renderAutomaticImagePreload(resource, frame) {
1309
1301
  try {
@@ -1316,20 +1308,27 @@ function renderAutomaticImagePreload(resource, frame) {
1316
1308
  }
1317
1309
  function renderSuspense(props, frame) {
1318
1310
  consumePendingLeadingNewline(frame);
1319
- const fallbackAbortableTasks = /* @__PURE__ */ new Set();
1320
- const contentSegment = createSegment(0, null);
1321
- const boundary = createBoundary(fallbackAbortableTasks, contentSegment);
1322
- boundary.activityId = frame.hiddenActivityId;
1311
+ const contentSegment = createSegment(0);
1312
+ const boundary = {
1313
+ activityId: frame.hiddenActivityId,
1314
+ completedSegments: [],
1315
+ contentSegment,
1316
+ error: null,
1317
+ fallbackSegment: null,
1318
+ fallbackTasks: /* @__PURE__ */ new Set(),
1319
+ id: null,
1320
+ metadataVisible: false,
1321
+ parentFlushed: false,
1322
+ pendingTasks: 0,
1323
+ status: "pending"
1324
+ };
1323
1325
  const parentSegment = frame.segment;
1324
1326
  const boundarySegment = createSegment(parentSegment.chunks.length, boundary);
1325
1327
  boundary.fallbackSegment = boundarySegment;
1326
1328
  parentSegment.children.push(boundarySegment);
1327
1329
  parentSegment.lastPushedText = false;
1328
1330
  contentSegment.parentFlushed = true;
1329
- const contentFrame = createRenderFrame(frame.request, contentSegment, {
1330
- ...forkScope(frame),
1331
- boundary
1332
- });
1331
+ const contentFrame = forkFrame(frame, contentSegment, boundary);
1333
1332
  try {
1334
1333
  renderChildren(props.children, contentFrame);
1335
1334
  contentSegment.status = "completed";
@@ -1339,46 +1338,36 @@ function renderSuspense(props, frame) {
1339
1338
  contentSegment.status = "completed";
1340
1339
  markBoundaryClientRendered(frame.request, boundary, error, frame.stack);
1341
1340
  }
1342
- const advanceSurfaceWatermark = (branch) => {
1343
- if (frame.viewTransition !== null && branch.viewTransition !== null) frame.viewTransition.index = Math.max(frame.viewTransition.index, branch.viewTransition.index);
1344
- };
1345
- advanceSurfaceWatermark(contentFrame);
1341
+ advanceViewTransitionWatermark(frame, contentFrame);
1346
1342
  if (boundary.status === "completed") return;
1347
- const fallbackFrame = createRenderFrame(frame.request, boundarySegment, {
1348
- ...forkScope(frame),
1349
- abortSet: fallbackAbortableTasks
1350
- });
1343
+ const fallbackFrame = forkFrame(frame, boundarySegment, frame.boundary, boundary.fallbackTasks);
1351
1344
  try {
1352
1345
  renderChildren(props.fallback, fallbackFrame);
1353
1346
  boundarySegment.status = "completed";
1354
1347
  } catch (error) {
1355
- if (boundary.pendingTasks > 0) for (const task of Array.from(boundary.fallbackAbortableTasks)) abortTask(frame.request, task);
1348
+ if (boundary.pendingTasks > 0) for (const task of boundary.fallbackTasks) abortTask(task);
1356
1349
  throw error;
1357
1350
  } finally {
1358
- advanceSurfaceWatermark(fallbackFrame);
1351
+ advanceViewTransitionWatermark(frame, fallbackFrame);
1359
1352
  }
1360
1353
  }
1354
+ function advanceViewTransitionWatermark(parent, branch) {
1355
+ if (parent.viewTransition !== null && branch.viewTransition !== null) parent.viewTransition.index = Math.max(parent.viewTransition.index, branch.viewTransition.index);
1356
+ }
1361
1357
  function renderViewTransition(props, frame) {
1362
1358
  const previousViewTransition = frame.viewTransition;
1363
- frame.viewTransition = createServerViewTransition(props, frame.request);
1359
+ const className = props.default;
1360
+ frame.viewTransition = {
1361
+ className: className === void 0 || className === "auto" || className === "none" ? null : className,
1362
+ index: 0,
1363
+ name: props.name === void 0 || props.name === "auto" ? `fig-vt-${frame.request.nextViewTransitionId++}` : props.name
1364
+ };
1364
1365
  try {
1365
1366
  renderChildren(props.children, frame);
1366
1367
  } finally {
1367
1368
  frame.viewTransition = previousViewTransition;
1368
1369
  }
1369
1370
  }
1370
- function createServerViewTransition(props, request) {
1371
- return {
1372
- className: serverViewTransitionClass(props),
1373
- index: 0,
1374
- name: props.name === void 0 || props.name === "auto" ? `fig-vt-${request.nextViewTransitionId++}` : props.name
1375
- };
1376
- }
1377
- function serverViewTransitionClass(props) {
1378
- const className = props.default;
1379
- if (className === void 0 || className === "auto" || className === "none") return null;
1380
- return className;
1381
- }
1382
1371
  function renderActivity(props, frame) {
1383
1372
  if (props.mode !== "hidden") {
1384
1373
  renderChildren(props.children, frame);
@@ -1396,14 +1385,16 @@ function renderActivity(props, frame) {
1396
1385
  frame.segment.write("</template>");
1397
1386
  }
1398
1387
  function renderHostElement(type, props, frame) {
1399
- const namespace = hostElementNamespace(type, frame.hostNamespace);
1400
- if (namespace === "html" && renderHostAsset(type, props, frame)) return;
1401
- const document = frame.request.document;
1402
- if (document !== null && !document.hasHead) {
1388
+ const normalizedType = type.toLowerCase();
1389
+ const namespace = normalizedType === "svg" ? "svg" : normalizedType === "math" ? "mathml" : frame.hostNamespace;
1390
+ if (namespace === "html" && renderHostAsset(normalizedType, props, frame)) return;
1391
+ const isDocument = frame.request.documentHasHead !== null;
1392
+ const isDocumentHead = isDocument && type === "head";
1393
+ if (frame.request.documentHasHead === false) {
1403
1394
  if (type !== "html" && type !== "head") throw invalidDocumentShellError();
1404
1395
  }
1405
- if (document !== null && type === "html") frame.segment.write("<!doctype html>");
1406
- if (document !== null && type === "head") document.hasHead = true;
1396
+ if (isDocument && type === "html") frame.segment.write("<!doctype html>");
1397
+ if (isDocumentHead) frame.request.documentHasHead = true;
1407
1398
  const isVoid = namespace === "html" && isVoidElement(type);
1408
1399
  const unsafeHTML = unsafeHTMLContent(props);
1409
1400
  if (isVoid && hasRenderableChild(props.children)) throw new Error(`Void element <${type}> cannot have children.`);
@@ -1415,21 +1406,18 @@ function renderHostElement(type, props, frame) {
1415
1406
  }
1416
1407
  consumePendingLeadingNewline(frame);
1417
1408
  const viewTransition = frame.viewTransition;
1418
- writeElementStart(type, viewTransition === null ? props : viewTransitionHostProps(props, viewTransition), frame.segment, frame.selectProps ?? {});
1419
- if (document !== null && type === "head") frame.segment.write(earlyEventCaptureMarkup(frame.request));
1409
+ writeElementStart(type, viewTransition === null ? props : viewTransitionHostProps(props, viewTransition), frame.segment, frame.selectProps);
1410
+ if (isDocumentHead) frame.segment.write(earlyEventCaptureMarkup(frame.request));
1420
1411
  if (isVoid) return;
1421
1412
  const previousPendingLeadingNewline = frame.pendingLeadingNewline;
1422
- const tracksLeadingNewline = leadingNewlineStrippedHost(type);
1413
+ const tracksLeadingNewline = type === "pre" || type === "textarea";
1423
1414
  frame.pendingLeadingNewline = tracksLeadingNewline;
1424
- if (unsafeHTML !== null) {
1425
- frame.segment.write(consumePendingLeadingNewline(frame) ? preserveParserStrippedLeadingNewline(unsafeHTML) : unsafeHTML);
1426
- frame.pendingLeadingNewline = previousPendingLeadingNewline;
1427
- writeElementEnd(type, frame.segment);
1428
- return;
1429
- }
1430
1415
  const formText = namespace === "html" ? formTextContent(type, props) : null;
1431
- if (formText !== null) {
1432
- writeText(consumePendingLeadingNewline(frame) ? preserveParserStrippedLeadingNewline(formText) : formText, frame.segment);
1416
+ const staticContent = unsafeHTML ?? formText;
1417
+ if (staticContent !== null) {
1418
+ const content = consumePendingLeadingNewline(frame) && staticContent.startsWith("\n") ? `\n${staticContent}` : staticContent;
1419
+ if (unsafeHTML === null) writeText(content, frame.segment);
1420
+ else frame.segment.write(content);
1433
1421
  frame.pendingLeadingNewline = previousPendingLeadingNewline;
1434
1422
  writeElementEnd(type, frame.segment);
1435
1423
  return;
@@ -1441,7 +1429,7 @@ function renderHostElement(type, props, frame) {
1441
1429
  const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;
1442
1430
  const previousViewTransition = frame.viewTransition;
1443
1431
  if (viewTransition !== null) frame.viewTransition = null;
1444
- frame.hostNamespace = childHostNamespace(type, namespace);
1432
+ frame.hostNamespace = namespace === "svg" && normalizedType === "foreignobject" ? "html" : namespace;
1445
1433
  frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed || namespace === "html" && suppressesImagePreloads(type);
1446
1434
  if (tracksLeadingNewline) frame.segment.chunks.push(leadingNewlineStartMarker);
1447
1435
  try {
@@ -1455,20 +1443,19 @@ function renderHostElement(type, props, frame) {
1455
1443
  frame.pendingLeadingNewline = previousPendingLeadingNewline;
1456
1444
  }
1457
1445
  if (tracksLeadingNewline) frame.segment.chunks.push(leadingNewlineEndMarker);
1458
- if (document !== null && type === "head") writeDocumentHeadMarker(frame.segment);
1446
+ if (isDocumentHead) frame.segment.write(documentHeadMarker);
1459
1447
  writeElementEnd(type, frame.segment);
1460
1448
  }
1461
- function hostElementNamespace(type, parent) {
1462
- const normalizedType = type.toLowerCase();
1463
- if (normalizedType === "svg") return "svg";
1464
- if (normalizedType === "math") return "mathml";
1465
- return parent;
1466
- }
1467
- function childHostNamespace(type, namespace) {
1468
- return namespace === "svg" && type.toLowerCase() === "foreignobject" ? "html" : namespace;
1469
- }
1470
- function renderHostAsset(type, props, frame) {
1471
- const resource = assetResourceFromHostProps(type, props);
1449
+ function renderHostAsset(normalizedType, props, frame) {
1450
+ if (normalizedType.length < 4 || normalizedType.length > 6) return false;
1451
+ switch (normalizedType) {
1452
+ case "link":
1453
+ case "meta":
1454
+ case "script":
1455
+ case "title": break;
1456
+ default: return false;
1457
+ }
1458
+ const resource = assetResourceFromHostProps(normalizedType, props);
1472
1459
  if (resource === null) return false;
1473
1460
  renderAssetValue(resource, frame);
1474
1461
  return true;
@@ -1484,144 +1471,106 @@ function viewTransitionHostProps(props, viewTransition) {
1484
1471
  return nextProps;
1485
1472
  }
1486
1473
  function spawnSuspendedTask(frame, node, thenable, childIndexBase) {
1487
- const request = frame.request;
1488
- const segment = createSegment(frame.segment.chunks.length, null, {
1489
- lastPushedText: frame.segment.lastPushedText,
1490
- textEmbedded: true
1491
- });
1474
+ const segment = createSegment(frame.segment.chunks.length);
1475
+ segment.lastPushedText = frame.segment.lastPushedText;
1476
+ segment.textEmbedded = true;
1492
1477
  frame.segment.lastPushedText = false;
1493
1478
  frame.segment.children.push(segment);
1494
- const task = createTask(request, node, segment, forkScope(frame), childIndexBase);
1495
- thenable.then(() => pingTask(request, task), () => pingTask(request, task));
1479
+ const task = createTask(node, forkFrame(frame, segment), childIndexBase);
1480
+ const ping = () => pingTask(task);
1481
+ thenable.then(ping, ping);
1496
1482
  }
1497
- function pingTask(request, task) {
1483
+ function pingTask(task) {
1484
+ const { request } = task.frame;
1498
1485
  if (request.status === "closed" || request.status === "aborting") return;
1486
+ const shouldSchedule = request.pingedTasks.length === 0;
1499
1487
  request.pingedTasks.push(task);
1500
- if (request.workScheduled) return;
1501
- request.workScheduled = true;
1502
- queueMicrotask(() => {
1503
- request.workScheduled = false;
1504
- performWork(request);
1505
- });
1488
+ if (shouldSchedule) queueMicrotask(() => performWork(request));
1506
1489
  }
1507
- function finishedTask(request, task) {
1508
- request.pendingTasks -= 1;
1509
- const boundary = task.boundary;
1490
+ function settleTask(task, outcome, error) {
1491
+ const { boundary, request, segment, stack } = task.frame;
1510
1492
  if (boundary === null) {
1511
1493
  request.pendingRootTasks -= 1;
1512
- if (task.segment === request.rootSegment || request.completedRootSegment === null) request.completedRootSegment = request.rootSegment;
1494
+ if (outcome === "errored") {
1495
+ fatalError(request, error);
1496
+ return;
1497
+ }
1513
1498
  if (request.pendingRootTasks === 0) finishRootShell(request);
1514
1499
  } else {
1515
1500
  boundary.pendingTasks -= 1;
1516
- if (task.segment.parentFlushed) enqueueUnique(boundary.completedSegments, task.segment);
1517
- if (!completeBoundaryIfReady(request, boundary) && boundary.parentFlushed) request.partialBoundaries.add(boundary);
1518
- }
1519
- if (request.pendingTasks === 0) request.allReady.resolve(void 0);
1520
- }
1521
- function erroredTask(request, task, error) {
1522
- request.pendingTasks -= 1;
1523
- const boundary = task.boundary;
1524
- if (boundary === null) {
1525
- request.pendingRootTasks -= 1;
1526
- fatalError(request, error);
1527
- return;
1501
+ if (outcome === "errored") markBoundaryClientRendered(request, boundary, error, stack);
1502
+ else if (outcome === "completed" && segment.parentFlushed) boundary.completedSegments.push(segment);
1503
+ if (outcome !== "errored") {
1504
+ const boundaryCompleted = completeBoundaryIfReady(request, boundary);
1505
+ if (outcome === "completed" && !boundaryCompleted && boundary.parentFlushed) request.partialBoundaries.add(boundary);
1506
+ }
1528
1507
  }
1529
- boundary.pendingTasks -= 1;
1530
- markBoundaryClientRendered(request, boundary, error, task.stack);
1531
- if (request.pendingTasks === 0) request.allReady.resolve(void 0);
1508
+ if (request.abortableTasks.size === 0) request.allReady.resolve(void 0);
1532
1509
  }
1533
- function detachTask(request, task) {
1534
- task.abortSet.delete(task);
1535
- request.abortableTasks.delete(task);
1510
+ function detachTask(task) {
1511
+ task.frame.fallbackTasks?.delete(task);
1512
+ return task.frame.request.abortableTasks.delete(task);
1536
1513
  }
1537
- function abortTask(request, task) {
1538
- if (!request.abortableTasks.delete(task)) return;
1539
- task.segment.status = "completed";
1540
- task.abortSet.delete(task);
1541
- request.pendingTasks -= 1;
1542
- const boundary = task.boundary;
1543
- if (boundary === null) {
1544
- request.pendingRootTasks -= 1;
1545
- if (request.pendingRootTasks === 0) finishRootShell(request);
1546
- } else {
1547
- boundary.pendingTasks -= 1;
1548
- completeBoundaryIfReady(request, boundary);
1549
- }
1550
- if (request.pendingTasks === 0) request.allReady.resolve(void 0);
1514
+ function abortTask(task) {
1515
+ if (!detachTask(task)) return;
1516
+ const { frame } = task;
1517
+ frame.segment.status = "completed";
1518
+ settleTask(task, "aborted");
1551
1519
  }
1552
1520
  function completeBoundaryIfReady(request, boundary) {
1553
1521
  if (boundary.pendingTasks !== 0 || boundary.status !== "pending") return false;
1554
1522
  boundary.status = "completed";
1555
- abortFallbackTasks(request, boundary);
1523
+ for (const fallbackTask of boundary.fallbackTasks) abortTask(fallbackTask);
1556
1524
  if (boundary.parentFlushed) request.completedBoundaries.add(boundary);
1557
1525
  return true;
1558
1526
  }
1559
- function abortFallbackTasks(request, boundary) {
1560
- for (const fallbackTask of Array.from(boundary.fallbackAbortableTasks)) abortTask(request, fallbackTask);
1561
- }
1562
1527
  function markBoundaryClientRendered(request, boundary, error, stack, payload) {
1563
1528
  if (boundary.status !== "client-rendered") {
1564
1529
  boundary.status = "client-rendered";
1565
- boundary.error = payload ?? reportBoundaryError(request, error, stack);
1530
+ boundary.error = payload ?? serverErrorPayload(error, stackForError(error, stack), request.onError);
1566
1531
  }
1567
- boundary.completedSegments = [];
1532
+ boundary.completedSegments.length = 0;
1568
1533
  request.completedBoundaries.delete(boundary);
1569
1534
  request.partialBoundaries.delete(boundary);
1570
- for (const task of Array.from(request.abortableTasks)) if (task.boundary === boundary) abortTask(request, task);
1571
- for (const task of Array.from(boundary.fallbackAbortableTasks)) abortTask(request, task);
1535
+ for (const task of request.abortableTasks) if (task.frame.boundary === boundary) abortTask(task);
1536
+ for (const task of boundary.fallbackTasks) abortTask(task);
1572
1537
  if (boundary.parentFlushed) request.clientRenderedBoundaries.add(boundary);
1573
1538
  }
1574
1539
  function abort(request, reason) {
1575
1540
  if (request.status === "closed") return;
1576
- request.cleanupAbortListener();
1577
1541
  request.status = "aborting";
1578
- request.dataStore.dispose();
1579
1542
  const error = abortError(reason);
1580
- request.fatalError = error;
1543
+ request.abortReason = error;
1581
1544
  if (request.pendingRootTasks > 0) {
1582
1545
  fatalError(request, error);
1583
1546
  return;
1584
1547
  }
1585
- for (const task of Array.from(request.abortableTasks)) {
1586
- const boundary = task.boundary;
1587
- if (boundary !== null) markBoundaryClientRendered(request, boundary, error, task.stack, {});
1548
+ request.dispose();
1549
+ for (const task of request.abortableTasks) {
1550
+ const { boundary, stack } = task.frame;
1551
+ if (boundary !== null) markBoundaryClientRendered(request, boundary, error, stack, {});
1588
1552
  }
1589
1553
  request.abortableTasks.clear();
1590
- request.pendingTasks = 0;
1591
1554
  request.allReady.resolve(void 0);
1592
1555
  flushCompletedQueues(request);
1593
1556
  }
1594
1557
  function fatalError(request, error) {
1595
1558
  if (request.status === "closed") return;
1596
- request.cleanupAbortListener();
1597
1559
  request.status = "closed";
1598
- request.dataStore.dispose();
1599
- request.fatalError = error;
1560
+ request.dispose();
1600
1561
  request.headReady.reject(error);
1601
1562
  request.shellReady.reject(error);
1602
1563
  request.allReady.reject(error);
1603
1564
  request.controller?.error(error);
1604
1565
  }
1605
1566
  function finishRootShell(request) {
1606
- if (request.document !== null && !request.document.hasHead) {
1567
+ if (request.documentHasHead === false) {
1607
1568
  fatalError(request, invalidDocumentShellError());
1608
1569
  return;
1609
1570
  }
1610
1571
  if (!request.prerender) sealHead(request);
1611
1572
  request.shellReady.resolve(void 0);
1612
1573
  }
1613
- function enqueueUnique(queue, item) {
1614
- if (!queue.includes(item)) queue.push(item);
1615
- }
1616
- function reportBoundaryError(request, error, stack) {
1617
- const info = { componentStack: componentStack(stackForError(error, stack)) };
1618
- if (request.onError === void 0) return {};
1619
- try {
1620
- return request.onError(error, info) ?? {};
1621
- } catch {
1622
- return {};
1623
- }
1624
- }
1625
1574
  function recordErrorStack(error, stack) {
1626
1575
  if (stack === null) return;
1627
1576
  if (typeof error !== "object" && typeof error !== "function") return;
@@ -1635,29 +1584,14 @@ function stackForError(error, fallback) {
1635
1584
  function createRuntimeName(identifierPrefix) {
1636
1585
  const id = nextRuntimeId.toString(36);
1637
1586
  nextRuntimeId += 1;
1638
- const prefix = identifierPrefix?.replace(/[^A-Za-z0-9_$]/g, "_") ?? "";
1587
+ const prefix = identifierPrefix.replace(/[^A-Za-z0-9_$]/g, "_");
1639
1588
  return prefix === "" ? `__figSSR_${id}` : `__figSSR_${prefix}_${id}`;
1640
1589
  }
1641
- function writeDocumentHeadMarker(segment) {
1642
- segment.lastPushedText = false;
1643
- segment.chunks.push(documentHeadMarker);
1644
- }
1645
1590
  function consumePendingLeadingNewline(frame) {
1646
1591
  const pending = frame.pendingLeadingNewline;
1647
1592
  frame.pendingLeadingNewline = false;
1648
1593
  return pending;
1649
1594
  }
1650
- function leadingNewlineStrippedHost(type) {
1651
- return type === "pre" || type === "textarea";
1652
- }
1653
- function writeLeadingNewlineText(text, segment) {
1654
- writeText(text, { write(value) {
1655
- segment.write({ value });
1656
- } });
1657
- }
1658
- function preserveParserStrippedLeadingNewline(text) {
1659
- return text.startsWith("\n") ? `\n${text}` : text;
1660
- }
1661
1595
  function invalidDocumentShellError() {
1662
1596
  return /* @__PURE__ */ new Error("renderToDocumentStream requires the root to render an <html> document with a <head>.");
1663
1597
  }
@@ -1665,7 +1599,7 @@ function throwIfAborted(signal) {
1665
1599
  if (signal?.aborted === true) throw abortReason(signal.reason);
1666
1600
  }
1667
1601
  function throwIfAborting(request) {
1668
- if (request.status === "aborting") throw abortReason(request.fatalError);
1602
+ if (request.status === "aborting") throw abortReason(request.abortReason);
1669
1603
  }
1670
1604
  function abortError(reason) {
1671
1605
  if (reason instanceof Error) return reason;
@@ -1696,17 +1630,8 @@ function renderToStream(node, options = {}) {
1696
1630
  return createServerRenderRequest(node, options);
1697
1631
  }
1698
1632
  function renderToDocumentStream(node, options = {}) {
1699
- const request = createServerRenderRequest(node, options, { document: true });
1700
- return {
1701
- abort: (reason) => request.abort(reason),
1702
- allReady: request.allReady,
1703
- contentType: request.contentType,
1704
- data: request.data,
1705
- getData: () => request.getData(),
1706
- getPreloadHeader: (headerOptions) => request.getPreloadHeader(headerOptions),
1707
- shellReady: request.shellReady,
1708
- stream: request.stream
1709
- };
1633
+ const { getHead: _getHead, headReady: _headReady, ...result } = createServerRenderRequest(node, options, { document: true });
1634
+ return result;
1710
1635
  }
1711
1636
  /**
1712
1637
  * The streamed output, buffered: awaits `allReady` and concatenates exactly
@@ -1732,8 +1657,8 @@ async function renderToDocumentHtml(node, options = {}) {
1732
1657
  * Suspense content is emitted in logical position without streaming scripts.
1733
1658
  */
1734
1659
  async function prerender(node, options = {}) {
1735
- const { document = false, ...renderOptions } = options;
1736
- const result = createServerRenderRequest(node, renderOptions, {
1660
+ const document = options.document === true;
1661
+ const result = createServerRenderRequest(node, options, {
1737
1662
  document,
1738
1663
  prerender: true
1739
1664
  });