@bgub/fig-server 2.0.0 → 2.2.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.
@@ -1,7 +1,7 @@
1
1
  import { i as escapeText, n as escapeScriptJson, t as escapeAttribute } from "./escaping-2fHOwhEM.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-CXnAwZ0S.js";
2
+ import { a as componentStack, c as noLane, d as serverErrorPayload, f as streamFlowBlocked, i as cloneContextValues, l as nonceAttribute, m as withContextValue, n as suppressesImagePreloads, o as createStaticDispatcher, p as streamHighWaterMark, r as STREAMED_METADATA_ATTRIBUTE, s as deferred, t as imagePreloadFromHostProps, u as noop } from "./image-preloads-CztoSryT.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, assetResourceHostProps, assetResourceKey, attachDataStore, collectChildren, createRendererDataStore, invalidChildError, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPortal, isSuspense, isThenable, isViewTransition, readThenable, setCurrentDataStore, setCurrentDispatcher, validateInstanceNesting, validateTextNesting } from "@bgub/fig/internal";
4
+ import { ACTIVITY_TEMPLATE_ATTRIBUTE, EARLY_EVENT_HANDLER_PROPERTY, EARLY_EVENT_QUEUE_PROPERTY, HYDRATION_SKIP_ATTRIBUTE, REPLAYABLE_EVENT_TYPES, STREAMED_DATA_PROPERTY, SUSPENSE_BROWSER_MARKER, 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, decodePayloadDataEntries, encodePayloadDataEntries, invalidChildError, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPortal, isSuspense, isThenable, isViewTransition, normalizeDataResourceKey, readThenable, setCurrentDataStore, setCurrentDispatcher, validateInstanceNesting, validateTextNesting } from "@bgub/fig/internal";
5
5
  //#region src/html.ts
6
6
  const voidElements = /* @__PURE__ */ new Set([
7
7
  "area",
@@ -183,7 +183,7 @@ function snapshotPreloadHeaderResources(resources, isEarlyImage) {
183
183
  if (!isServerPreloadHeaderResource(resource)) continue;
184
184
  const snapshot = { ...resource };
185
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);
186
+ else if (resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || isEarlyImage?.(resource) === true))) criticalPreloads.push(snapshot);
187
187
  else if (resource.kind === "stylesheet") stylesheets.push(snapshot);
188
188
  else remaining.push(snapshot);
189
189
  }
@@ -233,13 +233,6 @@ function preloadHeaderValue(resource) {
233
233
  ["crossorigin", resource.crossorigin],
234
234
  ["fetchpriority", resource.fetchpriority]
235
235
  ]);
236
- case "font": return serializeLink(resource.href, [
237
- ["rel", "preload"],
238
- ["as", "font"],
239
- ["crossorigin", resource.crossorigin ?? "anonymous"],
240
- ["type", resource.type],
241
- ["fetchpriority", resource.fetchpriority]
242
- ]);
243
236
  case "preconnect": return serializeLink(resource.href, [["rel", "preconnect"], ["crossorigin", resource.crossorigin]]);
244
237
  }
245
238
  }
@@ -356,7 +349,7 @@ var AssetResourceRegistry = class {
356
349
  for (const resource of resources) {
357
350
  if (isMetadataResource(resource)) continue;
358
351
  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);
352
+ else if (resource.kind === "preload" && (resource.as === "font" || resource.as === "image" && (resource.fetchpriority === "high" || this.isEarlyImage(resource)))) criticalPreloads.push(resource);
360
353
  else if (resource.kind === "stylesheet") stylesheets.push(resource);
361
354
  else afterMetadata.push(resource);
362
355
  }
@@ -512,7 +505,6 @@ function assetSignature(resource) {
512
505
  return signature(resource.kind, imagesrcset === void 0 ? resource.href ?? "" : "", resource.as, resource.type ?? "", resource.crossorigin ?? "", resource.fetchpriority ?? "", imagesrcset ?? "", imagesrcset === void 0 ? "" : resource.imagesizes ?? "", resource.referrerpolicy ?? "");
513
506
  }
514
507
  case "modulepreload": return signature(resource.kind, resource.href, resource.crossorigin ?? "", resource.fetchpriority ?? "");
515
- case "font": return signature("preload", resource.href, "font", resource.type, resource.crossorigin ?? "anonymous", resource.fetchpriority ?? "", "", "", "");
516
508
  case "preconnect": return signature(resource.kind, resource.href, resource.crossorigin ?? "");
517
509
  case "script": return signature(resource.kind, resource.src, resource.module === true, resource.async !== false, resource.defer === true, resource.crossorigin ?? "");
518
510
  case "title": return signature(resource.kind, resource.value);
@@ -543,7 +535,7 @@ function signature(...values) {
543
535
  //#endregion
544
536
  //#region src/protocol.ts
545
537
  function buildServerRuntimeCode(runtimeName) {
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)}}`;
538
+ 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,()=>{if(!s.isConnected)return;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||!s.isConnected)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,a,r){this.y(document.getElementById(b),d,m,a,r)},y(b,d,m,a,r){for(let i of a||[])document.getElementById(i)?.remove();if(!b)return;let s=b.previousSibling;if(s&&s.nodeType===8){s.data=r?'${SUSPENSE_BROWSER_MARKER}':'${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,a,r){this.y(this.b(t,b),d,m,a,r)},d(p,r){((document.${STREAMED_DATA_PROPERTY}??={})[p]??=[]).push(r)}}`;
547
539
  }
548
540
  const RUNTIME_CODE_PREFIX = "globalThis[";
549
541
  const EMPTY_RUNTIME_REFERENCE = `${RUNTIME_CODE_PREFIX}${jsString("")}`;
@@ -613,6 +605,7 @@ function flushCompletedQueues(request) {
613
605
  sealHead(request);
614
606
  if (request.rootSegment.status !== "flushed") {
615
607
  flushSegment(request, request.rootSegment);
608
+ request.pendingDataKeys?.clear();
616
609
  flushWriteBuffer(request);
617
610
  }
618
611
  if (!drainBoundaryQueue(request, request.clientRenderedBoundaries, flushClientRenderedBoundary) && !drainBoundaryQueue(request, request.completedBoundaries, flushCompletedBoundary)) drainBoundaryQueue(request, request.partialBoundaries, flushPartialBoundary);
@@ -622,7 +615,12 @@ function flushCompletedQueues(request) {
622
615
  }
623
616
  if (request.abortableTasks.size === 0 && request.completedBoundaries.size === 0 && request.clientRenderedBoundaries.size === 0 && request.partialBoundaries.size === 0) {
624
617
  request.status = "closed";
625
- request.dispose();
618
+ try {
619
+ request.dispose();
620
+ } catch (error) {
621
+ request.controller.error(error);
622
+ return;
623
+ }
626
624
  request.controller.close();
627
625
  }
628
626
  }
@@ -653,6 +651,10 @@ function flushSubtree(request, segment) {
653
651
  }
654
652
  if (segment.status === "flushed") return;
655
653
  segment.status = "flushed";
654
+ if (segment.dataKeys !== null) {
655
+ for (const key of segment.dataKeys) request.pendingDataKeys?.add(key);
656
+ segment.dataKeys = null;
657
+ }
656
658
  if (request.documentHasHead === null || segment !== request.rootSegment) collectSegmentAssets(request, segment, null);
657
659
  let chunkIndex = 0;
658
660
  for (const child of segment.children) {
@@ -673,8 +675,9 @@ function flushSuspenseBoundary(request, segment, boundary) {
673
675
  segment.chunks.length = 0;
674
676
  return;
675
677
  }
676
- if (request.prerender && boundary.status === "client-rendered") {
677
- request.write(`<!--${SUSPENSE_CLIENT_MARKER}-->`);
678
+ if (request.prerender && (boundary.status === "browser-rendered" || boundary.status === "client-rendered")) {
679
+ const marker = boundary.status === "browser-rendered" ? SUSPENSE_BROWSER_MARKER : SUSPENSE_CLIENT_MARKER;
680
+ request.write(`<!--${marker}-->`);
678
681
  request.write(clientRenderedBoundaryPlaceholderMarkup(request, boundary));
679
682
  flushSubtree(request, segment);
680
683
  request.write(`<!--${SUSPENSE_END_MARKER}-->`);
@@ -686,7 +689,7 @@ function flushSuspenseBoundary(request, segment, boundary) {
686
689
  request.write(boundaryPlaceholderMarkup(request, boundaryIdValue));
687
690
  flushSubtree(request, segment);
688
691
  request.write(`<!--${SUSPENSE_END_MARKER}-->`);
689
- if (boundary.status === "client-rendered") request.clientRenderedBoundaries.add(boundary);
692
+ if (boundary.status === "browser-rendered" || boundary.status === "client-rendered") request.clientRenderedBoundaries.add(boundary);
690
693
  else if (boundary.completedSegments.length > 0) request.partialBoundaries.add(boundary);
691
694
  }
692
695
  function clientRenderedBoundaryPlaceholderMarkup(request, boundary) {
@@ -708,15 +711,18 @@ function flushBoundarySegment(request, boundary, segment) {
708
711
  let blockingIds = "";
709
712
  if (segment.status !== "flushed") {
710
713
  blockingIds = flushSegmentAssets(request, segment);
711
- request.write(segmentContainerStartMarkup(request, ensureSegmentId(request, segment)));
714
+ const id = ensureSegmentId(request, segment);
715
+ boundary.stagedSegmentIds.add(id);
716
+ request.write(segmentContainerStartMarkup(request, id));
712
717
  flushSegment(request, segment);
713
718
  request.write("</div>");
714
719
  }
715
- if (segment !== boundary.contentSegment) writeSegmentRevealScript(request, segment, blockingIds);
720
+ if (segment !== boundary.contentSegment) writeSegmentRevealScript(request, boundary, segment, blockingIds);
716
721
  }
717
- function writeSegmentRevealScript(request, segment, blockingIds) {
722
+ function writeSegmentRevealScript(request, boundary, segment, blockingIds) {
718
723
  const id = ensureSegmentId(request, segment);
719
724
  writeRuntime(request);
725
+ writeDataOperation(request, boundary);
720
726
  writeScript(request, withAssetGate(blockingIds, `${RUNTIME_REF}.s(${jsString(placeholderId(request, id))},${jsString(segmentId(request, id))})`));
721
727
  }
722
728
  function writeBoundaryRevealScript(request, boundary) {
@@ -724,9 +730,86 @@ function writeBoundaryRevealScript(request, boundary) {
724
730
  const metadata = switchBoundaryMetadata(request, boundary);
725
731
  const metadataArgument = metadata === null ? "" : `,${metadata}`;
726
732
  writeRuntime(request);
733
+ writeDataOperation(request, boundary);
727
734
  const boundaryRef = jsString(boundaryId(request, ensureBoundaryId(request, boundary)));
728
735
  const contentRef = jsString(segmentId(request, ensureSegmentId(request, boundary.contentSegment)));
729
736
  writeScript(request, withAssetGate(blockingIds, boundary.activityId === null ? `${RUNTIME_REF}.c(${boundaryRef},${contentRef}${metadataArgument})` : `${RUNTIME_REF}.ac(${jsString(boundary.activityId)},${boundaryRef},${contentRef}${metadataArgument})`));
737
+ writeLateDataOperations(request, boundary);
738
+ }
739
+ function takeData(request) {
740
+ return [...[...new Set(request.queuedDataRows.values())].flatMap((batch) => decodePayloadDataEntries(takeQueuedDataBatch(request, batch))), ...claimData(request, request.dataStore.snapshot())];
741
+ }
742
+ function claimData(request, entries) {
743
+ return entries.filter((entry) => {
744
+ const key = normalizeDataResourceKey(entry.key);
745
+ if (request.writtenDataKeys.has(key)) return false;
746
+ if (request.streamDataFilter?.(entry) === false) return false;
747
+ request.writtenDataKeys.add(key);
748
+ return true;
749
+ });
750
+ }
751
+ function unqueuedData(request, entries) {
752
+ return entries.filter((entry) => {
753
+ const key = normalizeDataResourceKey(entry.key);
754
+ if (request.writtenDataKeys.has(key)) return false;
755
+ if (request.queuedDataRows.has(key)) return false;
756
+ return request.streamDataFilter?.(entry) !== false;
757
+ });
758
+ }
759
+ function writeDataOperation(request, boundary) {
760
+ const pending = request.pendingDataKeys;
761
+ if (pending === null || pending.size === 0) return;
762
+ for (const key of pending) {
763
+ const batch = request.queuedDataRows.get(key);
764
+ if (batch !== void 0) writeDataRows(request, takeQueuedDataBatch(request, batch));
765
+ }
766
+ const dependencies = [];
767
+ const rows = encodeDataRows(claimData(request, request.dataStore.snapshotKeys(pending, dependencies)));
768
+ pending.clear();
769
+ for (const entry of dependencies) {
770
+ const batch = request.queuedDataRows.get(normalizeDataResourceKey(entry.key));
771
+ if (batch !== void 0 && !boundary.lateDataRows.includes(batch)) boundary.lateDataRows.push(batch);
772
+ }
773
+ const late = encodeDataRows(unqueuedData(request, dependencies));
774
+ if (late.length > 0) {
775
+ boundary.lateDataRows.push(late);
776
+ for (const row of late) request.queuedDataRows.set(normalizeDataResourceKey(row.key), late);
777
+ }
778
+ writeDataRows(request, [...late.map((row) => ({
779
+ key: row.key,
780
+ pending: true
781
+ })), ...rows]);
782
+ }
783
+ function writeLateDataOperations(request, boundary) {
784
+ const batches = boundary.lateDataRows;
785
+ boundary.lateDataRows = [];
786
+ for (const rows of batches) writeDataRows(request, takeQueuedDataBatch(request, rows));
787
+ }
788
+ function takeQueuedDataBatch(request, batch) {
789
+ const rows = batch.splice(0);
790
+ for (const row of rows) {
791
+ const key = normalizeDataResourceKey(row.key);
792
+ request.queuedDataRows.delete(key);
793
+ request.writtenDataKeys.add(key);
794
+ }
795
+ return rows;
796
+ }
797
+ function writeDataRows(request, rows) {
798
+ if (rows.length === 0) return;
799
+ writeScript(request, `${RUNTIME_REF}.d(${jsString(request.identifierPrefix)},${escapeScriptJson(rows)})`);
800
+ }
801
+ function encodeDataRows(entries) {
802
+ try {
803
+ return encodePayloadDataEntries(entries);
804
+ } catch {
805
+ return entries.flatMap((entry) => {
806
+ try {
807
+ return encodePayloadDataEntries([entry]);
808
+ } catch {
809
+ return [];
810
+ }
811
+ });
812
+ }
730
813
  }
731
814
  function switchBoundaryMetadata(request, boundary) {
732
815
  if (!boundary.metadataVisible) return null;
@@ -788,7 +871,13 @@ function flushClientRenderedBoundary(request, boundary) {
788
871
  const boundaryRef = jsString(boundaryId(request, boundary.id));
789
872
  const digest = jsString(boundary.error?.digest ?? "");
790
873
  const message = jsString(boundary.error?.message ?? "");
791
- writeScript(request, boundary.activityId === null ? `${RUNTIME_REF}.x(${boundaryRef},${digest},${message})` : `${RUNTIME_REF}.ax(${jsString(boundary.activityId)},${boundaryRef},${digest},${message})`);
874
+ const stagedIds = [...boundary.stagedSegmentIds].map((id) => segmentId(request, id));
875
+ const browser = boundary.status === "browser-rendered";
876
+ const cleanup = stagedIds.length === 0 && !browser ? "" : `,${escapeScriptJson(stagedIds)}${browser ? ",1" : ""}`;
877
+ const call = boundary.activityId === null ? `${RUNTIME_REF}.x(${boundaryRef},${digest},${message}${cleanup})` : `${RUNTIME_REF}.ax(${jsString(boundary.activityId)},${boundaryRef},${digest},${message}${cleanup})`;
878
+ boundary.stagedSegmentIds.clear();
879
+ writeScript(request, call);
880
+ writeLateDataOperations(request, boundary);
792
881
  }
793
882
  function drainBoundaryQueue(request, queue, flush) {
794
883
  for (;;) {
@@ -840,6 +929,7 @@ function ensureBoundaryId(request, boundary) {
840
929
  //#endregion
841
930
  //#region src/renderer.ts
842
931
  const errorStacks = /* @__PURE__ */ new WeakMap();
932
+ const browserBailoutBrand = Symbol("fig.browser-bailout");
843
933
  const TEXT_SEPARATOR = `<!--${TEXT_SEPARATOR_DATA}-->`;
844
934
  let nextRuntimeId = 0;
845
935
  function createServerRenderRequest(node, options, mode) {
@@ -854,7 +944,6 @@ function createServerRenderRequest(node, options, mode) {
854
944
  const rootSegment = createSegment(0);
855
945
  const dataStoreHost = {
856
946
  getLane: noLane,
857
- partition: options.dataPartition,
858
947
  schedule: noop
859
948
  };
860
949
  const dataStore = options.dataStore === void 0 ? createRendererDataStore(dataStoreHost) : attachDataStore(options.dataStore, dataStoreHost, options.initialData);
@@ -865,6 +954,10 @@ function createServerRenderRequest(node, options, mode) {
865
954
  completedBoundaries: /* @__PURE__ */ new Set(),
866
955
  controller: null,
867
956
  dataStore,
957
+ pendingDataKeys: mode?.prerender === true || options.streamData === false ? null : /* @__PURE__ */ new Set(),
958
+ streamDataFilter: typeof options.streamData === "object" ? options.streamData.filter ?? null : null,
959
+ writtenDataKeys: /* @__PURE__ */ new Set(),
960
+ queuedDataRows: /* @__PURE__ */ new Map(),
868
961
  dispose: disposeRequest,
869
962
  abortReason: null,
870
963
  identifierPrefix,
@@ -874,6 +967,7 @@ function createServerRenderRequest(node, options, mode) {
874
967
  nextActivityId: 0,
875
968
  nextViewTransitionId: 0,
876
969
  nonce: options.nonce,
970
+ onBrowserBailout: options.onBrowserBailout,
877
971
  onError: options.onError,
878
972
  pendingRootTasks: 0,
879
973
  pingedTasks: [],
@@ -948,6 +1042,7 @@ function createServerRenderRequest(node, options, mode) {
948
1042
  contentType: "text/html; charset=utf-8",
949
1043
  data: request.dataStore,
950
1044
  getData: () => request.dataStore.snapshot(),
1045
+ takeData: () => takeData(request),
951
1046
  getPreloadHeader: (headerOptions) => {
952
1047
  const snapshot = request.headSnapshot;
953
1048
  if (snapshot === null) return void 0;
@@ -1010,6 +1105,7 @@ function createSegment(index, boundary = null) {
1010
1105
  boundary,
1011
1106
  children: [],
1012
1107
  chunks: [],
1108
+ dataKeys: null,
1013
1109
  id: null,
1014
1110
  index,
1015
1111
  lastPushedText: false,
@@ -1059,17 +1155,18 @@ function createServerDispatcher(frame) {
1059
1155
  return createStaticDispatcher({
1060
1156
  contextValues: frame.contextValues,
1061
1157
  externalStoreError: "useSyncExternalStore requires getServerSnapshot during server render.",
1158
+ readBrowser(reason) {
1159
+ throw browserBailout(reason);
1160
+ },
1062
1161
  readPromise(promise) {
1063
1162
  throwIfAborting(frame.request);
1064
1163
  return readThenable(promise);
1065
1164
  },
1066
1165
  readData(resource, args) {
1067
1166
  throwIfAborting(frame.request);
1068
- return frame.request.dataStore.readData(resource, args);
1069
- },
1070
- preloadData(resource, args) {
1071
- throwIfAborting(frame.request);
1072
- frame.request.dataStore.preloadData(resource, ...args);
1167
+ const value = frame.request.dataStore.readData(resource, args);
1168
+ if (frame.request.pendingDataKeys !== null) (frame.segment.dataKeys ??= /* @__PURE__ */ new Set()).add(normalizeDataResourceKey(resource.key(...args)));
1169
+ return value;
1073
1170
  },
1074
1171
  useId() {
1075
1172
  frame.idPathString ??= formatIdPath(frame.idPath);
@@ -1317,6 +1414,8 @@ function renderSuspense(props, frame) {
1317
1414
  error: null,
1318
1415
  fallbackSegment: null,
1319
1416
  fallbackTasks: /* @__PURE__ */ new Set(),
1417
+ lateDataRows: [],
1418
+ stagedSegmentIds: /* @__PURE__ */ new Set(),
1320
1419
  id: null,
1321
1420
  metadataVisible: false,
1322
1421
  parentFlushed: false,
@@ -1337,7 +1436,7 @@ function renderSuspense(props, frame) {
1337
1436
  if (boundary.pendingTasks === 0) boundary.status = "completed";
1338
1437
  } catch (error) {
1339
1438
  contentSegment.status = "completed";
1340
- markBoundaryClientRendered(frame.request, boundary, error, frame.stack);
1439
+ markBoundaryForClientRender(frame.request, boundary, error, frame.stack);
1341
1440
  }
1342
1441
  advanceViewTransitionWatermark(frame, contentFrame);
1343
1442
  if (boundary.status === "completed") return;
@@ -1495,13 +1594,13 @@ function settleTask(task, outcome, error) {
1495
1594
  if (boundary === null) {
1496
1595
  request.pendingRootTasks -= 1;
1497
1596
  if (outcome === "errored") {
1498
- fatalError(request, error);
1597
+ fatalError(request, isBrowserBailout(error) ? browserBailoutError(error) : error);
1499
1598
  return;
1500
1599
  }
1501
1600
  if (request.pendingRootTasks === 0) finishRootShell(request);
1502
1601
  } else {
1503
1602
  boundary.pendingTasks -= 1;
1504
- if (outcome === "errored") markBoundaryClientRendered(request, boundary, error, stack);
1603
+ if (outcome === "errored") markBoundaryForClientRender(request, boundary, error, stack);
1505
1604
  else if (outcome === "completed" && segment.parentFlushed) boundary.completedSegments.push(segment);
1506
1605
  if (outcome !== "errored") {
1507
1606
  const boundaryCompleted = completeBoundaryIfReady(request, boundary);
@@ -1532,13 +1631,77 @@ function markBoundaryClientRendered(request, boundary, error, stack, payload) {
1532
1631
  boundary.status = "client-rendered";
1533
1632
  boundary.error = payload ?? serverErrorPayload(error, stackForError(error, stack), request.onError);
1534
1633
  }
1634
+ discardBoundaryServerWork(request, boundary);
1635
+ }
1636
+ function discardBoundaryServerWork(request, boundary) {
1535
1637
  boundary.completedSegments.length = 0;
1536
1638
  request.completedBoundaries.delete(boundary);
1537
1639
  request.partialBoundaries.delete(boundary);
1538
- for (const task of request.abortableTasks) if (task.frame.boundary === boundary) abortTask(task);
1539
- for (const task of boundary.fallbackTasks) abortTask(task);
1640
+ const discardedSegments = /* @__PURE__ */ new Set();
1641
+ discardSegmentTree(request, boundary.contentSegment, discardedSegments, boundary);
1642
+ for (const task of request.abortableTasks) if (discardedSegments.has(task.frame.segment)) abortTask(task);
1540
1643
  if (boundary.parentFlushed) request.clientRenderedBoundaries.add(boundary);
1541
1644
  }
1645
+ function markBoundaryBrowserRendered(request, boundary, bailout, stack) {
1646
+ if (boundary.status !== "browser-rendered") {
1647
+ boundary.status = "browser-rendered";
1648
+ boundary.error = null;
1649
+ reportBrowserBailout(request, bailout, stackForError(bailout, stack));
1650
+ }
1651
+ discardBoundaryServerWork(request, boundary);
1652
+ }
1653
+ function markBoundaryForClientRender(request, boundary, error, stack) {
1654
+ if (isBrowserBailout(error)) {
1655
+ markBoundaryBrowserRendered(request, boundary, error, stack);
1656
+ return;
1657
+ }
1658
+ markBoundaryClientRendered(request, boundary, error, stack);
1659
+ }
1660
+ function browserBailout(reason) {
1661
+ return reason === void 0 ? { [browserBailoutBrand]: true } : {
1662
+ [browserBailoutBrand]: true,
1663
+ reason
1664
+ };
1665
+ }
1666
+ function isBrowserBailout(value) {
1667
+ return typeof value === "object" && value !== null && browserBailoutBrand in value;
1668
+ }
1669
+ function browserBailoutError(bailout, message = "A component requires browser rendering, but it is not inside a Suspense boundary.") {
1670
+ let cause;
1671
+ try {
1672
+ cause = typeof bailout.reason === "function" ? bailout.reason() : bailout.reason;
1673
+ } catch (error) {
1674
+ cause = error;
1675
+ }
1676
+ const error = new Error(message);
1677
+ if (cause !== void 0) error.cause = cause;
1678
+ return error;
1679
+ }
1680
+ function reportBrowserBailout(request, bailout, stack) {
1681
+ const error = browserBailoutError(bailout, "The server left a Suspense boundary for browser rendering.");
1682
+ const report = request.onBrowserBailout;
1683
+ if (report === void 0) return;
1684
+ try {
1685
+ report(error, { componentStack: componentStack(stack) });
1686
+ } catch {}
1687
+ }
1688
+ function discardSegmentTree(request, segment, discarded, owner) {
1689
+ discarded.add(segment);
1690
+ const boundary = segment.boundary;
1691
+ if (boundary !== null) {
1692
+ boundary.status = "client-rendered";
1693
+ for (const id of boundary.stagedSegmentIds) owner.stagedSegmentIds.add(id);
1694
+ boundary.stagedSegmentIds.clear();
1695
+ owner.lateDataRows.push(...boundary.lateDataRows);
1696
+ boundary.lateDataRows = [];
1697
+ boundary.completedSegments.length = 0;
1698
+ request.completedBoundaries.delete(boundary);
1699
+ request.partialBoundaries.delete(boundary);
1700
+ request.clientRenderedBoundaries.delete(boundary);
1701
+ discardSegmentTree(request, boundary.contentSegment, discarded, owner);
1702
+ }
1703
+ for (const child of segment.children) discardSegmentTree(request, child, discarded, owner);
1704
+ }
1542
1705
  function abort(request, reason) {
1543
1706
  if (request.status === "closed") return;
1544
1707
  request.status = "aborting";
@@ -1548,7 +1711,12 @@ function abort(request, reason) {
1548
1711
  fatalError(request, error);
1549
1712
  return;
1550
1713
  }
1551
- request.dispose();
1714
+ try {
1715
+ request.dispose();
1716
+ } catch {
1717
+ fatalError(request, error);
1718
+ return;
1719
+ }
1552
1720
  for (const task of request.abortableTasks) {
1553
1721
  const { boundary, stack } = task.frame;
1554
1722
  if (boundary !== null) markBoundaryClientRendered(request, boundary, error, stack, {});
@@ -1560,7 +1728,9 @@ function abort(request, reason) {
1560
1728
  function fatalError(request, error) {
1561
1729
  if (request.status === "closed") return;
1562
1730
  request.status = "closed";
1563
- request.dispose();
1731
+ try {
1732
+ request.dispose();
1733
+ } catch {}
1564
1734
  request.headReady.reject(error);
1565
1735
  request.shellReady.reject(error);
1566
1736
  request.allReady.reject(error);