@bgub/fig-server 2.1.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.
package/dist/payload.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { c as noLane, d as serverErrorPayload, f as streamFlowBlocked, i as cloneContextValues, m as withContextValue, n as suppressesImagePreloads, o as createStaticDispatcher, p as streamHighWaterMark, s as deferred, t as imagePreloadFromHostProps, u as noop } from "./image-preloads-DwTY3DIk.js";
2
2
  import { Fragment, isValidElement } from "@bgub/fig";
3
- import { assetResourceDestination, assetResourceKey, checkpointPayloadGraph, clientOnlyHostBehavior, clientReferenceAssets, createPayloadGraphEncodeContext, createRendererDataStore, definePayloadGraphElement, describeInvalidChild, encodePayloadDataEntries, encodePayloadValueWithGraph, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPlainPayloadValue, isPortal, isSuspense, isThenable, isViewTransition, jsonPayloadCodec, readThenable, rollbackPayloadGraph, serializePayloadArray, serializePayloadMap, serializePayloadPlainObject, serializePayloadSet, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
3
+ import { assetResourceDestination, assetResourceKey, checkpointPayloadGraph, clientOnlyHostBehavior, clientReferenceAssets, createPayloadGraphEncodeContext, createRendererDataStore, definePayloadGraphElement, describeInvalidChild, encodePayloadDataEntries, encodePayloadValueWithGraph, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPlainPayloadValue, isPortal, isSuspense, isThenable, isViewTransition, jsonPayloadCodec, normalizeDataResourceKey, readThenable, rollbackPayloadGraph, serializePayloadArray, serializePayloadMap, serializePayloadPlainObject, serializePayloadSet, setCurrentDataStore, setCurrentDispatcher } from "@bgub/fig/internal";
4
4
  //#region src/payload-assets.ts
5
5
  /** Owns request-wide delivery-asset dedupe and wire lowering. */
6
6
  var PayloadAssets = class {
@@ -126,6 +126,7 @@ function renderToPayloadStream(node, options = {}) {
126
126
  nextUseId: 0,
127
127
  onError: options.onError,
128
128
  pendingDataSnapshots,
129
+ readDataKeys: /* @__PURE__ */ new Set(),
129
130
  pendingTasks: 0,
130
131
  pingedTasks: [],
131
132
  queuedRows: [],
@@ -233,21 +234,19 @@ function finishTask(request) {
233
234
  }
234
235
  function emitDataRows(request) {
235
236
  if (request.pendingDataSnapshots.size === 0) return;
236
- const entries = [];
237
+ const keys = [];
237
238
  for (const snapshot of request.pendingDataSnapshots.values()) {
238
239
  if (!snapshot.hasValue || snapshot.status === "refreshing") continue;
239
- const key = snapshot.canonicalKey;
240
- if (request.emittedDataKeys.has(key)) {
241
- request.pendingDataSnapshots.delete(snapshot.canonicalKey);
242
- continue;
243
- }
244
- request.emittedDataKeys.add(key);
245
- request.pendingDataSnapshots.delete(snapshot.canonicalKey);
246
- entries.push({
247
- key: snapshot.key,
248
- value: snapshot.value
249
- });
240
+ if (!request.readDataKeys.has(snapshot.canonicalKey)) continue;
241
+ keys.push(snapshot.canonicalKey);
250
242
  }
243
+ const entries = request.dataStore.snapshotKeys(keys).filter((entry) => {
244
+ const key = normalizeDataResourceKey(entry.key);
245
+ request.pendingDataSnapshots.delete(key);
246
+ if (request.emittedDataKeys.has(key)) return false;
247
+ request.emittedDataKeys.add(key);
248
+ return true;
249
+ });
251
250
  if (entries.length > 0) emitRow(request, {
252
251
  tag: "data",
253
252
  value: encodePayloadDataEntries(entries)
@@ -272,6 +271,7 @@ function createPayloadDispatcher(frame) {
272
271
  },
273
272
  readPromise: readThenable,
274
273
  readData(resource, args) {
274
+ frame.request.readDataKeys.add(normalizeDataResourceKey(resource.key(...args)));
275
275
  return frame.request.dataStore.readData(resource, args);
276
276
  },
277
277
  useId() {
@@ -537,7 +537,12 @@ function flushRows(request) {
537
537
  if (request.pendingTasks === 0 && request.queuedRows.length === 0) {
538
538
  request.closed = true;
539
539
  request.cleanupAbortListener?.();
540
- request.dataStore.dispose();
540
+ try {
541
+ request.dataStore.dispose();
542
+ } catch (error) {
543
+ request.controller.error(error);
544
+ return;
545
+ }
541
546
  request.controller.close();
542
547
  }
543
548
  }
@@ -545,7 +550,9 @@ function closeWithError(request, error) {
545
550
  if (request.closed) return;
546
551
  request.cleanupAbortListener?.();
547
552
  request.closed = true;
548
- request.dataStore.dispose();
553
+ try {
554
+ request.dataStore.dispose();
555
+ } catch {}
549
556
  request.allReady.reject(error);
550
557
  request.controller?.error(error);
551
558
  }
@@ -1 +1 @@
1
- {"version":3,"file":"payload.js","names":["invalidChildError"],"sources":["../src/payload-assets.ts","../src/payload.ts"],"sourcesContent":["import type {\n FigAssetResource,\n FigAssetResourceList,\n FigClientReference,\n} from \"@bgub/fig\";\nimport {\n assetResourceDestination,\n assetResourceKey,\n clientReferenceAssets,\n isFigAssetResource,\n type SerializedAssetResource,\n} from \"@bgub/fig/internal\";\n\ntype ResolveClientReferenceAssets = (metadata: {\n id: string;\n}) => FigAssetResourceList;\n\n/** Owns request-wide delivery-asset dedupe and wire lowering. */\nexport class PayloadAssets {\n private readonly emittedKeys = new Set<string>();\n\n constructor(\n private readonly resolveClientReference?: ResolveClientReferenceAssets,\n ) {}\n\n append(value: unknown, output: SerializedAssetResource[]): void {\n if (isFigAssetResource(value)) {\n this.appendResource(value, output);\n return;\n }\n if (!Array.isArray(value)) return;\n for (const resource of value) {\n if (isFigAssetResource(resource)) this.appendResource(resource, output);\n }\n }\n\n serializeClientReference(\n reference: FigClientReference,\n ): SerializedAssetResource[] {\n const declared = clientReferenceAssets(reference);\n const resolved = this.resolveClientReference?.({ id: reference.id });\n const serialized: SerializedAssetResource[] = [];\n this.append(declared, serialized);\n this.append(resolved, serialized);\n return serialized;\n }\n\n private appendResource(\n resource: FigAssetResource,\n output: SerializedAssetResource[],\n ): void {\n // Delivery assets are request-global and persistent, so the first\n // definition wins. Metadata remains owner-scoped and may repeat.\n if (assetResourceDestination(resource) === \"stream\") {\n const key = assetResourceKey(resource);\n if (this.emittedKeys.has(key)) return;\n this.emittedKeys.add(key);\n }\n output.push(serializeAssetResource(resource));\n }\n}\n\nfunction serializeAssetResource(\n resource: FigAssetResource,\n): SerializedAssetResource {\n // Delivery assets intentionally omit author-supplied `key` and dedupe by\n // concrete URL. JSON omits the optional fields that remain undefined.\n switch (resource.kind) {\n case \"stylesheet\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n media: resource.media,\n precedence: resource.precedence,\n };\n case \"preload\":\n return {\n as: resource.as,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n fetchpriority: resource.fetchpriority,\n href: resource.href,\n imagesizes: resource.imagesizes,\n imagesrcset: resource.imagesrcset,\n referrerpolicy: resource.referrerpolicy,\n type: resource.type,\n };\n case \"modulepreload\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n fetchpriority: resource.fetchpriority,\n };\n case \"script\":\n return {\n kind: resource.kind,\n src: resource.src,\n async: resource.async,\n crossorigin: resource.crossorigin,\n defer: resource.defer,\n module: resource.module,\n };\n case \"preconnect\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n };\n case \"title\":\n return { kind: resource.kind, value: resource.value };\n case \"meta\":\n return {\n kind: resource.kind,\n charset: resource.charset,\n content: resource.content,\n \"http-equiv\": resource[\"http-equiv\"],\n key: resource.key,\n name: resource.name,\n property: resource.property,\n };\n }\n}\n","/**\n * Server-side encoding APIs for Fig's server-component payload.\n *\n * @module\n */\nimport {\n type AwaitedFigNode,\n type FigAssetResourceList,\n type FigClientReference,\n type FigContext,\n type FigDataHydrationEntry,\n type FigElement,\n type FigNode,\n Fragment,\n isValidElement,\n type Props,\n} from \"@bgub/fig\";\nimport {\n checkpointPayloadGraph,\n clientOnlyHostBehavior,\n createRendererDataStore,\n createPayloadGraphEncodeContext,\n type DataStore,\n type DataStoreEntrySnapshot,\n definePayloadGraphElement,\n describeInvalidChild,\n encodePayloadDataEntries,\n encodePayloadValueWithGraph,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isPlainPayloadValue,\n isPortal,\n isSuspense,\n isThenable,\n isViewTransition,\n jsonPayloadCodec,\n type PayloadElementModel,\n type PayloadGraphEncodeContext,\n type PayloadModel,\n type PayloadRow,\n type PayloadSpecialModel,\n type RenderDispatcher,\n readThenable,\n rollbackPayloadGraph,\n serializePayloadArray,\n serializePayloadMap,\n serializePayloadPlainObject,\n serializePayloadSet,\n type SerializedAssetResource,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n} from \"@bgub/fig/internal\";\nimport { PayloadAssets } from \"./payload-assets.ts\";\nimport {\n type ContextValues,\n type StackFrame,\n cloneContextValues,\n createStaticDispatcher,\n type Deferred,\n deferred,\n noLane,\n noop,\n serverErrorPayload,\n streamFlowBlocked,\n streamHighWaterMark,\n withContextValue,\n} from \"./shared.ts\";\nimport {\n imagePreloadFromHostProps,\n suppressesImagePreloads,\n} from \"./image-preloads.ts\";\nimport type { ServerErrorInfo, ServerErrorPayload } from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\n/** Describes payload render result. */\nexport interface PayloadRenderResult {\n allReady: Promise<void>;\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n}\n\n/** Describes payload component. */\nexport type PayloadComponent = (\n props: Props & { children?: FigNode },\n) => FigNode;\n\n/** Describes payload render options. */\nexport interface PayloadRenderOptions {\n clientReferenceAssets?: (metadata: { id: string }) => FigAssetResourceList;\n componentAssets?: (\n type: PayloadComponent,\n ) => FigAssetResourceList | undefined;\n /**\n * Encoded bytes the result stream buffers before row flushing pauses until\n * the consumer reads (rendering itself never pauses; encoded rows wait\n * queued). Defaults to 65536; values below 1 are clamped to 1.\n */\n highWaterMark?: number;\n signal?: AbortSignal;\n /**\n * Decides what crosses the wire when a server render throws, mirroring the\n * HTML renderer's contract: the returned payload is authoritative. Without\n * a handler, development includes the error message and production sends\n * an empty payload.\n */\n onError?: (\n error: unknown,\n info: ServerErrorInfo,\n ) => ServerErrorPayload | undefined;\n}\n\nclass PayloadRequestCancelledError extends Error {\n constructor() {\n super(\"Payload request cancelled.\");\n this.name = \"PayloadRequestCancelledError\";\n }\n}\n\ntype PayloadRequest = {\n allReady: Deferred<void>;\n assets: PayloadAssets;\n cleanupAbortListener: (() => void) | null;\n clientReferenceRows: Map<string, number>;\n componentAssets: PayloadRenderOptions[\"componentAssets\"];\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: DataStore<object, null>;\n emittedDataKeys: Set<string>;\n graph: PayloadGraphEncodeContext;\n nextRowId: number;\n nextUseId: number;\n onError: PayloadRenderOptions[\"onError\"];\n pendingDataSnapshots: Map<string, DataStoreEntrySnapshot>;\n pendingTasks: number;\n pingedTasks: Task[];\n queuedRows: Uint8Array[];\n // Reentrancy guard: enqueueing inside flushRows can synchronously invoke\n // the stream's pull handler, which must not restart the drain — queuedRows\n // is spliced only after the loop, so a reentrant pass would re-enqueue the\n // same rows.\n flushingRows: boolean;\n closed: boolean;\n workScheduled: boolean;\n};\n\ntype Task = {\n contextValues: ContextValues;\n id: number;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n} & TaskValue;\n\ntype TaskValue =\n | { kind: \"node\"; value: FigNode }\n | { kind: \"node-promise\"; value: Thenable<AwaitedFigNode> }\n | { kind: \"promise\"; value: Thenable };\n\ntype Component = PayloadComponent;\n\ntype RenderFrame = {\n contextValues: ContextValues;\n // Built lazily on the first function component; reused for the whole task\n // (the dispatcher reads context through the frame, so it stays current).\n dispatcher: RenderDispatcher | null;\n // Assets discovered during this attempt whose owning row is not yet known.\n // Assets rows carry `for` — the row id whose reveal depends on them — and\n // the owner is only decided at scope exit: a subtree that completes keeps\n // its assets with the enclosing row, while one that suspends or fails takes\n // the assets discovered inside it to its outlined row. Scope exits happen\n // within the same synchronous attempt, so buffering costs no wire latency.\n pendingAssets: SerializedAssetResource[];\n request: PayloadRequest;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n};\n\nconst errorStacks = new WeakMap<object, StackFrame>();\ntype TreePropMode = \"children\" | \"suspense\" | null;\ntype OutlineKind = \"lazy\" | \"promise\";\ntype PayloadOutline = Extract<PayloadSpecialModel, { $fig: OutlineKind }>;\n\n/** Renders to payload stream. */\nexport function renderToPayloadStream(\n node: FigNode,\n options: PayloadRenderOptions = {},\n): PayloadRenderResult {\n throwIfAborted(options.signal);\n\n const pendingDataSnapshots = new Map<string, DataStoreEntrySnapshot>();\n const request: PayloadRequest = {\n allReady: deferred<void>(),\n assets: new PayloadAssets(options.clientReferenceAssets),\n cleanupAbortListener: null,\n clientReferenceRows: new Map(),\n componentAssets: options.componentAssets,\n controller: null,\n dataStore: createRendererDataStore<object, null>({\n getLane: noLane,\n onEntryChange: (entry: DataStoreEntrySnapshot) => {\n pendingDataSnapshots.set(entry.canonicalKey, entry);\n },\n schedule: noop,\n }),\n emittedDataKeys: new Set(),\n graph: createPayloadGraphEncodeContext(),\n nextRowId: 1,\n nextUseId: 0,\n onError: options.onError,\n pendingDataSnapshots,\n pendingTasks: 0,\n pingedTasks: [],\n queuedRows: [],\n flushingRows: false,\n closed: false,\n workScheduled: false,\n };\n // allReady also rejects through the stream when a consumer cancels (the\n // normal client-disconnect path); the pre-attached no-op handler keeps it\n // from becoming an unhandled rejection for callers that do not await it\n // (await-ers still observe the rejection).\n void request.allReady.promise.catch(noop);\n\n request.pingedTasks.push(\n createTask(\n request,\n 0,\n { kind: \"node\", value: node },\n new Map(),\n false,\n null,\n ),\n );\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(controller) {\n request.controller = controller;\n flushRows(request);\n },\n pull() {\n // The consumer drained below the high-water mark: resume flushing\n // rows that queued while the flow was blocked.\n flushRows(request);\n },\n cancel(reason) {\n abortPayloadRequest(request, reason);\n },\n },\n new ByteLengthQueuingStrategy({\n highWaterMark: streamHighWaterMark(options.highWaterMark),\n }),\n );\n\n const signal = options.signal;\n if (signal !== undefined) {\n const abortListener = () => abortPayloadRequest(request, signal.reason);\n signal.addEventListener(\"abort\", abortListener, { once: true });\n request.cleanupAbortListener = () => {\n signal.removeEventListener(\"abort\", abortListener);\n request.cleanupAbortListener = null;\n };\n }\n\n scheduleWork(request);\n\n return {\n allReady: request.allReady.promise,\n contentType: jsonPayloadCodec.contentType,\n stream,\n };\n}\n\nfunction createTask(\n request: PayloadRequest,\n id: number,\n value: TaskValue,\n contextValues: ContextValues,\n imagePreloadsSuppressed: boolean,\n stack: StackFrame | null,\n): Task {\n request.pendingTasks += 1;\n return { contextValues, id, imagePreloadsSuppressed, stack, ...value };\n}\n\nfunction performWork(request: PayloadRequest): void {\n if (request.closed) return;\n\n const tasks = request.pingedTasks;\n request.pingedTasks = [];\n\n for (const task of tasks) retryTask(request, task);\n\n flushRows(request);\n}\n\nfunction retryTask(request: PayloadRequest, task: Task): void {\n const frame: RenderFrame = {\n // Tasks already capture a context snapshot when outlined. Provider\n // mutation is balanced, so retries can use that snapshot directly.\n contextValues: task.contextValues,\n dispatcher: null,\n pendingAssets: [],\n request,\n imagePreloadsSuppressed: task.imagePreloadsSuppressed,\n stack: task.stack,\n };\n\n try {\n let value: PayloadModel;\n switch (task.kind) {\n case \"node\":\n value = serializeNode(task.value, frame);\n break;\n case \"node-promise\":\n value = serializeNode(readThenable(task.value), frame);\n break;\n case \"promise\":\n value = serializeValue(readThenable(task.value), frame);\n break;\n }\n flushFrameAssets(frame, task.id);\n emitDataRows(request);\n emitRow(request, { id: task.id, tag: \"model\", value });\n finishTask(request);\n } catch (error) {\n if (isThenable(error)) {\n // The retry re-discovers nothing already deduped by request.assets, so\n // this attempt's assets must ship now; the task still settles into id.\n flushFrameAssets(frame, task.id);\n const ping = () => pingTask(request, task);\n error.then(ping, ping);\n return;\n }\n\n flushFrameAssets(frame, task.id);\n emitRow(request, {\n id: task.id,\n tag: \"error\",\n value: errorRowPayload(request, error, task.stack),\n });\n finishTask(request);\n }\n}\n\nfunction finishTask(request: PayloadRequest): void {\n request.pendingTasks -= 1;\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction emitDataRows(request: PayloadRequest): void {\n if (request.pendingDataSnapshots.size === 0) return;\n const entries: FigDataHydrationEntry[] = [];\n\n for (const snapshot of request.pendingDataSnapshots.values()) {\n // Stream only settled values. A \"refreshing\" entry exposes a transient stale\n // value while its background refresh is in flight; emitting it would mark the\n // key emitted forever and permanently suppress the fresh value. Skipping it\n // lets the entry stream once its refresh settles.\n if (!snapshot.hasValue || snapshot.status === \"refreshing\") continue;\n\n const key = snapshot.canonicalKey;\n if (request.emittedDataKeys.has(key)) {\n request.pendingDataSnapshots.delete(snapshot.canonicalKey);\n continue;\n }\n\n request.emittedDataKeys.add(key);\n request.pendingDataSnapshots.delete(snapshot.canonicalKey);\n entries.push({ key: snapshot.key, value: snapshot.value });\n }\n\n if (entries.length > 0) {\n emitRow(request, { tag: \"data\", value: encodePayloadDataEntries(entries) });\n }\n}\n\nfunction flushFrameAssets(frame: RenderFrame, rowId: number): void {\n if (frame.pendingAssets.length === 0) return;\n const value = frame.pendingAssets;\n frame.pendingAssets = [];\n emitRow(frame.request, { for: rowId, tag: \"assets\", value });\n}\n\nfunction createPayloadDispatcher(frame: RenderFrame): RenderDispatcher {\n const dispatcher = createStaticDispatcher({\n contextValues: frame.contextValues,\n externalStoreError:\n \"useSyncExternalStore requires getServerSnapshot during payload render.\",\n readBrowser() {\n throw new Error(\n \"readBrowser cannot be used during payload render: serialized components do not run in the browser. Move browser-only behavior into a client reference.\",\n );\n },\n readPromise: readThenable,\n readData(resource, args) {\n return frame.request.dataStore.readData(resource, args);\n },\n useId() {\n const id = `fig-pl-${frame.request.nextUseId.toString(32)}`;\n frame.request.nextUseId += 1;\n return id;\n },\n updateError: \"State updates are not allowed during payload render.\",\n });\n\n // Serialized components are render-only: they never re-run on the client,\n // so state, effects, and interactivity are meaningless there — dev throws\n // at first use instead of silently freezing initial state into the wire.\n // Reads stay server-safe: readContext/readData/readPromise,\n // useMemo, useId, and useSyncExternalStore's getServerSnapshot path (a\n // read, not a subscription — the static dispatcher already requires it).\n if (__DEV__) {\n const throwClientApi = (hook: string) => (): never => {\n throw new Error(\n `${hook} cannot be used during payload render: serialized components are render-only. Move state, effects, and interactivity into a client reference.`,\n );\n };\n dispatcher.useState = throwClientApi(\"useState\");\n dispatcher.useActionState = throwClientApi(\"useActionState\");\n dispatcher.useTransition = throwClientApi(\"useTransition\");\n dispatcher.useStableEvent = throwClientApi(\"useStableEvent\");\n dispatcher.useReactive = throwClientApi(\"useReactive\");\n dispatcher.useBeforePaint = throwClientApi(\"useBeforePaint\");\n dispatcher.useBeforeLayout = throwClientApi(\"useBeforeLayout\");\n }\n\n return dispatcher;\n}\n\nfunction serializeNode(node: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(node)) {\n return serializeTreeArray(node, frame);\n }\n\n if (node === null || node === undefined || typeof node === \"boolean\") {\n return node === undefined ? { $fig: \"undefined\" } : node;\n }\n\n if (typeof node === \"string\" || typeof node === \"number\") {\n return node;\n }\n\n if (isPortal(node)) return null;\n if (isValidElement(node)) return serializeElement(node, frame, false);\n if (isThenable(node)) {\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: node },\n \"promise\",\n node,\n );\n }\n\n throw invalidChildError(node);\n}\n\nfunction serializeNodeOrLazy(\n node: FigNode,\n frame: RenderFrame,\n preserveElementIdentity = false,\n): PayloadModel {\n const graphCheckpoint = checkpointPayloadGraph(frame.request.graph);\n const assetCheckpoint = frame.pendingAssets.length;\n try {\n if (!isValidElement(node)) return serializeNode(node, frame);\n return serializeElement(node, frame, preserveElementIdentity);\n } catch (error) {\n rollbackPayloadGraph(frame.request.graph, graphCheckpoint);\n // Assets discovered inside this subtree belong to the outlined row, not\n // the enclosing one: gating the enclosing row would hold the whole tree's\n // reveal on stylesheets only the hole's content needs.\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n if (isThenable(error)) {\n return outlineTask(\n frame,\n { kind: \"node\", value: node },\n \"lazy\",\n error,\n scopedAssets,\n );\n }\n return outlineError(frame, error, \"lazy\", scopedAssets);\n }\n}\n\nfunction serializeElement(\n element: FigElement,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const type = element.type;\n\n if (typeof type === \"string\") {\n return serializeHostElement(element, type, frame, preserveIdentity);\n }\n\n if (type === Fragment) {\n return serializeElementModel(\n element,\n { $fig: \"fragment\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (isClientReference(type)) {\n const clientId = emitClientReference(frame.request, type);\n return serializeElementModel(\n element,\n { $fig: \"client\", id: clientId },\n frame,\n preserveIdentity,\n );\n }\n\n if (isContext(type)) {\n return serializeContextProvider(type, element.props, frame);\n }\n\n if (isAssets(type)) {\n return serializeAssets(element.props, frame);\n }\n\n if (isSuspense(type)) {\n return serializeElementModel(\n element,\n { $fig: \"suspense\" },\n frame,\n preserveIdentity,\n \"suspense\",\n );\n }\n\n if (isErrorBoundary(type)) {\n return serializeNode(element.props.children, frame);\n }\n\n if (isActivity(type)) {\n return serializeElementModel(\n element,\n { $fig: \"activity\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (isViewTransition(type)) {\n return serializeElementModel(\n element,\n { $fig: \"view-transition\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (typeof type === \"function\") {\n return serializeFunctionComponent(type, element.props, frame);\n }\n\n throw new Error(\"Unsupported Fig element type during payload render.\");\n}\n\nfunction serializeHostElement(\n element: FigElement,\n type: string,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const preload = imagePreloadFromHostProps(\n type,\n element.props,\n frame.imagePreloadsSuppressed,\n );\n if (preload !== null) {\n frame.request.assets.append(preload, frame.pendingAssets);\n }\n\n const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;\n frame.imagePreloadsSuppressed =\n previousImagePreloadsSuppressed || suppressesImagePreloads(type);\n try {\n return serializeElementModel(\n element,\n type,\n frame,\n preserveIdentity,\n \"children\",\n );\n } finally {\n frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;\n }\n}\n\nfunction serializeElementModel(\n element: FigElement,\n type: PayloadElementModel[\"type\"],\n frame: RenderFrame,\n preserveIdentity: boolean,\n treeProps: TreePropMode = null,\n): PayloadModel {\n const id = preserveIdentity\n ? definePayloadGraphElement(frame.request.graph, element)\n : undefined;\n if (typeof id === \"object\") return id;\n const model: PayloadElementModel = {\n $fig: \"element\",\n key: element.key,\n props: serializeProps(\n element.props,\n frame,\n treeProps,\n typeof type === \"string\",\n ),\n type,\n };\n if (id !== undefined) model.id = id;\n return model;\n}\n\nfunction serializeFunctionComponent(\n type: Component,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n const assetCheckpoint = frame.pendingAssets.length;\n frame.request.assets.append(\n frame.request.componentAssets?.(type),\n frame.pendingAssets,\n );\n frame.dispatcher ??= createPayloadDispatcher(frame);\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n if (__DEV__ || frame.request.onError !== undefined) {\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n }\n\n try {\n if (\n __DEV__ &&\n \"$$typeof\" in type &&\n type.$$typeof === Symbol.for(\"fig.data-resource\")\n ) {\n throw new Error(\n \"Payload components cannot be rendered inside Payload. Render the underlying server component directly, or mount separate Payload components from the client tree.\",\n );\n }\n const result = type(props);\n if (isThenable(result)) {\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: result },\n \"promise\",\n result,\n scopedAssets,\n );\n }\n return serializeNode(result, frame);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n } finally {\n frame.stack = previousStack;\n setCurrentDataStore(previousDataStore);\n setCurrentDispatcher(previousDispatcher);\n }\n}\n\nfunction serializeContextProvider(\n context: FigContext<unknown>,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n return withContextValue(frame.contextValues, context, props.value, () =>\n serializeNode(props.children, frame),\n );\n}\n\nfunction serializeAssets(props: Props, frame: RenderFrame): PayloadModel {\n // Buffered, not emitted: the owning row id is decided at scope exit (see\n // RenderFrame.pendingAssets). Dedupe happens here, so a retried subtree\n // does not re-buffer assets an earlier attempt already shipped.\n frame.request.assets.append(props.assets, frame.pendingAssets);\n return serializeNode(props.children, frame);\n}\n\nfunction serializeProps(\n props: Props,\n frame: RenderFrame,\n treeProps: TreePropMode,\n hostElement = false,\n): PayloadModel {\n const clientOnlyBehavior = hostElement\n ? clientOnlyHostBehavior(props)\n : undefined;\n if (clientOnlyBehavior !== undefined) {\n throw new Error(\n `Client-only host behavior from ${clientOnlyBehavior} cannot be ` +\n \"serialized in a payload; move it into a client reference.\",\n );\n }\n\n const value: Record<string, PayloadModel> = {};\n for (const name of Object.keys(props)) {\n // A host `mix` already resolved into these props at element creation;\n // the marker itself holds descriptors (functions) and stays server-side.\n // Component `mix` props still serialize (and fail loudly on functions).\n if (hostElement && name === \"mix\") continue;\n const child = props[name];\n const isTreeProp =\n treeProps !== null &&\n (name === \"children\" ||\n (treeProps === \"suspense\" && name === \"fallback\"));\n value[name] = isTreeProp\n ? serializeTreeProp(child, frame)\n : serializeValue(child, frame);\n }\n return {\n $fig: \"object\",\n value,\n };\n}\n\nfunction serializeTreeProp(value: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(value)) return serializeTreeArray(value, frame);\n return serializeNodeOrLazy(value, frame);\n}\n\nfunction serializeTreeArray(\n value: FigNode[],\n frame: RenderFrame,\n): PayloadModel[] {\n // Array.map preserves sparse root slots, which encode as null on the wire.\n // Once nested arrays are flattened, iteration intentionally makes holes\n // explicit undefined children, matching the existing flattening semantics.\n if (!value.some(Array.isArray)) {\n return value.map((child) => serializeNodeOrLazy(child, frame));\n }\n const serialized: PayloadModel[] = [];\n appendTreeArray(value, frame, serialized);\n return serialized;\n}\n\n// Payload flattens nested child arrays without dropping empty children or\n// merging text; the client performs normal child collection after decoding.\nfunction appendTreeArray(\n children: FigNode[],\n frame: RenderFrame,\n output: PayloadModel[],\n): void {\n for (const child of children) {\n if (Array.isArray(child)) appendTreeArray(child, frame, output);\n else output.push(serializeNodeOrLazy(child, frame));\n }\n}\n\nfunction serializeValue(value: unknown, frame: RenderFrame): PayloadModel {\n // Scalar values return from the shared encoder before any graph access, so\n // reusing the request graph here is free (no per-value context allocation).\n if (isPlainPayloadValue(value)) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n\n if (isClientReference(value)) {\n return { $fig: \"client\", id: emitClientReference(frame.request, value) };\n }\n\n if (isValidElement(value)) return serializeNodeOrLazy(value, frame, true);\n if (isPortal(value)) return null;\n if (isThenable(value)) {\n return outlineTask(frame, { kind: \"promise\", value }, \"promise\", value);\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be passed to client references.\");\n }\n\n if (typeof value === \"object\" && value !== null) {\n if (value instanceof Date) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n if (value instanceof Map) {\n return serializePayloadMap(value, frame.request.graph, ([key, item]) => [\n serializeValue(key, frame),\n serializeValue(item, frame),\n ]);\n }\n if (value instanceof Set) {\n return serializePayloadSet(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n if (Array.isArray(value)) {\n return serializePayloadArray(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n return serializePayloadPlainObject(value, frame.request.graph, (child) =>\n serializeValue(child, frame),\n );\n }\n\n throw new Error(`Cannot serialize ${typeof value} into the payload.`);\n}\nfunction outlineTask(\n frame: RenderFrame,\n value: TaskValue,\n referenceKind: OutlineKind,\n wakeable: Thenable,\n scopedAssets: SerializedAssetResource[] = [],\n): PayloadSpecialModel {\n const request = frame.request;\n const outline = createOutline(request, referenceKind, scopedAssets);\n const task = createTask(\n request,\n outline.id,\n value,\n cloneContextValues(frame.contextValues),\n frame.imagePreloadsSuppressed,\n stackForError(wakeable, frame.stack),\n );\n\n const ping = () => pingTask(request, task);\n wakeable.then(ping, ping);\n\n return outline;\n}\n\nfunction outlineError(\n frame: RenderFrame,\n error: unknown,\n referenceKind: OutlineKind,\n scopedAssets: SerializedAssetResource[],\n): PayloadSpecialModel {\n const request = frame.request;\n const outline = createOutline(request, referenceKind, scopedAssets);\n // Assets first so a decoder that drops gates on error rows sees the row\n // order it expects; the assets still preload even though the row failed.\n emitRow(request, {\n id: outline.id,\n tag: \"error\",\n value: errorRowPayload(request, error, frame.stack),\n });\n return outline;\n}\n\nfunction createOutline(\n request: PayloadRequest,\n kind: OutlineKind,\n assets: SerializedAssetResource[],\n): PayloadOutline {\n const outline: PayloadOutline = {\n $fig: kind,\n id: request.nextRowId++,\n };\n if (assets.length > 0) {\n emitRow(request, { for: outline.id, tag: \"assets\", value: assets });\n }\n return outline;\n}\n\n// The onError return value is authoritative, like the HTML renderer's\n// reportBoundaryError: message crosses the wire only when the handler says\n// so. Without a handler, development keeps the real message for debugging\n// (payload errors never re-execute on the client, so the wire is the only\n// surface) and production sends an empty payload.\nfunction errorRowPayload(\n request: PayloadRequest,\n error: unknown,\n stack: StackFrame | null,\n): ServerErrorPayload {\n return serverErrorPayload(\n error,\n stackForError(error, stack),\n request.onError,\n );\n}\n\nfunction recordErrorStack(error: unknown, stack: StackFrame | null): void {\n if (stack === null) return;\n if (typeof error !== \"object\" || error === null) return;\n if (!errorStacks.has(error)) errorStacks.set(error, stack);\n}\n\nfunction stackForError(\n error: unknown,\n fallback: StackFrame | null,\n): StackFrame | null {\n if (typeof error !== \"object\" || error === null) return fallback;\n return errorStacks.get(error) ?? fallback;\n}\n\nfunction clientReferenceExportName(id: string): string | undefined {\n const hashIndex = id.lastIndexOf(\"#\");\n if (hashIndex === -1) return undefined;\n return id.slice(hashIndex + 1) || undefined;\n}\n\nfunction emitClientReference(\n request: PayloadRequest,\n reference: FigClientReference,\n): number {\n const existing = request.clientReferenceRows.get(reference.id);\n if (existing !== undefined) return existing;\n\n // Resolve assets BEFORE reserving the row id and recording the mapping. A lazy\n // resource thunk (bundler-manifest resolution) may throw; reserving first would\n // leave a row id mapped but never emitted, so a later retry returns the cached\n // id and the client suspends on a chunk that never arrives. Resolving first\n // lets the throw propagate as an ordinary serialization error with no poisoned\n // mapping, so the reference can be retried cleanly.\n const assets = request.assets.serializeClientReference(reference);\n const value: Extract<PayloadRow, { tag: \"client\" }>[\"value\"] = {\n id: reference.id,\n };\n if (assets.length > 0) value.assets = assets;\n // The \"<module>#<export>\" authoring convention is split here, once, so the\n // wire is self-describing and the client never string-parses ids.\n const exportName = clientReferenceExportName(reference.id);\n if (exportName !== undefined) value.exportName = exportName;\n if (reference.ssr !== undefined) value.ssr = true;\n const id = request.nextRowId++;\n request.clientReferenceRows.set(reference.id, id);\n emitRow(request, {\n id,\n tag: \"client\",\n value,\n });\n return id;\n}\n\nfunction emitRow(request: PayloadRequest, row: PayloadRow): void {\n request.queuedRows.push(jsonPayloadCodec.encodeRow(row));\n flushRows(request);\n}\n\nfunction pingTask(request: PayloadRequest, task: Task): void {\n if (request.closed) return;\n request.pingedTasks.push(task);\n scheduleWork(request);\n}\n\nfunction scheduleWork(request: PayloadRequest): void {\n // Many thenables settling in one tick ping many tasks; one performWork\n // pass drains them all, so schedule at most one.\n if (request.workScheduled) return;\n request.workScheduled = true;\n queueMicrotask(() => {\n request.workScheduled = false;\n performWork(request);\n });\n}\n\nfunction flushRows(request: PayloadRequest): void {\n if (request.controller === null || request.closed) return;\n if (request.flushingRows) return;\n\n request.flushingRows = true;\n try {\n // Row-granular gating: rows already encode one complete wire row each,\n // so stopping between rows keeps every chunk parse-safe for consumers\n // that interleave per chunk.\n let flushed = 0;\n while (\n flushed < request.queuedRows.length &&\n !streamFlowBlocked(request.controller)\n ) {\n request.controller.enqueue(request.queuedRows[flushed]);\n flushed += 1;\n }\n if (flushed === request.queuedRows.length) request.queuedRows.length = 0;\n else if (flushed > 0) {\n request.queuedRows = request.queuedRows.slice(flushed);\n }\n } finally {\n request.flushingRows = false;\n }\n\n // Deliberately not conditioned on flow: close() only marks the end of the\n // queue, so a full queue with no rows left to write still closes here.\n if (request.pendingTasks === 0 && request.queuedRows.length === 0) {\n request.closed = true;\n request.cleanupAbortListener?.();\n request.dataStore.dispose();\n request.controller.close();\n }\n}\n\nfunction closeWithError(request: PayloadRequest, error: unknown): void {\n if (request.closed) return;\n request.cleanupAbortListener?.();\n request.closed = true;\n request.dataStore.dispose();\n request.allReady.reject(error);\n request.controller?.error(error);\n}\n\nfunction abortPayloadRequest(request: PayloadRequest, reason?: unknown): void {\n closeWithError(request, reason ?? new PayloadRequestCancelledError());\n}\n\nfunction invalidChildError(value: unknown): Error {\n return new Error(\n `Invalid Fig child in payload render: ${describeInvalidChild(value)}.`,\n );\n}\n\nfunction throwIfAborted(signal?: AbortSignal | null): void {\n if (signal?.aborted) throw new PayloadRequestCancelledError();\n}\n"],"mappings":";;;;;AAkBA,IAAa,gBAAb,MAA2B;CAIN;CAHnB,8BAA+B,IAAI,IAAY;CAE/C,YACE,wBACA;EADiB,KAAA,yBAAA;CAChB;CAEH,OAAO,OAAgB,QAAyC;EAC9D,IAAI,mBAAmB,KAAK,GAAG;GAC7B,KAAK,eAAe,OAAO,MAAM;GACjC;EACF;EACA,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG;EAC3B,KAAK,MAAM,YAAY,OACrB,IAAI,mBAAmB,QAAQ,GAAG,KAAK,eAAe,UAAU,MAAM;CAE1E;CAEA,yBACE,WAC2B;EAC3B,MAAM,WAAW,sBAAsB,SAAS;EAChD,MAAM,WAAW,KAAK,yBAAyB,EAAE,IAAI,UAAU,GAAG,CAAC;EACnE,MAAM,aAAwC,CAAC;EAC/C,KAAK,OAAO,UAAU,UAAU;EAChC,KAAK,OAAO,UAAU,UAAU;EAChC,OAAO;CACT;CAEA,eACE,UACA,QACM;EAGN,IAAI,yBAAyB,QAAQ,MAAM,UAAU;GACnD,MAAM,MAAM,iBAAiB,QAAQ;GACrC,IAAI,KAAK,YAAY,IAAI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AAK,EAAE,EACtE;AACF;AAEA,SAAS,eAAe,QAAmC;CACzD,IAAI,QAAQ,SAAS,MAAM,IAAI,6BAA6B;AAC9D"}
1
+ {"version":3,"file":"payload.js","names":["invalidChildError"],"sources":["../src/payload-assets.ts","../src/payload.ts"],"sourcesContent":["import type {\n FigAssetResource,\n FigAssetResourceList,\n FigClientReference,\n} from \"@bgub/fig\";\nimport {\n assetResourceDestination,\n assetResourceKey,\n clientReferenceAssets,\n isFigAssetResource,\n type SerializedAssetResource,\n} from \"@bgub/fig/internal\";\n\ntype ResolveClientReferenceAssets = (metadata: {\n id: string;\n}) => FigAssetResourceList;\n\n/** Owns request-wide delivery-asset dedupe and wire lowering. */\nexport class PayloadAssets {\n private readonly emittedKeys = new Set<string>();\n\n constructor(\n private readonly resolveClientReference?: ResolveClientReferenceAssets,\n ) {}\n\n append(value: unknown, output: SerializedAssetResource[]): void {\n if (isFigAssetResource(value)) {\n this.appendResource(value, output);\n return;\n }\n if (!Array.isArray(value)) return;\n for (const resource of value) {\n if (isFigAssetResource(resource)) this.appendResource(resource, output);\n }\n }\n\n serializeClientReference(\n reference: FigClientReference,\n ): SerializedAssetResource[] {\n const declared = clientReferenceAssets(reference);\n const resolved = this.resolveClientReference?.({ id: reference.id });\n const serialized: SerializedAssetResource[] = [];\n this.append(declared, serialized);\n this.append(resolved, serialized);\n return serialized;\n }\n\n private appendResource(\n resource: FigAssetResource,\n output: SerializedAssetResource[],\n ): void {\n // Delivery assets are request-global and persistent, so the first\n // definition wins. Metadata remains owner-scoped and may repeat.\n if (assetResourceDestination(resource) === \"stream\") {\n const key = assetResourceKey(resource);\n if (this.emittedKeys.has(key)) return;\n this.emittedKeys.add(key);\n }\n output.push(serializeAssetResource(resource));\n }\n}\n\nfunction serializeAssetResource(\n resource: FigAssetResource,\n): SerializedAssetResource {\n // Delivery assets intentionally omit author-supplied `key` and dedupe by\n // concrete URL. JSON omits the optional fields that remain undefined.\n switch (resource.kind) {\n case \"stylesheet\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n media: resource.media,\n precedence: resource.precedence,\n };\n case \"preload\":\n return {\n as: resource.as,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n fetchpriority: resource.fetchpriority,\n href: resource.href,\n imagesizes: resource.imagesizes,\n imagesrcset: resource.imagesrcset,\n referrerpolicy: resource.referrerpolicy,\n type: resource.type,\n };\n case \"modulepreload\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n fetchpriority: resource.fetchpriority,\n };\n case \"script\":\n return {\n kind: resource.kind,\n src: resource.src,\n async: resource.async,\n crossorigin: resource.crossorigin,\n defer: resource.defer,\n module: resource.module,\n };\n case \"preconnect\":\n return {\n href: resource.href,\n kind: resource.kind,\n crossorigin: resource.crossorigin,\n };\n case \"title\":\n return { kind: resource.kind, value: resource.value };\n case \"meta\":\n return {\n kind: resource.kind,\n charset: resource.charset,\n content: resource.content,\n \"http-equiv\": resource[\"http-equiv\"],\n key: resource.key,\n name: resource.name,\n property: resource.property,\n };\n }\n}\n","/**\n * Server-side encoding APIs for Fig's server-component payload.\n *\n * @module\n */\nimport {\n type AwaitedFigNode,\n type FigAssetResourceList,\n type FigClientReference,\n type FigContext,\n type FigElement,\n type FigNode,\n Fragment,\n isValidElement,\n type Props,\n} from \"@bgub/fig\";\nimport {\n checkpointPayloadGraph,\n clientOnlyHostBehavior,\n createRendererDataStore,\n createPayloadGraphEncodeContext,\n type DataStore,\n type DataStoreEntrySnapshot,\n definePayloadGraphElement,\n describeInvalidChild,\n encodePayloadDataEntries,\n encodePayloadValueWithGraph,\n isActivity,\n isAssets,\n isClientReference,\n isContext,\n isErrorBoundary,\n isPlainPayloadValue,\n isPortal,\n isSuspense,\n isThenable,\n isViewTransition,\n jsonPayloadCodec,\n normalizeDataResourceKey,\n type PayloadElementModel,\n type PayloadGraphEncodeContext,\n type PayloadModel,\n type PayloadRow,\n type PayloadSpecialModel,\n type RenderDispatcher,\n readThenable,\n rollbackPayloadGraph,\n serializePayloadArray,\n serializePayloadMap,\n serializePayloadPlainObject,\n serializePayloadSet,\n type SerializedAssetResource,\n setCurrentDataStore,\n setCurrentDispatcher,\n type Thenable,\n} from \"@bgub/fig/internal\";\nimport { PayloadAssets } from \"./payload-assets.ts\";\nimport {\n type ContextValues,\n type StackFrame,\n cloneContextValues,\n createStaticDispatcher,\n type Deferred,\n deferred,\n noLane,\n noop,\n serverErrorPayload,\n streamFlowBlocked,\n streamHighWaterMark,\n withContextValue,\n} from \"./shared.ts\";\nimport {\n imagePreloadFromHostProps,\n suppressesImagePreloads,\n} from \"./image-preloads.ts\";\nimport type { ServerErrorInfo, ServerErrorPayload } from \"./types.ts\";\n\ndeclare const __FIG_DEV__: boolean | undefined;\n\nconst __DEV__ = typeof __FIG_DEV__ === \"boolean\" ? __FIG_DEV__ : false;\n\n/** Describes payload render result. */\nexport interface PayloadRenderResult {\n allReady: Promise<void>;\n contentType: string;\n stream: ReadableStream<Uint8Array>;\n}\n\n/** Describes payload component. */\nexport type PayloadComponent = (\n props: Props & { children?: FigNode },\n) => FigNode;\n\n/** Describes payload render options. */\nexport interface PayloadRenderOptions {\n clientReferenceAssets?: (metadata: { id: string }) => FigAssetResourceList;\n componentAssets?: (\n type: PayloadComponent,\n ) => FigAssetResourceList | undefined;\n /**\n * Encoded bytes the result stream buffers before row flushing pauses until\n * the consumer reads (rendering itself never pauses; encoded rows wait\n * queued). Defaults to 65536; values below 1 are clamped to 1.\n */\n highWaterMark?: number;\n signal?: AbortSignal;\n /**\n * Decides what crosses the wire when a server render throws, mirroring the\n * HTML renderer's contract: the returned payload is authoritative. Without\n * a handler, development includes the error message and production sends\n * an empty payload.\n */\n onError?: (\n error: unknown,\n info: ServerErrorInfo,\n ) => ServerErrorPayload | undefined;\n}\n\nclass PayloadRequestCancelledError extends Error {\n constructor() {\n super(\"Payload request cancelled.\");\n this.name = \"PayloadRequestCancelledError\";\n }\n}\n\ntype PayloadRequest = {\n allReady: Deferred<void>;\n assets: PayloadAssets;\n cleanupAbortListener: (() => void) | null;\n clientReferenceRows: Map<string, number>;\n componentAssets: PayloadRenderOptions[\"componentAssets\"];\n controller: ReadableStreamDefaultController<Uint8Array> | null;\n dataStore: DataStore<object, null>;\n emittedDataKeys: Set<string>;\n // Keys this render read. Only these (and the opted-in dependencies their\n // loads ensured) become data rows, so any new read path must record its\n // keys here or its entries silently stop streaming.\n readDataKeys: Set<string>;\n graph: PayloadGraphEncodeContext;\n nextRowId: number;\n nextUseId: number;\n onError: PayloadRenderOptions[\"onError\"];\n pendingDataSnapshots: Map<string, DataStoreEntrySnapshot>;\n pendingTasks: number;\n pingedTasks: Task[];\n queuedRows: Uint8Array[];\n // Reentrancy guard: enqueueing inside flushRows can synchronously invoke\n // the stream's pull handler, which must not restart the drain — queuedRows\n // is spliced only after the loop, so a reentrant pass would re-enqueue the\n // same rows.\n flushingRows: boolean;\n closed: boolean;\n workScheduled: boolean;\n};\n\ntype Task = {\n contextValues: ContextValues;\n id: number;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n} & TaskValue;\n\ntype TaskValue =\n | { kind: \"node\"; value: FigNode }\n | { kind: \"node-promise\"; value: Thenable<AwaitedFigNode> }\n | { kind: \"promise\"; value: Thenable };\n\ntype Component = PayloadComponent;\n\ntype RenderFrame = {\n contextValues: ContextValues;\n // Built lazily on the first function component; reused for the whole task\n // (the dispatcher reads context through the frame, so it stays current).\n dispatcher: RenderDispatcher | null;\n // Assets discovered during this attempt whose owning row is not yet known.\n // Assets rows carry `for` — the row id whose reveal depends on them — and\n // the owner is only decided at scope exit: a subtree that completes keeps\n // its assets with the enclosing row, while one that suspends or fails takes\n // the assets discovered inside it to its outlined row. Scope exits happen\n // within the same synchronous attempt, so buffering costs no wire latency.\n pendingAssets: SerializedAssetResource[];\n request: PayloadRequest;\n imagePreloadsSuppressed: boolean;\n stack: StackFrame | null;\n};\n\nconst errorStacks = new WeakMap<object, StackFrame>();\ntype TreePropMode = \"children\" | \"suspense\" | null;\ntype OutlineKind = \"lazy\" | \"promise\";\ntype PayloadOutline = Extract<PayloadSpecialModel, { $fig: OutlineKind }>;\n\n/** Renders to payload stream. */\nexport function renderToPayloadStream(\n node: FigNode,\n options: PayloadRenderOptions = {},\n): PayloadRenderResult {\n throwIfAborted(options.signal);\n\n const pendingDataSnapshots = new Map<string, DataStoreEntrySnapshot>();\n const request: PayloadRequest = {\n allReady: deferred<void>(),\n assets: new PayloadAssets(options.clientReferenceAssets),\n cleanupAbortListener: null,\n clientReferenceRows: new Map(),\n componentAssets: options.componentAssets,\n controller: null,\n dataStore: createRendererDataStore<object, null>({\n getLane: noLane,\n onEntryChange: (entry: DataStoreEntrySnapshot) => {\n pendingDataSnapshots.set(entry.canonicalKey, entry);\n },\n schedule: noop,\n }),\n emittedDataKeys: new Set(),\n graph: createPayloadGraphEncodeContext(),\n nextRowId: 1,\n nextUseId: 0,\n onError: options.onError,\n pendingDataSnapshots,\n readDataKeys: new Set(),\n pendingTasks: 0,\n pingedTasks: [],\n queuedRows: [],\n flushingRows: false,\n closed: false,\n workScheduled: false,\n };\n // allReady also rejects through the stream when a consumer cancels (the\n // normal client-disconnect path); the pre-attached no-op handler keeps it\n // from becoming an unhandled rejection for callers that do not await it\n // (await-ers still observe the rejection).\n void request.allReady.promise.catch(noop);\n\n request.pingedTasks.push(\n createTask(\n request,\n 0,\n { kind: \"node\", value: node },\n new Map(),\n false,\n null,\n ),\n );\n\n const stream = new ReadableStream<Uint8Array>(\n {\n start(controller) {\n request.controller = controller;\n flushRows(request);\n },\n pull() {\n // The consumer drained below the high-water mark: resume flushing\n // rows that queued while the flow was blocked.\n flushRows(request);\n },\n cancel(reason) {\n abortPayloadRequest(request, reason);\n },\n },\n new ByteLengthQueuingStrategy({\n highWaterMark: streamHighWaterMark(options.highWaterMark),\n }),\n );\n\n const signal = options.signal;\n if (signal !== undefined) {\n const abortListener = () => abortPayloadRequest(request, signal.reason);\n signal.addEventListener(\"abort\", abortListener, { once: true });\n request.cleanupAbortListener = () => {\n signal.removeEventListener(\"abort\", abortListener);\n request.cleanupAbortListener = null;\n };\n }\n\n scheduleWork(request);\n\n return {\n allReady: request.allReady.promise,\n contentType: jsonPayloadCodec.contentType,\n stream,\n };\n}\n\nfunction createTask(\n request: PayloadRequest,\n id: number,\n value: TaskValue,\n contextValues: ContextValues,\n imagePreloadsSuppressed: boolean,\n stack: StackFrame | null,\n): Task {\n request.pendingTasks += 1;\n return { contextValues, id, imagePreloadsSuppressed, stack, ...value };\n}\n\nfunction performWork(request: PayloadRequest): void {\n if (request.closed) return;\n\n const tasks = request.pingedTasks;\n request.pingedTasks = [];\n\n for (const task of tasks) retryTask(request, task);\n\n flushRows(request);\n}\n\nfunction retryTask(request: PayloadRequest, task: Task): void {\n const frame: RenderFrame = {\n // Tasks already capture a context snapshot when outlined. Provider\n // mutation is balanced, so retries can use that snapshot directly.\n contextValues: task.contextValues,\n dispatcher: null,\n pendingAssets: [],\n request,\n imagePreloadsSuppressed: task.imagePreloadsSuppressed,\n stack: task.stack,\n };\n\n try {\n let value: PayloadModel;\n switch (task.kind) {\n case \"node\":\n value = serializeNode(task.value, frame);\n break;\n case \"node-promise\":\n value = serializeNode(readThenable(task.value), frame);\n break;\n case \"promise\":\n value = serializeValue(readThenable(task.value), frame);\n break;\n }\n flushFrameAssets(frame, task.id);\n emitDataRows(request);\n emitRow(request, { id: task.id, tag: \"model\", value });\n finishTask(request);\n } catch (error) {\n if (isThenable(error)) {\n // The retry re-discovers nothing already deduped by request.assets, so\n // this attempt's assets must ship now; the task still settles into id.\n flushFrameAssets(frame, task.id);\n const ping = () => pingTask(request, task);\n error.then(ping, ping);\n return;\n }\n\n flushFrameAssets(frame, task.id);\n emitRow(request, {\n id: task.id,\n tag: \"error\",\n value: errorRowPayload(request, error, task.stack),\n });\n finishTask(request);\n }\n}\n\nfunction finishTask(request: PayloadRequest): void {\n request.pendingTasks -= 1;\n if (request.pendingTasks === 0) request.allReady.resolve(undefined);\n}\n\nfunction emitDataRows(request: PayloadRequest): void {\n if (request.pendingDataSnapshots.size === 0) return;\n const keys: string[] = [];\n\n for (const snapshot of request.pendingDataSnapshots.values()) {\n // Stream only settled values. A \"refreshing\" entry exposes a transient stale\n // value while its background refresh is in flight; emitting it would mark the\n // key emitted forever and permanently suppress the fresh value. Skipping it\n // lets the entry stream once its refresh settles.\n if (!snapshot.hasValue || snapshot.status === \"refreshing\") continue;\n\n // Keep dependency-only snapshots available in case a later task reads\n // them directly without changing their cached value.\n if (!request.readDataKeys.has(snapshot.canonicalKey)) continue;\n keys.push(snapshot.canonicalKey);\n }\n\n // Each key, including opted-in sources a read's load ensured, is emitted once;\n // the resource's transfer rule decides what crosses.\n const entries = request.dataStore.snapshotKeys(keys).filter((entry) => {\n const key = normalizeDataResourceKey(entry.key);\n // A transfer that returns undefined must stay pending: its live state\n // can become transferable before a later task reads it again.\n request.pendingDataSnapshots.delete(key);\n if (request.emittedDataKeys.has(key)) return false;\n request.emittedDataKeys.add(key);\n return true;\n });\n\n if (entries.length > 0) {\n emitRow(request, { tag: \"data\", value: encodePayloadDataEntries(entries) });\n }\n}\n\nfunction flushFrameAssets(frame: RenderFrame, rowId: number): void {\n if (frame.pendingAssets.length === 0) return;\n const value = frame.pendingAssets;\n frame.pendingAssets = [];\n emitRow(frame.request, { for: rowId, tag: \"assets\", value });\n}\n\nfunction createPayloadDispatcher(frame: RenderFrame): RenderDispatcher {\n const dispatcher = createStaticDispatcher({\n contextValues: frame.contextValues,\n externalStoreError:\n \"useSyncExternalStore requires getServerSnapshot during payload render.\",\n readBrowser() {\n throw new Error(\n \"readBrowser cannot be used during payload render: serialized components do not run in the browser. Move browser-only behavior into a client reference.\",\n );\n },\n readPromise: readThenable,\n readData(resource, args) {\n frame.request.readDataKeys.add(\n normalizeDataResourceKey(resource.key(...args)),\n );\n return frame.request.dataStore.readData(resource, args);\n },\n useId() {\n const id = `fig-pl-${frame.request.nextUseId.toString(32)}`;\n frame.request.nextUseId += 1;\n return id;\n },\n updateError: \"State updates are not allowed during payload render.\",\n });\n\n // Serialized components are render-only: they never re-run on the client,\n // so state, effects, and interactivity are meaningless there — dev throws\n // at first use instead of silently freezing initial state into the wire.\n // Reads stay server-safe: readContext/readData/readPromise,\n // useMemo, useId, and useSyncExternalStore's getServerSnapshot path (a\n // read, not a subscription — the static dispatcher already requires it).\n if (__DEV__) {\n const throwClientApi = (hook: string) => (): never => {\n throw new Error(\n `${hook} cannot be used during payload render: serialized components are render-only. Move state, effects, and interactivity into a client reference.`,\n );\n };\n dispatcher.useState = throwClientApi(\"useState\");\n dispatcher.useActionState = throwClientApi(\"useActionState\");\n dispatcher.useTransition = throwClientApi(\"useTransition\");\n dispatcher.useStableEvent = throwClientApi(\"useStableEvent\");\n dispatcher.useReactive = throwClientApi(\"useReactive\");\n dispatcher.useBeforePaint = throwClientApi(\"useBeforePaint\");\n dispatcher.useBeforeLayout = throwClientApi(\"useBeforeLayout\");\n }\n\n return dispatcher;\n}\n\nfunction serializeNode(node: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(node)) {\n return serializeTreeArray(node, frame);\n }\n\n if (node === null || node === undefined || typeof node === \"boolean\") {\n return node === undefined ? { $fig: \"undefined\" } : node;\n }\n\n if (typeof node === \"string\" || typeof node === \"number\") {\n return node;\n }\n\n if (isPortal(node)) return null;\n if (isValidElement(node)) return serializeElement(node, frame, false);\n if (isThenable(node)) {\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: node },\n \"promise\",\n node,\n );\n }\n\n throw invalidChildError(node);\n}\n\nfunction serializeNodeOrLazy(\n node: FigNode,\n frame: RenderFrame,\n preserveElementIdentity = false,\n): PayloadModel {\n const graphCheckpoint = checkpointPayloadGraph(frame.request.graph);\n const assetCheckpoint = frame.pendingAssets.length;\n try {\n if (!isValidElement(node)) return serializeNode(node, frame);\n return serializeElement(node, frame, preserveElementIdentity);\n } catch (error) {\n rollbackPayloadGraph(frame.request.graph, graphCheckpoint);\n // Assets discovered inside this subtree belong to the outlined row, not\n // the enclosing one: gating the enclosing row would hold the whole tree's\n // reveal on stylesheets only the hole's content needs.\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n if (isThenable(error)) {\n return outlineTask(\n frame,\n { kind: \"node\", value: node },\n \"lazy\",\n error,\n scopedAssets,\n );\n }\n return outlineError(frame, error, \"lazy\", scopedAssets);\n }\n}\n\nfunction serializeElement(\n element: FigElement,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const type = element.type;\n\n if (typeof type === \"string\") {\n return serializeHostElement(element, type, frame, preserveIdentity);\n }\n\n if (type === Fragment) {\n return serializeElementModel(\n element,\n { $fig: \"fragment\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (isClientReference(type)) {\n const clientId = emitClientReference(frame.request, type);\n return serializeElementModel(\n element,\n { $fig: \"client\", id: clientId },\n frame,\n preserveIdentity,\n );\n }\n\n if (isContext(type)) {\n return serializeContextProvider(type, element.props, frame);\n }\n\n if (isAssets(type)) {\n return serializeAssets(element.props, frame);\n }\n\n if (isSuspense(type)) {\n return serializeElementModel(\n element,\n { $fig: \"suspense\" },\n frame,\n preserveIdentity,\n \"suspense\",\n );\n }\n\n if (isErrorBoundary(type)) {\n return serializeNode(element.props.children, frame);\n }\n\n if (isActivity(type)) {\n return serializeElementModel(\n element,\n { $fig: \"activity\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (isViewTransition(type)) {\n return serializeElementModel(\n element,\n { $fig: \"view-transition\" },\n frame,\n preserveIdentity,\n \"children\",\n );\n }\n\n if (typeof type === \"function\") {\n return serializeFunctionComponent(type, element.props, frame);\n }\n\n throw new Error(\"Unsupported Fig element type during payload render.\");\n}\n\nfunction serializeHostElement(\n element: FigElement,\n type: string,\n frame: RenderFrame,\n preserveIdentity: boolean,\n): PayloadModel {\n const preload = imagePreloadFromHostProps(\n type,\n element.props,\n frame.imagePreloadsSuppressed,\n );\n if (preload !== null) {\n frame.request.assets.append(preload, frame.pendingAssets);\n }\n\n const previousImagePreloadsSuppressed = frame.imagePreloadsSuppressed;\n frame.imagePreloadsSuppressed =\n previousImagePreloadsSuppressed || suppressesImagePreloads(type);\n try {\n return serializeElementModel(\n element,\n type,\n frame,\n preserveIdentity,\n \"children\",\n );\n } finally {\n frame.imagePreloadsSuppressed = previousImagePreloadsSuppressed;\n }\n}\n\nfunction serializeElementModel(\n element: FigElement,\n type: PayloadElementModel[\"type\"],\n frame: RenderFrame,\n preserveIdentity: boolean,\n treeProps: TreePropMode = null,\n): PayloadModel {\n const id = preserveIdentity\n ? definePayloadGraphElement(frame.request.graph, element)\n : undefined;\n if (typeof id === \"object\") return id;\n const model: PayloadElementModel = {\n $fig: \"element\",\n key: element.key,\n props: serializeProps(\n element.props,\n frame,\n treeProps,\n typeof type === \"string\",\n ),\n type,\n };\n if (id !== undefined) model.id = id;\n return model;\n}\n\nfunction serializeFunctionComponent(\n type: Component,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n const assetCheckpoint = frame.pendingAssets.length;\n frame.request.assets.append(\n frame.request.componentAssets?.(type),\n frame.pendingAssets,\n );\n frame.dispatcher ??= createPayloadDispatcher(frame);\n const previousDispatcher = setCurrentDispatcher(frame.dispatcher);\n const previousDataStore = setCurrentDataStore(frame.request.dataStore);\n const previousStack = frame.stack;\n if (__DEV__ || frame.request.onError !== undefined) {\n frame.stack = { name: type.name || \"Anonymous\", parent: previousStack };\n }\n\n try {\n if (\n __DEV__ &&\n \"$$typeof\" in type &&\n type.$$typeof === Symbol.for(\"fig.data-resource\")\n ) {\n throw new Error(\n \"Payload components cannot be rendered inside Payload. Render the underlying server component directly, or mount separate Payload components from the client tree.\",\n );\n }\n const result = type(props);\n if (isThenable(result)) {\n const scopedAssets = frame.pendingAssets.splice(assetCheckpoint);\n return outlineTask(\n frame,\n { kind: \"node-promise\", value: result },\n \"promise\",\n result,\n scopedAssets,\n );\n }\n return serializeNode(result, frame);\n } catch (error) {\n recordErrorStack(error, frame.stack);\n throw error;\n } finally {\n frame.stack = previousStack;\n setCurrentDataStore(previousDataStore);\n setCurrentDispatcher(previousDispatcher);\n }\n}\n\nfunction serializeContextProvider(\n context: FigContext<unknown>,\n props: Props,\n frame: RenderFrame,\n): PayloadModel {\n return withContextValue(frame.contextValues, context, props.value, () =>\n serializeNode(props.children, frame),\n );\n}\n\nfunction serializeAssets(props: Props, frame: RenderFrame): PayloadModel {\n // Buffered, not emitted: the owning row id is decided at scope exit (see\n // RenderFrame.pendingAssets). Dedupe happens here, so a retried subtree\n // does not re-buffer assets an earlier attempt already shipped.\n frame.request.assets.append(props.assets, frame.pendingAssets);\n return serializeNode(props.children, frame);\n}\n\nfunction serializeProps(\n props: Props,\n frame: RenderFrame,\n treeProps: TreePropMode,\n hostElement = false,\n): PayloadModel {\n const clientOnlyBehavior = hostElement\n ? clientOnlyHostBehavior(props)\n : undefined;\n if (clientOnlyBehavior !== undefined) {\n throw new Error(\n `Client-only host behavior from ${clientOnlyBehavior} cannot be ` +\n \"serialized in a payload; move it into a client reference.\",\n );\n }\n\n const value: Record<string, PayloadModel> = {};\n for (const name of Object.keys(props)) {\n // A host `mix` already resolved into these props at element creation;\n // the marker itself holds descriptors (functions) and stays server-side.\n // Component `mix` props still serialize (and fail loudly on functions).\n if (hostElement && name === \"mix\") continue;\n const child = props[name];\n const isTreeProp =\n treeProps !== null &&\n (name === \"children\" ||\n (treeProps === \"suspense\" && name === \"fallback\"));\n value[name] = isTreeProp\n ? serializeTreeProp(child, frame)\n : serializeValue(child, frame);\n }\n return {\n $fig: \"object\",\n value,\n };\n}\n\nfunction serializeTreeProp(value: FigNode, frame: RenderFrame): PayloadModel {\n if (Array.isArray(value)) return serializeTreeArray(value, frame);\n return serializeNodeOrLazy(value, frame);\n}\n\nfunction serializeTreeArray(\n value: FigNode[],\n frame: RenderFrame,\n): PayloadModel[] {\n // Array.map preserves sparse root slots, which encode as null on the wire.\n // Once nested arrays are flattened, iteration intentionally makes holes\n // explicit undefined children, matching the existing flattening semantics.\n if (!value.some(Array.isArray)) {\n return value.map((child) => serializeNodeOrLazy(child, frame));\n }\n const serialized: PayloadModel[] = [];\n appendTreeArray(value, frame, serialized);\n return serialized;\n}\n\n// Payload flattens nested child arrays without dropping empty children or\n// merging text; the client performs normal child collection after decoding.\nfunction appendTreeArray(\n children: FigNode[],\n frame: RenderFrame,\n output: PayloadModel[],\n): void {\n for (const child of children) {\n if (Array.isArray(child)) appendTreeArray(child, frame, output);\n else output.push(serializeNodeOrLazy(child, frame));\n }\n}\n\nfunction serializeValue(value: unknown, frame: RenderFrame): PayloadModel {\n // Scalar values return from the shared encoder before any graph access, so\n // reusing the request graph here is free (no per-value context allocation).\n if (isPlainPayloadValue(value)) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n\n if (isClientReference(value)) {\n return { $fig: \"client\", id: emitClientReference(frame.request, value) };\n }\n\n if (isValidElement(value)) return serializeNodeOrLazy(value, frame, true);\n if (isPortal(value)) return null;\n if (isThenable(value)) {\n return outlineTask(frame, { kind: \"promise\", value }, \"promise\", value);\n }\n if (typeof value === \"function\") {\n throw new Error(\"Functions cannot be passed to client references.\");\n }\n\n if (typeof value === \"object\" && value !== null) {\n if (value instanceof Date) {\n return encodePayloadValueWithGraph(value, frame.request.graph);\n }\n if (value instanceof Map) {\n return serializePayloadMap(value, frame.request.graph, ([key, item]) => [\n serializeValue(key, frame),\n serializeValue(item, frame),\n ]);\n }\n if (value instanceof Set) {\n return serializePayloadSet(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n if (Array.isArray(value)) {\n return serializePayloadArray(value, frame.request.graph, (item) =>\n serializeValue(item, frame),\n );\n }\n\n return serializePayloadPlainObject(value, frame.request.graph, (child) =>\n serializeValue(child, frame),\n );\n }\n\n throw new Error(`Cannot serialize ${typeof value} into the payload.`);\n}\nfunction outlineTask(\n frame: RenderFrame,\n value: TaskValue,\n referenceKind: OutlineKind,\n wakeable: Thenable,\n scopedAssets: SerializedAssetResource[] = [],\n): PayloadSpecialModel {\n const request = frame.request;\n const outline = createOutline(request, referenceKind, scopedAssets);\n const task = createTask(\n request,\n outline.id,\n value,\n cloneContextValues(frame.contextValues),\n frame.imagePreloadsSuppressed,\n stackForError(wakeable, frame.stack),\n );\n\n const ping = () => pingTask(request, task);\n wakeable.then(ping, ping);\n\n return outline;\n}\n\nfunction outlineError(\n frame: RenderFrame,\n error: unknown,\n referenceKind: OutlineKind,\n scopedAssets: SerializedAssetResource[],\n): PayloadSpecialModel {\n const request = frame.request;\n const outline = createOutline(request, referenceKind, scopedAssets);\n // Assets first so a decoder that drops gates on error rows sees the row\n // order it expects; the assets still preload even though the row failed.\n emitRow(request, {\n id: outline.id,\n tag: \"error\",\n value: errorRowPayload(request, error, frame.stack),\n });\n return outline;\n}\n\nfunction createOutline(\n request: PayloadRequest,\n kind: OutlineKind,\n assets: SerializedAssetResource[],\n): PayloadOutline {\n const outline: PayloadOutline = {\n $fig: kind,\n id: request.nextRowId++,\n };\n if (assets.length > 0) {\n emitRow(request, { for: outline.id, tag: \"assets\", value: assets });\n }\n return outline;\n}\n\n// The onError return value is authoritative, like the HTML renderer's\n// reportBoundaryError: message crosses the wire only when the handler says\n// so. Without a handler, development keeps the real message for debugging\n// (payload errors never re-execute on the client, so the wire is the only\n// surface) and production sends an empty payload.\nfunction errorRowPayload(\n request: PayloadRequest,\n error: unknown,\n stack: StackFrame | null,\n): ServerErrorPayload {\n return serverErrorPayload(\n error,\n stackForError(error, stack),\n request.onError,\n );\n}\n\nfunction recordErrorStack(error: unknown, stack: StackFrame | null): void {\n if (stack === null) return;\n if (typeof error !== \"object\" || error === null) return;\n if (!errorStacks.has(error)) errorStacks.set(error, stack);\n}\n\nfunction stackForError(\n error: unknown,\n fallback: StackFrame | null,\n): StackFrame | null {\n if (typeof error !== \"object\" || error === null) return fallback;\n return errorStacks.get(error) ?? fallback;\n}\n\nfunction clientReferenceExportName(id: string): string | undefined {\n const hashIndex = id.lastIndexOf(\"#\");\n if (hashIndex === -1) return undefined;\n return id.slice(hashIndex + 1) || undefined;\n}\n\nfunction emitClientReference(\n request: PayloadRequest,\n reference: FigClientReference,\n): number {\n const existing = request.clientReferenceRows.get(reference.id);\n if (existing !== undefined) return existing;\n\n // Resolve assets BEFORE reserving the row id and recording the mapping. A lazy\n // resource thunk (bundler-manifest resolution) may throw; reserving first would\n // leave a row id mapped but never emitted, so a later retry returns the cached\n // id and the client suspends on a chunk that never arrives. Resolving first\n // lets the throw propagate as an ordinary serialization error with no poisoned\n // mapping, so the reference can be retried cleanly.\n const assets = request.assets.serializeClientReference(reference);\n const value: Extract<PayloadRow, { tag: \"client\" }>[\"value\"] = {\n id: reference.id,\n };\n if (assets.length > 0) value.assets = assets;\n // The \"<module>#<export>\" authoring convention is split here, once, so the\n // wire is self-describing and the client never string-parses ids.\n const exportName = clientReferenceExportName(reference.id);\n if (exportName !== undefined) value.exportName = exportName;\n if (reference.ssr !== undefined) value.ssr = true;\n const id = request.nextRowId++;\n request.clientReferenceRows.set(reference.id, id);\n emitRow(request, {\n id,\n tag: \"client\",\n value,\n });\n return id;\n}\n\nfunction emitRow(request: PayloadRequest, row: PayloadRow): void {\n request.queuedRows.push(jsonPayloadCodec.encodeRow(row));\n flushRows(request);\n}\n\nfunction pingTask(request: PayloadRequest, task: Task): void {\n if (request.closed) return;\n request.pingedTasks.push(task);\n scheduleWork(request);\n}\n\nfunction scheduleWork(request: PayloadRequest): void {\n // Many thenables settling in one tick ping many tasks; one performWork\n // pass drains them all, so schedule at most one.\n if (request.workScheduled) return;\n request.workScheduled = true;\n queueMicrotask(() => {\n request.workScheduled = false;\n performWork(request);\n });\n}\n\nfunction flushRows(request: PayloadRequest): void {\n if (request.controller === null || request.closed) return;\n if (request.flushingRows) return;\n\n request.flushingRows = true;\n try {\n // Row-granular gating: rows already encode one complete wire row each,\n // so stopping between rows keeps every chunk parse-safe for consumers\n // that interleave per chunk.\n let flushed = 0;\n while (\n flushed < request.queuedRows.length &&\n !streamFlowBlocked(request.controller)\n ) {\n request.controller.enqueue(request.queuedRows[flushed]);\n flushed += 1;\n }\n if (flushed === request.queuedRows.length) request.queuedRows.length = 0;\n else if (flushed > 0) {\n request.queuedRows = request.queuedRows.slice(flushed);\n }\n } finally {\n request.flushingRows = false;\n }\n\n // Deliberately not conditioned on flow: close() only marks the end of the\n // queue, so a full queue with no rows left to write still closes here.\n if (request.pendingTasks === 0 && request.queuedRows.length === 0) {\n request.closed = true;\n request.cleanupAbortListener?.();\n try {\n request.dataStore.dispose();\n } catch (error) {\n request.controller.error(error);\n return;\n }\n request.controller.close();\n }\n}\n\nfunction closeWithError(request: PayloadRequest, error: unknown): void {\n if (request.closed) return;\n request.cleanupAbortListener?.();\n request.closed = true;\n try {\n request.dataStore.dispose();\n } catch {\n // Preserve the failure that caused teardown; disposal already ran cleanup.\n }\n request.allReady.reject(error);\n request.controller?.error(error);\n}\n\nfunction abortPayloadRequest(request: PayloadRequest, reason?: unknown): void {\n closeWithError(request, reason ?? new PayloadRequestCancelledError());\n}\n\nfunction invalidChildError(value: unknown): Error {\n return new Error(\n `Invalid Fig child in payload render: ${describeInvalidChild(value)}.`,\n );\n}\n\nfunction throwIfAborted(signal?: AbortSignal | null): void {\n if (signal?.aborted) throw new PayloadRequestCancelledError();\n}\n"],"mappings":";;;;;AAkBA,IAAa,gBAAb,MAA2B;CAIN;CAHnB,8BAA+B,IAAI,IAAY;CAE/C,YACE,wBACA;EADiB,KAAA,yBAAA;CAChB;CAEH,OAAO,OAAgB,QAAyC;EAC9D,IAAI,mBAAmB,KAAK,GAAG;GAC7B,KAAK,eAAe,OAAO,MAAM;GACjC;EACF;EACA,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG;EAC3B,KAAK,MAAM,YAAY,OACrB,IAAI,mBAAmB,QAAQ,GAAG,KAAK,eAAe,UAAU,MAAM;CAE1E;CAEA,yBACE,WAC2B;EAC3B,MAAM,WAAW,sBAAsB,SAAS;EAChD,MAAM,WAAW,KAAK,yBAAyB,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BAAuB;EAC/B,IAAI;GACF,QAAQ,UAAU,QAAQ;EAC5B,SAAS,OAAO;GACd,QAAQ,WAAW,MAAM,KAAK;GAC9B;EACF;EACA,QAAQ,WAAW,MAAM;CAC3B;AACF;AAEA,SAAS,eAAe,SAAyB,OAAsB;CACrE,IAAI,QAAQ,QAAQ;CACpB,QAAQ,uBAAuB;CAC/B,QAAQ,SAAS;CACjB,IAAI;EACF,QAAQ,UAAU,QAAQ;CAC5B,QAAQ,CAER;CACA,QAAQ,SAAS,OAAO,KAAK;CAC7B,QAAQ,YAAY,MAAM,KAAK;AACjC;AAEA,SAAS,oBAAoB,SAAyB,QAAwB;CAC5E,eAAe,SAAS,UAAU,IAAI,6BAA6B,CAAC;AACtE;AAEA,SAASA,oBAAkB,OAAuB;CAChD,uBAAO,IAAI,MACT,wCAAwC,qBAAqB,KAAK,EAAE,EACtE;AACF;AAEA,SAAS,eAAe,QAAmC;CACzD,IAAI,QAAQ,SAAS,MAAM,IAAI,6BAA6B;AAC9D"}
@@ -1,7 +1,7 @@
1
1
  import { i as escapeText, n as escapeScriptJson, t as escapeAttribute } from "./escaping-2fHOwhEM.js";
2
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, 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, encodePayloadDataEntries, invalidChildError, isActivity, isAssets, isClientReference, isContext, isErrorBoundary, isFigAssetResource, isPortal, isSuspense, isThenable, isViewTransition, normalizeDataResourceKey, 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",
@@ -615,7 +615,12 @@ function flushCompletedQueues(request) {
615
615
  }
616
616
  if (request.abortableTasks.size === 0 && request.completedBoundaries.size === 0 && request.clientRenderedBoundaries.size === 0 && request.partialBoundaries.size === 0) {
617
617
  request.status = "closed";
618
- request.dispose();
618
+ try {
619
+ request.dispose();
620
+ } catch (error) {
621
+ request.controller.error(error);
622
+ return;
623
+ }
619
624
  request.controller.close();
620
625
  }
621
626
  }
@@ -712,12 +717,12 @@ function flushBoundarySegment(request, boundary, segment) {
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);
720
- writeDataOperation(request);
725
+ writeDataOperation(request, boundary);
721
726
  writeScript(request, withAssetGate(blockingIds, `${RUNTIME_REF}.s(${jsString(placeholderId(request, id))},${jsString(segmentId(request, id))})`));
722
727
  }
723
728
  function writeBoundaryRevealScript(request, boundary) {
@@ -725,13 +730,14 @@ function writeBoundaryRevealScript(request, boundary) {
725
730
  const metadata = switchBoundaryMetadata(request, boundary);
726
731
  const metadataArgument = metadata === null ? "" : `,${metadata}`;
727
732
  writeRuntime(request);
728
- writeDataOperation(request);
733
+ writeDataOperation(request, boundary);
729
734
  const boundaryRef = jsString(boundaryId(request, ensureBoundaryId(request, boundary)));
730
735
  const contentRef = jsString(segmentId(request, ensureSegmentId(request, boundary.contentSegment)));
731
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);
732
738
  }
733
739
  function takeData(request) {
734
- return claimData(request, request.dataStore.snapshot());
740
+ return [...[...new Set(request.queuedDataRows.values())].flatMap((batch) => decodePayloadDataEntries(takeQueuedDataBatch(request, batch))), ...claimData(request, request.dataStore.snapshot())];
735
741
  }
736
742
  function claimData(request, entries) {
737
743
  return entries.filter((entry) => {
@@ -742,11 +748,53 @@ function claimData(request, entries) {
742
748
  return true;
743
749
  });
744
750
  }
745
- function writeDataOperation(request) {
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) {
746
760
  const pending = request.pendingDataKeys;
747
761
  if (pending === null || pending.size === 0) return;
748
- const rows = encodeDataRows(claimData(request, request.dataStore.snapshotKeys(pending)));
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)));
749
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) {
750
798
  if (rows.length === 0) return;
751
799
  writeScript(request, `${RUNTIME_REF}.d(${jsString(request.identifierPrefix)},${escapeScriptJson(rows)})`);
752
800
  }
@@ -829,6 +877,7 @@ function flushClientRenderedBoundary(request, boundary) {
829
877
  const call = boundary.activityId === null ? `${RUNTIME_REF}.x(${boundaryRef},${digest},${message}${cleanup})` : `${RUNTIME_REF}.ax(${jsString(boundary.activityId)},${boundaryRef},${digest},${message}${cleanup})`;
830
878
  boundary.stagedSegmentIds.clear();
831
879
  writeScript(request, call);
880
+ writeLateDataOperations(request, boundary);
832
881
  }
833
882
  function drainBoundaryQueue(request, queue, flush) {
834
883
  for (;;) {
@@ -908,6 +957,7 @@ function createServerRenderRequest(node, options, mode) {
908
957
  pendingDataKeys: mode?.prerender === true || options.streamData === false ? null : /* @__PURE__ */ new Set(),
909
958
  streamDataFilter: typeof options.streamData === "object" ? options.streamData.filter ?? null : null,
910
959
  writtenDataKeys: /* @__PURE__ */ new Set(),
960
+ queuedDataRows: /* @__PURE__ */ new Map(),
911
961
  dispose: disposeRequest,
912
962
  abortReason: null,
913
963
  identifierPrefix,
@@ -1364,6 +1414,7 @@ function renderSuspense(props, frame) {
1364
1414
  error: null,
1365
1415
  fallbackSegment: null,
1366
1416
  fallbackTasks: /* @__PURE__ */ new Set(),
1417
+ lateDataRows: [],
1367
1418
  stagedSegmentIds: /* @__PURE__ */ new Set(),
1368
1419
  id: null,
1369
1420
  metadataVisible: false,
@@ -1587,7 +1638,7 @@ function discardBoundaryServerWork(request, boundary) {
1587
1638
  request.completedBoundaries.delete(boundary);
1588
1639
  request.partialBoundaries.delete(boundary);
1589
1640
  const discardedSegments = /* @__PURE__ */ new Set();
1590
- discardSegmentTree(request, boundary.contentSegment, discardedSegments, boundary.stagedSegmentIds);
1641
+ discardSegmentTree(request, boundary.contentSegment, discardedSegments, boundary);
1591
1642
  for (const task of request.abortableTasks) if (discardedSegments.has(task.frame.segment)) abortTask(task);
1592
1643
  if (boundary.parentFlushed) request.clientRenderedBoundaries.add(boundary);
1593
1644
  }
@@ -1634,20 +1685,22 @@ function reportBrowserBailout(request, bailout, stack) {
1634
1685
  report(error, { componentStack: componentStack(stack) });
1635
1686
  } catch {}
1636
1687
  }
1637
- function discardSegmentTree(request, segment, discarded, stagedSegmentIds) {
1688
+ function discardSegmentTree(request, segment, discarded, owner) {
1638
1689
  discarded.add(segment);
1639
1690
  const boundary = segment.boundary;
1640
1691
  if (boundary !== null) {
1641
1692
  boundary.status = "client-rendered";
1642
- for (const id of boundary.stagedSegmentIds) stagedSegmentIds.add(id);
1693
+ for (const id of boundary.stagedSegmentIds) owner.stagedSegmentIds.add(id);
1643
1694
  boundary.stagedSegmentIds.clear();
1695
+ owner.lateDataRows.push(...boundary.lateDataRows);
1696
+ boundary.lateDataRows = [];
1644
1697
  boundary.completedSegments.length = 0;
1645
1698
  request.completedBoundaries.delete(boundary);
1646
1699
  request.partialBoundaries.delete(boundary);
1647
1700
  request.clientRenderedBoundaries.delete(boundary);
1648
- discardSegmentTree(request, boundary.contentSegment, discarded, stagedSegmentIds);
1701
+ discardSegmentTree(request, boundary.contentSegment, discarded, owner);
1649
1702
  }
1650
- for (const child of segment.children) discardSegmentTree(request, child, discarded, stagedSegmentIds);
1703
+ for (const child of segment.children) discardSegmentTree(request, child, discarded, owner);
1651
1704
  }
1652
1705
  function abort(request, reason) {
1653
1706
  if (request.status === "closed") return;
@@ -1658,7 +1711,12 @@ function abort(request, reason) {
1658
1711
  fatalError(request, error);
1659
1712
  return;
1660
1713
  }
1661
- request.dispose();
1714
+ try {
1715
+ request.dispose();
1716
+ } catch {
1717
+ fatalError(request, error);
1718
+ return;
1719
+ }
1662
1720
  for (const task of request.abortableTasks) {
1663
1721
  const { boundary, stack } = task.frame;
1664
1722
  if (boundary !== null) markBoundaryClientRendered(request, boundary, error, stack, {});
@@ -1670,7 +1728,9 @@ function abort(request, reason) {
1670
1728
  function fatalError(request, error) {
1671
1729
  if (request.status === "closed") return;
1672
1730
  request.status = "closed";
1673
- request.dispose();
1731
+ try {
1732
+ request.dispose();
1733
+ } catch {}
1674
1734
  request.headReady.reject(error);
1675
1735
  request.shellReady.reject(error);
1676
1736
  request.allReady.reject(error);