@tanstack/redact 0.0.9 → 0.0.11

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.
@@ -8,6 +8,7 @@ import {
8
8
  } from "./dispatcher";
9
9
  import { walk } from "./walk";
10
10
  import { BOUNDARY_REVEAL_RUNTIME, revealScript } from "./bootstrap-script";
11
+ import { escapeScript } from "./escape";
11
12
  async function streamHtml(children, emit, options, state) {
12
13
  installSSRDispatcher();
13
14
  beginSSR(options.identifierPrefix);
@@ -18,14 +19,36 @@ async function streamHtml(children, emit, options, state) {
18
19
  const bufferedEmit = (chunk) => {
19
20
  shellChunks.push(chunk);
20
21
  };
21
- walk(children, {
22
- emit: bufferedEmit,
23
- onSuspend: (b) => boundaries.push(b),
24
- nextBoundaryId: () => state.nextId++
25
- });
26
- const hasBootstrap = (options.bootstrapScripts?.length ?? 0) > 0 || (options.bootstrapModules?.length ?? 0) > 0;
22
+ let shellRendered = false;
23
+ let rootRetries = 0;
24
+ while (!shellRendered) {
25
+ const chunkCount = shellChunks.length;
26
+ const boundaryCount = boundaries.length;
27
+ const nextId = state.nextId;
28
+ try {
29
+ walk(children, {
30
+ emit: bufferedEmit,
31
+ onSuspend: (b) => boundaries.push(b),
32
+ nextBoundaryId: () => state.nextId++
33
+ });
34
+ shellRendered = true;
35
+ } catch (err) {
36
+ shellChunks.length = chunkCount;
37
+ boundaries.length = boundaryCount;
38
+ state.nextId = nextId;
39
+ if (!isThenable(err)) throw err;
40
+ if (++rootRetries > 50) {
41
+ throw new Error("renderToReadableStream exceeded 50 root suspension retries.");
42
+ }
43
+ await err;
44
+ }
45
+ }
46
+ const hasBootstrap = bootstrapScriptContentToArray(options.bootstrapScriptContent).length > 0 || (options.bootstrapScripts?.length ?? 0) > 0 || (options.bootstrapModules?.length ?? 0) > 0;
27
47
  if (boundaries.length > 0 || hasBootstrap) {
28
48
  shellChunks.push(`<script${nonce ? ` nonce="${nonce}"` : ""}>${BOUNDARY_REVEAL_RUNTIME}<\/script>`);
49
+ for (const content of bootstrapScriptContentToArray(options.bootstrapScriptContent)) {
50
+ shellChunks.push(inlineBootstrapTag(content, nonce));
51
+ }
29
52
  for (const s of options.bootstrapScripts ?? []) {
30
53
  shellChunks.push(bootstrapTag(s, "script", nonce));
31
54
  }
@@ -33,7 +56,7 @@ async function streamHtml(children, emit, options, state) {
33
56
  shellChunks.push(bootstrapTag(m, "module", nonce));
34
57
  }
35
58
  }
36
- if (shellChunks.length) emit(shellChunks.join(""));
59
+ if (shellChunks.length) emit(normalizeDocumentShell(shellChunks.join("")));
37
60
  for (const b of boundaries) streamBoundary(b, emit, options, state);
38
61
  await drain(state);
39
62
  } catch (err) {
@@ -80,6 +103,48 @@ async function drain(state) {
80
103
  await Promise.race(state.pending);
81
104
  }
82
105
  }
106
+ function isThenable(value) {
107
+ return !!value && typeof value.then === "function";
108
+ }
109
+ function bootstrapScriptContentToArray(content) {
110
+ if (content === void 0) return [];
111
+ return typeof content === "string" ? [content] : [...content];
112
+ }
113
+ function inlineBootstrapTag(content, defaultNonce) {
114
+ const nAttr = defaultNonce ? ` nonce="${defaultNonce}"` : "";
115
+ return `<script${nAttr}>${escapeScript(content)}<\/script>`;
116
+ }
117
+ function normalizeDocumentShell(html) {
118
+ const doctypeIndex = html.indexOf("<!DOCTYPE html><html");
119
+ if (doctypeIndex <= 0) return html;
120
+ const headPrefix = html.slice(0, doctypeIndex);
121
+ if (!isHeadPrefix(headPrefix)) return html;
122
+ const documentHtml = html.slice(doctypeIndex);
123
+ const headOpen = documentHtml.match(/<head(?:\s[^>]*)?>/);
124
+ if (!headOpen || headOpen.index === void 0) return html;
125
+ const insertAt = headOpen.index + headOpen[0].length;
126
+ return documentHtml.slice(0, insertAt) + headPrefix + documentHtml.slice(insertAt);
127
+ }
128
+ function isHeadPrefix(value) {
129
+ if (!value) return false;
130
+ return stripLeadingHeadTags(value).trim() === "";
131
+ }
132
+ function stripLeadingHeadTags(value) {
133
+ let rest = value;
134
+ let changed = true;
135
+ while (changed) {
136
+ changed = false;
137
+ const next = rest.replace(
138
+ /^\s*(?:<meta\b[^>]*>|<link\b[^>]*>|<base\b[^>]*>|<title\b[^>]*>[\s\S]*?<\/title>|<style\b[^>]*>[\s\S]*?<\/style>|<script\b[^>]*>[\s\S]*?<\/script>)/i,
139
+ ""
140
+ );
141
+ if (next !== rest) {
142
+ rest = next;
143
+ changed = true;
144
+ }
145
+ }
146
+ return rest;
147
+ }
83
148
  function bootstrapTag(entry, kind, defaultNonce) {
84
149
  const src = typeof entry === "string" ? entry : entry.src;
85
150
  const nonce = typeof entry === "string" ? defaultNonce : entry.nonce ?? defaultNonce;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/server/stream.ts"],
4
- "sourcesContent": ["import type { ReactNode } from '../core'\nimport {\n beginSSR,\n endSSR,\n installSSRDispatcher,\n uninstallSSRDispatcher,\n applyContextSnapshot,\n} from './dispatcher'\nimport { walk, type SuspendedBoundary } from './walk'\nimport { BOUNDARY_REVEAL_RUNTIME, revealScript } from './bootstrap-script'\n\nexport interface StreamOptions {\n identifierPrefix?: string\n nonce?: string\n bootstrapScripts?: ReadonlyArray<string | { src: string; async?: boolean; nonce?: string }>\n bootstrapModules?: ReadonlyArray<string | { src: string; nonce?: string }>\n onError?: (error: unknown) => string | void\n signal?: AbortSignal\n progressiveChunkSize?: number\n}\n\nexport interface ReadableStreamResult extends ReadableStream<Uint8Array> {\n allReady: Promise<void>\n}\n\nexport interface OrchestratorState {\n nextId: number\n pending: Set<Promise<void>>\n closed: boolean\n errored: unknown | null\n}\n\ntype Emit = (chunk: string) => void\n\nexport async function streamHtml(\n children: ReactNode,\n emit: Emit,\n options: StreamOptions,\n state: OrchestratorState,\n): Promise<void> {\n installSSRDispatcher()\n beginSSR(options.identifierPrefix)\n const nonce = options.nonce\n\n try {\n const boundaries: SuspendedBoundary[] = []\n\n // Buffer shell + bootstrap into a string[] and flush as a single emit.\n // Per-emit overhead in renderToReadableStream is TextEncoder.encode +\n // controller.enqueue \u2014 each walkHost normally fires 3+ emits (opening\n // tag, per-attribute, closing bracket), which for a ~30-component tree\n // is ~100 stream-controller round-trips. Batching collapses those into\n // one encode and one enqueue per shell \u2014 measured ~2-4% of total SSR\n // time on CPU profiles.\n const shellChunks: string[] = []\n const bufferedEmit: Emit = (chunk) => {\n shellChunks.push(chunk)\n }\n\n // 1. Render the shell\n walk(children, {\n emit: bufferedEmit,\n onSuspend: (b) => boundaries.push(b),\n nextBoundaryId: () => state.nextId++,\n })\n\n // 2. Inject runtime + bootstrap scripts (once, after shell). Skip the\n // reveal/event-replay runtime when nothing needs it \u2014 no suspensions to\n // reveal and no bootstrap scripts to guard against early user input. That\n // keeps fully-static SSR responses byte-equivalent to a plain walk and\n // matches React's behavior where `renderToReadableStream` of a static\n // tree emits only the markup.\n const hasBootstrap =\n (options.bootstrapScripts?.length ?? 0) > 0 ||\n (options.bootstrapModules?.length ?? 0) > 0\n if (boundaries.length > 0 || hasBootstrap) {\n shellChunks.push(`<script${nonce ? ` nonce=\"${nonce}\"` : ''}>${BOUNDARY_REVEAL_RUNTIME}</script>`)\n for (const s of options.bootstrapScripts ?? []) {\n shellChunks.push(bootstrapTag(s, 'script', nonce))\n }\n for (const m of options.bootstrapModules ?? []) {\n shellChunks.push(bootstrapTag(m, 'module', nonce))\n }\n }\n\n if (shellChunks.length) emit(shellChunks.join(''))\n\n // 3. Stream suspended boundaries as they resolve\n for (const b of boundaries) streamBoundary(b, emit, options, state)\n await drain(state)\n } catch (err) {\n state.errored = err\n if (options.onError) options.onError(err)\n throw err\n } finally {\n endSSR()\n uninstallSSRDispatcher()\n state.closed = true\n }\n}\n\nfunction streamBoundary(\n b: SuspendedBoundary,\n emit: Emit,\n options: StreamOptions,\n state: OrchestratorState,\n): void {\n const task = (async () => {\n try {\n await b.thenable\n } catch (err) {\n if (options.onError) options.onError(err)\n }\n if (state.closed) return\n\n // Re-render the boundary's children into a string, restoring the\n // provider stack from when the boundary first suspended.\n const parts: string[] = []\n const sub: SuspendedBoundary[] = []\n const restore = applyContextSnapshot(b.contextSnapshot)\n try {\n walk(b.children, {\n emit: (s) => parts.push(s),\n onSuspend: (n) => sub.push(n),\n nextBoundaryId: () => state.nextId++,\n })\n } catch (err) {\n if (options.onError) options.onError(err)\n restore()\n return\n }\n restore()\n\n emit(`<div hidden id=\"S:${b.id}\">${parts.join('')}</div>${revealScript(b.id, options.nonce)}`)\n\n // Recurse: any nested suspensions inside the now-revealed content\n for (const s of sub) streamBoundary(s, emit, options, state)\n })()\n state.pending.add(task)\n task.finally(() => state.pending.delete(task))\n}\n\nasync function drain(state: OrchestratorState): Promise<void> {\n while (state.pending.size > 0) {\n await Promise.race(state.pending)\n }\n}\n\nfunction bootstrapTag(\n entry: string | { src: string; async?: boolean; nonce?: string },\n kind: 'script' | 'module',\n defaultNonce: string | undefined,\n): string {\n const src = typeof entry === 'string' ? entry : entry.src\n const nonce = typeof entry === 'string' ? defaultNonce : entry.nonce ?? defaultNonce\n const nAttr = nonce ? ` nonce=\"${nonce}\"` : ''\n if (kind === 'module') return `<script type=\"module\"${nAttr} src=\"${src}\"></script>`\n return `<script async${nAttr} src=\"${src}\"></script>`\n}\n\n// ---------------------------------------------------------------------------\n// Web Streams: renderToReadableStream\n// ---------------------------------------------------------------------------\n\nexport function renderToReadableStream(\n children: ReactNode,\n options: StreamOptions = {},\n): Promise<ReadableStreamResult> {\n const state: OrchestratorState = {\n nextId: 0,\n pending: new Set(),\n closed: false,\n errored: null,\n }\n const encoder = new TextEncoder()\n\n let allReadyResolve!: () => void\n let allReadyReject!: (e: unknown) => void\n const allReady = new Promise<void>((r, rej) => {\n allReadyResolve = r\n allReadyReject = rej\n })\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n const emit = (chunk: string) => {\n try {\n controller.enqueue(encoder.encode(chunk))\n } catch {}\n }\n\n streamHtml(children, emit, options, state).then(\n () => {\n try {\n controller.close()\n } catch {}\n allReadyResolve()\n },\n (err) => {\n try {\n controller.error(err)\n } catch {}\n allReadyReject(err)\n },\n )\n\n options.signal?.addEventListener('abort', () => {\n state.closed = true\n try {\n controller.close()\n } catch {}\n })\n },\n })\n\n return Promise.resolve(Object.assign(stream, { allReady }))\n}\n\n// ---------------------------------------------------------------------------\n// Node Streams: renderToPipeableStream\n// ---------------------------------------------------------------------------\n\nexport interface PipeableHandle {\n pipe<T extends NodeJS.WritableStream>(dest: T): T\n abort(reason?: unknown): void\n}\n\nexport interface PipeableOptions extends StreamOptions {\n onShellReady?: () => void\n onShellError?: (err: unknown) => void\n onAllReady?: () => void\n}\n\nexport function renderToPipeableStream(\n children: ReactNode,\n options: PipeableOptions = {},\n): PipeableHandle {\n const state: OrchestratorState = {\n nextId: 0,\n pending: new Set(),\n closed: false,\n errored: null,\n }\n\n const buffers: string[] = []\n let dest: NodeJS.WritableStream | null = null\n let shellReady = false\n let finished = false\n let aborted = false\n\n const flushTo = (w: NodeJS.WritableStream) => {\n if (!buffers.length) return\n for (const b of buffers) w.write(b)\n buffers.length = 0\n }\n\n const emit: Emit = (chunk) => {\n if (aborted || finished) return\n if (dest) dest.write(chunk)\n else buffers.push(chunk)\n }\n\n // Kick off rendering\n streamHtml(children, emit, options, state).then(\n () => {\n finished = true\n if (dest) dest.end()\n options.onAllReady?.()\n },\n (err) => {\n if (!shellReady) {\n options.onShellError?.(err)\n } else {\n options.onError?.(err)\n if (dest) dest.end()\n }\n },\n )\n\n // We call onShellReady once the first synchronous emit has landed.\n // streamHtml above runs the shell synchronously before the first await in drain(),\n // so we can schedule onShellReady right after the first microtask.\n queueMicrotask(() => {\n if (aborted || finished) return\n shellReady = true\n options.onShellReady?.()\n })\n\n return {\n pipe<T extends NodeJS.WritableStream>(target: T): T {\n dest = target\n flushTo(target)\n if (finished) target.end()\n return target\n },\n abort(_reason?: unknown) {\n aborted = true\n state.closed = true\n if (dest) dest.end()\n },\n }\n}\n"],
5
- "mappings": ";AACA;AAAA,EACE;AAAA,E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AI,aAAa;AACjB,MAAI,WAAW;AACf,MAAI,UAAU;AAEd,QAAM,UAAU,CAAC,MAA6B;AAC5C,QAAI,CAAC,QAAQ,OAAQ;AACrB,eAAW,KAAK,QAAS,GAAE,MAAM,CAAC;AAClC,YAAQ,SAAS;AAAA,EACnB;AAEA,QAAM,OAAa,CAAC,UAAU;AAC5B,QAAI,WAAW,SAAU;AACzB,QAAI,KAAM,MAAK,MAAM,KAAK;AAAA,QACrB,SAAQ,KAAK,KAAK;AAAA,EACzB;AAGA,aAAW,UAAU,MAAM,SAAS,KAAK,EAAE;AAAA,IACzC,MAAM;AACJ,iBAAW;AACX,UAAI,KAAM,MAAK,IAAI;AACnB,cAAQ,aAAa;AAAA,IACvB;AAAA,IACA,CAAC,QAAQ;AACP,UAAI,CAAC,YAAY;AACf,gBAAQ,eAAe,GAAG;AAAA,MAC5B,OAAO;AACL,gBAAQ,UAAU,GAAG;AACrB,YAAI,KAAM,MAAK,IAAI;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AAKA,iBAAe,MAAM;AACnB,QAAI,WAAW,SAAU;AACzB,iBAAa;AACb,YAAQ,eAAe;AAAA,EACzB,CAAC;AAED,SAAO;AAAA,IACL,KAAsC,QAAc;AAClD,aAAO;AACP,cAAQ,MAAM;AACd,UAAI,SAAU,QAAO,IAAI;AACzB,aAAO;AAAA,IACT;AAAA,IACA,MAAM,SAAmB;AACvB,gBAAU;AACV,YAAM,SAAS;AACf,UAAI,KAAM,MAAK,IAAI;AAAA,IACrB;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { ReactNode } from '../core'\nimport {\n beginSSR,\n endSSR,\n installSSRDispatcher,\n uninstallSSRDispatcher,\n applyContextSnapshot,\n} from './dispatcher'\nimport { walk, type SuspendedBoundary } from './walk'\nimport { BOUNDARY_REVEAL_RUNTIME, revealScript } from './bootstrap-script'\nimport { escapeScript } from './escape'\n\nexport interface StreamOptions {\n identifierPrefix?: string\n nonce?: string\n bootstrapScriptContent?: string | ReadonlyArray<string>\n bootstrapScripts?: ReadonlyArray<string | { src: string; async?: boolean; nonce?: string }>\n bootstrapModules?: ReadonlyArray<string | { src: string; nonce?: string }>\n onError?: (error: unknown) => string | void\n signal?: AbortSignal\n progressiveChunkSize?: number\n}\n\nexport interface ReadableStreamResult extends ReadableStream<Uint8Array> {\n allReady: Promise<void>\n}\n\nexport interface OrchestratorState {\n nextId: number\n pending: Set<Promise<void>>\n closed: boolean\n errored: unknown | null\n}\n\ntype Emit = (chunk: string) => void\n\nexport async function streamHtml(\n children: ReactNode,\n emit: Emit,\n options: StreamOptions,\n state: OrchestratorState,\n): Promise<void> {\n installSSRDispatcher()\n beginSSR(options.identifierPrefix)\n const nonce = options.nonce\n\n try {\n const boundaries: SuspendedBoundary[] = []\n\n // Buffer shell + bootstrap into a string[] and flush as a single emit.\n // Per-emit overhead in renderToReadableStream is TextEncoder.encode +\n // controller.enqueue \u2014 each walkHost normally fires 3+ emits (opening\n // tag, per-attribute, closing bracket), which for a ~30-component tree\n // is ~100 stream-controller round-trips. Batching collapses those into\n // one encode and one enqueue per shell \u2014 measured ~2-4% of total SSR\n // time on CPU profiles.\n const shellChunks: string[] = []\n const bufferedEmit: Emit = (chunk) => {\n shellChunks.push(chunk)\n }\n\n // 1. Render the shell. A root-level `use(promise)` has no Suspense\n // boundary to capture it, but App Router SSR commonly suspends at this\n // level while resolving the RSC stream. Wait and retry without leaking\n // partial shell chunks or boundary ids from the aborted attempt.\n let shellRendered = false\n let rootRetries = 0\n while (!shellRendered) {\n const chunkCount = shellChunks.length\n const boundaryCount = boundaries.length\n const nextId = state.nextId\n try {\n walk(children, {\n emit: bufferedEmit,\n onSuspend: (b) => boundaries.push(b),\n nextBoundaryId: () => state.nextId++,\n })\n shellRendered = true\n } catch (err) {\n shellChunks.length = chunkCount\n boundaries.length = boundaryCount\n state.nextId = nextId\n if (!isThenable(err)) throw err\n if (++rootRetries > 50) {\n throw new Error('renderToReadableStream exceeded 50 root suspension retries.')\n }\n await err\n }\n }\n\n // 2. Inject runtime + bootstrap scripts (once, after shell). Skip the\n // reveal/event-replay runtime when nothing needs it \u2014 no suspensions to\n // reveal and no bootstrap scripts to guard against early user input. That\n // keeps fully-static SSR responses byte-equivalent to a plain walk and\n // matches React's behavior where `renderToReadableStream` of a static\n // tree emits only the markup.\n const hasBootstrap =\n bootstrapScriptContentToArray(options.bootstrapScriptContent).length > 0 ||\n (options.bootstrapScripts?.length ?? 0) > 0 ||\n (options.bootstrapModules?.length ?? 0) > 0\n if (boundaries.length > 0 || hasBootstrap) {\n shellChunks.push(`<script${nonce ? ` nonce=\"${nonce}\"` : ''}>${BOUNDARY_REVEAL_RUNTIME}</script>`)\n for (const content of bootstrapScriptContentToArray(options.bootstrapScriptContent)) {\n shellChunks.push(inlineBootstrapTag(content, nonce))\n }\n for (const s of options.bootstrapScripts ?? []) {\n shellChunks.push(bootstrapTag(s, 'script', nonce))\n }\n for (const m of options.bootstrapModules ?? []) {\n shellChunks.push(bootstrapTag(m, 'module', nonce))\n }\n }\n\n if (shellChunks.length) emit(normalizeDocumentShell(shellChunks.join('')))\n\n // 3. Stream suspended boundaries as they resolve\n for (const b of boundaries) streamBoundary(b, emit, options, state)\n await drain(state)\n } catch (err) {\n state.errored = err\n if (options.onError) options.onError(err)\n throw err\n } finally {\n endSSR()\n uninstallSSRDispatcher()\n state.closed = true\n }\n}\n\nfunction streamBoundary(\n b: SuspendedBoundary,\n emit: Emit,\n options: StreamOptions,\n state: OrchestratorState,\n): void {\n const task = (async () => {\n try {\n await b.thenable\n } catch (err) {\n if (options.onError) options.onError(err)\n }\n if (state.closed) return\n\n // Re-render the boundary's children into a string, restoring the\n // provider stack from when the boundary first suspended.\n const parts: string[] = []\n const sub: SuspendedBoundary[] = []\n const restore = applyContextSnapshot(b.contextSnapshot)\n try {\n walk(b.children, {\n emit: (s) => parts.push(s),\n onSuspend: (n) => sub.push(n),\n nextBoundaryId: () => state.nextId++,\n })\n } catch (err) {\n if (options.onError) options.onError(err)\n restore()\n return\n }\n restore()\n\n emit(`<div hidden id=\"S:${b.id}\">${parts.join('')}</div>${revealScript(b.id, options.nonce)}`)\n\n // Recurse: any nested suspensions inside the now-revealed content\n for (const s of sub) streamBoundary(s, emit, options, state)\n })()\n state.pending.add(task)\n task.finally(() => state.pending.delete(task))\n}\n\nasync function drain(state: OrchestratorState): Promise<void> {\n while (state.pending.size > 0) {\n await Promise.race(state.pending)\n }\n}\n\nfunction isThenable(value: unknown): value is Promise<unknown> {\n return !!value && typeof (value as { then?: unknown }).then === 'function'\n}\n\nfunction bootstrapScriptContentToArray(\n content: StreamOptions['bootstrapScriptContent'],\n): string[] {\n if (content === undefined) return []\n return typeof content === 'string' ? [content] : [...content]\n}\n\nfunction inlineBootstrapTag(content: string, defaultNonce: string | undefined): string {\n const nAttr = defaultNonce ? ` nonce=\"${defaultNonce}\"` : ''\n return `<script${nAttr}>${escapeScript(content)}</script>`\n}\n\nfunction normalizeDocumentShell(html: string): string {\n const doctypeIndex = html.indexOf('<!DOCTYPE html><html')\n if (doctypeIndex <= 0) return html\n\n const headPrefix = html.slice(0, doctypeIndex)\n if (!isHeadPrefix(headPrefix)) return html\n\n const documentHtml = html.slice(doctypeIndex)\n const headOpen = documentHtml.match(/<head(?:\\s[^>]*)?>/)\n if (!headOpen || headOpen.index === undefined) return html\n\n const insertAt = headOpen.index + headOpen[0].length\n return documentHtml.slice(0, insertAt) + headPrefix + documentHtml.slice(insertAt)\n}\n\nfunction isHeadPrefix(value: string): boolean {\n if (!value) return false\n return stripLeadingHeadTags(value).trim() === ''\n}\n\nfunction stripLeadingHeadTags(value: string): string {\n let rest = value\n let changed = true\n while (changed) {\n changed = false\n const next = rest.replace(\n /^\\s*(?:<meta\\b[^>]*>|<link\\b[^>]*>|<base\\b[^>]*>|<title\\b[^>]*>[\\s\\S]*?<\\/title>|<style\\b[^>]*>[\\s\\S]*?<\\/style>|<script\\b[^>]*>[\\s\\S]*?<\\/script>)/i,\n '',\n )\n if (next !== rest) {\n rest = next\n changed = true\n }\n }\n return rest\n}\n\nfunction bootstrapTag(\n entry: string | { src: string; async?: boolean; nonce?: string },\n kind: 'script' | 'module',\n defaultNonce: string | undefined,\n): string {\n const src = typeof entry === 'string' ? entry : entry.src\n const nonce = typeof entry === 'string' ? defaultNonce : entry.nonce ?? defaultNonce\n const nAttr = nonce ? ` nonce=\"${nonce}\"` : ''\n if (kind === 'module') return `<script type=\"module\"${nAttr} src=\"${src}\"></script>`\n return `<script async${nAttr} src=\"${src}\"></script>`\n}\n\n// ---------------------------------------------------------------------------\n// Web Streams: renderToReadableStream\n// ---------------------------------------------------------------------------\n\nexport function renderToReadableStream(\n children: ReactNode,\n options: StreamOptions = {},\n): Promise<ReadableStreamResult> {\n const state: OrchestratorState = {\n nextId: 0,\n pending: new Set(),\n closed: false,\n errored: null,\n }\n const encoder = new TextEncoder()\n\n let allReadyResolve!: () => void\n let allReadyReject!: (e: unknown) => void\n const allReady = new Promise<void>((r, rej) => {\n allReadyResolve = r\n allReadyReject = rej\n })\n\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n const emit = (chunk: string) => {\n try {\n controller.enqueue(encoder.encode(chunk))\n } catch {}\n }\n\n streamHtml(children, emit, options, state).then(\n () => {\n try {\n controller.close()\n } catch {}\n allReadyResolve()\n },\n (err) => {\n try {\n controller.error(err)\n } catch {}\n allReadyReject(err)\n },\n )\n\n options.signal?.addEventListener('abort', () => {\n state.closed = true\n try {\n controller.close()\n } catch {}\n })\n },\n })\n\n return Promise.resolve(Object.assign(stream, { allReady }))\n}\n\n// ---------------------------------------------------------------------------\n// Node Streams: renderToPipeableStream\n// ---------------------------------------------------------------------------\n\nexport interface PipeableHandle {\n pipe<T extends NodeJS.WritableStream>(dest: T): T\n abort(reason?: unknown): void\n}\n\nexport interface PipeableOptions extends StreamOptions {\n onShellReady?: () => void\n onShellError?: (err: unknown) => void\n onAllReady?: () => void\n}\n\nexport function renderToPipeableStream(\n children: ReactNode,\n options: PipeableOptions = {},\n): PipeableHandle {\n const state: OrchestratorState = {\n nextId: 0,\n pending: new Set(),\n closed: false,\n errored: null,\n }\n\n const buffers: string[] = []\n let dest: NodeJS.WritableStream | null = null\n let shellReady = false\n let finished = false\n let aborted = false\n\n const flushTo = (w: NodeJS.WritableStream) => {\n if (!buffers.length) return\n for (const b of buffers) w.write(b)\n buffers.length = 0\n }\n\n const emit: Emit = (chunk) => {\n if (aborted || finished) return\n if (dest) dest.write(chunk)\n else buffers.push(chunk)\n }\n\n // Kick off rendering\n streamHtml(children, emit, options, state).then(\n () => {\n finished = true\n if (dest) dest.end()\n options.onAllReady?.()\n },\n (err) => {\n if (!shellReady) {\n options.onShellError?.(err)\n } else {\n options.onError?.(err)\n if (dest) dest.end()\n }\n },\n )\n\n // We call onShellReady once the first synchronous emit has landed.\n // streamHtml above runs the shell synchronously before the first await in drain(),\n // so we can schedule onShellReady right after the first microtask.\n queueMicrotask(() => {\n if (aborted || finished) return\n shellReady = true\n options.onShellReady?.()\n })\n\n return {\n pipe<T extends NodeJS.WritableStream>(target: T): T {\n dest = target\n flushTo(target)\n if (finished) target.end()\n return target\n },\n abort(_reason?: unknown) {\n aborted = true\n state.closed = true\n if (dest) dest.end()\n },\n }\n}\n"],
5
+ "mappings": ";AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAoC;AAC7C,SAAS,yBAAyB,oBAAoB;AACtD,SAAS,oBAAoB;AA0B7B,eAAsB,WACpB,UACA,MACA,SACA,OACe;AACf,uBAAqB;AACrB,WAAS,QAAQ,gBAAgB;AACjC,QAAM,QAAQ,QAAQ;AAEtB,MAAI;AACF,UAAM,aAAkC,CAAC;AASzC,UAAM,cAAwB,CAAC;AAC/B,UAAM,eAAqB,CAAC,UAAU;AACpC,kBAAY,KAAK,KAAK;AAAA,IACxB;AAMA,QAAI,gBAAgB;AACpB,QAAI,cAAc;AAClB,WAAO,CAAC,eAAe;AACrB,YAAM,aAAa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CAAC;AAC3B,MAAI,OAAqC;AACzC,MAAI,aAAa;AACjB,MAAI,WAAW;AACf,MAAI,UAAU;AAEd,QAAM,UAAU,CAAC,MAA6B;AAC5C,QAAI,CAAC,QAAQ,OAAQ;AACrB,eAAW,KAAK,QAAS,GAAE,MAAM,CAAC;AAClC,YAAQ,SAAS;AAAA,EACnB;AAEA,QAAM,OAAa,CAAC,UAAU;AAC5B,QAAI,WAAW,SAAU;AACzB,QAAI,KAAM,MAAK,MAAM,KAAK;AAAA,QACrB,SAAQ,KAAK,KAAK;AAAA,EACzB;AAGA,aAAW,UAAU,MAAM,SAAS,KAAK,EAAE;AAAA,IACzC,MAAM;AACJ,iBAAW;AACX,UAAI,KAAM,MAAK,IAAI;AACnB,cAAQ,aAAa;AAAA,IACvB;AAAA,IACA,CAAC,QAAQ;AACP,UAAI,CAAC,YAAY;AACf,gBAAQ,eAAe,GAAG;AAAA,MAC5B,OAAO;AACL,gBAAQ,UAAU,GAAG;AACrB,YAAI,KAAM,MAAK,IAAI;AAAA,MACrB;AAAA,IACF;AAAA,EACF;AAKA,iBAAe,MAAM;AACnB,QAAI,WAAW,SAAU;AACzB,iBAAa;AACb,YAAQ,eAAe;AAAA,EACzB,CAAC;AAED,SAAO;AAAA,IACL,KAAsC,QAAc;AAClD,aAAO;AACP,cAAQ,MAAM;AACd,UAAI,SAAU,QAAO,IAAI;AACzB,aAAO;AAAA,IACT;AAAA,IACA,MAAM,SAAmB;AACvB,gBAAU;AACV,YAAM,SAAS;AACf,UAAI,KAAM,MAAK,IAAI;AAAA,IACrB;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -196,6 +196,9 @@ function walkHost(tag, props, opts) {
196
196
  opts.emit(">");
197
197
  const parentTextState = opts.textState;
198
198
  const childOpts = { ...opts, textState: { lastWasText: false } };
199
+ if (tag === "html" && !hasHeadChild(props.children)) {
200
+ opts.emit("<head></head>");
201
+ }
199
202
  const dangerouslyHtml = props.dangerouslySetInnerHTML?.__html;
200
203
  if (isTextarea && textareaValue != null) {
201
204
  opts.emit(escapeText(String(textareaValue)));
@@ -227,6 +230,24 @@ function walkHost(tag, props, opts) {
227
230
  if (isSelect) popSelectContext();
228
231
  if (parentTextState) parentTextState.lastWasText = false;
229
232
  }
233
+ function hasHeadChild(children) {
234
+ if (children == null || typeof children === "boolean") return false;
235
+ if (Array.isArray(children)) return children.some(hasHeadChild);
236
+ if (typeof children !== "string" && isIterable(children)) {
237
+ for (const child of children) {
238
+ if (hasHeadChild(child)) return true;
239
+ }
240
+ return false;
241
+ }
242
+ return isElementOfType(children, "head");
243
+ }
244
+ function isElementOfType(value, type) {
245
+ const marker = value?.$$typeof;
246
+ return !!value && typeof value === "object" && (marker === REACT_ELEMENT_TYPE || marker === REACT_LEGACY_ELEMENT_TYPE) && value.type === type;
247
+ }
248
+ function isIterable(value) {
249
+ return !!value && typeof value[Symbol.iterator] === "function";
250
+ }
230
251
  function walkComponent(fn, props, opts) {
231
252
  if (fn.prototype?.isReactComponent) {
232
253
  const ctxType = fn.contextType;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/server/walk.ts"],
4
- "sourcesContent": ["import {\n REACT_ELEMENT_TYPE,\n REACT_LEGACY_ELEMENT_TYPE,\n REACT_FRAGMENT_TYPE,\n type ReactNode,\n type ReactElement,\n} from '../core'\nimport {\n REACT_SUSPENSE_TYPE,\n REACT_PROVIDER_TYPE,\n REACT_CONSUMER_TYPE,\n REACT_FORWARD_REF_TYPE,\n REACT_MEMO_TYPE,\n REACT_LAZY_TYPE,\n REACT_STRICT_MODE_TYPE,\n REACT_PROFILER_TYPE,\n REACT_PORTAL_TYPE,\n} from '../react'\nimport {\n attrToHtml,\n escapeText,\n escapeScript,\n VOID_ELEMENTS,\n RAW_TEXT_ELEMENTS,\n} from './escape'\nimport {\n pushContext,\n popContext,\n snapshotContexts,\n type ContextSnapshot,\n} from './dispatcher'\n\nexport interface SuspendedBoundary {\n id: number\n fallbackHTML: string\n children: ReactNode\n thenable: Promise<any>\n contextSnapshot: ContextSnapshot\n}\n\nexport interface WalkOptions {\n emit: (chunk: string) => void\n onSuspend?: ((boundary: SuspendedBoundary) => void) | undefined\n nextBoundaryId: () => number\n bootstrapped?: boolean | undefined\n isBoundaryResolution?: boolean | undefined\n /**\n * Tracks whether the most recent emission within the *current text flow*\n * ended with a text node. When the next emission is also text, we emit a\n * `<!-- -->` separator so the browser's HTML parser doesn't merge them\n * into a single text node \u2014 required for hydration to line up text\n * boundaries with the React tree. Reset to `false` whenever we enter a\n * new host element (`<tag>` opens a fresh text flow).\n */\n textState?: { lastWasText: boolean }\n}\n\n/**\n * Synchronously walk a React node and emit HTML string pieces to `opts.emit`.\n * Suspended boundaries are emitted as fallbacks with marker IDs; if `opts.onSuspend`\n * is provided, the suspension is recorded for later streaming.\n */\nexport function walk(node: ReactNode, opts: WalkOptions): void {\n // Seed a text state if the caller didn't provide one so the separator logic\n // is active for the whole tree.\n if (!opts.textState) opts = { ...opts, textState: { lastWasText: false } }\n walkNode(node, opts)\n}\n\n// --- <select> selection context ----------------------------------------------\n// Stack of active select values (or `undefined` when the current select has\n// no controlled value). `<option>` walks read the top of stack to decide\n// whether to emit `selected=\"\"`.\nconst selectValueStack: unknown[] = []\nfunction pushSelectContext(value: unknown): void {\n selectValueStack.push(value)\n}\nfunction popSelectContext(): void {\n selectValueStack.pop()\n}\nfunction currentSelectValue(): unknown {\n return selectValueStack.length ? selectValueStack[selectValueStack.length - 1] : undefined\n}\n\nfunction optionChildText(children: unknown): string {\n // `<option>Text</option>` \u2014 if no `value` prop, the option's value is its\n // flat string/number child content. Matches DOM semantics (`option.value`\n // defaults to `textContent` when no attribute is set).\n if (children == null) return ''\n if (typeof children === 'string' || typeof children === 'number') return '' + children\n if (Array.isArray(children)) return children.map(optionChildText).join('')\n return ''\n}\n\nfunction emitText(text: string, opts: WalkOptions): void {\n // Empty string renders no text node and doesn't start/extend a text flow \u2014\n // skip entirely so sibling text isn't separated by a stray `<!-- -->`.\n if (text === '') return\n if (opts.textState?.lastWasText) opts.emit('<!-- -->')\n opts.emit(escapeText(text))\n if (opts.textState) opts.textState.lastWasText = true\n}\n\nfunction walkNode(node: ReactNode, opts: WalkOptions): void {\n if (node == null || node === false || node === true) return\n\n if (typeof node === 'string') {\n emitText(node, opts)\n return\n }\n if (typeof node === 'number') {\n emitText(String(node), opts)\n return\n }\n if (Array.isArray(node)) {\n for (const c of node) walkNode(c, opts)\n return\n }\n if (typeof (node as any)[Symbol.iterator] === 'function') {\n for (const item of node as Iterable<ReactNode>) walkNode(item, opts)\n return\n }\n\n if (typeof node !== 'object') return\n const t = (node as any).$$typeof\n\n // Raw React.lazy in the tree (RSC Flight encodes 'use client' components \u2014\n // CodeBlock, CodeExplorer, etc. \u2014 as bare Lazy objects directly in the\n // tree, not wrapped in REACT_ELEMENT_TYPE). SSR previously dropped these\n // here, so code snippets never made it into the server HTML. The RSC\n // decoder server-side awaits payloads before rendering, so status is\n // 'fulfilled' and `_init()` returns the resolved element synchronously.\n // If still pending (shouldn't happen post-awaitLazyElements), throw the\n // thenable so streaming SSR suspends the current boundary and retries.\n if (t === REACT_LAZY_TYPE) {\n const lazy = node as any\n const resolved = lazy._init(lazy._payload)\n walkNode(resolved, opts)\n return\n }\n\n if (t !== REACT_ELEMENT_TYPE && t !== REACT_LEGACY_ELEMENT_TYPE) return\n\n const el = node as ReactElement\n walkElement(el, opts)\n}\n\nfunction walkElement(el: ReactElement, opts: WalkOptions): void {\n const type = el.type\n const props = el.props ?? {}\n\n if (type === REACT_FRAGMENT_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_PROFILER_TYPE) {\n walkNode(props.children, opts)\n return\n }\n\n if (type === REACT_SUSPENSE_TYPE) {\n walkSuspense(props, opts)\n return\n }\n\n if (typeof type === 'string') {\n walkHost(type, props, opts)\n return\n }\n\n const marker = (type as any)?.$$typeof\n\n if (marker === REACT_PORTAL_TYPE) {\n // Portals don't render to the main HTML output on the server.\n return\n }\n\n if (marker === REACT_PROVIDER_TYPE) {\n const ctx = (type as any)._context\n pushContext(ctx, props.value)\n try {\n walkNode(props.children, opts)\n } finally {\n popContext(ctx)\n }\n return\n }\n\n if (marker === REACT_CONSUMER_TYPE) {\n const ctx = (type as any)._context\n const render = props.children\n if (typeof render === 'function') {\n walkNode(render(ctx._currentValue), opts)\n }\n return\n }\n\n if (marker === REACT_FORWARD_REF_TYPE) {\n const render = (type as any).render\n const ref = (props as any).ref ?? null\n const { ref: _omit, ...rest } = props as any\n const rendered = render(rest, ref)\n walkNode(rendered, opts)\n return\n }\n\n if (marker === REACT_MEMO_TYPE) {\n const inner = (type as any).type\n walkElement({ ...el, type: inner } as ReactElement, opts)\n return\n }\n\n if (marker === REACT_LAZY_TYPE) {\n const { _payload, _init } = type as any\n try {\n const resolved = _init(_payload)\n walkElement({ ...el, type: resolved } as ReactElement, opts)\n } catch (thenable: any) {\n if (isThenable(thenable)) {\n // Suspend this point\n throw thenable\n }\n throw thenable\n }\n return\n }\n\n if (typeof type === 'function') {\n walkComponent(type, props, opts)\n return\n }\n}\n\nfunction walkHost(\n tag: string,\n props: Record<string, any>,\n opts: WalkOptions,\n): void {\n // <textarea value=\"...\"> serializes its value as a TEXT CHILD, not an\n // attribute. `defaultValue` is the fallback when `value` is absent. This\n // matches React and the HTML spec \u2014 `<textarea value=\"x\">` is not valid\n // HTML; the value is the element's textContent.\n const isTextarea = tag === 'textarea'\n const textareaValue = isTextarea\n ? props.value != null\n ? props.value\n : props.defaultValue\n : undefined\n\n // <input defaultValue=\"...\"> should parse with that value \u2014 emit it as a\n // `value` attribute. Similarly `defaultChecked` becomes `checked`. This\n // keeps hydration consistent: the browser parser sees the initial value,\n // and on client commit our setProp seeds `.defaultValue`/`.defaultChecked`\n // without stomping the user-typed value.\n const isInput = tag === 'input'\n const inputValueAttr =\n isInput && props.value == null && props.defaultValue != null\n ? props.defaultValue\n : undefined\n const inputCheckedAttr =\n isInput && props.checked == null && props.defaultChecked != null\n ? props.defaultChecked\n : undefined\n\n // <select value=\"...\"> does NOT become an attribute on `<select>` \u2014 the\n // HTML spec has no such attribute. React resolves the selection by stamping\n // `selected` on the matching `<option>` children during render. Stash the\n // target value(s) on the walk state and the child `<option>` walk reads it.\n const isSelect = tag === 'select'\n if (isSelect) {\n const val = props.value != null ? props.value : props.defaultValue\n pushSelectContext(val)\n }\n const isOption = tag === 'option'\n\n // Prepend the HTML5 doctype to the stream when rendering an <html> root.\n // Without it the browser parses the document in quirks mode, which breaks\n // CSS sizing (documentElement.clientHeight returns the content height, not\n // the viewport) \u2014 and Floating-UI-based libraries (Radix dropdowns etc.)\n // then compute off-screen positions for overlays.\n if (tag === 'html') opts.emit('<!DOCTYPE html>')\n\n opts.emit('<' + tag)\n for (const k in props) {\n if (isTextarea && (k === 'value' || k === 'defaultValue')) continue\n if (isInput && (k === 'defaultValue' || k === 'defaultChecked')) continue\n if (isSelect && (k === 'value' || k === 'defaultValue')) continue\n if (isOption && k === 'selected') continue\n opts.emit(attrToHtml(k, props[k]))\n }\n if (inputValueAttr !== undefined) {\n opts.emit(attrToHtml('value', inputValueAttr))\n }\n if (inputCheckedAttr !== undefined) {\n opts.emit(attrToHtml('checked', inputCheckedAttr))\n }\n if (isOption) {\n const selectVal = currentSelectValue()\n if (selectVal !== undefined) {\n const optionValue =\n props.value != null ? props.value : optionChildText(props.children)\n const matches = Array.isArray(selectVal)\n ? selectVal.some((v) => '' + v === '' + optionValue)\n : '' + selectVal === '' + optionValue\n if (matches) opts.emit(' selected=\"\"')\n } else if (props.selected) {\n opts.emit(' selected=\"\"')\n }\n }\n\n if (VOID_ELEMENTS.has(tag)) {\n opts.emit('/>')\n if (opts.textState) opts.textState.lastWasText = false\n return\n }\n opts.emit('>')\n // Opening a host element starts a fresh text flow context for its children.\n // Children's text separator tracking is independent of the outer context.\n const parentTextState = opts.textState\n const childOpts: WalkOptions = { ...opts, textState: { lastWasText: false } }\n\n const dangerouslyHtml = props.dangerouslySetInnerHTML?.__html\n\n if (isTextarea && textareaValue != null) {\n opts.emit(escapeText(String(textareaValue)))\n opts.emit(`</${tag}>`)\n if (parentTextState) parentTextState.lastWasText = false\n return\n }\n\n if (RAW_TEXT_ELEMENTS.has(tag)) {\n // script/style: raw-text. React allows either a string/number child or\n // dangerouslySetInnerHTML \u2014 some libs (Start's Scripts) use the latter.\n if (dangerouslyHtml != null) {\n opts.emit(escapeScript(String(dangerouslyHtml)))\n } else {\n const children = props.children\n if (typeof children === 'string' || typeof children === 'number') {\n opts.emit(escapeScript(String(children)))\n } else if (Array.isArray(children)) {\n opts.emit(escapeScript(children.filter((c) => c != null).join('')))\n }\n }\n opts.emit(`</${tag}>`)\n if (parentTextState) parentTextState.lastWasText = false\n return\n }\n\n if (dangerouslyHtml != null) {\n opts.emit(String(dangerouslyHtml))\n } else {\n walkNode(props.children, childOpts)\n }\n opts.emit(`</${tag}>`)\n if (isSelect) popSelectContext()\n // Host element closing resets outer flow \u2014 next sibling text starts fresh.\n if (parentTextState) parentTextState.lastWasText = false\n}\n\nfunction walkComponent(\n fn: Function,\n props: Record<string, any>,\n opts: WalkOptions,\n): void {\n if ((fn as any).prototype?.isReactComponent) {\n const ctxType = (fn as any).contextType\n const ctxValue = ctxType ? ctxType._currentValue : undefined\n const instance = new (fn as any)(props, ctxValue)\n instance.props = props\n instance.context = ctxValue\n if ((fn as any).getDerivedStateFromProps) {\n const d = (fn as any).getDerivedStateFromProps(props, instance.state)\n if (d) instance.state = { ...instance.state, ...d }\n }\n walkNode(instance.render(), opts)\n return\n }\n const rendered = (fn as any)(props)\n walkNode(rendered, opts)\n}\n\nfunction walkSuspense(\n props: Record<string, any>,\n opts: WalkOptions,\n): void {\n const id = opts.nextBoundaryId()\n // Snapshot contexts BEFORE attempting children, so if a descendant suspends\n // we can replay the same provider stack when re-rendering the boundary.\n const contextSnapshot = snapshotContexts()\n\n // Try to render the children synchronously. If a thenable is thrown,\n // record the boundary and emit the fallback.\n const childParts: string[] = []\n const childEmit = (s: string) => childParts.push(s)\n try {\n walkNode(props.children, {\n emit: childEmit,\n onSuspend: opts.onSuspend,\n nextBoundaryId: opts.nextBoundaryId,\n })\n } catch (thenable: any) {\n if (isThenable(thenable)) {\n const fallbackParts: string[] = []\n try {\n walkNode(props.fallback, {\n emit: (s) => fallbackParts.push(s),\n onSuspend: opts.onSuspend,\n nextBoundaryId: opts.nextBoundaryId,\n })\n } catch {\n // Fallback suspending is unsupported; emit nothing\n }\n emitBoundary(opts, id, fallbackParts.join(''))\n\n if (opts.onSuspend) {\n opts.onSuspend({\n id,\n fallbackHTML: fallbackParts.join(''),\n children: props.children,\n thenable,\n contextSnapshot,\n })\n }\n return\n }\n throw thenable\n }\n\n // Children rendered fully \u2014 emit them wrapped in resolved-boundary markers\n // (`<!--$N-->` / `<!--/$-->`). Without markers, the client hydrator has no\n // way to know this subtree is inside a Suspense, so if the client version\n // of a descendant (e.g. `React.lazy`) suspends it can't pinpoint which DOM\n // range to adopt on resolve \u2014 it creates fresh DOM next to the SSR content,\n // producing visible duplicates (e.g. double navbar logos). Markers let the\n // client treat this as a resolved boundary and hydrate in-place.\n opts.emit(`<!--$${id}-->`)\n opts.emit(childParts.join(''))\n opts.emit(`<!--/$-->`)\n}\n\nfunction emitBoundary(opts: WalkOptions, id: number, fallbackHTML: string): void {\n // Visible div wrapper so the fallback UI shows; B: id lets $RC locate it on\n // reveal. The leading/trailing comments let hydration detect a pending\n // boundary and register a reveal callback.\n opts.emit(`<!--$?${id}--><div id=\"B:${id}\">`)\n opts.emit(fallbackHTML)\n opts.emit(`</div><!--/$-->`)\n}\n\nfunction isThenable(x: any): x is Promise<any> {\n return x != null && typeof x.then === 'function'\n}\n"],
5
- "mappings": ";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,E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,aAAuB,CAAC;AAC9B,QAAM,YAAY,CAAC,MAAc,WAAW,KAAK,CAAC;AAClD,MAAI;AACF,aAAS,MAAM,UAAU;AAAA,MACvB,MAAM;AAAA,MACN,WAAW,KAAK;AAAA,MAChB,gBAAgB,KAAK;AAAA,IACvB,CAAC;AAAA,EACH,SAAS,UAAe;AACtB,QAAI,WAAW,QAAQ,GAAG;AACxB,YAAM,gBAA0B,CAAC;AACjC,UAAI;AACF,iBAAS,MAAM,UAAU;AAAA,UACvB,MAAM,CAAC,MAAM,cAAc,KAAK,CAAC;AAAA,UACjC,WAAW,KAAK;AAAA,UAChB,gBAAgB,KAAK;AAAA,QACvB,CAAC;AAAA,MACH,QAAQ;AAAA,MAER;AACA,mBAAa,MAAM,IAAI,cAAc,KAAK,EAAE,CAAC;AAE7C,UAAI,KAAK,WAAW;AAClB,aAAK,UAAU;AAAA,UACb;AAAA,UACA,cAAc,cAAc,KAAK,EAAE;AAAA,UACnC,UAAU,MAAM;AAAA,UAChB;AAAA,UACA;AAAA,QACF,CAAC;AAAA,MACH;AACA;AAAA,IACF;AACA,UAAM;AAAA,EACR;AASA,OAAK,KAAK,QAAQ,EAAE,KAAK;AACzB,OAAK,KAAK,WAAW,KAAK,EAAE,CAAC;AAC7B,OAAK,KAAK,WAAW;AACvB;AAEA,SAAS,aAAa,MAAmB,IAAY,cAA4B;AAI/E,OAAK,KAAK,SAAS,EAAE,iBAAiB,EAAE,IAAI;AAC5C,OAAK,KAAK,YAAY;AACtB,OAAK,KAAK,iBAAiB;AAC7B;AAEA,SAAS,WAAW,GAA2B;AAC7C,SAAO,KAAK,QAAQ,OAAO,EAAE,SAAS;AACxC;",
4
+ "sourcesContent": ["import {\n REACT_ELEMENT_TYPE,\n REACT_LEGACY_ELEMENT_TYPE,\n REACT_FRAGMENT_TYPE,\n type ReactNode,\n type ReactElement,\n} from '../core'\nimport {\n REACT_SUSPENSE_TYPE,\n REACT_PROVIDER_TYPE,\n REACT_CONSUMER_TYPE,\n REACT_FORWARD_REF_TYPE,\n REACT_MEMO_TYPE,\n REACT_LAZY_TYPE,\n REACT_STRICT_MODE_TYPE,\n REACT_PROFILER_TYPE,\n REACT_PORTAL_TYPE,\n} from '../react'\nimport {\n attrToHtml,\n escapeText,\n escapeScript,\n VOID_ELEMENTS,\n RAW_TEXT_ELEMENTS,\n} from './escape'\nimport {\n pushContext,\n popContext,\n snapshotContexts,\n type ContextSnapshot,\n} from './dispatcher'\n\nexport interface SuspendedBoundary {\n id: number\n fallbackHTML: string\n children: ReactNode\n thenable: Promise<any>\n contextSnapshot: ContextSnapshot\n}\n\nexport interface WalkOptions {\n emit: (chunk: string) => void\n onSuspend?: ((boundary: SuspendedBoundary) => void) | undefined\n nextBoundaryId: () => number\n bootstrapped?: boolean | undefined\n isBoundaryResolution?: boolean | undefined\n /**\n * Tracks whether the most recent emission within the *current text flow*\n * ended with a text node. When the next emission is also text, we emit a\n * `<!-- -->` separator so the browser's HTML parser doesn't merge them\n * into a single text node \u2014 required for hydration to line up text\n * boundaries with the React tree. Reset to `false` whenever we enter a\n * new host element (`<tag>` opens a fresh text flow).\n */\n textState?: { lastWasText: boolean }\n}\n\n/**\n * Synchronously walk a React node and emit HTML string pieces to `opts.emit`.\n * Suspended boundaries are emitted as fallbacks with marker IDs; if `opts.onSuspend`\n * is provided, the suspension is recorded for later streaming.\n */\nexport function walk(node: ReactNode, opts: WalkOptions): void {\n // Seed a text state if the caller didn't provide one so the separator logic\n // is active for the whole tree.\n if (!opts.textState) opts = { ...opts, textState: { lastWasText: false } }\n walkNode(node, opts)\n}\n\n// --- <select> selection context ----------------------------------------------\n// Stack of active select values (or `undefined` when the current select has\n// no controlled value). `<option>` walks read the top of stack to decide\n// whether to emit `selected=\"\"`.\nconst selectValueStack: unknown[] = []\nfunction pushSelectContext(value: unknown): void {\n selectValueStack.push(value)\n}\nfunction popSelectContext(): void {\n selectValueStack.pop()\n}\nfunction currentSelectValue(): unknown {\n return selectValueStack.length ? selectValueStack[selectValueStack.length - 1] : undefined\n}\n\nfunction optionChildText(children: unknown): string {\n // `<option>Text</option>` \u2014 if no `value` prop, the option's value is its\n // flat string/number child content. Matches DOM semantics (`option.value`\n // defaults to `textContent` when no attribute is set).\n if (children == null) return ''\n if (typeof children === 'string' || typeof children === 'number') return '' + children\n if (Array.isArray(children)) return children.map(optionChildText).join('')\n return ''\n}\n\nfunction emitText(text: string, opts: WalkOptions): void {\n // Empty string renders no text node and doesn't start/extend a text flow \u2014\n // skip entirely so sibling text isn't separated by a stray `<!-- -->`.\n if (text === '') return\n if (opts.textState?.lastWasText) opts.emit('<!-- -->')\n opts.emit(escapeText(text))\n if (opts.textState) opts.textState.lastWasText = true\n}\n\nfunction walkNode(node: ReactNode, opts: WalkOptions): void {\n if (node == null || node === false || node === true) return\n\n if (typeof node === 'string') {\n emitText(node, opts)\n return\n }\n if (typeof node === 'number') {\n emitText(String(node), opts)\n return\n }\n if (Array.isArray(node)) {\n for (const c of node) walkNode(c, opts)\n return\n }\n if (typeof (node as any)[Symbol.iterator] === 'function') {\n for (const item of node as Iterable<ReactNode>) walkNode(item, opts)\n return\n }\n\n if (typeof node !== 'object') return\n const t = (node as any).$$typeof\n\n // Raw React.lazy in the tree (RSC Flight encodes 'use client' components \u2014\n // CodeBlock, CodeExplorer, etc. \u2014 as bare Lazy objects directly in the\n // tree, not wrapped in REACT_ELEMENT_TYPE). SSR previously dropped these\n // here, so code snippets never made it into the server HTML. The RSC\n // decoder server-side awaits payloads before rendering, so status is\n // 'fulfilled' and `_init()` returns the resolved element synchronously.\n // If still pending (shouldn't happen post-awaitLazyElements), throw the\n // thenable so streaming SSR suspends the current boundary and retries.\n if (t === REACT_LAZY_TYPE) {\n const lazy = node as any\n const resolved = lazy._init(lazy._payload)\n walkNode(resolved, opts)\n return\n }\n\n if (t !== REACT_ELEMENT_TYPE && t !== REACT_LEGACY_ELEMENT_TYPE) return\n\n const el = node as ReactElement\n walkElement(el, opts)\n}\n\nfunction walkElement(el: ReactElement, opts: WalkOptions): void {\n const type = el.type\n const props = el.props ?? {}\n\n if (type === REACT_FRAGMENT_TYPE || type === REACT_STRICT_MODE_TYPE || type === REACT_PROFILER_TYPE) {\n walkNode(props.children, opts)\n return\n }\n\n if (type === REACT_SUSPENSE_TYPE) {\n walkSuspense(props, opts)\n return\n }\n\n if (typeof type === 'string') {\n walkHost(type, props, opts)\n return\n }\n\n const marker = (type as any)?.$$typeof\n\n if (marker === REACT_PORTAL_TYPE) {\n // Portals don't render to the main HTML output on the server.\n return\n }\n\n if (marker === REACT_PROVIDER_TYPE) {\n const ctx = (type as any)._context\n pushContext(ctx, props.value)\n try {\n walkNode(props.children, opts)\n } finally {\n popContext(ctx)\n }\n return\n }\n\n if (marker === REACT_CONSUMER_TYPE) {\n const ctx = (type as any)._context\n const render = props.children\n if (typeof render === 'function') {\n walkNode(render(ctx._currentValue), opts)\n }\n return\n }\n\n if (marker === REACT_FORWARD_REF_TYPE) {\n const render = (type as any).render\n const ref = (props as any).ref ?? null\n const { ref: _omit, ...rest } = props as any\n const rendered = render(rest, ref)\n walkNode(rendered, opts)\n return\n }\n\n if (marker === REACT_MEMO_TYPE) {\n const inner = (type as any).type\n walkElement({ ...el, type: inner } as ReactElement, opts)\n return\n }\n\n if (marker === REACT_LAZY_TYPE) {\n const { _payload, _init } = type as any\n try {\n const resolved = _init(_payload)\n walkElement({ ...el, type: resolved } as ReactElement, opts)\n } catch (thenable: any) {\n if (isThenable(thenable)) {\n // Suspend this point\n throw thenable\n }\n throw thenable\n }\n return\n }\n\n if (typeof type === 'function') {\n walkComponent(type, props, opts)\n return\n }\n}\n\nfunction walkHost(\n tag: string,\n props: Record<string, any>,\n opts: WalkOptions,\n): void {\n // <textarea value=\"...\"> serializes its value as a TEXT CHILD, not an\n // attribute. `defaultValue` is the fallback when `value` is absent. This\n // matches React and the HTML spec \u2014 `<textarea value=\"x\">` is not valid\n // HTML; the value is the element's textContent.\n const isTextarea = tag === 'textarea'\n const textareaValue = isTextarea\n ? props.value != null\n ? props.value\n : props.defaultValue\n : undefined\n\n // <input defaultValue=\"...\"> should parse with that value \u2014 emit it as a\n // `value` attribute. Similarly `defaultChecked` becomes `checked`. This\n // keeps hydration consistent: the browser parser sees the initial value,\n // and on client commit our setProp seeds `.defaultValue`/`.defaultChecked`\n // without stomping the user-typed value.\n const isInput = tag === 'input'\n const inputValueAttr =\n isInput && props.value == null && props.defaultValue != null\n ? props.defaultValue\n : undefined\n const inputCheckedAttr =\n isInput && props.checked == null && props.defaultChecked != null\n ? props.defaultChecked\n : undefined\n\n // <select value=\"...\"> does NOT become an attribute on `<select>` \u2014 the\n // HTML spec has no such attribute. React resolves the selection by stamping\n // `selected` on the matching `<option>` children during render. Stash the\n // target value(s) on the walk state and the child `<option>` walk reads it.\n const isSelect = tag === 'select'\n if (isSelect) {\n const val = props.value != null ? props.value : props.defaultValue\n pushSelectContext(val)\n }\n const isOption = tag === 'option'\n\n // Prepend the HTML5 doctype to the stream when rendering an <html> root.\n // Without it the browser parses the document in quirks mode, which breaks\n // CSS sizing (documentElement.clientHeight returns the content height, not\n // the viewport) \u2014 and Floating-UI-based libraries (Radix dropdowns etc.)\n // then compute off-screen positions for overlays.\n if (tag === 'html') opts.emit('<!DOCTYPE html>')\n\n opts.emit('<' + tag)\n for (const k in props) {\n if (isTextarea && (k === 'value' || k === 'defaultValue')) continue\n if (isInput && (k === 'defaultValue' || k === 'defaultChecked')) continue\n if (isSelect && (k === 'value' || k === 'defaultValue')) continue\n if (isOption && k === 'selected') continue\n opts.emit(attrToHtml(k, props[k]))\n }\n if (inputValueAttr !== undefined) {\n opts.emit(attrToHtml('value', inputValueAttr))\n }\n if (inputCheckedAttr !== undefined) {\n opts.emit(attrToHtml('checked', inputCheckedAttr))\n }\n if (isOption) {\n const selectVal = currentSelectValue()\n if (selectVal !== undefined) {\n const optionValue =\n props.value != null ? props.value : optionChildText(props.children)\n const matches = Array.isArray(selectVal)\n ? selectVal.some((v) => '' + v === '' + optionValue)\n : '' + selectVal === '' + optionValue\n if (matches) opts.emit(' selected=\"\"')\n } else if (props.selected) {\n opts.emit(' selected=\"\"')\n }\n }\n\n if (VOID_ELEMENTS.has(tag)) {\n opts.emit('/>')\n if (opts.textState) opts.textState.lastWasText = false\n return\n }\n opts.emit('>')\n // Opening a host element starts a fresh text flow context for its children.\n // Children's text separator tracking is independent of the outer context.\n const parentTextState = opts.textState\n const childOpts: WalkOptions = { ...opts, textState: { lastWasText: false } }\n\n if (tag === 'html' && !hasHeadChild(props.children)) {\n opts.emit('<head></head>')\n }\n\n const dangerouslyHtml = props.dangerouslySetInnerHTML?.__html\n\n if (isTextarea && textareaValue != null) {\n opts.emit(escapeText(String(textareaValue)))\n opts.emit(`</${tag}>`)\n if (parentTextState) parentTextState.lastWasText = false\n return\n }\n\n if (RAW_TEXT_ELEMENTS.has(tag)) {\n // script/style: raw-text. React allows either a string/number child or\n // dangerouslySetInnerHTML \u2014 some libs (Start's Scripts) use the latter.\n if (dangerouslyHtml != null) {\n opts.emit(escapeScript(String(dangerouslyHtml)))\n } else {\n const children = props.children\n if (typeof children === 'string' || typeof children === 'number') {\n opts.emit(escapeScript(String(children)))\n } else if (Array.isArray(children)) {\n opts.emit(escapeScript(children.filter((c) => c != null).join('')))\n }\n }\n opts.emit(`</${tag}>`)\n if (parentTextState) parentTextState.lastWasText = false\n return\n }\n\n if (dangerouslyHtml != null) {\n opts.emit(String(dangerouslyHtml))\n } else {\n walkNode(props.children, childOpts)\n }\n opts.emit(`</${tag}>`)\n if (isSelect) popSelectContext()\n // Host element closing resets outer flow \u2014 next sibling text starts fresh.\n if (parentTextState) parentTextState.lastWasText = false\n}\n\nfunction hasHeadChild(children: unknown): boolean {\n if (children == null || typeof children === 'boolean') return false\n if (Array.isArray(children)) return children.some(hasHeadChild)\n if (typeof children !== 'string' && isIterable(children)) {\n for (const child of children as Iterable<unknown>) {\n if (hasHeadChild(child)) return true\n }\n return false\n }\n return isElementOfType(children, 'head')\n}\n\nfunction isElementOfType(value: unknown, type: string): value is ReactElement {\n const marker = (value as ReactElement | null)?.$$typeof as unknown\n return (\n !!value &&\n typeof value === 'object' &&\n (marker === REACT_ELEMENT_TYPE || marker === REACT_LEGACY_ELEMENT_TYPE) &&\n (value as ReactElement).type === type\n )\n}\n\nfunction isIterable(value: unknown): value is Iterable<unknown> {\n return !!value && typeof (value as { [Symbol.iterator]?: unknown })[Symbol.iterator] === 'function'\n}\n\nfunction walkComponent(\n fn: Function,\n props: Record<string, any>,\n opts: WalkOptions,\n): void {\n if ((fn as any).prototype?.isReactComponent) {\n const ctxType = (fn as any).contextType\n const ctxValue = ctxType ? ctxType._currentValue : undefined\n const instance = new (fn as any)(props, ctxValue)\n instance.props = props\n instance.context = ctxValue\n if ((fn as any).getDerivedStateFromProps) {\n const d = (fn as any).getDerivedStateFromProps(props, instance.state)\n if (d) instance.state = { ...instance.state, ...d }\n }\n walkNode(instance.render(), opts)\n return\n }\n const rendered = (fn as any)(props)\n walkNode(rendered, opts)\n}\n\nfunction walkSuspense(\n props: Record<string, any>,\n opts: WalkOptions,\n): void {\n const id = opts.nextBoundaryId()\n // Snapshot contexts BEFORE attempting children, so if a descendant suspends\n // we can replay the same provider stack when re-rendering the boundary.\n const contextSnapshot = snapshotContexts()\n\n // Try to render the children synchronously. If a thenable is thrown,\n // record the boundary and emit the fallback.\n const childParts: string[] = []\n const childEmit = (s: string) => childParts.push(s)\n try {\n walkNode(props.children, {\n emit: childEmit,\n onSuspend: opts.onSuspend,\n nextBoundaryId: opts.nextBoundaryId,\n })\n } catch (thenable: any) {\n if (isThenable(thenable)) {\n const fallbackParts: string[] = []\n try {\n walkNode(props.fallback, {\n emit: (s) => fallbackParts.push(s),\n onSuspend: opts.onSuspend,\n nextBoundaryId: opts.nextBoundaryId,\n })\n } catch {\n // Fallback suspending is unsupported; emit nothing\n }\n emitBoundary(opts, id, fallbackParts.join(''))\n\n if (opts.onSuspend) {\n opts.onSuspend({\n id,\n fallbackHTML: fallbackParts.join(''),\n children: props.children,\n thenable,\n contextSnapshot,\n })\n }\n return\n }\n throw thenable\n }\n\n // Children rendered fully \u2014 emit them wrapped in resolved-boundary markers\n // (`<!--$N-->` / `<!--/$-->`). Without markers, the client hydrator has no\n // way to know this subtree is inside a Suspense, so if the client version\n // of a descendant (e.g. `React.lazy`) suspends it can't pinpoint which DOM\n // range to adopt on resolve \u2014 it creates fresh DOM next to the SSR content,\n // producing visible duplicates (e.g. double navbar logos). Markers let the\n // client treat this as a resolved boundary and hydrate in-place.\n opts.emit(`<!--$${id}-->`)\n opts.emit(childParts.join(''))\n opts.emit(`<!--/$-->`)\n}\n\nfunction emitBoundary(opts: WalkOptions, id: number, fallbackHTML: string): void {\n // Visible div wrapper so the fallback UI shows; B: id lets $RC locate it on\n // reveal. The leading/trailing comments let hydration detect a pending\n // boundary and register a reveal callback.\n opts.emit(`<!--$?${id}--><div id=\"B:${id}\">`)\n opts.emit(fallbackHTML)\n opts.emit(`</div><!--/$-->`)\n}\n\nfunction isThenable(x: any): x is Promise<any> {\n return x != null && typeof x.then === 'function'\n}\n"],
5
+ "mappings": ";AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAgCA,SAAS,KAAK,MAAiB,MAAyB;AAG7D,MAAI,CAAC,KAAK,UAAW,QAAO,EAAE,GAAG,MAAM,WAAW,EAAE,aAAa,MAAM,EAAE;AACzE,WAAS,MAAM,IAAI;AACrB;AAMA,IAAM,mBAA8B,CAAC;AACrC,SAAS,kBAAkB,OAAsB;AAC/C,mBAAiB,KAAK,KAAK;AAC7B;AACA,SAAS,mBAAyB;AAChC,mBAAiB,IAAI;A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C7B;AAEA,SAAS,WAAW,GAA2B;AAC7C,SAAO,KAAK,QAAQ,OAAO,EAAE,SAAS;AACxC;",
6
6
  "names": []
7
7
  }
@@ -52,6 +52,8 @@ var ALIASES = {
52
52
  "react/jsx-dev-runtime": "@tanstack/redact/jsx-dev-runtime",
53
53
  "react/compiler-runtime": "@tanstack/redact/compiler-runtime",
54
54
  "react-dom/client": "@tanstack/redact/dom-client",
55
+ "react-dom/server.edge": "@tanstack/redact/server",
56
+ "react-dom/static.edge": "@tanstack/redact/server",
55
57
  "react-dom/server": "@tanstack/redact/server",
56
58
  "react-dom/test-utils": "@tanstack/redact/dom-test-utils",
57
59
  "react-dom": "@tanstack/redact/dom",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/vite/index.ts"],
4
- "sourcesContent": ["import { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { dirname, resolve as resolvePath } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nexport type RedactPreset = 'nano' | 'full'\n\n/**\n * Opt-in feature set. Each flag toggles whether the feature's real\n * implementation ships (`true`) or is swapped with a stub module that\n * degrades gracefully (`false`). Missing keys fall back to the preset's\n * default. Adding a feature to this interface propagates to consumer\n * configs as autocompleted options.\n */\nexport interface RedactFeatures {\n /**\n * `createPortal`. When `false`, portal elements render in place as a\n * Fragment (the `container` prop is ignored). `renderPortal` and its\n * deps are stripped from the bundle.\n */\n portal?: boolean\n /**\n * `createContext` / `useContext` / `<Provider>` / `<Consumer>`. When\n * `false`, Providers render as Fragments (value never propagates),\n * Consumers invoke their function-children with the context's default\n * value, and `useContext` returns the default. Provider-walk logic and\n * `renderProvider` are stripped.\n */\n context?: boolean\n /**\n * `<Suspense>` boundaries + streaming hydration. When `false`, Suspense\n * elements render as Fragments (children mount inline, `fallback` is\n * ignored). Thrown thenables still schedule a re-render on settle, so\n * eventual consistency works \u2014 just no fallback UI during the pending\n * window. Boundary-handler stack and hydration integration are stripped.\n */\n suspense?: boolean\n /**\n * `React.memo`. When `false`, memoized components still render but without\n * the prop-equality gate \u2014 every parent rerender passes through.\n * `shallowEqual` and the force-rerender bypass are stripped.\n */\n memo?: boolean\n /**\n * `React.forwardRef`. When `false`, forwardRef components still render but\n * the ref prop isn't forwarded to the inner function. React 19+ treats\n * refs as normal props on function components anyway, so most apps can\n * drop this. The dispatcher save/restore machinery is stripped.\n */\n forwardRef?: boolean\n /**\n * `React.lazy`. When `false`, lazy elements still resolve if their payload\n * is already available synchronously (e.g. pre-awaited RSC Flight); async\n * resolution throws a clear error. The hydration-deferred-reveal path and\n * Suspense coordination are stripped.\n */\n lazy?: boolean\n /**\n * Class components (`extends Component`). When `false`, class components\n * still render but only honor the core contract: constructor + `render()`\n * + `setState`. Dropped: `contextType`, `getDerivedStateFromProps`,\n * `shouldComponentUpdate`, `componentDidMount`/`Update`/`WillUnmount`,\n * `getDerivedStateFromError`/`componentDidCatch` (error boundaries).\n */\n classComponents?: boolean\n /**\n * SSR hydration (`hydrateRoot`). When `false`, `hydrateRoot` throws\n * (use `createRoot` for SPAs). The HydrationCursor / DOM adoption /\n * streaming-boundary coordination / event-replay / scroll-guard\n * machinery is stripped \u2014 the biggest single chunk of reducible code.\n */\n hydration?: boolean\n}\n\ninterface ResolvedFeatures {\n portal: boolean\n context: boolean\n suspense: boolean\n memo: boolean\n forwardRef: boolean\n lazy: boolean\n classComponents: boolean\n hydration: boolean\n}\n\nconst PRESET_DEFAULTS: Record<RedactPreset, ResolvedFeatures> = {\n // Opt-in: everything off. Turn individual features on via `features`.\n nano: {\n portal: false, context: false, suspense: false, memo: false,\n forwardRef: false, lazy: false, classComponents: false, hydration: false,\n },\n // Opt-out: everything on (drop-in React parity). Turn features off via `features`.\n full: {\n portal: true, context: true, suspense: true, memo: true,\n forwardRef: true, lazy: true, classComponents: true, hydration: true,\n },\n}\n\nfunction resolveFeatures(\n preset: RedactPreset,\n overrides: RedactFeatures,\n): ResolvedFeatures {\n const p = PRESET_DEFAULTS[preset]\n return {\n portal: overrides.portal ?? p.portal,\n context: overrides.context ?? p.context,\n suspense: overrides.suspense ?? p.suspense,\n memo: overrides.memo ?? p.memo,\n forwardRef: overrides.forwardRef ?? p.forwardRef,\n lazy: overrides.lazy ?? p.lazy,\n classComponents: overrides.classComponents ?? p.classComponents,\n hydration: overrides.hydration ?? p.hydration,\n }\n}\n\nexport interface RedactOptions {\n /** Skip aliasing specific specifiers, e.g. if a consumer wants real React somewhere. */\n skip?: ReadonlyArray<string>\n /**\n * Override package resolution root. Defaults to the Vite config root. Useful\n * for monorepos where the plugin lives in a different workspace than the\n * consumer app.\n */\n resolveFrom?: string\n /**\n * Explicit package roots, bypassing node_modules lookup. Keys are package\n * names (e.g. `@tanstack/redact`), values are absolute paths to the package\n * directory. Handy for cross-workspace testing / bring-your-own-build setups.\n */\n packageRoots?: Record<string, string>\n /**\n * Starting point for feature selection. `'full'` (default) turns every\n * feature on \u2014 drop-in React parity, opt-out individual features via\n * `features`. `'nano'` turns everything off \u2014 opt in to what you need.\n */\n preset?: RedactPreset\n /**\n * Per-feature overrides merged on top of the preset's defaults. Enables\n * fine-grained \"preset minus X\" or \"preset plus Y\" configurations.\n */\n features?: RedactFeatures\n}\n\n// Alias map. ORDER MATTERS \u2014 Vite's alias matcher uses first-match against\n// prefix, so more-specific specifiers MUST come before less-specific ones.\n// Without this, `react-dom/server` would prefix-match `react-dom` first and\n// resolve to `@tanstack/redact/dom/server` (wrong) instead of\n// `@tanstack/redact/server`.\n//\n// `use-sync-external-store` aliases are here because its CJS-only React 17\n// compat shim does `var React = require('react')`. That survives Vite's\n// pre-bundling intact and explodes in Cloudflare Workers (no `require`).\n// Modern React has `useSyncExternalStore` built-in, and `@tanstack/redact`\n// additionally exports `useSyncExternalStoreWithSelector` so this alias\n// is safe everywhere.\nconst ALIASES: Record<string, string> = {\n // ---- most-specific first ----\n 'use-sync-external-store/shim/with-selector': '@tanstack/redact',\n 'use-sync-external-store/shim/with-selector.js': '@tanstack/redact',\n 'use-sync-external-store/with-selector': '@tanstack/redact',\n 'use-sync-external-store/with-selector.js': '@tanstack/redact',\n 'use-sync-external-store/shim': '@tanstack/redact',\n 'use-sync-external-store': '@tanstack/redact',\n\n // React drop-in shim targets. Subpaths first.\n 'react/jsx-runtime': '@tanstack/redact/jsx-runtime',\n 'react/jsx-dev-runtime': '@tanstack/redact/jsx-dev-runtime',\n 'react/compiler-runtime': '@tanstack/redact/compiler-runtime',\n 'react-dom/client': '@tanstack/redact/dom-client',\n 'react-dom/server': '@tanstack/redact/server',\n 'react-dom/test-utils': '@tanstack/redact/dom-test-utils',\n 'react-dom': '@tanstack/redact/dom',\n react: '@tanstack/redact',\n scheduler: '@tanstack/redact/scheduler',\n\n // Self-aliases so Vite resolves `@tanstack/redact/*` imports to the same\n // canonical file path no matter where they originate (worker bundle vs\n // deps_ssr pre-bundle vs source). Without these, Cloudflare's\n // `noExternal: true` worker config inlines one copy while Vite's\n // optimizeDeps pre-bundles another, ending up with two separate\n // ReactSharedInternals instances and a null dispatcher in user hooks.\n // Subpaths first here too.\n '@tanstack/redact/jsx-runtime': '@tanstack/redact/jsx-runtime',\n '@tanstack/redact/jsx-dev-runtime': '@tanstack/redact/jsx-dev-runtime',\n '@tanstack/redact/compiler-runtime': '@tanstack/redact/compiler-runtime',\n '@tanstack/redact/dom-client': '@tanstack/redact/dom-client',\n '@tanstack/redact/dom-test-utils': '@tanstack/redact/dom-test-utils',\n '@tanstack/redact/server': '@tanstack/redact/server',\n '@tanstack/redact/scheduler': '@tanstack/redact/scheduler',\n '@tanstack/redact/dom': '@tanstack/redact/dom',\n '@tanstack/redact': '@tanstack/redact',\n}\n\nfunction splitSpecifier(specifier: string): { pkg: string; sub: string } {\n if (specifier.startsWith('@')) {\n const slash1 = specifier.indexOf('/')\n const slash2 = specifier.indexOf('/', slash1 + 1)\n if (slash2 < 0) return { pkg: specifier, sub: '' }\n return { pkg: specifier.slice(0, slash2), sub: specifier.slice(slash2 + 1) }\n }\n const slash = specifier.indexOf('/')\n if (slash < 0) return { pkg: specifier, sub: '' }\n return { pkg: specifier.slice(0, slash), sub: specifier.slice(slash + 1) }\n}\n\nfunction findPackageDir(pkg: string, fromDir: string): string | null {\n let dir = fromDir\n while (true) {\n const candidate = resolvePath(dir, 'node_modules', pkg)\n if (existsSync(resolvePath(candidate, 'package.json'))) return candidate\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\nfunction resolveExport(packageDir: string, sub: string): string | null {\n const pkgJsonPath = resolvePath(packageDir, 'package.json')\n let pkg: any\n try {\n pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf8'))\n } catch {\n return null\n }\n const key = sub ? './' + sub : '.'\n const exp = pkg.exports?.[key]\n // Prefer published `import` (dist/.js) over `source` \u2014 dist is a single\n // transformed bundle so Vite's dep optimizer doesn't thrash on dozens of\n // individual source files. The package keeps cross-subpath imports\n // external, so there's still only one runtime instance.\n const pick = (v: any): string | null => {\n if (typeof v === 'string') return v\n if (v && typeof v === 'object') {\n return pick(v.import ?? v.module ?? v.source ?? v.default ?? null)\n }\n return null\n }\n const target = pick(exp)\n if (target) return resolvePath(packageDir, target)\n if (!sub) {\n const main = pkg.module ?? pkg.main\n if (typeof main === 'string') return resolvePath(packageDir, main)\n }\n return null\n}\n\n// When installed from npm, `@tanstack/redact` is declared as a `dependency`\n// of consumer apps. Under pnpm's strict mode it ends up nested under the\n// plugin's own `.pnpm/@tanstack+redact@.../node_modules/` rather than\n// hoisted to the consumer's root, so a `findPackageDir` walk starting at\n// the Vite project root won't always find it. Search from the plugin's own\n// directory first (which walks into its nested node_modules), then fall\n// back to the consumer root for hoisted installs.\nconst pluginDir = dirname(fileURLToPath(import.meta.url))\n\nfunction resolveSpecifier(\n specifier: string,\n fromDir: string,\n packageRoots: Record<string, string>,\n): string | null {\n const { pkg, sub } = splitSpecifier(specifier)\n const packageDir =\n packageRoots[pkg] ??\n findPackageDir(pkg, pluginDir) ??\n findPackageDir(pkg, fromDir)\n if (!packageDir) return null\n const target = resolveExport(packageDir, sub)\n if (!target) return null\n // Canonicalize through pnpm symlinks. Under strict pnpm, the package may\n // live nested under `.pnpm/@tanstack+redact@.../node_modules/*`, but each\n // of those is itself a symlink to the flat `.pnpm/@tanstack+redact@.../`\n // entry. Vite's `fetchModule` (used by TanStack Start's server-fn\n // compiler) follows the realpath, so the id seen by the capture-transform\n // differs from the nested id we'd return. That leaves the compiler's\n // moduleCache keyed on the realpath while `getModuleInfo` looks up the\n // nested path \u2192 miss \u2192 \"could not load module info\". Returning the\n // canonical realpath here keeps the two sides in agreement.\n try {\n return realpathSync(target)\n } catch {\n return target\n }\n}\n\nexport function redact(options: RedactOptions = {}): any {\n const skip = new Set(options.skip ?? [])\n const entries = Object.entries(ALIASES).filter(([k]) => !skip.has(k))\n const features = resolveFeatures(options.preset ?? 'full', options.features ?? {})\n\n const resolvedMap: Record<string, string> = {}\n let done = false\n\n function resolveAll(root: string): void {\n if (done) return\n const fromDir = options.resolveFrom ?? root\n const packageRoots = options.packageRoots ?? {}\n for (const [from, to] of entries) {\n const resolved = resolveSpecifier(to, fromDir, packageRoots)\n if (resolved) resolvedMap[from] = resolved\n }\n done = true\n }\n\n return {\n name: 'redact',\n enforce: 'pre',\n\n config() {\n const excludeList = entries.map(([k]) => k)\n // Single package \u2014 only one name to dedupe / no-external.\n const noExt = ['@tanstack/redact']\n const aliasMap = Object.fromEntries(entries.filter(([from, to]) => from !== to))\n // Dedupe `@tanstack/redact` so Vite resolves it to a single instance\n // even when multiple packages (e.g. @tanstack/react-router and user\n // code) drag it into different parts of the module graph.\n const dedupe = noExt\n // Scope `resolve.alias` to client + ssr environments ONLY. Do NOT set\n // a top-level alias: it would apply to the `rsc` environment too,\n // where `@vitejs/plugin-rsc`'s vendored `react-server-dom-server`\n // imports `react` and needs the *real* React (with the `.d` field on\n // ReactSharedInternals that our shim deliberately doesn't have).\n // Aliasing `react` \u2192 `@tanstack/redact` in the RSC env crashes Flight\n // serialization. The Cloudflare vite-plugin's rolldown worker-runner\n // also pre-scans bare specifiers via Vite's alias map (not plugin\n // hooks), but it scans within the *ssr* environment specifically \u2014\n // so per-env `environments.ssr.resolve.alias` covers it. The\n // `enforce: 'pre'` resolveId hook below already skips RSC, so the\n // remaining concern is alias placement. Object form is required \u2014\n // array form is silently ignored by rolldown's worker-runner.\n return {\n environments: {\n client: {\n optimizeDeps: { exclude: excludeList },\n resolve: { alias: aliasMap, dedupe },\n },\n ssr: {\n optimizeDeps: { exclude: excludeList },\n resolve: { alias: aliasMap, dedupe, noExternal: noExt },\n },\n },\n ssr: { noExternal: noExt },\n }\n },\n\n configResolved(config: any) {\n resolveAll(config.root)\n // With `packageRoots`, package sources live outside the consumer's Vite\n // project root, so the default server.fs.allow list blocks them. Append\n // to the resolved allow list rather than replacing via `config()`, so we\n // keep Vite's defaults (root + node_modules + client runtime).\n const fsAllow = Object.values(options.packageRoots ?? {})\n if (fsAllow.length && config.server?.fs?.allow) {\n for (const p of fsAllow) {\n if (!config.server.fs.allow.includes(p)) {\n config.server.fs.allow.push(p)\n }\n }\n }\n },\n\n async resolveId(this: any, id: string, importer?: string, opts?: any) {\n // Skip the RSC environment \u2014 it relies on real React internals via\n // @vitejs/plugin-rsc's vendored react-server-dom. Substituting our\n // shim there breaks Flight serialization. Client + SSR envs still swap.\n const envName = this?.environment?.name\n if (envName === 'rsc') return null\n\n // Feature-flag swap: when the reconciler's `features/index` module\n // imports a feature by relative path, redirect to that feature's stub\n // if the flag is off. The stub registers a graceful-degradation\n // matcher (e.g. Portal \u2192 Fragment) so user code keeps working.\n if (importer && /[\\\\/]features[\\\\/]index\\.[jt]sx?$/.test(importer)) {\n const m = id.match(/^\\.\\/([a-z-]+)$/)\n if (m) {\n const name = m[1] as keyof ResolvedFeatures\n if (name in features && !features[name]) {\n const r = await this.resolve(`./${name}/stub`, importer, {\n ...opts,\n skipSelf: true,\n })\n if (r) return r.id\n }\n }\n }\n\n // Hydration swap: hydration isn't self-registering, so it's imported\n // from reconcile.ts, root.ts, and the Suspense/Lazy feature modules.\n // Any specifier ending in `/hydration` that resolves to our feature\n // module gets redirected to the stub when the flag is off.\n if (!features.hydration && importer && /[\\\\/]hydration$/.test(id)) {\n const r = await this.resolve(id, importer, { ...opts, skipSelf: true })\n if (r && /features[\\\\/]hydration[\\\\/]index\\.(ts|js)$/.test(r.id)) {\n return r.id.replace(/index\\.(ts|js)$/, 'stub.$1')\n }\n }\n\n return resolvedMap[id] ?? null\n },\n }\n}\n\nexport default redact\n"],
5
- "mappings": ";AAAA,SAAS,YAAY,cAAc,oBAAoB;AACvD,SAAS,SAAS,WAAW,mBAAmB;AAChD,SAAS,qBAAqB;AAkF9B,IAAM,kBAA0D;AAAA;AAAA,EAE9D,MAAM;AAAA,IACJ,QAAQ;AAAA,IAAO,SAAS;AAAA,IAAO,UAAU;AAAA,IAAO,MAAM;AAAA,IACtD,YAAY;AAAA,IAAO,MAAM;AAAA,IAAO,iBAAiB;AAAA,IAAO,WAAW;AAAA,EACrE;AAAA;AAAA,EAEA,MAAM;AAAA,IACJ,QAAQ;AAAA,IAAM,SAAS;AAAA,IAAM,UAAU;AAAA,IAAM,MAAM;AAAA,IACnD,YAAY;AAAA,IAAM,MAAM;AAAA,IAAM,iBAAiB;AAAA,IAAM,WAAW;AAAA,EAClE;AACF;AAEA,SAAS,gBACP,QACA,WACkB;AAClB,QAAM,IAAI,gBAAgB,MAAM;AAChC,SAAO;AAAA,IACL,QAAQ,UAAU,UAAU,EAAE;AAAA,IAC9B,SAAS,UAAU,WAAW,EAAE;AAAA,IAChC,UAAU,UAAU,YAAY,EAAE;AAAA,IAClC,MAAM,UAAU,QAAQ,EAAE;AAAA,IAC1B,YAAY,UAAU,cAAc,EAAE;AAAA,IACtC,MAAM,UAAU,QAAQ,EAAE;AAAA,IAC1B,iBAAiB,UAAU,mBAAmB,EAAE;AAAA,IAChD,WAAW,UAAU,aAAa,EAAE;AAAA,EACtC;AACF;AA0CA,IAAM,UAAkC;AAAA;AAAA,EAEtC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Q,IAAI,OAAO;AAC9C,mBAAW,KAAK,SAAS;AACvB,cAAI,CAAC,OAAO,OAAO,GAAG,MAAM,SAAS,CAAC,GAAG;AACvC,mBAAO,OAAO,GAAG,MAAM,KAAK,CAAC;AAAA,UAC/B;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,IAEA,MAAM,UAAqB,IAAY,UAAmB,MAAY;AAIpE,YAAM,UAAU,MAAM,aAAa;AACnC,UAAI,YAAY,MAAO,QAAO;AAM9B,UAAI,YAAY,oCAAoC,KAAK,QAAQ,GAAG;AAClE,cAAM,IAAI,GAAG,MAAM,iBAAiB;AACpC,YAAI,GAAG;AACL,gBAAM,OAAO,EAAE,CAAC;AAChB,cAAI,QAAQ,YAAY,CAAC,SAAS,IAAI,GAAG;AACvC,kBAAM,IAAI,MAAM,KAAK,QAAQ,KAAK,IAAI,SAAS,UAAU;AAAA,cACvD,GAAG;AAAA,cACH,UAAU;AAAA,YACZ,CAAC;AACD,gBAAI,EAAG,QAAO,EAAE;AAAA,UAClB;AAAA,QACF;AAAA,MACF;AAMA,UAAI,CAAC,SAAS,aAAa,YAAY,kBAAkB,KAAK,EAAE,GAAG;AACjE,cAAM,IAAI,MAAM,KAAK,QAAQ,IAAI,UAAU,EAAE,GAAG,MAAM,UAAU,KAAK,CAAC;AACtE,YAAI,KAAK,6CAA6C,KAAK,EAAE,EAAE,GAAG;AAChE,iBAAO,EAAE,GAAG,QAAQ,mBAAmB,SAAS;AAAA,QAClD;AAAA,MACF;AAEA,aAAO,YAAY,EAAE,KAAK;AAAA,IAC5B;AAAA,EACF;AACF;AAEA,IAAO,eAAQ;",
4
+ "sourcesContent": ["import { existsSync, readFileSync, realpathSync } from 'node:fs'\nimport { dirname, resolve as resolvePath } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nexport type RedactPreset = 'nano' | 'full'\n\n/**\n * Opt-in feature set. Each flag toggles whether the feature's real\n * implementation ships (`true`) or is swapped with a stub module that\n * degrades gracefully (`false`). Missing keys fall back to the preset's\n * default. Adding a feature to this interface propagates to consumer\n * configs as autocompleted options.\n */\nexport interface RedactFeatures {\n /**\n * `createPortal`. When `false`, portal elements render in place as a\n * Fragment (the `container` prop is ignored). `renderPortal` and its\n * deps are stripped from the bundle.\n */\n portal?: boolean\n /**\n * `createContext` / `useContext` / `<Provider>` / `<Consumer>`. When\n * `false`, Providers render as Fragments (value never propagates),\n * Consumers invoke their function-children with the context's default\n * value, and `useContext` returns the default. Provider-walk logic and\n * `renderProvider` are stripped.\n */\n context?: boolean\n /**\n * `<Suspense>` boundaries + streaming hydration. When `false`, Suspense\n * elements render as Fragments (children mount inline, `fallback` is\n * ignored). Thrown thenables still schedule a re-render on settle, so\n * eventual consistency works \u2014 just no fallback UI during the pending\n * window. Boundary-handler stack and hydration integration are stripped.\n */\n suspense?: boolean\n /**\n * `React.memo`. When `false`, memoized components still render but without\n * the prop-equality gate \u2014 every parent rerender passes through.\n * `shallowEqual` and the force-rerender bypass are stripped.\n */\n memo?: boolean\n /**\n * `React.forwardRef`. When `false`, forwardRef components still render but\n * the ref prop isn't forwarded to the inner function. React 19+ treats\n * refs as normal props on function components anyway, so most apps can\n * drop this. The dispatcher save/restore machinery is stripped.\n */\n forwardRef?: boolean\n /**\n * `React.lazy`. When `false`, lazy elements still resolve if their payload\n * is already available synchronously (e.g. pre-awaited RSC Flight); async\n * resolution throws a clear error. The hydration-deferred-reveal path and\n * Suspense coordination are stripped.\n */\n lazy?: boolean\n /**\n * Class components (`extends Component`). When `false`, class components\n * still render but only honor the core contract: constructor + `render()`\n * + `setState`. Dropped: `contextType`, `getDerivedStateFromProps`,\n * `shouldComponentUpdate`, `componentDidMount`/`Update`/`WillUnmount`,\n * `getDerivedStateFromError`/`componentDidCatch` (error boundaries).\n */\n classComponents?: boolean\n /**\n * SSR hydration (`hydrateRoot`). When `false`, `hydrateRoot` throws\n * (use `createRoot` for SPAs). The HydrationCursor / DOM adoption /\n * streaming-boundary coordination / event-replay / scroll-guard\n * machinery is stripped \u2014 the biggest single chunk of reducible code.\n */\n hydration?: boolean\n}\n\ninterface ResolvedFeatures {\n portal: boolean\n context: boolean\n suspense: boolean\n memo: boolean\n forwardRef: boolean\n lazy: boolean\n classComponents: boolean\n hydration: boolean\n}\n\nconst PRESET_DEFAULTS: Record<RedactPreset, ResolvedFeatures> = {\n // Opt-in: everything off. Turn individual features on via `features`.\n nano: {\n portal: false, context: false, suspense: false, memo: false,\n forwardRef: false, lazy: false, classComponents: false, hydration: false,\n },\n // Opt-out: everything on (drop-in React parity). Turn features off via `features`.\n full: {\n portal: true, context: true, suspense: true, memo: true,\n forwardRef: true, lazy: true, classComponents: true, hydration: true,\n },\n}\n\nfunction resolveFeatures(\n preset: RedactPreset,\n overrides: RedactFeatures,\n): ResolvedFeatures {\n const p = PRESET_DEFAULTS[preset]\n return {\n portal: overrides.portal ?? p.portal,\n context: overrides.context ?? p.context,\n suspense: overrides.suspense ?? p.suspense,\n memo: overrides.memo ?? p.memo,\n forwardRef: overrides.forwardRef ?? p.forwardRef,\n lazy: overrides.lazy ?? p.lazy,\n classComponents: overrides.classComponents ?? p.classComponents,\n hydration: overrides.hydration ?? p.hydration,\n }\n}\n\nexport interface RedactOptions {\n /** Skip aliasing specific specifiers, e.g. if a consumer wants real React somewhere. */\n skip?: ReadonlyArray<string>\n /**\n * Override package resolution root. Defaults to the Vite config root. Useful\n * for monorepos where the plugin lives in a different workspace than the\n * consumer app.\n */\n resolveFrom?: string\n /**\n * Explicit package roots, bypassing node_modules lookup. Keys are package\n * names (e.g. `@tanstack/redact`), values are absolute paths to the package\n * directory. Handy for cross-workspace testing / bring-your-own-build setups.\n */\n packageRoots?: Record<string, string>\n /**\n * Starting point for feature selection. `'full'` (default) turns every\n * feature on \u2014 drop-in React parity, opt-out individual features via\n * `features`. `'nano'` turns everything off \u2014 opt in to what you need.\n */\n preset?: RedactPreset\n /**\n * Per-feature overrides merged on top of the preset's defaults. Enables\n * fine-grained \"preset minus X\" or \"preset plus Y\" configurations.\n */\n features?: RedactFeatures\n}\n\n// Alias map. ORDER MATTERS \u2014 Vite's alias matcher uses first-match against\n// prefix, so more-specific specifiers MUST come before less-specific ones.\n// Without this, `react-dom/server` would prefix-match `react-dom` first and\n// resolve to `@tanstack/redact/dom/server` (wrong) instead of\n// `@tanstack/redact/server`.\n//\n// `use-sync-external-store` aliases are here because its CJS-only React 17\n// compat shim does `var React = require('react')`. That survives Vite's\n// pre-bundling intact and explodes in Cloudflare Workers (no `require`).\n// Modern React has `useSyncExternalStore` built-in, and `@tanstack/redact`\n// additionally exports `useSyncExternalStoreWithSelector` so this alias\n// is safe everywhere.\nconst ALIASES: Record<string, string> = {\n // ---- most-specific first ----\n 'use-sync-external-store/shim/with-selector': '@tanstack/redact',\n 'use-sync-external-store/shim/with-selector.js': '@tanstack/redact',\n 'use-sync-external-store/with-selector': '@tanstack/redact',\n 'use-sync-external-store/with-selector.js': '@tanstack/redact',\n 'use-sync-external-store/shim': '@tanstack/redact',\n 'use-sync-external-store': '@tanstack/redact',\n\n // React drop-in shim targets. Subpaths first.\n 'react/jsx-runtime': '@tanstack/redact/jsx-runtime',\n 'react/jsx-dev-runtime': '@tanstack/redact/jsx-dev-runtime',\n 'react/compiler-runtime': '@tanstack/redact/compiler-runtime',\n 'react-dom/client': '@tanstack/redact/dom-client',\n 'react-dom/server.edge': '@tanstack/redact/server',\n 'react-dom/static.edge': '@tanstack/redact/server',\n 'react-dom/server': '@tanstack/redact/server',\n 'react-dom/test-utils': '@tanstack/redact/dom-test-utils',\n 'react-dom': '@tanstack/redact/dom',\n react: '@tanstack/redact',\n scheduler: '@tanstack/redact/scheduler',\n\n // Self-aliases so Vite resolves `@tanstack/redact/*` imports to the same\n // canonical file path no matter where they originate (worker bundle vs\n // deps_ssr pre-bundle vs source). Without these, Cloudflare's\n // `noExternal: true` worker config inlines one copy while Vite's\n // optimizeDeps pre-bundles another, ending up with two separate\n // ReactSharedInternals instances and a null dispatcher in user hooks.\n // Subpaths first here too.\n '@tanstack/redact/jsx-runtime': '@tanstack/redact/jsx-runtime',\n '@tanstack/redact/jsx-dev-runtime': '@tanstack/redact/jsx-dev-runtime',\n '@tanstack/redact/compiler-runtime': '@tanstack/redact/compiler-runtime',\n '@tanstack/redact/dom-client': '@tanstack/redact/dom-client',\n '@tanstack/redact/dom-test-utils': '@tanstack/redact/dom-test-utils',\n '@tanstack/redact/server': '@tanstack/redact/server',\n '@tanstack/redact/scheduler': '@tanstack/redact/scheduler',\n '@tanstack/redact/dom': '@tanstack/redact/dom',\n '@tanstack/redact': '@tanstack/redact',\n}\n\nfunction splitSpecifier(specifier: string): { pkg: string; sub: string } {\n if (specifier.startsWith('@')) {\n const slash1 = specifier.indexOf('/')\n const slash2 = specifier.indexOf('/', slash1 + 1)\n if (slash2 < 0) return { pkg: specifier, sub: '' }\n return { pkg: specifier.slice(0, slash2), sub: specifier.slice(slash2 + 1) }\n }\n const slash = specifier.indexOf('/')\n if (slash < 0) return { pkg: specifier, sub: '' }\n return { pkg: specifier.slice(0, slash), sub: specifier.slice(slash + 1) }\n}\n\nfunction findPackageDir(pkg: string, fromDir: string): string | null {\n let dir = fromDir\n while (true) {\n const candidate = resolvePath(dir, 'node_modules', pkg)\n if (existsSync(resolvePath(candidate, 'package.json'))) return candidate\n const parent = dirname(dir)\n if (parent === dir) return null\n dir = parent\n }\n}\n\nfunction resolveExport(packageDir: string, sub: string): string | null {\n const pkgJsonPath = resolvePath(packageDir, 'package.json')\n let pkg: any\n try {\n pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf8'))\n } catch {\n return null\n }\n const key = sub ? './' + sub : '.'\n const exp = pkg.exports?.[key]\n // Prefer published `import` (dist/.js) over `source` \u2014 dist is a single\n // transformed bundle so Vite's dep optimizer doesn't thrash on dozens of\n // individual source files. The package keeps cross-subpath imports\n // external, so there's still only one runtime instance.\n const pick = (v: any): string | null => {\n if (typeof v === 'string') return v\n if (v && typeof v === 'object') {\n return pick(v.import ?? v.module ?? v.source ?? v.default ?? null)\n }\n return null\n }\n const target = pick(exp)\n if (target) return resolvePath(packageDir, target)\n if (!sub) {\n const main = pkg.module ?? pkg.main\n if (typeof main === 'string') return resolvePath(packageDir, main)\n }\n return null\n}\n\n// When installed from npm, `@tanstack/redact` is declared as a `dependency`\n// of consumer apps. Under pnpm's strict mode it ends up nested under the\n// plugin's own `.pnpm/@tanstack+redact@.../node_modules/` rather than\n// hoisted to the consumer's root, so a `findPackageDir` walk starting at\n// the Vite project root won't always find it. Search from the plugin's own\n// directory first (which walks into its nested node_modules), then fall\n// back to the consumer root for hoisted installs.\nconst pluginDir = dirname(fileURLToPath(import.meta.url))\n\nfunction resolveSpecifier(\n specifier: string,\n fromDir: string,\n packageRoots: Record<string, string>,\n): string | null {\n const { pkg, sub } = splitSpecifier(specifier)\n const packageDir =\n packageRoots[pkg] ??\n findPackageDir(pkg, pluginDir) ??\n findPackageDir(pkg, fromDir)\n if (!packageDir) return null\n const target = resolveExport(packageDir, sub)\n if (!target) return null\n // Canonicalize through pnpm symlinks. Under strict pnpm, the package may\n // live nested under `.pnpm/@tanstack+redact@.../node_modules/*`, but each\n // of those is itself a symlink to the flat `.pnpm/@tanstack+redact@.../`\n // entry. Vite's `fetchModule` (used by TanStack Start's server-fn\n // compiler) follows the realpath, so the id seen by the capture-transform\n // differs from the nested id we'd return. That leaves the compiler's\n // moduleCache keyed on the realpath while `getModuleInfo` looks up the\n // nested path \u2192 miss \u2192 \"could not load module info\". Returning the\n // canonical realpath here keeps the two sides in agreement.\n try {\n return realpathSync(target)\n } catch {\n return target\n }\n}\n\nexport function redact(options: RedactOptions = {}): any {\n const skip = new Set(options.skip ?? [])\n const entries = Object.entries(ALIASES).filter(([k]) => !skip.has(k))\n const features = resolveFeatures(options.preset ?? 'full', options.features ?? {})\n\n const resolvedMap: Record<string, string> = {}\n let done = false\n\n function resolveAll(root: string): void {\n if (done) return\n const fromDir = options.resolveFrom ?? root\n const packageRoots = options.packageRoots ?? {}\n for (const [from, to] of entries) {\n const resolved = resolveSpecifier(to, fromDir, packageRoots)\n if (resolved) resolvedMap[from] = resolved\n }\n done = true\n }\n\n return {\n name: 'redact',\n enforce: 'pre',\n\n config() {\n const excludeList = entries.map(([k]) => k)\n // Single package \u2014 only one name to dedupe / no-external.\n const noExt = ['@tanstack/redact']\n const aliasMap = Object.fromEntries(entries.filter(([from, to]) => from !== to))\n // Dedupe `@tanstack/redact` so Vite resolves it to a single instance\n // even when multiple packages (e.g. @tanstack/react-router and user\n // code) drag it into different parts of the module graph.\n const dedupe = noExt\n // Scope `resolve.alias` to client + ssr environments ONLY. Do NOT set\n // a top-level alias: it would apply to the `rsc` environment too,\n // where `@vitejs/plugin-rsc`'s vendored `react-server-dom-server`\n // imports `react` and needs the *real* React (with the `.d` field on\n // ReactSharedInternals that our shim deliberately doesn't have).\n // Aliasing `react` \u2192 `@tanstack/redact` in the RSC env crashes Flight\n // serialization. The Cloudflare vite-plugin's rolldown worker-runner\n // also pre-scans bare specifiers via Vite's alias map (not plugin\n // hooks), but it scans within the *ssr* environment specifically \u2014\n // so per-env `environments.ssr.resolve.alias` covers it. The\n // `enforce: 'pre'` resolveId hook below already skips RSC, so the\n // remaining concern is alias placement. Object form is required \u2014\n // array form is silently ignored by rolldown's worker-runner.\n return {\n environments: {\n client: {\n optimizeDeps: { exclude: excludeList },\n resolve: { alias: aliasMap, dedupe },\n },\n ssr: {\n optimizeDeps: { exclude: excludeList },\n resolve: { alias: aliasMap, dedupe, noExternal: noExt },\n },\n },\n ssr: { noExternal: noExt },\n }\n },\n\n configResolved(config: any) {\n resolveAll(config.root)\n // With `packageRoots`, package sources live outside the consumer's Vite\n // project root, so the default server.fs.allow list blocks them. Append\n // to the resolved allow list rather than replacing via `config()`, so we\n // keep Vite's defaults (root + node_modules + client runtime).\n const fsAllow = Object.values(options.packageRoots ?? {})\n if (fsAllow.length && config.server?.fs?.allow) {\n for (const p of fsAllow) {\n if (!config.server.fs.allow.includes(p)) {\n config.server.fs.allow.push(p)\n }\n }\n }\n },\n\n async resolveId(this: any, id: string, importer?: string, opts?: any) {\n // Skip the RSC environment \u2014 it relies on real React internals via\n // @vitejs/plugin-rsc's vendored react-server-dom. Substituting our\n // shim there breaks Flight serialization. Client + SSR envs still swap.\n const envName = this?.environment?.name\n if (envName === 'rsc') return null\n\n // Feature-flag swap: when the reconciler's `features/index` module\n // imports a feature by relative path, redirect to that feature's stub\n // if the flag is off. The stub registers a graceful-degradation\n // matcher (e.g. Portal \u2192 Fragment) so user code keeps working.\n if (importer && /[\\\\/]features[\\\\/]index\\.[jt]sx?$/.test(importer)) {\n const m = id.match(/^\\.\\/([a-z-]+)$/)\n if (m) {\n const name = m[1] as keyof ResolvedFeatures\n if (name in features && !features[name]) {\n const r = await this.resolve(`./${name}/stub`, importer, {\n ...opts,\n skipSelf: true,\n })\n if (r) return r.id\n }\n }\n }\n\n // Hydration swap: hydration isn't self-registering, so it's imported\n // from reconcile.ts, root.ts, and the Suspense/Lazy feature modules.\n // Any specifier ending in `/hydration` that resolves to our feature\n // module gets redirected to the stub when the flag is off.\n if (!features.hydration && importer && /[\\\\/]hydration$/.test(id)) {\n const r = await this.resolve(id, importer, { ...opts, skipSelf: true })\n if (r && /features[\\\\/]hydration[\\\\/]index\\.(ts|js)$/.test(r.id)) {\n return r.id.replace(/index\\.(ts|js)$/, 'stub.$1')\n }\n }\n\n return resolvedMap[id] ?? null\n },\n }\n}\n\nexport default redact\n"],
5
+ "mappings": ";AAAA,SAAS,YAAY,cAAc,oBAAoB;AACvD,SAAS,SAAS,WAAW,mBAAmB;AAChD,SAAS,qBAAqB;AAkF9B,IAAM,kBAA0D;AAAA;AAAA,EAE9D,MAAM;AAAA,IACJ,QAAQ;AAAA,IAAO,SAAS;AAAA,IAAO,UAAU;AAAA,IAAO,MAAM;AAAA,IACtD,YAAY;AAAA,IAAO,MAAM;AAAA,IAAO,iBAAiB;AAAA,IAAO,WAAW;AAAA,EACrE;AAAA;AAAA,EAEA,MAAM;AAAA,IACJ,QAAQ;AAA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AAE;AAAA,UAClB;AAAA,QACF;AAAA,MACF;AAMA,UAAI,CAAC,SAAS,aAAa,YAAY,kBAAkB,KAAK,EAAE,GAAG;AACjE,cAAM,IAAI,MAAM,KAAK,QAAQ,IAAI,UAAU,EAAE,GAAG,MAAM,UAAU,KAAK,CAAC;AACtE,YAAI,KAAK,6CAA6C,KAAK,EAAE,EAAE,GAAG;AAChE,iBAAO,EAAE,GAAG,QAAQ,mBAAmB,SAAS;AAAA,QAClD;AAAA,MACF;AAEA,aAAO,YAAY,EAAE,KAAK;AAAA,IAC5B;AAAA,EACF;AACF;AAEA,IAAO,eAAQ;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/redact",
3
- "version": "0.0.9",
3
+ "version": "0.0.11",
4
4
  "description": "React, redacted. A minimal React-API-compatible drop-in replacement.",
5
5
  "type": "module",
6
6
  "main": "./dist/react/index.js",
@@ -50,7 +50,17 @@ function depsEqual(
50
50
  return true
51
51
  }
52
52
 
53
+ // Singleton — every method reads render context via ReactSharedInternals,
54
+ // and per-hook closures live on the hook itself, so nothing is render-local
55
+ // to capture. Allocating a fresh wrapper + 17 method closures per function-
56
+ // component render was pure GC pressure.
57
+ const DISPATCHER = makeDispatcherImpl()
58
+
53
59
  export function makeDispatcher() {
60
+ return DISPATCHER
61
+ }
62
+
63
+ function makeDispatcherImpl() {
54
64
  return {
55
65
  useState<S>(initial: S | (() => S)) {
56
66
  return this.useReducer<S, S | ((p: S) => S)>(
@@ -21,18 +21,18 @@ const GUARD_WINDOW_MS = 3000
21
21
  export function installHydrationScrollGuard(): void {
22
22
  if (typeof window === 'undefined') return
23
23
  const w = window as any
24
- if (w.__tdomScrollGuardInstalled) return
25
- w.__tdomScrollGuardInstalled = true
24
+ if (w.__redactScrollGuardInstalled) return
25
+ w.__redactScrollGuardInstalled = true
26
26
  const guardStartedAt = performance.now()
27
27
  let lastUserScrollAt = 0
28
28
  let programmatic = 0
29
- w.__tdomScrollLog = []
29
+ w.__redactScrollLog = []
30
30
  window.addEventListener(
31
31
  'scroll',
32
32
  () => {
33
33
  if (programmatic === 0) {
34
34
  lastUserScrollAt = performance.now()
35
- w.__tdomScrollLog.push({ t: Math.round(lastUserScrollAt), ev: 'user-scroll', y: window.scrollY })
35
+ w.__redactScrollLog.push({ t: Math.round(lastUserScrollAt), ev: 'user-scroll', y: window.scrollY })
36
36
  }
37
37
  },
38
38
  { capture: true, passive: true },
@@ -43,7 +43,7 @@ export function installHydrationScrollGuard(): void {
43
43
  const inGuardWindow = now - guardStartedAt < GUARD_WINDOW_MS
44
44
  const userScrolledRecently = lastUserScrollAt > 0 && now - lastUserScrollAt < 1500
45
45
  if (inGuardWindow && userScrolledRecently) {
46
- w.__tdomScrollLog.push({
46
+ w.__redactScrollLog.push({
47
47
  t: Math.round(now),
48
48
  ev: 'suppressed',
49
49
  args: JSON.stringify(args).slice(0, 80),
@@ -52,7 +52,7 @@ export function installHydrationScrollGuard(): void {
52
52
  })
53
53
  return
54
54
  }
55
- w.__tdomScrollLog.push({
55
+ w.__redactScrollLog.push({
56
56
  t: Math.round(now),
57
57
  ev: 'allowed',
58
58
  args: JSON.stringify(args).slice(0, 80),
@@ -147,6 +147,8 @@ const HEAD_KEY_ATTRS: Record<string, ReadonlyArray<string>> = {
147
147
  title: [],
148
148
  }
149
149
 
150
+ const DOCUMENT_HEAD_TAGS = new Set(['base', 'link', 'meta', 'script', 'style', 'title'])
151
+
150
152
  // DOM elements already claimed by some fiber during this hydration pass.
151
153
  const CLAIMED = new WeakSet<Node>()
152
154
 
@@ -246,13 +248,23 @@ export function adoptHostDom(fiber: Fiber, parent: Fiber): boolean {
246
248
  if (!cursor) return false
247
249
 
248
250
  const tag = (fiber.type as string).toLowerCase()
251
+ const documentHeadParent = getDocumentHeadParent(cursor.parent, tag)
249
252
  const parentEl = cursor.parent as Element
250
253
  const parentTag =
251
254
  parentEl.nodeType === 1 ? (parentEl as Element).tagName.toLowerCase() : ''
252
- const isHeadish = parentTag === 'head' || parentTag === 'html'
255
+ const isHeadish = parentTag === 'head' || parentTag === 'html' || !!documentHeadParent
253
256
 
254
257
  let candidate: ChildNode | null
255
- if (isHeadish) {
258
+ if (documentHeadParent) {
259
+ // React 19 can project <meta>/<title>/<link> from anywhere in the tree into
260
+ // document.head. Redact does not have that projection yet, so when a
261
+ // document-root hydration pass sees a top-level head element, adopt it
262
+ // from <head> rather than trying to append it beside <html>.
263
+ candidate = new HydrationCursor(documentHeadParent).takeMatchingHeadElement(
264
+ tag,
265
+ fiber.pendingProps ?? {},
266
+ )
267
+ } else if (isHeadish) {
256
268
  // Head/html children are position-insensitive — server may emit them in
257
269
  // a different order than the React tree (React 19 head hoisting, etc.).
258
270
  // Scan forward without removing non-matching nodes; match on attribute
@@ -297,6 +309,11 @@ export function adoptHostDom(fiber: Fiber, parent: Fiber): boolean {
297
309
  return true
298
310
  }
299
311
 
312
+ function getDocumentHeadParent(parent: Node, tag: string): HTMLHeadElement | null {
313
+ if (parent.nodeType !== 9 || !DOCUMENT_HEAD_TAGS.has(tag)) return null
314
+ return (parent as Document).head
315
+ }
316
+
300
317
  export function adoptTextDom(fiber: Fiber, parent: Fiber, text: string): boolean {
301
318
  const cursor = hydrationCursors.get(findHostParent(parent))
302
319
  if (!cursor) return false
package/src/dom/index.ts CHANGED
@@ -14,6 +14,22 @@ export function preinit(_href: string, _opts?: any): void {}
14
14
  export function preloadModule(_href: string, _opts?: any): void {}
15
15
  export function preinitModule(_href: string, _opts?: any): void {}
16
16
 
17
+ export const __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = {
18
+ d: {
19
+ f() {},
20
+ r() {},
21
+ D() {},
22
+ C() {},
23
+ L() {},
24
+ m() {},
25
+ X() {},
26
+ S() {},
27
+ M() {},
28
+ },
29
+ p: 0,
30
+ findDOMNode: null,
31
+ }
32
+
17
33
  export const version = '19.2.3'
18
34
 
19
35
  // Required by React's default export consumers
@@ -29,5 +45,6 @@ export default {
29
45
  preinit,
30
46
  preloadModule,
31
47
  preinitModule,
48
+ __DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,
32
49
  version: '19.2.3',
33
50
  }