dinou 9.0.2 → 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.
Files changed (41) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +379 -9742
  3. package/dinou/bun/build.js +38 -1
  4. package/{cli.js → dinou/cli.js} +8 -7
  5. package/dinou/cloudflare/build.js +37 -0
  6. package/dinou/core/bailout-proxy.js +2 -2
  7. package/dinou/core/build-static-pages.js +17 -7
  8. package/dinou/core/cache-revalidate.js +977 -152
  9. package/dinou/core/cache-slot.js +848 -103
  10. package/dinou/core/client-webpack.jsx +60 -9
  11. package/dinou/core/client.jsx +60 -9
  12. package/dinou/core/edge-ssr.js +33 -5
  13. package/dinou/core/generate-static.js +109 -47
  14. package/dinou/core/get-jsx.js +35 -27
  15. package/dinou/core/handler.js +786 -54
  16. package/dinou/core/layout-functions.js +102 -1
  17. package/dinou/core/no-dynamic.js +25 -0
  18. package/dinou/core/ppr-context.js +293 -10
  19. package/dinou/core/ppr-runtime.js +373 -37
  20. package/dinou/core/render-jsx-to-client-jsx.js +205 -74
  21. package/dinou/core/slot.js +246 -33
  22. package/dinou/core/storage-adapter.js +117 -11
  23. package/dinou/deno/build.js +38 -1
  24. package/dinou/deno/seed-kv.js +43 -11
  25. package/dinou/esbuild/helpers-esbuild/swc-disk-cache.js +242 -225
  26. package/dinou/esbuild/plugins-esbuild/server-functions-plugin.js +253 -226
  27. package/dinou/esbuild/react-refresh/esm-hmr/client.js +209 -209
  28. package/dinou/index.d.ts +10 -0
  29. package/dinou/index.js +3 -0
  30. package/dinou/node/build.js +2 -2
  31. package/dinou/node/bundle-dual-engine.js +2 -0
  32. package/dinou/node/dev.js +2853 -2704
  33. package/dinou/package.json +4 -1
  34. package/dinou/rollup/react-refresh/esm-hmr/client.js +220 -220
  35. package/dinou/rollup/rollup-plugins/rollup-plugin-server-functions.js +182 -160
  36. package/dinou/server.d.ts +65 -12
  37. package/dinou/server.js +11 -0
  38. package/dinou/webpack/loaders/server-functions-loader.js +101 -94
  39. package/dinou/webpack/webpack.config.js +9 -4
  40. package/eject.js +219 -223
  41. package/package.json +2 -2
@@ -1,10 +1,236 @@
1
1
  import path from "node:path";
2
2
  import fs from "node:fs/promises";
3
3
  import { existsSync, copyFileSync } from "node:fs";
4
- import { getContext } from "./request-context.js";
4
+ import { AsyncLocalStorage } from "node:async_hooks";
5
+ import { getContext, requestStorage } from "./request-context.js";
5
6
  import { resolveRelativeUrl } from "./url-resolver.js";
6
7
  import { getStorageAdapter } from "./storage-adapter.js";
7
- import { isEdgeRuntime } from "./rsc-renderer.js";
8
+ import { isEdgeRuntime, renderRSCStream } from "./rsc-renderer.js";
9
+ import getJSX from "./get-jsx.js";
10
+ import { getFilePathAndDynamicParams } from "./get-file-path-and-dynamic-params.js";
11
+ import { getActiveLayoutChain, resolveLayoutFunctionsConfig } from "./layout-functions.js";
12
+ import importModule from "./import-module.js";
13
+ import { resolveModulePpr } from "./resolve-module-ppr.js";
14
+ import { getDinouConfig } from "./load-dinou-config.js";
15
+ import { createBailoutProxy } from "./bailout-proxy.js";
16
+ import {
17
+ runWithPprContext,
18
+ resetPprHoles,
19
+ getRegisteredHoles,
20
+ getPprHoleCounter,
21
+ runInPageSegment,
22
+ runInLayoutSegment,
23
+ } from "./ppr-context.js";
24
+ import { asyncRenderJSXToClientJSX } from "./render-jsx-to-client-jsx.js";
25
+ import {
26
+ serializeJSX,
27
+ deserializeJSX,
28
+ refreshNestedSlotsInTree,
29
+ } from "./cache-slot.js";
30
+
31
+ const INFLIGHT_LAYOUT_REVAL_KEY = Symbol.for("dinou.layout.inflight.revalidations");
32
+ if (!globalThis[INFLIGHT_LAYOUT_REVAL_KEY]) {
33
+ globalThis[INFLIGHT_LAYOUT_REVAL_KEY] = new Map();
34
+ }
35
+ const inflightLayoutRevalidations = globalThis[INFLIGHT_LAYOUT_REVAL_KEY];
36
+
37
+ const REVAL_QUEUE_STORAGE_KEY = Symbol.for("dinou.reval.queue.storage");
38
+ if (!globalThis[REVAL_QUEUE_STORAGE_KEY]) {
39
+ globalThis[REVAL_QUEUE_STORAGE_KEY] = new AsyncLocalStorage();
40
+ }
41
+ const revalQueueStorage = globalThis[REVAL_QUEUE_STORAGE_KEY];
42
+
43
+ const REVAL_STATE_KEY = Symbol.for("dinou.reval.queue.state");
44
+ if (!globalThis[REVAL_STATE_KEY]) {
45
+ globalThis[REVAL_STATE_KEY] = {
46
+ queue: Promise.resolve(),
47
+ lastGenTime: 0,
48
+ };
49
+ }
50
+ const revalState = globalThis[REVAL_STATE_KEY];
51
+
52
+ function markRouteDynamicInMap(reqPathWithSlash, cleanPath, isDyn) {
53
+ const map = typeof globalThis !== "undefined" ? globalThis[Symbol.for("dinou.isDynamic.map")] : null;
54
+ if (!map) return;
55
+ for (const key of [reqPathWithSlash, cleanPath]) {
56
+ if (!key) continue;
57
+ if (!map.has(key)) {
58
+ map.set(key, { value: Boolean(isDyn) });
59
+ } else {
60
+ map.get(key).value = Boolean(isDyn);
61
+ }
62
+ }
63
+ }
64
+
65
+ function nextMonotonicGenTime(prevGenTime = 0) {
66
+ const now = Date.now();
67
+ const next = Math.max(now, Number(prevGenTime || 0) + 1, revalState.lastGenTime + 1);
68
+ revalState.lastGenTime = next;
69
+ return next;
70
+ }
71
+
72
+ function enqueueRevalidation(fn) {
73
+ if (revalQueueStorage.getStore()) {
74
+ return fn();
75
+ }
76
+ const run = () => revalQueueStorage.run(true, fn);
77
+ const nextPromise = revalState.queue.then(run, run);
78
+ revalState.queue = nextPromise.catch(() => {});
79
+ return nextPromise;
80
+ }
81
+
82
+ async function readEdgeStorageOrAsset(storage, key) {
83
+ if (!storage || !key) return null;
84
+ try {
85
+ const item = await storage.get(key);
86
+ if (item && item.content) return item;
87
+ } catch (e) {}
88
+ if (typeof storage.isDeleted === "function" && storage.isDeleted(key)) {
89
+ return null;
90
+ }
91
+ try {
92
+ const reqContext = getContext();
93
+ const assets =
94
+ reqContext?.env?.ASSETS ||
95
+ reqContext?.platformContext?.env?.ASSETS ||
96
+ reqContext?.req?.env?.ASSETS ||
97
+ (typeof globalThis !== "undefined" ? globalThis.__DINOU_ENV__?.ASSETS : null);
98
+ if (assets && typeof assets.fetch === "function") {
99
+ const cleanKey = String(key).replace(/^\/+/, "");
100
+ const res = await assets.fetch(new Request(`http://localhost/${cleanKey}`));
101
+ if (res && res.status === 200) {
102
+ const ct = res.headers?.get?.("content-type") || "";
103
+ const content = await res.text();
104
+ const isHtmlExpected = cleanKey.endsWith(".html");
105
+ if (
106
+ content &&
107
+ (isHtmlExpected || (!ct.includes("text/html") && !content.trimStart().startsWith("<")))
108
+ ) {
109
+ const item = { content };
110
+ await storage.set(cleanKey, content);
111
+ return item;
112
+ }
113
+ }
114
+ }
115
+ } catch (e) {}
116
+ return null;
117
+ }
118
+
119
+ async function resolveRouteConfigForRevalidate(pagePath, reqSegments, existingMeta = {}) {
120
+ const srcFolder = path.resolve(process.cwd(), "src");
121
+ let isRoutePpr =
122
+ typeof existingMeta?.ppr === "boolean" ? existingMeta.ppr : null;
123
+ let tags = Array.isArray(existingMeta?.tags) ? existingMeta.tags : null;
124
+ let revalidate = existingMeta?.revalidate;
125
+ let pageRevalidate = existingMeta?.pageRevalidate;
126
+
127
+ let pfMod = null;
128
+ let dParams = {};
129
+ if (pagePath) {
130
+ try {
131
+ const [, resolvedParams] = getFilePathAndDynamicParams(
132
+ reqSegments,
133
+ {},
134
+ srcFolder
135
+ );
136
+ dParams = resolvedParams ?? {};
137
+ const pageFolder = path.dirname(pagePath);
138
+ const [pageFunctionsPath] = getFilePathAndDynamicParams(
139
+ reqSegments,
140
+ {},
141
+ pageFolder,
142
+ "page_functions",
143
+ true,
144
+ true,
145
+ undefined,
146
+ reqSegments.length
147
+ );
148
+ if (pageFunctionsPath) {
149
+ pfMod = await importModule(pageFunctionsPath);
150
+ }
151
+ } catch (e) {}
152
+ }
153
+
154
+ if (isRoutePpr === null) {
155
+ let inheritedPpr = false;
156
+ try {
157
+ const globalCfg = await getDinouConfig();
158
+ inheritedPpr = Boolean(globalCfg?.ppr);
159
+ const layouts = getFilePathAndDynamicParams(
160
+ reqSegments,
161
+ {},
162
+ srcFolder,
163
+ "layout",
164
+ true,
165
+ false,
166
+ undefined,
167
+ 0,
168
+ {},
169
+ true
170
+ );
171
+ if (layouts && Array.isArray(layouts)) {
172
+ for (const [lPath, lParams] of layouts) {
173
+ const lConfig = await resolveLayoutFunctionsConfig(lPath, lParams);
174
+ if (lConfig && lConfig.ppr !== null && lConfig.ppr !== undefined) {
175
+ inheritedPpr = Boolean(lConfig.ppr);
176
+ }
177
+ }
178
+ }
179
+ } catch (e) {}
180
+
181
+ let explicitPagePpr = null;
182
+ if (pfMod) {
183
+ try {
184
+ explicitPagePpr = await resolveModulePpr(pfMod);
185
+ } catch (e) {}
186
+ }
187
+ isRoutePpr = explicitPagePpr !== null ? explicitPagePpr : inheritedPpr;
188
+ }
189
+
190
+ if ((!tags || tags.length === 0) && pfMod) {
191
+ try {
192
+ const defaultExport = pfMod.default?.default
193
+ ? pfMod.default.default
194
+ : pfMod.default;
195
+ const rawTags = pfMod.getCacheTags ?? defaultExport?.getCacheTags;
196
+ if (typeof rawTags === "function") {
197
+ tags = await rawTags(dParams);
198
+ } else if (Array.isArray(rawTags)) {
199
+ tags = rawTags;
200
+ }
201
+ } catch (e) {}
202
+ }
203
+
204
+ if ((revalidate === undefined || pageRevalidate === undefined) && pfMod) {
205
+ try {
206
+ const defaultExport = pfMod.default?.default
207
+ ? pfMod.default.default
208
+ : pfMod.default;
209
+ const pfRevalidate =
210
+ typeof pfMod.revalidate === "function"
211
+ ? await pfMod.revalidate()
212
+ : typeof defaultExport?.revalidate === "function"
213
+ ? await defaultExport.revalidate()
214
+ : pfMod.revalidate ?? defaultExport?.revalidate;
215
+ if (revalidate === undefined) {
216
+ revalidate = pfRevalidate;
217
+ }
218
+ if (pageRevalidate === undefined) {
219
+ pageRevalidate = pfRevalidate !== undefined ? pfRevalidate : null;
220
+ }
221
+ } catch (e) {}
222
+ }
223
+ if (pageRevalidate === undefined) {
224
+ pageRevalidate = null;
225
+ }
226
+
227
+ return {
228
+ isRoutePpr: Boolean(isRoutePpr),
229
+ tags: Array.isArray(tags) ? tags : [],
230
+ revalidate,
231
+ pageRevalidate,
232
+ };
233
+ }
8
234
 
9
235
  async function walkMetadataFiles(dir, fileList = []) {
10
236
  try {
@@ -43,7 +269,7 @@ function normalizeRevalidatePath(reqPath) {
43
269
  } else if (referer) {
44
270
  try {
45
271
  currentPathname = new URL(referer).pathname;
46
- } catch (e) { }
272
+ } catch (e) {}
47
273
  } else {
48
274
  currentPathname = ctx.req.path || "/";
49
275
  }
@@ -61,58 +287,444 @@ function normalizeRevalidatePath(reqPath) {
61
287
  return cleanPath;
62
288
  }
63
289
 
64
- async function revalidatePage(reqPath) {
290
+ async function revalidatePage(reqPath, internalOptions = {}) {
65
291
  const cleanPath = normalizeRevalidatePath(reqPath);
66
-
292
+ const onlyRefreshSlots = Boolean(internalOptions?.onlyRefreshSlots);
293
+ return enqueueRevalidation(async () => {
67
294
  if (isEdgeRuntime()) {
68
295
  const storage = getStorageAdapter();
69
296
  const cleanPathKey = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
70
297
  const htmlKey = cleanPathKey ? `${cleanPathKey}/index.html` : "index.html";
298
+ const shellHtmlKey = cleanPathKey ? `${cleanPathKey}/shell.html` : "shell.html";
299
+ const oldHtmlKey = cleanPathKey ? `${cleanPathKey}/index._old.html` : "index._old.html";
71
300
  const metaKey = cleanPathKey ? `${cleanPathKey}/metadata.json` : "metadata.json";
72
301
  const rscKey = cleanPathKey ? `${cleanPathKey}/page.rsc` : "page.rsc";
302
+ const shellRscKey = cleanPathKey ? `${cleanPathKey}/shell.rsc` : "shell.rsc";
303
+ const shellPageKey = cleanPathKey ? `${cleanPathKey}/shell.page.json` : "shell.page.json";
304
+ const oldRscKey = cleanPathKey ? `${cleanPathKey}/page._old.rsc` : "page._old.rsc";
73
305
  const legacyRscKey = cleanPathKey ? `${cleanPathKey}/rsc.rsc` : "rsc.rsc";
74
306
 
75
307
  let cached = await storage.get(htmlKey);
76
308
  if (!cached && cleanPathKey) {
77
309
  cached = await storage.get(cleanPathKey);
78
310
  }
311
+ if (!cached) {
312
+ cached = await storage.get(shellHtmlKey);
313
+ }
314
+ if (!cached) {
315
+ cached = await readEdgeStorageOrAsset(storage, htmlKey);
316
+ }
79
317
  let currentMeta = (cached && cached.metadata) || {};
80
318
  try {
81
- const metaItem = await storage.get(metaKey);
319
+ const metaItem = await readEdgeStorageOrAsset(storage, metaKey);
82
320
  if (metaItem && metaItem.content) {
83
321
  currentMeta = JSON.parse(metaItem.content);
84
322
  }
85
323
  } catch (e) {}
86
324
 
87
- const prevGenTime = (currentMeta && currentMeta.generatedAt) || 0;
325
+ let existingPageRsc = null;
326
+ try {
327
+ existingPageRsc = await readEdgeStorageOrAsset(storage, rscKey);
328
+ } catch (e) {}
329
+
330
+ const reqPathWithSlash = cleanPath.endsWith("/") ? cleanPath : cleanPath + "/";
331
+ const reqSegments = cleanPath.split("/").filter(Boolean);
332
+ const srcFolder = path.resolve(process.cwd(), "src");
333
+ const [pagePath] = getFilePathAndDynamicParams(reqSegments, {}, srcFolder);
334
+
335
+ const routeCfg = await resolveRouteConfigForRevalidate(
336
+ pagePath,
337
+ reqSegments,
338
+ currentMeta
339
+ );
340
+ const isRoutePpr = routeCfg.isRoutePpr;
341
+ if (!Array.isArray(currentMeta.tags) || currentMeta.tags.length === 0) {
342
+ currentMeta.tags = routeCfg.tags;
343
+ }
344
+ if (currentMeta.revalidate === undefined && routeCfg.revalidate !== undefined) {
345
+ currentMeta.revalidate = routeCfg.revalidate;
346
+ }
347
+ if (currentMeta.pageRevalidate === undefined && routeCfg.pageRevalidate !== undefined) {
348
+ currentMeta.pageRevalidate = routeCfg.pageRevalidate;
349
+ }
350
+ if (currentMeta.status === undefined) {
351
+ currentMeta.status = 200;
352
+ }
353
+
354
+ let activeLayoutRscText = "";
355
+ let maxActiveLayoutGenTime = 0;
356
+ let leafSuspenseCount = 0;
357
+ let leafHoles = [];
358
+ try {
359
+ const activeChain = getActiveLayoutChain(reqSegments, {}, srcFolder);
360
+ if (activeChain.length > 0) {
361
+ for (const entry of activeChain) {
362
+ const lMetaKey = entry.cleanLayoutKey
363
+ ? `${entry.cleanLayoutKey}/layout.metadata.json`
364
+ : "layout.metadata.json";
365
+ const lItem = await readEdgeStorageOrAsset(storage, lMetaKey);
366
+ let lMetaObj = lItem?.metadata || null;
367
+ if (!lMetaObj && lItem?.content) {
368
+ try {
369
+ lMetaObj = JSON.parse(lItem.content);
370
+ } catch (e) {}
371
+ }
372
+ const lGen = Number(lMetaObj?.generatedAt || 0);
373
+ entry.generatedAt = lGen;
374
+ entry.suspenseCount = Number(lMetaObj?.suspenseCount || 0);
375
+ entry.holes = Array.isArray(lMetaObj?.holes) ? lMetaObj.holes : [];
376
+ if (lGen > maxActiveLayoutGenTime) {
377
+ maxActiveLayoutGenTime = lGen;
378
+ }
379
+ }
380
+ const leafLayout = activeChain[0];
381
+ if (activeChain.length > 1 && maxActiveLayoutGenTime > (leafLayout.generatedAt || 0)) {
382
+ await revalidateLayout(leafLayout.layoutRoutePath);
383
+ const refreshedMetaKey = leafLayout.cleanLayoutKey
384
+ ? `${leafLayout.cleanLayoutKey}/layout.metadata.json`
385
+ : "layout.metadata.json";
386
+ const refreshedItem = await readEdgeStorageOrAsset(storage, refreshedMetaKey);
387
+ if (refreshedItem?.content) {
388
+ try {
389
+ const parsed = JSON.parse(refreshedItem.content);
390
+ leafLayout.generatedAt = Number(parsed?.generatedAt || leafLayout.generatedAt || 0);
391
+ leafLayout.suspenseCount = Number(parsed?.suspenseCount || 0);
392
+ leafLayout.holes = Array.isArray(parsed?.holes) ? parsed.holes : [];
393
+ if (leafLayout.generatedAt > maxActiveLayoutGenTime) {
394
+ maxActiveLayoutGenTime = leafLayout.generatedAt;
395
+ }
396
+ } catch (e) {}
397
+ }
398
+ }
399
+ leafSuspenseCount = Number(leafLayout.suspenseCount || 0);
400
+ leafHoles = Array.isArray(leafLayout.holes) ? leafLayout.holes : [];
401
+ const leafRscKey = leafLayout.cleanLayoutKey
402
+ ? `${leafLayout.cleanLayoutKey}/layout.rsc`
403
+ : "layout.rsc";
404
+ const leafRscItem = await readEdgeStorageOrAsset(storage, leafRscKey);
405
+ if (leafRscItem && leafRscItem.content && !leafRscItem.content.trimStart().startsWith("<")) {
406
+ activeLayoutRscText = leafRscItem.content;
407
+ }
408
+ }
409
+ } catch (e) {}
410
+
411
+ const prevGenTime = Math.max((currentMeta && currentMeta.generatedAt) || 0, maxActiveLayoutGenTime);
88
412
  const now = Date.now();
89
- const newGenTime = now <= prevGenTime ? prevGenTime + 100 : now;
413
+ const newGenTime = nextMonotonicGenTime(prevGenTime);
90
414
  currentMeta.generatedAt = newGenTime;
415
+ currentMeta.pageGeneratedAt = newGenTime;
91
416
 
92
417
  let newHtml = cached ? cached.content : "";
93
- if (newHtml) {
418
+ let renderedRsc = "";
419
+ let renderedFullRsc = "";
420
+ let composedFromCachedLayout = false;
421
+
422
+ if (pagePath) {
423
+ const revalDynamicState = { value: false };
424
+ const rawHeaders = {
425
+ "user-agent": "Dinou-ISR-Revalidator",
426
+ host: "localhost",
427
+ "x-forwarded-proto": "http",
428
+ };
429
+ const markRevalDynamic = () => {
430
+ revalDynamicState.value = true;
431
+ };
432
+ const outerCtx = getContext();
433
+ const activeEnv =
434
+ outerCtx?.env ||
435
+ outerCtx?.platformContext?.env ||
436
+ outerCtx?.req?.env ||
437
+ (typeof globalThis !== "undefined" ? globalThis.__DINOU_ENV__ : undefined) ||
438
+ {};
439
+ const revalContext = {
440
+ req: {
441
+ query: createBailoutProxy({}, "req.query", markRevalDynamic),
442
+ cookies: createBailoutProxy({}, "req.cookies", markRevalDynamic),
443
+ headers: createBailoutProxy(rawHeaders, "req.headers", markRevalDynamic),
444
+ path: reqPathWithSlash,
445
+ method: "GET",
446
+ env: activeEnv,
447
+ },
448
+ res: {
449
+ status() {},
450
+ setHeader() {
451
+ markRevalDynamic();
452
+ },
453
+ cookie() {
454
+ markRevalDynamic();
455
+ },
456
+ clearCookie() {
457
+ markRevalDynamic();
458
+ },
459
+ redirect() {
460
+ markRevalDynamic();
461
+ },
462
+ },
463
+ env: activeEnv,
464
+ platformContext: outerCtx?.platformContext || { env: activeEnv },
465
+ };
466
+ const clientManifest =
467
+ (typeof globalThis !== "undefined" && globalThis.__DINOU_CLIENT_MANIFEST__) || {};
468
+
469
+ try {
470
+ await requestStorage.run(revalContext, async () => {
471
+ const isNotFound = {};
472
+ let resolvedPageJsx = null;
473
+
474
+ if (onlyRefreshSlots) {
475
+ try {
476
+ const existingShellPage = await readEdgeStorageOrAsset(storage, shellPageKey);
477
+ if (existingShellPage && existingShellPage.content) {
478
+ const deserialized = deserializeJSX(existingShellPage.content);
479
+ resolvedPageJsx = await runInPageSegment(() =>
480
+ refreshNestedSlotsInTree(deserialized, "__ppr_shell__", {
481
+ currentPath: reqPathWithSlash,
482
+ })
483
+ );
484
+ if (resolvedPageJsx) {
485
+ await storage.set(shellPageKey, serializeJSX(resolvedPageJsx));
486
+ }
487
+ }
488
+ } catch (e) {
489
+ resolvedPageJsx = null;
490
+ }
491
+ }
492
+
493
+ if (isRoutePpr) {
494
+ let pageHoles = Array.isArray(currentMeta.holes) ? currentMeta.holes : [];
495
+ if (!resolvedPageJsx) {
496
+ await runWithPprContext({ isPpr: true }, async () => {
497
+ const rawPageJsx = await getJSX(
498
+ reqPathWithSlash,
499
+ {},
500
+ isNotFound,
501
+ false,
502
+ false,
503
+ { segment: "page" }
504
+ );
505
+ resetPprHoles(leafSuspenseCount);
506
+ resolvedPageJsx = await runInPageSegment(() =>
507
+ asyncRenderJSXToClientJSX(rawPageJsx)
508
+ );
509
+ pageHoles = getRegisteredHoles();
510
+ });
511
+ if (resolvedPageJsx && !isNotFound.value) {
512
+ try {
513
+ await storage.set(shellPageKey, serializeJSX(resolvedPageJsx));
514
+ } catch (e) {}
515
+ }
516
+ }
517
+ if (resolvedPageJsx && !isNotFound.value) {
518
+ const pageStream = renderRSCStream(resolvedPageJsx, clientManifest, {
519
+ runtime: "edge",
520
+ });
521
+ renderedRsc = await new Response(pageStream).text();
522
+ }
523
+ currentMeta.ppr = true;
524
+ const mergedHoles = Array.from(new Set([...leafHoles, ...pageHoles]));
525
+ if (mergedHoles.length > 0 || !Array.isArray(currentMeta.holes)) {
526
+ currentMeta.holes = mergedHoles;
527
+ }
528
+ } else {
529
+ if (!resolvedPageJsx) {
530
+ const rawPageJsx = await getJSX(
531
+ reqPathWithSlash,
532
+ {},
533
+ isNotFound,
534
+ false,
535
+ false,
536
+ {
537
+ segment: "page",
538
+ }
539
+ );
540
+ if (revalDynamicState.value) {
541
+ return;
542
+ }
543
+ if (rawPageJsx && !isNotFound.value) {
544
+ resolvedPageJsx = await runInPageSegment(() =>
545
+ asyncRenderJSXToClientJSX(rawPageJsx)
546
+ );
547
+ if (revalDynamicState.value) {
548
+ return;
549
+ }
550
+ if (resolvedPageJsx) {
551
+ try {
552
+ await storage.set(shellPageKey, serializeJSX(resolvedPageJsx));
553
+ } catch (e) {}
554
+ }
555
+ }
556
+ }
557
+ if (resolvedPageJsx && !isNotFound.value) {
558
+ const pageStream = renderRSCStream(resolvedPageJsx, clientManifest, {
559
+ runtime: "edge",
560
+ });
561
+ renderedRsc = await new Response(pageStream).text();
562
+ }
563
+ }
564
+
565
+ const pageSlotTags = revalContext._pageSlotTags || revalContext._slotTags;
566
+ if (pageSlotTags && pageSlotTags.size > 0) {
567
+ currentMeta.slotTags = Array.from(pageSlotTags);
568
+ }
569
+
570
+ const renderHtmlStream =
571
+ typeof globalThis !== "undefined" && globalThis.__DINOU_RENDER_HTML_STREAM__;
572
+ const knownLayouts =
573
+ (typeof globalThis !== "undefined" && globalThis.__DINOU_LAYOUTS__) || [];
574
+ const bootstrapScriptContent = isRoutePpr
575
+ ? `window.__DINOU_LAYOUTS__ = ${JSON.stringify(knownLayouts)};\nwindow.__DINOU_USE_STATIC__ = false;\nwindow.__DINOU_PPR__ = true;\nwindow.__DINOU_BUILD_ID__ = "${newGenTime}";\n`
576
+ : `window.__DINOU_LAYOUTS__ = ${JSON.stringify(knownLayouts)};\nwindow.__DINOU_USE_STATIC__ = true;\nwindow.__DINOU_BUILD_ID__ = "${newGenTime}";\n`;
577
+ const assetManifest =
578
+ (typeof globalThis !== "undefined" && globalThis.__DINOU_ASSET_MANIFEST__) || {};
579
+ const rawMain = assetManifest["main.js"] || "/main.js";
580
+ const clientEntry = rawMain.startsWith("/") ? rawMain : "/" + rawMain;
581
+
582
+ const encoder = new TextEncoder();
583
+ const toStream = (str) =>
584
+ new ReadableStream({
585
+ start(controller) {
586
+ controller.enqueue(encoder.encode(str));
587
+ controller.close();
588
+ },
589
+ });
590
+
591
+ if (activeLayoutRscText && renderedRsc && typeof renderHtmlStream === "function") {
592
+ try {
593
+ const htmlStream = await renderHtmlStream(toStream(activeLayoutRscText), {
594
+ pageRscStream: toStream(renderedRsc),
595
+ bootstrapModules: [clientEntry],
596
+ bootstrapScriptContent,
597
+ waitForAll: true,
598
+ });
599
+ const htmlText = await new Response(htmlStream).text();
600
+ if (htmlText) {
601
+ newHtml = htmlText;
602
+ composedFromCachedLayout = true;
603
+ }
604
+ } catch (composeErr) {
605
+ if (process.env.DINOU_DEBUG) {
606
+ console.warn(`⚠️ [Edge Revalidate] Layout+Page composition fallback for ${cleanPath}:`, composeErr?.message || composeErr);
607
+ }
608
+ }
609
+ }
610
+
611
+ if (!composedFromCachedLayout) {
612
+ let fullJsx = null;
613
+ if (isRoutePpr) {
614
+ await runWithPprContext({ isPpr: true }, async () => {
615
+ const rawFullJsx = await getJSX(
616
+ reqPathWithSlash,
617
+ {},
618
+ isNotFound,
619
+ false,
620
+ false
621
+ );
622
+ resetPprHoles(0);
623
+ fullJsx = await asyncRenderJSXToClientJSX(rawFullJsx);
624
+ const fullHoles = getRegisteredHoles();
625
+ if (fullHoles.length > 0) {
626
+ currentMeta.holes = fullHoles;
627
+ }
628
+ });
629
+ } else {
630
+ fullJsx = await getJSX(reqPathWithSlash, {}, isNotFound, false, false);
631
+ if (revalDynamicState.value) {
632
+ return;
633
+ }
634
+ }
635
+ if (fullJsx && !isNotFound.value) {
636
+ const fullRscStream = renderRSCStream(fullJsx, clientManifest, { runtime: "edge" });
637
+ if (typeof renderHtmlStream === "function") {
638
+ const [streamForSsr, streamForRsc] = fullRscStream.tee();
639
+ const [rscText, htmlStream] = await Promise.all([
640
+ new Response(streamForRsc).text(),
641
+ renderHtmlStream(streamForSsr, {
642
+ bootstrapModules: [clientEntry],
643
+ bootstrapScriptContent,
644
+ waitForAll: true,
645
+ }),
646
+ ]);
647
+ renderedFullRsc = rscText;
648
+ const htmlText = await new Response(htmlStream).text();
649
+ if (htmlText) {
650
+ newHtml = htmlText;
651
+ }
652
+ } else {
653
+ renderedFullRsc = await new Response(fullRscStream).text();
654
+ }
655
+ }
656
+ }
657
+ });
658
+ } catch (e) {
659
+ console.warn(`⚠️ [Edge Revalidate] Render fallback for ${cleanPath}:`, e?.message || e);
660
+ }
661
+ if (revalDynamicState.value && !isRoutePpr) {
662
+ markRouteDynamicInMap(reqPathWithSlash, cleanPath, true);
663
+ console.log(`[ISR] Bailout detected for ${cleanPath}. Switching to Dynamic.`);
664
+ return;
665
+ }
666
+ markRouteDynamicInMap(reqPathWithSlash, cleanPath, false);
667
+ }
668
+
669
+ try {
670
+ if (cached && cached.content) {
671
+ await storage.set(oldHtmlKey, cached.content);
672
+ }
673
+ if (existingPageRsc && existingPageRsc.content) {
674
+ await storage.set(oldRscKey, existingPageRsc.content);
675
+ }
676
+ } catch (e) {}
677
+
678
+ if (newHtml && ((!renderedFullRsc && !composedFromCachedLayout) || now <= prevGenTime)) {
94
679
  newHtml = newHtml.replace(
95
680
  /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
96
681
  new Date(newGenTime).toISOString()
97
682
  );
98
683
  }
99
684
  await storage.set(htmlKey, newHtml, currentMeta);
685
+ if (isRoutePpr) {
686
+ await storage.set(shellHtmlKey, newHtml, currentMeta);
687
+ }
100
688
  if (cleanPathKey) {
101
689
  await storage.set(cleanPathKey, newHtml, currentMeta);
102
690
  }
103
691
  await storage.set(metaKey, JSON.stringify(currentMeta));
104
692
 
105
693
  try {
106
- let cachedRsc = await storage.get(rscKey);
107
- if (!cachedRsc) {
108
- cachedRsc = await storage.get(legacyRscKey);
109
- }
110
- if (cachedRsc && cachedRsc.content) {
111
- const newRsc = cachedRsc.content.replace(
112
- /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
113
- new Date(newGenTime).toISOString()
114
- );
115
- await storage.set(rscKey, newRsc);
694
+ if (renderedRsc) {
695
+ const finalRsc =
696
+ now <= prevGenTime
697
+ ? renderedRsc.replace(
698
+ /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
699
+ new Date(newGenTime).toISOString()
700
+ )
701
+ : renderedRsc;
702
+ await storage.set(rscKey, finalRsc);
703
+ if (isRoutePpr) {
704
+ await storage.set(shellRscKey, finalRsc);
705
+ }
706
+ if (renderedFullRsc) {
707
+ const finalFullRsc =
708
+ now <= prevGenTime
709
+ ? renderedFullRsc.replace(
710
+ /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
711
+ new Date(newGenTime).toISOString()
712
+ )
713
+ : renderedFullRsc;
714
+ await storage.set(legacyRscKey, finalFullRsc);
715
+ }
716
+ } else {
717
+ let cachedRsc = await storage.get(rscKey);
718
+ if (!cachedRsc) {
719
+ cachedRsc = await storage.get(legacyRscKey);
720
+ }
721
+ if (cachedRsc && cachedRsc.content) {
722
+ const newRsc = cachedRsc.content.replace(
723
+ /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
724
+ new Date(newGenTime).toISOString()
725
+ );
726
+ await storage.set(rscKey, newRsc);
727
+ }
116
728
  }
117
729
  } catch (e) {}
118
730
 
@@ -160,7 +772,7 @@ async function revalidatePage(reqPath) {
160
772
  if (!rscResult.success) {
161
773
  console.warn(`⚠️ [Revalidate] RSC generation failed for ${cleanPath}.`);
162
774
  if (rscResult.tempPath && existsSync(rscResult.tempPath)) {
163
- await fs.unlink(rscResult.tempPath).catch(() => { });
775
+ await fs.unlink(rscResult.tempPath).catch(() => {});
164
776
  }
165
777
  return;
166
778
  }
@@ -175,53 +787,38 @@ async function revalidatePage(reqPath) {
175
787
  } else {
176
788
  console.warn(`⚠️ [Revalidate] HTML generation failed for ${cleanPath}.`);
177
789
  if (pageResult.tempPath && existsSync(pageResult.tempPath)) {
178
- await fs.unlink(pageResult.tempPath).catch(() => { });
790
+ await fs.unlink(pageResult.tempPath).catch(() => {});
179
791
  }
180
792
  }
181
793
  } catch (e) {
182
794
  console.warn(`⚠️ [Revalidate] Failed to revalidate page ${cleanPath}:`, e.message || e);
183
795
  }
796
+ });
184
797
  }
185
798
 
186
- async function revalidatePath(reqPath, options = {}) {
187
- const isCascade = options === "layout" || (typeof options === "object" && options?.cascade === true);
799
+ async function revalidatePath(reqPath, options) {
800
+ if (options !== undefined) {
801
+ console.warn(
802
+ `⚠️ [Dinou] The second parameter (options) in revalidatePath("${reqPath}", ...) is deprecated and ignored since v9.0.3. Zero hydration mismatch is now guaranteed automatically via lazy index.html re-composition.`
803
+ );
804
+ }
188
805
  const cleanPath = normalizeRevalidatePath(reqPath);
189
- let layoutRevalidated = false;
190
806
 
191
807
  if (isEdgeRuntime()) {
192
- // 1. Revalidar la página
193
- await revalidatePage(cleanPath);
194
-
195
- // 2. Paridad Edge: Revalidar layout si existe para este segmento
196
808
  const storage = getStorageAdapter();
197
809
  const cleanPathKey = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
198
810
  const layoutRscKey = cleanPathKey ? `${cleanPathKey}/layout.rsc` : "layout.rsc";
199
811
  const layoutMetaKey = cleanPathKey ? `${cleanPathKey}/layout.metadata.json` : "layout.metadata.json";
200
812
 
813
+ // 1. Revalidar primero el layout si existe para este segmento (para que revalidatePage componga con el layout fresco)
201
814
  const cachedLayout = await storage.get(layoutRscKey);
202
815
  const cachedLayoutMeta = await storage.get(layoutMetaKey);
203
816
  if (cachedLayout || cachedLayoutMeta) {
204
- layoutRevalidated = await revalidateLayout(cleanPath);
817
+ await revalidateLayout(cleanPath);
205
818
  }
206
819
 
207
- // 3. Cascada en Edge: solo si se solicitó cascade y se revalidó un layout
208
- if (isCascade && layoutRevalidated && typeof storage.keys === "function") {
209
- const allKeys = await storage.keys();
210
- const prefix = cleanPathKey ? `${cleanPathKey}/` : "";
211
- const childPaths = new Set();
212
- for (const key of allKeys) {
213
- if (key.startsWith(prefix) && (key.endsWith("metadata.json") || key.endsWith("index.html"))) {
214
- if (!key.endsWith("layout.metadata.json") && !key.endsWith("slot.metadata.json")) {
215
- const relKey = key.replace(/\/(?:metadata\.json|index\.html)$/, "").replace(/^(?:metadata\.json|index\.html)$/, "");
216
- const childPath = "/" + relKey;
217
- if (childPath !== cleanPath) {
218
- childPaths.add(childPath);
219
- }
220
- }
221
- }
222
- }
223
- await Promise.all(Array.from(childPaths).map((p) => revalidatePage(p)));
224
- }
820
+ // 2. Revalidar la página
821
+ await revalidatePage(cleanPath);
225
822
  return;
226
823
  }
227
824
 
@@ -229,36 +826,18 @@ async function revalidatePath(reqPath, options = {}) {
229
826
  const reqPathWithSlash = cleanPath.endsWith("/") ? cleanPath : cleanPath + "/";
230
827
  const targetDir = path.join(dist2Folder, reqPathWithSlash);
231
828
 
232
- // 1. Revalidar la página
233
- await revalidatePage(cleanPath);
234
-
235
- // 2. Revalidar el layout si existe en este segmento
829
+ // 1. Revalidar el layout si existe en este segmento
236
830
  const layoutFinalPath = path.join(targetDir, "layout.rsc");
237
831
  const layoutOldPath = path.join(targetDir, "layout._old.rsc");
238
832
  if (existsSync(layoutFinalPath) || existsSync(layoutOldPath)) {
239
- layoutRevalidated = await revalidateLayout(cleanPath);
833
+ await revalidateLayout(cleanPath);
240
834
  }
241
835
 
242
- // 3. Cascada en Node: solo si se solicitó cascade y se revalidó un layout
243
- if (isCascade && layoutRevalidated) {
244
- if (existsSync(targetDir)) {
245
- const childFiles = await walkMetadataFiles(targetDir);
246
- const childPaths = new Set();
247
- for (const fileOfMeta of childFiles) {
248
- if (path.basename(fileOfMeta) === "metadata.json") {
249
- const relative = path.relative(dist2Folder, path.dirname(fileOfMeta));
250
- const childPath = "/" + relative.replace(/\\/g, "/");
251
- if (childPath !== cleanPath) {
252
- childPaths.add(childPath);
253
- }
254
- }
255
- }
256
- await Promise.all(Array.from(childPaths).map((p) => revalidatePage(p)));
257
- }
258
- }
836
+ // 2. Revalidar la página
837
+ await revalidatePage(cleanPath);
259
838
  }
260
839
 
261
- async function revalidateLayout(cleanPath) {
840
+ async function revalidateLayout(cleanPath, internalOptions = {}) {
262
841
  let targetPath = cleanPath;
263
842
  if (!targetPath.startsWith("/")) {
264
843
  targetPath = "/" + targetPath;
@@ -266,97 +845,303 @@ async function revalidateLayout(cleanPath) {
266
845
  if (targetPath !== "/" && targetPath.endsWith("/")) {
267
846
  targetPath = targetPath.slice(0, -1);
268
847
  }
848
+ const onlyRefreshSlots = Boolean(internalOptions?.onlyRefreshSlots);
849
+ const inFlightKey = `${targetPath}:${onlyRefreshSlots ? "slots" : "full"}`;
269
850
 
270
- if (isEdgeRuntime()) {
271
- const storage = getStorageAdapter();
272
- const cleanPathKey = targetPath.replace(/^\/+/, "").replace(/\/+$/, "");
273
- const layoutRscKey = cleanPathKey ? `${cleanPathKey}/layout.rsc` : "layout.rsc";
274
- const layoutMetaKey = cleanPathKey ? `${cleanPathKey}/layout.metadata.json` : "layout.metadata.json";
851
+ if (inflightLayoutRevalidations.has(inFlightKey)) {
852
+ return inflightLayoutRevalidations.get(inFlightKey);
853
+ }
275
854
 
276
- let cached = await storage.get(layoutRscKey);
277
- let currentMeta = (cached && cached.metadata) || {};
278
- try {
279
- const metaItem = await storage.get(layoutMetaKey);
280
- if (metaItem && metaItem.content) {
281
- currentMeta = JSON.parse(metaItem.content);
282
- }
283
- } catch (e) {}
855
+ const revalPromise = enqueueRevalidation(async () => {
856
+ if (isEdgeRuntime()) {
857
+ const storage = getStorageAdapter();
858
+ const cleanPathKey = targetPath.replace(/^\/+/, "").replace(/\/+$/, "");
859
+ const layoutRscKey = cleanPathKey ? `${cleanPathKey}/layout.rsc` : "layout.rsc";
860
+ const layoutOldRscKey = cleanPathKey ? `${cleanPathKey}/layout._old.rsc` : "layout._old.rsc";
861
+ const layoutMetaKey = cleanPathKey ? `${cleanPathKey}/layout.metadata.json` : "layout.metadata.json";
862
+ const shellLayoutKey = cleanPathKey ? `${cleanPathKey}/shell.layout.json` : "shell.layout.json";
284
863
 
285
- const prevGenTime = (currentMeta && currentMeta.generatedAt) || 0;
286
- const now = Date.now();
287
- const newGenTime = now <= prevGenTime ? prevGenTime + 100 : now;
288
- currentMeta.generatedAt = newGenTime;
864
+ let cached = await readEdgeStorageOrAsset(storage, layoutRscKey);
865
+ let currentMeta = (cached && cached.metadata) || {};
866
+ try {
867
+ const metaItem = await readEdgeStorageOrAsset(storage, layoutMetaKey);
868
+ if (metaItem && metaItem.content) {
869
+ currentMeta = JSON.parse(metaItem.content);
870
+ }
871
+ } catch (e) {}
872
+
873
+ try {
874
+ if (cached && cached.content) {
875
+ await storage.set(layoutOldRscKey, cached.content);
876
+ }
877
+ } catch (e) {}
289
878
 
290
- await storage.set(layoutMetaKey, JSON.stringify(currentMeta));
291
- if (cached && cached.content) {
292
- await storage.set(layoutRscKey, cached.content, currentMeta);
879
+ const reqSegments = targetPath.split("/").filter(Boolean);
880
+ const srcFolder = path.resolve(process.cwd(), "src");
881
+ try {
882
+ const [layoutPath, layoutParams] = getFilePathAndDynamicParams(
883
+ reqSegments,
884
+ {},
885
+ srcFolder,
886
+ "layout",
887
+ true,
888
+ false,
889
+ undefined,
890
+ 0
891
+ );
892
+ if (layoutPath) {
893
+ const layoutCfg = await resolveLayoutFunctionsConfig(layoutPath, layoutParams || {});
894
+ if (Array.isArray(layoutCfg.tags) && layoutCfg.tags.length > 0) {
895
+ currentMeta.tags = layoutCfg.tags;
896
+ } else if (!Array.isArray(currentMeta.tags)) {
897
+ currentMeta.tags = [];
898
+ }
899
+ if (layoutCfg.revalidate !== undefined) {
900
+ currentMeta.revalidate = layoutCfg.revalidate;
901
+ }
902
+ if (layoutCfg.ppr !== null && layoutCfg.ppr !== undefined) {
903
+ currentMeta.ppr = Boolean(layoutCfg.ppr);
904
+ }
905
+ }
906
+ if (typeof currentMeta.ppr !== "boolean") {
907
+ const layoutRouteCfg = await resolveRouteConfigForRevalidate(null, reqSegments, currentMeta);
908
+ currentMeta.ppr = Boolean(layoutRouteCfg.isRoutePpr);
909
+ }
910
+ } catch (e) {}
911
+
912
+ const prevGenTime = (currentMeta && currentMeta.generatedAt) || 0;
913
+ const now = Date.now();
914
+ const newGenTime = nextMonotonicGenTime(prevGenTime);
915
+ currentMeta.generatedAt = newGenTime;
916
+ if (currentMeta.status === undefined) {
917
+ currentMeta.status = 200;
918
+ }
919
+
920
+ const reqPathWithSlash = targetPath.endsWith("/") ? targetPath : targetPath + "/";
921
+ let newLayoutRsc = cached && cached.content ? cached.content : "";
922
+ try {
923
+ const revalDynamicState = { value: false };
924
+ const rawHeaders = {
925
+ "user-agent": "Dinou-ISR-Revalidator",
926
+ host: "localhost",
927
+ "x-forwarded-proto": "http",
928
+ };
929
+ const markRevalDynamic = () => {
930
+ revalDynamicState.value = true;
931
+ };
932
+ const outerCtx = getContext();
933
+ const activeEnv =
934
+ outerCtx?.env ||
935
+ outerCtx?.platformContext?.env ||
936
+ outerCtx?.req?.env ||
937
+ (typeof globalThis !== "undefined" ? globalThis.__DINOU_ENV__ : undefined) ||
938
+ {};
939
+ const revalContext = {
940
+ req: {
941
+ query: createBailoutProxy({}, "req.query", markRevalDynamic),
942
+ cookies: createBailoutProxy({}, "req.cookies", markRevalDynamic),
943
+ headers: createBailoutProxy(rawHeaders, "req.headers", markRevalDynamic),
944
+ path: reqPathWithSlash,
945
+ method: "GET",
946
+ env: activeEnv,
947
+ },
948
+ res: {
949
+ status() {},
950
+ setHeader() {
951
+ markRevalDynamic();
952
+ },
953
+ cookie() {
954
+ markRevalDynamic();
955
+ },
956
+ clearCookie() {
957
+ markRevalDynamic();
958
+ },
959
+ redirect() {
960
+ markRevalDynamic();
961
+ },
962
+ },
963
+ env: activeEnv,
964
+ platformContext: outerCtx?.platformContext || { env: activeEnv },
965
+ };
966
+ const clientManifest =
967
+ (typeof globalThis !== "undefined" && globalThis.__DINOU_CLIENT_MANIFEST__) || {};
968
+ await requestStorage.run(revalContext, async () => {
969
+ let resolvedLayoutJsx = null;
970
+ if (onlyRefreshSlots) {
971
+ try {
972
+ const existingShellLayout = await readEdgeStorageOrAsset(storage, shellLayoutKey);
973
+ if (existingShellLayout && existingShellLayout.content) {
974
+ const deserialized = deserializeJSX(existingShellLayout.content);
975
+ resolvedLayoutJsx = await runInLayoutSegment(() =>
976
+ refreshNestedSlotsInTree(deserialized, "__layout_shell__", {
977
+ currentPath: reqPathWithSlash,
978
+ })
979
+ );
980
+ if (resolvedLayoutJsx) {
981
+ await storage.set(shellLayoutKey, serializeJSX(resolvedLayoutJsx));
982
+ }
983
+ }
984
+ } catch (e) {
985
+ resolvedLayoutJsx = null;
986
+ }
987
+ }
988
+ if (!resolvedLayoutJsx) {
989
+ const isLayoutPpr = Boolean(
990
+ currentMeta.ppr || (Array.isArray(currentMeta.holes) && currentMeta.holes.length > 0)
991
+ );
992
+ await runWithPprContext({ isPpr: isLayoutPpr }, async () => {
993
+ const rawJsx = await getJSX(reqPathWithSlash, {}, {}, false, false, {
994
+ segment: "layout",
995
+ });
996
+ resetPprHoles(0);
997
+ resolvedLayoutJsx = await runInLayoutSegment(() =>
998
+ asyncRenderJSXToClientJSX(rawJsx)
999
+ );
1000
+ const layoutHoles = getRegisteredHoles();
1001
+ if (layoutHoles.length > 0) {
1002
+ currentMeta.holes = layoutHoles;
1003
+ }
1004
+ currentMeta.suspenseCount = getPprHoleCounter();
1005
+ if (resolvedLayoutJsx) {
1006
+ try {
1007
+ await storage.set(shellLayoutKey, serializeJSX(resolvedLayoutJsx));
1008
+ } catch (e) {}
1009
+ }
1010
+ });
1011
+ }
1012
+ if (resolvedLayoutJsx) {
1013
+ const stream = renderRSCStream(resolvedLayoutJsx, clientManifest, {
1014
+ runtime: "edge",
1015
+ });
1016
+ const rendered = await new Response(stream).text();
1017
+ if (rendered) {
1018
+ newLayoutRsc = rendered;
1019
+ }
1020
+ }
1021
+ const layoutSlotTags = revalContext._layoutSlotTags || revalContext._slotTags;
1022
+ if (layoutSlotTags && layoutSlotTags.size > 0) {
1023
+ currentMeta.slotTags = Array.from(layoutSlotTags);
1024
+ }
1025
+ });
1026
+ } catch (e) {
1027
+ console.warn(`⚠️ [Edge Revalidate] Layout render fallback for ${targetPath}:`, e?.message || e);
1028
+ }
1029
+ if (newLayoutRsc && now <= prevGenTime) {
1030
+ newLayoutRsc = newLayoutRsc.replace(
1031
+ /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
1032
+ new Date(newGenTime).toISOString()
1033
+ );
1034
+ }
1035
+ if (newLayoutRsc) {
1036
+ await storage.set(layoutRscKey, newLayoutRsc, currentMeta);
1037
+ }
1038
+ await storage.set(layoutMetaKey, JSON.stringify(currentMeta));
1039
+ console.log(`✅ [Edge Revalidate] Successfully revalidated layout ${targetPath} (generatedAt: ${newGenTime})`);
1040
+ return true;
293
1041
  }
294
- console.log(`✅ [Edge Revalidate] Successfully revalidated layout ${targetPath} (generatedAt: ${newGenTime})`);
295
- return true;
296
- }
297
1042
 
298
- const dist2Folder = path.resolve(process.cwd(), ".dinou/dist2");
299
- const reqPathWithSlash = targetPath.endsWith("/") ? targetPath : targetPath + "/";
300
- const layoutFinalPath = path.join(dist2Folder, reqPathWithSlash, "layout.rsc");
301
- const layoutOldPath = path.join(dist2Folder, reqPathWithSlash, "layout._old.rsc");
1043
+ const dist2Folder = path.resolve(process.cwd(), ".dinou/dist2");
1044
+ const reqPathWithSlash = targetPath.endsWith("/") ? targetPath : targetPath + "/";
1045
+ const layoutFinalPath = path.join(dist2Folder, reqPathWithSlash, "layout.rsc");
1046
+ const layoutOldPath = path.join(dist2Folder, reqPathWithSlash, "layout._old.rsc");
1047
+
1048
+ if (existsSync(layoutFinalPath)) {
1049
+ try {
1050
+ copyFileSync(layoutFinalPath, layoutOldPath);
1051
+ } catch (e) {}
1052
+ }
302
1053
 
303
- if (existsSync(layoutFinalPath)) {
1054
+ console.log(`[Revalidate] Starting on-demand layout revalidation for ${targetPath}...`);
304
1055
  try {
305
- copyFileSync(layoutFinalPath, layoutOldPath);
306
- } catch (e) {}
307
- }
1056
+ const layoutRscResult = await getGenerateStaticRSC()(targetPath, { segment: "layout" });
1057
+ if (layoutRscResult && layoutRscResult.success) {
1058
+ await getSafeRename()(layoutRscResult.tempPath, layoutRscResult.finalPath);
1059
+ console.log(`✅ [Revalidate] Successfully revalidated layout ${targetPath}`);
1060
+ return true;
1061
+ }
1062
+ } catch (err) {
1063
+ console.warn(`⚠️ [Revalidate] Failed to revalidate layout ${targetPath}:`, err.message || err);
1064
+ }
1065
+ return false;
1066
+ });
308
1067
 
309
- console.log(`[Revalidate] Starting on-demand layout revalidation for ${targetPath}...`);
1068
+ inflightLayoutRevalidations.set(inFlightKey, revalPromise);
310
1069
  try {
311
- const layoutRscResult = await getGenerateStaticRSC()(targetPath, { segment: "layout" });
312
- if (layoutRscResult && layoutRscResult.success) {
313
- await getSafeRename()(layoutRscResult.tempPath, layoutRscResult.finalPath);
314
- console.log(`✅ [Revalidate] Successfully revalidated layout ${targetPath}`);
315
- return true;
316
- }
317
- } catch (err) {
318
- console.warn(`⚠️ [Revalidate] Failed to revalidate layout ${targetPath}:`, err.message || err);
1070
+ return await revalPromise;
1071
+ } finally {
1072
+ inflightLayoutRevalidations.delete(inFlightKey);
319
1073
  }
320
- return false;
321
1074
  }
322
1075
 
323
- async function revalidateTag(tag, options = {}) {
324
- const isCascade = options === "layout" || (typeof options === "object" && options?.cascade === true);
325
- console.log(`[Revalidate] Starting on-demand revalidation for tag: "${tag}" (cascade: ${isCascade})...`);
1076
+ async function revalidateTag(tag, options) {
1077
+ if (options !== undefined) {
1078
+ console.warn(
1079
+ `⚠️ [Dinou] The second parameter (options) in revalidateTag("${tag}", ...) is deprecated and ignored since v9.0.3. Zero hydration mismatch is now guaranteed automatically via lazy index.html re-composition.`
1080
+ );
1081
+ }
1082
+ console.log(`[Revalidate] Starting on-demand revalidation for tag: "${tag}"...`);
326
1083
 
327
- if (isEdgeRuntime()) {
328
- const storage = getStorageAdapter();
329
- if (typeof storage.keys === "function") {
1084
+ const storage = getStorageAdapter();
1085
+ if (isEdgeRuntime() || (storage && typeof storage.keys === "function")) {
1086
+ if (storage && typeof storage.keys === "function") {
330
1087
  const allKeys = await storage.keys();
331
- const targetPaths = new Set();
332
- const targetLayoutPaths = new Set();
1088
+ const targetPaths = new Map();
1089
+ const targetLayoutPaths = new Map();
333
1090
  const targetSlotKeys = new Set();
1091
+ if (typeof storage.markTagInvalidated === "function") {
1092
+ storage.markTagInvalidated(tag);
1093
+ }
1094
+ globalThis[Symbol.for("dinou.slot.recent.fresh")]?.clear?.();
1095
+ const slotReg = globalThis[Symbol.for("dinou.slot.registry")];
1096
+ if (slotReg && typeof slotReg.entries === "function") {
1097
+ for (const [regId, entry] of slotReg.entries()) {
1098
+ if (regId === tag || (Array.isArray(entry?.tags) && entry.tags.includes(tag))) {
1099
+ targetSlotKeys.add(`slots/${regId}/slot.json`);
1100
+ targetSlotKeys.add(`slots/${regId}/slot.metadata.json`);
1101
+ }
1102
+ }
1103
+ }
1104
+ const isFsStorage = Boolean(storage && storage.baseDir);
334
1105
  for (const rawKey of allKeys) {
335
1106
  const key = String(rawKey || "").replace(/\\/g, "/");
336
- if (key.includes("slot")) {
1107
+ if (key.endsWith("/slot.metadata.json") || (!isFsStorage && (key.startsWith("slots/") || key.endsWith("/slot.json")))) {
337
1108
  try {
338
1109
  const item = await storage.get(key);
339
1110
  let meta = item?.metadata;
340
1111
  if (!meta && item?.content) {
341
- try { meta = JSON.parse(item.content); } catch (e) {}
1112
+ try {
1113
+ meta = JSON.parse(item.content);
1114
+ } catch (e) {}
342
1115
  }
343
1116
  if (meta && Array.isArray(meta.tags) && meta.tags.includes(tag)) {
344
1117
  targetSlotKeys.add(key);
1118
+ if (key.endsWith("/slot.metadata.json")) {
1119
+ targetSlotKeys.add(key.slice(0, -"/slot.metadata.json".length) + "/slot.json");
1120
+ } else if (key.endsWith("/slot.json")) {
1121
+ targetSlotKeys.add(key.slice(0, -"/slot.json".length) + "/slot.metadata.json");
1122
+ }
345
1123
  }
346
1124
  } catch (e) {}
347
- } else if (key.endsWith("layout.metadata.json") || key.endsWith("layout.rsc")) {
1125
+ } else if (key.endsWith("layout.metadata.json") || (!isFsStorage && key.endsWith("layout.rsc"))) {
348
1126
  try {
349
1127
  const item = await storage.get(key);
350
1128
  let meta = item?.metadata;
351
1129
  if (!meta && item?.content) {
352
- try { meta = JSON.parse(item.content); } catch (e) {}
1130
+ try {
1131
+ meta = JSON.parse(item.content);
1132
+ } catch (e) {}
353
1133
  }
354
- if (meta && Array.isArray(meta.tags) && meta.tags.includes(tag)) {
1134
+ const hasRouteTag = Boolean(meta && Array.isArray(meta.tags) && meta.tags.includes(tag));
1135
+ const hasSlotTag = Boolean(meta && Array.isArray(meta.slotTags) && meta.slotTags.includes(tag));
1136
+ if (hasRouteTag || hasSlotTag) {
355
1137
  const cleanKey = key
356
1138
  .replace(/\/(?:layout\.metadata\.json|layout\.rsc)$/, "")
357
1139
  .replace(/^(?:layout\.metadata\.json|layout\.rsc)$/, "");
358
1140
  const normPath = cleanKey ? (cleanKey.startsWith("/") ? cleanKey : "/" + cleanKey) : "/";
359
- targetLayoutPaths.add(normPath);
1141
+ const prev = targetLayoutPaths.get(normPath);
1142
+ targetLayoutPaths.set(normPath, {
1143
+ onlyRefreshSlots: prev ? prev.onlyRefreshSlots && !hasRouteTag : !hasRouteTag && hasSlotTag,
1144
+ });
360
1145
  }
361
1146
  } catch (e) {}
362
1147
  } else if (key.endsWith("metadata.json")) {
@@ -364,37 +1149,61 @@ async function revalidateTag(tag, options = {}) {
364
1149
  const item = await storage.get(key);
365
1150
  let meta = item?.metadata;
366
1151
  if (!meta && item?.content) {
367
- try { meta = JSON.parse(item.content); } catch (e) {}
1152
+ try {
1153
+ meta = JSON.parse(item.content);
1154
+ } catch (e) {}
368
1155
  }
369
- if (meta && Array.isArray(meta.tags) && meta.tags.includes(tag)) {
1156
+ const hasRouteTag = Boolean(meta && Array.isArray(meta.tags) && meta.tags.includes(tag));
1157
+ const hasSlotTag = Boolean(meta && Array.isArray(meta.slotTags) && meta.slotTags.includes(tag));
1158
+ if (hasRouteTag || hasSlotTag) {
370
1159
  const cleanKey = key
371
- .replace(/\/metadata\.json$/, "")
372
- .replace(/^metadata\.json$/, "");
1160
+ .replace(/\/(?:metadata\.json|index\.html)$/, "")
1161
+ .replace(/^(?:metadata\.json|index\.html)$/, "");
1162
+ if (cleanKey.startsWith("slots/") || cleanKey.endsWith("layout.rsc") || cleanKey.endsWith("layout.metadata.json")) {
1163
+ continue;
1164
+ }
373
1165
  const normPath = cleanKey ? (cleanKey.startsWith("/") ? cleanKey : "/" + cleanKey) : "/";
374
- targetPaths.add(normPath);
1166
+ const prev = targetPaths.get(normPath);
1167
+ targetPaths.set(normPath, {
1168
+ onlyRefreshSlots: prev ? prev.onlyRefreshSlots && !hasRouteTag : !hasRouteTag && hasSlotTag,
1169
+ });
375
1170
  }
376
1171
  } catch (e) {}
377
- } else if (key.endsWith("index.html")) {
1172
+ } else if (!isFsStorage && (key.endsWith("index.html") || key.endsWith("shell.html"))) {
378
1173
  try {
379
1174
  const item = await storage.get(key);
380
1175
  const meta = item?.metadata;
381
- if (meta && Array.isArray(meta.tags) && meta.tags.includes(tag)) {
1176
+ const hasRouteTag = Boolean(meta && Array.isArray(meta.tags) && meta.tags.includes(tag));
1177
+ const hasSlotTag = Boolean(meta && Array.isArray(meta.slotTags) && meta.slotTags.includes(tag));
1178
+ if (hasRouteTag || hasSlotTag) {
382
1179
  const cleanKey = key
383
- .replace(/\/index\.html$/, "")
384
- .replace(/^index\.html$/, "");
1180
+ .replace(/\/(?:metadata\.json|index\.html|shell\.html)$/, "")
1181
+ .replace(/^(?:metadata\.json|index\.html|shell\.html)$/, "");
1182
+ if (cleanKey.startsWith("slots/") || cleanKey.endsWith("layout.rsc") || cleanKey.endsWith("layout.metadata.json")) {
1183
+ continue;
1184
+ }
385
1185
  const normPath = cleanKey ? (cleanKey.startsWith("/") ? cleanKey : "/" + cleanKey) : "/";
386
- targetPaths.add(normPath);
1186
+ const prev = targetPaths.get(normPath);
1187
+ targetPaths.set(normPath, {
1188
+ onlyRefreshSlots: prev ? prev.onlyRefreshSlots && !hasRouteTag : !hasRouteTag && hasSlotTag,
1189
+ });
387
1190
  }
388
1191
  } catch (e) {}
389
1192
  }
390
1193
  }
391
- await Promise.all([
392
- ...Array.from(targetPaths).map((p) => revalidatePage(p)),
393
- ...Array.from(targetLayoutPaths).map((p) =>
394
- isCascade ? revalidatePath(p, { cascade: true }) : revalidateLayout(p)
395
- ),
396
- ...Array.from(targetSlotKeys).map((k) => storage.delete(k)),
397
- ]);
1194
+
1195
+ // 1. Delete invalidated slot artifacts first so subsequent layout/page revalidations re-render the fresh slot
1196
+ await Promise.all(Array.from(targetSlotKeys).map((k) => storage.delete(k)));
1197
+
1198
+ // 2. Revalidate affected layouts first so any subsequent revalidatePage uses the updated layout.rsc
1199
+ await Promise.all(
1200
+ Array.from(targetLayoutPaths.entries()).map(([p, opts]) => revalidateLayout(p, opts))
1201
+ );
1202
+
1203
+ // 3. Revalidate affected pages (without deleting metadata.json!)
1204
+ await Promise.all(
1205
+ Array.from(targetPaths.entries()).map(([p, opts]) => revalidatePage(p, opts))
1206
+ );
398
1207
  }
399
1208
  return;
400
1209
  }
@@ -403,31 +1212,37 @@ async function revalidateTag(tag, options = {}) {
403
1212
  if (!existsSync(dist2Folder)) return;
404
1213
 
405
1214
  const metadataFiles = await walkMetadataFiles(dist2Folder);
406
- const revalidatePromises = [];
1215
+ const slotPromises = [];
1216
+ const targetLayoutPaths = [];
1217
+ const targetPagePaths = [];
407
1218
 
408
1219
  for (const fileOfMeta of metadataFiles) {
409
1220
  try {
410
1221
  const content = await fs.readFile(fileOfMeta, "utf8");
411
1222
  const metadata = JSON.parse(content);
412
- if (metadata && Array.isArray(metadata.tags) && metadata.tags.includes(tag)) {
1223
+ const hasRouteTag = Boolean(metadata && Array.isArray(metadata.tags) && metadata.tags.includes(tag));
1224
+ const hasSlotTag = Boolean(metadata && Array.isArray(metadata.slotTags) && metadata.slotTags.includes(tag));
1225
+ if (hasRouteTag || hasSlotTag) {
413
1226
  if (path.basename(fileOfMeta) === "slot.metadata.json") {
414
1227
  const slotFolder = path.dirname(fileOfMeta);
415
1228
  console.log(`✅ [Revalidate] Invalidating cache slot directory: ${slotFolder}`);
416
- revalidatePromises.push(
1229
+ slotPromises.push(
417
1230
  fs.rm(slotFolder, { recursive: true, force: true }).catch(() => {})
418
1231
  );
419
1232
  } else if (path.basename(fileOfMeta) === "layout.metadata.json") {
420
1233
  const relative = path.relative(dist2Folder, path.dirname(fileOfMeta));
421
1234
  const reqPath = "/" + relative.replace(/\\/g, "/");
422
- if (isCascade) {
423
- revalidatePromises.push(revalidatePath(reqPath, { cascade: true }));
424
- } else {
425
- revalidatePromises.push(revalidateLayout(reqPath));
426
- }
1235
+ targetLayoutPaths.push({
1236
+ reqPath,
1237
+ onlyRefreshSlots: !hasRouteTag && hasSlotTag,
1238
+ });
427
1239
  } else {
428
1240
  const relative = path.relative(dist2Folder, path.dirname(fileOfMeta));
429
1241
  const reqPath = "/" + relative.replace(/\\/g, "/");
430
- revalidatePromises.push(revalidatePage(reqPath));
1242
+ targetPagePaths.push({
1243
+ reqPath,
1244
+ onlyRefreshSlots: !hasRouteTag && hasSlotTag,
1245
+ });
431
1246
  }
432
1247
  }
433
1248
  } catch (err) {
@@ -435,7 +1250,17 @@ async function revalidateTag(tag, options = {}) {
435
1250
  }
436
1251
  }
437
1252
 
438
- await Promise.all(revalidatePromises);
1253
+ await Promise.all(slotPromises);
1254
+ await Promise.all(
1255
+ targetLayoutPaths.map(({ reqPath, onlyRefreshSlots }) =>
1256
+ revalidateLayout(reqPath, { onlyRefreshSlots })
1257
+ )
1258
+ );
1259
+ await Promise.all(
1260
+ targetPagePaths.map(({ reqPath, onlyRefreshSlots }) =>
1261
+ revalidatePage(reqPath, { onlyRefreshSlots })
1262
+ )
1263
+ );
439
1264
  }
440
1265
 
441
1266
  export {