dinou 9.0.3 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,540 +1,603 @@
1
- // dinou/core/ppr-runtime.js
2
- // Dinou Partial Prerendering (PPR) Runtime Streaming Resume Engine.
3
- // Sends the pre-rendered shell immediately (0ms TTFB) and progressively
4
- // streams dynamic Suspense holes as they resolve over the same HTTP connection.
5
- // Designed for the Dual-Bundle architecture (Pass A: RSC, Pass B: SSR).
6
-
7
- import React from "react";
8
- import { renderRSCStream } from "./rsc-renderer.js";
9
- import { getClientManifest } from "./manifest-provider.js";
10
- import { requestStorage, setCurrentContext } from "./request-context.js";
11
- import getJSX from "./get-jsx.js";
12
-
13
- function escapeHtml(str) {
14
- return String(str)
15
- .replace(/&/g, "&")
16
- .replace(/</g, "&lt;")
17
- .replace(/>/g, "&gt;")
18
- .replace(/"/g, "&quot;")
19
- .replace(/'/g, "&#39;");
20
- }
21
-
22
- function isClientComponentRef(type) {
23
- if (!type) return false;
24
- return (
25
- type.$$typeof === Symbol.for("react.client.reference") ||
26
- Boolean(type.$$id) ||
27
- Boolean(type.filepath)
28
- );
29
- }
30
-
31
- /**
32
- * Splices live dynamic <Suspense> subtrees from a live page evaluation into a
33
- * cached PPR static shell client-JSX tree (deserialized from shell.page.json),
34
- * keeping the static shell of the page 100% immutable across /____rsc_page____
35
- * refreshes and soft-navigations while evaluating dynamic holes fresh.
36
- */
37
- async function spliceDynamicHolesIntoShell(
38
- cachedShellTree,
39
- livePageNodeOrFn,
40
- startHoleIndex = 0
41
- ) {
42
- const knownHoleIds = new Set();
43
- function collectKnownHoles(node) {
44
- if (!node || typeof node !== "object") return;
45
- if (Array.isArray(node)) {
46
- for (const item of node) collectKnownHoles(item);
47
- return;
48
- }
49
- if (node.$$typeof === Symbol.for("react.transitional.element")) {
50
- if (node.props && typeof node.props["data-ppr-hole"] === "string") {
51
- knownHoleIds.add(node.props["data-ppr-hole"]);
52
- }
53
- if (node.props && typeof node.props === "object") {
54
- for (const val of Object.values(node.props)) {
55
- if (val && typeof val === "object") collectKnownHoles(val);
56
- }
57
- }
58
- } else {
59
- for (const val of Object.values(node)) {
60
- if (val && typeof val === "object") collectKnownHoles(val);
61
- }
62
- }
63
- }
64
-
65
- collectKnownHoles(cachedShellTree);
66
- if (knownHoleIds.size === 0) {
67
- return cachedShellTree;
68
- }
69
-
70
- const livePageNode =
71
- typeof livePageNodeOrFn === "function"
72
- ? await livePageNodeOrFn()
73
- : livePageNodeOrFn;
74
-
75
- let holeIndex = Number(startHoleIndex) || 0;
76
- const liveHolesMap = new Map();
77
-
78
- async function traverseProps(props) {
79
- if (!props || typeof props !== "object") return;
80
- for (const [, value] of Object.entries(props)) {
81
- if (value && typeof value === "object") {
82
- await traverse(value);
83
- }
84
- }
85
- }
86
-
87
- async function traverse(current) {
88
- if (!current) return;
89
- if (Array.isArray(current)) {
90
- for (const item of current) {
91
- await traverse(item);
92
- }
93
- return;
94
- }
95
- if (typeof current !== "object" || current instanceof Promise) {
96
- return;
97
- }
98
- if (
99
- isClientComponentRef(current?.type) ||
100
- current?.$$typeof === Symbol.for("react.client.reference")
101
- ) {
102
- await traverseProps(current?.props);
103
- return;
104
- }
105
- if (typeof current?.type === "function") {
106
- try {
107
- const evaluated = await current.type(current.props || {});
108
- await traverse(evaluated);
109
- } catch (err) {
110
- console.error("[Dinou PPR] Error evaluating component in hole splice:", err);
111
- }
112
- return;
113
- }
114
- if (
115
- typeof current?.type === "object" &&
116
- current.type !== null &&
117
- current.type.$$typeof === Symbol.for("react.forward_ref")
118
- ) {
119
- if (isClientComponentRef(current.type)) {
120
- await traverseProps(current.props);
121
- return;
122
- }
123
- try {
124
- const rendered = await current.type.render(current.props || {}, current.ref);
125
- await traverse(rendered);
126
- } catch (err) {
127
- console.error("[Dinou PPR] Error evaluating forward_ref in hole splice:", err);
128
- }
129
- return;
130
- }
131
- if (
132
- typeof current?.type === "object" &&
133
- current.type !== null &&
134
- current.type.$$typeof === Symbol.for("react.memo")
135
- ) {
136
- if (isClientComponentRef(current.type)) {
137
- await traverseProps(current.props);
138
- return;
139
- }
140
- try {
141
- const innerComp = current.type.type;
142
- const rendered =
143
- typeof innerComp === "function" ? await innerComp(current.props || {}) : null;
144
- await traverse(rendered);
145
- } catch (err) {
146
- console.error("[Dinou PPR] Error evaluating memo in hole splice:", err);
147
- }
148
- return;
149
- }
150
- if (
151
- current?.type === Symbol.for("react.suspense") ||
152
- current?.type === React.Suspense
153
- ) {
154
- holeIndex++;
155
- const currentHoleId = `ppr-hole-${holeIndex}`;
156
- if (knownHoleIds.has(currentHoleId)) {
157
- liveHolesMap.set(currentHoleId, current);
158
- return;
159
- }
160
- if (current.props?.children) {
161
- await traverse(current.props.children);
162
- }
163
- if (current.props?.fallback) {
164
- await traverse(current.props.fallback);
165
- }
166
- return;
167
- }
168
- if (current?.$$typeof === Symbol.for("react.transitional.element")) {
169
- await traverseProps(current.props);
170
- } else {
171
- await traverseProps(current);
172
- }
173
- }
174
-
175
- await traverse(livePageNode);
176
-
177
- function replaceHoles(node) {
178
- if (!node || typeof node !== "object") return node;
179
- if (Array.isArray(node)) {
180
- return node.map((item) => replaceHoles(item));
181
- }
182
- if (node.$$typeof === Symbol.for("react.transitional.element")) {
183
- const holeId = node.props && node.props["data-ppr-hole"];
184
- if (typeof holeId === "string" && liveHolesMap.has(holeId)) {
185
- return liveHolesMap.get(holeId);
186
- }
187
- if (node.props && typeof node.props === "object") {
188
- let changed = false;
189
- const newProps = { ...node.props };
190
- for (const [k, v] of Object.entries(node.props)) {
191
- if (v && typeof v === "object") {
192
- const updated = replaceHoles(v);
193
- if (updated !== v) {
194
- newProps[k] = updated;
195
- changed = true;
196
- }
197
- }
198
- }
199
- if (changed) {
200
- if (node.key != null) newProps.key = node.key;
201
- const children = newProps.children;
202
- if (Array.isArray(children)) {
203
- delete newProps.children;
204
- return React.createElement(node.type, newProps, ...children);
205
- }
206
- return React.createElement(node.type, newProps);
207
- }
208
- }
209
- return node;
210
- }
211
- let changed = false;
212
- const clone = { ...node };
213
- for (const [k, v] of Object.entries(node)) {
214
- if (v && typeof v === "object") {
215
- const updated = replaceHoles(v);
216
- if (updated !== v) {
217
- clone[k] = updated;
218
- changed = true;
219
- }
220
- }
221
- }
222
- return changed ? clone : node;
223
- }
224
-
225
- return replaceHoles(cachedShellTree);
226
- }
227
-
228
- /**
229
- * Traverses a React JSX element tree to find Suspense boundaries,
230
- * evaluates their dynamic children, and streams replacement chunks.
231
- *
232
- * @param {object} node - Root JSX node (layout + page)
233
- * @param {Array<string|object>|null} expectedHoles - Holes registered at build time
234
- * @param {WritableStreamDefaultWriter} writer - Response stream writer
235
- * @param {TextEncoder} encoder - Text encoder
236
- * @param {object} platformContext - Dinou platform context (containing renderHtmlStream)
237
- * @param {boolean} isDevelopment - Dev mode flag
238
- */
239
- async function streamDynamicHoles(
240
- node,
241
- expectedHoles,
242
- writer,
243
- encoder,
244
- platformContext,
245
- isDevelopment = false
246
- ) {
247
- let holeIndex = 0;
248
- const holePromises = [];
249
-
250
- const hasExplicitHoles = Array.isArray(expectedHoles);
251
- const knownHoleIds = new Set(
252
- (expectedHoles || []).map((h) => (typeof h === "object" ? h.id : h))
253
- );
254
-
255
- const clientManifest = getClientManifest();
256
-
257
- async function traverseProps(props) {
258
- if (!props || typeof props !== "object") return;
259
- for (const [, value] of Object.entries(props)) {
260
- if (value && typeof value === "object") {
261
- await traverse(value);
262
- }
263
- }
264
- }
265
-
266
- async function traverse(current) {
267
- if (!current) return;
268
-
269
- // Handle Arrays (children)
270
- if (Array.isArray(current)) {
271
- for (const item of current) {
272
- await traverse(item);
273
- }
274
- return;
275
- }
276
-
277
- if (typeof current !== "object" || current instanceof Promise) {
278
- return;
279
- }
280
-
281
- // Handle Client Component: do NOT execute, only traverse props in deterministic order
282
- if (
283
- isClientComponentRef(current?.type) ||
284
- current?.$$typeof === Symbol.for("react.client.reference")
285
- ) {
286
- await traverseProps(current?.props);
287
- return;
288
- }
289
-
290
- // Handle React Server Component function
291
- if (typeof current?.type === "function") {
292
- try {
293
- const evaluated = await current.type(current.props || {});
294
- await traverse(evaluated);
295
- } catch (err) {
296
- console.error("[Dinou PPR] Error evaluating component in hole traversal:", err);
297
- }
298
- return;
299
- }
300
-
301
- // Handle React.forward_ref
302
- if (
303
- typeof current?.type === "object" &&
304
- current.type !== null &&
305
- current.type.$$typeof === Symbol.for("react.forward_ref")
306
- ) {
307
- if (isClientComponentRef(current.type)) {
308
- await traverseProps(current.props);
309
- return;
310
- }
311
- try {
312
- const rendered = await current.type.render(current.props || {}, current.ref);
313
- await traverse(rendered);
314
- } catch (err) {
315
- console.error("[Dinou PPR] Error evaluating forward_ref in hole traversal:", err);
316
- }
317
- return;
318
- }
319
-
320
- // Handle React.memo
321
- if (
322
- typeof current?.type === "object" &&
323
- current.type !== null &&
324
- current.type.$$typeof === Symbol.for("react.memo")
325
- ) {
326
- if (isClientComponentRef(current.type)) {
327
- await traverseProps(current.props);
328
- return;
329
- }
330
- try {
331
- const innerComp = current.type.type;
332
- const rendered =
333
- typeof innerComp === "function" ? await innerComp(current.props || {}) : null;
334
- await traverse(rendered);
335
- } catch (err) {
336
- console.error("[Dinou PPR] Error evaluating memo in hole traversal:", err);
337
- }
338
- return;
339
- }
340
-
341
- // Handle React.Suspense
342
- if (
343
- current?.type === Symbol.for("react.suspense") ||
344
- current?.type === React.Suspense
345
- ) {
346
- holeIndex++;
347
- const currentBoundaryIndex = holeIndex - 1;
348
- const currentHoleId = `ppr-hole-${holeIndex}`;
349
-
350
- // Check if this boundary was registered as a dynamic hole at build time
351
- const shouldStream = hasExplicitHoles
352
- ? knownHoleIds.has(currentHoleId)
353
- : true;
354
-
355
- if (shouldStream) {
356
- const children = current.props?.children;
357
- const promise = (async () => {
358
- try {
359
- let html = "";
360
- if (platformContext && platformContext.renderHtmlStream) {
361
- const rscStream = renderRSCStream(children, clientManifest, { runtime: "edge" });
362
- const htmlStream = await platformContext.renderHtmlStream(rscStream, {
363
- bootstrapModules: [],
364
- });
365
- html = await new Response(htmlStream).text();
366
- }
367
-
368
- const chunk = `\n<template id="ppr-content-${currentHoleId}">${html}</template>\n<script>(function(){var c=document.getElementById("ppr-content-${currentHoleId}");if(!c)return;var b=document.getElementById("B:${currentBoundaryIndex}");var t=document.querySelector('[data-ppr-hole="${currentHoleId}"]')||(b?b.nextElementSibling:null);try{if(t){if(c.content){t.replaceWith(c.content);}else{t.replaceWith.apply(t,Array.from(c.childNodes));}}}finally{c.remove();}})();</script>\n`;
369
- await writer.write(encoder.encode(chunk));
370
- } catch (holeErr) {
371
- console.error(`[Dinou PPR] Error resolving dynamic hole ${currentHoleId}:`, holeErr);
372
- const rawErrMsg = isDevelopment
373
- ? (holeErr?.message || "Unknown dynamic error")
374
- : "Error loading dynamic content";
375
- const errMsg = escapeHtml(rawErrMsg);
376
- const errChunk = `\n<template id="ppr-content-${currentHoleId}"><div style="color:#e11d48;padding:8px 12px;background:#fff1f2;border:1px solid #fecdd3;border-radius:6px;font-size:0.875rem;font-family:system-ui,sans-serif;">[PPR Error: ${errMsg}]</div></template>\n<script>(function(){var c=document.getElementById("ppr-content-${currentHoleId}");if(!c)return;var b=document.getElementById("B:${currentBoundaryIndex}");var t=document.querySelector('[data-ppr-hole="${currentHoleId}"]')||(b?b.nextElementSibling:null);try{if(t){if(c.content){t.replaceWith(c.content);}else{t.replaceWith.apply(t,Array.from(c.childNodes));}}}finally{c.remove();}})();</script>\n`;
377
- await writer.write(encoder.encode(errChunk));
378
- }
379
- })();
380
- holePromises.push(promise);
381
- return;
382
- }
383
-
384
- // Static <Suspense> boundary: do not re-stream it, but traverse its children & fallback
385
- // in the same order as asyncRenderJSXToClientJSX so nested dynamic <Suspense> holes are
386
- // discovered and holeIndex remains synchronized.
387
- if (current.props?.children) {
388
- await traverse(current.props.children);
389
- }
390
- if (current.props?.fallback) {
391
- await traverse(current.props.fallback);
392
- }
393
- return;
394
- }
395
-
396
- // Traverse host element / Fragment props or plain props object
397
- if (current?.$$typeof === Symbol.for("react.transitional.element")) {
398
- await traverseProps(current.props);
399
- } else {
400
- await traverseProps(current);
401
- }
402
- }
403
-
404
- await traverse(node);
405
- await Promise.all(holePromises);
406
- }
407
-
408
- /**
409
- * Handles PPR Runtime Streaming Resume.
410
- * Immediately flushes shellPrelude to the client, then resolves dynamic holes in parallel.
411
- */
412
- async function handlePprResume({
413
- reqPath,
414
- queryObj,
415
- simReq,
416
- bridge,
417
- platformContext,
418
- rootContext,
419
- cachedItem,
420
- metadata,
421
- isDevelopment,
422
- getDiscoveredLayouts,
423
- createRequestContext,
424
- copyCustomContextProperties,
425
- }) {
426
- let shellHtml = cachedItem.content;
427
- if (typeof shellHtml === "string") {
428
- if (!shellHtml.includes("window.__DINOU_LAYOUTS__")) {
429
- const knownLayouts = typeof getDiscoveredLayouts === "function" ? getDiscoveredLayouts() : {};
430
- shellHtml = shellHtml.replace(
431
- "</head>",
432
- `<script>window.__DINOU_LAYOUTS__=${JSON.stringify(knownLayouts)};</script></head>`
433
- );
434
- }
435
- shellHtml = shellHtml.replace(
436
- /window\.__DINOU_USE_STATIC__\s*=\s*true;?/g,
437
- "window.__DINOU_USE_STATIC__ = false; window.__DINOU_PPR__ = true;"
438
- );
439
- if (!shellHtml.includes("window.__DINOU_PPR__")) {
440
- shellHtml = shellHtml.replace(
441
- "</head>",
442
- `<script>window.__DINOU_USE_STATIC__ = false; window.__DINOU_PPR__ = true;</script></head>`
443
- );
444
- }
445
- }
446
-
447
- // Separate shell into prelude (up to </body>) and postlude
448
- const lowerHtml = shellHtml.toLowerCase();
449
- const bodyCloseIndex = lowerHtml.lastIndexOf("</body>");
450
- let shellPrelude =
451
- bodyCloseIndex !== -1 ? shellHtml.slice(0, bodyCloseIndex) : shellHtml;
452
- let shellPostlude =
453
- bodyCloseIndex !== -1 ? shellHtml.slice(bodyCloseIndex) : "</body></html>";
454
-
455
- const { readable, writable } = new TransformStream();
456
- const writer = writable.getWriter();
457
- const encoder = new TextEncoder();
458
-
459
- // Stream dynamic holes in parallel with the prelude
460
- const resumePromise = (async () => {
461
- try {
462
- // 1. Immediately flush static shell prelude (0ms TTFB)
463
- await writer.write(encoder.encode(shellPrelude));
464
-
465
- const dynamicState = { value: true };
466
- const context = createRequestContext(simReq, bridge, platformContext, dynamicState);
467
- if (typeof copyCustomContextProperties === "function") {
468
- copyCustomContextProperties(rootContext, context);
469
- }
470
- if (typeof setCurrentContext === "function") {
471
- setCurrentContext(context);
472
- }
473
-
474
- await requestStorage.run(context, async () => {
475
- const isNotFound = { value: false };
476
- const jsx = await getJSX(
477
- reqPath,
478
- queryObj,
479
- isNotFound,
480
- isDevelopment,
481
- false
482
- );
483
-
484
- let holes = Array.isArray(metadata?.holes) ? metadata.holes : null;
485
- if ((!holes || holes.length === 0) && typeof shellPrelude === "string") {
486
- const extracted = [
487
- ...shellPrelude.matchAll(/data-ppr-hole="(ppr-hole-\d+)"/g),
488
- ].map((m) => m[1]);
489
- if (extracted.length > 0 || Array.isArray(metadata?.holes)) {
490
- holes = extracted;
491
- }
492
- }
493
-
494
- await streamDynamicHoles(
495
- jsx,
496
- holes,
497
- writer,
498
- encoder,
499
- platformContext,
500
- isDevelopment
501
- );
502
- });
503
- } catch (streamErr) {
504
- console.error("[Dinou PPR] Runtime streaming resume error:", streamErr);
505
- } finally {
506
- try {
507
- await writer.write(encoder.encode(shellPostlude));
508
- await writer.close();
509
- } catch (_) {}
510
- }
511
- })();
512
-
513
- if (
514
- platformContext &&
515
- platformContext.ctx &&
516
- typeof platformContext.ctx.waitUntil === "function"
517
- ) {
518
- platformContext.ctx.waitUntil(resumePromise);
519
- }
520
-
521
- const headers = new Headers(bridge.headers);
522
- headers.set("Content-Type", "text/html; charset=utf-8");
523
- headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
524
-
525
- return new Response(readable, {
526
- status: metadata?.status || 200,
527
- headers,
528
- });
529
- }
530
-
531
- export {
532
- streamDynamicHoles,
533
- handlePprResume,
534
- spliceDynamicHolesIntoShell,
535
- };
536
- export default {
537
- streamDynamicHoles,
538
- handlePprResume,
539
- spliceDynamicHolesIntoShell,
540
- };
1
+ // dinou/core/ppr-runtime.js
2
+ // Dinou Partial Prerendering (PPR) Runtime Streaming Resume Engine.
3
+ // Sends the pre-rendered shell immediately (0ms TTFB) and progressively
4
+ // streams dynamic Suspense holes as they resolve over the same HTTP connection.
5
+ // Designed for the Dual-Bundle architecture (Pass A: RSC, Pass B: SSR).
6
+
7
+ import React from "react";
8
+ import { renderRSCStream } from "./rsc-renderer.js";
9
+ import { getClientManifest } from "./manifest-provider.js";
10
+ import { requestStorage, setCurrentContext } from "./request-context.js";
11
+ import getJSX from "./get-jsx.js";
12
+ import {
13
+ SKIP_STATIC_SUSPENSE_SYMBOL,
14
+ runInRuntimeStaticSuspense,
15
+ runInRuntimeDynamicHole,
16
+ } from "./ppr-context.js";
17
+
18
+ function escapeHtml(str) {
19
+ return String(str)
20
+ .replace(/&/g, "&amp;")
21
+ .replace(/</g, "&lt;")
22
+ .replace(/>/g, "&gt;")
23
+ .replace(/"/g, "&quot;")
24
+ .replace(/'/g, "&#39;");
25
+ }
26
+
27
+ function isClientComponentRef(type) {
28
+ if (!type) return false;
29
+ return (
30
+ type.$$typeof === Symbol.for("react.client.reference") ||
31
+ Boolean(type.$$id) ||
32
+ Boolean(type.filepath)
33
+ );
34
+ }
35
+
36
+ /**
37
+ * Splices live dynamic <Suspense> subtrees from a live page evaluation into a
38
+ * cached PPR static shell client-JSX tree (deserialized from shell.page.json),
39
+ * keeping the static shell of the page 100% immutable across /____rsc_page____
40
+ * refreshes and soft-navigations while evaluating dynamic holes fresh.
41
+ */
42
+ async function spliceDynamicHolesIntoShell(
43
+ cachedShellTree,
44
+ livePageNodeOrFn,
45
+ startHoleIndex = 0
46
+ ) {
47
+ const knownHoleIds = new Set();
48
+ const staticParentHoleIds = new Set();
49
+ function collectKnownHoles(node) {
50
+ if (!node || typeof node !== "object") return;
51
+ if (Array.isArray(node)) {
52
+ for (const item of node) collectKnownHoles(item);
53
+ return;
54
+ }
55
+ if (node.$$typeof === Symbol.for("react.transitional.element")) {
56
+ if (node.props && typeof node.props["data-ppr-hole"] === "string") {
57
+ knownHoleIds.add(node.props["data-ppr-hole"]);
58
+ }
59
+ if (node.props && typeof node.props["data-ppr-static-parent"] === "string") {
60
+ staticParentHoleIds.add(node.props["data-ppr-static-parent"]);
61
+ }
62
+ if (node.props && typeof node.props === "object") {
63
+ for (const val of Object.values(node.props)) {
64
+ if (val && typeof val === "object") collectKnownHoles(val);
65
+ }
66
+ }
67
+ } else {
68
+ for (const val of Object.values(node)) {
69
+ if (val && typeof val === "object") collectKnownHoles(val);
70
+ }
71
+ }
72
+ }
73
+
74
+ collectKnownHoles(cachedShellTree);
75
+ if (knownHoleIds.size === 0) {
76
+ return cachedShellTree;
77
+ }
78
+
79
+ const livePageNode =
80
+ typeof livePageNodeOrFn === "function"
81
+ ? await livePageNodeOrFn()
82
+ : livePageNodeOrFn;
83
+
84
+ let holeIndex = Number(startHoleIndex) || 0;
85
+ const liveHolesMap = new Map();
86
+
87
+ async function traverseProps(props) {
88
+ if (!props || typeof props !== "object") return;
89
+ for (const [, value] of Object.entries(props)) {
90
+ if (value && typeof value === "object") {
91
+ await traverse(value);
92
+ }
93
+ }
94
+ }
95
+
96
+ async function traverse(current) {
97
+ if (!current || liveHolesMap.size >= knownHoleIds.size) return;
98
+ if (Array.isArray(current)) {
99
+ for (const item of current) {
100
+ if (liveHolesMap.size >= knownHoleIds.size) return;
101
+ await traverse(item);
102
+ }
103
+ return;
104
+ }
105
+ if (typeof current !== "object" || current instanceof Promise) {
106
+ return;
107
+ }
108
+ if (
109
+ isClientComponentRef(current?.type) ||
110
+ current?.$$typeof === Symbol.for("react.client.reference")
111
+ ) {
112
+ await traverseProps(current?.props);
113
+ return;
114
+ }
115
+ if (typeof current?.type === "function") {
116
+ try {
117
+ const evaluated = await current.type(current.props || {});
118
+ await traverse(evaluated);
119
+ } catch (err) {
120
+ if (err && err.$$typeof === SKIP_STATIC_SUSPENSE_SYMBOL) {
121
+ return;
122
+ }
123
+ console.error("[Dinou PPR] Error evaluating component in hole splice:", err);
124
+ }
125
+ return;
126
+ }
127
+ if (
128
+ typeof current?.type === "object" &&
129
+ current.type !== null &&
130
+ current.type.$$typeof === Symbol.for("react.forward_ref")
131
+ ) {
132
+ if (isClientComponentRef(current.type)) {
133
+ await traverseProps(current.props);
134
+ return;
135
+ }
136
+ try {
137
+ const rendered = await current.type.render(current.props || {}, current.ref);
138
+ await traverse(rendered);
139
+ } catch (err) {
140
+ if (err && err.$$typeof === SKIP_STATIC_SUSPENSE_SYMBOL) {
141
+ return;
142
+ }
143
+ console.error("[Dinou PPR] Error evaluating forward_ref in hole splice:", err);
144
+ }
145
+ return;
146
+ }
147
+ if (
148
+ typeof current?.type === "object" &&
149
+ current.type !== null &&
150
+ current.type.$$typeof === Symbol.for("react.memo")
151
+ ) {
152
+ if (isClientComponentRef(current.type)) {
153
+ await traverseProps(current.props);
154
+ return;
155
+ }
156
+ try {
157
+ const innerComp = current.type.type;
158
+ const rendered =
159
+ typeof innerComp === "function" ? await innerComp(current.props || {}) : null;
160
+ await traverse(rendered);
161
+ } catch (err) {
162
+ if (err && err.$$typeof === SKIP_STATIC_SUSPENSE_SYMBOL) {
163
+ return;
164
+ }
165
+ console.error("[Dinou PPR] Error evaluating memo in hole splice:", err);
166
+ }
167
+ return;
168
+ }
169
+ if (
170
+ current?.type === Symbol.for("react.suspense") ||
171
+ current?.type === React.Suspense
172
+ ) {
173
+ holeIndex++;
174
+ const currentHoleId = `ppr-hole-${holeIndex}`;
175
+ if (knownHoleIds.has(currentHoleId)) {
176
+ liveHolesMap.set(currentHoleId, current);
177
+ return;
178
+ }
179
+ const runStaticScope = staticParentHoleIds.has(currentHoleId)
180
+ ? runInRuntimeDynamicHole
181
+ : runInRuntimeStaticSuspense;
182
+ await runStaticScope(async () => {
183
+ if (current.props?.children) {
184
+ await traverse(current.props.children);
185
+ }
186
+ if (current.props?.fallback) {
187
+ await traverse(current.props.fallback);
188
+ }
189
+ });
190
+ return;
191
+ }
192
+ if (current?.$$typeof === Symbol.for("react.transitional.element")) {
193
+ await traverseProps(current.props);
194
+ } else {
195
+ await traverseProps(current);
196
+ }
197
+ }
198
+
199
+ await traverse(livePageNode);
200
+
201
+ function replaceHoles(node) {
202
+ if (!node || typeof node !== "object") return node;
203
+ if (Array.isArray(node)) {
204
+ return node.map((item) => replaceHoles(item));
205
+ }
206
+ if (node.$$typeof === Symbol.for("react.transitional.element")) {
207
+ const holeId = node.props && node.props["data-ppr-hole"];
208
+ if (typeof holeId === "string" && liveHolesMap.has(holeId)) {
209
+ return liveHolesMap.get(holeId);
210
+ }
211
+ if (node.props && typeof node.props === "object") {
212
+ let changed = false;
213
+ const newProps = { ...node.props };
214
+ for (const [k, v] of Object.entries(node.props)) {
215
+ if (v && typeof v === "object") {
216
+ const updated = replaceHoles(v);
217
+ if (updated !== v) {
218
+ newProps[k] = updated;
219
+ changed = true;
220
+ }
221
+ }
222
+ }
223
+ if (changed) {
224
+ if (node.key != null) newProps.key = node.key;
225
+ const children = newProps.children;
226
+ if (Array.isArray(children)) {
227
+ delete newProps.children;
228
+ return React.createElement(node.type, newProps, ...children);
229
+ }
230
+ return React.createElement(node.type, newProps);
231
+ }
232
+ }
233
+ return node;
234
+ }
235
+ let changed = false;
236
+ const clone = { ...node };
237
+ for (const [k, v] of Object.entries(node)) {
238
+ if (v && typeof v === "object") {
239
+ const updated = replaceHoles(v);
240
+ if (updated !== v) {
241
+ clone[k] = updated;
242
+ changed = true;
243
+ }
244
+ }
245
+ }
246
+ return changed ? clone : node;
247
+ }
248
+
249
+ return replaceHoles(cachedShellTree);
250
+ }
251
+
252
+ /**
253
+ * Traverses a React JSX element tree to find Suspense boundaries,
254
+ * evaluates their dynamic children, and streams replacement chunks.
255
+ *
256
+ * @param {object} node - Root JSX node (layout + page)
257
+ * @param {Array<string|object>|null} expectedHoles - Holes registered at build time
258
+ * @param {WritableStreamDefaultWriter} writer - Response stream writer
259
+ * @param {TextEncoder} encoder - Text encoder
260
+ * @param {object} platformContext - Dinou platform context (containing renderHtmlStream)
261
+ * @param {boolean} isDevelopment - Dev mode flag
262
+ */
263
+ async function streamDynamicHoles(
264
+ node,
265
+ expectedHoles,
266
+ writer,
267
+ encoder,
268
+ platformContext,
269
+ isDevelopment = false,
270
+ staticParentHoles = null
271
+ ) {
272
+ let holeIndex = 0;
273
+ const holePromises = [];
274
+
275
+ const hasExplicitHoles = Array.isArray(expectedHoles);
276
+ const knownHoleIds = new Set(
277
+ (expectedHoles || []).map((h) => (typeof h === "object" ? h.id : h))
278
+ );
279
+ if (hasExplicitHoles && knownHoleIds.size === 0) {
280
+ return;
281
+ }
282
+
283
+ const clientManifest = getClientManifest();
284
+
285
+ async function traverseProps(props) {
286
+ if (!props || typeof props !== "object") return;
287
+ for (const [, value] of Object.entries(props)) {
288
+ if (hasExplicitHoles && holePromises.length >= knownHoleIds.size) return;
289
+ if (value && typeof value === "object") {
290
+ await traverse(value);
291
+ }
292
+ }
293
+ }
294
+
295
+ async function traverse(current) {
296
+ if (!current || (hasExplicitHoles && holePromises.length >= knownHoleIds.size)) return;
297
+
298
+ // Handle Arrays (children)
299
+ if (Array.isArray(current)) {
300
+ for (const item of current) {
301
+ if (hasExplicitHoles && holePromises.length >= knownHoleIds.size) return;
302
+ await traverse(item);
303
+ }
304
+ return;
305
+ }
306
+
307
+ if (typeof current !== "object" || current instanceof Promise) {
308
+ return;
309
+ }
310
+
311
+ // Handle Client Component: do NOT execute, only traverse props in deterministic order
312
+ if (
313
+ isClientComponentRef(current?.type) ||
314
+ current?.$$typeof === Symbol.for("react.client.reference")
315
+ ) {
316
+ await traverseProps(current?.props);
317
+ return;
318
+ }
319
+
320
+ // Handle React Server Component function
321
+ if (typeof current?.type === "function") {
322
+ try {
323
+ const evaluated = await current.type(current.props || {});
324
+ await traverse(evaluated);
325
+ } catch (err) {
326
+ if (err && err.$$typeof === SKIP_STATIC_SUSPENSE_SYMBOL) {
327
+ return;
328
+ }
329
+ console.error("[Dinou PPR] Error evaluating component in hole traversal:", err);
330
+ }
331
+ return;
332
+ }
333
+
334
+ // Handle React.forward_ref
335
+ if (
336
+ typeof current?.type === "object" &&
337
+ current.type !== null &&
338
+ current.type.$$typeof === Symbol.for("react.forward_ref")
339
+ ) {
340
+ if (isClientComponentRef(current.type)) {
341
+ await traverseProps(current.props);
342
+ return;
343
+ }
344
+ try {
345
+ const rendered = await current.type.render(current.props || {}, current.ref);
346
+ await traverse(rendered);
347
+ } catch (err) {
348
+ if (err && err.$$typeof === SKIP_STATIC_SUSPENSE_SYMBOL) {
349
+ return;
350
+ }
351
+ console.error("[Dinou PPR] Error evaluating forward_ref in hole traversal:", err);
352
+ }
353
+ return;
354
+ }
355
+
356
+ // Handle React.memo
357
+ if (
358
+ typeof current?.type === "object" &&
359
+ current.type !== null &&
360
+ current.type.$$typeof === Symbol.for("react.memo")
361
+ ) {
362
+ if (isClientComponentRef(current.type)) {
363
+ await traverseProps(current.props);
364
+ return;
365
+ }
366
+ try {
367
+ const innerComp = current.type.type;
368
+ const rendered =
369
+ typeof innerComp === "function" ? await innerComp(current.props || {}) : null;
370
+ await traverse(rendered);
371
+ } catch (err) {
372
+ if (err && err.$$typeof === SKIP_STATIC_SUSPENSE_SYMBOL) {
373
+ return;
374
+ }
375
+ console.error("[Dinou PPR] Error evaluating memo in hole traversal:", err);
376
+ }
377
+ return;
378
+ }
379
+
380
+ // Handle React.Suspense
381
+ if (
382
+ current?.type === Symbol.for("react.suspense") ||
383
+ current?.type === React.Suspense
384
+ ) {
385
+ holeIndex++;
386
+ const currentBoundaryIndex = holeIndex - 1;
387
+ const currentHoleId = `ppr-hole-${holeIndex}`;
388
+
389
+ // Check if this boundary was registered as a dynamic hole at build time
390
+ const shouldStream = hasExplicitHoles
391
+ ? knownHoleIds.has(currentHoleId)
392
+ : true;
393
+
394
+ if (shouldStream) {
395
+ const children = current.props?.children;
396
+ const promise = runInRuntimeDynamicHole(() => (async () => {
397
+ try {
398
+ let html = "";
399
+ if (platformContext && platformContext.renderHtmlStream) {
400
+ const rscStream = renderRSCStream(children, clientManifest, { runtime: "edge" });
401
+ const htmlStream = await platformContext.renderHtmlStream(rscStream, {
402
+ bootstrapModules: [],
403
+ });
404
+ html = await new Response(htmlStream).text();
405
+ }
406
+
407
+ const chunk = `\n<template id="ppr-content-${currentHoleId}">${html}</template>\n<script>(function(){var c=document.getElementById("ppr-content-${currentHoleId}");if(!c)return;var b=document.getElementById("B:${currentBoundaryIndex}");var t=document.querySelector('[data-ppr-hole="${currentHoleId}"]')||(b?b.nextElementSibling:null);try{if(t){if(c.content){t.replaceWith(c.content);}else{t.replaceWith.apply(t,Array.from(c.childNodes));}}}finally{c.remove();}})();</script>\n`;
408
+ await writer.write(encoder.encode(chunk));
409
+ } catch (holeErr) {
410
+ console.error(`[Dinou PPR] Error resolving dynamic hole ${currentHoleId}:`, holeErr);
411
+ const rawErrMsg = isDevelopment
412
+ ? (holeErr?.message || "Unknown dynamic error")
413
+ : "Error loading dynamic content";
414
+ const errMsg = escapeHtml(rawErrMsg);
415
+ const errChunk = `\n<template id="ppr-content-${currentHoleId}"><div style="color:#e11d48;padding:8px 12px;background:#fff1f2;border:1px solid #fecdd3;border-radius:6px;font-size:0.875rem;font-family:system-ui,sans-serif;">[PPR Error: ${errMsg}]</div></template>\n<script>(function(){var c=document.getElementById("ppr-content-${currentHoleId}");if(!c)return;var b=document.getElementById("B:${currentBoundaryIndex}");var t=document.querySelector('[data-ppr-hole="${currentHoleId}"]')||(b?b.nextElementSibling:null);try{if(t){if(c.content){t.replaceWith(c.content);}else{t.replaceWith.apply(t,Array.from(c.childNodes));}}}finally{c.remove();}})();</script>\n`;
416
+ await writer.write(encoder.encode(errChunk));
417
+ }
418
+ })());
419
+ holePromises.push(promise);
420
+ return;
421
+ }
422
+
423
+ // Static <Suspense> boundary: do not re-stream it, but traverse its children & fallback
424
+ // in the same order as asyncRenderJSXToClientJSX so nested dynamic <Suspense> holes are
425
+ // discovered and holeIndex remains synchronized.
426
+ const runStaticScope =
427
+ staticParentHoles && staticParentHoles.has(currentHoleId)
428
+ ? runInRuntimeDynamicHole
429
+ : runInRuntimeStaticSuspense;
430
+ await runStaticScope(async () => {
431
+ if (current.props?.children) {
432
+ await traverse(current.props.children);
433
+ }
434
+ if (current.props?.fallback) {
435
+ await traverse(current.props.fallback);
436
+ }
437
+ });
438
+ return;
439
+ }
440
+
441
+ // Traverse host element / Fragment props or plain props object
442
+ if (current?.$$typeof === Symbol.for("react.transitional.element")) {
443
+ await traverseProps(current.props);
444
+ } else {
445
+ await traverseProps(current);
446
+ }
447
+ }
448
+
449
+ await traverse(node);
450
+ await Promise.all(holePromises);
451
+ }
452
+
453
+ /**
454
+ * Handles PPR Runtime Streaming Resume.
455
+ * Immediately flushes shellPrelude to the client, then resolves dynamic holes in parallel.
456
+ */
457
+ async function handlePprResume({
458
+ reqPath,
459
+ queryObj,
460
+ simReq,
461
+ bridge,
462
+ platformContext,
463
+ rootContext,
464
+ cachedItem,
465
+ metadata,
466
+ isDevelopment,
467
+ getDiscoveredLayouts,
468
+ createRequestContext,
469
+ copyCustomContextProperties,
470
+ }) {
471
+ let shellHtml = cachedItem.content;
472
+ if (typeof shellHtml === "string") {
473
+ if (!shellHtml.includes("window.__DINOU_LAYOUTS__")) {
474
+ const knownLayouts = typeof getDiscoveredLayouts === "function" ? getDiscoveredLayouts() : {};
475
+ shellHtml = shellHtml.replace(
476
+ "</head>",
477
+ `<script>window.__DINOU_LAYOUTS__=${JSON.stringify(knownLayouts)};</script></head>`
478
+ );
479
+ }
480
+ shellHtml = shellHtml.replace(
481
+ /window\.__DINOU_USE_STATIC__\s*=\s*true;?/g,
482
+ "window.__DINOU_USE_STATIC__ = false; window.__DINOU_PPR__ = true;"
483
+ );
484
+ if (!shellHtml.includes("window.__DINOU_PPR__")) {
485
+ shellHtml = shellHtml.replace(
486
+ "</head>",
487
+ `<script>window.__DINOU_USE_STATIC__ = false; window.__DINOU_PPR__ = true;</script></head>`
488
+ );
489
+ }
490
+ }
491
+
492
+ // Separate shell into prelude (up to </body>) and postlude
493
+ const lowerHtml = shellHtml.toLowerCase();
494
+ const bodyCloseIndex = lowerHtml.lastIndexOf("</body>");
495
+ let shellPrelude =
496
+ bodyCloseIndex !== -1 ? shellHtml.slice(0, bodyCloseIndex) : shellHtml;
497
+ let shellPostlude =
498
+ bodyCloseIndex !== -1 ? shellHtml.slice(bodyCloseIndex) : "</body></html>";
499
+
500
+ const { readable, writable } = new TransformStream();
501
+ const writer = writable.getWriter();
502
+ const encoder = new TextEncoder();
503
+
504
+ // Stream dynamic holes in parallel with the prelude
505
+ const resumePromise = (async () => {
506
+ try {
507
+ // 1. Immediately flush static shell prelude (0ms TTFB)
508
+ await writer.write(encoder.encode(shellPrelude));
509
+
510
+ let holes = Array.isArray(metadata?.holes) ? metadata.holes : null;
511
+ if ((!holes || holes.length === 0) && typeof shellPrelude === "string") {
512
+ const extracted = [
513
+ ...shellPrelude.matchAll(/data-ppr-hole="(ppr-hole-\d+)"/g),
514
+ ].map((m) => m[1]);
515
+ if (extracted.length > 0 || Array.isArray(metadata?.holes)) {
516
+ holes = extracted;
517
+ }
518
+ }
519
+
520
+ if (Array.isArray(holes) && holes.length === 0) {
521
+ return;
522
+ }
523
+
524
+ const dynamicState = { value: true };
525
+ const context = createRequestContext(simReq, bridge, platformContext, dynamicState);
526
+ context._isPprRuntimeResume = true;
527
+ if (typeof copyCustomContextProperties === "function") {
528
+ copyCustomContextProperties(rootContext, context);
529
+ }
530
+ if (typeof setCurrentContext === "function") {
531
+ setCurrentContext(context);
532
+ }
533
+
534
+ await requestStorage.run(context, async () => {
535
+ const isNotFound = { value: false };
536
+ const jsx = await getJSX(
537
+ reqPath,
538
+ queryObj,
539
+ isNotFound,
540
+ isDevelopment,
541
+ false,
542
+ { skipLayoutProbe: true }
543
+ );
544
+
545
+ const staticParentHoles =
546
+ typeof shellPrelude === "string"
547
+ ? new Set(
548
+ [
549
+ ...shellPrelude.matchAll(
550
+ /data-ppr-static-parent="(ppr-hole-\d+)"/g
551
+ ),
552
+ ].map((m) => m[1])
553
+ )
554
+ : null;
555
+
556
+ await streamDynamicHoles(
557
+ jsx,
558
+ holes,
559
+ writer,
560
+ encoder,
561
+ platformContext,
562
+ isDevelopment,
563
+ staticParentHoles
564
+ );
565
+ });
566
+ } catch (streamErr) {
567
+ console.error("[Dinou PPR] Runtime streaming resume error:", streamErr);
568
+ } finally {
569
+ try {
570
+ await writer.write(encoder.encode(shellPostlude));
571
+ await writer.close();
572
+ } catch (_) {}
573
+ }
574
+ })();
575
+
576
+ if (
577
+ platformContext &&
578
+ platformContext.ctx &&
579
+ typeof platformContext.ctx.waitUntil === "function"
580
+ ) {
581
+ platformContext.ctx.waitUntil(resumePromise);
582
+ }
583
+
584
+ const headers = new Headers(bridge.headers);
585
+ headers.set("Content-Type", "text/html; charset=utf-8");
586
+ headers.set("Cache-Control", "no-store, no-cache, must-revalidate");
587
+
588
+ return new Response(readable, {
589
+ status: metadata?.status || 200,
590
+ headers,
591
+ });
592
+ }
593
+
594
+ export {
595
+ streamDynamicHoles,
596
+ handlePprResume,
597
+ spliceDynamicHolesIntoShell,
598
+ };
599
+ export default {
600
+ streamDynamicHoles,
601
+ handlePprResume,
602
+ spliceDynamicHolesIntoShell,
603
+ };