dinou 9.0.3 → 9.2.0

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