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
@@ -23,11 +23,17 @@ import { getFilePathAndDynamicParams } from "./get-file-path-and-dynamic-params.
23
23
  import getJSX from "./get-jsx.js";
24
24
  import { getErrorJSX } from "./get-error-jsx.js";
25
25
  import importModule from "./import-module.js";
26
- import { resolveLayoutFunctionsConfig, getActiveLayoutChain } from "./layout-functions.js";
26
+ import { resolveLayoutFunctionsConfig, getActiveLayoutChain, resolveLayoutChainPpr } from "./layout-functions.js";
27
27
  import { revalidating, regenerating, inFlightGenerations } from "./revalidating.js";
28
28
  import { generatingISG } from "./generating-isg.js";
29
29
  import { requestStorage, setCurrentContext } from "./request-context.js";
30
+ import {
31
+ createUnifiedEnv,
32
+ syncEdgeEnvToProcessEnv,
33
+ isBotEnvProbePath,
34
+ } from "./runtime-env.js";
30
35
  import { getStatus } from "./status-manifest.js";
36
+ import { discoverLayoutsFromFileRelPaths, discoverLayoutsFromFs } from "./discover-layouts.js";
31
37
 
32
38
  import {
33
39
  isManifestReady,
@@ -35,9 +41,17 @@ import {
35
41
  getServerFunctionsManifest,
36
42
  } from "./manifest-provider.js";
37
43
  import { pipeRSC, renderRSCStream, isEdgeRuntime } from "./rsc-renderer.js";
38
- import { getStorageAdapter, setStorageAdapter } from "./storage-adapter.js";
44
+ import {
45
+ getStorageAdapter,
46
+ setStorageAdapter,
47
+ readDist2Fallback,
48
+ } from "./storage-adapter.js";
39
49
  import { createBailoutProxy } from "./bailout-proxy.js";
40
50
  import getAssetFromManifest from "./get-asset-from-manifest.js";
51
+ import {
52
+ fetchCloudflareDist2Asset,
53
+ isReservedCloudflareDist2RequestPath,
54
+ } from "./static-assets.js";
41
55
  import { handlePprResume, spliceDynamicHolesIntoShell } from "./ppr-runtime.js";
42
56
  import { resolveModulePpr } from "./resolve-module-ppr.js";
43
57
  import { getDinouConfig as loadDinouConfig } from "./load-dinou-config.js";
@@ -55,40 +69,55 @@ import {
55
69
  getPprHoleCounter,
56
70
  runInPageSegment,
57
71
  runInLayoutSegment,
72
+ isSlotDiscoveryActive,
58
73
  } from "./ppr-context.js";
59
74
  import { asyncRenderJSXToClientJSX } from "./render-jsx-to-client-jsx.js";
60
75
 
61
76
  // Load Dinou configuration and plugins
62
77
  let dinouConfig = { plugins: [] };
63
78
  let dinouConfigPromise = null;
79
+ const AUTO_LOADED_PROD_CONFIG = Symbol.for("dinou.autoLoadedProdConfig");
64
80
 
65
81
  async function getDinouConfig() {
66
- if (typeof globalThis !== "undefined" && globalThis.__DINOU_CONFIG__) {
67
- const cfg = globalThis.__DINOU_CONFIG__;
68
- if (cfg && cfg.storage) {
69
- setStorageAdapter(cfg.storage);
70
- }
71
- dinouConfig = cfg;
72
- return cfg;
73
- }
74
- if (dinouConfigPromise && !isDevelopment) {
75
- return dinouConfigPromise;
76
- }
77
- dinouConfigPromise = (async () => {
78
- const cfg = await loadDinouConfig();
79
- if (cfg && cfg.storage) {
80
- setStorageAdapter(cfg.storage);
81
- }
82
- dinouConfig = cfg;
83
- return cfg;
84
- })();
85
- return dinouConfigPromise;
82
+ const isSsgBuild =
83
+ typeof globalThis !== "undefined" && Boolean(globalThis.__DINOU_IS_SSG_BUILD__);
84
+ const isActiveDevServer =
85
+ process.env.DINOU_DEV === "true" ||
86
+ (typeof globalThis !== "undefined" && Boolean(globalThis.__DINOU_DEV__));
87
+ const aotOrProdCached =
88
+ typeof globalThis !== "undefined"
89
+ ? globalThis.__DINOU_AOT_CONFIG__ ||
90
+ (globalThis.__DINOU_CONFIG__ &&
91
+ !isActiveDevServer &&
92
+ (!isDevelopment || !globalThis.__DINOU_CONFIG__[AUTO_LOADED_PROD_CONFIG])
93
+ ? globalThis.__DINOU_CONFIG__
94
+ : null)
95
+ : null;
96
+ if (aotOrProdCached) {
97
+ if (!isSsgBuild && aotOrProdCached.storage) {
98
+ setStorageAdapter(aotOrProdCached.storage);
99
+ }
100
+ dinouConfig = aotOrProdCached;
101
+ return aotOrProdCached;
102
+ }
103
+ if (!dinouConfigPromise || isDevelopment) {
104
+ dinouConfigPromise = loadDinouConfig();
105
+ }
106
+ const cfg = await dinouConfigPromise;
107
+ if (!isSsgBuild && cfg && cfg.storage) {
108
+ setStorageAdapter(cfg.storage);
109
+ }
110
+ dinouConfig = cfg;
111
+ return cfg;
86
112
  }
87
113
 
88
114
  // Initial sync load attempt for immediate storage adapter setup
89
- if (typeof globalThis !== "undefined" && globalThis.__DINOU_CONFIG__) {
90
- const cfg = globalThis.__DINOU_CONFIG__;
91
- if (cfg && cfg.storage) {
115
+ if (
116
+ typeof globalThis !== "undefined" &&
117
+ (globalThis.__DINOU_AOT_CONFIG__ || globalThis.__DINOU_CONFIG__)
118
+ ) {
119
+ const cfg = globalThis.__DINOU_AOT_CONFIG__ || globalThis.__DINOU_CONFIG__;
120
+ if (!globalThis.__DINOU_IS_SSG_BUILD__ && cfg && cfg.storage) {
92
121
  setStorageAdapter(cfg.storage);
93
122
  }
94
123
  dinouConfig = cfg;
@@ -105,7 +134,11 @@ if (typeof globalThis !== "undefined" && globalThis.__DINOU_CONFIG__) {
105
134
  if (nodeReqSync) {
106
135
  const loaded = nodeReqSync(syncPath);
107
136
  const cfg = (loaded && loaded.default) ? loaded.default : (loaded || { plugins: [] });
108
- if (cfg && cfg.storage) {
137
+ if (
138
+ !(typeof globalThis !== "undefined" && globalThis.__DINOU_IS_SSG_BUILD__) &&
139
+ cfg &&
140
+ cfg.storage
141
+ ) {
109
142
  setStorageAdapter(cfg.storage);
110
143
  }
111
144
  dinouConfig = cfg;
@@ -120,19 +153,295 @@ if (typeof globalThis !== "undefined" && globalThis.__DINOU_CONFIG__) {
120
153
  function copyCustomContextProperties(source, target) {
121
154
  if (!source || !target) return;
122
155
  for (const key of Object.keys(source)) {
123
- if (!["req", "res", "env", "ctx", "platformContext", "_markDynamic", "_dynamicState"].includes(key)) {
156
+ if (
157
+ ![
158
+ "req",
159
+ "res",
160
+ "env",
161
+ "ctx",
162
+ "platformContext",
163
+ "_markDynamic",
164
+ "_dynamicState",
165
+ "_hasRedirected",
166
+ "_isStaticHtmlRender",
167
+ "_isPprRuntimeResume",
168
+ ].includes(key)
169
+ ) {
124
170
  target[key] = source[key];
125
171
  }
126
172
  }
127
173
  if (source.req && target.req) {
128
174
  for (const key of Object.keys(source.req)) {
129
- if (!["cookies", "headers", "query", "path", "url", "method", "env", "ctx"].includes(key)) {
175
+ if (
176
+ ![
177
+ "cookies",
178
+ "headers",
179
+ "query",
180
+ "path",
181
+ "rawPath",
182
+ "isRscRequest",
183
+ "url",
184
+ "method",
185
+ "env",
186
+ "ctx",
187
+ ].includes(key)
188
+ ) {
130
189
  target.req[key] = source.req[key];
131
190
  }
132
191
  }
133
192
  }
134
193
  }
135
194
 
195
+ function safeJsonForInlineScript(str) {
196
+ return JSON.stringify(str)
197
+ .replace(/</g, "\\u003c")
198
+ .replace(/>/g, "\\u003e")
199
+ .replace(/\u2028/g, "\\u2028")
200
+ .replace(/\u2029/g, "\\u2029");
201
+ }
202
+
203
+ function formatRscPushScript(kind, chunkStr) {
204
+ const arrName = `__DINOU_RSC_${kind}__`;
205
+ const pushFn = `__DINOU_RSC_${kind}_PUSH__`;
206
+ const encoded = safeJsonForInlineScript(chunkStr);
207
+ return `<script>(self.${arrName}=self.${arrName}||[]).push(${encoded});if(self.${pushFn})self.${pushFn}(${encoded});</script>`;
208
+ }
209
+
210
+ function formatRscDoneScript(kind) {
211
+ const doneName = `__DINOU_RSC_${kind}_DONE__`;
212
+ const closeFn = `__DINOU_RSC_${kind}_CLOSE__`;
213
+ return `<script>self.${doneName}=true;if(self.${closeFn})self.${closeFn}();</script>`;
214
+ }
215
+
216
+ function injectInlineRscIntoHtmlString(fullHtml, layoutRscText, pageRscText, hasLayout) {
217
+ if (!fullHtml || !pageRscText || (hasLayout && !layoutRscText)) return fullHtml;
218
+ let inlineScripts =
219
+ "<script>window.__DINOU_INLINE_RSC__=true;window.__DINOU_RSC_P__=window.__DINOU_RSC_P__||[];window.__DINOU_RSC_L__=window.__DINOU_RSC_L__||[];</script>";
220
+ if (hasLayout && layoutRscText) {
221
+ inlineScripts += formatRscPushScript("L", layoutRscText) + formatRscDoneScript("L");
222
+ }
223
+ inlineScripts += formatRscPushScript("P", pageRscText) + formatRscDoneScript("P");
224
+ const scriptMatch = fullHtml.match(/<script[^>]*\bsrc="\/(?:runtime|main)/i);
225
+ if (scriptMatch && typeof scriptMatch.index === "number") {
226
+ const idx = scriptMatch.index;
227
+ return fullHtml.slice(0, idx) + inlineScripts + fullHtml.slice(idx);
228
+ }
229
+ const bodyCloseIdx = fullHtml.toLowerCase().lastIndexOf("</body>");
230
+ if (bodyCloseIdx !== -1) {
231
+ return fullHtml.slice(0, bodyCloseIdx) + inlineScripts + fullHtml.slice(bodyCloseIdx);
232
+ }
233
+ return fullHtml + inlineScripts;
234
+ }
235
+
236
+ function createInlineRscHtmlStream(htmlStream, context, clientManifest) {
237
+ const hasLayoutSegment =
238
+ context._resolvedLayoutClientJsx !== null &&
239
+ context._resolvedLayoutClientJsx !== undefined;
240
+ const layoutStream = hasLayoutSegment
241
+ ? requestStorage.run(context, () =>
242
+ renderRSCStream(context._resolvedLayoutClientJsx, clientManifest, {
243
+ runtime: "edge",
244
+ })
245
+ )
246
+ : null;
247
+ const pageStream = requestStorage.run(context, () =>
248
+ renderRSCStream(context._resolvedPageClientJsx, clientManifest, {
249
+ runtime: "edge",
250
+ })
251
+ );
252
+
253
+ const encoder = new TextEncoder();
254
+ let initialSpliceDone = false;
255
+ let streamClosed = false;
256
+ let htmlBuffer = "";
257
+ const pendingScripts = [];
258
+
259
+ return new ReadableStream({
260
+ async start(controller) {
261
+ const safeEnqueueText = (str) => {
262
+ if (streamClosed || !str) return;
263
+ try {
264
+ controller.enqueue(encoder.encode(str));
265
+ } catch (e) {}
266
+ };
267
+
268
+ const flushPendingScripts = () => {
269
+ if (pendingScripts.length === 0) return;
270
+ const batch = pendingScripts.splice(0, pendingScripts.length).join("");
271
+ safeEnqueueText(batch);
272
+ };
273
+
274
+ const onRscScript = (scriptStr) => {
275
+ pendingScripts.push(scriptStr);
276
+ if (initialSpliceDone && htmlBuffer.length === 0) {
277
+ flushPendingScripts();
278
+ }
279
+ };
280
+
281
+ const startPump = (rscStream, kind) => {
282
+ if (!rscStream) {
283
+ return {
284
+ firstChunkReady: Promise.resolve(),
285
+ donePromise: Promise.resolve(),
286
+ };
287
+ }
288
+ let resolveFirst;
289
+ const firstChunkReady = new Promise((r) => {
290
+ resolveFirst = r;
291
+ });
292
+ const donePromise = (async () => {
293
+ const reader = rscStream.getReader();
294
+ const decoder = new TextDecoder();
295
+ let first = true;
296
+ try {
297
+ while (true) {
298
+ const { done, value } = await reader.read();
299
+ if (done) {
300
+ const rem = decoder.decode();
301
+ if (rem) {
302
+ onRscScript(formatRscPushScript(kind, rem));
303
+ }
304
+ onRscScript(formatRscDoneScript(kind));
305
+ if (first) {
306
+ first = false;
307
+ resolveFirst();
308
+ }
309
+ break;
310
+ }
311
+ const chunkStr = decoder.decode(value, { stream: true });
312
+ if (chunkStr) {
313
+ onRscScript(formatRscPushScript(kind, chunkStr));
314
+ if (first) {
315
+ first = false;
316
+ resolveFirst();
317
+ }
318
+ }
319
+ }
320
+ } catch (err) {
321
+ onRscScript(formatRscDoneScript(kind));
322
+ if (first) {
323
+ first = false;
324
+ resolveFirst();
325
+ }
326
+ }
327
+ })();
328
+ return { firstChunkReady, donePromise };
329
+ };
330
+
331
+ const layoutPump = startPump(layoutStream, "L");
332
+ const pagePump = startPump(pageStream, "P");
333
+
334
+ const htmlReader = htmlStream.getReader();
335
+ const htmlDecoder = new TextDecoder();
336
+ let heldBodyClose = "";
337
+
338
+ try {
339
+ while (true) {
340
+ const { done, value } = await htmlReader.read();
341
+ if (done) {
342
+ const rem = htmlDecoder.decode();
343
+ if (rem) {
344
+ htmlBuffer += rem;
345
+ }
346
+ if (heldBodyClose) {
347
+ htmlBuffer = heldBodyClose + htmlBuffer;
348
+ heldBodyClose = "";
349
+ }
350
+ const closeMatch = htmlBuffer.match(/<\/body>\s*<\/html>\s*$/i);
351
+ if (closeMatch) {
352
+ heldBodyClose = closeMatch[0];
353
+ htmlBuffer = htmlBuffer.slice(0, htmlBuffer.length - heldBodyClose.length);
354
+ }
355
+ if (!initialSpliceDone) {
356
+ await Promise.race([
357
+ Promise.all([layoutPump.firstChunkReady, pagePump.firstChunkReady]),
358
+ new Promise((r) => setTimeout(r, 15)),
359
+ ]);
360
+ const scriptMatch = htmlBuffer.match(/<script[^>]*\bsrc="\/(?:runtime|main)/i);
361
+ const scriptsToInject = pendingScripts.splice(0, pendingScripts.length).join("");
362
+ if (scriptMatch && typeof scriptMatch.index === "number") {
363
+ const idx = scriptMatch.index;
364
+ htmlBuffer = htmlBuffer.slice(0, idx) + scriptsToInject + htmlBuffer.slice(idx);
365
+ } else {
366
+ htmlBuffer += scriptsToInject;
367
+ }
368
+ initialSpliceDone = true;
369
+ }
370
+ if (htmlBuffer) {
371
+ safeEnqueueText(htmlBuffer);
372
+ htmlBuffer = "";
373
+ }
374
+ break;
375
+ }
376
+
377
+ const text = htmlDecoder.decode(value, { stream: true });
378
+ if (!text) continue;
379
+
380
+ if (heldBodyClose) {
381
+ htmlBuffer += heldBodyClose + text;
382
+ heldBodyClose = "";
383
+ } else {
384
+ htmlBuffer += text;
385
+ }
386
+
387
+ const closeMatch = htmlBuffer.match(/<\/body>\s*<\/html>\s*$/i);
388
+ if (closeMatch) {
389
+ heldBodyClose = closeMatch[0];
390
+ htmlBuffer = htmlBuffer.slice(0, htmlBuffer.length - heldBodyClose.length);
391
+ }
392
+
393
+ if (!initialSpliceDone) {
394
+ const scriptMatch = htmlBuffer.match(
395
+ /<script\b[^>]*\bsrc="\/(?:runtime|main)[^"]*"[^>]*><\/script>/i
396
+ );
397
+ if (scriptMatch && typeof scriptMatch.index === "number") {
398
+ await Promise.race([
399
+ Promise.all([layoutPump.firstChunkReady, pagePump.firstChunkReady]),
400
+ new Promise((r) => setTimeout(r, 15)),
401
+ ]);
402
+ const idx = scriptMatch.index;
403
+ const scriptsToInject = pendingScripts.splice(0, pendingScripts.length).join("");
404
+ htmlBuffer = htmlBuffer.slice(0, idx) + scriptsToInject + htmlBuffer.slice(idx);
405
+ initialSpliceDone = true;
406
+ }
407
+ }
408
+
409
+ if (initialSpliceDone) {
410
+ const lastScriptClose = htmlBuffer.toLowerCase().lastIndexOf("</script>");
411
+ if (lastScriptClose !== -1) {
412
+ const cutIdx = lastScriptClose + 9;
413
+ const toFlush = htmlBuffer.slice(0, cutIdx);
414
+ htmlBuffer = htmlBuffer.slice(cutIdx);
415
+ if (toFlush) {
416
+ safeEnqueueText(toFlush);
417
+ }
418
+ if (htmlBuffer.length === 0 && pendingScripts.length > 0) {
419
+ flushPendingScripts();
420
+ }
421
+ }
422
+ }
423
+ }
424
+
425
+ initialSpliceDone = true;
426
+ flushPendingScripts();
427
+ await Promise.all([layoutPump.donePromise, pagePump.donePromise]);
428
+ flushPendingScripts();
429
+ if (heldBodyClose) {
430
+ safeEnqueueText(heldBodyClose);
431
+ heldBodyClose = "";
432
+ }
433
+ streamClosed = true;
434
+ controller.close();
435
+ } catch (err) {
436
+ streamClosed = true;
437
+ try {
438
+ controller.error(err);
439
+ } catch (e) {}
440
+ }
441
+ },
442
+ });
443
+ }
444
+
136
445
  // Anti-Bot Shield patterns
137
446
  const botGarbagePatterns = [
138
447
  /\.php$/i,
@@ -150,6 +459,18 @@ const botGarbagePatterns = [
150
459
  /\.log$/i,
151
460
  ];
152
461
 
462
+ function isBotScannerRequest(pathname) {
463
+ if (!pathname || typeof pathname !== "string") return false;
464
+ if (isBotEnvProbePath(pathname)) return true;
465
+ let decoded = pathname;
466
+ try {
467
+ decoded = decodeURIComponent(pathname);
468
+ } catch {}
469
+ return botGarbagePatterns.some(
470
+ (pattern) => pattern.test(pathname) || pattern.test(decoded)
471
+ );
472
+ }
473
+
153
474
  const IS_DYNAMIC_MAP_KEY = Symbol.for("dinou.isDynamic.map");
154
475
  if (!globalThis[IS_DYNAMIC_MAP_KEY]) {
155
476
  globalThis[IS_DYNAMIC_MAP_KEY] = new Map();
@@ -157,32 +478,24 @@ if (!globalThis[IS_DYNAMIC_MAP_KEY]) {
157
478
  const isDynamic = globalThis[IS_DYNAMIC_MAP_KEY];
158
479
  const pageFunctionsConfigCache = new Map();
159
480
 
160
- async function resolvePprForRoute(pagePath, pageFunctionsModule, reqSegments, queryObj) {
161
- const globalCfg = await getDinouConfig();
162
- let inheritedPpr = Boolean(globalCfg?.ppr);
163
- try {
164
- const srcFolder = path.resolve(process.cwd(), "src");
165
- const layouts = getFilePathAndDynamicParams(
166
- reqSegments || [],
167
- queryObj || {},
168
- srcFolder,
169
- "layout",
170
- true,
171
- false,
172
- undefined,
173
- 0,
174
- {},
175
- true
176
- );
177
- if (layouts && Array.isArray(layouts)) {
178
- for (const [lPath, lParams] of layouts) {
179
- const lConfig = await resolveLayoutFunctionsConfig(lPath, lParams);
180
- if (lConfig && lConfig.ppr !== null && lConfig.ppr !== undefined) {
181
- inheritedPpr = Boolean(lConfig.ppr);
182
- }
183
- }
184
- }
185
- } catch (e) {}
481
+ async function resolvePprForRoute(
482
+ pagePath,
483
+ pageFunctionsModule,
484
+ reqSegments,
485
+ queryObj,
486
+ options = {},
487
+ ) {
488
+ const srcFolder = path.resolve(process.cwd(), "src");
489
+ const { defaultPpr, anyLayoutPpr } = await resolveLayoutChainPpr(
490
+ reqSegments || [],
491
+ queryObj || {},
492
+ srcFolder,
493
+ { ignoreNoLayout: Boolean(options?.ignoreNoLayout) },
494
+ );
495
+
496
+ if (options?.segment === "layout") {
497
+ return Boolean(anyLayoutPpr);
498
+ }
186
499
 
187
500
  let explicitPagePpr = null;
188
501
  let pfMod = pageFunctionsModule;
@@ -197,7 +510,7 @@ async function resolvePprForRoute(pagePath, pageFunctionsModule, reqSegments, qu
197
510
  true,
198
511
  true,
199
512
  undefined,
200
- (reqSegments || []).length
513
+ (reqSegments || []).length,
201
514
  );
202
515
  if (pageFunctionsPath) {
203
516
  pfMod = await importModule(pageFunctionsPath);
@@ -208,17 +521,48 @@ async function resolvePprForRoute(pagePath, pageFunctionsModule, reqSegments, qu
208
521
  if (pfMod) {
209
522
  explicitPagePpr = await resolveModulePpr(pfMod);
210
523
  }
524
+ if (
525
+ explicitPagePpr === null &&
526
+ typeof globalThis !== "undefined" &&
527
+ globalThis.__DINOU_ROUTE_METADATA__ &&
528
+ pagePath
529
+ ) {
530
+ const normPage = pagePath.replace(/\\/g, "/");
531
+ const pageDir = path.dirname(normPage);
532
+ for (const [k, meta] of Object.entries(
533
+ globalThis.__DINOU_ROUTE_METADATA__,
534
+ )) {
535
+ if (
536
+ meta.ppr !== undefined &&
537
+ (normPage.endsWith(k) || k.startsWith(pageDir + "/page_functions"))
538
+ ) {
539
+ explicitPagePpr = Boolean(meta.ppr);
540
+ break;
541
+ }
542
+ }
543
+ }
211
544
 
212
- return explicitPagePpr !== null ? explicitPagePpr : inheritedPpr;
545
+ const pageEffectivePpr =
546
+ explicitPagePpr !== null ? explicitPagePpr : Boolean(defaultPpr);
547
+ if (options?.segment === "page") {
548
+ return Boolean(pageEffectivePpr);
549
+ }
550
+ return Boolean(pageEffectivePpr || anyLayoutPpr);
213
551
  }
214
552
 
215
553
  /**
216
554
  * Resolves page_functions configuration (allowISG, validateParams, getStaticPaths)
217
555
  * and determines whether the current request path is blocked or allowed for ISG.
218
556
  */
219
- async function resolvePageFunctionsConfig(pagePath, reqSegments, queryObj, dynamicParams, reqPath) {
557
+ async function resolvePageFunctionsConfig(pagePath, reqSegments, queryObj, dynamicParams, reqPath, isSSG = false) {
558
+ const globalCfg = await getDinouConfig();
559
+ const defaultAllowISG =
560
+ globalCfg?.allowISG !== undefined && globalCfg?.allowISG !== null
561
+ ? Boolean(globalCfg.allowISG)
562
+ : true;
563
+
220
564
  let isPathBlocked = false;
221
- let allowISGValue = true;
565
+ let allowISGValue = defaultAllowISG;
222
566
  let isDynamicConfig = false;
223
567
  let cachedConfig = null;
224
568
 
@@ -245,15 +589,20 @@ async function resolvePageFunctionsConfig(pagePath, reqSegments, queryObj, dynam
245
589
  }
246
590
 
247
591
  const isPpr = await resolvePprForRoute(pagePath, pageFunctionsModule, reqSegments, queryObj);
592
+ const isPagePpr = await resolvePprForRoute(pagePath, pageFunctionsModule, reqSegments, queryObj, {
593
+ segment: "page",
594
+ });
248
595
 
249
596
  if (pageFunctionsModule) {
250
597
  const defaultExport = pageFunctionsModule.default?.default ? pageFunctionsModule.default.default : pageFunctionsModule.default;
598
+ const rawAllowISG =
599
+ pageFunctionsModule.allowISG !== undefined
600
+ ? pageFunctionsModule.allowISG
601
+ : defaultExport?.allowISG;
251
602
  const resolvedAllowISG =
252
- typeof pageFunctionsModule.allowISG === "function"
253
- ? await pageFunctionsModule.allowISG()
254
- : typeof defaultExport?.allowISG === "function"
255
- ? await defaultExport.allowISG()
256
- : (pageFunctionsModule.allowISG ?? defaultExport?.allowISG ?? true);
603
+ typeof rawAllowISG === "function"
604
+ ? await rawAllowISG()
605
+ : (rawAllowISG ?? null);
257
606
 
258
607
  const getStaticPathsFn = pageFunctionsModule.getStaticPaths || defaultExport?.getStaticPaths;
259
608
  let staticPathsSet = null;
@@ -265,36 +614,38 @@ async function resolvePageFunctionsConfig(pagePath, reqSegments, queryObj, dynam
265
614
  staticPathsSet = new Set(
266
615
  paths.map((pathObj) => {
267
616
  if (pathObj && typeof pathObj === "object" && !Array.isArray(pathObj)) {
268
- const sortedEntries = Object.entries(pathObj).sort((a, b) =>
269
- a[0].localeCompare(b[0])
270
- );
617
+ const sortedEntries = Object.entries(pathObj)
618
+ .sort((a, b) => a[0].localeCompare(b[0]))
619
+ .map(([k, v]) => [
620
+ k,
621
+ Array.isArray(v)
622
+ ? v.join(",")
623
+ : v === undefined || v === null
624
+ ? ""
625
+ : String(v),
626
+ ]);
271
627
  return JSON.stringify(sortedEntries);
272
628
  }
273
- return String(pathObj);
629
+ if (Array.isArray(pathObj)) {
630
+ return pathObj.join(",");
631
+ }
632
+ return pathObj === undefined || pathObj === null ? "" : String(pathObj);
274
633
  })
275
634
  );
276
635
  }
277
636
  }
278
637
 
638
+ const rawRevalidate =
639
+ pageFunctionsModule.revalidate !== undefined
640
+ ? pageFunctionsModule.revalidate
641
+ : defaultExport?.revalidate;
279
642
  let revalidateVal =
280
- typeof pageFunctionsModule.revalidate === "function"
281
- ? await pageFunctionsModule.revalidate()
282
- : typeof defaultExport?.revalidate === "function"
283
- ? await defaultExport.revalidate()
284
- : (pageFunctionsModule.revalidate ?? defaultExport?.revalidate);
643
+ typeof rawRevalidate === "function"
644
+ ? await rawRevalidate()
645
+ : rawRevalidate;
285
646
 
286
647
  const isDynamic = typeof revalidateVal === "number" && revalidateVal < 1;
287
648
  const rawTags = pageFunctionsModule.getCacheTags ?? defaultExport?.getCacheTags;
288
- let tagsVal = [];
289
- if (typeof rawTags === "function") {
290
- try {
291
- tagsVal = await rawTags(dynamicParams);
292
- } catch (e) {
293
- console.error("Error running getCacheTags in handler:", e);
294
- }
295
- } else if (Array.isArray(rawTags)) {
296
- tagsVal = rawTags;
297
- }
298
649
 
299
650
  cachedConfig = {
300
651
  allowISG: resolvedAllowISG,
@@ -302,18 +653,22 @@ async function resolvePageFunctionsConfig(pagePath, reqSegments, queryObj, dynam
302
653
  validateParams: pageFunctionsModule.validateParams || defaultExport?.validateParams || null,
303
654
  isDynamic,
304
655
  revalidate: revalidateVal,
305
- tags: tagsVal,
656
+ getCacheTagsFn: typeof rawTags === "function" ? rawTags : null,
657
+ staticTags: Array.isArray(rawTags) ? rawTags : [],
306
658
  ppr: isPpr,
659
+ pagePpr: isPagePpr,
307
660
  };
308
661
  } else {
309
662
  cachedConfig = {
310
- allowISG: true,
663
+ allowISG: null,
311
664
  staticPathsSet: null,
312
665
  validateParams: null,
313
666
  isDynamic: false,
314
667
  revalidate: undefined,
315
- tags: [],
668
+ getCacheTagsFn: null,
669
+ staticTags: [],
316
670
  ppr: isPpr,
671
+ pagePpr: isPagePpr,
317
672
  };
318
673
  }
319
674
 
@@ -323,7 +678,10 @@ async function resolvePageFunctionsConfig(pagePath, reqSegments, queryObj, dynam
323
678
  }
324
679
 
325
680
  const { allowISG: cachedAllowISG, staticPathsSet, validateParams: validateParamsFn, isDynamic: cachedIsDynamic } = cachedConfig;
326
- allowISGValue = cachedAllowISG;
681
+ allowISGValue =
682
+ cachedAllowISG !== null && cachedAllowISG !== undefined
683
+ ? Boolean(cachedAllowISG)
684
+ : defaultAllowISG;
327
685
  isDynamicConfig = Boolean(cachedIsDynamic);
328
686
  const hasParams = Object.keys(dynamicParams || {}).length > 0;
329
687
  if (hasParams) {
@@ -334,18 +692,26 @@ async function resolvePageFunctionsConfig(pagePath, reqSegments, queryObj, dynam
334
692
  }
335
693
  }
336
694
 
337
- if (!isPathBlocked && allowISGValue === false) {
695
+ if (!isPathBlocked && allowISGValue === false && !isSSG) {
338
696
  let isPathAllowed = false;
339
697
  if (staticPathsSet) {
340
698
  const sortedQueryEntries = Object.entries(dynamicParams)
341
699
  .sort((a, b) => a[0].localeCompare(b[0]))
342
- .map(([k, v]) => {
343
- if (Array.isArray(v)) return [k, v.join(",")];
344
- return [k, String(v)];
345
- });
700
+ .map(([k, v]) => [
701
+ k,
702
+ Array.isArray(v)
703
+ ? v.join(",")
704
+ : v === undefined || v === null
705
+ ? ""
706
+ : String(v),
707
+ ]);
346
708
  const serializedQuery = JSON.stringify(sortedQueryEntries);
347
709
  const singleVal = Object.values(dynamicParams)[0];
348
- const singleValStr = Array.isArray(singleVal) ? singleVal.join(",") : String(singleVal);
710
+ const singleValStr = Array.isArray(singleVal)
711
+ ? singleVal.join(",")
712
+ : singleVal === undefined || singleVal === null
713
+ ? ""
714
+ : String(singleVal);
349
715
  isPathAllowed = staticPathsSet.has(serializedQuery) || staticPathsSet.has(singleValStr);
350
716
  }
351
717
  if (!isPathAllowed) {
@@ -354,7 +720,9 @@ async function resolvePageFunctionsConfig(pagePath, reqSegments, queryObj, dynam
354
720
  } else {
355
721
  const cleanReq = reqPath.replace(/^\//, "").replace(/\/$/, "");
356
722
  const htmlPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "index.html");
357
- if (!existsSync(htmlPath)) {
723
+ const shellHtmlPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "shell.html");
724
+ const pageRscPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "page.rsc");
725
+ if (!existsSync(htmlPath) && !existsSync(shellHtmlPath) && !existsSync(pageRscPath)) {
358
726
  isPathBlocked = true;
359
727
  }
360
728
  }
@@ -363,17 +731,93 @@ async function resolvePageFunctionsConfig(pagePath, reqSegments, queryObj, dynam
363
731
  }
364
732
  }
365
733
 
734
+ let resolvedTags = cachedConfig?.staticTags || [];
735
+ if (typeof cachedConfig?.getCacheTagsFn === "function") {
736
+ try {
737
+ const dynamicTags = await cachedConfig.getCacheTagsFn(dynamicParams);
738
+ resolvedTags = Array.isArray(dynamicTags) ? dynamicTags : [];
739
+ } catch (e) {
740
+ console.error("Error running getCacheTags in handler:", e);
741
+ }
742
+ }
743
+
366
744
  return {
367
745
  isPathBlocked,
368
746
  allowISGValue,
369
747
  isDynamicConfig,
370
748
  revalidate: cachedConfig?.revalidate,
371
- tags: cachedConfig?.tags || [],
749
+ tags: resolvedTags,
372
750
  ppr: Boolean(cachedConfig?.ppr),
751
+ pagePpr: Boolean(cachedConfig?.pagePpr),
373
752
  staticPathsSet: cachedConfig?.staticPathsSet || null,
374
753
  };
375
754
  }
376
755
 
756
+ /**
757
+ * Evaluates whether a layout segment blocks the current request via validateParams or allowISG=false.
758
+ * Only applies when the layout segment has dynamic parameters (Object.keys(lParams || {}).length > 0).
759
+ */
760
+ async function isLayoutSegmentBlocked(
761
+ layoutPath,
762
+ lParams,
763
+ layoutConfig,
764
+ cleanLayoutKey,
765
+ reqPath,
766
+ isDevelopment,
767
+ isSSG = false,
768
+ ) {
769
+ if (!layoutPath || !layoutConfig) return false;
770
+ if (Object.keys(lParams || {}).length === 0) return false;
771
+
772
+ if (layoutConfig.validateParams) {
773
+ const isValid = await layoutConfig.validateParams(lParams);
774
+ if (!isValid) {
775
+ return true;
776
+ }
777
+ }
778
+
779
+ if (layoutConfig.allowISG === false && !isSSG) {
780
+ let isPathAllowed = false;
781
+ if (layoutConfig.staticPathsSet) {
782
+ const sortedEntries = Object.entries(lParams)
783
+ .sort((a, b) => a[0].localeCompare(b[0]))
784
+ .map(([k, v]) => [
785
+ k,
786
+ Array.isArray(v)
787
+ ? v.join(",")
788
+ : v === undefined || v === null
789
+ ? ""
790
+ : String(v),
791
+ ]);
792
+ const serialized = JSON.stringify(sortedEntries);
793
+ const singleVal = Object.values(lParams)[0];
794
+ const singleValStr = Array.isArray(singleVal)
795
+ ? singleVal.join(",")
796
+ : singleVal === undefined || singleVal === null
797
+ ? ""
798
+ : String(singleVal);
799
+ isPathAllowed =
800
+ layoutConfig.staticPathsSet.has(serialized) ||
801
+ layoutConfig.staticPathsSet.has(singleValStr);
802
+ }
803
+ if (!isPathAllowed) {
804
+ if (isDevelopment) {
805
+ return true;
806
+ }
807
+ const cleanReq = reqPath.replace(/^\//, "").replace(/\/$/, "");
808
+ const targetLayoutKey = cleanLayoutKey !== undefined ? cleanLayoutKey : cleanReq;
809
+ const layoutRscPath = path.join(process.cwd(), ".dinou/dist2", targetLayoutKey, "layout.rsc");
810
+ const htmlPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "index.html");
811
+ const shellHtmlPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "shell.html");
812
+ if (!existsSync(layoutRscPath) && !existsSync(htmlPath) && !existsSync(shellHtmlPath)) {
813
+ return true;
814
+ }
815
+ }
816
+ }
817
+
818
+ return false;
819
+ }
820
+
377
821
  /**
378
822
  * Parses the Cookie header into an object dictionary.
379
823
  */
@@ -406,61 +850,46 @@ function getDiscoveredLayouts() {
406
850
  if (discoveredLayoutsCache && now - lastLayoutsDiscoveryTime < 1000) {
407
851
  return discoveredLayoutsCache;
408
852
  }
409
- const discovered = [];
853
+ let discovered = [];
410
854
 
411
- // 1. Edge/Workers: Discover layouts from VFS
855
+ // 1. Edge/Workers: Discover layouts and page rules from VFS
412
856
  if (typeof globalThis !== "undefined" && globalThis.__DINOU_VFS__) {
413
857
  const vfs = globalThis.__DINOU_VFS__;
858
+ const vfsFiles = [];
414
859
  for (const key of Object.keys(vfs)) {
415
- if (vfs[key]?.type === "file" && /(?:^|\/)layout\.[jt]sx?$/.test(key)) {
416
- const clean = key.replace(/^\/?src\/?/, "").replace(/\/?layout\.[jt]sx?$/, "");
417
- if (!discovered.includes(clean)) {
418
- discovered.push(clean);
419
- }
420
- } else if (vfs[key]?.type === "file" && /(?:^|\/)no_layout$/.test(key)) {
421
- const clean = "!" + key.replace(/^\/?src\/?/, "").replace(/\/?no_layout$/, "");
422
- if (!discovered.includes(clean)) {
423
- discovered.push(clean);
860
+ if (vfs[key]?.type === "file") {
861
+ const idx = key.indexOf("src/");
862
+ if (idx !== -1) {
863
+ vfsFiles.push(key.slice(idx + 4));
424
864
  }
425
865
  }
426
866
  }
867
+ if (vfsFiles.length > 0) {
868
+ discovered = discoverLayoutsFromFileRelPaths(vfsFiles);
869
+ }
427
870
  }
428
871
 
429
- // 2. Edge/Workers: Discover layouts from Route Modules registry
872
+ // 2. Edge/Workers: Discover layouts and page rules from Route Modules registry
430
873
  if (discovered.length === 0 && typeof globalThis !== "undefined" && globalThis.__DINOU_ROUTE_MODULES__) {
874
+ const modFiles = [];
431
875
  for (const key of Object.keys(globalThis.__DINOU_ROUTE_MODULES__)) {
432
- if (/(?:^|\/)layout\.[jt]sx?$/.test(key)) {
433
- const clean = key.replace(/^\/?src\/?/, "").replace(/\/?layout\.[jt]sx?$/, "");
434
- if (!discovered.includes(clean)) {
435
- discovered.push(clean);
436
- }
876
+ const idx = key.indexOf("src/");
877
+ if (idx !== -1) {
878
+ modFiles.push(key.slice(idx + 4));
879
+ } else {
880
+ modFiles.push(key);
437
881
  }
438
882
  }
883
+ if (modFiles.length > 0) {
884
+ discovered = discoverLayoutsFromFileRelPaths(modFiles);
885
+ }
439
886
  }
440
887
 
441
888
  // 3. Node/Local filesystem discovery
442
889
  if (discovered.length === 0) {
443
890
  try {
444
891
  const srcFolder = path.resolve(process.cwd(), "src");
445
- function find(dir, rel = "") {
446
- if (!existsSync(dir)) return;
447
- let entries;
448
- try {
449
- entries = readdirSync(dir, { withFileTypes: true });
450
- } catch {
451
- return;
452
- }
453
- for (const entry of entries) {
454
- if (entry.isDirectory()) {
455
- find(path.join(dir, entry.name), rel ? `${rel}/${entry.name}` : entry.name);
456
- } else if (/^layout\.[jt]sx?$/.test(entry.name)) {
457
- discovered.push(rel);
458
- } else if (entry.name === "no_layout") {
459
- discovered.push("!" + rel);
460
- }
461
- }
462
- }
463
- find(srcFolder);
892
+ discovered = discoverLayoutsFromFs(srcFolder, { existsSync, readdirSync });
464
893
  } catch (e) {}
465
894
  }
466
895
 
@@ -489,15 +918,24 @@ async function readMetaFromStorage(storage, metaKey, fallbackKey = null, platfor
489
918
  }
490
919
  } catch (e) {}
491
920
  }
921
+ const isDeleted =
922
+ storage &&
923
+ (typeof storage.isKeyDeleted === "function"
924
+ ? await storage.isKeyDeleted(metaKey)
925
+ : typeof storage.isDeleted === "function" && storage.isDeleted(metaKey));
492
926
  if (
493
927
  platformContext &&
494
928
  platformContext.env &&
495
929
  platformContext.env.ASSETS &&
496
930
  requestUrl &&
497
- !(storage && typeof storage.isDeleted === "function" && storage.isDeleted(metaKey))
931
+ !isDeleted
498
932
  ) {
499
933
  try {
500
- const metaRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${metaKey}`, requestUrl)));
934
+ const metaRes = await fetchCloudflareDist2Asset(
935
+ platformContext.env.ASSETS,
936
+ metaKey,
937
+ requestUrl
938
+ );
501
939
  if (metaRes && metaRes.status === 200) {
502
940
  const text = await metaRes.text();
503
941
  if (text && text.trim().startsWith("{")) {
@@ -510,6 +948,19 @@ async function readMetaFromStorage(storage, metaKey, fallbackKey = null, platfor
510
948
  }
511
949
  } catch (e) {}
512
950
  }
951
+ if (!isDeleted && storage) {
952
+ const dist2Item = await readDist2Fallback(storage, metaKey);
953
+ if (dist2Item) {
954
+ if (dist2Item.metadata && typeof dist2Item.metadata === "object" && dist2Item.metadata.generatedAt) {
955
+ return dist2Item.metadata;
956
+ }
957
+ if (typeof dist2Item.content === "string" && dist2Item.content.trim().startsWith("{")) {
958
+ try {
959
+ return JSON.parse(dist2Item.content);
960
+ } catch (e) {}
961
+ }
962
+ }
963
+ }
513
964
  return null;
514
965
  }
515
966
 
@@ -522,15 +973,24 @@ async function readRscFromStorage(storage, rscKey, platformContext = null, reque
522
973
  }
523
974
  } catch (e) {}
524
975
  }
976
+ const isDeleted =
977
+ storage &&
978
+ (typeof storage.isKeyDeleted === "function"
979
+ ? await storage.isKeyDeleted(rscKey)
980
+ : typeof storage.isDeleted === "function" && storage.isDeleted(rscKey));
525
981
  if (
526
982
  platformContext &&
527
983
  platformContext.env &&
528
984
  platformContext.env.ASSETS &&
529
985
  requestUrl &&
530
- !(storage && typeof storage.isDeleted === "function" && storage.isDeleted(rscKey))
986
+ !isDeleted
531
987
  ) {
532
988
  try {
533
- const assetRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${rscKey}`, requestUrl)));
989
+ const assetRes = await fetchCloudflareDist2Asset(
990
+ platformContext.env.ASSETS,
991
+ rscKey,
992
+ requestUrl
993
+ );
534
994
  if (assetRes && assetRes.status === 200) {
535
995
  const text = await assetRes.text();
536
996
  if (text && !text.trimStart().startsWith("<")) {
@@ -542,6 +1002,17 @@ async function readRscFromStorage(storage, rscKey, platformContext = null, reque
542
1002
  }
543
1003
  } catch (e) {}
544
1004
  }
1005
+ if (!isDeleted && storage) {
1006
+ const dist2Item = await readDist2Fallback(storage, rscKey);
1007
+ if (
1008
+ dist2Item &&
1009
+ typeof dist2Item.content === "string" &&
1010
+ dist2Item.content.length > 0 &&
1011
+ !dist2Item.content.trimStart().startsWith("<")
1012
+ ) {
1013
+ return dist2Item.content;
1014
+ }
1015
+ }
545
1016
  return "";
546
1017
  }
547
1018
 
@@ -549,18 +1020,35 @@ function __noopMarker() {
549
1020
  return discovered;
550
1021
  }
551
1022
 
1023
+ function applyStreamingResponseHeaders(headers) {
1024
+ if (!headers.has("Content-Encoding")) {
1025
+ headers.set("Content-Encoding", "identity");
1026
+ }
1027
+ if (!headers.has("X-Accel-Buffering")) {
1028
+ headers.set("X-Accel-Buffering", "no");
1029
+ }
1030
+ const cacheControl = headers.get("Cache-Control");
1031
+ if (!cacheControl) {
1032
+ headers.set("Cache-Control", "no-store, no-cache, must-revalidate, no-transform");
1033
+ } else if (!/\bno-transform\b/i.test(cacheControl)) {
1034
+ headers.set("Cache-Control", `${cacheControl}, no-transform`);
1035
+ }
1036
+ }
1037
+
552
1038
  /**
553
1039
  * Bridges Node.js style response methods to a WHATWG Web Response.
554
1040
  */
555
1041
  class WebResponseBridge extends PassThrough {
556
- constructor() {
1042
+ constructor(platformContext = null) {
557
1043
  super();
558
1044
  this.statusCode = 200;
1045
+ this._explicitStatusSet = false;
559
1046
  this.statusMessage = "";
560
1047
  this.headers = new Headers();
561
1048
  this.cookies = [];
562
1049
  this.headersSent = false;
563
1050
  this._resolved = false;
1051
+ this._platformContext = platformContext;
564
1052
  this._responsePromise = new Promise((resolve) => {
565
1053
  this._resolveResponse = resolve;
566
1054
  });
@@ -569,6 +1057,7 @@ class WebResponseBridge extends PassThrough {
569
1057
 
570
1058
  status(code) {
571
1059
  this.statusCode = code;
1060
+ this._explicitStatusSet = true;
572
1061
  return this;
573
1062
  }
574
1063
 
@@ -641,11 +1130,13 @@ class WebResponseBridge extends PassThrough {
641
1130
  for (const c of this.cookies) {
642
1131
  this.headers.append("Set-Cookie", c);
643
1132
  }
1133
+ applyStreamingResponseHeaders(this.headers);
644
1134
  const webStream = Readable.toWeb(this);
645
1135
  const res = new Response(webStream, {
646
1136
  status: this.statusCode,
647
1137
  statusText: this.statusMessage || undefined,
648
1138
  headers: this.headers,
1139
+ encodeBody: "manual",
649
1140
  });
650
1141
  this._resolved = true;
651
1142
  this._resolveResponse(res);
@@ -695,6 +1186,7 @@ class WebResponseBridge extends PassThrough {
695
1186
  for (const c of this.cookies) {
696
1187
  this.headers.append("Set-Cookie", c);
697
1188
  }
1189
+ applyStreamingResponseHeaders(this.headers);
698
1190
 
699
1191
  const textEncoder = new TextEncoder();
700
1192
  const { readable, writable } = new TransformStream();
@@ -708,7 +1200,7 @@ class WebResponseBridge extends PassThrough {
708
1200
  };
709
1201
  this.on("data", onBridgeData);
710
1202
 
711
- (async () => {
1203
+ const pumpPromise = (async () => {
712
1204
  let reader;
713
1205
  try {
714
1206
  reader = readableStream.getReader();
@@ -737,10 +1229,19 @@ class WebResponseBridge extends PassThrough {
737
1229
  } catch (e) {}
738
1230
  })();
739
1231
 
1232
+ if (
1233
+ this._platformContext &&
1234
+ this._platformContext.ctx &&
1235
+ typeof this._platformContext.ctx.waitUntil === "function"
1236
+ ) {
1237
+ this._platformContext.ctx.waitUntil(pumpPromise);
1238
+ }
1239
+
740
1240
  const res = new Response(readable, {
741
1241
  status: this.statusCode,
742
1242
  statusText: this.statusMessage || undefined,
743
1243
  headers: this.headers,
1244
+ encodeBody: "manual",
744
1245
  });
745
1246
  this._resolved = true;
746
1247
  this._resolveResponse(res);
@@ -758,14 +1259,31 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
758
1259
  let hasRedirected = false;
759
1260
 
760
1261
  const markDynamic = () => {
1262
+ if (isSlotDiscoveryActive()) return;
761
1263
  if (dynamicState) {
762
1264
  dynamicState.value = true;
763
1265
  }
764
1266
  };
765
1267
 
1268
+ const isRscSimReq = Boolean(
1269
+ simReq.isRscRequest ||
1270
+ String(simReq.rawPath || simReq.path || "").includes("____rsc_")
1271
+ );
1272
+
1273
+ const isAllowedRedirectTarget = (candidate) =>
1274
+ typeof candidate === "string" &&
1275
+ ((candidate.startsWith("/") && !candidate.startsWith("//")) ||
1276
+ /^https?:\/\//i.test(candidate));
1277
+
766
1278
  const safeResCall = (methodName, ...args) => {
767
1279
  if (hasRedirected) return;
768
- if (methodName === "setHeader" || methodName === "cookie" || methodName === "clearCookie" || methodName === "redirect") {
1280
+ if (
1281
+ methodName === "status" ||
1282
+ methodName === "setHeader" ||
1283
+ methodName === "cookie" ||
1284
+ methodName === "clearCookie" ||
1285
+ methodName === "redirect"
1286
+ ) {
769
1287
  markDynamic();
770
1288
  }
771
1289
  if (methodName === "clearCookie") {
@@ -783,7 +1301,7 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
783
1301
  const scriptTag = `<script>document.cookie = ${safeCookieStr};</script>`;
784
1302
  resBridge._injectedScripts = (resBridge._injectedScripts || "") + scriptTag;
785
1303
  if (resBridge.headersSent) {
786
- if (!simReq.path.includes("____rsc_")) {
1304
+ if (!isRscSimReq) {
787
1305
  resBridge.write(scriptTag);
788
1306
  }
789
1307
  return;
@@ -806,7 +1324,7 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
806
1324
  const scriptTag = `<script>document.cookie = ${safeCookieStr};</script>`;
807
1325
  resBridge._injectedScripts = (resBridge._injectedScripts || "") + scriptTag;
808
1326
  if (resBridge.headersSent) {
809
- if (!simReq.path.includes("____rsc_")) {
1327
+ if (!isRscSimReq) {
810
1328
  resBridge.write(scriptTag);
811
1329
  }
812
1330
  return;
@@ -819,19 +1337,17 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
819
1337
  }
820
1338
  if (resBridge.headersSent) {
821
1339
  if (methodName === "redirect") {
822
- if (simReq.path.includes("____rsc_")) {
1340
+ if (isRscSimReq) {
823
1341
  return;
824
1342
  }
825
1343
  hasRedirected = true;
1344
+ if (context) context._hasRedirected = true;
826
1345
  let url = args[0];
827
1346
  if (args.length === 2) {
828
1347
  url = args[1];
829
1348
  }
830
1349
  const resolvedUrl = resolveRelativeUrl(url, simReq.path);
831
- let finalUrl = "/";
832
- if (typeof resolvedUrl === "string" && resolvedUrl.startsWith("/") && !resolvedUrl.startsWith("//")) {
833
- finalUrl = resolvedUrl;
834
- }
1350
+ const finalUrl = isAllowedRedirectTarget(resolvedUrl) ? resolvedUrl : "/";
835
1351
  const safeUrl = JSON.stringify(finalUrl);
836
1352
  resBridge.write(`<script>window.location.href = ${safeUrl};</script>`);
837
1353
  resBridge.end();
@@ -841,6 +1357,7 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
841
1357
  }
842
1358
  if (methodName === "redirect") {
843
1359
  hasRedirected = true;
1360
+ if (context) context._hasRedirected = true;
844
1361
  let url = args[0];
845
1362
  let status = 302;
846
1363
  if (args.length === 2) {
@@ -848,11 +1365,8 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
848
1365
  url = args[1];
849
1366
  }
850
1367
  const resolvedUrl = resolveRelativeUrl(url, simReq.path);
851
- let finalUrl = "/";
852
- if (typeof resolvedUrl === "string" && resolvedUrl.startsWith("/") && !resolvedUrl.startsWith("//")) {
853
- finalUrl = resolvedUrl;
854
- }
855
- if (simReq.path.includes("____rsc_")) {
1368
+ const finalUrl = isAllowedRedirectTarget(resolvedUrl) ? resolvedUrl : "/";
1369
+ if (isRscSimReq) {
856
1370
  resBridge.setHeader("x-rsc-redirect", finalUrl);
857
1371
  resBridge.status(200).end();
858
1372
  return;
@@ -865,6 +1379,7 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
865
1379
  const cookiesProxy = createBailoutProxy(simReq.cookies, "Cookies", markDynamic);
866
1380
  const headersProxy = createBailoutProxy(simReq.headers, "Headers", markDynamic);
867
1381
  const queryProxy = createBailoutProxy(simReq.query, "Query", markDynamic);
1382
+ const unifiedEnv = createUnifiedEnv(platformContext.env);
868
1383
 
869
1384
  const context = {
870
1385
  req: {
@@ -872,8 +1387,10 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
872
1387
  headers: headersProxy,
873
1388
  query: queryProxy,
874
1389
  path: simReq.path,
1390
+ rawPath: simReq.rawPath || simReq.path,
1391
+ isRscRequest: isRscSimReq,
875
1392
  method: simReq.method,
876
- env: platformContext.env || {},
1393
+ env: unifiedEnv,
877
1394
  ctx: platformContext.ctx || null,
878
1395
  },
879
1396
  res: {
@@ -883,14 +1400,19 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
883
1400
  cookie: (name, value, options) => safeResCall("cookie", name, value, options),
884
1401
  redirect: (...args) => safeResCall("redirect", ...args),
885
1402
  },
886
- env: platformContext.env || {},
1403
+ env: unifiedEnv,
887
1404
  ctx: platformContext.ctx || null,
888
1405
  platformContext,
889
1406
  _markDynamic: markDynamic,
890
1407
  _dynamicState: dynamicState,
1408
+ _hasRedirected: false,
891
1409
  };
892
1410
 
893
- if (dinouConfig.plugins && Array.isArray(dinouConfig.plugins)) {
1411
+ if (
1412
+ !platformContext?.isSSG &&
1413
+ dinouConfig.plugins &&
1414
+ Array.isArray(dinouConfig.plugins)
1415
+ ) {
894
1416
  for (const plugin of dinouConfig.plugins) {
895
1417
  if (typeof plugin.onRequestContext === "function") {
896
1418
  try {
@@ -910,14 +1432,17 @@ function createRequestContext(simReq, resBridge, platformContext = {}, dynamicSt
910
1432
  * Context for Server Function endpoints.
911
1433
  */
912
1434
  function createServerFunctionContext(simReq, resBridge, platformContext = {}) {
1435
+ const unifiedEnv = createUnifiedEnv(platformContext.env);
913
1436
  const context = {
914
1437
  req: {
915
1438
  cookies: { ...simReq.cookies },
916
1439
  headers: { ...simReq.headers },
917
1440
  query: { ...simReq.query },
918
1441
  path: simReq.path,
1442
+ rawPath: simReq.rawPath || simReq.path,
1443
+ isRscRequest: false,
919
1444
  method: simReq.method,
920
- env: platformContext.env || {},
1445
+ env: unifiedEnv,
921
1446
  ctx: platformContext.ctx || null,
922
1447
  },
923
1448
  res: {
@@ -976,14 +1501,113 @@ function createServerFunctionContext(simReq, resBridge, platformContext = {}) {
976
1501
  resBridge.write(`D:{"type":"cookie","cookie":${JSON.stringify(cookieStr)}}\n`);
977
1502
  },
978
1503
  },
979
- env: platformContext.env || {},
1504
+ env: unifiedEnv,
980
1505
  ctx: platformContext.ctx || null,
981
1506
  platformContext,
1507
+ _dynamicState: { value: true },
982
1508
  };
983
1509
  setCurrentContext(context);
984
1510
  return context;
985
1511
  }
986
1512
 
1513
+ function normalizeLogicalRequestPathname(pathname, headersObj = {}) {
1514
+ if (typeof pathname !== "string" || !pathname) {
1515
+ return "/";
1516
+ }
1517
+ if (
1518
+ /^\/____rsc_(?:page|layout|payload)(?:_(?:old_static|old|static))?____(?:\/|$)/.test(
1519
+ pathname
1520
+ )
1521
+ ) {
1522
+ const stripped = pathname.replace(
1523
+ /^\/____rsc_(?:page|layout|payload)(?:_(?:old_static|old|static))?____/,
1524
+ ""
1525
+ );
1526
+ return stripped || "/";
1527
+ }
1528
+ if (/^\/____rsc_payload_error____(?:\/|$)/.test(pathname)) {
1529
+ const stripped = pathname.replace(/^\/____rsc_payload_error____/, "");
1530
+ return stripped || "/";
1531
+ }
1532
+ if (/^\/____rsc_slot____(?:\/|$)/.test(pathname)) {
1533
+ const currentPath = headersObj["x-dinou-current-path"];
1534
+ if (typeof currentPath === "string" && currentPath.startsWith("/")) {
1535
+ return currentPath.split("?")[0] || "/";
1536
+ }
1537
+ }
1538
+ return pathname;
1539
+ }
1540
+
1541
+ function finalizePluginResponse(result, bridge, request, isRscWireRequest) {
1542
+ let hasBridgeHeaders = false;
1543
+ for (const _ of bridge.headers.keys()) {
1544
+ hasBridgeHeaders = true;
1545
+ break;
1546
+ }
1547
+ const hasBridgeCookies = bridge.cookies.length > 0;
1548
+ let finalRes = result;
1549
+
1550
+ if (hasBridgeHeaders || hasBridgeCookies) {
1551
+ const mergedHeaders = new Headers(result.headers);
1552
+ for (const [k, v] of bridge.headers.entries()) {
1553
+ if (!mergedHeaders.has(k)) {
1554
+ mergedHeaders.set(k, v);
1555
+ }
1556
+ }
1557
+ for (const c of bridge.cookies) {
1558
+ mergedHeaders.append("Set-Cookie", c);
1559
+ }
1560
+ finalRes = new Response(result.body, {
1561
+ status: result.status,
1562
+ statusText: result.statusText,
1563
+ headers: mergedHeaders,
1564
+ });
1565
+ }
1566
+
1567
+ const location = finalRes.headers.get("location");
1568
+ if (
1569
+ isRscWireRequest &&
1570
+ finalRes.status >= 300 &&
1571
+ finalRes.status < 400 &&
1572
+ location
1573
+ ) {
1574
+ const reqUrl = new URL(request.url);
1575
+ let redirectTarget = location;
1576
+ try {
1577
+ const resolved = new URL(location, reqUrl.origin);
1578
+ if (resolved.origin === reqUrl.origin) {
1579
+ redirectTarget = resolved.pathname + resolved.search + resolved.hash;
1580
+ } else {
1581
+ redirectTarget = resolved.href;
1582
+ }
1583
+ } catch (e) {}
1584
+
1585
+ const rscHeaders = new Headers();
1586
+ for (const [k, v] of finalRes.headers.entries()) {
1587
+ const lower = k.toLowerCase();
1588
+ if (lower === "location" || lower === "set-cookie") continue;
1589
+ rscHeaders.set(k, v);
1590
+ }
1591
+ const setCookies =
1592
+ typeof finalRes.headers.getSetCookie === "function"
1593
+ ? finalRes.headers.getSetCookie()
1594
+ : [];
1595
+ for (const c of setCookies) {
1596
+ rscHeaders.append("Set-Cookie", c);
1597
+ }
1598
+ rscHeaders.set("x-rsc-redirect", redirectTarget);
1599
+ if (!rscHeaders.has("Cache-Control")) {
1600
+ rscHeaders.set("Cache-Control", "no-store, no-cache, must-revalidate");
1601
+ }
1602
+ return new Response("", {
1603
+ status: 200,
1604
+ headers: rscHeaders,
1605
+ });
1606
+ }
1607
+
1608
+ return finalRes;
1609
+ }
1610
+
987
1611
  /**
988
1612
  * Universal request handler: (Request, platformContext?) => Promise<Response>
989
1613
  * @param {Request} request
@@ -997,13 +1621,17 @@ async function handleRequest(request, platformContext = {}) {
997
1621
  }
998
1622
  if (platformContext?.env) {
999
1623
  globalThis.__DINOU_ENV__ = platformContext.env;
1624
+ syncEdgeEnvToProcessEnv(platformContext.env);
1000
1625
  }
1001
1626
  }
1002
1627
  const url = new URL(request.url);
1003
1628
  const pathname = url.pathname;
1004
1629
 
1005
- // 1. Anti-Bot Shield
1006
- if (botGarbagePatterns.some((pattern) => pattern.test(pathname))) {
1630
+ // 1. Anti-Bot Shield & Reserved Internal Namespace Guard
1631
+ if (
1632
+ isBotScannerRequest(pathname) ||
1633
+ isReservedCloudflareDist2RequestPath(pathname)
1634
+ ) {
1007
1635
  return new Response("Not Found", { status: 404 });
1008
1636
  }
1009
1637
 
@@ -1032,33 +1660,61 @@ async function handleRequest(request, platformContext = {}) {
1032
1660
  headersObj[k.toLowerCase()] = v;
1033
1661
  }
1034
1662
  const cookiesObj = parseCookieHeader(headersObj["cookie"] || "");
1035
- const queryObj = Object.fromEntries(url.searchParams.entries());
1663
+ const queryObj = {};
1664
+ for (const [k, v] of url.searchParams.entries()) {
1665
+ if (k === "__proto__") continue;
1666
+ if (Object.prototype.hasOwnProperty.call(queryObj, k)) {
1667
+ if (Array.isArray(queryObj[k])) {
1668
+ queryObj[k].push(v);
1669
+ } else {
1670
+ queryObj[k] = [queryObj[k], v];
1671
+ }
1672
+ } else {
1673
+ queryObj[k] = v;
1674
+ }
1675
+ }
1036
1676
  const internalBuildId = queryObj.____build_id____;
1037
1677
  const internalRefreshVersion = queryObj.____v____;
1038
1678
  delete queryObj.____build_id____;
1039
1679
  delete queryObj.____v____;
1040
1680
 
1681
+ const isRscWireRequest =
1682
+ pathname.includes("____rsc_") && !pathname.includes("____server_function____");
1683
+ const logicalPathname = normalizeLogicalRequestPathname(pathname, headersObj);
1684
+
1041
1685
  const simReq = {
1042
- path: pathname,
1043
- url: pathname + url.search,
1686
+ path: logicalPathname,
1687
+ rawPath: pathname,
1688
+ isRscRequest: isRscWireRequest,
1689
+ url: logicalPathname + url.search,
1044
1690
  query: queryObj,
1045
1691
  headers: headersObj,
1046
1692
  cookies: cookiesObj,
1047
1693
  method: request.method,
1048
1694
  };
1049
1695
 
1050
- const bridge = new WebResponseBridge();
1696
+ const cfg = await getDinouConfig();
1697
+ const bridge = new WebResponseBridge(platformContext);
1051
1698
  const rootContext = createRequestContext(simReq, bridge, platformContext);
1052
1699
 
1053
- // 4. Plugin onRequest Hook (Universal Middlewares & Webhooks)
1054
- const cfg = await getDinouConfig();
1055
- if (cfg.plugins && Array.isArray(cfg.plugins)) {
1700
+ // 4. Plugin onRequest Hook (Universal Middlewares & Webhooks; skipped during build-time SSG)
1701
+ if (!platformContext?.isSSG && cfg.plugins && Array.isArray(cfg.plugins)) {
1056
1702
  for (const plugin of cfg.plugins) {
1057
1703
  if (typeof plugin.onRequest === "function") {
1058
1704
  try {
1059
- const result = await plugin.onRequest(request, rootContext);
1705
+ const result = await requestStorage.run(rootContext, () =>
1706
+ plugin.onRequest(request, rootContext)
1707
+ );
1708
+ if (bridge._resolved || bridge.headersSent) {
1709
+ return bridge.toResponse();
1710
+ }
1060
1711
  if (result instanceof Response) {
1061
- return result;
1712
+ return finalizePluginResponse(
1713
+ result,
1714
+ bridge,
1715
+ request,
1716
+ isRscWireRequest
1717
+ );
1062
1718
  }
1063
1719
  } catch (pluginErr) {
1064
1720
  console.error(`[Dinou Plugin Error: "${plugin.name || "unnamed"}"]:`, pluginErr);
@@ -1146,19 +1802,29 @@ async function handleRequest(request, platformContext = {}) {
1146
1802
  }
1147
1803
 
1148
1804
  const normalizedRelativePath = path.normalize(relativePath).replace(/\\/g, "/");
1149
- if (!normalizedRelativePath.startsWith("src/") && normalizedRelativePath !== "src") {
1805
+ const hasEscapedDir = normalizedRelativePath.split("/").slice(1, -1).some((seg) => seg.startsWith("_"));
1806
+ if ((!normalizedRelativePath.startsWith("src/") && normalizedRelativePath !== "src") || hasEscapedDir) {
1150
1807
  return Response.json({ error: "Forbidden access" }, { status: 403 });
1151
1808
  }
1152
1809
 
1153
1810
  const sfManifest = getServerFunctionsManifest();
1811
+ let resolvedRelativePath = normalizedRelativePath;
1154
1812
  if (sfManifest) {
1155
- const allowedExports = sfManifest[normalizedRelativePath];
1813
+ let allowedExports = sfManifest[normalizedRelativePath];
1814
+ if (!allowedExports) {
1815
+ const lowerTarget = normalizedRelativePath.toLowerCase();
1816
+ const matchedKey = Object.keys(sfManifest).find((k) => k.toLowerCase() === lowerTarget);
1817
+ if (matchedKey) {
1818
+ allowedExports = sfManifest[matchedKey];
1819
+ resolvedRelativePath = matchedKey;
1820
+ }
1821
+ }
1156
1822
  if (!allowedExports || !allowedExports.has(exportName)) {
1157
1823
  return Response.json({ error: "Invalid export name" }, { status: 400 });
1158
1824
  }
1159
1825
  }
1160
1826
 
1161
- const absPath = path.resolve(process.cwd(), relativePath);
1827
+ const absPath = path.resolve(process.cwd(), resolvedRelativePath);
1162
1828
  const mod = await importModule(absPath);
1163
1829
  const fn = exportName === "default" ? mod.default : mod[exportName];
1164
1830
 
@@ -1193,14 +1859,22 @@ async function handleRequest(request, platformContext = {}) {
1193
1859
  }
1194
1860
 
1195
1861
  bridge.setHeader("Content-Type", "text/x-component");
1196
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
1862
+ if (!bridge.headers.has("Cache-Control")) {
1863
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
1864
+ }
1197
1865
 
1198
1866
  const manifest = getClientManifest();
1199
- pipeRSC(returnValue, bridge, manifest, platformContext);
1867
+ requestStorage.run(context, () => {
1868
+ pipeRSC(returnValue, bridge, manifest, platformContext);
1869
+ });
1200
1870
  return bridge.toResponse();
1201
1871
  } catch (err) {
1202
1872
  console.error("[Dinou] Error executing server function:", err);
1203
- return Response.json({ error: err.message || "Internal Server Error" }, { status: 500 });
1873
+ const errorPayload = { error: err?.message || "Internal Server Error" };
1874
+ if (err && typeof err.digest === "string") {
1875
+ errorPayload.digest = err.digest;
1876
+ }
1877
+ return Response.json(errorPayload, { status: 500 });
1204
1878
  }
1205
1879
  }
1206
1880
 
@@ -1235,7 +1909,9 @@ async function handleRequest(request, platformContext = {}) {
1235
1909
  { segment: "page" },
1236
1910
  );
1237
1911
  bridge.setHeader("Content-Type", "text/x-component");
1238
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
1912
+ if (!bridge.headers.has("Cache-Control")) {
1913
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
1914
+ }
1239
1915
 
1240
1916
  const manifest = getClientManifest();
1241
1917
  pipeRSC(jsx, bridge, manifest, platformContext);
@@ -1286,7 +1962,9 @@ async function handleRequest(request, platformContext = {}) {
1286
1962
  }
1287
1963
 
1288
1964
  bridge.setHeader("Content-Type", "text/x-component");
1289
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
1965
+ if (!bridge.headers.has("Cache-Control")) {
1966
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
1967
+ }
1290
1968
  bridge.setHeader("X-Dinou-Slot", slotId);
1291
1969
 
1292
1970
  const manifest = getClientManifest();
@@ -1356,23 +2034,74 @@ async function handleRequest(request, platformContext = {}) {
1356
2034
 
1357
2035
  let layoutConfig = null;
1358
2036
  let pageConfig = null;
1359
- if (isLayoutReq) {
1360
- layoutConfig = await resolveLayoutFunctionsConfig(layoutPath, layoutParams);
1361
- if (layoutConfig.isDynamic) {
1362
- dynamicState.value = true;
2037
+ await requestStorage.run(rootContext, async () => {
2038
+ // Authoritative perimeter validation (root-to-child layouts, then page) BEFORE any cached RSC hit
2039
+ const perimeterLayoutChain = getActiveLayoutChain(reqSegments, queryObj, srcFolder, {
2040
+ ignoreNoLayout: isLayoutReq,
2041
+ });
2042
+ if (perimeterLayoutChain.length > 0) {
2043
+ for (let i = perimeterLayoutChain.length - 1; i >= 0; i--) {
2044
+ const entry = perimeterLayoutChain[i];
2045
+ const lCfg = await resolveLayoutFunctionsConfig(entry.layoutPath, entry.dParams);
2046
+ if (i === 0 && isLayoutReq) {
2047
+ layoutConfig = lCfg;
2048
+ }
2049
+ if (isLayoutReq && lCfg.isDynamic) {
2050
+ dynamicState.value = true;
2051
+ }
2052
+ if (
2053
+ await isLayoutSegmentBlocked(
2054
+ entry.layoutPath,
2055
+ entry.dParams,
2056
+ lCfg,
2057
+ entry.cleanLayoutKey,
2058
+ reqPath,
2059
+ isDevelopment,
2060
+ Boolean(platformContext?.isSSG),
2061
+ )
2062
+ ) {
2063
+ isPathBlocked = true;
2064
+ break;
2065
+ }
2066
+ }
2067
+ } else if (isLayoutReq && layoutPath) {
2068
+ layoutConfig = await resolveLayoutFunctionsConfig(layoutPath, layoutParams);
2069
+ if (layoutConfig.isDynamic) {
2070
+ dynamicState.value = true;
2071
+ }
2072
+ if (
2073
+ await isLayoutSegmentBlocked(
2074
+ layoutPath,
2075
+ layoutParams,
2076
+ layoutConfig,
2077
+ undefined,
2078
+ reqPath,
2079
+ isDevelopment,
2080
+ Boolean(platformContext?.isSSG),
2081
+ )
2082
+ ) {
2083
+ isPathBlocked = true;
2084
+ }
1363
2085
  }
1364
- } else if (isPageReq) {
1365
- pageConfig = await resolvePageFunctionsConfig(
1366
- pagePath,
1367
- reqSegments,
1368
- queryObj,
1369
- dynamicParams,
1370
- reqPath,
1371
- );
1372
- if (pageConfig.isDynamicConfig) {
1373
- dynamicState.value = true;
2086
+
2087
+ if (!isLayoutReq && !isPathBlocked) {
2088
+ pageConfig = await resolvePageFunctionsConfig(
2089
+ pagePath,
2090
+ reqSegments,
2091
+ queryObj,
2092
+ dynamicParams,
2093
+ reqPath,
2094
+ Boolean(platformContext?.isSSG),
2095
+ );
2096
+ if (pageConfig.isDynamicConfig) {
2097
+ dynamicState.value = true;
2098
+ }
2099
+ isPathBlocked = pageConfig.isPathBlocked;
1374
2100
  }
1375
- isPathBlocked = pageConfig.isPathBlocked;
2101
+ });
2102
+
2103
+ if (isPathBlocked) {
2104
+ return new Response("Not Found", { status: 404 });
1376
2105
  }
1377
2106
 
1378
2107
  const nonBuildIdQueryKeys = Object.keys(queryObj);
@@ -1387,6 +2116,7 @@ async function handleRequest(request, platformContext = {}) {
1387
2116
  : "page.rsc";
1388
2117
 
1389
2118
  let isRoutePpr = false;
2119
+ let hasDetectedSegmentPpr = false;
1390
2120
  let currentGeneratedAt = null;
1391
2121
  let leafLayoutSuspenseCount = 0;
1392
2122
  if (!isDevelopment && isEdgeRuntime(platformContext)) {
@@ -1402,6 +2132,7 @@ async function handleRequest(request, platformContext = {}) {
1402
2132
  const lRscKey = entry.cleanLayoutKey ? `${entry.cleanLayoutKey}/layout.rsc` : "layout.rsc";
1403
2133
  const lMeta = await readMetaFromStorage(storage, lMetaKey, lRscKey, platformContext, request.url);
1404
2134
  entry.generatedAt = Number(lMeta?.generatedAt || 0);
2135
+ entry.layoutGeneratedAt = Number(lMeta?.layoutGeneratedAt || lMeta?.generatedAt || 0);
1405
2136
  entry.suspenseCount = Number(lMeta?.suspenseCount || 0);
1406
2137
  entry.revalidate = lMeta?.revalidate;
1407
2138
  entry.slotTags = Array.isArray(lMeta?.slotTags) ? lMeta.slotTags : [];
@@ -1412,17 +2143,33 @@ async function handleRequest(request, platformContext = {}) {
1412
2143
  const isLayoutTtlExpired =
1413
2144
  typeof entry.revalidate === "number" &&
1414
2145
  entry.revalidate >= 1 &&
1415
- entry.generatedAt > 0 &&
1416
- Date.now() > entry.generatedAt + entry.revalidate * 1000;
2146
+ entry.layoutGeneratedAt > 0 &&
2147
+ Date.now() > entry.layoutGeneratedAt + entry.revalidate * 1000;
1417
2148
  const isLayoutSlotTtlExpired =
1418
2149
  !isLayoutTtlExpired &&
1419
2150
  entry.slotTags.length > 0 &&
1420
2151
  (await hasExpiredSlots(entry.slotTags));
2152
+ const ancestors =
2153
+ i < activeChain.length - 1 ? activeChain.slice(i + 1) : [];
1421
2154
  const maxAncestorGen =
1422
- i < activeChain.length - 1
1423
- ? Math.max(0, ...activeChain.slice(i + 1).map((l) => l.generatedAt || 0))
2155
+ ancestors.length > 0
2156
+ ? Math.max(0, ...ancestors.map((l) => l.generatedAt || 0))
1424
2157
  : 0;
1425
- const isAncestorNewer = entry.generatedAt > 0 && maxAncestorGen > entry.generatedAt;
2158
+ const maxAncestorOwnGen =
2159
+ ancestors.length > 0
2160
+ ? Math.max(
2161
+ 0,
2162
+ ...ancestors.map((l) => l.layoutGeneratedAt || l.generatedAt || 0)
2163
+ )
2164
+ : 0;
2165
+ const entryOwnGen = entry.layoutGeneratedAt || entry.generatedAt || 0;
2166
+ const isAncestorOwnNewer =
2167
+ entryOwnGen > 0 && maxAncestorOwnGen > entryOwnGen;
2168
+ const isAncestorSlotOnlyNewer =
2169
+ !isAncestorOwnNewer &&
2170
+ entry.generatedAt > 0 &&
2171
+ maxAncestorGen > entry.generatedAt;
2172
+ const isAncestorNewer = isAncestorOwnNewer || isAncestorSlotOnlyNewer;
1426
2173
  if (isLayoutSlotTtlExpired && !isLayoutTtlExpired && !(isLayoutReq && isAncestorNewer)) {
1427
2174
  const layoutSlotRevalKey = `layout-slot:${entry.layoutRoutePath}`;
1428
2175
  const layoutSlotRevalPromise = (async () => {
@@ -1442,7 +2189,11 @@ async function handleRequest(request, platformContext = {}) {
1442
2189
  }
1443
2190
  } else if (isLayoutTtlExpired || (isLayoutReq && isAncestorNewer)) {
1444
2191
  const { revalidateLayout } = await import("./cache-revalidate.js");
1445
- await revalidateLayout(entry.layoutRoutePath, {});
2192
+ await revalidateLayout(entry.layoutRoutePath, {
2193
+ onlyRefreshSlots:
2194
+ !isLayoutTtlExpired && !isAncestorOwnNewer && isAncestorSlotOnlyNewer,
2195
+ onlyIfExpired: isLayoutTtlExpired && !(isLayoutReq && isAncestorNewer),
2196
+ });
1446
2197
  const lMetaKey = entry.cleanLayoutKey
1447
2198
  ? `${entry.cleanLayoutKey}/layout.metadata.json`
1448
2199
  : "layout.metadata.json";
@@ -1459,6 +2210,11 @@ async function handleRequest(request, platformContext = {}) {
1459
2210
  if (refreshedMeta?.generatedAt) {
1460
2211
  entry.generatedAt = Number(refreshedMeta.generatedAt);
1461
2212
  }
2213
+ if (refreshedMeta?.layoutGeneratedAt || refreshedMeta?.generatedAt) {
2214
+ entry.layoutGeneratedAt = Number(
2215
+ refreshedMeta.layoutGeneratedAt || refreshedMeta.generatedAt
2216
+ );
2217
+ }
1462
2218
  if (refreshedMeta?.suspenseCount !== undefined) {
1463
2219
  entry.suspenseCount = Number(refreshedMeta.suspenseCount || 0);
1464
2220
  }
@@ -1481,16 +2237,25 @@ async function handleRequest(request, platformContext = {}) {
1481
2237
  if (edgeMeta.dynamic) {
1482
2238
  dynamicState.value = true;
1483
2239
  }
2240
+ if (edgeMeta.ppr !== undefined) {
2241
+ isRoutePpr = Boolean(edgeMeta.ppr);
2242
+ hasDetectedSegmentPpr = true;
2243
+ }
1484
2244
  if (Array.isArray(edgeMeta.holes) && edgeMeta.holes.length > 0) {
1485
2245
  isRoutePpr = true;
2246
+ hasDetectedSegmentPpr = true;
1486
2247
  }
1487
- } else if (edgeMeta.ppr) {
1488
- isRoutePpr = true;
2248
+ } else if (edgeMeta.pagePpr !== undefined) {
2249
+ isRoutePpr = Boolean(edgeMeta.pagePpr);
2250
+ hasDetectedSegmentPpr = true;
2251
+ } else if (edgeMeta.ppr !== undefined) {
2252
+ isRoutePpr = Boolean(edgeMeta.ppr);
2253
+ hasDetectedSegmentPpr = true;
1489
2254
  }
1490
2255
  }
1491
2256
  }
1492
2257
  }
1493
- if (!currentGeneratedAt && !platformContext?.isSSG) {
2258
+ if (!currentGeneratedAt && !platformContext?.isSSG && !isEdgeRuntime(platformContext)) {
1494
2259
  try {
1495
2260
  const metaFileName = isLayoutReq ? "layout.metadata.json" : "metadata.json";
1496
2261
  const metadataPath = path.join(".dinou/dist2", cleanPath, metaFileName);
@@ -1501,42 +2266,67 @@ async function handleRequest(request, platformContext = {}) {
1501
2266
  if (metaObj.dynamic) {
1502
2267
  dynamicState.value = true;
1503
2268
  }
2269
+ if (metaObj.ppr !== undefined) {
2270
+ isRoutePpr = Boolean(metaObj.ppr);
2271
+ hasDetectedSegmentPpr = true;
2272
+ }
1504
2273
  if (Array.isArray(metaObj.holes) && metaObj.holes.length > 0) {
1505
2274
  isRoutePpr = true;
2275
+ hasDetectedSegmentPpr = true;
1506
2276
  }
1507
- } else if (metaObj.ppr) {
1508
- isRoutePpr = true;
2277
+ } else if (metaObj.pagePpr !== undefined) {
2278
+ isRoutePpr = Boolean(metaObj.pagePpr);
2279
+ hasDetectedSegmentPpr = true;
2280
+ } else if (metaObj.ppr !== undefined) {
2281
+ isRoutePpr = Boolean(metaObj.ppr);
2282
+ hasDetectedSegmentPpr = true;
1509
2283
  }
1510
2284
  }
1511
2285
  } catch (e) {}
1512
2286
  }
1513
2287
 
1514
- if (!isRoutePpr) {
2288
+ if (!hasDetectedSegmentPpr) {
1515
2289
  isRoutePpr = isLayoutReq
1516
- ? Boolean(platformContext?.isSSG && layoutConfig?.ppr)
1517
- : pageConfig?.ppr !== undefined && pageConfig?.ppr !== null
1518
- ? Boolean(pageConfig.ppr)
1519
- : await resolvePprForRoute(pagePath, null, reqSegments, queryObj);
2290
+ ? await resolvePprForRoute(null, null, reqSegments, queryObj, {
2291
+ segment: "layout",
2292
+ ignoreNoLayout: true,
2293
+ })
2294
+ : pageConfig?.pagePpr !== undefined && pageConfig?.pagePpr !== null
2295
+ ? Boolean(pageConfig.pagePpr)
2296
+ : await resolvePprForRoute(pagePath, null, reqSegments, queryObj, {
2297
+ segment: "page",
2298
+ });
1520
2299
  }
1521
2300
 
1522
2301
  const canServeCachedRsc = isLayoutReq
1523
- ? !isDevelopment && !platformContext?.isSSG && !dynamicState.value && !isRoutePpr
1524
- : !isDevelopment && !platformContext?.isSSG && !dynamicState.value && (!hasQueryParams || isStatic) && !isRoutePpr;
2302
+ ? !isDevelopment &&
2303
+ !platformContext?.isSSG &&
2304
+ (!dynamicState.value || (isStatic && Boolean(internalBuildId))) &&
2305
+ !isRoutePpr
2306
+ : !isDevelopment &&
2307
+ !platformContext?.isSSG &&
2308
+ (!dynamicState.value || (isStatic && Boolean(internalBuildId))) &&
2309
+ (!hasQueryParams || isStatic) &&
2310
+ !isRoutePpr;
1525
2311
 
1526
2312
  if (canServeCachedRsc) {
2313
+ const hasTimestampComparison = Boolean(
2314
+ !internalRefreshVersion && internalBuildId && currentGeneratedAt
2315
+ );
1527
2316
  const useOld =
1528
2317
  isOld ||
1529
- regenerating.has(cleanPath) ||
1530
- (!internalRefreshVersion &&
1531
- internalBuildId &&
1532
- currentGeneratedAt &&
1533
- Number(internalBuildId) < Number(currentGeneratedAt));
2318
+ (hasTimestampComparison
2319
+ ? Number(internalBuildId) < Number(currentGeneratedAt)
2320
+ : !isEdgeRuntime(platformContext) &&
2321
+ (regenerating.has(reqPath) || regenerating.has(cleanPath)));
2322
+
2323
+ const resolvedTargetFileName = targetFileName;
1534
2324
 
1535
2325
  const actualFileName = useOld
1536
2326
  ? isLayoutReq
1537
2327
  ? "layout._old.rsc"
1538
2328
  : "page._old.rsc"
1539
- : targetFileName;
2329
+ : resolvedTargetFileName;
1540
2330
 
1541
2331
  let payloadPath = path.resolve(
1542
2332
  ".dinou/dist2",
@@ -1544,6 +2334,17 @@ async function handleRequest(request, platformContext = {}) {
1544
2334
  actualFileName,
1545
2335
  );
1546
2336
 
2337
+ if (!existsSync(payloadPath) && useOld) {
2338
+ const currentFallbackPath = path.resolve(
2339
+ ".dinou/dist2",
2340
+ cleanPath.replace(/^\//, ""),
2341
+ resolvedTargetFileName,
2342
+ );
2343
+ if (existsSync(currentFallbackPath)) {
2344
+ payloadPath = currentFallbackPath;
2345
+ }
2346
+ }
2347
+
1547
2348
  // Legacy fallback for rsc_payload if page.rsc doesn't exist
1548
2349
  if (!existsSync(payloadPath) && !isLayoutReq && !isPageReq) {
1549
2350
  const legacyPath = path.resolve(
@@ -1568,7 +2369,9 @@ async function handleRequest(request, platformContext = {}) {
1568
2369
  try {
1569
2370
  let cached = await storage.get(rscKey);
1570
2371
  if (!cached && useOld) {
1571
- const fallbackCurrKey = cleanRel ? `${cleanRel}/${targetFileName}` : targetFileName;
2372
+ const fallbackCurrKey = cleanRel
2373
+ ? `${cleanRel}/${resolvedTargetFileName}`
2374
+ : resolvedTargetFileName;
1572
2375
  cached = await storage.get(fallbackCurrKey);
1573
2376
  }
1574
2377
  if (!cached && !isLayoutReq && !isPageReq) {
@@ -1590,7 +2393,9 @@ async function handleRequest(request, platformContext = {}) {
1590
2393
  (await readMetaFromStorage(storage, pMetaKey, pRscBaseKey, platformContext, request.url));
1591
2394
  if (pMeta) {
1592
2395
  const pReval =
1593
- pMeta.pageRevalidate !== undefined ? pMeta.pageRevalidate : pMeta.revalidate;
2396
+ pMeta.pageRevalidate !== undefined && pMeta.pageRevalidate !== null
2397
+ ? pMeta.pageRevalidate
2398
+ : pMeta.revalidate;
1594
2399
  const pGen = pMeta.pageGeneratedAt || pMeta.generatedAt || 0;
1595
2400
  if (typeof pReval === "number" && pReval >= 1 && pGen > 0 && Date.now() > pGen + pReval * 1000) {
1596
2401
  isExpired = true;
@@ -1599,9 +2404,15 @@ async function handleRequest(request, platformContext = {}) {
1599
2404
  }
1600
2405
  }
1601
2406
  if (isSlotOnlyExpired && !isExpired) {
1602
- const slotRevalKey = `slot:${cleanPath}`;
2407
+ const slotRevalKey = `slot:${reqPath}`;
1603
2408
  const slotRevalPromise = (async () => {
1604
- if (regenerating.has(slotRevalKey) || regenerating.has(cleanPath)) return;
2409
+ if (
2410
+ regenerating.has(slotRevalKey) ||
2411
+ regenerating.has(reqPath) ||
2412
+ regenerating.has(cleanPath)
2413
+ ) {
2414
+ return;
2415
+ }
1605
2416
  regenerating.add(slotRevalKey);
1606
2417
  try {
1607
2418
  const { revalidatePage } = await import("./cache-revalidate.js");
@@ -1616,16 +2427,25 @@ async function handleRequest(request, platformContext = {}) {
1616
2427
  platformContext.ctx.waitUntil(slotRevalPromise);
1617
2428
  }
1618
2429
  } else if (isExpired) {
1619
- const { revalidatePage } = await import("./cache-revalidate.js");
1620
- await revalidatePage(cleanPath, {});
1621
- if (!dynamicState.value) {
1622
- const refreshedCached = await storage.get(rscKey);
1623
- if (refreshedCached && refreshedCached.content) {
1624
- cached = refreshedCached;
1625
- isExpired = false;
1626
- }
2430
+ if (regenerating.has(reqPath) || regenerating.has(cleanPath)) {
2431
+ isExpired = false;
1627
2432
  } else {
1628
- isExpired = true;
2433
+ regenerating.add(reqPath);
2434
+ try {
2435
+ const { revalidatePage } = await import("./cache-revalidate.js");
2436
+ await revalidatePage(cleanPath, { onlyIfExpired: true });
2437
+ } finally {
2438
+ regenerating.delete(reqPath);
2439
+ }
2440
+ if (!dynamicState.value) {
2441
+ const refreshedCached = await storage.get(rscKey);
2442
+ if (refreshedCached && refreshedCached.content) {
2443
+ cached = refreshedCached;
2444
+ isExpired = false;
2445
+ }
2446
+ } else {
2447
+ isExpired = true;
2448
+ }
1629
2449
  }
1630
2450
  }
1631
2451
  }
@@ -1633,7 +2453,9 @@ async function handleRequest(request, platformContext = {}) {
1633
2453
  const contentStr = typeof cached.content === "string" ? cached.content : "";
1634
2454
  if (!contentStr.trimStart().startsWith("<")) {
1635
2455
  bridge.setHeader("Content-Type", "text/x-component");
1636
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2456
+ if (!bridge.headers.has("Cache-Control")) {
2457
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2458
+ }
1637
2459
  bridge.end(cached.content);
1638
2460
  return bridge.toResponse();
1639
2461
  }
@@ -1641,14 +2463,23 @@ async function handleRequest(request, platformContext = {}) {
1641
2463
  }
1642
2464
  } catch (e) {}
1643
2465
 
2466
+ const isRscDeleted =
2467
+ typeof storage.isKeyDeleted === "function"
2468
+ ? await storage.isKeyDeleted(rscKey)
2469
+ : typeof storage.isDeleted === "function" && storage.isDeleted(rscKey);
2470
+
1644
2471
  if (
1645
2472
  platformContext &&
1646
2473
  platformContext.env &&
1647
2474
  platformContext.env.ASSETS &&
1648
- !(typeof storage.isDeleted === "function" && storage.isDeleted(rscKey))
2475
+ !isRscDeleted
1649
2476
  ) {
1650
2477
  try {
1651
- const assetRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${rscKey}`, request.url)));
2478
+ const assetRes = await fetchCloudflareDist2Asset(
2479
+ platformContext.env.ASSETS,
2480
+ rscKey,
2481
+ request.url
2482
+ );
1652
2483
  if (assetRes && assetRes.status === 200) {
1653
2484
  const contentType = assetRes.headers.get("content-type") || "";
1654
2485
  const rscContent = await assetRes.text();
@@ -1660,19 +2491,40 @@ async function handleRequest(request, platformContext = {}) {
1660
2491
  ) {
1661
2492
  await storage.set(rscKey, rscContent);
1662
2493
  bridge.setHeader("Content-Type", "text/x-component");
1663
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2494
+ if (!bridge.headers.has("Cache-Control")) {
2495
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2496
+ }
1664
2497
  bridge.end(rscContent);
1665
2498
  return bridge.toResponse();
1666
2499
  }
1667
2500
  }
1668
2501
  } catch (e) {}
1669
2502
  }
2503
+
2504
+ if (!isRscDeleted) {
2505
+ const dist2Rsc = await readDist2Fallback(storage, rscKey);
2506
+ if (
2507
+ dist2Rsc &&
2508
+ typeof dist2Rsc.content === "string" &&
2509
+ dist2Rsc.content.trim().length > 0 &&
2510
+ !dist2Rsc.content.trimStart().startsWith("<")
2511
+ ) {
2512
+ bridge.setHeader("Content-Type", "text/x-component");
2513
+ if (!bridge.headers.has("Cache-Control")) {
2514
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2515
+ }
2516
+ bridge.end(dist2Rsc.content);
2517
+ return bridge.toResponse();
2518
+ }
2519
+ }
1670
2520
  } else if (existsSync(payloadPath)) {
1671
2521
  try {
1672
2522
  const buffer = readFileSync(payloadPath);
1673
2523
  if (buffer && buffer.length > 0) {
1674
2524
  bridge.setHeader("Content-Type", "application/octet-stream");
1675
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2525
+ if (!bridge.headers.has("Cache-Control")) {
2526
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2527
+ }
1676
2528
  bridge.end(buffer);
1677
2529
  return bridge.toResponse();
1678
2530
  }
@@ -1683,94 +2535,9 @@ async function handleRequest(request, platformContext = {}) {
1683
2535
  }
1684
2536
  }
1685
2537
 
1686
- if (isLayoutReq) {
1687
- if (layouts && Array.isArray(layouts)) {
1688
- for (const [lPath, lParams] of layouts) {
1689
- const lConfig = await resolveLayoutFunctionsConfig(lPath, lParams);
1690
- if (lConfig.allowISG === false) {
1691
- let isPathAllowed = false;
1692
- if (lConfig.staticPathsSet) {
1693
- const sortedEntries = Object.entries(lParams || {})
1694
- .sort((a, b) => a[0].localeCompare(b[0]))
1695
- .map(([k, v]) => {
1696
- if (Array.isArray(v)) return [k, v.join(",")];
1697
- return [k, String(v)];
1698
- });
1699
- const serializedQuery = JSON.stringify(sortedEntries);
1700
- const singleVal = Object.values(lParams || {})[0];
1701
- const singleValStr = Array.isArray(singleVal) ? singleVal.join(",") : String(singleVal);
1702
- isPathAllowed = lConfig.staticPathsSet.has(serializedQuery) || lConfig.staticPathsSet.has(singleValStr);
1703
- }
1704
- if (!isPathAllowed) {
1705
- if (isDevelopment) {
1706
- isPathBlocked = true;
1707
- break;
1708
- }
1709
- const cleanReq = reqPath.replace(/^\//, "").replace(/\/$/, "");
1710
- const rscPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "layout.rsc");
1711
- if (!existsSync(rscPath)) {
1712
- isPathBlocked = true;
1713
- break;
1714
- }
1715
- }
1716
- }
1717
- if (lConfig.validateParams) {
1718
- const isValid = await lConfig.validateParams(lParams);
1719
- if (!isValid) {
1720
- isPathBlocked = true;
1721
- break;
1722
- }
1723
- }
1724
- }
1725
- } else {
1726
- if (!layoutConfig) {
1727
- layoutConfig = await resolveLayoutFunctionsConfig(layoutPath, layoutParams);
1728
- }
1729
- if (layoutConfig.allowISG === false) {
1730
- let isPathAllowed = false;
1731
- if (layoutConfig.staticPathsSet) {
1732
- const sortedEntries = Object.entries(layoutParams || {})
1733
- .sort((a, b) => a[0].localeCompare(b[0]))
1734
- .map(([k, v]) => {
1735
- if (Array.isArray(v)) return [k, v.join(",")];
1736
- return [k, String(v)];
1737
- });
1738
- const serializedQuery = JSON.stringify(sortedEntries);
1739
- const singleVal = Object.values(layoutParams || {})[0];
1740
- const singleValStr = Array.isArray(singleVal) ? singleVal.join(",") : String(singleVal);
1741
- isPathAllowed = layoutConfig.staticPathsSet.has(serializedQuery) || layoutConfig.staticPathsSet.has(singleValStr);
1742
- }
1743
- if (!isPathAllowed) {
1744
- if (isDevelopment) {
1745
- isPathBlocked = true;
1746
- } else {
1747
- const cleanReq = reqPath.replace(/^\//, "").replace(/\/$/, "");
1748
- const rscPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "layout.rsc");
1749
- if (!existsSync(rscPath)) {
1750
- isPathBlocked = true;
1751
- }
1752
- }
1753
- }
1754
- }
1755
- if (layoutConfig.validateParams) {
1756
- const isValid = await layoutConfig.validateParams(layoutParams);
1757
- if (!isValid) {
1758
- isPathBlocked = true;
1759
- }
1760
- }
1761
- }
1762
- if (isPathBlocked) {
1763
- return new Response("Not Found", { status: 404 });
1764
- }
1765
- } else if (!pageConfig) {
1766
- pageConfig = await resolvePageFunctionsConfig(
1767
- pagePath,
1768
- reqSegments,
1769
- queryObj,
1770
- dynamicParams,
1771
- reqPath,
1772
- );
1773
- isPathBlocked = pageConfig.isPathBlocked;
2538
+ // Perimeter checks (root-to-child layouts + page) already ran authoritatively above before cache lookup.
2539
+ if (isPathBlocked) {
2540
+ return new Response("Not Found", { status: 404 });
1774
2541
  }
1775
2542
 
1776
2543
  const rscDynamicState = isLayoutReq ? dynamicState : (isRoutePpr ? { value: false } : dynamicState);
@@ -1784,7 +2551,13 @@ async function handleRequest(request, platformContext = {}) {
1784
2551
  let jsx;
1785
2552
  if (platformContext?.isSSG) {
1786
2553
  const ssgIsPpr = isLayoutReq
1787
- ? Boolean(isRoutePpr || (await resolvePprForRoute(null, null, reqSegments, queryObj)))
2554
+ ? Boolean(
2555
+ isRoutePpr ||
2556
+ (await resolvePprForRoute(null, null, reqSegments, queryObj, {
2557
+ segment: "layout",
2558
+ ignoreNoLayout: true,
2559
+ })),
2560
+ )
1788
2561
  : Boolean(isRoutePpr);
1789
2562
  jsx = await runWithPprContext({ isPpr: ssgIsPpr }, async () => {
1790
2563
  const rawJsx = await getJSX(reqPath, queryObj, isNotFound, isDevelopment, isPathBlocked, {
@@ -1804,11 +2577,14 @@ async function handleRequest(request, platformContext = {}) {
1804
2577
  if (regHoles.length > 0) {
1805
2578
  bridge.setHeader("X-Dinou-Ppr-Holes", JSON.stringify(regHoles));
1806
2579
  }
2580
+ if (isLayoutReq && ssgIsPpr) {
2581
+ bridge.setHeader("X-Dinou-Ppr", "true");
2582
+ }
1807
2583
  bridge.setHeader("X-Dinou-Suspense-Count", String(getPprHoleCounter()));
1808
2584
  if (rscDynamicState.value) {
1809
2585
  bridge.setHeader("X-Dinou-Dynamic", "true");
1810
2586
  }
1811
- if (rendered && isEdgeRuntime(platformContext)) {
2587
+ if (rendered && !rscDynamicState.value && isEdgeRuntime(platformContext)) {
1812
2588
  try {
1813
2589
  const storage = getStorageAdapter();
1814
2590
  const cleanRel = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
@@ -1818,7 +2594,7 @@ async function handleRequest(request, platformContext = {}) {
1818
2594
  }
1819
2595
  return rendered;
1820
2596
  });
1821
- } else if (!isDevelopment && (isPageReq || isLayoutReq) && isRoutePpr && isEdgeRuntime(platformContext)) {
2597
+ } else if (!isDevelopment && !dynamicState.value && (isPageReq || isLayoutReq) && isRoutePpr && isEdgeRuntime(platformContext)) {
1822
2598
  const storage = getStorageAdapter();
1823
2599
  const cleanRel = cleanPath.replace(/^\/+/, "").replace(/\/+$/, "");
1824
2600
  if (isPageReq) {
@@ -1878,7 +2654,7 @@ async function handleRequest(request, platformContext = {}) {
1878
2654
  jsx = await spliceDynamicHolesIntoShell(
1879
2655
  cachedShellTree,
1880
2656
  () =>
1881
- getJSX(reqPath, queryObj, isNotFound, isDevelopment, isPathBlocked, {
2657
+ getJSX(reqPath, queryObj, isNotFound, isDevelopment, isPathBlocked, { skipLayoutProbe: true,
1882
2658
  segment,
1883
2659
  }),
1884
2660
  isLayoutReq ? 0 : leafLayoutSuspenseCount
@@ -1905,11 +2681,16 @@ async function handleRequest(request, platformContext = {}) {
1905
2681
  bridge.status(404);
1906
2682
  }
1907
2683
  bridge.setHeader("Content-Type", "text/x-component");
1908
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2684
+ if (!bridge.headers.has("Cache-Control")) {
2685
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2686
+ }
1909
2687
 
1910
2688
  const manifest = getClientManifest();
1911
2689
  pipeRSC(jsx, bridge, manifest, platformContext);
1912
2690
  } catch (err) {
2691
+ if (bridge.headers.has("x-rsc-redirect") || bridge.headers.has("Location")) {
2692
+ return;
2693
+ }
1913
2694
  console.error(`[Dinou] Error rendering RSC ${segment}:`, err);
1914
2695
  const serializedError = {
1915
2696
  message: isDevelopment
@@ -1946,18 +2727,6 @@ async function handleRequest(request, platformContext = {}) {
1946
2727
  dynamicState.value = false;
1947
2728
  }
1948
2729
 
1949
- let { isPathBlocked, allowISGValue, isDynamicConfig, revalidate, tags, ppr: isPprConfig } = await resolvePageFunctionsConfig(
1950
- pagePath,
1951
- reqSegments,
1952
- queryObj,
1953
- dynamicParams,
1954
- reqPath,
1955
- );
1956
- let hasStaticDynamicConfig = Boolean(isDynamicConfig);
1957
- if (isDynamicConfig) {
1958
- dynamicState.value = true;
1959
- }
1960
-
1961
2730
  const layouts = getFilePathAndDynamicParams(
1962
2731
  reqSegments,
1963
2732
  queryObj,
@@ -1971,72 +2740,107 @@ async function handleRequest(request, platformContext = {}) {
1971
2740
  true
1972
2741
  );
1973
2742
 
1974
- let combinedTags = Array.isArray(tags) ? [...tags] : [];
1975
- let combinedRevalidate = revalidate;
1976
-
1977
- if (layouts && Array.isArray(layouts)) {
1978
- for (const [layoutPath, layoutParams] of layouts) {
1979
- const layoutConfig = await resolveLayoutFunctionsConfig(layoutPath, layoutParams);
2743
+ let isPathBlocked = false;
2744
+ let allowISGValue = true;
2745
+ let isDynamicConfig = false;
2746
+ let revalidate = undefined;
2747
+ let tags = [];
2748
+ let isPprConfig = false;
2749
+ let isPagePprConfig = false;
2750
+ let hasStaticDynamicConfig = false;
2751
+ let combinedTags = [];
2752
+ let combinedRevalidate = undefined;
2753
+
2754
+ // 1. Evaluate ancestor layouts root-to-child FIRST so a parent layout perimeter guard
2755
+ // (`validateParams` returning false or `allowISG: false`) halts before child layouts/pages run.
2756
+ const activeLayoutsForRoute = getActiveLayoutChain(reqSegments, queryObj, srcFolder);
2757
+ if (activeLayoutsForRoute.length > 0) {
2758
+ await requestStorage.run(rootContext, async () => {
2759
+ for (let i = activeLayoutsForRoute.length - 1; i >= 0; i--) {
2760
+ const entry = activeLayoutsForRoute[i];
2761
+ const layoutConfig = await resolveLayoutFunctionsConfig(entry.layoutPath, entry.dParams);
1980
2762
 
1981
- if (layoutConfig.validateParams) {
1982
- try {
1983
- const isValid = await layoutConfig.validateParams(layoutParams);
1984
- if (!isValid) {
1985
- isPathBlocked = true;
1986
- }
1987
- } catch (e) {
1988
- console.error(`[Dinou] Error executing validateParams for layout ${layoutPath}:`, e);
2763
+ if (
2764
+ await isLayoutSegmentBlocked(
2765
+ entry.layoutPath,
2766
+ entry.dParams,
2767
+ layoutConfig,
2768
+ entry.cleanLayoutKey,
2769
+ reqPath,
2770
+ isDevelopment,
2771
+ Boolean(platformContext?.isSSG),
2772
+ )
2773
+ ) {
2774
+ isPathBlocked = true;
2775
+ allowISGValue = false;
2776
+ break;
1989
2777
  }
1990
- }
1991
2778
 
1992
- if (layoutConfig.isDynamic) {
1993
- dynamicState.value = true;
1994
- hasStaticDynamicConfig = true;
1995
- }
1996
-
1997
- if (layoutConfig.allowISG === false) {
1998
- allowISGValue = false;
1999
- let isPathAllowed = false;
2000
- if (layoutConfig.staticPathsSet) {
2001
- const sortedEntries = Object.entries(layoutParams || {})
2002
- .sort((a, b) => a[0].localeCompare(b[0]))
2003
- .map(([k, v]) => {
2004
- if (Array.isArray(v)) return [k, v.join(",")];
2005
- return [k, String(v)];
2006
- });
2007
- const serializedQuery = JSON.stringify(sortedEntries);
2008
- const singleVal = Object.values(layoutParams || {})[0];
2009
- const singleValStr = Array.isArray(singleVal) ? singleVal.join(",") : String(singleVal);
2010
- isPathAllowed = layoutConfig.staticPathsSet.has(serializedQuery) || layoutConfig.staticPathsSet.has(singleValStr);
2779
+ if (layoutConfig.isDynamic) {
2780
+ dynamicState.value = true;
2781
+ hasStaticDynamicConfig = true;
2011
2782
  }
2012
- if (!isPathAllowed) {
2013
- if (isDevelopment) {
2014
- isPathBlocked = true;
2783
+
2784
+ if (typeof layoutConfig.revalidate === "number" && layoutConfig.revalidate >= 0) {
2785
+ if (typeof combinedRevalidate === "number") {
2786
+ combinedRevalidate = Math.min(combinedRevalidate, layoutConfig.revalidate);
2015
2787
  } else {
2016
- const cleanReq = reqPath.replace(/^\//, "").replace(/\/$/, "");
2017
- const htmlPath = path.join(process.cwd(), ".dinou/dist2", cleanReq, "index.html");
2018
- if (!existsSync(htmlPath)) {
2019
- isPathBlocked = true;
2788
+ combinedRevalidate = layoutConfig.revalidate;
2789
+ }
2790
+ }
2791
+
2792
+ if (Array.isArray(layoutConfig.tags)) {
2793
+ for (const t of layoutConfig.tags) {
2794
+ if (!combinedTags.includes(t)) {
2795
+ combinedTags.push(t);
2020
2796
  }
2021
2797
  }
2022
2798
  }
2023
2799
  }
2800
+ });
2801
+ }
2024
2802
 
2025
- if (typeof layoutConfig.revalidate === "number" && layoutConfig.revalidate >= 0) {
2026
- if (typeof combinedRevalidate === "number") {
2027
- combinedRevalidate = Math.min(combinedRevalidate, layoutConfig.revalidate);
2028
- } else {
2029
- combinedRevalidate = layoutConfig.revalidate;
2030
- }
2803
+ // 2. Evaluate page_functions only when no ancestor layout blocked the request
2804
+ if (!isPathBlocked) {
2805
+ const pageCfg = await requestStorage.run(rootContext, () =>
2806
+ resolvePageFunctionsConfig(
2807
+ pagePath,
2808
+ reqSegments,
2809
+ queryObj,
2810
+ dynamicParams,
2811
+ reqPath,
2812
+ Boolean(platformContext?.isSSG),
2813
+ )
2814
+ );
2815
+ isPathBlocked = pageCfg.isPathBlocked;
2816
+ allowISGValue = pageCfg.allowISGValue;
2817
+ isDynamicConfig = pageCfg.isDynamicConfig;
2818
+ revalidate = pageCfg.revalidate;
2819
+ tags = pageCfg.tags;
2820
+ isPprConfig = pageCfg.ppr;
2821
+ isPagePprConfig = pageCfg.pagePpr;
2822
+
2823
+ if (isDynamicConfig) {
2824
+ dynamicState.value = true;
2825
+ hasStaticDynamicConfig = true;
2826
+ }
2827
+
2828
+ if (typeof revalidate === "number" && revalidate >= 0) {
2829
+ if (typeof combinedRevalidate === "number") {
2830
+ combinedRevalidate = Math.min(combinedRevalidate, revalidate);
2831
+ } else {
2832
+ combinedRevalidate = revalidate;
2031
2833
  }
2834
+ }
2032
2835
 
2033
- if (Array.isArray(layoutConfig.tags)) {
2034
- for (const t of layoutConfig.tags) {
2035
- if (!combinedTags.includes(t)) {
2036
- combinedTags.push(t);
2037
- }
2836
+ if (Array.isArray(tags)) {
2837
+ const merged = [...tags];
2838
+ for (const t of combinedTags) {
2839
+ if (!merged.includes(t)) {
2840
+ merged.push(t);
2038
2841
  }
2039
2842
  }
2843
+ combinedTags = merged;
2040
2844
  }
2041
2845
  }
2042
2846
 
@@ -2060,13 +2864,22 @@ async function handleRequest(request, platformContext = {}) {
2060
2864
  }
2061
2865
  }
2062
2866
 
2063
- // 2. If not in storageAdapter, check env.ASSETS for pre-rendered build static page
2867
+ // 2. If not in storageAdapter, check env.ASSETS or local .dinou/dist2 for pre-rendered build static page
2868
+ const checkDeleted = async (k) =>
2869
+ typeof storage.isKeyDeleted === "function"
2870
+ ? await storage.isKeyDeleted(k)
2871
+ : typeof storage.isDeleted === "function" && storage.isDeleted(k);
2064
2872
  const isRouteDeletedInStorage =
2065
- typeof storage.isDeleted === "function" &&
2066
- (storage.isDeleted(htmlKey) || storage.isDeleted(metaKey) || (cleanPath && storage.isDeleted(cleanPath)));
2873
+ (await checkDeleted(htmlKey)) ||
2874
+ (await checkDeleted(metaKey)) ||
2875
+ (cleanPath ? await checkDeleted(cleanPath) : false);
2067
2876
  if (!isDevelopment && !cachedItem && !isRouteDeletedInStorage && platformContext && platformContext.env && platformContext.env.ASSETS) {
2068
2877
  try {
2069
- const metaRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${metaKey}`, request.url)));
2878
+ const metaRes = await fetchCloudflareDist2Asset(
2879
+ platformContext.env.ASSETS,
2880
+ metaKey,
2881
+ request.url
2882
+ );
2070
2883
  if (metaRes && metaRes.status === 200) {
2071
2884
  const ct = metaRes.headers.get("content-type") || "";
2072
2885
  if (ct.includes("json") || !ct.includes("html")) {
@@ -2076,15 +2889,11 @@ async function handleRequest(request, platformContext = {}) {
2076
2889
  } catch (e) {}
2077
2890
 
2078
2891
  if (metadata && typeof metadata === "object" && metadata.generatedAt) {
2079
- const fetchPath = cleanPath ? `/${cleanPath}/` : "/";
2080
- let assetRes = await platformContext.env.ASSETS.fetch(new Request(new URL(fetchPath, request.url)));
2081
- if (!assetRes || assetRes.status !== 200) {
2082
- assetRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${htmlKey}`, request.url)));
2083
- }
2084
- if (!assetRes || assetRes.status !== 200) {
2085
- const altPath = cleanPath ? `/${cleanPath}` : "/index.html";
2086
- assetRes = await platformContext.env.ASSETS.fetch(new Request(new URL(altPath, request.url)));
2087
- }
2892
+ const assetRes = await fetchCloudflareDist2Asset(
2893
+ platformContext.env.ASSETS,
2894
+ htmlKey,
2895
+ request.url
2896
+ );
2088
2897
  if (assetRes && assetRes.status === 200) {
2089
2898
  const html = await assetRes.text();
2090
2899
  cachedItem = {
@@ -2095,7 +2904,11 @@ async function handleRequest(request, platformContext = {}) {
2095
2904
  await storage.set(metaKey, JSON.stringify(cachedItem.metadata));
2096
2905
  const layoutMetaKey = cleanPath ? `${cleanPath}/layout.metadata.json` : "layout.metadata.json";
2097
2906
  try {
2098
- const layoutMetaRes = await platformContext.env.ASSETS.fetch(new Request(new URL(`/${layoutMetaKey}`, request.url)));
2907
+ const layoutMetaRes = await fetchCloudflareDist2Asset(
2908
+ platformContext.env.ASSETS,
2909
+ layoutMetaKey,
2910
+ request.url
2911
+ );
2099
2912
  if (layoutMetaRes && layoutMetaRes.status === 200) {
2100
2913
  const layoutMetaText = await layoutMetaRes.text();
2101
2914
  await storage.set(layoutMetaKey, layoutMetaText);
@@ -2108,13 +2921,24 @@ async function handleRequest(request, platformContext = {}) {
2108
2921
  } catch (e) {}
2109
2922
  }
2110
2923
 
2924
+ if (!isDevelopment && !cachedItem && !isRouteDeletedInStorage) {
2925
+ cachedItem = await readDist2Fallback(storage, htmlKey);
2926
+ if (!cachedItem && isPprConfig) {
2927
+ const shellHtmlKey = cleanPath ? `${cleanPath}/shell.html` : "shell.html";
2928
+ cachedItem = await readDist2Fallback(storage, shellHtmlKey);
2929
+ }
2930
+ if (cachedItem) {
2931
+ const layoutMetaKey = cleanPath ? `${cleanPath}/layout.metadata.json` : "layout.metadata.json";
2932
+ await readDist2Fallback(storage, layoutMetaKey);
2933
+ }
2934
+ }
2935
+
2111
2936
  // 2b. If PPR route shell was invalidated (e.g. by revalidateTag on a static shell slot),
2112
2937
  // or is a dynamic-param ISG route being visited for the first time,
2113
2938
  // regenerate the static shell in an isolated SSG pass before resuming dynamic holes.
2114
2939
  const shellHtmlKeyForCheck = cleanPath ? `${cleanPath}/shell.html` : "shell.html";
2115
2940
  const isShellDeletedInStorage =
2116
- isRouteDeletedInStorage ||
2117
- (typeof storage.isDeleted === "function" && storage.isDeleted(shellHtmlKeyForCheck));
2941
+ isRouteDeletedInStorage || (await checkDeleted(shellHtmlKeyForCheck));
2118
2942
  const hasDynamicUrlParams = Boolean(dynamicParams && Object.keys(dynamicParams).length > 0);
2119
2943
  if (
2120
2944
  !isDevelopment &&
@@ -2164,6 +2988,7 @@ async function handleRequest(request, platformContext = {}) {
2164
2988
  request.url
2165
2989
  );
2166
2990
  entry.generatedAt = Number(lMeta?.generatedAt || 0);
2991
+ entry.layoutGeneratedAt = Number(lMeta?.layoutGeneratedAt || lMeta?.generatedAt || 0);
2167
2992
  entry.revalidate = lMeta?.revalidate;
2168
2993
  entry.slotTags = Array.isArray(lMeta?.slotTags) ? lMeta.slotTags : [];
2169
2994
  }
@@ -2172,21 +2997,33 @@ async function handleRequest(request, platformContext = {}) {
2172
2997
  const isLayoutTtlExpired =
2173
2998
  typeof entry.revalidate === "number" &&
2174
2999
  entry.revalidate >= 1 &&
2175
- entry.generatedAt > 0 &&
2176
- Date.now() > entry.generatedAt + entry.revalidate * 1000;
3000
+ entry.layoutGeneratedAt > 0 &&
3001
+ Date.now() > entry.layoutGeneratedAt + entry.revalidate * 1000;
2177
3002
  const isLayoutSlotTtlExpired =
2178
3003
  !isLayoutTtlExpired &&
2179
3004
  entry.slotTags.length > 0 &&
2180
3005
  (await hasExpiredSlots(entry.slotTags));
3006
+ const ancestors =
3007
+ i < activeLayoutChain.length - 1 ? activeLayoutChain.slice(i + 1) : [];
2181
3008
  const maxAncestorGen =
2182
- i < activeLayoutChain.length - 1
3009
+ ancestors.length > 0
3010
+ ? Math.max(0, ...ancestors.map((l) => l.generatedAt || 0))
3011
+ : 0;
3012
+ const maxAncestorOwnGen =
3013
+ ancestors.length > 0
2183
3014
  ? Math.max(
2184
3015
  0,
2185
- ...activeLayoutChain.slice(i + 1).map((l) => l.generatedAt || 0)
3016
+ ...ancestors.map((l) => l.layoutGeneratedAt || l.generatedAt || 0)
2186
3017
  )
2187
3018
  : 0;
2188
- const isAncestorNewer =
2189
- entry.generatedAt > 0 && maxAncestorGen > entry.generatedAt;
3019
+ const entryOwnGen = entry.layoutGeneratedAt || entry.generatedAt || 0;
3020
+ const isAncestorOwnNewer =
3021
+ entryOwnGen > 0 && maxAncestorOwnGen > entryOwnGen;
3022
+ const isAncestorSlotOnlyNewer =
3023
+ !isAncestorOwnNewer &&
3024
+ entry.generatedAt > 0 &&
3025
+ maxAncestorGen > entry.generatedAt;
3026
+ const isAncestorNewer = isAncestorOwnNewer || isAncestorSlotOnlyNewer;
2190
3027
  if (isLayoutSlotTtlExpired && !isLayoutTtlExpired && !isAncestorNewer) {
2191
3028
  const layoutSlotRevalKey = `layout-slot:${entry.layoutRoutePath}`;
2192
3029
  const layoutSlotRevalPromise = (async () => {
@@ -2206,7 +3043,11 @@ async function handleRequest(request, platformContext = {}) {
2206
3043
  }
2207
3044
  } else if (isLayoutTtlExpired || isAncestorNewer) {
2208
3045
  const { revalidateLayout } = await import("./cache-revalidate.js");
2209
- await revalidateLayout(entry.layoutRoutePath, {});
3046
+ await revalidateLayout(entry.layoutRoutePath, {
3047
+ onlyRefreshSlots:
3048
+ !isLayoutTtlExpired && !isAncestorOwnNewer && isAncestorSlotOnlyNewer,
3049
+ onlyIfExpired: isLayoutTtlExpired && !isAncestorNewer,
3050
+ });
2210
3051
  const refreshedMeta = await readMetaFromStorage(
2211
3052
  storage,
2212
3053
  entry.cleanLayoutKey
@@ -2221,6 +3062,11 @@ async function handleRequest(request, platformContext = {}) {
2221
3062
  if (refreshedMeta?.generatedAt) {
2222
3063
  entry.generatedAt = Number(refreshedMeta.generatedAt);
2223
3064
  }
3065
+ if (refreshedMeta?.layoutGeneratedAt || refreshedMeta?.generatedAt) {
3066
+ entry.layoutGeneratedAt = Number(
3067
+ refreshedMeta.layoutGeneratedAt || refreshedMeta.generatedAt
3068
+ );
3069
+ }
2224
3070
  }
2225
3071
  }
2226
3072
  const leafLayout = activeLayoutChain[0];
@@ -2262,7 +3108,11 @@ async function handleRequest(request, platformContext = {}) {
2262
3108
  }
2263
3109
  bootstrapScriptContent += `window.__DINOU_BUILD_ID__ = "${leafLayout.generatedAt}";\n`;
2264
3110
  const clientEntry = getAssetFromManifest("main.js");
2265
- const recomposeCtx = createRequestContext(simReq, bridge, platformContext);
3111
+ const recomposeSimReq = simReq
3112
+ ? { ...simReq, query: {}, cookies: {} }
3113
+ : { query: {}, cookies: {}, headers: {}, path: reqPath, method: "GET" };
3114
+ const recomposeCtx = createRequestContext(recomposeSimReq, bridge, platformContext);
3115
+ recomposeCtx._isStaticHtmlRender = true;
2266
3116
  copyCustomContextProperties(rootContext, recomposeCtx);
2267
3117
  let htmlStream;
2268
3118
  await requestStorage.run(recomposeCtx, async () => {
@@ -2286,6 +3136,7 @@ async function handleRequest(request, platformContext = {}) {
2286
3136
  content: recomposedHtml,
2287
3137
  metadata: updatedMeta,
2288
3138
  };
3139
+ await storage.set(metaKey, JSON.stringify(updatedMeta));
2289
3140
  await storage.set(htmlKey, recomposedHtml, updatedMeta);
2290
3141
  if (isPprRoute) {
2291
3142
  const shellHtmlKey = cleanPath ? `${cleanPath}/shell.html` : "shell.html";
@@ -2294,7 +3145,6 @@ async function handleRequest(request, platformContext = {}) {
2294
3145
  if (cleanPath) {
2295
3146
  await storage.set(cleanPath, recomposedHtml, updatedMeta);
2296
3147
  }
2297
- await storage.set(metaKey, JSON.stringify(updatedMeta));
2298
3148
  }
2299
3149
  }
2300
3150
  }
@@ -2328,7 +3178,7 @@ async function handleRequest(request, platformContext = {}) {
2328
3178
  const metadata = cachedItem.metadata || {};
2329
3179
  const { generatedAt } = metadata;
2330
3180
  const pageOwnRevalidate =
2331
- metadata.pageRevalidate !== undefined
3181
+ metadata.pageRevalidate !== undefined && metadata.pageRevalidate !== null
2332
3182
  ? metadata.pageRevalidate
2333
3183
  : revalidate;
2334
3184
  const pageOwnGeneratedAt = metadata.pageGeneratedAt || generatedAt;
@@ -2337,20 +3187,45 @@ async function handleRequest(request, platformContext = {}) {
2337
3187
  pageOwnRevalidate >= 1 &&
2338
3188
  Date.now() > (pageOwnGeneratedAt || 0) + pageOwnRevalidate * 1000;
2339
3189
 
2340
- if (isExpired) {
3190
+ if (isExpired && !regenerating.has(reqPath)) {
2341
3191
  // Trigger background revalidation on Edge!
3192
+ regenerating.add(reqPath);
2342
3193
  const revalPromise = (async () => {
2343
- if (regenerating.has(reqPath)) return;
2344
- regenerating.add(reqPath);
2345
3194
  try {
2346
3195
  console.log(`[Edge ISR] Starting regeneration for ${reqPath}...`);
2347
3196
  if (metadata.ppr || isPprConfig || (platformContext && platformContext.renderHtmlStream)) {
2348
3197
  const { revalidatePage } = await import("./cache-revalidate.js");
2349
- await revalidatePage(reqPath);
3198
+ await revalidatePage(reqPath, { onlyIfExpired: true });
2350
3199
  return;
2351
3200
  }
3201
+ const latestMeta = await readMetaFromStorage(
3202
+ storage,
3203
+ metaKey,
3204
+ cleanPath ? `${cleanPath}/page.rsc` : "page.rsc",
3205
+ platformContext,
3206
+ request.url
3207
+ );
3208
+ if (latestMeta) {
3209
+ const latestReval =
3210
+ latestMeta.pageRevalidate !== undefined && latestMeta.pageRevalidate !== null
3211
+ ? latestMeta.pageRevalidate
3212
+ : pageOwnRevalidate;
3213
+ const latestPageGen = Number(latestMeta.pageGeneratedAt || latestMeta.generatedAt || 0);
3214
+ if (
3215
+ typeof latestReval === "number" &&
3216
+ latestReval >= 1 &&
3217
+ latestPageGen > 0 &&
3218
+ Date.now() <= latestPageGen + latestReval * 1000
3219
+ ) {
3220
+ return;
3221
+ }
3222
+ }
2352
3223
  const revalBridge = new WebResponseBridge();
2353
- const context = createRequestContext(simReq, revalBridge, platformContext);
3224
+ const revalSimReq = simReq
3225
+ ? { ...simReq, query: {}, cookies: {} }
3226
+ : { query: {}, cookies: {}, headers: {}, path: reqPath, method: "GET" };
3227
+ const context = createRequestContext(revalSimReq, revalBridge, platformContext);
3228
+ context._isStaticHtmlRender = true;
2354
3229
  const isNotFound = {};
2355
3230
  let jsx;
2356
3231
  await requestStorage.run(context, async () => {
@@ -2379,12 +3254,23 @@ async function handleRequest(request, platformContext = {}) {
2379
3254
  pageRscText = rscText;
2380
3255
  }
2381
3256
 
2382
- await storage.set(pageRscKey, pageRscText);
2383
- await storage.set(rscKey, rscText);
3257
+ const oldRscKey = cleanPath ? `${cleanPath}/page._old.rsc` : "page._old.rsc";
3258
+ const oldHtmlKey = cleanPath ? `${cleanPath}/index._old.html` : "index._old.html";
3259
+ try {
3260
+ const prevPageRsc = await storage.get(pageRscKey);
3261
+ if (prevPageRsc && prevPageRsc.content) {
3262
+ await storage.set(oldRscKey, prevPageRsc.content);
3263
+ }
3264
+ if (cachedItem && cachedItem.content) {
3265
+ await storage.set(oldHtmlKey, cachedItem.content);
3266
+ }
3267
+ } catch (e) {}
3268
+
3269
+ const nextGenAt = Math.max(Date.now(), Number(metadata.generatedAt || 0) + 1);
2384
3270
  const updatedMeta = {
2385
3271
  status: 200,
2386
3272
  revalidate: metadata.revalidate || 3,
2387
- generatedAt: Date.now(),
3273
+ generatedAt: nextGenAt,
2388
3274
  ...(Array.isArray(metadata.tags) ? { tags: metadata.tags } : {}),
2389
3275
  ...(context._slotTags && context._slotTags.size > 0
2390
3276
  ? { slotTags: Array.from(context._slotTags) }
@@ -2392,13 +3278,17 @@ async function handleRequest(request, platformContext = {}) {
2392
3278
  ? { slotTags: metadata.slotTags }
2393
3279
  : {}),
2394
3280
  };
2395
- await storage.set(htmlKey, htmlText, updatedMeta);
2396
3281
  await storage.set(metaKey, JSON.stringify(updatedMeta));
3282
+ await storage.set(pageRscKey, pageRscText);
3283
+ await storage.set(rscKey, rscText);
3284
+ await storage.set(htmlKey, htmlText, updatedMeta);
2397
3285
  console.log(`✅ [Edge ISR] Successfully regenerated ${reqPath}`);
2398
3286
  } else {
2399
3287
  const rscText = await new Response(rscStream).text();
2400
3288
  const pageRscKey = cleanPath ? `${cleanPath}/page.rsc` : "page.rsc";
2401
3289
  const rscKey = cleanPath ? `${cleanPath}/rsc.rsc` : "rsc.rsc";
3290
+ const oldRscKey = cleanPath ? `${cleanPath}/page._old.rsc` : "page._old.rsc";
3291
+ const oldHtmlKey = cleanPath ? `${cleanPath}/index._old.html` : "index._old.html";
2402
3292
 
2403
3293
  let pageRscText = "";
2404
3294
  try {
@@ -2409,25 +3299,33 @@ async function handleRequest(request, platformContext = {}) {
2409
3299
  pageRscText = rscText;
2410
3300
  }
2411
3301
 
2412
- await storage.set(pageRscKey, pageRscText);
2413
- await storage.set(rscKey, rscText);
3302
+ try {
3303
+ const prevPageRsc = await storage.get(pageRscKey);
3304
+ if (prevPageRsc && prevPageRsc.content) {
3305
+ await storage.set(oldRscKey, prevPageRsc.content);
3306
+ }
3307
+ if (cachedItem && cachedItem.content) {
3308
+ await storage.set(oldHtmlKey, cachedItem.content);
3309
+ }
3310
+ } catch (e) {}
2414
3311
 
3312
+ const nextGenAt = Math.max(Date.now(), Number(metadata.generatedAt || 0) + 1);
2415
3313
  // Update HTML with new timestamp
2416
3314
  let html = cachedItem.content || "";
2417
- const newTimestamp = new Date().toISOString();
3315
+ const newTimestamp = new Date(nextGenAt).toISOString();
2418
3316
  html = html.replace(
2419
3317
  /<div data-testid="timestamp">[^<]*<\/div>/g,
2420
3318
  `<div data-testid="timestamp">${newTimestamp}</div>`
2421
3319
  );
2422
3320
  html = html.replace(
2423
- /window\.__DINOU_BUILD_ID__="[^"]*"/g,
2424
- `window.__DINOU_BUILD_ID__="${Date.now()}"`
3321
+ /window\.__DINOU_BUILD_ID__\s*=\s*"[^"]*"/g,
3322
+ `window.__DINOU_BUILD_ID__ = "${nextGenAt}"`
2425
3323
  );
2426
3324
 
2427
3325
  const updatedMeta = {
2428
3326
  status: 200,
2429
3327
  revalidate: metadata.revalidate || 3,
2430
- generatedAt: Date.now(),
3328
+ generatedAt: nextGenAt,
2431
3329
  ...(Array.isArray(metadata.tags) ? { tags: metadata.tags } : {}),
2432
3330
  ...(context._slotTags && context._slotTags.size > 0
2433
3331
  ? { slotTags: Array.from(context._slotTags) }
@@ -2435,8 +3333,10 @@ async function handleRequest(request, platformContext = {}) {
2435
3333
  ? { slotTags: metadata.slotTags }
2436
3334
  : {}),
2437
3335
  };
2438
- await storage.set(htmlKey, html, updatedMeta);
2439
3336
  await storage.set(metaKey, JSON.stringify(updatedMeta));
3337
+ await storage.set(pageRscKey, pageRscText);
3338
+ await storage.set(rscKey, rscText);
3339
+ await storage.set(htmlKey, html, updatedMeta);
2440
3340
  console.log(`✅ [Edge ISR] Successfully regenerated ${reqPath} with timestamp ${newTimestamp}`);
2441
3341
  }
2442
3342
  });
@@ -2470,8 +3370,14 @@ async function handleRequest(request, platformContext = {}) {
2470
3370
  }
2471
3371
 
2472
3372
  bridge.setHeader("Content-Type", "text/html; charset=utf-8");
2473
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2474
- bridge.status(metadata.status || 200);
3373
+ if (!bridge.headers.has("Cache-Control")) {
3374
+ if (!bridge.headers.has("Cache-Control")) {
3375
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
3376
+ }
3377
+ }
3378
+ if (!bridge._explicitStatusSet) {
3379
+ bridge.status(metadata.status || 200);
3380
+ }
2475
3381
  let content = cachedItem.content;
2476
3382
  if (typeof content === "string" && !content.includes("window.__DINOU_LAYOUTS__")) {
2477
3383
  const knownLayouts = getDiscoveredLayouts();
@@ -2486,11 +3392,16 @@ async function handleRequest(request, platformContext = {}) {
2486
3392
  return new Response("Not Found", { status: 404 });
2487
3393
  }
2488
3394
 
2489
- // Concurrency Stampede Protection (Production only, never share dynamic streams in dev or requests with user cookies)
3395
+ // Concurrency Stampede Protection (Production only, never share dynamic streams in dev or requests with user/plugin cookies)
3396
+ const preRenderPluginCookiesCount = bridge.cookies.length;
2490
3397
  const hasCookies = simReq.cookies && Object.keys(simReq.cookies).length > 0;
3398
+ const hasPluginMutation =
3399
+ preRenderPluginCookiesCount > 0 ||
3400
+ (bridge._explicitStatusSet && bridge.statusCode !== 200);
2491
3401
  const canUseInFlight =
2492
3402
  !isDevelopment &&
2493
3403
  !hasCookies &&
3404
+ !hasPluginMutation &&
2494
3405
  !isDynamicConfig &&
2495
3406
  allowISGValue !== false &&
2496
3407
  Object.keys(queryObj).length === 0;
@@ -2514,19 +3425,81 @@ async function handleRequest(request, platformContext = {}) {
2514
3425
  : null;
2515
3426
  let jsx;
2516
3427
  let rscText = "";
3428
+ let precomputedPageRscText = "";
3429
+ let precomputedLayoutRscText = "";
2517
3430
 
2518
3431
  let pprHoles = [];
2519
3432
  try {
2520
3433
  if (!isError) {
2521
3434
  if (platformContext?.isSSG && isPprConfig) {
2522
- await requestStorage.run(context, async () => {
2523
- await runWithPprContext({ isPpr: true }, async () => {
2524
- jsx = await getJSX(reqPath, queryObj, isNotFound, isDevelopment, !pagePath);
2525
- resetPprHoles();
2526
- jsx = await asyncRenderJSXToClientJSX(jsx);
2527
- pprHoles = getRegisteredHoles();
3435
+ const activeChain = getActiveLayoutChain(reqSegments, queryObj, srcFolder);
3436
+ let leafLayoutRsc = "";
3437
+ let leafMeta = null;
3438
+ if (activeChain.length > 0) {
3439
+ const leafLayout = activeChain[0];
3440
+ const leafRscKey = leafLayout.cleanLayoutKey
3441
+ ? `${leafLayout.cleanLayoutKey}/layout.rsc`
3442
+ : "layout.rsc";
3443
+ const leafMetaKey = leafLayout.cleanLayoutKey
3444
+ ? `${leafLayout.cleanLayoutKey}/layout.metadata.json`
3445
+ : "layout.metadata.json";
3446
+ leafMeta = await readMetaFromStorage(
3447
+ storage,
3448
+ leafMetaKey,
3449
+ leafRscKey,
3450
+ platformContext,
3451
+ request.url,
3452
+ );
3453
+ if (!leafMeta?.dynamic) {
3454
+ leafLayoutRsc = await readRscFromStorage(
3455
+ storage,
3456
+ leafRscKey,
3457
+ platformContext,
3458
+ request.url,
3459
+ );
3460
+ }
3461
+ }
3462
+
3463
+ if (activeChain.length > 0 && leafLayoutRsc) {
3464
+ precomputedLayoutRscText = leafLayoutRsc;
3465
+ const leafSuspenseCount = Number(leafMeta?.suspenseCount || 0);
3466
+ const leafHoles = Array.isArray(leafMeta?.holes) ? leafMeta.holes : [];
3467
+ await requestStorage.run(context, async () => {
3468
+ await runWithPprContext({ isPpr: Boolean(isPagePprConfig) }, async () => {
3469
+ const rawPageJsx = await getJSX(
3470
+ reqPath,
3471
+ queryObj,
3472
+ isNotFound,
3473
+ isDevelopment,
3474
+ !pagePath,
3475
+ { segment: "page" },
3476
+ );
3477
+ resetPprHoles(leafSuspenseCount);
3478
+ const renderedPageJsx = await runInPageSegment(() =>
3479
+ asyncRenderJSXToClientJSX(rawPageJsx),
3480
+ );
3481
+ context._resolvedPageClientJsx = renderedPageJsx;
3482
+ context._hasResolvedSegments = true;
3483
+ jsx = renderedPageJsx;
3484
+ const pageHoles = isPagePprConfig ? getRegisteredHoles() : [];
3485
+ pprHoles = Array.from(new Set([...leafHoles, ...pageHoles]));
3486
+ });
2528
3487
  });
2529
- });
3488
+ } else {
3489
+ await requestStorage.run(context, async () => {
3490
+ await runWithPprContext({ isPpr: true }, async () => {
3491
+ jsx = await getJSX(reqPath, queryObj, isNotFound, isDevelopment, !pagePath);
3492
+ resetPprHoles();
3493
+ jsx = await asyncRenderJSXToClientJSX(jsx);
3494
+ pprHoles = getRegisteredHoles();
3495
+ if (activeChain.length === 0) {
3496
+ context._resolvedPageClientJsx = jsx;
3497
+ context._resolvedLayoutClientJsx = null;
3498
+ context._hasResolvedSegments = true;
3499
+ }
3500
+ });
3501
+ });
3502
+ }
2530
3503
  } else {
2531
3504
  await requestStorage.run(context, async () => {
2532
3505
  jsx = await getJSX(reqPath, queryObj, isNotFound, isDevelopment, !pagePath);
@@ -2568,17 +3541,24 @@ async function handleRequest(request, platformContext = {}) {
2568
3541
 
2569
3542
  const nowGen = Date.now();
2570
3543
  const genMeta = {
2571
- status: isError ? 500 : isNotFound.value ? 404 : 200,
3544
+ status: isError
3545
+ ? 500
3546
+ : isNotFound.value
3547
+ ? 404
3548
+ : bridge._explicitStatusSet
3549
+ ? bridge.statusCode
3550
+ : 200,
2572
3551
  generatedAt: nowGen,
2573
3552
  pageGeneratedAt: nowGen,
2574
3553
  revalidate: combinedRevalidate,
2575
3554
  pageRevalidate: revalidate !== undefined ? revalidate : null,
2576
3555
  tags: tags || [],
2577
3556
  ppr: Boolean(isPprConfig),
3557
+ pagePpr: Boolean(isPagePprConfig),
2578
3558
  holes: pprHoles,
2579
3559
  effects: {
2580
3560
  redirect: bridge.headers.get("Location") || null,
2581
- cookies: [...bridge.cookies],
3561
+ cookies: bridge.cookies.slice(preRenderPluginCookiesCount),
2582
3562
  },
2583
3563
  };
2584
3564
 
@@ -2622,7 +3602,21 @@ async function handleRequest(request, platformContext = {}) {
2622
3602
  const rscStream = requestStorage.run(context, () => renderRSCStream(jsx, clientManifest, { runtime: "edge" }));
2623
3603
 
2624
3604
  if (platformContext && platformContext.renderHtmlStream) {
2625
- const [streamForSsr, streamForCache] = rscStream.tee();
3605
+ const canUseInlineRsc = Boolean(
3606
+ !isError &&
3607
+ !platformContext?.isSSG &&
3608
+ !shouldCacheISG &&
3609
+ context._hasResolvedSegments &&
3610
+ context._resolvedPageClientJsx !== undefined
3611
+ );
3612
+
3613
+ let streamForSsr = rscStream;
3614
+ let streamForCache = null;
3615
+ if (shouldCacheISG) {
3616
+ const teed = rscStream.tee();
3617
+ streamForSsr = teed[0];
3618
+ streamForCache = teed[1];
3619
+ }
2626
3620
 
2627
3621
  let bootstrapScriptContent = "";
2628
3622
  const knownLayouts = getDiscoveredLayouts();
@@ -2639,6 +3633,12 @@ async function handleRequest(request, platformContext = {}) {
2639
3633
  }
2640
3634
  }
2641
3635
  }
3636
+ if (canUseInlineRsc) {
3637
+ bootstrapScriptContent +=
3638
+ "window.__DINOU_INLINE_RSC__ = true;\n" +
3639
+ "window.__DINOU_RSC_P__ = window.__DINOU_RSC_P__ || [];\n" +
3640
+ "window.__DINOU_RSC_L__ = window.__DINOU_RSC_L__ || [];\n";
3641
+ }
2642
3642
  if (isDevelopment) {
2643
3643
  const isStrictMode = dinouConfig?.reactStrictMode !== false;
2644
3644
  bootstrapScriptContent += `window.__DINOU_STRICT_MODE__ = ${isStrictMode ? "true" : "false"};\n`;
@@ -2683,20 +3683,113 @@ async function handleRequest(request, platformContext = {}) {
2683
3683
  bootstrapScriptContent += `window.HMR_WEBSOCKET_URL="ws://localhost:${hmrPort}";\n`;
2684
3684
  }
2685
3685
 
3686
+ if (
3687
+ precomputedLayoutRscText &&
3688
+ !precomputedPageRscText &&
3689
+ !isError &&
3690
+ context._resolvedPageClientJsx !== undefined
3691
+ ) {
3692
+ try {
3693
+ const pageStream = requestStorage.run(context, () =>
3694
+ renderRSCStream(context._resolvedPageClientJsx, clientManifest, {
3695
+ runtime: "edge",
3696
+ })
3697
+ );
3698
+ precomputedPageRscText = await new Response(pageStream).text();
3699
+ } catch (e) {}
3700
+ } else if (
3701
+ shouldCacheISG &&
3702
+ !isPprConfig &&
3703
+ !isError &&
3704
+ context._hasResolvedSegments &&
3705
+ context._resolvedPageClientJsx !== undefined
3706
+ ) {
3707
+ try {
3708
+ const pageStream = requestStorage.run(context, () =>
3709
+ renderRSCStream(context._resolvedPageClientJsx, clientManifest, {
3710
+ runtime: "edge",
3711
+ })
3712
+ );
3713
+ precomputedPageRscText = await new Response(pageStream).text();
3714
+ } catch (e) {}
3715
+ if (
3716
+ precomputedPageRscText &&
3717
+ context._resolvedLayoutClientJsx !== null &&
3718
+ context._resolvedLayoutClientJsx !== undefined
3719
+ ) {
3720
+ try {
3721
+ const activeChain = getActiveLayoutChain(reqSegments, queryObj, srcFolder);
3722
+ if (activeChain.length > 0) {
3723
+ const leafLayout = activeChain[0];
3724
+ const leafRscKey = leafLayout.cleanLayoutKey
3725
+ ? `${leafLayout.cleanLayoutKey}/layout.rsc`
3726
+ : "layout.rsc";
3727
+ const leafMetaKey = leafLayout.cleanLayoutKey
3728
+ ? `${leafLayout.cleanLayoutKey}/layout.metadata.json`
3729
+ : "layout.metadata.json";
3730
+ const lMeta = await readMetaFromStorage(
3731
+ storage,
3732
+ leafMetaKey,
3733
+ leafRscKey,
3734
+ platformContext,
3735
+ request.url
3736
+ );
3737
+ const layoutHasPprHoles =
3738
+ Boolean(lMeta?.ppr) ||
3739
+ (Array.isArray(lMeta?.holes) && lMeta.holes.length > 0);
3740
+ if (!layoutHasPprHoles) {
3741
+ precomputedLayoutRscText = await readRscFromStorage(
3742
+ storage,
3743
+ leafRscKey,
3744
+ platformContext,
3745
+ request.url
3746
+ );
3747
+ }
3748
+ }
3749
+ } catch (e) {}
3750
+ }
3751
+ }
3752
+
2686
3753
  let htmlStream;
3754
+ context._isStaticHtmlRender = Boolean(shouldCacheISG);
2687
3755
  try {
2688
3756
  await requestStorage.run(context, async () => {
2689
- htmlStream = await platformContext.renderHtmlStream(streamForSsr, {
2690
- bootstrapModules,
2691
- bootstrapScriptContent,
2692
- onError(err) {
2693
- if (!platformContext?.isSSG || process.env.DINOU_DEBUG) {
2694
- console.error("[Edge Native SSR] Stream error:", err);
3757
+ if (precomputedLayoutRscText && precomputedPageRscText) {
3758
+ const encoder = new TextEncoder();
3759
+ const toStream = (str) =>
3760
+ new ReadableStream({
3761
+ start(controller) {
3762
+ controller.enqueue(encoder.encode(str));
3763
+ controller.close();
3764
+ },
3765
+ });
3766
+ htmlStream = await platformContext.renderHtmlStream(
3767
+ toStream(precomputedLayoutRscText),
3768
+ {
3769
+ pageRscStream: toStream(precomputedPageRscText),
3770
+ bootstrapModules,
3771
+ bootstrapScriptContent,
3772
+ onError(err) {
3773
+ if (!platformContext?.isSSG || process.env.DINOU_DEBUG) {
3774
+ console.error("[Edge Native SSR] Stream error:", err);
3775
+ }
3776
+ },
2695
3777
  }
2696
- },
2697
- });
3778
+ );
3779
+ } else {
3780
+ htmlStream = await platformContext.renderHtmlStream(streamForSsr, {
3781
+ bootstrapModules,
3782
+ bootstrapScriptContent,
3783
+ onError(err) {
3784
+ if (!platformContext?.isSSG || process.env.DINOU_DEBUG) {
3785
+ console.error("[Edge Native SSR] Stream error:", err);
3786
+ }
3787
+ },
3788
+ });
3789
+ }
2698
3790
  });
2699
3791
  } catch (ssrErr) {
3792
+ context._isStaticHtmlRender = false;
2700
3793
  if (!platformContext?.isSSG || process.env.DINOU_DEBUG) {
2701
3794
  console.error("[Edge Native SSR] SSR render threw error, falling back to getErrorJSX:", ssrErr.message);
2702
3795
  }
@@ -2742,7 +3835,9 @@ async function handleRequest(request, platformContext = {}) {
2742
3835
  };
2743
3836
  }
2744
3837
 
2745
- const errorRscStream = renderRSCStream(errorJsx, clientManifest, { runtime: "edge" });
3838
+ const errorRscStream = requestStorage.run(context, () =>
3839
+ renderRSCStream(errorJsx, clientManifest, { runtime: "edge" })
3840
+ );
2746
3841
  const errorClientEntry = getAssetFromManifest("main.js");
2747
3842
  const errorBootstrapModules = isDevelopment
2748
3843
  ? [
@@ -2827,14 +3922,18 @@ async function handleRequest(request, platformContext = {}) {
2827
3922
  let fullHtml = "";
2828
3923
  let rscPayload = "";
2829
3924
  try {
2830
- const [rsc, html] = await Promise.all([
2831
- new Response(streamForCache).text(),
2832
- new Response(htmlStream).text(),
2833
- ]);
3925
+ const [rsc, html] = await requestStorage.run(context, () =>
3926
+ Promise.all([
3927
+ new Response(streamForCache).text(),
3928
+ new Response(htmlStream).text(),
3929
+ ])
3930
+ );
2834
3931
  rscPayload = rsc;
2835
3932
  fullHtml = html;
2836
3933
  } catch (drainErr) {
2837
3934
  console.error("[Edge ISG] Error reading streams:", drainErr);
3935
+ } finally {
3936
+ context._isStaticHtmlRender = false;
2838
3937
  }
2839
3938
 
2840
3939
  if (fullHtml) {
@@ -2857,14 +3956,16 @@ async function handleRequest(request, platformContext = {}) {
2857
3956
  }
2858
3957
  try {
2859
3958
  const pageRscKey = cleanPath ? `${cleanPath}/page.rsc` : "page.rsc";
2860
- let pageRscText = "";
3959
+ let pageRscText = precomputedPageRscText || "";
2861
3960
  if (context._resolvedPageClientJsx) {
2862
- try {
2863
- const pageStream = requestStorage.run(context, () =>
2864
- renderRSCStream(context._resolvedPageClientJsx, clientManifest, { runtime: "edge" })
2865
- );
2866
- pageRscText = await new Response(pageStream).text();
2867
- } catch (e) {}
3961
+ if (!pageRscText) {
3962
+ try {
3963
+ const pageStream = requestStorage.run(context, () =>
3964
+ renderRSCStream(context._resolvedPageClientJsx, clientManifest, { runtime: "edge" })
3965
+ );
3966
+ pageRscText = await new Response(pageStream).text();
3967
+ } catch (e) {}
3968
+ }
2868
3969
  if (genMeta.ppr || (Array.isArray(genMeta.slotTags) && genMeta.slotTags.length > 0)) {
2869
3970
  try {
2870
3971
  const shellPageKey = cleanPath ? `${cleanPath}/shell.page.json` : "shell.page.json";
@@ -2897,6 +3998,30 @@ async function handleRequest(request, platformContext = {}) {
2897
3998
  await storage.set(shellHtmlKey, fullHtml, genMeta);
2898
3999
  await storage.set(shellRscKey, pageRscText || rscPayload);
2899
4000
  }
4001
+ if (!platformContext?.isSSG && !genMeta.ppr && !isError && context._hasResolvedSegments && pageRscText) {
4002
+ let layoutRscText = precomputedLayoutRscText || "";
4003
+ const hasLayoutSeg =
4004
+ context._resolvedLayoutClientJsx !== null &&
4005
+ context._resolvedLayoutClientJsx !== undefined;
4006
+ if (hasLayoutSeg && !layoutRscText) {
4007
+ try {
4008
+ const layoutStream = requestStorage.run(context, () =>
4009
+ renderRSCStream(context._resolvedLayoutClientJsx, clientManifest, {
4010
+ runtime: "edge",
4011
+ })
4012
+ );
4013
+ layoutRscText = await new Response(layoutStream).text();
4014
+ } catch (e) {}
4015
+ }
4016
+ if (!hasLayoutSeg || layoutRscText) {
4017
+ fullHtml = injectInlineRscIntoHtmlString(
4018
+ fullHtml,
4019
+ layoutRscText,
4020
+ pageRscText,
4021
+ hasLayoutSeg
4022
+ );
4023
+ }
4024
+ }
2900
4025
  if (!platformContext?.isSSG || process.env.DINOU_DEBUG) {
2901
4026
  console.log(`✅ [Edge ISG] Successfully cached ${reqPath} to KV`);
2902
4027
  }
@@ -2911,6 +4036,44 @@ async function handleRequest(request, platformContext = {}) {
2911
4036
  "window.__DINOU_USE_STATIC__ = true;",
2912
4037
  "window.__DINOU_USE_STATIC__ = false;"
2913
4038
  );
4039
+ if (
4040
+ !platformContext?.isSSG &&
4041
+ !isError &&
4042
+ context._hasResolvedSegments &&
4043
+ context._resolvedPageClientJsx !== undefined
4044
+ ) {
4045
+ try {
4046
+ const hasLayoutSeg =
4047
+ context._resolvedLayoutClientJsx !== null &&
4048
+ context._resolvedLayoutClientJsx !== undefined;
4049
+ const pageStream = requestStorage.run(context, () =>
4050
+ renderRSCStream(context._resolvedPageClientJsx, clientManifest, {
4051
+ runtime: "edge",
4052
+ })
4053
+ );
4054
+ const layoutPromise = hasLayoutSeg
4055
+ ? new Response(
4056
+ requestStorage.run(context, () =>
4057
+ renderRSCStream(context._resolvedLayoutClientJsx, clientManifest, {
4058
+ runtime: "edge",
4059
+ })
4060
+ )
4061
+ ).text()
4062
+ : Promise.resolve("");
4063
+ const [layoutRscText, pageRscText] = await Promise.all([
4064
+ layoutPromise,
4065
+ new Response(pageStream).text(),
4066
+ ]);
4067
+ if (pageRscText && (!hasLayoutSeg || layoutRscText)) {
4068
+ fullHtml = injectInlineRscIntoHtmlString(
4069
+ fullHtml,
4070
+ layoutRscText,
4071
+ pageRscText,
4072
+ hasLayoutSeg
4073
+ );
4074
+ }
4075
+ } catch (e) {}
4076
+ }
2914
4077
  if (!platformContext?.isSSG || process.env.DINOU_DEBUG) {
2915
4078
  console.log(`ℹ️ [Edge ISG] Dynamic bailout detected during render for ${reqPath}, skipping KV cache`);
2916
4079
  }
@@ -2930,6 +4093,10 @@ async function handleRequest(request, platformContext = {}) {
2930
4093
  inFlightGenerations.delete(inFlightKey);
2931
4094
  }
2932
4095
 
4096
+ if (canUseInlineRsc && !isError && htmlStream) {
4097
+ htmlStream = createInlineRscHtmlStream(htmlStream, context, clientManifest);
4098
+ }
4099
+
2933
4100
  return {
2934
4101
  type: "stream",
2935
4102
  stream: htmlStream,
@@ -2982,8 +4149,18 @@ async function handleRequest(request, platformContext = {}) {
2982
4149
  }
2983
4150
  }
2984
4151
  bridge.setHeader("Content-Type", "text/html; charset=utf-8");
2985
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
2986
- bridge.status(result.status || 200);
4152
+ if (!bridge.headers.has("Cache-Control")) {
4153
+ if (!bridge.headers.has("Cache-Control")) {
4154
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
4155
+ }
4156
+ }
4157
+ if (
4158
+ !bridge._explicitStatusSet ||
4159
+ result.status === 404 ||
4160
+ result.status === 500
4161
+ ) {
4162
+ bridge.status(result.status || 200);
4163
+ }
2987
4164
 
2988
4165
  if (result.type === "stream") {
2989
4166
  bridge.setEdgeStream(result.stream);
@@ -3011,7 +4188,9 @@ async function handleRequest(request, platformContext = {}) {
3011
4188
 
3012
4189
  if (existsSync(fileToRead) && (!dynamicState.value || isPprConfig)) {
3013
4190
  bridge.setHeader("Content-Type", "text/html; charset=utf-8");
3014
- bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
4191
+ if (!bridge.headers.has("Cache-Control")) {
4192
+ bridge.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
4193
+ }
3015
4194
  let status = getStatus(reqPath);
3016
4195
  try {
3017
4196
  let htmlContent = readFileSync(fileToRead, "utf8");
@@ -3043,7 +4222,9 @@ async function handleRequest(request, platformContext = {}) {
3043
4222
  }
3044
4223
  } catch (e) {}
3045
4224
 
3046
- bridge.status(status || 200);
4225
+ if (!bridge._explicitStatusSet) {
4226
+ bridge.status(status || 200);
4227
+ }
3047
4228
 
3048
4229
  const knownLayouts = getDiscoveredLayouts();
3049
4230
  let scripts = `<script>window.__DINOU_USE_STATIC__=true;window.__DINOU_LAYOUTS__=${JSON.stringify(knownLayouts)};</script>`;