@pyreon/runtime-server 0.7.12 → 0.7.14

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.
@@ -5386,7 +5386,7 @@ var drawChart = (function (exports) {
5386
5386
  </script>
5387
5387
  <script>
5388
5388
  /*<!--*/
5389
- const data = {"version":2,"tree":{"name":"root","children":[{"name":"index.js","children":[{"name":"src/index.ts","uid":"d0a4fa41-1"}]}],"isRoot":true},"nodeParts":{"d0a4fa41-1":{"renderedLength":10634,"gzipLength":3472,"brotliLength":0,"metaUid":"d0a4fa41-0"}},"nodeMetas":{"d0a4fa41-0":{"id":"/src/index.ts","moduleParts":{"index.js":"d0a4fa41-1"},"imported":[{"uid":"d0a4fa41-2"},{"uid":"d0a4fa41-3"}],"importedBy":[],"isEntry":true},"d0a4fa41-2":{"id":"node:async_hooks","moduleParts":{},"imported":[],"importedBy":[{"uid":"d0a4fa41-0"}]},"d0a4fa41-3":{"id":"@pyreon/core","moduleParts":{},"imported":[],"importedBy":[{"uid":"d0a4fa41-0"}]}},"env":{"rollup":"4.23.0"},"options":{"gzip":true,"brotli":false,"sourcemap":false}};
5389
+ const data = {"version":2,"tree":{"name":"root","children":[{"name":"index.js","children":[{"name":"src/index.ts","uid":"b6b89270-1"}]}],"isRoot":true},"nodeParts":{"b6b89270-1":{"renderedLength":11206,"gzipLength":3685,"brotliLength":0,"metaUid":"b6b89270-0"}},"nodeMetas":{"b6b89270-0":{"id":"/src/index.ts","moduleParts":{"index.js":"b6b89270-1"},"imported":[{"uid":"b6b89270-2"},{"uid":"b6b89270-3"}],"importedBy":[],"isEntry":true},"b6b89270-2":{"id":"node:async_hooks","moduleParts":{},"imported":[],"importedBy":[{"uid":"b6b89270-0"}]},"b6b89270-3":{"id":"@pyreon/core","moduleParts":{},"imported":[],"importedBy":[{"uid":"b6b89270-0"}]}},"env":{"rollup":"4.23.0"},"options":{"gzip":true,"brotli":false,"sourcemap":false}};
5390
5390
 
5391
5391
  const run = () => {
5392
5392
  const width = window.innerWidth;
package/lib/index.js CHANGED
@@ -16,6 +16,7 @@ import { ForSymbol, Fragment, Suspense, cx, normalizeStyleValue, runWithHooks, s
16
16
  * renderToString(vnode) → Promise<string>
17
17
  * renderToStream(vnode) → ReadableStream<string>
18
18
  */
19
+ const __DEV__ = typeof process !== "undefined" && process.env.NODE_ENV !== "production";
19
20
  const _streamCtxAls = new AsyncLocalStorage();
20
21
  const _contextAls = new AsyncLocalStorage();
21
22
  const _fallbackStack = [];
@@ -72,7 +73,8 @@ function renderToStream(root) {
72
73
  const ctx = {
73
74
  pending: [],
74
75
  nextId: () => bid++,
75
- mainEnqueue: enqueue
76
+ mainEnqueue: enqueue,
77
+ suspenseDepth: 0
76
78
  };
77
79
  return withStoreContext(() => _contextAls.run([], () => _streamCtxAls.run(ctx, async () => {
78
80
  await streamNode(root, enqueue);
@@ -104,9 +106,19 @@ async function streamComponentNode(vnode, enqueue) {
104
106
  await streamSuspenseBoundary(vnode, enqueue);
105
107
  return;
106
108
  }
107
- const { vnode: output } = runWithHooks(vnode.type, mergeChildrenIntoProps(vnode));
108
- const resolved = output instanceof Promise ? await output : output;
109
- if (resolved !== null) await streamNode(resolved, enqueue);
109
+ try {
110
+ const { vnode: output } = runWithHooks(vnode.type, mergeChildrenIntoProps(vnode));
111
+ const resolved = output instanceof Promise ? await output : output;
112
+ if (resolved !== null) await streamNode(resolved, enqueue);
113
+ } catch (err) {
114
+ if (__DEV__) {
115
+ const name = vnode.type.name || "Anonymous";
116
+ console.error(`[Pyreon SSR] Error rendering <${name}>:`, err);
117
+ }
118
+ const ctx = _streamCtxAls.getStore();
119
+ if (ctx && ctx.suspenseDepth > 0) throw err;
120
+ enqueue("<!--pyreon-error-->");
121
+ }
110
122
  }
111
123
  async function streamElementNode(vnode, enqueue) {
112
124
  const tag = vnode.type;
@@ -166,11 +178,16 @@ async function streamSuspenseBoundary(vnode, enqueue) {
166
178
  const ctxStore = _contextAls.getStore() ?? [];
167
179
  ctx.pending.push(_contextAls.run(ctxStore, async () => {
168
180
  try {
181
+ ctx.suspenseDepth++;
169
182
  const buf = [];
170
183
  await streamNode(children ?? null, (s) => buf.push(s));
171
184
  mainEnqueue(`<template id="pyreon-t-${id}">${buf.join("")}</template>`);
172
185
  mainEnqueue(`<script>__NS("pyreon-s-${id}","pyreon-t-${id}")<\/script>`);
173
- } catch (_err) {}
186
+ } catch (err) {
187
+ if (__DEV__) console.error(`[Pyreon SSR] Suspense boundary caught an error — fallback will remain:`, err);
188
+ } finally {
189
+ ctx.suspenseDepth--;
190
+ }
174
191
  }));
175
192
  }
176
193
  async function renderNode(node) {
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * @pyreon/runtime-server — SSR/SSG renderer for Pyreon.\n *\n * Walks a VNode tree and produces HTML strings.\n * Signal accessors (reactive getters `() => value`) are called synchronously\n * to snapshot their current value — no effects are set up on the server.\n *\n * Async components (`async function Component()`) are fully supported:\n * renderToString will await them before continuing the tree walk.\n *\n * API:\n * renderToString(vnode) → Promise<string>\n * renderToStream(vnode) → ReadableStream<string>\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\"\nimport type { ClassValue, ComponentFn, ForProps, VNode, VNodeChild } from \"@pyreon/core\"\nimport {\n cx,\n ForSymbol,\n Fragment,\n normalizeStyleValue,\n runWithHooks,\n Suspense,\n setContextStackProvider,\n} from \"@pyreon/core\"\n\n// ─── Streaming Suspense context ───────────────────────────────────────────────\n// Tracks in-flight async Suspense boundary resolutions within a single stream.\n\ninterface StreamCtx {\n pending: Promise<void>[]\n nextId: () => number\n mainEnqueue: (s: string) => void\n}\n\nconst _streamCtxAls = new AsyncLocalStorage<StreamCtx>()\n\n// ─── Concurrent SSR context isolation ────────────────────────────────────────\n// Each renderToString call runs in its own ALS store (a fresh empty stack[]).\n// Concurrent requests never share context frames.\n\nconst _contextAls = new AsyncLocalStorage<Map<symbol, unknown>[]>()\nconst _fallbackStack: Map<symbol, unknown>[] = []\n\nsetContextStackProvider(() => _contextAls.getStore() ?? _fallbackStack)\n\n// ─── Store isolation (optional) ───────────────────────────────────────────────\n// A second ALS isolates store registries between concurrent requests.\n// Activated only when the user calls configureStoreIsolation().\n\nconst _storeAls = new AsyncLocalStorage<Map<string, unknown>>()\nlet _storeIsolationActive = false\n\n/**\n * Wire up per-request store isolation.\n * Call once at server startup, passing a `setStoreRegistryProvider` function.\n *\n * @example\n * import { configureStoreIsolation } from \"@pyreon/runtime-server\"\n * configureStoreIsolation(setStoreRegistryProvider)\n */\nexport function configureStoreIsolation(\n setStoreRegistryProvider: (fn: () => Map<string, unknown>) => void,\n): void {\n setStoreRegistryProvider(() => _storeAls.getStore() ?? new Map())\n _storeIsolationActive = true\n}\n\n/** Wrap a function call in a fresh store registry (no-op if isolation not configured). */\nfunction withStoreContext<T>(fn: () => T): T {\n if (!_storeIsolationActive) return fn()\n return _storeAls.run(new Map(), fn)\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/** Render a VNode tree to an HTML string. Supports async component functions. */\nexport async function renderToString(root: VNode | null): Promise<string> {\n if (root === null) return \"\"\n // Each call gets a fresh isolated context stack and (optionally) store registry\n return withStoreContext(() => _contextAls.run([], () => renderNode(root)))\n}\n\n/**\n * Run an async function with a fresh, isolated context stack and store registry.\n * Useful when you need to call Pyreon APIs (e.g. useHead, prefetchLoaderData)\n * outside of renderToString but still want per-request isolation.\n */\nexport function runWithRequestContext<T>(fn: () => Promise<T>): Promise<T> {\n return withStoreContext(() => _contextAls.run([], fn))\n}\n\n/**\n * Render a VNode tree to a Web-standard ReadableStream of HTML chunks.\n *\n * True progressive streaming: HTML is flushed to the client as soon as each\n * node is ready. Synchronous subtrees are enqueued immediately; async component\n * boundaries are awaited in-order and their output is enqueued as it resolves.\n *\n * Suspense boundaries are streamed out-of-order: the fallback is emitted\n * immediately, and the resolved children are sent as a `<template>` + inline\n * swap script once ready — without blocking the rest of the page.\n *\n * Each renderToStream call gets its own isolated ALS context stack.\n */\nexport function renderToStream(root: VNode | null): ReadableStream<string> {\n return new ReadableStream<string>({\n start(controller) {\n const enqueue = (chunk: string) => controller.enqueue(chunk)\n let bid = 0\n const ctx: StreamCtx = {\n pending: [],\n nextId: () => bid++,\n mainEnqueue: enqueue,\n }\n return withStoreContext(() =>\n _contextAls.run([], () =>\n _streamCtxAls\n .run(ctx, async () => {\n await streamNode(root, enqueue)\n // Drain all pending Suspense resolutions (may spawn nested ones)\n while (ctx.pending.length > 0) {\n await Promise.all(ctx.pending.splice(0))\n }\n controller.close()\n })\n .catch((err) => controller.error(err)),\n ),\n )\n },\n })\n}\n\n// ─── Streaming renderer ───────────────────────────────────────────────────────\n\nasync function streamVNode(vnode: VNode, enqueue: (s: string) => void): Promise<void> {\n if (vnode.type === Fragment) {\n for (const child of vnode.children) await streamNode(child, enqueue)\n return\n }\n\n if (vnode.type === (ForSymbol as unknown as string)) {\n const { each, children } = vnode.props as unknown as ForProps<unknown>\n enqueue(\"<!--pyreon-for-->\")\n for (const item of each()) await streamNode(children(item) as VNodeChild, enqueue)\n enqueue(\"<!--/pyreon-for-->\")\n return\n }\n\n if (typeof vnode.type === \"function\") {\n await streamComponentNode(vnode, enqueue)\n return\n }\n\n await streamElementNode(vnode, enqueue)\n}\n\nasync function streamComponentNode(vnode: VNode, enqueue: (s: string) => void): Promise<void> {\n if (vnode.type === Suspense) {\n await streamSuspenseBoundary(vnode, enqueue)\n return\n }\n const { vnode: output } = runWithHooks(vnode.type as ComponentFn, mergeChildrenIntoProps(vnode))\n const resolved = output instanceof Promise ? await output : output\n if (resolved !== null) await streamNode(resolved, enqueue)\n}\n\nasync function streamElementNode(vnode: VNode, enqueue: (s: string) => void): Promise<void> {\n const tag = vnode.type as string\n let open = `<${tag}`\n const props = vnode.props as Record<string, unknown>\n for (const key in props) {\n const attr = renderProp(key, props[key])\n if (attr) open += ` ${attr}`\n }\n if (isVoidElement(tag)) {\n enqueue(`${open} />`)\n return\n }\n enqueue(`${open}>`)\n for (const child of vnode.children) await streamNode(child, enqueue)\n enqueue(`</${tag}>`)\n}\n\nasync function streamNode(\n node: VNodeChild | null | (() => VNodeChild),\n enqueue: (s: string) => void,\n): Promise<void> {\n if (typeof node === \"function\") {\n return streamNode((node as () => VNodeChild)(), enqueue)\n }\n if (node == null || node === false) return\n if (typeof node === \"string\") {\n enqueue(escapeHtml(node))\n return\n }\n if (typeof node === \"number\" || typeof node === \"boolean\") {\n enqueue(String(node))\n return\n }\n if (Array.isArray(node)) {\n for (const child of node) await streamNode(child, enqueue)\n return\n }\n\n await streamVNode(node as VNode, enqueue)\n}\n\n// Inline swap helper emitted once per stream, before the first <template>\nconst SUSPENSE_SWAP_FN =\n \"<script>function __NS(s,t){var e=document.getElementById(s),l=document.getElementById(t);\" +\n \"if(e&&l){e.replaceWith(l.content.cloneNode(!0));l.remove()}}</script>\"\n\n/**\n * Stream a Suspense boundary: emit fallback immediately, then resolve children\n * asynchronously and emit them as a `<template>` + client-side swap.\n *\n * The actual children HTML is buffered until fully resolved, then emitted to the\n * main stream enqueue so it always arrives after the fallback placeholder.\n */\nasync function streamSuspenseBoundary(vnode: VNode, enqueue: (s: string) => void): Promise<void> {\n const ctx = _streamCtxAls.getStore()\n const { fallback, children } = vnode.props as { fallback: VNodeChild; children?: VNodeChild }\n\n // No streaming context (e.g. called from renderToString) — render children inline\n if (!ctx) {\n const { vnode: output } = runWithHooks(Suspense as ComponentFn, vnode.props)\n if (output !== null) await streamNode(output, enqueue)\n return\n }\n\n const id = ctx.nextId()\n const { mainEnqueue } = ctx\n\n // Emit the swap helper function once (before first use)\n if (id === 0) mainEnqueue(SUSPENSE_SWAP_FN)\n\n // Stream the fallback synchronously (no await on children)\n mainEnqueue(`<div id=\"pyreon-s-${id}\">`)\n await streamNode(fallback ?? null, enqueue)\n mainEnqueue(\"</div>\")\n\n // Capture the context store for the async resolution so it inherits context\n const ctxStore = _contextAls.getStore() ?? []\n\n // Queue async resolution — runs in parallel, emits to main stream when done\n // Errors are caught per-boundary so one failing Suspense doesn't abort the stream.\n ctx.pending.push(\n _contextAls.run(ctxStore, async () => {\n try {\n const buf: string[] = []\n await streamNode(children ?? null, (s) => buf.push(s))\n mainEnqueue(`<template id=\"pyreon-t-${id}\">${buf.join(\"\")}</template>`)\n mainEnqueue(`<script>__NS(\"pyreon-s-${id}\",\"pyreon-t-${id}\")</script>`)\n } catch (_err) {\n // Fallback stays visible — no swap script emitted\n }\n }),\n )\n}\n\n// ─── Core renderer ───────────────────────────────────────────────────────────\n\nasync function renderNode(node: VNodeChild | (() => VNodeChild)): Promise<string> {\n // Reactive accessor — call it synchronously (snapshot)\n if (typeof node === \"function\") {\n return renderNode((node as () => VNodeChild)())\n }\n\n if (node == null || node === false) return \"\"\n\n if (typeof node === \"string\") return escapeHtml(node)\n if (typeof node === \"number\" || typeof node === \"boolean\") return String(node)\n\n if (Array.isArray(node)) {\n let html = \"\"\n for (const child of node) html += await renderNode(child)\n return html\n }\n\n const vnode = node as VNode\n\n if (vnode.type === Fragment) {\n return renderChildren(vnode.children)\n }\n\n if (vnode.type === (ForSymbol as unknown as string)) {\n const { each, children } = vnode.props as unknown as ForProps<unknown>\n let forHtml = \"<!--pyreon-for-->\"\n for (const item of each()) forHtml += await renderNode(children(item) as VNodeChild)\n forHtml += \"<!--/pyreon-for-->\"\n return forHtml\n }\n\n if (typeof vnode.type === \"function\") {\n return renderComponent(vnode as VNode & { type: ComponentFn })\n }\n\n return renderElement(vnode)\n}\n\nasync function renderChildren(children: VNodeChild[]): Promise<string> {\n let html = \"\"\n for (const child of children) html += await renderNode(child)\n return html\n}\n\nasync function renderComponent(vnode: VNode & { type: ComponentFn }): Promise<string> {\n const { vnode: output } = runWithHooks(vnode.type, mergeChildrenIntoProps(vnode))\n\n // Async component function (async function Component()) — await the promise\n if (output instanceof Promise) {\n const resolved = await output\n if (resolved === null) return \"\"\n return renderNode(resolved)\n }\n\n if (output === null) return \"\"\n return renderNode(output)\n}\n\nasync function renderElement(vnode: VNode): Promise<string> {\n const tag = vnode.type as string\n let html = `<${tag}`\n\n const props = vnode.props as Record<string, unknown>\n for (const key in props) {\n const attr = renderProp(key, props[key])\n if (attr) html += ` ${attr}`\n }\n\n if (isVoidElement(tag)) {\n html += \" />\"\n return html\n }\n\n html += \">\"\n\n for (const child of vnode.children) {\n html += await renderNode(child)\n }\n\n html += `</${tag}>`\n return html\n}\n\nconst SSR_URL_ATTRS = new Set([\"href\", \"src\", \"action\", \"formaction\", \"poster\", \"cite\", \"data\"])\nconst SSR_UNSAFE_URL_RE = /^\\s*(?:javascript|data):/i\n\nfunction renderPropSkipped(key: string): boolean {\n if (key === \"key\" || key === \"ref\") return true\n if (/^on[A-Z]/.test(key)) return true\n return false\n}\n\nfunction renderPropValue(key: string, value: unknown): string | null {\n if (value === null || value === undefined || value === false) return null\n if (value === true) return escapeHtml(toAttrName(key))\n\n if (key === \"class\") {\n const cls = cx(value as ClassValue)\n return cls ? `class=\"${escapeHtml(cls)}\"` : null\n }\n\n if (key === \"style\") {\n const style = normalizeStyle(value)\n return style ? `style=\"${escapeHtml(style)}\"` : null\n }\n\n return `${escapeHtml(toAttrName(key))}=\"${escapeHtml(String(value))}\"`\n}\n\nfunction renderProp(key: string, value: unknown): string | null {\n if (renderPropSkipped(key)) return null\n\n if (typeof value === \"function\") {\n return renderProp(key, (value as () => unknown)())\n }\n\n if (SSR_URL_ATTRS.has(key) && typeof value === \"string\" && SSR_UNSAFE_URL_RE.test(value)) {\n return null\n }\n\n return renderPropValue(key, value)\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nconst VOID_ELEMENTS = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n])\n\nfunction isVoidElement(tag: string): boolean {\n return VOID_ELEMENTS.has(tag.toLowerCase())\n}\n\n/** camelCase prop → kebab-case HTML attribute (e.g. className → class, htmlFor → for) */\nfunction toAttrName(key: string): string {\n if (key === \"className\") return \"class\"\n if (key === \"htmlFor\") return \"for\"\n return key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)\n}\n\nfunction normalizeStyle(value: unknown): string {\n if (typeof value === \"string\") return value\n if (typeof value === \"object\" && value !== null) {\n return Object.entries(value as Record<string, unknown>)\n .map(([k, v]) => `${toKebab(k)}: ${normalizeStyleValue(k, v)}`)\n .join(\"; \")\n }\n return \"\"\n}\n\nfunction toKebab(str: string): string {\n return str.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)\n}\n\nconst ESCAPE_MAP: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n}\n\n// Fast test — most strings in SSR have no special chars (tag names, class names, etc.)\nconst NEEDS_ESCAPE_RE = /[&<>\"']/\n\nfunction escapeHtml(str: string): string {\n if (!NEEDS_ESCAPE_RE.test(str)) return str\n return str.replace(/[&<>\"']/g, (c) => ESCAPE_MAP[c] ?? c)\n}\n\n/**\n * Merge vnode.children into props.children for component rendering.\n * Matches the behavior of mount.ts and hydrate.ts so components can\n * access children passed via h(Comp, props, child1, child2).\n */\nfunction mergeChildrenIntoProps(vnode: VNode): Record<string, unknown> {\n if (\n vnode.children.length > 0 &&\n (vnode.props as Record<string, unknown>).children === undefined\n ) {\n return {\n ...vnode.props,\n children: vnode.children.length === 1 ? vnode.children[0] : vnode.children,\n }\n }\n return vnode.props as Record<string, unknown>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoCA,MAAM,gBAAgB,IAAI,mBAA8B;AAMxD,MAAM,cAAc,IAAI,mBAA2C;AACnE,MAAM,iBAAyC,EAAE;AAEjD,8BAA8B,YAAY,UAAU,IAAI,eAAe;AAMvE,MAAM,YAAY,IAAI,mBAAyC;AAC/D,IAAI,wBAAwB;;;;;;;;;AAU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EAAE,CAAC,IAAI,oBAAoB,GAAG,EAAE,GAAG,CAC9D,KAAK,KAAK;AAEf,QAAO;;AAGT,SAAS,QAAQ,KAAqB;AACpC,QAAO,IAAI,QAAQ,WAAW,MAAM,IAAI,EAAE,aAAa,GAAG;;AAG5D,MAAM,aAAqC;CACzC,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAK;CACL,KAAK;CACN;AAGD,MAAM,kBAAkB;AAExB,SAAS,WAAW,KAAqB;AACvC,KAAI,CAAC,gBAAgB,KAAK,IAAI,CAAE,QAAO;AACvC,QAAO,IAAI,QAAQ,aAAa,MAAM,WAAW,MAAM,EAAE;;;;;;;AAQ3D,SAAS,uBAAuB,OAAuC;AACrE,KACE,MAAM,SAAS,SAAS,KACvB,MAAM,MAAkC,aAAa,OAEtD,QAAO;EACL,GAAG,MAAM;EACT,UAAU,MAAM,SAAS,WAAW,IAAI,MAAM,SAAS,KAAK,MAAM;EACnE;AAEH,QAAO,MAAM"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * @pyreon/runtime-server — SSR/SSG renderer for Pyreon.\n *\n * Walks a VNode tree and produces HTML strings.\n * Signal accessors (reactive getters `() => value`) are called synchronously\n * to snapshot their current value — no effects are set up on the server.\n *\n * Async components (`async function Component()`) are fully supported:\n * renderToString will await them before continuing the tree walk.\n *\n * API:\n * renderToString(vnode) → Promise<string>\n * renderToStream(vnode) → ReadableStream<string>\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\"\nimport type { ClassValue, ComponentFn, ForProps, VNode, VNodeChild } from \"@pyreon/core\"\nimport {\n cx,\n ForSymbol,\n Fragment,\n normalizeStyleValue,\n runWithHooks,\n Suspense,\n setContextStackProvider,\n} from \"@pyreon/core\"\n\nconst __DEV__ = typeof process !== \"undefined\" && process.env.NODE_ENV !== \"production\"\n\n// ─── Streaming Suspense context ───────────────────────────────────────────────\n// Tracks in-flight async Suspense boundary resolutions within a single stream.\n\ninterface StreamCtx {\n pending: Promise<void>[]\n nextId: () => number\n mainEnqueue: (s: string) => void\n /** Depth counter — non-zero when rendering inside a Suspense child resolution. */\n suspenseDepth: number\n}\n\nconst _streamCtxAls = new AsyncLocalStorage<StreamCtx>()\n\n// ─── Concurrent SSR context isolation ────────────────────────────────────────\n// Each renderToString call runs in its own ALS store (a fresh empty stack[]).\n// Concurrent requests never share context frames.\n\nconst _contextAls = new AsyncLocalStorage<Map<symbol, unknown>[]>()\nconst _fallbackStack: Map<symbol, unknown>[] = []\n\nsetContextStackProvider(() => _contextAls.getStore() ?? _fallbackStack)\n\n// ─── Store isolation (optional) ───────────────────────────────────────────────\n// A second ALS isolates store registries between concurrent requests.\n// Activated only when the user calls configureStoreIsolation().\n\nconst _storeAls = new AsyncLocalStorage<Map<string, unknown>>()\nlet _storeIsolationActive = false\n\n/**\n * Wire up per-request store isolation.\n * Call once at server startup, passing a `setStoreRegistryProvider` function.\n *\n * @example\n * import { configureStoreIsolation } from \"@pyreon/runtime-server\"\n * configureStoreIsolation(setStoreRegistryProvider)\n */\nexport function configureStoreIsolation(\n setStoreRegistryProvider: (fn: () => Map<string, unknown>) => void,\n): void {\n setStoreRegistryProvider(() => _storeAls.getStore() ?? new Map())\n _storeIsolationActive = true\n}\n\n/** Wrap a function call in a fresh store registry (no-op if isolation not configured). */\nfunction withStoreContext<T>(fn: () => T): T {\n if (!_storeIsolationActive) return fn()\n return _storeAls.run(new Map(), fn)\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/** Render a VNode tree to an HTML string. Supports async component functions. */\nexport async function renderToString(root: VNode | null): Promise<string> {\n if (root === null) return \"\"\n // Each call gets a fresh isolated context stack and (optionally) store registry\n return withStoreContext(() => _contextAls.run([], () => renderNode(root)))\n}\n\n/**\n * Run an async function with a fresh, isolated context stack and store registry.\n * Useful when you need to call Pyreon APIs (e.g. useHead, prefetchLoaderData)\n * outside of renderToString but still want per-request isolation.\n */\nexport function runWithRequestContext<T>(fn: () => Promise<T>): Promise<T> {\n return withStoreContext(() => _contextAls.run([], fn))\n}\n\n/**\n * Render a VNode tree to a Web-standard ReadableStream of HTML chunks.\n *\n * True progressive streaming: HTML is flushed to the client as soon as each\n * node is ready. Synchronous subtrees are enqueued immediately; async component\n * boundaries are awaited in-order and their output is enqueued as it resolves.\n *\n * Suspense boundaries are streamed out-of-order: the fallback is emitted\n * immediately, and the resolved children are sent as a `<template>` + inline\n * swap script once ready — without blocking the rest of the page.\n *\n * Each renderToStream call gets its own isolated ALS context stack.\n */\nexport function renderToStream(root: VNode | null): ReadableStream<string> {\n return new ReadableStream<string>({\n start(controller) {\n const enqueue = (chunk: string) => controller.enqueue(chunk)\n let bid = 0\n const ctx: StreamCtx = {\n pending: [],\n nextId: () => bid++,\n mainEnqueue: enqueue,\n suspenseDepth: 0,\n }\n return withStoreContext(() =>\n _contextAls.run([], () =>\n _streamCtxAls\n .run(ctx, async () => {\n await streamNode(root, enqueue)\n // Drain all pending Suspense resolutions (may spawn nested ones)\n while (ctx.pending.length > 0) {\n await Promise.all(ctx.pending.splice(0))\n }\n controller.close()\n })\n .catch((err) => controller.error(err)),\n ),\n )\n },\n })\n}\n\n// ─── Streaming renderer ───────────────────────────────────────────────────────\n\nasync function streamVNode(vnode: VNode, enqueue: (s: string) => void): Promise<void> {\n if (vnode.type === Fragment) {\n for (const child of vnode.children) await streamNode(child, enqueue)\n return\n }\n\n if (vnode.type === (ForSymbol as unknown as string)) {\n const { each, children } = vnode.props as unknown as ForProps<unknown>\n enqueue(\"<!--pyreon-for-->\")\n for (const item of each()) await streamNode(children(item) as VNodeChild, enqueue)\n enqueue(\"<!--/pyreon-for-->\")\n return\n }\n\n if (typeof vnode.type === \"function\") {\n await streamComponentNode(vnode, enqueue)\n return\n }\n\n await streamElementNode(vnode, enqueue)\n}\n\nasync function streamComponentNode(vnode: VNode, enqueue: (s: string) => void): Promise<void> {\n if (vnode.type === Suspense) {\n await streamSuspenseBoundary(vnode, enqueue)\n return\n }\n try {\n const { vnode: output } = runWithHooks(vnode.type as ComponentFn, mergeChildrenIntoProps(vnode))\n const resolved = output instanceof Promise ? await output : output\n if (resolved !== null) await streamNode(resolved, enqueue)\n } catch (err) {\n if (__DEV__) {\n const name = (vnode.type as ComponentFn).name || \"Anonymous\"\n console.error(`[Pyreon SSR] Error rendering <${name}>:`, err)\n }\n // Inside a Suspense child resolution, re-throw so the boundary can catch and\n // suppress the swap (fallback stays visible). Outside Suspense, swallow the\n // error and emit a marker so the stream can continue.\n const ctx = _streamCtxAls.getStore()\n if (ctx && ctx.suspenseDepth > 0) throw err\n enqueue(\"<!--pyreon-error-->\")\n }\n}\n\nasync function streamElementNode(vnode: VNode, enqueue: (s: string) => void): Promise<void> {\n const tag = vnode.type as string\n let open = `<${tag}`\n const props = vnode.props as Record<string, unknown>\n for (const key in props) {\n const attr = renderProp(key, props[key])\n if (attr) open += ` ${attr}`\n }\n if (isVoidElement(tag)) {\n enqueue(`${open} />`)\n return\n }\n enqueue(`${open}>`)\n for (const child of vnode.children) await streamNode(child, enqueue)\n enqueue(`</${tag}>`)\n}\n\nasync function streamNode(\n node: VNodeChild | null | (() => VNodeChild),\n enqueue: (s: string) => void,\n): Promise<void> {\n if (typeof node === \"function\") {\n return streamNode((node as () => VNodeChild)(), enqueue)\n }\n if (node == null || node === false) return\n if (typeof node === \"string\") {\n enqueue(escapeHtml(node))\n return\n }\n if (typeof node === \"number\" || typeof node === \"boolean\") {\n enqueue(String(node))\n return\n }\n if (Array.isArray(node)) {\n for (const child of node) await streamNode(child, enqueue)\n return\n }\n\n await streamVNode(node as VNode, enqueue)\n}\n\n// Inline swap helper emitted once per stream, before the first <template>\nconst SUSPENSE_SWAP_FN =\n \"<script>function __NS(s,t){var e=document.getElementById(s),l=document.getElementById(t);\" +\n \"if(e&&l){e.replaceWith(l.content.cloneNode(!0));l.remove()}}</script>\"\n\n/**\n * Stream a Suspense boundary: emit fallback immediately, then resolve children\n * asynchronously and emit them as a `<template>` + client-side swap.\n *\n * The actual children HTML is buffered until fully resolved, then emitted to the\n * main stream enqueue so it always arrives after the fallback placeholder.\n */\nasync function streamSuspenseBoundary(vnode: VNode, enqueue: (s: string) => void): Promise<void> {\n const ctx = _streamCtxAls.getStore()\n const { fallback, children } = vnode.props as { fallback: VNodeChild; children?: VNodeChild }\n\n // No streaming context (e.g. called from renderToString) — render children inline\n if (!ctx) {\n const { vnode: output } = runWithHooks(Suspense as ComponentFn, vnode.props)\n if (output !== null) await streamNode(output, enqueue)\n return\n }\n\n const id = ctx.nextId()\n const { mainEnqueue } = ctx\n\n // Emit the swap helper function once (before first use)\n if (id === 0) mainEnqueue(SUSPENSE_SWAP_FN)\n\n // Stream the fallback synchronously (no await on children)\n mainEnqueue(`<div id=\"pyreon-s-${id}\">`)\n await streamNode(fallback ?? null, enqueue)\n mainEnqueue(\"</div>\")\n\n // Capture the context store for the async resolution so it inherits context\n const ctxStore = _contextAls.getStore() ?? []\n\n // Queue async resolution — runs in parallel, emits to main stream when done\n // Errors are caught per-boundary so one failing Suspense doesn't abort the stream.\n ctx.pending.push(\n _contextAls.run(ctxStore, async () => {\n try {\n ctx.suspenseDepth++\n const buf: string[] = []\n await streamNode(children ?? null, (s) => buf.push(s))\n mainEnqueue(`<template id=\"pyreon-t-${id}\">${buf.join(\"\")}</template>`)\n mainEnqueue(`<script>__NS(\"pyreon-s-${id}\",\"pyreon-t-${id}\")</script>`)\n } catch (err) {\n if (__DEV__) {\n console.error(\n `[Pyreon SSR] Suspense boundary caught an error — fallback will remain:`,\n err,\n )\n }\n // Fallback stays visible — no swap script emitted\n } finally {\n ctx.suspenseDepth--\n }\n }),\n )\n}\n\n// ─── Core renderer ───────────────────────────────────────────────────────────\n\nasync function renderNode(node: VNodeChild | (() => VNodeChild)): Promise<string> {\n // Reactive accessor — call it synchronously (snapshot)\n if (typeof node === \"function\") {\n return renderNode((node as () => VNodeChild)())\n }\n\n if (node == null || node === false) return \"\"\n\n if (typeof node === \"string\") return escapeHtml(node)\n if (typeof node === \"number\" || typeof node === \"boolean\") return String(node)\n\n if (Array.isArray(node)) {\n let html = \"\"\n for (const child of node) html += await renderNode(child)\n return html\n }\n\n const vnode = node as VNode\n\n if (vnode.type === Fragment) {\n return renderChildren(vnode.children)\n }\n\n if (vnode.type === (ForSymbol as unknown as string)) {\n const { each, children } = vnode.props as unknown as ForProps<unknown>\n let forHtml = \"<!--pyreon-for-->\"\n for (const item of each()) forHtml += await renderNode(children(item) as VNodeChild)\n forHtml += \"<!--/pyreon-for-->\"\n return forHtml\n }\n\n if (typeof vnode.type === \"function\") {\n return renderComponent(vnode as VNode & { type: ComponentFn })\n }\n\n return renderElement(vnode)\n}\n\nasync function renderChildren(children: VNodeChild[]): Promise<string> {\n let html = \"\"\n for (const child of children) html += await renderNode(child)\n return html\n}\n\nasync function renderComponent(vnode: VNode & { type: ComponentFn }): Promise<string> {\n const { vnode: output } = runWithHooks(vnode.type, mergeChildrenIntoProps(vnode))\n\n // Async component function (async function Component()) — await the promise\n if (output instanceof Promise) {\n const resolved = await output\n if (resolved === null) return \"\"\n return renderNode(resolved)\n }\n\n if (output === null) return \"\"\n return renderNode(output)\n}\n\nasync function renderElement(vnode: VNode): Promise<string> {\n const tag = vnode.type as string\n let html = `<${tag}`\n\n const props = vnode.props as Record<string, unknown>\n for (const key in props) {\n const attr = renderProp(key, props[key])\n if (attr) html += ` ${attr}`\n }\n\n if (isVoidElement(tag)) {\n html += \" />\"\n return html\n }\n\n html += \">\"\n\n for (const child of vnode.children) {\n html += await renderNode(child)\n }\n\n html += `</${tag}>`\n return html\n}\n\nconst SSR_URL_ATTRS = new Set([\"href\", \"src\", \"action\", \"formaction\", \"poster\", \"cite\", \"data\"])\nconst SSR_UNSAFE_URL_RE = /^\\s*(?:javascript|data):/i\n\nfunction renderPropSkipped(key: string): boolean {\n if (key === \"key\" || key === \"ref\") return true\n if (/^on[A-Z]/.test(key)) return true\n return false\n}\n\nfunction renderPropValue(key: string, value: unknown): string | null {\n if (value === null || value === undefined || value === false) return null\n if (value === true) return escapeHtml(toAttrName(key))\n\n if (key === \"class\") {\n const cls = cx(value as ClassValue)\n return cls ? `class=\"${escapeHtml(cls)}\"` : null\n }\n\n if (key === \"style\") {\n const style = normalizeStyle(value)\n return style ? `style=\"${escapeHtml(style)}\"` : null\n }\n\n return `${escapeHtml(toAttrName(key))}=\"${escapeHtml(String(value))}\"`\n}\n\nfunction renderProp(key: string, value: unknown): string | null {\n if (renderPropSkipped(key)) return null\n\n if (typeof value === \"function\") {\n return renderProp(key, (value as () => unknown)())\n }\n\n if (SSR_URL_ATTRS.has(key) && typeof value === \"string\" && SSR_UNSAFE_URL_RE.test(value)) {\n return null\n }\n\n return renderPropValue(key, value)\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nconst VOID_ELEMENTS = new Set([\n \"area\",\n \"base\",\n \"br\",\n \"col\",\n \"embed\",\n \"hr\",\n \"img\",\n \"input\",\n \"link\",\n \"meta\",\n \"param\",\n \"source\",\n \"track\",\n \"wbr\",\n])\n\nfunction isVoidElement(tag: string): boolean {\n return VOID_ELEMENTS.has(tag.toLowerCase())\n}\n\n/** camelCase prop → kebab-case HTML attribute (e.g. className → class, htmlFor → for) */\nfunction toAttrName(key: string): string {\n if (key === \"className\") return \"class\"\n if (key === \"htmlFor\") return \"for\"\n return key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)\n}\n\nfunction normalizeStyle(value: unknown): string {\n if (typeof value === \"string\") return value\n if (typeof value === \"object\" && value !== null) {\n return Object.entries(value as Record<string, unknown>)\n .map(([k, v]) => `${toKebab(k)}: ${normalizeStyleValue(k, v)}`)\n .join(\"; \")\n }\n return \"\"\n}\n\nfunction toKebab(str: string): string {\n return str.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)\n}\n\nconst ESCAPE_MAP: Record<string, string> = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': \"&quot;\",\n \"'\": \"&#39;\",\n}\n\n// Fast test — most strings in SSR have no special chars (tag names, class names, etc.)\nconst NEEDS_ESCAPE_RE = /[&<>\"']/\n\nfunction escapeHtml(str: string): string {\n if (!NEEDS_ESCAPE_RE.test(str)) return str\n return str.replace(/[&<>\"']/g, (c) => ESCAPE_MAP[c] ?? c)\n}\n\n/**\n * Merge vnode.children into props.children for component rendering.\n * Matches the behavior of mount.ts and hydrate.ts so components can\n * access children passed via h(Comp, props, child1, child2).\n */\nfunction mergeChildrenIntoProps(vnode: VNode): Record<string, unknown> {\n if (\n vnode.children.length > 0 &&\n (vnode.props as Record<string, unknown>).children === undefined\n ) {\n return {\n ...vnode.props,\n children: vnode.children.length === 1 ? vnode.children[0] : vnode.children,\n }\n }\n return vnode.props as Record<string, unknown>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,MAAM,UAAU,OAAO,YAAY,eAAe,QAAQ,IAAI,aAAa;AAa3E,MAAM,gBAAgB,IAAI,mBAA8B;AAMxD,MAAM,cAAc,IAAI,mBAA2C;AACnE,MAAM,iBAAyC,EAAE;AAEjD,8BAA8B,YAAY,UAAU,IAAI,eAAe;AAMvE,MAAM,YAAY,IAAI,mBAAyC;AAC/D,IAAI,wBAAwB;;;;;;;;;AAU5B,SAAgB,wBACd,0BACM;AACN,gCAA+B,UAAU,UAAU,oBAAI,IAAI,KAAK,CAAC;AACjE,yBAAwB;;;AAI1B,SAAS,iBAAoB,IAAgB;AAC3C,KAAI,CAAC,sBAAuB,QAAO,IAAI;AACvC,QAAO,UAAU,oBAAI,IAAI,KAAK,EAAE,GAAG;;;AAMrC,eAAsB,eAAe,MAAqC;AACxE,KAAI,SAAS,KAAM,QAAO;AAE1B,QAAO,uBAAuB,YAAY,IAAI,EAAE,QAAQ,WAAW,KAAK,CAAC,CAAC;;;;;;;AAQ5E,SAAgB,sBAAyB,IAAkC;AACzE,QAAO,uBAAuB,YAAY,IAAI,EAAE,EAAE,GAAG,CAAC;;;;;;;;;;;;;;;AAgBxD,SAAgB,eAAe,MAA4C;A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AAM,aAAqC;CACzC,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAK;CACL,KAAK;CACN;AAGD,MAAM,kBAAkB;AAExB,SAAS,WAAW,KAAqB;AACvC,KAAI,CAAC,gBAAgB,KAAK,IAAI,CAAE,QAAO;AACvC,QAAO,IAAI,QAAQ,aAAa,MAAM,WAAW,MAAM,EAAE;;;;;;;AAQ3D,SAAS,uBAAuB,OAAuC;AACrE,KACE,MAAM,SAAS,SAAS,KACvB,MAAM,MAAkC,aAAa,OAEtD,QAAO;EACL,GAAG,MAAM;EACT,UAAU,MAAM,SAAS,WAAW,IAAI,MAAM,SAAS,KAAK,MAAM;EACnE;AAEH,QAAO,MAAM"}
@@ -1 +1 @@
1
- {"version":3,"file":"index2.d.ts","names":[],"sources":["../../../src/index.ts"],"mappings":";;;;;;;;;AAyFA;;iBA3BgB,uBAAA,CACd,wBAAA,GAA2B,EAAA,QAAU,GAAA;;iBAejB,cAAA,CAAe,IAAA,EAAM,KAAA,UAAe,OAAA;;;;;;iBAW1C,qBAAA,GAAA,CAAyB,EAAA,QAAU,OAAA,CAAQ,CAAA,IAAK,OAAA,CAAQ,CAAA;;;;;;;AAiBxE;;;;;;;iBAAgB,cAAA,CAAe,IAAA,EAAM,KAAA,UAAe,cAAA"}
1
+ {"version":3,"file":"index2.d.ts","names":[],"sources":["../../../src/index.ts"],"mappings":";;;;;;;;;AA6FA;;iBA3BgB,uBAAA,CACd,wBAAA,GAA2B,EAAA,QAAU,GAAA;;iBAejB,cAAA,CAAe,IAAA,EAAM,KAAA,UAAe,OAAA;;;;;;iBAW1C,qBAAA,GAAA,CAAyB,EAAA,QAAU,OAAA,CAAQ,CAAA,IAAK,OAAA,CAAQ,CAAA;;;;;;;AAiBxE;;;;;;;iBAAgB,cAAA,CAAe,IAAA,EAAM,KAAA,UAAe,cAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pyreon/runtime-server",
3
- "version": "0.7.12",
3
+ "version": "0.7.14",
4
4
  "description": "SSR/SSG renderer for Pyreon — streaming HTML + static generation",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -39,8 +39,8 @@
39
39
  "prepublishOnly": "bun run build"
40
40
  },
41
41
  "dependencies": {
42
- "@pyreon/core": "^0.7.12",
43
- "@pyreon/reactivity": "^0.7.12"
42
+ "@pyreon/core": "^0.7.14",
43
+ "@pyreon/reactivity": "^0.7.14"
44
44
  },
45
45
  "publishConfig": {
46
46
  "access": "public"
package/src/index.ts CHANGED
@@ -25,6 +25,8 @@ import {
25
25
  setContextStackProvider,
26
26
  } from "@pyreon/core"
27
27
 
28
+ const __DEV__ = typeof process !== "undefined" && process.env.NODE_ENV !== "production"
29
+
28
30
  // ─── Streaming Suspense context ───────────────────────────────────────────────
29
31
  // Tracks in-flight async Suspense boundary resolutions within a single stream.
30
32
 
@@ -32,6 +34,8 @@ interface StreamCtx {
32
34
  pending: Promise<void>[]
33
35
  nextId: () => number
34
36
  mainEnqueue: (s: string) => void
37
+ /** Depth counter — non-zero when rendering inside a Suspense child resolution. */
38
+ suspenseDepth: number
35
39
  }
36
40
 
37
41
  const _streamCtxAls = new AsyncLocalStorage<StreamCtx>()
@@ -113,6 +117,7 @@ export function renderToStream(root: VNode | null): ReadableStream<string> {
113
117
  pending: [],
114
118
  nextId: () => bid++,
115
119
  mainEnqueue: enqueue,
120
+ suspenseDepth: 0,
116
121
  }
117
122
  return withStoreContext(() =>
118
123
  _contextAls.run([], () =>
@@ -161,9 +166,22 @@ async function streamComponentNode(vnode: VNode, enqueue: (s: string) => void):
161
166
  await streamSuspenseBoundary(vnode, enqueue)
162
167
  return
163
168
  }
164
- const { vnode: output } = runWithHooks(vnode.type as ComponentFn, mergeChildrenIntoProps(vnode))
165
- const resolved = output instanceof Promise ? await output : output
166
- if (resolved !== null) await streamNode(resolved, enqueue)
169
+ try {
170
+ const { vnode: output } = runWithHooks(vnode.type as ComponentFn, mergeChildrenIntoProps(vnode))
171
+ const resolved = output instanceof Promise ? await output : output
172
+ if (resolved !== null) await streamNode(resolved, enqueue)
173
+ } catch (err) {
174
+ if (__DEV__) {
175
+ const name = (vnode.type as ComponentFn).name || "Anonymous"
176
+ console.error(`[Pyreon SSR] Error rendering <${name}>:`, err)
177
+ }
178
+ // Inside a Suspense child resolution, re-throw so the boundary can catch and
179
+ // suppress the swap (fallback stays visible). Outside Suspense, swallow the
180
+ // error and emit a marker so the stream can continue.
181
+ const ctx = _streamCtxAls.getStore()
182
+ if (ctx && ctx.suspenseDepth > 0) throw err
183
+ enqueue("<!--pyreon-error-->")
184
+ }
167
185
  }
168
186
 
169
187
  async function streamElementNode(vnode: VNode, enqueue: (s: string) => void): Promise<void> {
@@ -249,12 +267,21 @@ async function streamSuspenseBoundary(vnode: VNode, enqueue: (s: string) => void
249
267
  ctx.pending.push(
250
268
  _contextAls.run(ctxStore, async () => {
251
269
  try {
270
+ ctx.suspenseDepth++
252
271
  const buf: string[] = []
253
272
  await streamNode(children ?? null, (s) => buf.push(s))
254
273
  mainEnqueue(`<template id="pyreon-t-${id}">${buf.join("")}</template>`)
255
274
  mainEnqueue(`<script>__NS("pyreon-s-${id}","pyreon-t-${id}")</script>`)
256
- } catch (_err) {
275
+ } catch (err) {
276
+ if (__DEV__) {
277
+ console.error(
278
+ `[Pyreon SSR] Suspense boundary caught an error — fallback will remain:`,
279
+ err,
280
+ )
281
+ }
257
282
  // Fallback stays visible — no swap script emitted
283
+ } finally {
284
+ ctx.suspenseDepth--
258
285
  }
259
286
  }),
260
287
  )
@@ -888,14 +888,13 @@ describe("renderToStream — error handling", () => {
888
888
  return result
889
889
  }
890
890
 
891
- test("stream errors when component throws", async () => {
891
+ test("stream emits error comment when component throws outside Suspense", async () => {
892
892
  function Boom(): VNode {
893
893
  throw new Error("render error")
894
894
  }
895
895
 
896
- const stream = renderToStream(h(Boom as ComponentFn, null))
897
- const reader = stream.getReader()
898
- await expect(reader.read()).rejects.toThrow("render error")
896
+ const html = await collectStream(renderToStream(h(Boom as ComponentFn, null)))
897
+ expect(html).toContain("<!--pyreon-error-->")
899
898
  })
900
899
 
901
900
  test("stream renders element with skipped prop (event handler)", async () => {
@@ -933,3 +932,59 @@ describe("edge-case branches", () => {
933
932
  expect(typeof html).toBe("string")
934
933
  })
935
934
  })
935
+
936
+ // ─── renderToString — Suspense with async components ─────────────────────────
937
+
938
+ describe("renderToString — Suspense async paths", () => {
939
+ test("renderToString with Suspense waits for async component and renders inline", async () => {
940
+ async function AsyncData(): Promise<ReturnType<typeof h>> {
941
+ await new Promise<void>((r) => setTimeout(r, 5))
942
+ return h("p", { id: "content" }, "loaded data")
943
+ }
944
+
945
+ const vnode = h(Suspense, {
946
+ fallback: h("span", null, "loading..."),
947
+ children: h(AsyncData as unknown as ComponentFn, null),
948
+ })
949
+
950
+ const html = await renderToString(vnode)
951
+ // The async content should be present (renderToString awaits async components)
952
+ expect(html).toContain("loaded data")
953
+ })
954
+
955
+ test("renderToString with Suspense where async component throws propagates error", async () => {
956
+ async function FailingComponent(): Promise<ReturnType<typeof h>> {
957
+ await new Promise<void>((r) => setTimeout(r, 1))
958
+ throw new Error("SSR component failure")
959
+ }
960
+
961
+ const vnode = h(Suspense, {
962
+ fallback: h("span", null, "fallback"),
963
+ children: h(FailingComponent as unknown as ComponentFn, null),
964
+ })
965
+
966
+ // renderToString does not catch per-boundary — the error propagates
967
+ await expect(renderToString(vnode)).rejects.toThrow("SSR component failure")
968
+ })
969
+ })
970
+
971
+ describe("renderToStream — Suspense error fallback", () => {
972
+ test("renderToStream keeps fallback visible when async component throws", async () => {
973
+ async function ThrowingChild(): Promise<ReturnType<typeof h>> {
974
+ await new Promise<void>((r) => setTimeout(r, 5))
975
+ throw new Error("stream component error")
976
+ }
977
+
978
+ const vnode = h(Suspense, {
979
+ fallback: h("span", { id: "fb" }, "fallback content"),
980
+ children: h(ThrowingChild as unknown as ComponentFn, null),
981
+ })
982
+
983
+ const html = await collectStream(renderToStream(vnode))
984
+ // Fallback should be present
985
+ expect(html).toContain("fallback content")
986
+ // No swap script invocation should be emitted (error was caught, no template + swap)
987
+ expect(html).not.toContain("pyreon-t-")
988
+ expect(html).not.toContain('__NS("pyreon-s-')
989
+ })
990
+ })