dinou 9.0.2 → 9.0.3

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