dinou 9.3.0 → 10.0.1

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 (166) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/README.md +157 -132
  3. package/dinou/adapters/bun.js +34 -5
  4. package/dinou/adapters/cloudflare.js +110 -17
  5. package/dinou/adapters/deno.js +46 -8
  6. package/dinou/adapters/netlify.js +86 -50
  7. package/dinou/adapters/node.js +8 -0
  8. package/dinou/assets.d.ts +32 -5
  9. package/dinou/bun/build.js +190 -106
  10. package/dinou/cli.js +992 -532
  11. package/dinou/cloudflare/build.js +187 -106
  12. package/dinou/compiled/autoprefixer/index.js +509 -517
  13. package/dinou/compiled/babel-core/index.js +738 -716
  14. package/dinou/compiled/babel-generator/index.js +341 -299
  15. package/dinou/compiled/babel-loader/index.js +766 -744
  16. package/dinou/compiled/babel-parser/index.js +2 -2
  17. package/dinou/compiled/babel-plugin-react-compiler/index.js +178 -178
  18. package/dinou/compiled/babel-plugin-syntax-import-meta/index.js +4 -4
  19. package/dinou/compiled/babel-preset-react/index.js +752 -730
  20. package/dinou/compiled/babel-preset-typescript/index.js +738 -716
  21. package/dinou/compiled/babel-traverse/index.js +463 -433
  22. package/dinou/compiled/babel-types/index.js +176 -176
  23. package/dinou/compiled/chokidar/index.js +4 -4
  24. package/dinou/compiled/commander/index.js +15 -15
  25. package/dinou/compiled/copy-webpack-plugin/index.js +433 -425
  26. package/dinou/compiled/css-loader/index.js +289 -289
  27. package/dinou/compiled/css-loader/runtime/api.js +85 -0
  28. package/dinou/compiled/css-loader/runtime/getUrl.js +26 -0
  29. package/dinou/compiled/css-loader/runtime/noSourceMaps.js +5 -0
  30. package/dinou/compiled/css-loader/runtime/package.json +3 -0
  31. package/dinou/compiled/css-loader/runtime/sourceMaps.js +16 -0
  32. package/dinou/compiled/fast-glob/index.js +5810 -0
  33. package/dinou/compiled/generic-names/index.js +16 -16
  34. package/dinou/compiled/mini-css-extract-plugin/{chunk-YYEJWYXE.js → chunk-R6DP5ZYM.js} +36 -36
  35. package/dinou/compiled/mini-css-extract-plugin/hmr/hotModuleReplacement.js +253 -0
  36. package/dinou/compiled/mini-css-extract-plugin/hmr/normalize-url.js +39 -0
  37. package/dinou/compiled/mini-css-extract-plugin/hmr/package.json +3 -0
  38. package/dinou/compiled/mini-css-extract-plugin/index.js +1 -1
  39. package/dinou/compiled/mini-css-extract-plugin/loader.js +5 -5
  40. package/dinou/compiled/postcss/index.js +83 -83
  41. package/dinou/compiled/postcss-import/index.js +147 -117
  42. package/dinou/compiled/postcss-modules/index.js +216 -216
  43. package/dinou/compiled/resolve/index.js +1224 -0
  44. package/dinou/compiled/rollup-plugin-babel/index.js +753 -731
  45. package/dinou/compiled/rollup-plugin-commonjs/index.js +43 -38
  46. package/dinou/compiled/rollup-plugin-delete/index.js +615 -253
  47. package/dinou/compiled/rollup-plugin-json/index.js +22 -18
  48. package/dinou/compiled/rollup-plugin-node-resolve/index.js +130 -100
  49. package/dinou/compiled/rollup-plugin-postcss/index.js +3299 -3277
  50. package/dinou/compiled/rollup-plugin-replace/index.js +34 -29
  51. package/dinou/compiled/tailwindcss-postcss/index.js +214 -211
  52. package/dinou/compiled/vendors-manifest.json +59 -83
  53. package/dinou/core/asset-extensions.js +482 -33
  54. package/dinou/core/bailout-proxy.js +21 -2
  55. package/dinou/core/build-static-pages.js +523 -371
  56. package/dinou/core/builtin-asset-extensions.js +63 -0
  57. package/dinou/core/cache-revalidate.js +449 -256
  58. package/dinou/core/cache-slot.js +289 -79
  59. package/dinou/core/client-webpack.jsx +470 -39
  60. package/dinou/core/client.jsx +402 -39
  61. package/dinou/core/config.js +3 -0
  62. package/dinou/core/copy-static-dirs.js +98 -0
  63. package/dinou/core/createScopedName.js +22 -4
  64. package/dinou/core/dinou-paths.js +1 -1
  65. package/dinou/core/discover-layouts.js +200 -0
  66. package/dinou/core/edge-ssr.js +1 -1
  67. package/dinou/core/ensure-vendor-mode.js +78 -19
  68. package/dinou/core/env.js +544 -0
  69. package/dinou/core/export-static.js +41 -9
  70. package/dinou/core/generate-route-types.js +989 -95
  71. package/dinou/core/generate-static-rsc.js +5 -6
  72. package/dinou/core/generate-static.js +45 -6
  73. package/dinou/core/get-abs-path-with-ext.js +217 -75
  74. package/dinou/core/get-asset-from-manifest.js +19 -8
  75. package/dinou/core/get-error-jsx.js +4 -5
  76. package/dinou/core/get-file-path-and-dynamic-params.js +561 -338
  77. package/dinou/core/get-jsx.js +220 -53
  78. package/dinou/core/handler.js +1647 -466
  79. package/dinou/core/import-module.js +7 -0
  80. package/dinou/core/layout-functions.js +72 -13
  81. package/dinou/core/link.jsx +34 -6
  82. package/dinou/core/load-dinou-config.js +520 -89
  83. package/dinou/core/manifest-provider.js +4 -14
  84. package/dinou/core/navigation-utils.js +141 -3
  85. package/dinou/core/navigation.js +134 -50
  86. package/dinou/core/node-middleware-runner.js +165 -0
  87. package/dinou/core/postcss-pipeline.js +236 -0
  88. package/dinou/core/ppr-context.js +114 -22
  89. package/dinou/core/ppr-runtime.js +391 -127
  90. package/dinou/core/redirect.jsx +1 -1
  91. package/dinou/core/render-jsx-to-client-jsx.js +216 -48
  92. package/dinou/core/request-context.js +59 -3
  93. package/dinou/core/resolve-contextual-dinou.js +523 -0
  94. package/dinou/core/resolve-setup-files.js +85 -27
  95. package/dinou/core/revalidating.js +10 -2
  96. package/dinou/core/route-generator.js +6 -2
  97. package/dinou/core/rsc-renderer.js +4 -1
  98. package/dinou/core/run-ssg.js +6 -0
  99. package/dinou/core/runtime-env.js +265 -0
  100. package/dinou/core/server-css-modules-plugin.js +155 -0
  101. package/dinou/core/server-function-proxy-webpack.js +27 -2
  102. package/dinou/core/server-function-proxy.js +27 -2
  103. package/dinou/core/slot.js +47 -2
  104. package/dinou/core/static-assets.js +503 -0
  105. package/dinou/core/storage-adapter.js +452 -24
  106. package/dinou/core/transform-server-functions.js +272 -24
  107. package/dinou/core/tsconfig-aliases.js +964 -0
  108. package/dinou/core/uneject.js +640 -0
  109. package/dinou/core/url-resolver.js +1 -1
  110. package/dinou/core/vfs.js +11 -2
  111. package/dinou/css.d.ts +4 -1
  112. package/dinou/deno/build.js +205 -153
  113. package/dinou/deno/seed-kv.js +4 -0
  114. package/dinou/env.d.ts +22 -2
  115. package/dinou/esbuild/build.js +40 -50
  116. package/dinou/esbuild/dev.js +33 -7
  117. package/dinou/esbuild/helpers-esbuild/get-config-esbuild-prod.js +41 -16
  118. package/dinou/esbuild/helpers-esbuild/get-config-esbuild.js +51 -49
  119. package/dinou/esbuild/helpers-esbuild/get-esbuild-entries.js +73 -60
  120. package/dinou/esbuild/helpers-esbuild/swc-disk-cache.js +35 -16
  121. package/dinou/esbuild/helpers-esbuild/write.js +13 -3
  122. package/dinou/esbuild/plugins-esbuild/assets-plugin.js +100 -238
  123. package/dinou/esbuild/plugins-esbuild/babel-react-compiler-plugin.js +73 -29
  124. package/dinou/esbuild/plugins-esbuild/css-processor-plugin.js +283 -91
  125. package/dinou/esbuild/plugins-esbuild/manifest-generator-plugin.js +3 -5
  126. package/dinou/esbuild/plugins-esbuild/react-client-manifest-plugin.js +9 -3
  127. package/dinou/esbuild/plugins-esbuild/server-functions-plugin.js +4 -3
  128. package/dinou/esbuild/plugins-esbuild/stable-chunk-names-and-maps-plugin.js +10 -1
  129. package/dinou/esbuild/plugins-postcss/postcss-extract-plugin.js +84 -21
  130. package/dinou/esbuild/react-refresh/esm-hmr/client.js +31 -10
  131. package/dinou/esbuild/react-refresh/esm-hmr-plugin.js +48 -18
  132. package/dinou/esbuild/react-refresh/is-react-refresh-boundary.js +9 -1
  133. package/dinou/esbuild/react-refresh/react-refresh-runtime.js +13 -7
  134. package/dinou/index.d.ts +1028 -88
  135. package/dinou/node/build.js +138 -74
  136. package/dinou/node/bundle-dual-engine.js +393 -131
  137. package/dinou/node/dev.js +1005 -275
  138. package/dinou/package.json +11 -34
  139. package/dinou/rollup/postcss.config.js +3 -4
  140. package/dinou/rollup/react-refresh/esm-hmr/client.js +31 -10
  141. package/dinou/rollup/react-refresh/react-refresh-wrap-modules.js +16 -13
  142. package/dinou/rollup/react-refresh/rollup-plugin-esm-hmr.js +53 -7
  143. package/dinou/rollup/rollup-plugins/dinou-asset-plugin.js +58 -20
  144. package/dinou/rollup/rollup-plugins/manifest-generator-plugin.js +16 -7
  145. package/dinou/rollup/rollup-plugins/rollup-plugin-react-client-manifest.js +118 -42
  146. package/dinou/rollup/rollup-plugins/rollup-plugin-server-functions.js +48 -36
  147. package/dinou/rollup/rollup.config.js +174 -101
  148. package/dinou/scripts/build-vendors.js +123 -33
  149. package/dinou/server.d.ts +126 -15
  150. package/dinou/webpack/helpers/get-webpack-entries.js +87 -41
  151. package/dinou/webpack/helpers/patch-webpack-internals.js +93 -1
  152. package/dinou/webpack/loaders/server-functions-loader.js +1 -1
  153. package/dinou/webpack/plugins/manifest-generator-plugin.js +27 -7
  154. package/dinou/webpack/plugins/server-functions-plugin.js +39 -12
  155. package/dinou/webpack/plugins/webpack-memory-plugin.js +25 -12
  156. package/dinou/webpack/postcss.config.js +3 -4
  157. package/dinou/webpack/webpack.config.js +408 -132
  158. package/eject.js +6 -224
  159. package/package.json +7 -9
  160. package/dinou/compiled/cross-env/index.js +0 -661
  161. package/dinou/compiled/dotenv/index.js +0 -375
  162. package/dinou/compiled/esbuild-copy-static-files/index.js +0 -63
  163. package/dinou/compiled/esbuild-tsconfig-paths/index.js +0 -1314
  164. package/dinou/compiled/rollup-plugin-copy/index.js +0 -12066
  165. package/dinou/compiled/rollup-plugin-tsconfig-paths/index.js +0 -569
  166. package/dinou/compiled/tsconfig-paths-webpack-plugin/index.js +0 -3956
@@ -4,15 +4,15 @@ import { existsSync, copyFileSync } from "node:fs";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  import { getContext, requestStorage } from "./request-context.js";
6
6
  import { resolveRelativeUrl } from "./url-resolver.js";
7
- import { getStorageAdapter } from "./storage-adapter.js";
7
+ import { getStorageAdapter, readDist2Fallback } from "./storage-adapter.js";
8
8
  import { isEdgeRuntime, renderRSCStream } from "./rsc-renderer.js";
9
9
  import getJSX from "./get-jsx.js";
10
10
  import { getFilePathAndDynamicParams } from "./get-file-path-and-dynamic-params.js";
11
- import { getActiveLayoutChain, resolveLayoutFunctionsConfig } from "./layout-functions.js";
11
+ import { getActiveLayoutChain, resolveLayoutFunctionsConfig, resolveLayoutChainPpr } from "./layout-functions.js";
12
12
  import importModule from "./import-module.js";
13
13
  import { resolveModulePpr } from "./resolve-module-ppr.js";
14
14
  import { getDinouConfig } from "./load-dinou-config.js";
15
- import { createBailoutProxy } from "./bailout-proxy.js";
15
+ import { createBailoutProxy, unwrapBailoutProxy } from "./bailout-proxy.js";
16
16
  import {
17
17
  runWithPprContext,
18
18
  resetPprHoles,
@@ -20,6 +20,7 @@ import {
20
20
  getPprHoleCounter,
21
21
  runInPageSegment,
22
22
  runInLayoutSegment,
23
+ isSlotDiscoveryActive,
23
24
  } from "./ppr-context.js";
24
25
  import { asyncRenderJSXToClientJSX } from "./render-jsx-to-client-jsx.js";
25
26
  import {
@@ -27,6 +28,7 @@ import {
27
28
  deserializeJSX,
28
29
  refreshNestedSlotsInTree,
29
30
  } from "./cache-slot.js";
31
+ import { fetchCloudflareDist2Asset } from "./static-assets.js";
30
32
 
31
33
  const INFLIGHT_LAYOUT_REVAL_KEY = Symbol.for("dinou.layout.inflight.revalidations");
32
34
  if (!globalThis[INFLIGHT_LAYOUT_REVAL_KEY]) {
@@ -85,7 +87,11 @@ async function readEdgeStorageOrAsset(storage, key) {
85
87
  const item = await storage.get(key);
86
88
  if (item && item.content) return item;
87
89
  } catch (e) {}
88
- if (typeof storage.isDeleted === "function" && storage.isDeleted(key)) {
90
+ const isDeleted =
91
+ typeof storage.isKeyDeleted === "function"
92
+ ? await storage.isKeyDeleted(key)
93
+ : typeof storage.isDeleted === "function" && storage.isDeleted(key);
94
+ if (isDeleted) {
89
95
  return null;
90
96
  }
91
97
  try {
@@ -97,7 +103,7 @@ async function readEdgeStorageOrAsset(storage, key) {
97
103
  (typeof globalThis !== "undefined" ? globalThis.__DINOU_ENV__?.ASSETS : null);
98
104
  if (assets && typeof assets.fetch === "function") {
99
105
  const cleanKey = String(key).replace(/^\/+/, "");
100
- const res = await assets.fetch(new Request(`http://localhost/${cleanKey}`));
106
+ const res = await fetchCloudflareDist2Asset(assets, cleanKey);
101
107
  if (res && res.status === 200) {
102
108
  const ct = res.headers?.get?.("content-type") || "";
103
109
  const content = await res.text();
@@ -113,13 +119,15 @@ async function readEdgeStorageOrAsset(storage, key) {
113
119
  }
114
120
  }
115
121
  } catch (e) {}
116
- return null;
122
+ return await readDist2Fallback(storage, key);
117
123
  }
118
124
 
119
125
  async function resolveRouteConfigForRevalidate(pagePath, reqSegments, existingMeta = {}) {
120
126
  const srcFolder = path.resolve(process.cwd(), "src");
121
127
  let isRoutePpr =
122
128
  typeof existingMeta?.ppr === "boolean" ? existingMeta.ppr : null;
129
+ let isPagePpr =
130
+ typeof existingMeta?.pagePpr === "boolean" ? existingMeta.pagePpr : null;
123
131
  let tags = Array.isArray(existingMeta?.tags) ? existingMeta.tags : null;
124
132
  let revalidate = existingMeta?.revalidate;
125
133
  let pageRevalidate = existingMeta?.pageRevalidate;
@@ -151,32 +159,12 @@ async function resolveRouteConfigForRevalidate(pagePath, reqSegments, existingMe
151
159
  } catch (e) {}
152
160
  }
153
161
 
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) {}
162
+ if (isRoutePpr === null || isPagePpr === null) {
163
+ const { defaultPpr, anyLayoutPpr } = await resolveLayoutChainPpr(
164
+ reqSegments || [],
165
+ {},
166
+ srcFolder,
167
+ );
180
168
 
181
169
  let explicitPagePpr = null;
182
170
  if (pfMod) {
@@ -184,7 +172,14 @@ async function resolveRouteConfigForRevalidate(pagePath, reqSegments, existingMe
184
172
  explicitPagePpr = await resolveModulePpr(pfMod);
185
173
  } catch (e) {}
186
174
  }
187
- isRoutePpr = explicitPagePpr !== null ? explicitPagePpr : inheritedPpr;
175
+ const resolvedPagePpr =
176
+ explicitPagePpr !== null ? explicitPagePpr : Boolean(defaultPpr);
177
+ if (isPagePpr === null) {
178
+ isPagePpr = Boolean(resolvedPagePpr);
179
+ }
180
+ if (isRoutePpr === null) {
181
+ isRoutePpr = Boolean(resolvedPagePpr || anyLayoutPpr);
182
+ }
188
183
  }
189
184
 
190
185
  if ((!tags || tags.length === 0) && pfMod) {
@@ -206,12 +201,14 @@ async function resolveRouteConfigForRevalidate(pagePath, reqSegments, existingMe
206
201
  const defaultExport = pfMod.default?.default
207
202
  ? pfMod.default.default
208
203
  : pfMod.default;
204
+ const rawRevalidate =
205
+ pfMod.revalidate !== undefined
206
+ ? pfMod.revalidate
207
+ : defaultExport?.revalidate;
209
208
  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;
209
+ typeof rawRevalidate === "function"
210
+ ? await rawRevalidate()
211
+ : rawRevalidate;
215
212
  if (revalidate === undefined) {
216
213
  revalidate = pfRevalidate;
217
214
  }
@@ -226,15 +223,27 @@ async function resolveRouteConfigForRevalidate(pagePath, reqSegments, existingMe
226
223
 
227
224
  return {
228
225
  isRoutePpr: Boolean(isRoutePpr),
226
+ isPagePpr: Boolean(isPagePpr),
229
227
  tags: Array.isArray(tags) ? tags : [],
230
228
  revalidate,
231
229
  pageRevalidate,
232
230
  };
233
231
  }
234
232
 
233
+ function compareLayoutPathsAncestorFirst(pathA, pathB) {
234
+ const cleanA = String(pathA || "/").replace(/^\/+/, "").replace(/\/+$/, "");
235
+ const cleanB = String(pathB || "/").replace(/^\/+/, "").replace(/\/+$/, "");
236
+ const depthA = cleanA ? cleanA.split("/").filter(Boolean).length : 0;
237
+ const depthB = cleanB ? cleanB.split("/").filter(Boolean).length : 0;
238
+ if (depthA !== depthB) return depthA - depthB;
239
+ return cleanA < cleanB ? -1 : cleanA > cleanB ? 1 : 0;
240
+ }
241
+
235
242
  async function walkMetadataFiles(dir, fileList = []) {
236
243
  try {
237
- const entries = await fs.readdir(dir, { withFileTypes: true });
244
+ const entries = (await fs.readdir(dir, { withFileTypes: true })).sort((a, b) =>
245
+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0
246
+ );
238
247
  for (const entry of entries) {
239
248
  const entryPath = path.join(dir, entry.name);
240
249
  if (entry.isDirectory()) {
@@ -260,24 +269,28 @@ function normalizeRevalidatePath(reqPath) {
260
269
  const ctx = getContext();
261
270
  let currentPathname = "/";
262
271
  if (ctx && ctx.req) {
272
+ const rawReqHeaders = unwrapBailoutProxy(ctx.req.headers);
263
273
  const headerPath =
264
- ctx.req.headers?.["x-dinou-current-path"] ||
265
- ctx.req.headers?.["X-Dinou-Current-Path"];
266
- const referer = ctx.req.headers?.referer;
274
+ rawReqHeaders?.["x-dinou-current-path"] ||
275
+ rawReqHeaders?.["X-Dinou-Current-Path"];
276
+ const referer = rawReqHeaders?.referer;
267
277
  if (headerPath) {
268
- currentPathname = headerPath;
278
+ currentPathname = String(headerPath).split("?")[0].split("#")[0] || "/";
269
279
  } else if (referer) {
270
280
  try {
271
281
  currentPathname = new URL(referer).pathname;
272
282
  } catch (e) {}
273
283
  } else {
274
- currentPathname = ctx.req.path || "/";
284
+ const reqPathCandidate = ctx.req.path || "/";
285
+ currentPathname = reqPathCandidate.includes("____server_function____")
286
+ ? "/"
287
+ : reqPathCandidate;
275
288
  }
276
289
  }
277
290
  targetPath = resolveRelativeUrl(targetPath, currentPathname);
278
291
  }
279
292
 
280
- let cleanPath = targetPath;
293
+ let cleanPath = String(targetPath || "/").split("?")[0].split("#")[0] || "/";
281
294
  if (!cleanPath.startsWith("/")) {
282
295
  cleanPath = "/" + cleanPath;
283
296
  }
@@ -290,8 +303,8 @@ function normalizeRevalidatePath(reqPath) {
290
303
  async function revalidatePage(reqPath, internalOptions = {}) {
291
304
  const cleanPath = normalizeRevalidatePath(reqPath);
292
305
  const onlyRefreshSlots = Boolean(internalOptions?.onlyRefreshSlots);
306
+ const onlyIfExpired = Boolean(internalOptions?.onlyIfExpired);
293
307
  return enqueueRevalidation(async () => {
294
- if (isEdgeRuntime()) {
295
308
  const storage = getStorageAdapter();
296
309
  const cleanPathKey = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
297
310
  const htmlKey = cleanPathKey ? `${cleanPathKey}/index.html` : "index.html";
@@ -338,6 +351,7 @@ async function revalidatePage(reqPath, internalOptions = {}) {
338
351
  currentMeta
339
352
  );
340
353
  const isRoutePpr = routeCfg.isRoutePpr;
354
+ const isPagePpr = routeCfg.isPagePpr;
341
355
  if (!Array.isArray(currentMeta.tags) || currentMeta.tags.length === 0) {
342
356
  currentMeta.tags = routeCfg.tags;
343
357
  }
@@ -351,13 +365,33 @@ async function revalidatePage(reqPath, internalOptions = {}) {
351
365
  currentMeta.status = 200;
352
366
  }
353
367
 
368
+ if (onlyIfExpired && !onlyRefreshSlots) {
369
+ const latestReval =
370
+ currentMeta.pageRevalidate !== undefined && currentMeta.pageRevalidate !== null
371
+ ? currentMeta.pageRevalidate
372
+ : currentMeta.revalidate;
373
+ const latestPageGenAt = Number(
374
+ currentMeta.pageGeneratedAt || currentMeta.generatedAt || 0
375
+ );
376
+ const stillExpired =
377
+ typeof latestReval === "number" &&
378
+ latestReval >= 1 &&
379
+ latestPageGenAt > 0 &&
380
+ Date.now() > latestPageGenAt + latestReval * 1000;
381
+ if (!stillExpired) {
382
+ return;
383
+ }
384
+ }
385
+
354
386
  let activeLayoutRscText = "";
355
387
  let maxActiveLayoutGenTime = 0;
356
388
  let leafSuspenseCount = 0;
357
389
  let leafHoles = [];
390
+ let hasActiveLayoutChain = false;
358
391
  try {
359
392
  const activeChain = getActiveLayoutChain(reqSegments, {}, srcFolder);
360
393
  if (activeChain.length > 0) {
394
+ hasActiveLayoutChain = true;
361
395
  for (const entry of activeChain) {
362
396
  const lMetaKey = entry.cleanLayoutKey
363
397
  ? `${entry.cleanLayoutKey}/layout.metadata.json`
@@ -371,6 +405,7 @@ async function revalidatePage(reqPath, internalOptions = {}) {
371
405
  }
372
406
  const lGen = Number(lMetaObj?.generatedAt || 0);
373
407
  entry.generatedAt = lGen;
408
+ entry.layoutGeneratedAt = Number(lMetaObj?.layoutGeneratedAt || lGen || 0);
374
409
  entry.suspenseCount = Number(lMetaObj?.suspenseCount || 0);
375
410
  entry.holes = Array.isArray(lMetaObj?.holes) ? lMetaObj.holes : [];
376
411
  if (lGen > maxActiveLayoutGenTime) {
@@ -378,8 +413,39 @@ async function revalidatePage(reqPath, internalOptions = {}) {
378
413
  }
379
414
  }
380
415
  const leafLayout = activeChain[0];
381
- if (activeChain.length > 1 && maxActiveLayoutGenTime > (leafLayout.generatedAt || 0)) {
382
- await revalidateLayout(leafLayout.layoutRoutePath);
416
+ const leafRscKey = leafLayout.cleanLayoutKey
417
+ ? `${leafLayout.cleanLayoutKey}/layout.rsc`
418
+ : "layout.rsc";
419
+ let leafRscItem = await readEdgeStorageOrAsset(storage, leafRscKey);
420
+ let hasValidLeafRsc = Boolean(
421
+ leafRscItem &&
422
+ leafRscItem.content &&
423
+ !leafRscItem.content.trimStart().startsWith("<")
424
+ );
425
+ const ancestors = activeChain.length > 1 ? activeChain.slice(1) : [];
426
+ const maxAncestorGen =
427
+ ancestors.length > 0
428
+ ? Math.max(0, ...ancestors.map((l) => l.generatedAt || 0))
429
+ : 0;
430
+ const maxAncestorOwnGen =
431
+ ancestors.length > 0
432
+ ? Math.max(
433
+ 0,
434
+ ...ancestors.map((l) => l.layoutGeneratedAt || l.generatedAt || 0)
435
+ )
436
+ : 0;
437
+ const leafGen = leafLayout.generatedAt || 0;
438
+ const leafOwnGen = leafLayout.layoutGeneratedAt || leafGen;
439
+ const isLeafMissing =
440
+ !hasValidLeafRsc && (isEdgeRuntime() || maxAncestorGen > 0 || onlyRefreshSlots);
441
+ const isAncestorOwnNewer = leafOwnGen > 0 && maxAncestorOwnGen > leafOwnGen;
442
+ const isAncestorSlotOnlyNewer =
443
+ !isAncestorOwnNewer && leafGen > 0 && maxAncestorGen > leafGen;
444
+ if (isLeafMissing || isAncestorOwnNewer || isAncestorSlotOnlyNewer) {
445
+ await revalidateLayout(leafLayout.layoutRoutePath, {
446
+ onlyRefreshSlots:
447
+ !isAncestorOwnNewer && (isAncestorSlotOnlyNewer || isLeafMissing),
448
+ });
383
449
  const refreshedMetaKey = leafLayout.cleanLayoutKey
384
450
  ? `${leafLayout.cleanLayoutKey}/layout.metadata.json`
385
451
  : "layout.metadata.json";
@@ -388,6 +454,9 @@ async function revalidatePage(reqPath, internalOptions = {}) {
388
454
  try {
389
455
  const parsed = JSON.parse(refreshedItem.content);
390
456
  leafLayout.generatedAt = Number(parsed?.generatedAt || leafLayout.generatedAt || 0);
457
+ leafLayout.layoutGeneratedAt = Number(
458
+ parsed?.layoutGeneratedAt || leafLayout.generatedAt || 0
459
+ );
391
460
  leafLayout.suspenseCount = Number(parsed?.suspenseCount || 0);
392
461
  leafLayout.holes = Array.isArray(parsed?.holes) ? parsed.holes : [];
393
462
  if (leafLayout.generatedAt > maxActiveLayoutGenTime) {
@@ -395,28 +464,33 @@ async function revalidatePage(reqPath, internalOptions = {}) {
395
464
  }
396
465
  } catch (e) {}
397
466
  }
467
+ leafRscItem = await readEdgeStorageOrAsset(storage, leafRscKey);
468
+ hasValidLeafRsc = Boolean(
469
+ leafRscItem &&
470
+ leafRscItem.content &&
471
+ !leafRscItem.content.trimStart().startsWith("<")
472
+ );
398
473
  }
399
474
  leafSuspenseCount = Number(leafLayout.suspenseCount || 0);
400
475
  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("<")) {
476
+ if (hasValidLeafRsc) {
406
477
  activeLayoutRscText = leafRscItem.content;
407
478
  }
408
479
  }
409
480
  } catch (e) {}
410
481
 
411
482
  const prevGenTime = Math.max((currentMeta && currentMeta.generatedAt) || 0, maxActiveLayoutGenTime);
483
+ const prevPageOwnGenTime =
484
+ (currentMeta && (currentMeta.pageGeneratedAt || currentMeta.generatedAt)) || 0;
412
485
  const now = Date.now();
413
486
  const newGenTime = nextMonotonicGenTime(prevGenTime);
414
487
  currentMeta.generatedAt = newGenTime;
415
- currentMeta.pageGeneratedAt = newGenTime;
488
+ let didSpliceOnlyPageSlots = false;
416
489
 
417
490
  let newHtml = cached ? cached.content : "";
418
491
  let renderedRsc = "";
419
492
  let renderedFullRsc = "";
493
+ let pendingShellPageJson = null;
420
494
  let composedFromCachedLayout = false;
421
495
 
422
496
  if (pagePath) {
@@ -427,6 +501,7 @@ async function revalidatePage(reqPath, internalOptions = {}) {
427
501
  "x-forwarded-proto": "http",
428
502
  };
429
503
  const markRevalDynamic = () => {
504
+ if (isSlotDiscoveryActive()) return;
430
505
  revalDynamicState.value = true;
431
506
  };
432
507
  const outerCtx = getContext();
@@ -462,6 +537,7 @@ async function revalidatePage(reqPath, internalOptions = {}) {
462
537
  },
463
538
  env: activeEnv,
464
539
  platformContext: outerCtx?.platformContext || { env: activeEnv },
540
+ _isStaticHtmlRender: true,
465
541
  };
466
542
  const clientManifest =
467
543
  (typeof globalThis !== "undefined" && globalThis.__DINOU_CLIENT_MANIFEST__) || {};
@@ -482,7 +558,8 @@ async function revalidatePage(reqPath, internalOptions = {}) {
482
558
  })
483
559
  );
484
560
  if (resolvedPageJsx) {
485
- await storage.set(shellPageKey, serializeJSX(resolvedPageJsx));
561
+ didSpliceOnlyPageSlots = true;
562
+ pendingShellPageJson = serializeJSX(resolvedPageJsx);
486
563
  }
487
564
  }
488
565
  } catch (e) {
@@ -491,9 +568,9 @@ async function revalidatePage(reqPath, internalOptions = {}) {
491
568
  }
492
569
 
493
570
  if (isRoutePpr) {
494
- let pageHoles = Array.isArray(currentMeta.holes) ? currentMeta.holes : [];
571
+ let pageHoles = [];
495
572
  if (!resolvedPageJsx) {
496
- await runWithPprContext({ isPpr: true }, async () => {
573
+ await runWithPprContext({ isPpr: Boolean(isPagePpr) }, async () => {
497
574
  const rawPageJsx = await getJSX(
498
575
  reqPathWithSlash,
499
576
  {},
@@ -506,11 +583,11 @@ async function revalidatePage(reqPath, internalOptions = {}) {
506
583
  resolvedPageJsx = await runInPageSegment(() =>
507
584
  asyncRenderJSXToClientJSX(rawPageJsx)
508
585
  );
509
- pageHoles = getRegisteredHoles();
586
+ pageHoles = isPagePpr ? getRegisteredHoles() : [];
510
587
  });
511
588
  if (resolvedPageJsx && !isNotFound.value) {
512
589
  try {
513
- await storage.set(shellPageKey, serializeJSX(resolvedPageJsx));
590
+ pendingShellPageJson = serializeJSX(resolvedPageJsx);
514
591
  } catch (e) {}
515
592
  }
516
593
  }
@@ -521,7 +598,11 @@ async function revalidatePage(reqPath, internalOptions = {}) {
521
598
  renderedRsc = await new Response(pageStream).text();
522
599
  }
523
600
  currentMeta.ppr = true;
524
- const mergedHoles = Array.from(new Set([...leafHoles, ...pageHoles]));
601
+ currentMeta.pagePpr = Boolean(isPagePpr);
602
+ const mergedHoles =
603
+ onlyRefreshSlots && Array.isArray(currentMeta.holes)
604
+ ? currentMeta.holes
605
+ : Array.from(new Set([...leafHoles, ...pageHoles]));
525
606
  if (mergedHoles.length > 0 || !Array.isArray(currentMeta.holes)) {
526
607
  currentMeta.holes = mergedHoles;
527
608
  }
@@ -549,7 +630,7 @@ async function revalidatePage(reqPath, internalOptions = {}) {
549
630
  }
550
631
  if (resolvedPageJsx) {
551
632
  try {
552
- await storage.set(shellPageKey, serializeJSX(resolvedPageJsx));
633
+ pendingShellPageJson = serializeJSX(resolvedPageJsx);
553
634
  } catch (e) {}
554
635
  }
555
636
  }
@@ -606,6 +687,25 @@ async function revalidatePage(reqPath, internalOptions = {}) {
606
687
  console.warn(`⚠️ [Edge Revalidate] Layout+Page composition fallback for ${cleanPath}:`, composeErr?.message || composeErr);
607
688
  }
608
689
  }
690
+ } else if (
691
+ !hasActiveLayoutChain &&
692
+ didSpliceOnlyPageSlots &&
693
+ renderedRsc &&
694
+ typeof renderHtmlStream === "function"
695
+ ) {
696
+ try {
697
+ const htmlStream = await renderHtmlStream(toStream(renderedRsc), {
698
+ bootstrapModules: [clientEntry],
699
+ bootstrapScriptContent,
700
+ waitForAll: true,
701
+ });
702
+ const htmlText = await new Response(htmlStream).text();
703
+ if (htmlText) {
704
+ renderedFullRsc = renderedRsc;
705
+ newHtml = htmlText;
706
+ composedFromCachedLayout = true;
707
+ }
708
+ } catch (composeErr) {}
609
709
  }
610
710
 
611
711
  if (!composedFromCachedLayout) {
@@ -656,7 +756,9 @@ async function revalidatePage(reqPath, internalOptions = {}) {
656
756
  }
657
757
  });
658
758
  } catch (e) {
659
- console.warn(`⚠️ [Edge Revalidate] Render fallback for ${cleanPath}:`, e?.message || e);
759
+ if (isEdgeRuntime() || process.env.DINOU_DEBUG) {
760
+ console.warn(`⚠️ [Edge Revalidate] Render fallback for ${cleanPath}:`, e?.message || e);
761
+ }
660
762
  }
661
763
  if (revalDynamicState.value && !isRoutePpr) {
662
764
  markRouteDynamicInMap(reqPathWithSlash, cleanPath, true);
@@ -666,6 +768,35 @@ async function revalidatePage(reqPath, internalOptions = {}) {
666
768
  markRouteDynamicInMap(reqPathWithSlash, cleanPath, false);
667
769
  }
668
770
 
771
+ const didRenderFreshPage = Boolean(
772
+ renderedRsc || renderedFullRsc || composedFromCachedLayout
773
+ );
774
+
775
+ if (!didRenderFreshPage && !isEdgeRuntime()) {
776
+ const keysToEvict = [
777
+ htmlKey,
778
+ shellHtmlKey,
779
+ oldHtmlKey,
780
+ rscKey,
781
+ shellRscKey,
782
+ shellPageKey,
783
+ oldRscKey,
784
+ legacyRscKey,
785
+ metaKey,
786
+ ];
787
+ if (cleanPathKey) {
788
+ keysToEvict.push(cleanPathKey);
789
+ }
790
+ await Promise.all(
791
+ keysToEvict.map((k) => Promise.resolve(storage.delete(k)).catch(() => {}))
792
+ );
793
+ return;
794
+ }
795
+
796
+ if (!pagePath && !cached && !existingPageRsc) {
797
+ return;
798
+ }
799
+
669
800
  try {
670
801
  if (cached && cached.content) {
671
802
  await storage.set(oldHtmlKey, cached.content);
@@ -675,124 +806,97 @@ async function revalidatePage(reqPath, internalOptions = {}) {
675
806
  }
676
807
  } catch (e) {}
677
808
 
809
+ const commitGenTime = nextMonotonicGenTime(newGenTime);
810
+ if (commitGenTime !== newGenTime && newHtml) {
811
+ newHtml = newHtml.replace(
812
+ `window.__DINOU_BUILD_ID__ = "${newGenTime}"`,
813
+ `window.__DINOU_BUILD_ID__ = "${commitGenTime}"`
814
+ );
815
+ }
816
+ currentMeta.generatedAt = commitGenTime;
817
+
678
818
  if (newHtml && ((!renderedFullRsc && !composedFromCachedLayout) || now <= prevGenTime)) {
679
819
  newHtml = newHtml.replace(
680
820
  /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
681
- new Date(newGenTime).toISOString()
821
+ new Date(commitGenTime).toISOString()
682
822
  );
683
823
  }
684
- await storage.set(htmlKey, newHtml, currentMeta);
685
- if (isRoutePpr) {
686
- await storage.set(shellHtmlKey, newHtml, currentMeta);
687
- }
688
- if (cleanPathKey) {
689
- await storage.set(cleanPathKey, newHtml, currentMeta);
690
- }
691
- await storage.set(metaKey, JSON.stringify(currentMeta));
692
-
693
- try {
694
- if (renderedRsc) {
695
- const finalRsc =
824
+ currentMeta.pageGeneratedAt =
825
+ didSpliceOnlyPageSlots && prevPageOwnGenTime > 0
826
+ ? prevPageOwnGenTime
827
+ : commitGenTime;
828
+
829
+ let finalPageRscToWrite = "";
830
+ let finalFullRscToWrite = "";
831
+ if (renderedRsc) {
832
+ finalPageRscToWrite =
833
+ now <= prevGenTime
834
+ ? renderedRsc.replace(
835
+ /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
836
+ new Date(commitGenTime).toISOString()
837
+ )
838
+ : renderedRsc;
839
+ if (renderedFullRsc) {
840
+ finalFullRscToWrite =
696
841
  now <= prevGenTime
697
- ? renderedRsc.replace(
842
+ ? renderedFullRsc.replace(
698
843
  /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
699
- new Date(newGenTime).toISOString()
844
+ new Date(commitGenTime).toISOString()
700
845
  )
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);
846
+ : renderedFullRsc;
847
+ }
848
+ } else {
849
+ try {
850
+ let cachedRsc =
851
+ existingPageRsc && existingPageRsc.content
852
+ ? existingPageRsc
853
+ : await storage.get(rscKey);
718
854
  if (!cachedRsc) {
719
855
  cachedRsc = await storage.get(legacyRscKey);
720
856
  }
721
857
  if (cachedRsc && cachedRsc.content) {
722
- const newRsc = cachedRsc.content.replace(
858
+ finalPageRscToWrite = cachedRsc.content.replace(
723
859
  /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
724
- new Date(newGenTime).toISOString()
860
+ new Date(commitGenTime).toISOString()
725
861
  );
726
- await storage.set(rscKey, newRsc);
727
862
  }
728
- }
729
- } catch (e) {}
730
-
731
- console.log(`✅ [Edge Revalidate] Successfully revalidated page ${cleanPath} (generatedAt: ${newGenTime})`);
732
- return;
733
- }
734
-
735
- const dist2Folder = path.resolve(process.cwd(), ".dinou/dist2");
736
- const reqPathWithSlash = cleanPath.endsWith("/") ? cleanPath : cleanPath + "/";
737
-
738
- // Check if there is an existing page to copy to _old
739
- try {
740
- if (existsSync(path.join(dist2Folder, reqPathWithSlash, "index.html"))) {
741
- copyFileSync(
742
- path.join(dist2Folder, reqPathWithSlash, "index.html"),
743
- path.join(dist2Folder, reqPathWithSlash, "index._old.html")
744
- );
745
- }
746
- if (existsSync(path.join(dist2Folder, reqPathWithSlash, "page.rsc"))) {
747
- copyFileSync(
748
- path.join(dist2Folder, reqPathWithSlash, "page.rsc"),
749
- path.join(dist2Folder, reqPathWithSlash, "page._old.rsc")
750
- );
751
- }
752
- if (existsSync(path.join(dist2Folder, reqPathWithSlash, "rsc.rsc"))) {
753
- copyFileSync(
754
- path.join(dist2Folder, reqPathWithSlash, "rsc.rsc"),
755
- path.join(dist2Folder, reqPathWithSlash, "rsc._old.rsc")
756
- );
863
+ } catch (e) {}
757
864
  }
758
- } catch (e) {
759
- // Ignore copy errors
760
- }
761
865
 
762
- console.log(`[Revalidate] Starting on-demand page revalidation for ${cleanPath}...`);
763
- try {
764
- const isDynamic = {};
765
- await getBuildStaticPage()(cleanPath, isDynamic);
766
- if (isDynamic.value) {
767
- console.log(`[Revalidate] Bailout detected for ${cleanPath}. Switching to dynamic (skipping static write).`);
768
- return;
769
- }
866
+ // Causal commit order to guarantee zero hydration mismatch (#418) under concurrent ISR reads:
867
+ // 1. _old snapshot already committed above (so buildId < currentGeneratedAt resolves T_prev)
868
+ // 2. metadata.json advances currentGeneratedAt to commitGenTime (routing T_prev clients to _old)
869
+ // 3. page.rsc / shell.rsc / shell.page.json commit T_new before any HTML exposes buildId=commitGenTime
870
+ // 4. index.html / shell.html / cleanPathKey commit last
871
+ await storage.set(metaKey, JSON.stringify(currentMeta));
770
872
 
771
- const rscResult = await getGenerateStaticRSC()(cleanPath);
772
- if (!rscResult.success) {
773
- console.warn(`⚠️ [Revalidate] RSC generation failed for ${cleanPath}.`);
774
- if (rscResult.tempPath && existsSync(rscResult.tempPath)) {
775
- await fs.unlink(rscResult.tempPath).catch(() => {});
776
- }
777
- return;
873
+ if (pendingShellPageJson) {
874
+ try {
875
+ await storage.set(shellPageKey, pendingShellPageJson);
876
+ } catch (e) {}
778
877
  }
779
878
 
780
- await getSafeRename()(rscResult.tempPath, rscResult.finalPath);
781
-
782
- const pageResult = await getGenerateStaticPage()(cleanPath);
783
- if (pageResult.success) {
784
- await getSafeRename()(pageResult.tempPath, pageResult.finalPath);
785
- getUpdateStatus()(cleanPath, pageResult.status);
786
- console.log(`✅ [Revalidate] Successfully revalidated page ${cleanPath} (Status: ${pageResult.status})`);
787
- } else {
788
- console.warn(`⚠️ [Revalidate] HTML generation failed for ${cleanPath}.`);
789
- if (pageResult.tempPath && existsSync(pageResult.tempPath)) {
790
- await fs.unlink(pageResult.tempPath).catch(() => {});
879
+ try {
880
+ if (finalPageRscToWrite) {
881
+ await storage.set(rscKey, finalPageRscToWrite);
882
+ if (isRoutePpr && renderedRsc) {
883
+ await storage.set(shellRscKey, finalPageRscToWrite);
884
+ }
885
+ }
886
+ if (finalFullRscToWrite) {
887
+ await storage.set(legacyRscKey, finalFullRscToWrite);
791
888
  }
889
+ } catch (e) {}
890
+
891
+ await storage.set(htmlKey, newHtml, currentMeta);
892
+ if (isRoutePpr) {
893
+ await storage.set(shellHtmlKey, newHtml, currentMeta);
792
894
  }
793
- } catch (e) {
794
- console.warn(`⚠️ [Revalidate] Failed to revalidate page ${cleanPath}:`, e.message || e);
795
- }
895
+ if (cleanPathKey) {
896
+ await storage.set(cleanPathKey, newHtml, currentMeta);
897
+ }
898
+
899
+ console.log(`✅ [Edge Revalidate] Successfully revalidated page ${cleanPath} (generatedAt: ${commitGenTime})`);
796
900
  });
797
901
  }
798
902
 
@@ -803,57 +907,51 @@ async function revalidatePath(reqPath, options) {
803
907
  );
804
908
  }
805
909
  const cleanPath = normalizeRevalidatePath(reqPath);
806
-
807
- if (isEdgeRuntime()) {
808
- const storage = getStorageAdapter();
809
- const cleanPathKey = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
810
- const layoutRscKey = cleanPathKey ? `${cleanPathKey}/layout.rsc` : "layout.rsc";
811
- const layoutMetaKey = cleanPathKey ? `${cleanPathKey}/layout.metadata.json` : "layout.metadata.json";
812
-
813
- // 1. Revalidar primero el layout si existe para este segmento (para que revalidatePage componga con el layout fresco)
814
- const cachedLayout = await storage.get(layoutRscKey);
815
- const cachedLayoutMeta = await storage.get(layoutMetaKey);
816
- if (cachedLayout || cachedLayoutMeta) {
817
- await revalidateLayout(cleanPath);
818
- }
819
-
820
- // 2. Revalidar la página
821
- await revalidatePage(cleanPath);
822
- return;
910
+ const storage = getStorageAdapter();
911
+ const cleanPathKey = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
912
+ const layoutRscKey = cleanPathKey ? `${cleanPathKey}/layout.rsc` : "layout.rsc";
913
+ const layoutMetaKey = cleanPathKey ? `${cleanPathKey}/layout.metadata.json` : "layout.metadata.json";
914
+
915
+ // 1. Revalidate layout first if present for this segment (so revalidatePage composes with the fresh layout)
916
+ const cachedLayout = await readEdgeStorageOrAsset(storage, layoutRscKey);
917
+ const cachedLayoutMeta = await readEdgeStorageOrAsset(storage, layoutMetaKey);
918
+ let hasOwnLayoutFile = false;
919
+ if (!cachedLayout && !cachedLayoutMeta) {
920
+ try {
921
+ const reqSegments = cleanPath.split("/").filter(Boolean);
922
+ const srcFolder = path.resolve(process.cwd(), "src");
923
+ const [exactLayoutPath] = getFilePathAndDynamicParams(
924
+ reqSegments,
925
+ {},
926
+ srcFolder,
927
+ "layout",
928
+ true,
929
+ true,
930
+ undefined,
931
+ 0
932
+ );
933
+ hasOwnLayoutFile = Boolean(exactLayoutPath);
934
+ } catch (e) {}
823
935
  }
824
-
825
- const dist2Folder = path.resolve(process.cwd(), ".dinou/dist2");
826
- const reqPathWithSlash = cleanPath.endsWith("/") ? cleanPath : cleanPath + "/";
827
- const targetDir = path.join(dist2Folder, reqPathWithSlash);
828
-
829
- // 1. Revalidar el layout si existe en este segmento
830
- const layoutFinalPath = path.join(targetDir, "layout.rsc");
831
- const layoutOldPath = path.join(targetDir, "layout._old.rsc");
832
- if (existsSync(layoutFinalPath) || existsSync(layoutOldPath)) {
936
+ if (cachedLayout || cachedLayoutMeta || hasOwnLayoutFile) {
833
937
  await revalidateLayout(cleanPath);
834
938
  }
835
939
 
836
- // 2. Revalidar la página
940
+ // 2. Revalidate page
837
941
  await revalidatePage(cleanPath);
838
942
  }
839
943
 
840
- async function revalidateLayout(cleanPath, internalOptions = {}) {
841
- let targetPath = cleanPath;
842
- if (!targetPath.startsWith("/")) {
843
- targetPath = "/" + targetPath;
844
- }
845
- if (targetPath !== "/" && targetPath.endsWith("/")) {
846
- targetPath = targetPath.slice(0, -1);
847
- }
944
+ async function revalidateLayout(reqPath, internalOptions = {}) {
945
+ const targetPath = normalizeRevalidatePath(reqPath);
848
946
  const onlyRefreshSlots = Boolean(internalOptions?.onlyRefreshSlots);
849
- const inFlightKey = `${targetPath}:${onlyRefreshSlots ? "slots" : "full"}`;
947
+ const onlyIfExpired = Boolean(internalOptions?.onlyIfExpired);
948
+ const inFlightKey = `${targetPath}:${onlyRefreshSlots ? "slots" : "full"}:${onlyIfExpired ? "ttl" : "force"}`;
850
949
 
851
950
  if (inflightLayoutRevalidations.has(inFlightKey)) {
852
951
  return inflightLayoutRevalidations.get(inFlightKey);
853
952
  }
854
953
 
855
954
  const revalPromise = enqueueRevalidation(async () => {
856
- if (isEdgeRuntime()) {
857
955
  const storage = getStorageAdapter();
858
956
  const cleanPathKey = targetPath.replace(/^\/+/, "").replace(/\/+$/, "");
859
957
  const layoutRscKey = cleanPathKey ? `${cleanPathKey}/layout.rsc` : "layout.rsc";
@@ -863,21 +961,18 @@ async function revalidateLayout(cleanPath, internalOptions = {}) {
863
961
 
864
962
  let cached = await readEdgeStorageOrAsset(storage, layoutRscKey);
865
963
  let currentMeta = (cached && cached.metadata) || {};
964
+ let hasCachedMeta = Boolean(cached && cached.metadata);
866
965
  try {
867
966
  const metaItem = await readEdgeStorageOrAsset(storage, layoutMetaKey);
868
967
  if (metaItem && metaItem.content) {
869
968
  currentMeta = JSON.parse(metaItem.content);
870
- }
871
- } catch (e) {}
872
-
873
- try {
874
- if (cached && cached.content) {
875
- await storage.set(layoutOldRscKey, cached.content);
969
+ hasCachedMeta = true;
876
970
  }
877
971
  } catch (e) {}
878
972
 
879
973
  const reqSegments = targetPath.split("/").filter(Boolean);
880
974
  const srcFolder = path.resolve(process.cwd(), "src");
975
+ let resolvedLayoutFilePath = null;
881
976
  try {
882
977
  const [layoutPath, layoutParams] = getFilePathAndDynamicParams(
883
978
  reqSegments,
@@ -889,6 +984,7 @@ async function revalidateLayout(cleanPath, internalOptions = {}) {
889
984
  undefined,
890
985
  0
891
986
  );
987
+ resolvedLayoutFilePath = layoutPath || null;
892
988
  if (layoutPath) {
893
989
  const layoutCfg = await resolveLayoutFunctionsConfig(layoutPath, layoutParams || {});
894
990
  if (Array.isArray(layoutCfg.tags) && layoutCfg.tags.length > 0) {
@@ -899,17 +995,31 @@ async function revalidateLayout(cleanPath, internalOptions = {}) {
899
995
  if (layoutCfg.revalidate !== undefined) {
900
996
  currentMeta.revalidate = layoutCfg.revalidate;
901
997
  }
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
998
  }
999
+ const { anyLayoutPpr } = await resolveLayoutChainPpr(reqSegments, {}, srcFolder, {
1000
+ ignoreNoLayout: true,
1001
+ });
1002
+ currentMeta.ppr = Boolean(anyLayoutPpr);
910
1003
  } catch (e) {}
911
1004
 
1005
+ if (onlyIfExpired && !onlyRefreshSlots) {
1006
+ const latestLayoutReval = currentMeta.revalidate;
1007
+ const latestLayoutGenAt = Number(
1008
+ currentMeta.layoutGeneratedAt || currentMeta.generatedAt || 0
1009
+ );
1010
+ const stillExpired =
1011
+ typeof latestLayoutReval === "number" &&
1012
+ latestLayoutReval >= 1 &&
1013
+ latestLayoutGenAt > 0 &&
1014
+ Date.now() > latestLayoutGenAt + latestLayoutReval * 1000;
1015
+ if (!stillExpired) {
1016
+ return false;
1017
+ }
1018
+ }
1019
+
912
1020
  const prevGenTime = (currentMeta && currentMeta.generatedAt) || 0;
1021
+ const prevLayoutOwnGenTime =
1022
+ (currentMeta && (currentMeta.layoutGeneratedAt || currentMeta.generatedAt)) || 0;
913
1023
  const now = Date.now();
914
1024
  const newGenTime = nextMonotonicGenTime(prevGenTime);
915
1025
  currentMeta.generatedAt = newGenTime;
@@ -919,6 +1029,8 @@ async function revalidateLayout(cleanPath, internalOptions = {}) {
919
1029
 
920
1030
  const reqPathWithSlash = targetPath.endsWith("/") ? targetPath : targetPath + "/";
921
1031
  let newLayoutRsc = cached && cached.content ? cached.content : "";
1032
+ let didRenderFreshLayout = false;
1033
+ let didSpliceOnlyLayoutSlots = false;
922
1034
  try {
923
1035
  const revalDynamicState = { value: false };
924
1036
  const rawHeaders = {
@@ -927,6 +1039,7 @@ async function revalidateLayout(cleanPath, internalOptions = {}) {
927
1039
  "x-forwarded-proto": "http",
928
1040
  };
929
1041
  const markRevalDynamic = () => {
1042
+ if (isSlotDiscoveryActive()) return;
930
1043
  revalDynamicState.value = true;
931
1044
  };
932
1045
  const outerCtx = getContext();
@@ -962,6 +1075,7 @@ async function revalidateLayout(cleanPath, internalOptions = {}) {
962
1075
  },
963
1076
  env: activeEnv,
964
1077
  platformContext: outerCtx?.platformContext || { env: activeEnv },
1078
+ _isStaticHtmlRender: true,
965
1079
  };
966
1080
  const clientManifest =
967
1081
  (typeof globalThis !== "undefined" && globalThis.__DINOU_CLIENT_MANIFEST__) || {};
@@ -969,16 +1083,44 @@ async function revalidateLayout(cleanPath, internalOptions = {}) {
969
1083
  let resolvedLayoutJsx = null;
970
1084
  if (onlyRefreshSlots) {
971
1085
  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));
1086
+ let hasNewerAncestorOwnLayout = false;
1087
+ if (prevLayoutOwnGenTime > 0) {
1088
+ const activeChain = getActiveLayoutChain(reqSegments, {}, srcFolder, {
1089
+ ignoreNoLayout: true,
1090
+ });
1091
+ for (const anc of activeChain.slice(1)) {
1092
+ const ancMetaKey = anc.cleanLayoutKey
1093
+ ? `${anc.cleanLayoutKey}/layout.metadata.json`
1094
+ : "layout.metadata.json";
1095
+ const ancItem = await readEdgeStorageOrAsset(storage, ancMetaKey);
1096
+ let ancMetaObj = ancItem?.metadata || null;
1097
+ if (!ancMetaObj && ancItem?.content) {
1098
+ try {
1099
+ ancMetaObj = JSON.parse(ancItem.content);
1100
+ } catch (e) {}
1101
+ }
1102
+ const ancOwnGen = Number(
1103
+ ancMetaObj?.layoutGeneratedAt || ancMetaObj?.generatedAt || 0
1104
+ );
1105
+ if (ancOwnGen > prevLayoutOwnGenTime) {
1106
+ hasNewerAncestorOwnLayout = true;
1107
+ break;
1108
+ }
1109
+ }
1110
+ }
1111
+ if (!hasNewerAncestorOwnLayout) {
1112
+ const existingShellLayout = await readEdgeStorageOrAsset(storage, shellLayoutKey);
1113
+ if (existingShellLayout && existingShellLayout.content) {
1114
+ const deserialized = deserializeJSX(existingShellLayout.content);
1115
+ resolvedLayoutJsx = await runInLayoutSegment(() =>
1116
+ refreshNestedSlotsInTree(deserialized, "__layout_shell__", {
1117
+ currentPath: reqPathWithSlash,
1118
+ })
1119
+ );
1120
+ if (resolvedLayoutJsx) {
1121
+ didSpliceOnlyLayoutSlots = true;
1122
+ await storage.set(shellLayoutKey, serializeJSX(resolvedLayoutJsx));
1123
+ }
982
1124
  }
983
1125
  }
984
1126
  } catch (e) {
@@ -1016,6 +1158,7 @@ async function revalidateLayout(cleanPath, internalOptions = {}) {
1016
1158
  const rendered = await new Response(stream).text();
1017
1159
  if (rendered) {
1018
1160
  newLayoutRsc = rendered;
1161
+ didRenderFreshLayout = true;
1019
1162
  }
1020
1163
  }
1021
1164
  const layoutSlotTags = revalContext._layoutSlotTags || revalContext._slotTags;
@@ -1024,45 +1167,46 @@ async function revalidateLayout(cleanPath, internalOptions = {}) {
1024
1167
  }
1025
1168
  });
1026
1169
  } catch (e) {
1027
- console.warn(`⚠️ [Edge Revalidate] Layout render fallback for ${targetPath}:`, e?.message || e);
1170
+ if (isEdgeRuntime() || process.env.DINOU_DEBUG) {
1171
+ console.warn(`⚠️ [Edge Revalidate] Layout render fallback for ${targetPath}:`, e?.message || e);
1172
+ }
1173
+ }
1174
+
1175
+ if (!didRenderFreshLayout && !isEdgeRuntime()) {
1176
+ await Promise.all(
1177
+ [layoutRscKey, layoutOldRscKey, layoutMetaKey, shellLayoutKey].map((k) =>
1178
+ Promise.resolve(storage.delete(k)).catch(() => {})
1179
+ )
1180
+ );
1181
+ return Boolean(cached || hasCachedMeta || resolvedLayoutFilePath);
1028
1182
  }
1183
+
1184
+ if (!resolvedLayoutFilePath && !cached && !hasCachedMeta) {
1185
+ return false;
1186
+ }
1187
+
1188
+ try {
1189
+ if (cached && cached.content) {
1190
+ await storage.set(layoutOldRscKey, cached.content);
1191
+ }
1192
+ } catch (e) {}
1193
+
1029
1194
  if (newLayoutRsc && now <= prevGenTime) {
1030
1195
  newLayoutRsc = newLayoutRsc.replace(
1031
1196
  /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g,
1032
1197
  new Date(newGenTime).toISOString()
1033
1198
  );
1034
1199
  }
1200
+ currentMeta.layoutGeneratedAt =
1201
+ didSpliceOnlyLayoutSlots && prevLayoutOwnGenTime > 0
1202
+ ? prevLayoutOwnGenTime
1203
+ : newGenTime;
1204
+ await storage.set(layoutMetaKey, JSON.stringify(currentMeta));
1035
1205
  if (newLayoutRsc) {
1036
1206
  await storage.set(layoutRscKey, newLayoutRsc, currentMeta);
1037
1207
  }
1038
- await storage.set(layoutMetaKey, JSON.stringify(currentMeta));
1039
1208
  console.log(`✅ [Edge Revalidate] Successfully revalidated layout ${targetPath} (generatedAt: ${newGenTime})`);
1040
1209
  return true;
1041
- }
1042
-
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
- }
1053
-
1054
- console.log(`[Revalidate] Starting on-demand layout revalidation for ${targetPath}...`);
1055
- try {
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
1210
  });
1067
1211
 
1068
1212
  inflightLayoutRevalidations.set(inFlightKey, revalPromise);
@@ -1084,11 +1228,36 @@ async function revalidateTag(tag, options) {
1084
1228
  const storage = getStorageAdapter();
1085
1229
  if (isEdgeRuntime() || (storage && typeof storage.keys === "function")) {
1086
1230
  if (storage && typeof storage.keys === "function") {
1087
- const allKeys = await storage.keys();
1231
+ const allKeysSet = new Set(await storage.keys());
1232
+ const isFsStorage = Boolean(storage && storage.baseDir);
1233
+ if (!isFsStorage && storage.hydrateFromDisk !== false) {
1234
+ try {
1235
+ const dist2Folder = path.resolve(process.cwd(), ".dinou/dist2");
1236
+ if (existsSync(dist2Folder)) {
1237
+ const diskMetaFiles = await walkMetadataFiles(dist2Folder);
1238
+ for (const diskMeta of diskMetaFiles) {
1239
+ const relKey = path
1240
+ .relative(dist2Folder, diskMeta)
1241
+ .replace(/\\/g, "/");
1242
+ const deleted =
1243
+ typeof storage.isKeyDeleted === "function"
1244
+ ? await storage.isKeyDeleted(relKey)
1245
+ : typeof storage.isDeleted === "function" &&
1246
+ storage.isDeleted(relKey);
1247
+ if (!deleted) {
1248
+ allKeysSet.add(relKey);
1249
+ }
1250
+ }
1251
+ }
1252
+ } catch (e) {}
1253
+ }
1254
+ const allKeys = Array.from(allKeysSet);
1088
1255
  const targetPaths = new Map();
1089
1256
  const targetLayoutPaths = new Map();
1090
1257
  const targetSlotKeys = new Set();
1091
- if (typeof storage.markTagInvalidated === "function") {
1258
+ if (typeof storage.markTagInvalidatedAsync === "function") {
1259
+ await storage.markTagInvalidatedAsync(tag);
1260
+ } else if (typeof storage.markTagInvalidated === "function") {
1092
1261
  storage.markTagInvalidated(tag);
1093
1262
  }
1094
1263
  globalThis[Symbol.for("dinou.slot.recent.fresh")]?.clear?.();
@@ -1101,19 +1270,26 @@ async function revalidateTag(tag, options) {
1101
1270
  }
1102
1271
  }
1103
1272
  }
1104
- const isFsStorage = Boolean(storage && storage.baseDir);
1273
+ const readKeyOrFallback = async (k) =>
1274
+ (await storage.get(k)) || (await readEdgeStorageOrAsset(storage, k));
1105
1275
  for (const rawKey of allKeys) {
1106
1276
  const key = String(rawKey || "").replace(/\\/g, "/");
1107
1277
  if (key.endsWith("/slot.metadata.json") || (!isFsStorage && (key.startsWith("slots/") || key.endsWith("/slot.json")))) {
1108
1278
  try {
1109
- const item = await storage.get(key);
1279
+ const item = await readKeyOrFallback(key);
1110
1280
  let meta = item?.metadata;
1111
1281
  if (!meta && item?.content) {
1112
1282
  try {
1113
1283
  meta = JSON.parse(item.content);
1114
1284
  } catch (e) {}
1115
1285
  }
1116
- if (meta && Array.isArray(meta.tags) && meta.tags.includes(tag)) {
1286
+ const slotIdMatch = key.match(/^slots\/([^/]+)\//);
1287
+ const matchedSlotId = meta?.slotId || slotIdMatch?.[1];
1288
+ const matchesSlotId = Boolean(matchedSlotId && matchedSlotId === tag);
1289
+ const matchesSlotTag = Boolean(
1290
+ meta && Array.isArray(meta.tags) && meta.tags.includes(tag)
1291
+ );
1292
+ if (matchesSlotId || matchesSlotTag) {
1117
1293
  targetSlotKeys.add(key);
1118
1294
  if (key.endsWith("/slot.metadata.json")) {
1119
1295
  targetSlotKeys.add(key.slice(0, -"/slot.metadata.json".length) + "/slot.json");
@@ -1124,7 +1300,7 @@ async function revalidateTag(tag, options) {
1124
1300
  } catch (e) {}
1125
1301
  } else if (key.endsWith("layout.metadata.json") || (!isFsStorage && key.endsWith("layout.rsc"))) {
1126
1302
  try {
1127
- const item = await storage.get(key);
1303
+ const item = await readKeyOrFallback(key);
1128
1304
  let meta = item?.metadata;
1129
1305
  if (!meta && item?.content) {
1130
1306
  try {
@@ -1146,7 +1322,7 @@ async function revalidateTag(tag, options) {
1146
1322
  } catch (e) {}
1147
1323
  } else if (key.endsWith("metadata.json")) {
1148
1324
  try {
1149
- const item = await storage.get(key);
1325
+ const item = await readKeyOrFallback(key);
1150
1326
  let meta = item?.metadata;
1151
1327
  if (!meta && item?.content) {
1152
1328
  try {
@@ -1195,9 +1371,12 @@ async function revalidateTag(tag, options) {
1195
1371
  // 1. Delete invalidated slot artifacts first so subsequent layout/page revalidations re-render the fresh slot
1196
1372
  await Promise.all(Array.from(targetSlotKeys).map((k) => storage.delete(k)));
1197
1373
 
1198
- // 2. Revalidate affected layouts first so any subsequent revalidatePage uses the updated layout.rsc
1374
+ // 2. Revalidate affected layouts ancestor-first so parent slots/timestamps settle before descendants
1375
+ const sortedTargetLayouts = Array.from(targetLayoutPaths.entries()).sort(([a], [b]) =>
1376
+ compareLayoutPathsAncestorFirst(a, b)
1377
+ );
1199
1378
  await Promise.all(
1200
- Array.from(targetLayoutPaths.entries()).map(([p, opts]) => revalidateLayout(p, opts))
1379
+ sortedTargetLayouts.map(([p, opts]) => revalidateLayout(p, opts))
1201
1380
  );
1202
1381
 
1203
1382
  // 3. Revalidate affected pages (without deleting metadata.json!)
@@ -1208,6 +1387,15 @@ async function revalidateTag(tag, options) {
1208
1387
  return;
1209
1388
  }
1210
1389
 
1390
+ if (storage) {
1391
+ if (typeof storage.markTagInvalidatedAsync === "function") {
1392
+ await storage.markTagInvalidatedAsync(tag);
1393
+ } else if (typeof storage.markTagInvalidated === "function") {
1394
+ storage.markTagInvalidated(tag);
1395
+ }
1396
+ }
1397
+ globalThis[Symbol.for("dinou.slot.recent.fresh")]?.clear?.();
1398
+
1211
1399
  const dist2Folder = path.resolve(process.cwd(), ".dinou/dist2");
1212
1400
  if (!existsSync(dist2Folder)) return;
1213
1401
 
@@ -1220,10 +1408,14 @@ async function revalidateTag(tag, options) {
1220
1408
  try {
1221
1409
  const content = await fs.readFile(fileOfMeta, "utf8");
1222
1410
  const metadata = JSON.parse(content);
1411
+ const isSlotMeta = path.basename(fileOfMeta) === "slot.metadata.json";
1412
+ const hasSlotIdMatch =
1413
+ isSlotMeta &&
1414
+ (metadata?.slotId === tag || path.basename(path.dirname(fileOfMeta)) === tag);
1223
1415
  const hasRouteTag = Boolean(metadata && Array.isArray(metadata.tags) && metadata.tags.includes(tag));
1224
1416
  const hasSlotTag = Boolean(metadata && Array.isArray(metadata.slotTags) && metadata.slotTags.includes(tag));
1225
- if (hasRouteTag || hasSlotTag) {
1226
- if (path.basename(fileOfMeta) === "slot.metadata.json") {
1417
+ if (hasSlotIdMatch || hasRouteTag || hasSlotTag) {
1418
+ if (isSlotMeta) {
1227
1419
  const slotFolder = path.dirname(fileOfMeta);
1228
1420
  console.log(`✅ [Revalidate] Invalidating cache slot directory: ${slotFolder}`);
1229
1421
  slotPromises.push(
@@ -1251,6 +1443,7 @@ async function revalidateTag(tag, options) {
1251
1443
  }
1252
1444
 
1253
1445
  await Promise.all(slotPromises);
1446
+ targetLayoutPaths.sort((a, b) => compareLayoutPathsAncestorFirst(a.reqPath, b.reqPath));
1254
1447
  await Promise.all(
1255
1448
  targetLayoutPaths.map(({ reqPath, onlyRefreshSlots }) =>
1256
1449
  revalidateLayout(reqPath, { onlyRefreshSlots })