@elurjs/kit 2.4.10 → 2.5.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 (188) hide show
  1. package/CHANGELOG.md +313 -0
  2. package/README.md +248 -15
  3. package/dist/lib/action/index.cjs +1 -1
  4. package/dist/lib/action/index.js +1 -1
  5. package/dist/lib/{action-DZHihU3Z.cjs → action-BiE4tEty.cjs} +2 -2
  6. package/dist/lib/{action-DZHihU3Z.cjs.map → action-BiE4tEty.cjs.map} +1 -1
  7. package/dist/lib/{action-BB6N5yD-.js → action-CXVk8rWt.js} +3 -3
  8. package/dist/lib/{action-BB6N5yD-.js.map → action-CXVk8rWt.js.map} +1 -1
  9. package/dist/lib/adapter-DNsjXvq5.js +160 -0
  10. package/dist/lib/adapter-DNsjXvq5.js.map +1 -0
  11. package/dist/lib/adapter-Dz2hzR36.cjs +3 -0
  12. package/dist/lib/adapter-Dz2hzR36.cjs.map +1 -0
  13. package/dist/lib/adapters/bun.cjs +2 -2
  14. package/dist/lib/adapters/bun.cjs.map +1 -1
  15. package/dist/lib/adapters/bun.js +17 -9
  16. package/dist/lib/adapters/bun.js.map +1 -1
  17. package/dist/lib/adapters/index.d.cts +34 -0
  18. package/dist/lib/adapters/index.d.ts +34 -0
  19. package/dist/lib/adapters/netlify.cjs +1 -1
  20. package/dist/lib/adapters/netlify.js +7 -7
  21. package/dist/lib/adapters/node.cjs +5 -5
  22. package/dist/lib/adapters/node.cjs.map +1 -1
  23. package/dist/lib/adapters/node.js +20 -12
  24. package/dist/lib/adapters/node.js.map +1 -1
  25. package/dist/lib/adapters/vercel.cjs +1 -1
  26. package/dist/lib/adapters/vercel.js +8 -8
  27. package/dist/lib/build/build.d.cts +40 -0
  28. package/dist/lib/build/build.d.ts +40 -0
  29. package/dist/lib/build/document-shell.d.cts +47 -1
  30. package/dist/lib/build/document-shell.d.ts +47 -1
  31. package/dist/lib/build/vite-build.d.cts +25 -2
  32. package/dist/lib/build/vite-build.d.ts +25 -2
  33. package/dist/lib/cache/adapter.d.cts +41 -0
  34. package/dist/lib/cache/adapter.d.ts +41 -0
  35. package/dist/lib/cache/index.cjs +2 -0
  36. package/dist/lib/cache/index.cjs.map +1 -0
  37. package/dist/lib/cache/index.d.cts +5 -0
  38. package/dist/lib/cache/index.d.ts +5 -0
  39. package/dist/lib/cache/index.js +113 -0
  40. package/dist/lib/cache/index.js.map +1 -0
  41. package/dist/lib/cache/invalidation.d.cts +36 -0
  42. package/dist/lib/cache/invalidation.d.ts +36 -0
  43. package/dist/lib/cache/redis-adapter.d.cts +49 -0
  44. package/dist/lib/cache/redis-adapter.d.ts +49 -0
  45. package/dist/lib/cache-DGhTYyqh.js +50 -0
  46. package/dist/lib/cache-DGhTYyqh.js.map +1 -0
  47. package/dist/lib/cache-X1n4Ossu.cjs +2 -0
  48. package/dist/lib/cache-X1n4Ossu.cjs.map +1 -0
  49. package/dist/lib/cli/output.d.cts +58 -0
  50. package/dist/lib/cli/output.d.ts +58 -0
  51. package/dist/lib/cli/ports.d.cts +20 -0
  52. package/dist/lib/cli/ports.d.ts +20 -0
  53. package/dist/lib/cli.cjs +2559 -1488
  54. package/dist/lib/cli.cjs.map +1 -1
  55. package/dist/lib/cli.d.cts +21 -0
  56. package/dist/lib/cli.d.ts +21 -0
  57. package/dist/lib/cli.js +2558 -1488
  58. package/dist/lib/cli.js.map +1 -1
  59. package/dist/lib/config/index.cjs +1 -1
  60. package/dist/lib/config/index.cjs.map +1 -1
  61. package/dist/lib/config/index.d.cts +79 -0
  62. package/dist/lib/config/index.d.ts +79 -0
  63. package/dist/lib/config/index.js +21 -14
  64. package/dist/lib/config/index.js.map +1 -1
  65. package/dist/lib/{errors-ePYxDlhU.js → errors-j4cg9VN3.js} +24 -30
  66. package/dist/lib/{errors-ePYxDlhU.js.map → errors-j4cg9VN3.js.map} +1 -1
  67. package/dist/lib/errors-kSl9yLkg.cjs +2 -0
  68. package/dist/lib/{errors-0X7pCFNU.cjs.map → errors-kSl9yLkg.cjs.map} +1 -1
  69. package/dist/lib/hydrate-BSLuI0Nh.cjs +2 -0
  70. package/dist/lib/hydrate-BSLuI0Nh.cjs.map +1 -0
  71. package/dist/lib/hydrate-BaS7-d8C.js +133 -0
  72. package/dist/lib/hydrate-BaS7-d8C.js.map +1 -0
  73. package/dist/lib/idiomorph.esm-BOOTOg1r.cjs +2 -0
  74. package/dist/lib/idiomorph.esm-BOOTOg1r.cjs.map +1 -0
  75. package/dist/lib/idiomorph.esm-CXuY-EHB.js +371 -0
  76. package/dist/lib/idiomorph.esm-CXuY-EHB.js.map +1 -0
  77. package/dist/lib/index.cjs +1 -1
  78. package/dist/lib/index.cjs.map +1 -1
  79. package/dist/lib/index.d.cts +8 -6
  80. package/dist/lib/index.d.ts +8 -6
  81. package/dist/lib/index.js +1 -1
  82. package/dist/lib/index.js.map +1 -1
  83. package/dist/lib/interpolation-plugin-C0dTd69H.cjs +58 -0
  84. package/dist/lib/interpolation-plugin-C0dTd69H.cjs.map +1 -0
  85. package/dist/lib/{interpolation-plugin-Wgb1j4pT.js → interpolation-plugin-K2qE69tF.js} +95 -126
  86. package/dist/lib/interpolation-plugin-K2qE69tF.js.map +1 -0
  87. package/dist/lib/invalidation-CFpNQUv6.cjs +2 -0
  88. package/dist/lib/invalidation-CFpNQUv6.cjs.map +1 -0
  89. package/dist/lib/invalidation-DXhdE9wj.js +64 -0
  90. package/dist/lib/invalidation-DXhdE9wj.js.map +1 -0
  91. package/dist/lib/island/generate-entry.d.cts +40 -2
  92. package/dist/lib/island/generate-entry.d.ts +40 -2
  93. package/dist/lib/island/hydrate.d.cts +19 -6
  94. package/dist/lib/island/hydrate.d.ts +19 -6
  95. package/dist/lib/island/index.cjs +1 -1
  96. package/dist/lib/island/index.d.cts +2 -1
  97. package/dist/lib/island/index.d.ts +2 -1
  98. package/dist/lib/island/index.js +1 -1
  99. package/dist/lib/island/island.d.cts +15 -0
  100. package/dist/lib/island/island.d.ts +15 -0
  101. package/dist/lib/island-CTBnsOhI.js +59 -0
  102. package/dist/lib/island-CTBnsOhI.js.map +1 -0
  103. package/dist/lib/island-kfQEKRe_.cjs +2 -0
  104. package/dist/lib/island-kfQEKRe_.cjs.map +1 -0
  105. package/dist/lib/node-http-DVFcYeBS.js +723 -0
  106. package/dist/lib/node-http-DVFcYeBS.js.map +1 -0
  107. package/dist/lib/node-http-Uct7DhmN.cjs +13 -0
  108. package/dist/lib/node-http-Uct7DhmN.cjs.map +1 -0
  109. package/dist/lib/rolldown-runtime-BIInC43l.cjs +1 -0
  110. package/dist/lib/rolldown-runtime-Dy4uBu1J.js +11 -0
  111. package/dist/lib/router/client.cjs +1 -1
  112. package/dist/lib/router/client.cjs.map +1 -1
  113. package/dist/lib/router/client.d.cts +55 -8
  114. package/dist/lib/router/client.d.ts +55 -8
  115. package/dist/lib/router/client.js +298 -97
  116. package/dist/lib/router/client.js.map +1 -1
  117. package/dist/lib/router/redirects.d.cts +34 -0
  118. package/dist/lib/router/redirects.d.ts +34 -0
  119. package/dist/lib/runtime/handler.d.cts +59 -0
  120. package/dist/lib/runtime/handler.d.ts +59 -0
  121. package/dist/lib/runtime/index.cjs +1 -1
  122. package/dist/lib/runtime/index.d.cts +2 -1
  123. package/dist/lib/runtime/index.d.ts +2 -1
  124. package/dist/lib/runtime/index.js +4 -4
  125. package/dist/lib/runtime/logger.d.cts +47 -0
  126. package/dist/lib/runtime/logger.d.ts +47 -0
  127. package/dist/lib/runtime/node-http.d.cts +11 -1
  128. package/dist/lib/runtime/node-http.d.ts +11 -1
  129. package/dist/lib/runtime-ChE4flX3.cjs +2 -0
  130. package/dist/lib/runtime-ChE4flX3.cjs.map +1 -0
  131. package/dist/lib/runtime-OMyz5yE-.js +905 -0
  132. package/dist/lib/runtime-OMyz5yE-.js.map +1 -0
  133. package/dist/lib/seo/index.cjs +1 -10
  134. package/dist/lib/seo/index.d.cts +1 -0
  135. package/dist/lib/seo/index.d.ts +1 -0
  136. package/dist/lib/seo/index.js +2 -41
  137. package/dist/lib/seo/sitemap-from-routes.d.cts +24 -0
  138. package/dist/lib/seo/sitemap-from-routes.d.ts +24 -0
  139. package/dist/lib/{shared-CfqOLsKj.cjs → shared-CP0Dc3cp.cjs} +72 -47
  140. package/dist/lib/shared-CP0Dc3cp.cjs.map +1 -0
  141. package/dist/lib/{shared-DU3iQgr7.js → shared-D8w-neq2.js} +87 -58
  142. package/dist/lib/shared-D8w-neq2.js.map +1 -0
  143. package/dist/lib/sitemap-from-routes-CaBoiGvE.js +77 -0
  144. package/dist/lib/sitemap-from-routes-CaBoiGvE.js.map +1 -0
  145. package/dist/lib/sitemap-from-routes-DbcLLL4G.cjs +13 -0
  146. package/dist/lib/sitemap-from-routes-DbcLLL4G.cjs.map +1 -0
  147. package/dist/lib/ssr/render.d.cts +8 -2
  148. package/dist/lib/ssr/render.d.ts +8 -2
  149. package/dist/lib/ssr/server.d.cts +7 -0
  150. package/dist/lib/ssr/server.d.ts +7 -0
  151. package/dist/lib/ssr/stream-response.d.cts +30 -0
  152. package/dist/lib/ssr/stream-response.d.ts +30 -0
  153. package/dist/lib/ssr/stream.d.cts +16 -1
  154. package/dist/lib/ssr/stream.d.ts +16 -1
  155. package/dist/lib/{stream-DmZjYqHm.cjs → stream-Cg-xYG82.cjs} +3 -3
  156. package/dist/lib/stream-Cg-xYG82.cjs.map +1 -0
  157. package/dist/lib/stream-D-ytogdu.js +106 -0
  158. package/dist/lib/stream-D-ytogdu.js.map +1 -0
  159. package/dist/lib/vite/index.cjs +1 -1
  160. package/dist/lib/vite/index.cjs.map +1 -1
  161. package/dist/lib/vite/index.d.cts +11 -0
  162. package/dist/lib/vite/index.d.ts +11 -0
  163. package/dist/lib/vite/index.js +101 -94
  164. package/dist/lib/vite/index.js.map +1 -1
  165. package/package.json +25 -8
  166. package/dist/lib/errors-0X7pCFNU.cjs +0 -2
  167. package/dist/lib/hydrate-CJbUWdXu.js +0 -126
  168. package/dist/lib/hydrate-CJbUWdXu.js.map +0 -1
  169. package/dist/lib/hydrate-D6MR24mz.cjs +0 -2
  170. package/dist/lib/hydrate-D6MR24mz.cjs.map +0 -1
  171. package/dist/lib/interpolation-plugin-TWDch8nn.cjs +0 -39
  172. package/dist/lib/interpolation-plugin-TWDch8nn.cjs.map +0 -1
  173. package/dist/lib/interpolation-plugin-Wgb1j4pT.js.map +0 -1
  174. package/dist/lib/node-http-DRAUhO0c.js +0 -617
  175. package/dist/lib/node-http-DRAUhO0c.js.map +0 -1
  176. package/dist/lib/node-http-DhxguYyz.cjs +0 -13
  177. package/dist/lib/node-http-DhxguYyz.cjs.map +0 -1
  178. package/dist/lib/runtime-CrH5X-Es.cjs +0 -2
  179. package/dist/lib/runtime-CrH5X-Es.cjs.map +0 -1
  180. package/dist/lib/runtime-Ds2-wH6P.js +0 -520
  181. package/dist/lib/runtime-Ds2-wH6P.js.map +0 -1
  182. package/dist/lib/seo/index.cjs.map +0 -1
  183. package/dist/lib/seo/index.js.map +0 -1
  184. package/dist/lib/shared-CfqOLsKj.cjs.map +0 -1
  185. package/dist/lib/shared-DU3iQgr7.js.map +0 -1
  186. package/dist/lib/stream-CpOG052V.js +0 -104
  187. package/dist/lib/stream-CpOG052V.js.map +0 -1
  188. package/dist/lib/stream-DmZjYqHm.cjs.map +0 -1
package/dist/lib/cli.cjs CHANGED
@@ -25,10 +25,13 @@ let node_path = require("node:path");
25
25
  let node_fs = require("node:fs");
26
26
  let node_child_process = require("node:child_process");
27
27
  let node_url = require("node:url");
28
+ let node_module = require("node:module");
28
29
  let _elurjs_core_server = require("@elurjs/core/server");
30
+ require("@elurjs/core");
29
31
  let node_crypto = require("node:crypto");
30
- let node_module = require("node:module");
31
32
  let vite = require("vite");
33
+ let node_os = require("node:os");
34
+ let node_async_hooks = require("node:async_hooks");
32
35
  let __image_registry_js = require("./image/registry.js");
33
36
  //#region src/router/route-scanner.ts
34
37
  function isRouteGroup(segment) {
@@ -201,8 +204,35 @@ function toIdentifier(name, index) {
201
204
  const cleaned = name.replace(/[^a-zA-Z0-9_$]/g, "_");
202
205
  return /^[a-zA-Z_$]/.test(cleaned) ? `${cleaned}_${index}` : `_${cleaned}_${index}`;
203
206
  }
207
+ /**
208
+ * Source for the standalone router module emitted in split builds. Router
209
+ * options are baked in so the public module takes no arguments.
210
+ */
211
+ function buildRouterEntrySource(routerImport = "@elurjs/kit/router", options = {}) {
212
+ const opts = {};
213
+ if (options.prefetch === false) opts.prefetch = false;
214
+ if (options.morph === true) opts.morph = true;
215
+ if (options.loadingIndicator === true) opts.loadingIndicator = true;
216
+ const args = Object.keys(opts).length > 0 ? JSON.stringify(opts) : "";
217
+ return `// AUTO-GENERATED by @elurjs/kit. Do not edit.
218
+ import { startClientRouter } from ${JSON.stringify(routerImport)};
219
+
220
+ startClientRouter(${args});
221
+ `;
222
+ }
223
+ /**
224
+ * Serializes the startClientRouter options embedded in a combined entry.
225
+ * Only non-default flags are emitted to keep the generated code minimal.
226
+ */
227
+ function routerCallArgs(router) {
228
+ const opts = {};
229
+ if (router?.prefetch === false) opts.prefetch = false;
230
+ if (router?.morph === true) opts.morph = true;
231
+ if (router?.loadingIndicator === true) opts.loadingIndicator = true;
232
+ return Object.keys(opts).length > 0 ? JSON.stringify(opts) : "";
233
+ }
204
234
  /** Builds the source code of the client entry module. */
205
- function buildEntrySource(islands, outFile, hydrateImport = "@elurjs/kit/island", routerImport = "@elurjs/kit/router") {
235
+ function buildEntrySource(islands, outFile, hydrateImport = "@elurjs/kit/island", routerImport = "@elurjs/kit/router", router) {
206
236
  const registryLines = islands.map((island, i) => ({
207
237
  ident: toIdentifier(island.name, i),
208
238
  name: island.name,
@@ -211,18 +241,36 @@ function buildEntrySource(islands, outFile, hydrateImport = "@elurjs/kit/island"
211
241
  const islandHydration = registryLines ? `const registry = {
212
242
  ${registryLines}
213
243
  };
214
- // Defer hydration until the browser is idle so the first paint is not
215
- // blocked. Islands with directive "load" already have SSR-rendered DOM,
216
- // so the user sees content immediately — hydration only adds interactivity.
217
244
  const hydrate = () => hydrateIslands(registry);
218
- if ("requestIdleCallback" in window) {
219
- requestIdleCallback(hydrate, { timeout: 2000 });
220
- } else {
221
- setTimeout(hydrate, 0);
222
- }
245
+ // Islands inside persisted nodes must not be disposed across navigations.
246
+ // The router announces the survivors in the elur:before-render detail; the
247
+ // DOM query fallback covers hosts that dispatch it without detail.
248
+ const cleanup = (persisted) =>
249
+ cleanupHydratedIslands({
250
+ except: persisted ?? document.querySelectorAll("[data-elur-persist]"),
251
+ });
252
+ let sawBeforeRender = false;
253
+
254
+ // Hydrate right after parse: module scripts are deferred, so this already
255
+ // runs once the DOM is ready. Directives schedule themselves inside
256
+ // hydrateIslands — "load"/"only" run immediately (real Astro semantics),
257
+ // "idle"/"visible" keep their deferred scheduling.
258
+ hydrate();
259
+
260
+ // The router dispatches elur:before-render BEFORE swapping #app: islands are
261
+ // disposed while still attached (Fase A2), except persisted subtrees.
262
+ document.addEventListener("elur:before-render", (event) => {
263
+ sawBeforeRender = true;
264
+ cleanup(event.detail?.persisted);
265
+ });
266
+
267
+ // Re-hydrate after SPA navigations.
223
268
  document.addEventListener("elur:rendered", () => {
224
- cleanupHydratedIslands();
225
- hydrateIslands(registry);
269
+ // Compat fallback: hosts that only dispatch elur:rendered (streaming swap
270
+ // script, hand-rolled integrations) still need the cleanup pass.
271
+ if (!sawBeforeRender) cleanup();
272
+ sawBeforeRender = false;
273
+ hydrate();
226
274
  });
227
275
 
228
276
  // Vite HMR: when an island module (or the entry itself) updates, dispose the
@@ -230,20 +278,15 @@ document.addEventListener("elur:rendered", () => {
230
278
  // dynamic import() resolves to the fresh modules, so no full page reload is
231
279
  // needed (progressive enhancement, audit §10.2 / §12.2).
232
280
  if (import.meta.hot) {
233
- import.meta.hot.accept((newModule) => {
281
+ import.meta.hot.accept(() => {
234
282
  cleanupHydratedIslands();
235
283
  hydrateIslands(registry);
236
- if (newModule) {
237
- // Re-run the module so its side effects (router, listeners) apply.
238
- }
239
284
  });
240
285
  }` : "";
286
+ const embedRouter = router ? router.enabled !== false && !router.separate : true;
241
287
  return `// AUTO-GENERATED by @elurjs/kit. Do not edit.
242
- import { startClientRouter } from ${JSON.stringify(routerImport)};
243
- import { hydrateIslands, cleanupHydratedIslands } from ${JSON.stringify(hydrateImport)};
244
-
245
- startClientRouter();
246
- ${islandHydration}
288
+ ${embedRouter ? `import { startClientRouter } from ${JSON.stringify(routerImport)};\n` : ""}import { hydrateIslands, cleanupHydratedIslands } from ${JSON.stringify(hydrateImport)};
289
+ ${embedRouter ? `\nstartClientRouter(${routerCallArgs(router)});\n` : ""}${islandHydration}
247
290
  `;
248
291
  }
249
292
  /** Computes a POSIX-style relative import specifier between two files. */
@@ -253,15 +296,23 @@ function toImportSpecifier(fromFile, toFile) {
253
296
  return spec;
254
297
  }
255
298
  /**
256
- * Generates and writes the client entry module for the given islands.
299
+ * Generates and writes the client entry module for the given islands. When
300
+ * `options.router.separate` is set (and the router is enabled), a standalone
301
+ * router module is written alongside it (default: `router.ts` next to the
302
+ * entry — bundle it as a second input to emit `/_elur/router.js`).
257
303
  *
258
304
  * @param options Generation options.
259
305
  * @returns The absolute path of the written entry file.
260
306
  */
261
307
  async function generateClientEntry(options) {
262
- const source = buildEntrySource(options.islands, options.outFile, options.hydrateImport, options.routerImport);
308
+ const source = buildEntrySource(options.islands, options.outFile, options.hydrateImport, options.routerImport, options.router);
263
309
  await (0, node_fs_promises.mkdir)((0, node_path.dirname)(options.outFile), { recursive: true });
264
310
  await (0, node_fs_promises.writeFile)(options.outFile, source, "utf8");
311
+ if (options.router) {
312
+ const routerFile = options.router.outFile ?? (0, node_path.join)((0, node_path.dirname)(options.outFile), "router.ts");
313
+ const routerSource = options.router.enabled === false ? `// AUTO-GENERATED by @elurjs/kit. Do not edit.\n// router.enabled: false — intentionally empty.\nexport {};\n` : buildRouterEntrySource(options.routerImport ?? "@elurjs/kit/router", options.router);
314
+ await (0, node_fs_promises.writeFile)(routerFile, routerSource, "utf8");
315
+ }
265
316
  return options.outFile;
266
317
  }
267
318
  //#endregion
@@ -301,6 +352,18 @@ var init_render_to_string = __esmMin((() => {
301
352
  }));
302
353
  //#endregion
303
354
  //#region src/build/document-shell.ts
355
+ /**
356
+ * Extracts the inner HTML of `#app` from a full document produced by
357
+ * `documentShell`. Returns `undefined` when the markers are missing (e.g. a
358
+ * hand-written document).
359
+ */
360
+ function extractAppBody(html) {
361
+ const start = html.indexOf(APP_START_MARKER);
362
+ if (start < 0) return void 0;
363
+ const end = html.indexOf(APP_END_MARKER, start + 21);
364
+ if (end < 0) return void 0;
365
+ return html.slice(start + 21, end);
366
+ }
304
367
  function escapeHtml(value) {
305
368
  return value.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
306
369
  }
@@ -348,12 +411,33 @@ function buildHeadTags(metadata, fallbackTitle) {
348
411
  if (metadata.other) for (const [name, content] of Object.entries(metadata.other)) tags.push(`<meta data-elur-head name="${escapeHtml(name)}" content="${escapeHtml(content)}" />`);
349
412
  return tags.map((t) => `\n ${t}`).join("");
350
413
  }
414
+ /**
415
+ * Document-level Speculation Rules (Chromium-only, ignored elsewhere).
416
+ *
417
+ * `href_matches: "/*"` scopes the rule to same-origin path links; the
418
+ * `selector_matches` exclusions keep downloads, new-tab links, router-opt-outs
419
+ * and explicit `data-no-speculation` links out of speculation. Actions are
420
+ * POST endpoints reached through forms/`callAction`, never through document
421
+ * links, so they are not speculated. `eagerness: "moderate"` speculates on
422
+ * hover — the same trigger as the client router's prefetch.
423
+ */
424
+ function speculationRulesScript(mode) {
425
+ return `\n <script type="speculationrules">${JSON.stringify({ [mode]: [{
426
+ source: "document",
427
+ where: { and: [{ href_matches: "/*" }, { not: { selector_matches: "a[download], a[target], a[data-no-router], a[data-no-speculation]" } }] },
428
+ eagerness: "moderate"
429
+ }] })}<\/script>`;
430
+ }
351
431
  /** Wraps rendered body HTML into a full HTML document. */
352
432
  function documentShell(opts) {
353
- const { body, title = "Elur Kit App", lang = "es", data, actions, clientEntry, htmlAttributes, headScripts, headLinks, metadata } = opts;
433
+ const { body, title = "Elur Kit App", lang = "es", data, actions, clientEntry, routerEntry, htmlAttributes, headScripts, headLinks, metadata } = opts;
354
434
  const dataScript = data !== void 0 ? `\n <script type="application/json" id="elur-data">${serializeData(data)}<\/script>` : "";
355
435
  const actionsScript = actions && Object.keys(actions).length > 0 ? `\n <script type="application/json" id="elur-actions">${serializeData(actions)}<\/script>` : "";
436
+ const modulePreload = (src) => `\n <link rel="modulepreload" href="${escapeHtml(src)}" />`;
437
+ const preloads = (clientEntry ? modulePreload(clientEntry) : "") + (routerEntry ? modulePreload(routerEntry) : "");
356
438
  const entryScript = clientEntry ? `\n <script type="module" src="${escapeHtml(clientEntry)}"><\/script>` : "";
439
+ const routerScript = routerEntry ? `\n <script type="module" src="${escapeHtml(routerEntry)}"><\/script>` : "";
440
+ const speculationScript = opts.speculation ? speculationRulesScript(opts.speculation) : "";
357
441
  const htmlAttrs = htmlAttributes ? Object.entries(htmlAttributes).filter(([, value]) => value !== void 0 && value !== null && value !== "").map(([key, value]) => ` ${escapeHtml(key)}="${escapeHtml(String(value))}"`).join("") : "";
358
442
  const headScriptsHtml = headScripts ? headScripts.filter((script) => typeof script === "string" && script.trim().length > 0).map((script) => {
359
443
  if (script.trimStart().startsWith("<script")) return `\n ${script}`;
@@ -362,20 +446,20 @@ function documentShell(opts) {
362
446
  const headTags = metadata ? buildHeadTags(metadata, title) : "";
363
447
  const titleTag = metadata?.title ? "" : `\n <title>${escapeHtml(title)}</title>`;
364
448
  const headLinksHtml = headLinks ? headLinks.filter((link) => typeof link === "string" && link.trim().length > 0).map((link) => `\n ${link}`).join("") : "";
365
- const renderEndpointMeta = opts.renderEndpoint === false ? "\n <meta name=\"elur:render-endpoint\" content=\"off\" />" : "";
449
+ const renderEndpointMeta = opts.renderEndpoint === false && opts.routerEnabled !== false ? "\n <meta name=\"elur:render-endpoint\" content=\"off\" />" : "";
366
450
  return `<!DOCTYPE html>
367
451
  <html lang="${escapeHtml(lang)}"${htmlAttrs}>
368
452
  <head>
369
453
  <meta charset="utf-8" />
370
- <meta name="viewport" content="width=device-width, initial-scale=1" />${renderEndpointMeta}${titleTag}${headTags}${headLinksHtml}${headScriptsHtml}
454
+ <meta name="viewport" content="width=device-width, initial-scale=1" />${renderEndpointMeta}${titleTag}${headTags}${headLinksHtml}${headScriptsHtml}${preloads}${speculationScript}
371
455
  </head>
372
456
  <body>
373
- <div id="app">${body}</div>${dataScript}${actionsScript}${entryScript}
457
+ <div id="app">${APP_START_MARKER}${body}${APP_END_MARKER}</div>${dataScript}${actionsScript}${entryScript}${routerScript}
374
458
  </body>
375
459
  </html>
376
460
  `;
377
461
  }
378
- var HTML_ESCAPES;
462
+ var HTML_ESCAPES, APP_START_MARKER, APP_END_MARKER;
379
463
  var init_document_shell = __esmMin((() => {
380
464
  HTML_ESCAPES = {
381
465
  "&": "&amp;",
@@ -384,6 +468,14 @@ var init_document_shell = __esmMin((() => {
384
468
  "\"": "&quot;",
385
469
  "'": "&#39;"
386
470
  };
471
+ APP_START_MARKER = "<!--elur:app:start-->";
472
+ APP_END_MARKER = "<!--elur:app:end-->";
473
+ }));
474
+ //#endregion
475
+ //#region src/island/island.ts
476
+ var ISLAND_MARKER_ATTR;
477
+ var init_island = __esmMin((() => {
478
+ ISLAND_MARKER_ATTR = "data-elur-island";
387
479
  }));
388
480
  //#endregion
389
481
  //#region src/action/error-store.ts
@@ -560,7 +652,7 @@ function collectShellExtras(pageData, layoutDataList) {
560
652
  };
561
653
  }
562
654
  async function renderPage(options) {
563
- const { route, params = {}, searchParams = new URLSearchParams(), config, importer = defaultImport$1, actions, request } = options;
655
+ const { route, params = {}, searchParams = new URLSearchParams(), config, importer = defaultImport$2, actions, request } = options;
564
656
  const { default: PageComponent, generateMetadata } = await importer(route.pagePath);
565
657
  let data;
566
658
  let revalidate;
@@ -667,6 +759,16 @@ async function renderPage(options) {
667
759
  });
668
760
  if (!metadata) metadata = extractMetadata(data) ?? extractMetadataFromList(layoutDataList);
669
761
  const resolvedTitle = metadata?.title ?? title;
762
+ const hasIslands = body.includes(ISLAND_MARKER_ATTR);
763
+ const routerCfg = config.router;
764
+ const routerEnabled = routerCfg?.enabled !== false;
765
+ let clientEntry;
766
+ let routerEntry;
767
+ if (!routerCfg || config.js === "legacy") clientEntry = config.clientEntry;
768
+ else if (routerCfg.entry) {
769
+ if (hasIslands) clientEntry = config.clientEntry;
770
+ if (routerEnabled) routerEntry = routerCfg.entry;
771
+ } else if (hasIslands || routerEnabled) clientEntry = config.clientEntry;
670
772
  const html = documentShell({
671
773
  title: resolvedTitle,
672
774
  lang: config.lang,
@@ -677,7 +779,10 @@ async function renderPage(options) {
677
779
  headScripts,
678
780
  headLinks,
679
781
  metadata,
680
- clientEntry: config.clientEntry,
782
+ clientEntry,
783
+ routerEntry,
784
+ routerEnabled: routerCfg ? routerEnabled : void 0,
785
+ speculation: routerCfg?.speculation,
681
786
  renderEndpoint: config.renderEndpoint
682
787
  });
683
788
  const head = metadata ? buildHeadTags(metadata, resolvedTitle) : "";
@@ -687,7 +792,8 @@ async function renderPage(options) {
687
792
  clearActionErrorCookie,
688
793
  head,
689
794
  resolvedTitle,
690
- cachePolicy
795
+ cachePolicy,
796
+ data
691
797
  };
692
798
  }
693
799
  /** Extracts a `metadata` field from a loader data object, if present. */
@@ -725,13 +831,14 @@ async function renderErrorPage(options) {
725
831
  return;
726
832
  }
727
833
  }
728
- var defaultImport$1;
834
+ var defaultImport$2;
729
835
  var init_render = __esmMin((() => {
730
836
  init_render_to_string();
731
837
  init_document_shell();
838
+ init_island();
732
839
  init_error_store();
733
840
  init_policy();
734
- defaultImport$1 = (path) => import(path);
841
+ defaultImport$2 = (path) => import(path);
735
842
  }));
736
843
  //#endregion
737
844
  //#region src/action/scan.ts
@@ -1041,6 +1148,132 @@ async function runIntegrationHook(integrations, hook, args) {
1041
1148
  }
1042
1149
  }
1043
1150
  //#endregion
1151
+ //#region src/seo/index.ts
1152
+ /**
1153
+ * SEO utilities — sitemap.xml and robots.txt generation.
1154
+ *
1155
+ * @module
1156
+ */
1157
+ /**
1158
+ * Generates a `sitemap.xml` file from a list of URLs.
1159
+ *
1160
+ * @example
1161
+ * ```ts
1162
+ * import { generateSitemap } from "@elurjs/kit/seo";
1163
+ *
1164
+ * await generateSitemap({
1165
+ * siteUrl: "https://elur-kit.dev",
1166
+ * outDir: "./dist",
1167
+ * urls: [
1168
+ * "/",
1169
+ * "/docs/introduction",
1170
+ * { url: "/docs/routing", changefreq: "weekly", priority: 0.8 },
1171
+ * ],
1172
+ * });
1173
+ * ```
1174
+ */
1175
+ async function generateSitemap(config) {
1176
+ const { siteUrl, urls, outDir } = config;
1177
+ const base = siteUrl.replace(/\/$/, "");
1178
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
1179
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
1180
+ ${urls.map((entry) => {
1181
+ const e = typeof entry === "string" ? { url: entry } : entry;
1182
+ const lines = [` <url>`, ` <loc>${escapeXml$1(`${base}${e.url.startsWith("/") ? "" : "/"}${e.url}`)}</loc>`];
1183
+ if (e.lastmod) lines.push(` <lastmod>${e.lastmod}</lastmod>`);
1184
+ if (e.changefreq) lines.push(` <changefreq>${e.changefreq}</changefreq>`);
1185
+ if (e.priority !== void 0) lines.push(` <priority>${e.priority.toFixed(1)}</priority>`);
1186
+ lines.push(` </url>`);
1187
+ return lines.join("\n");
1188
+ }).join("\n")}
1189
+ </urlset>
1190
+ `;
1191
+ const filePath = (0, node_path.join)(outDir, "sitemap.xml");
1192
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(filePath), { recursive: true });
1193
+ await (0, node_fs_promises.writeFile)(filePath, xml, "utf8");
1194
+ return filePath;
1195
+ }
1196
+ function escapeXml$1(str) {
1197
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1198
+ }
1199
+ //#endregion
1200
+ //#region src/seo/sitemap-from-routes.ts
1201
+ /**
1202
+ * Generates a sitemap.xml from the route manifest.
1203
+ *
1204
+ * Static routes are included automatically. Dynamic routes require the author
1205
+ * to provide URLs via `extraUrls` or a `generateSitemapUrls()` export.
1206
+ *
1207
+ * For large sites (>50,000 URLs), a sitemap index is generated.
1208
+ */
1209
+ async function generateSitemapFromRoutes(options) {
1210
+ const { siteUrl, outDir, routes, extraUrls = [], maxUrlsPerSitemap = 5e4 } = options;
1211
+ const routeUrls = [];
1212
+ for (const page of routes.pages) {
1213
+ if (page.params.length > 0) continue;
1214
+ if (page.path === "/404" || page.path === "/500") continue;
1215
+ if (page.path.startsWith("/_elur") || page.path.startsWith("/__elur-js")) continue;
1216
+ routeUrls.push({
1217
+ url: page.path,
1218
+ changefreq: options.defaultChangefreq,
1219
+ priority: options.defaultPriority
1220
+ });
1221
+ }
1222
+ const allUrls = [...routeUrls, ...extraUrls];
1223
+ if (allUrls.length <= maxUrlsPerSitemap) return [await generateSitemap({
1224
+ siteUrl,
1225
+ outDir,
1226
+ urls: allUrls
1227
+ })];
1228
+ return generateSitemapIndex({
1229
+ siteUrl,
1230
+ outDir,
1231
+ urls: allUrls,
1232
+ maxUrlsPerSitemap
1233
+ });
1234
+ }
1235
+ /**
1236
+ * Generates a sitemap index file that references multiple sitemap files.
1237
+ * Used for large sites (>50,000 URLs).
1238
+ */
1239
+ async function generateSitemapIndex(options) {
1240
+ const { siteUrl, outDir, urls, maxUrlsPerSitemap } = options;
1241
+ const base = siteUrl.replace(/\/$/, "");
1242
+ const files = [];
1243
+ const sitemapUrls = [];
1244
+ for (let i = 0; i < urls.length; i += maxUrlsPerSitemap) {
1245
+ const chunk = urls.slice(i, i + maxUrlsPerSitemap);
1246
+ const filename = `sitemap-${Math.floor(i / maxUrlsPerSitemap) + 1}.xml`;
1247
+ const { writeFile, mkdir } = await import("node:fs/promises");
1248
+ const { join, dirname } = await import("node:path");
1249
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${chunk.map((entry) => {
1250
+ const e = typeof entry === "string" ? { url: entry } : entry;
1251
+ const lines = [` <url>`, ` <loc>${escapeXml(`${base}${e.url.startsWith("/") ? "" : "/"}${e.url}`)}</loc>`];
1252
+ if (e.lastmod) lines.push(` <lastmod>${e.lastmod}</lastmod>`);
1253
+ if (e.changefreq) lines.push(` <changefreq>${e.changefreq}</changefreq>`);
1254
+ if (e.priority !== void 0) lines.push(` <priority>${e.priority.toFixed(1)}</priority>`);
1255
+ lines.push(` </url>`);
1256
+ return lines.join("\n");
1257
+ }).join("\n")}\n</urlset>\n`;
1258
+ const filePath = join(outDir, filename);
1259
+ await mkdir(dirname(filePath), { recursive: true });
1260
+ await writeFile(filePath, xml, "utf8");
1261
+ files.push(filePath);
1262
+ sitemapUrls.push(`${base}/${filename}`);
1263
+ }
1264
+ const { writeFile, mkdir } = await import("node:fs/promises");
1265
+ const { join, dirname } = await import("node:path");
1266
+ const indexXml = `<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${sitemapUrls.map((url) => ` <sitemap>\n <loc>${escapeXml(url)}</loc>\n </sitemap>`).join("\n")}\n</sitemapindex>\n`;
1267
+ const indexPath = join(outDir, "sitemap.xml");
1268
+ await mkdir(dirname(indexPath), { recursive: true });
1269
+ await writeFile(indexPath, indexXml, "utf8");
1270
+ files.push(indexPath);
1271
+ return files;
1272
+ }
1273
+ function escapeXml(str) {
1274
+ return str.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
1275
+ }
1276
+ //#endregion
1044
1277
  //#region src/build/build.ts
1045
1278
  init_route_scanner();
1046
1279
  function urlToFilePath(outDir, urlPath) {
@@ -1077,8 +1310,14 @@ async function build$3(config) {
1077
1310
  } catch (error) {
1078
1311
  if (error.code !== "ENOENT") throw error;
1079
1312
  }
1313
+ const reportPhase = (name, start) => {
1314
+ config.onPhase?.(name, performance.now() - start);
1315
+ };
1316
+ let phaseStart = performance.now();
1080
1317
  const routes = await scanRoutes(config.appDir);
1081
- const publicActions = actionNames(await scanActions(config.appDir));
1318
+ const actions = await scanActions(config.appDir);
1319
+ reportPhase("scan", phaseStart);
1320
+ const publicActions = actionNames(actions);
1082
1321
  const result = {
1083
1322
  pages: 0,
1084
1323
  skipped: [],
@@ -1092,8 +1331,17 @@ async function build$3(config) {
1092
1331
  islands: result.islands,
1093
1332
  outFile: config.generatedEntry,
1094
1333
  hydrateImport: config.hydrateImport,
1095
- routerImport: config.routerImport
1334
+ routerImport: config.routerImport,
1335
+ router: config.router ? {
1336
+ enabled: config.router.enabled !== false,
1337
+ prefetch: config.router.prefetch,
1338
+ morph: config.router.morph,
1339
+ loadingIndicator: config.router.loadingIndicator,
1340
+ separate: config.router.separate === true && config.js !== "legacy",
1341
+ outFile: config.router.outFile
1342
+ } : void 0
1096
1343
  });
1344
+ phaseStart = performance.now();
1097
1345
  for (const route of routes.pages) {
1098
1346
  if (!isDynamic(route.path)) {
1099
1347
  const filePath = await buildPage(config, route, publicActions);
@@ -1111,7 +1359,9 @@ async function build$3(config) {
1111
1359
  const errorConfig = {
1112
1360
  lang: config.lang,
1113
1361
  clientEntry: config.clientEntry,
1114
- renderEndpoint: false
1362
+ renderEndpoint: false,
1363
+ router: pageRouterConfig(config),
1364
+ js: config.js
1115
1365
  };
1116
1366
  if (routes.error404) {
1117
1367
  const result404 = await renderErrorPage({
@@ -1141,9 +1391,11 @@ async function build$3(config) {
1141
1391
  result.files.push(filePath);
1142
1392
  }
1143
1393
  }
1394
+ reportPhase("pages", phaseStart);
1144
1395
  const registeredImages = (0, __image_registry_js.consumeImageRegistry)();
1145
1396
  let manifest = null;
1146
1397
  if (registeredImages.length > 0 && config.publicDir) {
1398
+ phaseStart = performance.now();
1147
1399
  const manifestPath = (0, node_path.join)(config.outDir, ".elur", "image-manifest.json");
1148
1400
  const processResult = await processImageBatch(registeredImages, {
1149
1401
  publicDir: config.publicDir,
@@ -1200,12 +1452,33 @@ async function build$3(config) {
1200
1452
  }
1201
1453
  }
1202
1454
  }
1455
+ reportPhase("images", phaseStart);
1203
1456
  }
1204
1457
  (0, __image_registry_js.setImageManifest)(null);
1205
- if (config.integrations && config.integrations.length > 0) await runIntegrationHook(config.integrations, "build", [result, {
1206
- root: config.root ?? config.outDir,
1207
- command: "build"
1208
- }]);
1458
+ if (config.integrations && config.integrations.length > 0) {
1459
+ phaseStart = performance.now();
1460
+ await runIntegrationHook(config.integrations, "build", [result, {
1461
+ root: config.root ?? config.outDir,
1462
+ command: "build"
1463
+ }]);
1464
+ reportPhase("integrations", phaseStart);
1465
+ }
1466
+ if (config.site) {
1467
+ phaseStart = performance.now();
1468
+ let sitemapExists = false;
1469
+ try {
1470
+ sitemapExists = (await (0, node_fs_promises.stat)((0, node_path.join)(config.outDir, "sitemap.xml"))).isFile();
1471
+ } catch {}
1472
+ if (!sitemapExists) {
1473
+ const sitemapFiles = await generateSitemapFromRoutes({
1474
+ siteUrl: config.site,
1475
+ outDir: config.outDir,
1476
+ routes
1477
+ });
1478
+ result.files.push(...sitemapFiles);
1479
+ }
1480
+ reportPhase("sitemap", phaseStart);
1481
+ }
1209
1482
  return result;
1210
1483
  }
1211
1484
  async function buildPage(config, route, actions) {
@@ -1228,7 +1501,9 @@ async function buildConcretePage(config, route, params, actions) {
1228
1501
  config: {
1229
1502
  lang: config.lang,
1230
1503
  clientEntry: config.clientEntry,
1231
- renderEndpoint: false
1504
+ renderEndpoint: false,
1505
+ router: pageRouterConfig(config),
1506
+ js: config.js
1232
1507
  },
1233
1508
  actions
1234
1509
  });
@@ -1238,6 +1513,20 @@ async function buildConcretePage(config, route, params, actions) {
1238
1513
  await (0, node_fs_promises.writeFile)(filePath, htmlOut, "utf8");
1239
1514
  return filePath;
1240
1515
  }
1516
+ /**
1517
+ * The router slice of the per-page render config: `enabled` gates script/meta
1518
+ * emission, `entry` is advertised only for split bundles, and `speculation`
1519
+ * produces the Speculation Rules block on static pages.
1520
+ */
1521
+ function pageRouterConfig(config) {
1522
+ if (!config.router) return void 0;
1523
+ const separate = config.router.separate === true && config.js !== "legacy";
1524
+ return {
1525
+ enabled: config.router.enabled !== false,
1526
+ entry: separate ? config.router.entry ?? "/_elur/router.js" : void 0,
1527
+ speculation: config.router.speculation
1528
+ };
1529
+ }
1241
1530
  //#endregion
1242
1531
  //#region src/vite/interpolation-plugin.ts
1243
1532
  function warnLegacyOnce() {
@@ -1792,402 +2081,830 @@ async function transformProjectFiles(options) {
1792
2081
  }
1793
2082
  }
1794
2083
  //#endregion
1795
- //#region src/errors.ts
1796
- /**
1797
- * Type guard for action failures. Uses the marker field so it works across
1798
- * bundling boundaries where `instanceof` fails.
1799
- */
1800
- function isActionFailure(value) {
1801
- return typeof value === "object" && value !== null && value.__elur_js_action_failure === true;
1802
- }
1803
- /**
1804
- * Type guard for redirects. Uses the marker field so it works across bundling
1805
- * boundaries where `instanceof` fails.
1806
- */
1807
- function isRedirectResponse(value) {
1808
- return typeof value === "object" && value !== null && value.__elur_js_action_redirect === true;
1809
- }
1810
- /**
1811
- * Maps an arbitrary thrown value to a public-safe error info. By default the
1812
- * public message is generic; `includeDetail` (dev/verbose mode) appends the
1813
- * original `Error.message` for local debugging.
1814
- */
1815
- function toPublicErrorInfo(error, options = {}) {
1816
- const code = "INTERNAL_SERVER_ERROR";
1817
- const status = 500;
1818
- if (options.includeDetail && error instanceof Error && error.message) return {
1819
- code,
1820
- status,
1821
- message: error.message
1822
- };
1823
- return {
1824
- code,
1825
- status,
1826
- message: "Internal Server Error"
2084
+ //#region src/runtime/node-http.ts
2085
+ var GlobalAbortController = globalThis.AbortController ?? AbortController;
2086
+ function incomingMessageToRequest(req, body) {
2087
+ const headers = new Headers();
2088
+ for (let index = 0; index < req.rawHeaders.length; index += 2) headers.append(req.rawHeaders[index], req.rawHeaders[index + 1]);
2089
+ const controller = new GlobalAbortController();
2090
+ req.once("aborted", () => controller.abort());
2091
+ req.once("close", () => {
2092
+ if (!req.complete) controller.abort();
2093
+ });
2094
+ const protocol = req.socket.encrypted ? "https" : "http";
2095
+ const init = {
2096
+ method: req.method ?? "GET",
2097
+ headers,
2098
+ signal: controller.signal
1827
2099
  };
2100
+ if (body !== void 0 && body !== null && init.method !== "GET" && init.method !== "HEAD") init.body = body;
2101
+ return new Request(`${protocol}://${headers.get("host") ?? "localhost"}${req.url ?? "/"}`, init);
1828
2102
  }
1829
2103
  /**
1830
- * Builds a production-safe JSON error Response. Logs the raw error separately
1831
- * (never reflected in the response body) and keeps the request id header.
2104
+ * Writes a Web `Response` to a Node `ServerResponse`, streaming the body.
2105
+ *
2106
+ * Unlike `res.end(Buffer.from(await response.arrayBuffer()))`, this forwards
2107
+ * chunks as they are produced — required for streaming SSR responses to reach
2108
+ * the client progressively. Buffered (non-stream) bodies behave exactly as
2109
+ * before. Honors backpressure (`drain`) and cancels the upstream stream when
2110
+ * the client disconnects (`close` before `finish`).
1832
2111
  */
1833
- function publicErrorResponse(error, options = {}) {
1834
- const info = toPublicErrorInfo(error, options);
1835
- const headers = {
1836
- "Content-Type": "application/json; charset=utf-8",
1837
- "Cache-Control": "no-store"
2112
+ async function sendWebResponse(res, response) {
2113
+ const headers = Object.fromEntries(response.headers.entries());
2114
+ if (response.body !== null) {
2115
+ delete headers["content-length"];
2116
+ delete headers["transfer-encoding"];
2117
+ }
2118
+ res.writeHead(response.status, headers);
2119
+ const body = response.body;
2120
+ if (!body) {
2121
+ res.end();
2122
+ return;
2123
+ }
2124
+ const reader = body.getReader();
2125
+ let done = false;
2126
+ const onClose = () => {
2127
+ if (!done) reader.cancel().catch(() => {});
1838
2128
  };
1839
- if (options.requestId) headers["X-Request-Id"] = options.requestId;
1840
- return new Response(JSON.stringify({ error: info }), {
1841
- status: info.status,
1842
- headers
1843
- });
2129
+ res.once("close", onClose);
2130
+ try {
2131
+ for (;;) {
2132
+ const { done: readDone, value } = await reader.read();
2133
+ if (readDone) break;
2134
+ if (value && value.byteLength > 0 && !res.write(value)) await new Promise((resolveDrain) => res.once("drain", resolveDrain));
2135
+ }
2136
+ done = true;
2137
+ res.end();
2138
+ } catch {
2139
+ done = true;
2140
+ res.destroy();
2141
+ } finally {
2142
+ res.removeListener("close", onClose);
2143
+ }
1844
2144
  }
1845
- var init_errors = __esmMin((() => {}));
1846
2145
  //#endregion
1847
- //#region src/action/origin.ts
2146
+ //#region src/runtime/logger.ts
1848
2147
  /**
1849
- * Returns the host:port of a URL string, or undefined if it cannot be parsed.
2148
+ * Redacts sensitive fields from a log fields object.
2149
+ * Recursively redacts keys that match sensitive header names.
1850
2150
  */
1851
- function originOf(urlString) {
1852
- if (!urlString) return void 0;
1853
- try {
1854
- const url = new URL(urlString);
1855
- if (url.protocol !== "http:" && url.protocol !== "https:") return void 0;
1856
- return url.origin;
1857
- } catch {
1858
- return;
2151
+ function redactSensitive(fields) {
2152
+ const result = {};
2153
+ for (const [key, value] of Object.entries(fields)) {
2154
+ const lowerKey = key.toLowerCase();
2155
+ if (SENSITIVE_HEADERS.has(lowerKey)) result[key] = "[REDACTED]";
2156
+ else if (typeof value === "object" && value !== null && !Array.isArray(value)) result[key] = redactSensitive(value);
2157
+ else result[key] = value;
1859
2158
  }
2159
+ return result;
1860
2160
  }
1861
2161
  /**
1862
- * Verifies that a request originates from the same host (or an allow-listed
1863
- * origin). Returns an error message when the request must be rejected, or
1864
- * undefined when it is allowed.
1865
- *
1866
- * @param request The incoming Request to actions.
1867
- * @param options Origin check configuration.
2162
+ * Creates a logger for a request, optionally using the request's
2163
+ * X-Request-ID header if present.
1868
2164
  */
1869
- function verifyOrigin(request, options = {}) {
1870
- const targetOrigin = originOf(request.url);
1871
- if (!targetOrigin) return "Invalid target URL";
1872
- const origin = request.headers.get("Origin");
1873
- const referer = request.headers.get("Referer");
1874
- if (!origin && !referer) return options.strictOrigin ? "Missing Origin and Referer headers" : void 0;
1875
- const sourceOrigin = origin ? originOf(origin) : originOf(referer);
1876
- if (!sourceOrigin) return origin ? "Invalid Origin header" : "Invalid Referer header";
1877
- if (sourceOrigin === targetOrigin) return void 0;
1878
- if (options.allowedOrigins?.some((allowed) => originOf(allowed) === sourceOrigin)) return void 0;
1879
- return `Cross-origin request blocked: source "${sourceOrigin}" != target "${targetOrigin}"`;
1880
- }
1881
- /** Builds a 403 Response for a rejected origin. */
1882
- function originForbidden(message) {
1883
- return new Response(message, {
1884
- status: 403,
1885
- headers: { "Content-Type": "text/plain; charset=utf-8" }
2165
+ function createRequestLogger(request, minLevel) {
2166
+ const requestId = request?.headers.get("X-Request-ID") ?? void 0;
2167
+ return new StructuredLogger({
2168
+ minLevel,
2169
+ requestId
1886
2170
  });
1887
2171
  }
1888
- var init_origin = __esmMin((() => {}));
1889
- //#endregion
1890
- //#region src/action/server.ts
1891
- /**
1892
- * Reads the request body as text, enforcing a maximum size.
1893
- * Returns a 413 response if the body exceeds the limit.
1894
- */
1895
- async function readBodyWithLimit(request, limit) {
1896
- const contentLength = request.headers.get("Content-Length");
1897
- if (contentLength && parseInt(contentLength, 10) > limit) return {
1898
- ok: false,
1899
- response: new Response("Request body too large", {
1900
- status: 413,
1901
- headers: { "Content-Type": "text/plain" }
1902
- })
1903
- };
1904
- const reader = request.body?.getReader();
1905
- if (!reader) return {
1906
- ok: true,
1907
- text: ""
2172
+ var LEVEL_PRIORITY, SENSITIVE_HEADERS, StructuredLogger;
2173
+ var init_logger = __esmMin((() => {
2174
+ LEVEL_PRIORITY = {
2175
+ debug: 10,
2176
+ info: 20,
2177
+ warn: 30,
2178
+ error: 40
1908
2179
  };
1909
- const chunks = [];
1910
- let totalSize = 0;
1911
- try {
1912
- for (;;) {
1913
- const { done, value } = await reader.read();
1914
- if (done) break;
1915
- totalSize += value.byteLength;
1916
- if (totalSize > limit) {
1917
- try {
1918
- reader.cancel();
1919
- } catch {}
1920
- return {
1921
- ok: false,
1922
- response: new Response("Request body too large", {
1923
- status: 413,
1924
- headers: { "Content-Type": "text/plain" }
1925
- })
1926
- };
2180
+ SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
2181
+ "cookie",
2182
+ "authorization",
2183
+ "set-cookie",
2184
+ "x-api-key",
2185
+ "x-auth-token"
2186
+ ]);
2187
+ StructuredLogger = class {
2188
+ minLevel;
2189
+ requestId;
2190
+ timings = [];
2191
+ entries = [];
2192
+ constructor(options = {}) {
2193
+ this.minLevel = options.minLevel ?? (process.env.NODE_ENV === "production" ? "info" : "debug");
2194
+ this.requestId = options.requestId ?? (0, node_crypto.randomUUID)();
2195
+ }
2196
+ /** Returns the request ID for this logger instance. */
2197
+ getRequestId() {
2198
+ return this.requestId;
2199
+ }
2200
+ /** Logs a debug message. */
2201
+ debug(message, fields) {
2202
+ this.log("debug", message, fields);
2203
+ }
2204
+ /** Logs an info message. */
2205
+ info(message, fields) {
2206
+ this.log("info", message, fields);
2207
+ }
2208
+ /** Logs a warning. */
2209
+ warn(message, fields) {
2210
+ this.log("warn", message, fields);
2211
+ }
2212
+ /** Logs an error. */
2213
+ error(message, fields) {
2214
+ this.log("error", message, fields);
2215
+ }
2216
+ /** Records a Server-Timing metric. */
2217
+ timing(name, durationMs, description) {
2218
+ this.timings.push({
2219
+ name,
2220
+ durationMs,
2221
+ description
2222
+ });
2223
+ }
2224
+ /** Starts a timer and returns a function to stop it and record the timing. */
2225
+ startTimer(name, description) {
2226
+ const start = performance.now();
2227
+ return () => {
2228
+ this.timing(name, performance.now() - start, description);
2229
+ };
2230
+ }
2231
+ /** Returns the Server-Timing header value. */
2232
+ getServerTimingHeader() {
2233
+ return this.timings.map((t) => {
2234
+ const desc = t.description ? `;desc="${t.description}"` : "";
2235
+ return `${t.name};dur=${t.durationMs.toFixed(1)}${desc}`;
2236
+ }).join(", ");
2237
+ }
2238
+ /** Returns all log entries collected so far. */
2239
+ getEntries() {
2240
+ return this.entries;
2241
+ }
2242
+ log(level, message, fields) {
2243
+ if (LEVEL_PRIORITY[level] < LEVEL_PRIORITY[this.minLevel]) return;
2244
+ const entry = {
2245
+ level,
2246
+ message,
2247
+ requestId: this.requestId,
2248
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2249
+ fields: fields ? redactSensitive(fields) : void 0
2250
+ };
2251
+ this.entries.push(entry);
2252
+ if (process.env.NODE_ENV === "production") {
2253
+ const output = JSON.stringify(entry);
2254
+ if (level === "error") console.error(output);
2255
+ else if (level === "warn") console.warn(output);
2256
+ else console.log(output);
2257
+ } else {
2258
+ const output = `${`[${level.toUpperCase()}]`} ${message}${entry.fields ? " " + JSON.stringify(entry.fields) : ""}`;
2259
+ if (level === "error") console.error(output);
2260
+ else if (level === "warn") console.warn(output);
2261
+ else console.log(output);
1927
2262
  }
1928
- chunks.push(value);
1929
2263
  }
1930
- } finally {
1931
- try {
1932
- reader.releaseLock();
1933
- } catch {}
1934
- }
1935
- const total = new Uint8Array(totalSize);
1936
- let offset = 0;
1937
- for (const chunk of chunks) {
1938
- total.set(chunk, offset);
1939
- offset += chunk.byteLength;
1940
- }
1941
- return {
1942
- ok: true,
1943
- text: new TextDecoder().decode(total)
1944
2264
  };
2265
+ }));
2266
+ //#endregion
2267
+ //#region src/config/index.ts
2268
+ init_logger();
2269
+ async function loadElurConfig(options = {}) {
2270
+ const initialRoot = (0, node_path.resolve)(options.root ?? process.cwd());
2271
+ const configFile = options.configFile ? (0, node_path.resolve)(initialRoot, options.configFile) : await findConfigFile(initialRoot);
2272
+ let loaded = {};
2273
+ if (configFile) {
2274
+ const result = await (0, vite.loadConfigFromFile)({
2275
+ command: options.command === "build" ? "build" : "serve",
2276
+ mode: options.mode ?? "development"
2277
+ }, configFile, initialRoot);
2278
+ if (!result) throw new Error(`[elur-kit] Could not load config: ${configFile}`);
2279
+ loaded = result.config;
2280
+ }
2281
+ const merged = mergeConfig(loaded, options.overrides ?? {});
2282
+ const root = (0, node_path.resolve)(initialRoot, merged.root ?? ".");
2283
+ const resolved = resolveConfig(root, merged, configFile);
2284
+ await runIntegrationHook(resolved.integrations, "config", [resolved, {
2285
+ root,
2286
+ command: options.command ?? "dev"
2287
+ }]);
2288
+ return resolved;
1945
2289
  }
1946
- function parseFormBody(body) {
1947
- const params = new URLSearchParams(body);
1948
- const result = {};
1949
- for (const [key, value] of params) if (result[key] === void 0) result[key] = value;
1950
- else if (Array.isArray(result[key])) result[key].push(value);
1951
- else result[key] = [result[key], value];
1952
- return result;
2290
+ function resolveConfig(root, config, configFile) {
2291
+ if (config.site) new URL(config.site);
2292
+ const base = normalizeBase(config.base ?? "/");
2293
+ const imageQuality = config.images?.quality ?? 80;
2294
+ if (!Number.isFinite(imageQuality) || imageQuality < 1 || imageQuality > 100) throw new Error("[elur-kit] images.quality must be between 1 and 100");
2295
+ return {
2296
+ root,
2297
+ appDir: resolveInside(root, config.appDir ?? "src/app", "appDir"),
2298
+ islandsDir: resolveInside(root, config.islandsDir ?? "src/islands", "islandsDir"),
2299
+ contentDir: resolveInside(root, config.contentDir ?? "src/content", "contentDir"),
2300
+ publicDir: resolveInside(root, config.publicDir ?? "public", "publicDir"),
2301
+ outDir: resolveInside(root, config.outDir ?? "dist", "outDir"),
2302
+ site: config.site,
2303
+ base,
2304
+ trailingSlash: config.trailingSlash ?? "ignore",
2305
+ output: config.output ?? "static",
2306
+ adapter: config.adapter,
2307
+ images: {
2308
+ formats: config.images?.formats ?? ["webp", "avif"],
2309
+ quality: imageQuality,
2310
+ strict: config.images?.strict ?? false
2311
+ },
2312
+ cache: {
2313
+ dir: resolveInside(root, config.cache?.dir ?? ".elur/cache", "cache.dir"),
2314
+ defaultRevalidate: config.cache?.defaultRevalidate,
2315
+ adapter: config.cache?.adapter
2316
+ },
2317
+ security: {
2318
+ allowedOrigins: config.security?.allowedOrigins ?? [],
2319
+ strictOrigin: config.security?.strictOrigin ?? false,
2320
+ bodyLimit: config.security?.bodyLimit ?? 1048576,
2321
+ headers: config.security?.headers === false ? false : config.security?.headers ?? {}
2322
+ },
2323
+ router: {
2324
+ enabled: config.router?.enabled ?? true,
2325
+ prefetch: config.router?.prefetch ?? true,
2326
+ morph: config.router?.morph ?? false,
2327
+ speculation: config.router?.speculation,
2328
+ loadingIndicator: config.router?.loadingIndicator ?? false
2329
+ },
2330
+ js: config.js ?? "modern",
2331
+ logger: { level: config.logger?.level },
2332
+ redirects: config.redirects ?? [],
2333
+ rewrites: config.rewrites ?? [],
2334
+ streaming: config.streaming ?? false,
2335
+ headers: config.headers ?? [],
2336
+ integrations: config.integrations ?? [],
2337
+ configFile
2338
+ };
1953
2339
  }
1954
- async function parseActionRequest(request, bodyLimit = DEFAULT_BODY_LIMIT) {
1955
- if (request.method !== "POST") return {
1956
- ok: false,
1957
- response: new Response("Method not allowed", {
1958
- status: 405,
1959
- headers: { "Content-Type": "text/plain" }
1960
- })
2340
+ function mergeConfig(base, override) {
2341
+ return {
2342
+ ...base,
2343
+ ...override,
2344
+ images: {
2345
+ ...base.images,
2346
+ ...override.images
2347
+ },
2348
+ cache: {
2349
+ ...base.cache,
2350
+ ...override.cache
2351
+ },
2352
+ security: {
2353
+ ...base.security,
2354
+ ...override.security
2355
+ },
2356
+ router: {
2357
+ ...base.router,
2358
+ ...override.router
2359
+ },
2360
+ logger: {
2361
+ ...base.logger,
2362
+ ...override.logger
2363
+ },
2364
+ redirects: [...override.redirects ?? [], ...base.redirects ?? []],
2365
+ rewrites: [...override.rewrites ?? [], ...base.rewrites ?? []],
2366
+ headers: [...override.headers ?? [], ...base.headers ?? []],
2367
+ integrations: override.integrations ?? base.integrations
1961
2368
  };
1962
- const contentType = request.headers.get("Content-Type") ?? "";
1963
- const wantsJson = (request.headers.get("Accept") ?? "").includes("application/json");
1964
- let name;
1965
- let page;
1966
- let args = [];
1967
- if (contentType.includes("application/json")) {
1968
- const bodyResult = await readBodyWithLimit(request, bodyLimit);
1969
- if (!bodyResult.ok) return {
1970
- ok: false,
1971
- response: bodyResult.response
1972
- };
1973
- let body;
2369
+ }
2370
+ function resolveInside(root, path, name) {
2371
+ const resolved = (0, node_path.isAbsolute)(path) ? (0, node_path.resolve)(path) : (0, node_path.resolve)(root, path);
2372
+ const rel = (0, node_path.relative)(root, resolved);
2373
+ if (rel === ".." || rel.startsWith(`..${node_path.sep}`) || (0, node_path.isAbsolute)(rel)) throw new Error(`[elur-kit] ${name} must stay inside root: ${resolved}`);
2374
+ return resolved;
2375
+ }
2376
+ function normalizeBase(base) {
2377
+ if (!base.startsWith("/")) throw new Error("[elur-kit] base must start with /");
2378
+ return base === "/" ? base : `${base.replace(/\/+$/, "")}/`;
2379
+ }
2380
+ var PREFERRED_CONFIG_FILES = [
2381
+ "elur.config.ts",
2382
+ "elur.config.js",
2383
+ "elur.config.mjs"
2384
+ ];
2385
+ async function findConfigFile(root) {
2386
+ for (const name of PREFERRED_CONFIG_FILES) {
2387
+ const path = (0, node_path.resolve)(root, name);
1974
2388
  try {
1975
- body = JSON.parse(bodyResult.text);
1976
- } catch {
1977
- return {
1978
- ok: false,
1979
- response: new Response("Invalid JSON body", {
1980
- status: 400,
1981
- headers: { "Content-Type": "text/plain" }
1982
- })
1983
- };
1984
- }
1985
- name = body.name;
1986
- page = body.page;
1987
- args = Array.isArray(body.args) ? body.args : [];
1988
- } else if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
1989
- if (contentType.includes("multipart/form-data")) {
1990
- const contentLength = request.headers.get("Content-Length");
1991
- if (contentLength && parseInt(contentLength, 10) > bodyLimit) return {
1992
- ok: false,
1993
- response: new Response("Request body too large", {
1994
- status: 413,
1995
- headers: { "Content-Type": "text/plain" }
1996
- })
1997
- };
1998
- let form;
1999
- try {
2000
- form = await request.formData();
2001
- } catch {
2002
- return {
2003
- ok: false,
2004
- response: new Response("Invalid form body", {
2005
- status: 400,
2006
- headers: { "Content-Type": "text/plain" }
2007
- })
2008
- };
2009
- }
2010
- name = form.get("__elur_js_action_name") ?? void 0;
2011
- page = form.get("__elur_js_action_page") ?? void 0;
2012
- const input = {};
2013
- for (const [key, value] of form) {
2014
- if (key === "__elur_js_action_name" || key === "__elur_js_action_page") continue;
2015
- input[key] = value;
2016
- }
2017
- args = [input];
2018
- } else {
2019
- const bodyResult = await readBodyWithLimit(request, bodyLimit);
2020
- if (!bodyResult.ok) return {
2021
- ok: false,
2022
- response: bodyResult.response
2023
- };
2024
- const form = parseFormBody(bodyResult.text);
2025
- name = form.__elur_js_action_name;
2026
- page = form.__elur_js_action_page;
2027
- const input = {};
2028
- for (const [key, value] of Object.entries(form)) {
2029
- if (key === "__elur_js_action_name" || key === "__elur_js_action_page") continue;
2030
- input[key] = value;
2389
+ await (0, node_fs_promises.access)(path);
2390
+ return path;
2391
+ } catch {}
2392
+ }
2393
+ }
2394
+ //#endregion
2395
+ //#region src/manifest/index.ts
2396
+ init_scan();
2397
+ init_route_scanner();
2398
+ async function createAppManifest(config) {
2399
+ const [routes, actions, islands] = await Promise.all([
2400
+ scanRoutes(config.appDir),
2401
+ scanActions(config.appDir),
2402
+ scanIslands(config.islandsDir)
2403
+ ]);
2404
+ validateManifestRoutes(routes);
2405
+ validateIslands(islands);
2406
+ const manifest = {
2407
+ version: 1,
2408
+ root: config.root,
2409
+ routes,
2410
+ actions,
2411
+ islands,
2412
+ base: config.base,
2413
+ output: config.output
2414
+ };
2415
+ await runIntegrationHook(config.integrations, "routes", [manifest, {
2416
+ root: config.root,
2417
+ command: "build"
2418
+ }]);
2419
+ return manifest;
2420
+ }
2421
+ async function writeAppManifest(manifest, path) {
2422
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
2423
+ await (0, node_fs_promises.writeFile)(path, JSON.stringify(toPortableManifest(manifest), null, 2), "utf8");
2424
+ }
2425
+ async function writeRouteTypes(manifest, path) {
2426
+ const routePaths = manifest.routes.pages.map((route) => JSON.stringify(route.path));
2427
+ const actionNames = Object.values(manifest.actions).flatMap((actions) => Object.keys(actions)).filter((name, index, names) => names.indexOf(name) === index).map((name) => JSON.stringify(name));
2428
+ const source = [
2429
+ `export type ElurRoutePath = ${routePaths.length ? routePaths.join(" | ") : "never"};`,
2430
+ `export type ElurActionName = ${actionNames.length ? actionNames.join(" | ") : "never"};`,
2431
+ "export interface ElurRouteParams { [name: string]: string | string[] | undefined }",
2432
+ ""
2433
+ ].join("\n");
2434
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
2435
+ await (0, node_fs_promises.writeFile)(path, source, "utf8");
2436
+ }
2437
+ function validateManifestRoutes(routes) {
2438
+ const seen = /* @__PURE__ */ new Map();
2439
+ for (const route of routes.pages) {
2440
+ registerRoute(seen, route.path, route.pagePath, "page");
2441
+ assertNotReserved(route.path, route.pagePath);
2442
+ }
2443
+ for (const route of routes.api) {
2444
+ registerRoute(seen, route.path, route.routePath, "API");
2445
+ assertNotReserved(route.path, route.routePath);
2446
+ }
2447
+ }
2448
+ function registerRoute(seen, path, file, kind) {
2449
+ const existing = seen.get(path);
2450
+ if (existing) throw new Error(`[elur-kit] Duplicate ${kind} route "${path}": ${existing} and ${file}`);
2451
+ seen.set(path, file);
2452
+ }
2453
+ function assertNotReserved(path, file) {
2454
+ if (path === "/__elur-js" || path.startsWith("/__elur-js/") || path === "/_elur" || path.startsWith("/_elur/")) throw new Error(`[elur-kit] Reserved route "${path}" declared by ${file}`);
2455
+ }
2456
+ function validateIslands(islands) {
2457
+ const names = /* @__PURE__ */ new Set();
2458
+ for (const island of islands) {
2459
+ if (names.has(island.name)) throw new Error(`[elur-kit] Duplicate island name: ${island.name}`);
2460
+ names.add(island.name);
2461
+ }
2462
+ }
2463
+ function toPortableManifest(manifest) {
2464
+ const relativePath = (path) => path ? (0, node_path.relative)(manifest.root, path).split("\\").join("/") : void 0;
2465
+ const routes = {
2466
+ pages: manifest.routes.pages.map((route) => ({
2467
+ ...route,
2468
+ pagePath: relativePath(route.pagePath),
2469
+ dataPath: relativePath(route.dataPath),
2470
+ actionPath: relativePath(route.actionPath),
2471
+ loadingPath: relativePath(route.loadingPath),
2472
+ layouts: route.layouts.map((layout) => relativePath(layout))
2473
+ })),
2474
+ api: manifest.routes.api.map((route) => ({
2475
+ ...route,
2476
+ routePath: relativePath(route.routePath)
2477
+ })),
2478
+ error404: manifest.routes.error404 ? {
2479
+ ...manifest.routes.error404,
2480
+ pagePath: relativePath(manifest.routes.error404.pagePath),
2481
+ dataPath: relativePath(manifest.routes.error404.dataPath),
2482
+ actionPath: relativePath(manifest.routes.error404.actionPath),
2483
+ loadingPath: relativePath(manifest.routes.error404.loadingPath),
2484
+ layouts: manifest.routes.error404.layouts.map((layout) => relativePath(layout))
2485
+ } : void 0,
2486
+ error500: manifest.routes.error500 ? {
2487
+ ...manifest.routes.error500,
2488
+ pagePath: relativePath(manifest.routes.error500.pagePath),
2489
+ dataPath: relativePath(manifest.routes.error500.dataPath),
2490
+ actionPath: relativePath(manifest.routes.error500.actionPath),
2491
+ loadingPath: relativePath(manifest.routes.error500.loadingPath),
2492
+ layouts: manifest.routes.error500.layouts.map((layout) => relativePath(layout))
2493
+ } : void 0
2494
+ };
2495
+ const actions = {};
2496
+ for (const [page, pageActions] of Object.entries(manifest.actions)) actions[page] = Object.fromEntries(Object.entries(pageActions).map(([name, path]) => [name, relativePath(path)]));
2497
+ return {
2498
+ ...manifest,
2499
+ root: ".",
2500
+ routes,
2501
+ actions,
2502
+ islands: manifest.islands.map((island) => ({
2503
+ ...island,
2504
+ filePath: relativePath(island.filePath)
2505
+ }))
2506
+ };
2507
+ }
2508
+ //#endregion
2509
+ //#region src/runtime/capabilities.ts
2510
+ /** True when the host supports streaming responses (streaming !== false). */
2511
+ function supportsStreaming(capabilities = { streaming: true }) {
2512
+ return capabilities.streaming !== false;
2513
+ }
2514
+ /** True when the host can write to persistent storage (for ISR/cache/image writes). */
2515
+ function supportsPersistentStorage(capabilities) {
2516
+ return capabilities.filesystem === "persistent";
2517
+ }
2518
+ /**
2519
+ * Validates a capability declaration and reports incompatible combinations.
2520
+ * Used by the build pipeline so invalid hosts fail at build time instead of
2521
+ * producing a broken runtime.
2522
+ */
2523
+ function validateCapabilities(capabilities, features = {}) {
2524
+ const problems = [];
2525
+ if (features.isr && !supportsPersistentStorage(capabilities)) problems.push(`ISR requires a persistent filesystem; the host declares filesystem="${capabilities.filesystem}".`);
2526
+ if (features.images && capabilities.imageRuntime === false && capabilities.filesystem === "none") problems.push("On-demand image transforms require either imageRuntime=true or a readable filesystem; the host has neither.");
2527
+ if (features.streaming && capabilities.streaming === false) problems.push("Streaming was requested but the host declares streaming=false.");
2528
+ return {
2529
+ ok: problems.length === 0,
2530
+ problems
2531
+ };
2532
+ }
2533
+ var DEFAULT_CAPABILITIES, SERVERLESS_CAPABILITIES;
2534
+ var init_capabilities = __esmMin((() => {
2535
+ DEFAULT_CAPABILITIES = {
2536
+ streaming: true,
2537
+ filesystem: "persistent",
2538
+ imageRuntime: true,
2539
+ backgroundWork: true
2540
+ };
2541
+ SERVERLESS_CAPABILITIES = {
2542
+ streaming: true,
2543
+ filesystem: "ephemeral",
2544
+ imageRuntime: false,
2545
+ backgroundWork: false,
2546
+ maxBodySize: 1048576
2547
+ };
2548
+ }));
2549
+ //#endregion
2550
+ //#region src/cli/output.ts
2551
+ var useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
2552
+ function paint(code, text) {
2553
+ return useColor ? `\x1b[${code}m${text}\x1b[0m` : text;
2554
+ }
2555
+ var bold = (text) => paint(1, text);
2556
+ var dim = (text) => paint(2, text);
2557
+ var red = (text) => paint(31, text);
2558
+ var green = (text) => paint(32, text);
2559
+ var yellow = (text) => paint(33, text);
2560
+ var cyan = (text) => paint(36, text);
2561
+ var quiet = false;
2562
+ /** Enables quiet mode: only errors are printed. */
2563
+ function setQuiet(value) {
2564
+ quiet = value;
2565
+ }
2566
+ /** Success message with a green check. */
2567
+ function success(message) {
2568
+ if (quiet) return;
2569
+ console.log(`${green("✓")} ${message}`);
2570
+ }
2571
+ /** Indented info line with a cyan arrow. */
2572
+ function info(message) {
2573
+ if (quiet) return;
2574
+ console.log(` ${cyan("→")} ${message}`);
2575
+ }
2576
+ /** Indented detail line (file lists, sub-items). */
2577
+ function detail(message) {
2578
+ if (quiet) return;
2579
+ console.log(dim(` - ${message}`));
2580
+ }
2581
+ /** Lifecycle event with a dim bracket tag, e.g. [dev], [change]. */
2582
+ function event(tag, message) {
2583
+ if (quiet) return;
2584
+ console.log(`${dim(`[${tag}]`)} ${message}`);
2585
+ }
2586
+ /** Warning; suppressed in quiet mode. */
2587
+ function warn(message) {
2588
+ if (quiet) return;
2589
+ console.warn(`${yellow("!")} ${message}`);
2590
+ }
2591
+ /** Error; always printed, even in quiet mode. */
2592
+ function error(message) {
2593
+ console.error(`${red("✗")} ${message}`);
2594
+ }
2595
+ /** Formats a byte count as "640 B", "1.5 kB", "2.3 MB". */
2596
+ function formatBytes(bytes) {
2597
+ if (bytes < 1024) return `${bytes} B`;
2598
+ if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} kB`;
2599
+ return `${(bytes / 1048576).toFixed(1)} MB`;
2600
+ }
2601
+ /** Formats a duration as "45ms" or "1.23s". */
2602
+ function formatDuration(ms) {
2603
+ if (ms < 1e3) return `${Math.round(ms)}ms`;
2604
+ return `${(ms / 1e3).toFixed(2)}s`;
2605
+ }
2606
+ /** Build phase line: checkmark + label + dim duration. */
2607
+ function phase(label, durationMs) {
2608
+ if (quiet) return;
2609
+ console.log(` ${green("✓")} ${label} ${dim(formatDuration(durationMs))}`);
2610
+ }
2611
+ var MAX_FILE_ROWS = 20;
2612
+ var SHOWN_FILE_ROWS = 10;
2613
+ /**
2614
+ * Renders the generated-file list as aligned "path size" rows (plain text,
2615
+ * no color). With more than MAX_FILE_ROWS entries, shows the SHOWN_FILE_ROWS
2616
+ * largest plus a "… and N more" line.
2617
+ */
2618
+ function fileRows(files, max = MAX_FILE_ROWS, shown = SHOWN_FILE_ROWS) {
2619
+ const sorted = files.length > max ? [...files].sort((a, b) => b.bytes - a.bytes) : files;
2620
+ const visible = sorted.slice(0, files.length > max ? shown : sorted.length);
2621
+ const pathWidth = Math.max(...visible.map((f) => f.path.length), 0);
2622
+ const sizeWidth = Math.max(...visible.map((f) => formatBytes(f.bytes).length), 0);
2623
+ const rows = visible.map((f) => `${f.path.padEnd(pathWidth)} ${formatBytes(f.bytes).padStart(sizeWidth)}`);
2624
+ const hidden = files.length - visible.length;
2625
+ if (hidden > 0) rows.push(`… and ${hidden} more`);
2626
+ return rows;
2627
+ }
2628
+ /** Prints the generated-file list: dim paths, aligned sizes. */
2629
+ function fileList(files) {
2630
+ if (quiet || files.length === 0) return;
2631
+ for (const row of fileRows(files)) {
2632
+ const sizeMatch = /^(.*?)( \S+)$/.exec(row);
2633
+ if (sizeMatch) console.log(` ${dim(sizeMatch[1])} ${dim(sizeMatch[2])}`);
2634
+ else console.log(` ${dim(row)}`);
2635
+ }
2636
+ }
2637
+ /**
2638
+ * Plain-text lines of the server startup banner (Astro-style, no box):
2639
+ *
2640
+ * elur-kit v2.4.10 dev server running at:
2641
+ * → Local: http://localhost:3000/
2642
+ * → Network: http://192.168.1.20:3000/
2643
+ */
2644
+ function serverBannerLines(options) {
2645
+ const lines = [`${options.name} ${options.version} ${options.command} server running at:`, ""];
2646
+ const labelWidth = options.networkUrl ? 8 : 6;
2647
+ lines.push(` → ${"Local:".padEnd(labelWidth)} ${options.localUrl}`);
2648
+ if (options.networkUrl) lines.push(` → ${"Network:".padEnd(labelWidth)} ${options.networkUrl}`);
2649
+ return lines;
2650
+ }
2651
+ /** Prints the server startup banner with brand colors. */
2652
+ function serverBanner(options) {
2653
+ if (quiet) return;
2654
+ const [title, blank, ...urls] = serverBannerLines(options);
2655
+ console.log();
2656
+ console.log(` ${bold(cyan(title))}`);
2657
+ console.log(blank);
2658
+ for (const line of urls) {
2659
+ const arrowEnd = line.indexOf("→") + 1;
2660
+ console.log(` ${cyan("→")}${dim(line.slice(arrowEnd))}`);
2661
+ }
2662
+ }
2663
+ /** First external (LAN) IPv4 address, for the Network URL. */
2664
+ function getNetworkAddress() {
2665
+ for (const infos of Object.values((0, node_os.networkInterfaces)())) for (const info of infos ?? []) if (info.family === "IPv4" && !info.internal) return info.address;
2666
+ }
2667
+ /**
2668
+ * Listens on host:port, falling back to the next port while the failure is
2669
+ * EADDRINUSE. Resolves with the port actually bound. Rejects with the
2670
+ * original error for non-port failures or when the range is exhausted.
2671
+ */
2672
+ function listenWithFallback(server, host, port, options = {}) {
2673
+ const maxTries = options.maxTries ?? 20;
2674
+ return new Promise((resolvePromise, reject) => {
2675
+ let attempt = 0;
2676
+ let candidate = port;
2677
+ const onListening = () => {
2678
+ server.removeListener("error", onError);
2679
+ resolvePromise(candidate);
2680
+ };
2681
+ const onError = (err) => {
2682
+ server.removeListener("listening", onListening);
2683
+ if (err.code === "EADDRINUSE" && attempt < maxTries) {
2684
+ attempt++;
2685
+ const nextPort = port + attempt;
2686
+ options.onFallback?.(nextPort - 1, nextPort);
2687
+ tryListen(nextPort);
2688
+ return;
2031
2689
  }
2032
- args = [input];
2033
- }
2034
- } else {
2035
- const bodyResult = await readBodyWithLimit(request, bodyLimit);
2036
- if (!bodyResult.ok) return {
2037
- ok: false,
2038
- response: bodyResult.response
2690
+ reject(err);
2039
2691
  };
2040
- const form = parseFormBody(bodyResult.text);
2041
- name = form.__elur_js_action_name;
2042
- page = form.__elur_js_action_page;
2043
- const input = {};
2044
- for (const [key, value] of Object.entries(form)) {
2045
- if (key === "__elur_js_action_name" || key === "__elur_js_action_page") continue;
2046
- input[key] = value;
2692
+ const tryListen = (next) => {
2693
+ candidate = next;
2694
+ server.once("error", onError);
2695
+ server.once("listening", onListening);
2696
+ server.listen(candidate, host);
2697
+ };
2698
+ tryListen(port);
2699
+ });
2700
+ }
2701
+ //#endregion
2702
+ //#region src/build/vite-build.ts
2703
+ var vite_build_exports = /* @__PURE__ */ __exportAll({
2704
+ beginAtomicStage: () => beginAtomicStage,
2705
+ buildClientBundle: () => buildClientBundle,
2706
+ copyPublicAssets: () => copyPublicAssets,
2707
+ loadUserConfig: () => loadUserConfig,
2708
+ resolveClientInputs: () => resolveClientInputs
2709
+ });
2710
+ /**
2711
+ * Build the client hydration bundle using the Vite JavaScript API.
2712
+ *
2713
+ * The user's config is loaded programmatically and the elur interpolation
2714
+ * plugin is injected so partial attribute interpolations inside islands are
2715
+ * transformed before reaching the browser.
2716
+ */
2717
+ async function buildClientBundle(options) {
2718
+ const log = options.logPrefix ?? "[client]";
2719
+ const quiet = options.quiet ?? false;
2720
+ if (!quiet) console.log(`${log} Building hydration bundle...`);
2721
+ const userConfig = options.userConfigPath ? await loadUserConfig(options.userConfigPath, options.root) : defaultClientConfig(options.defaultInputs);
2722
+ const pluginOptions = shouldUseLegacyInterpolation(options.interpolation ?? "auto") ? elurJsInterpolationPlugin({
2723
+ appDir: options.appDir,
2724
+ islandsDir: options.islandsDir
2725
+ }) : [];
2726
+ const config = {
2727
+ ...userConfig,
2728
+ root: options.root,
2729
+ base: options.base ?? userConfig.base ?? "/",
2730
+ logLevel: quiet ? "silent" : userConfig.logLevel,
2731
+ build: {
2732
+ ...userConfig.build ?? {},
2733
+ outDir: options.outDir,
2734
+ emptyOutDir: true
2735
+ },
2736
+ plugins: [...userConfig.plugins ?? [], pluginOptions],
2737
+ configFile: false
2738
+ };
2739
+ const result = await (0, vite.build)(config);
2740
+ const outputCount = (Array.isArray(result) ? result : [result]).reduce((n, r) => n + ("output" in r ? r.output?.length ?? 0 : 0), 0);
2741
+ if (!quiet) console.log(`${log} ✓ ${outputCount} asset(s) emitted → ${(0, node_path.relative)(options.root, options.outDir)}`);
2742
+ return {
2743
+ outDir: options.outDir,
2744
+ outputCount
2745
+ };
2746
+ }
2747
+ async function loadUserConfig(path, _root) {
2748
+ const mod = await import(path);
2749
+ const raw = mod.default ?? mod;
2750
+ const resolved = typeof raw === "function" ? await raw({
2751
+ command: "build",
2752
+ mode: "production"
2753
+ }) : raw;
2754
+ return (resolved && typeof resolved.then === "function" ? await resolved : resolved) ?? {};
2755
+ }
2756
+ /**
2757
+ * Resolves a user Vite config's `build.rollupOptions.input` to a list of
2758
+ * absolute entry paths. Used to detect whether the bundle will emit the
2759
+ * generated router module as its own chunk (split build) or not (legacy
2760
+ * single-entry bundle — the router stays embedded in the entry).
2761
+ */
2762
+ async function resolveClientInputs(userConfigPath, root) {
2763
+ const input = (await loadUserConfig(userConfigPath, root)).build?.rollupOptions?.input;
2764
+ if (!input || typeof input === "string") return input ? [(0, node_path.resolve)(root, input)] : [];
2765
+ return (Array.isArray(input) ? input : Object.values(input)).filter((v) => typeof v === "string").map((v) => (0, node_path.resolve)(root, v));
2766
+ }
2767
+ /**
2768
+ * The synthesized client bundle config used when the project does not ship
2769
+ * its own `vite.client.config.*`: named inputs with `[name].js` filenames in
2770
+ * ES format — the same contract the docs give to hand-written client
2771
+ * configs, so `entry-client` → `entry-client.js` and `router` → `router.js`.
2772
+ */
2773
+ function defaultClientConfig(defaultInputs) {
2774
+ return { build: { rollupOptions: {
2775
+ input: defaultInputs ?? {},
2776
+ output: {
2777
+ entryFileNames: "[name].js",
2778
+ format: "es"
2047
2779
  }
2048
- args = [input];
2049
- }
2050
- if (!name || typeof name !== "string") return {
2051
- ok: false,
2052
- response: new Response("Missing action name", {
2053
- status: 400,
2054
- headers: { "Content-Type": "text/plain" }
2055
- })
2780
+ } } };
2781
+ }
2782
+ /**
2783
+ * Prepare an atomic staging directory for build output.
2784
+ *
2785
+ * Usage:
2786
+ * const stage = await beginAtomicStage({ outDir });
2787
+ * try {
2788
+ * await buildInto(stage.tempDir);
2789
+ * await stage.commit();
2790
+ * } catch (err) {
2791
+ * await stage.rollback();
2792
+ * throw err;
2793
+ * }
2794
+ */
2795
+ async function beginAtomicStage(options) {
2796
+ const outDir = (0, node_path.resolve)(options.outDir);
2797
+ const tempDir = (0, node_path.resolve)(options.tempDir ?? (0, node_path.join)((0, node_path.dirname)(outDir), `.${basename(outDir)}.tmp-${process.pid}`));
2798
+ await (0, node_fs_promises.rm)(tempDir, {
2799
+ recursive: true,
2800
+ force: true
2801
+ });
2802
+ await (0, node_fs_promises.mkdir)(tempDir, { recursive: true });
2803
+ const commit = async () => {
2804
+ const backup = options.keepExisting && (0, node_fs.existsSync)(outDir) ? `${outDir}.bak-${process.pid}` : void 0;
2805
+ if (backup) {
2806
+ await (0, node_fs_promises.rm)(backup, {
2807
+ recursive: true,
2808
+ force: true
2809
+ });
2810
+ await safeRename(outDir, backup);
2811
+ }
2812
+ try {
2813
+ await safeRename(tempDir, outDir);
2814
+ } catch (err) {
2815
+ if (isCrossDevice(err)) {
2816
+ await (0, node_fs_promises.cp)(tempDir, outDir, {
2817
+ recursive: true,
2818
+ force: true
2819
+ });
2820
+ await (0, node_fs_promises.rm)(tempDir, {
2821
+ recursive: true,
2822
+ force: true
2823
+ });
2824
+ } else {
2825
+ if (backup) await safeRename(backup, outDir);
2826
+ throw err;
2827
+ }
2828
+ }
2829
+ if (backup) await (0, node_fs_promises.rm)(backup, {
2830
+ recursive: true,
2831
+ force: true
2832
+ });
2833
+ };
2834
+ const rollback = async () => {
2835
+ await (0, node_fs_promises.rm)(tempDir, {
2836
+ recursive: true,
2837
+ force: true
2838
+ });
2056
2839
  };
2057
2840
  return {
2058
- ok: true,
2059
- name,
2060
- page,
2061
- args,
2062
- wantsJson
2841
+ tempDir,
2842
+ commit,
2843
+ rollback
2063
2844
  };
2064
2845
  }
2065
- /**
2066
- * Handles a POST request to the server action endpoint.
2067
- *
2068
- * Accepts both JSON requests (`{ name, page?, args }`) and HTML form submissions
2069
- * for progressive enhancement. The provided resolver looks up the action
2070
- * implementation, invokes it with the supplied arguments and returns the result
2071
- * as JSON or redirects back to the request origin for form submissions.
2072
- *
2073
- * Origin verification (CSRF protection) runs before parsing the body: any
2074
- * cross-origin POST is rejected with 403 unless its origin is allow-listed via
2075
- * `security.allowedOrigins`.
2076
- *
2077
- * For progressive-enhancement form submissions that fail, the failure payload
2078
- * is relayed back via a short-lived `__elur_js_action_error` cookie (SameSite=Lax,
2079
- * Max-Age=15s) instead of a query param, so errors do not leak into browser
2080
- * history, server logs or third-party Referer headers.
2081
- */
2082
- async function handleActionRequest(request, resolveAction, security = {}) {
2083
- const originError = verifyOrigin(request, security);
2084
- if (originError) return originForbidden(originError);
2085
- const parsed = await parseActionRequest(request, security.bodyLimit ?? DEFAULT_BODY_LIMIT);
2086
- if (!parsed.ok) return parsed.response;
2087
- const { name, page, args, wantsJson } = parsed;
2846
+ function basename(path) {
2847
+ const parts = path.split(/[\\/]+/).filter(Boolean);
2848
+ return parts[parts.length - 1] ?? "output";
2849
+ }
2850
+ async function safeRename(src, dest) {
2851
+ await (0, node_fs_promises.rm)(dest, {
2852
+ recursive: true,
2853
+ force: true
2854
+ });
2088
2855
  try {
2089
- const action = await resolveAction(name, page);
2090
- if (!action) {
2091
- const message = page ? `Action not found: ${name} (page: ${page})` : `Action not found: ${name}`;
2092
- return new Response(message, {
2093
- status: 404,
2094
- headers: { "Content-Type": "text/plain" }
2095
- });
2096
- }
2097
- const result = await action(...args);
2098
- if (isActionFailure(result)) {
2099
- if (wantsJson) return new Response(JSON.stringify({
2100
- __elur_js_action_failure: true,
2101
- status: result.status,
2102
- data: result.data
2103
- }), {
2104
- status: result.status,
2105
- headers: { "Content-Type": "application/json" }
2106
- });
2107
- const referer = request.headers.get("Referer") ?? "/";
2108
- const url = new URL(referer, "http://localhost");
2109
- const { value } = encodeActionErrorCookie(result.data, result.status);
2110
- return new Response(null, {
2111
- status: 303,
2112
- headers: {
2113
- Location: url.pathname + url.search,
2114
- "Content-Type": "text/plain",
2115
- "Set-Cookie": setActionErrorCookieHeader(value)
2116
- }
2117
- });
2118
- }
2119
- if (isRedirectResponse(result)) {
2120
- if (wantsJson) return new Response(JSON.stringify({
2121
- __elur_js_action_redirect: true,
2122
- status: result.status,
2123
- location: result.location
2124
- }), {
2125
- status: 200,
2126
- headers: { "Content-Type": "application/json" }
2856
+ await (0, node_fs_promises.rename)(src, dest);
2857
+ } catch (err) {
2858
+ if (isCrossDevice(err)) {
2859
+ await (0, node_fs_promises.cp)(src, dest, {
2860
+ recursive: true,
2861
+ force: true
2127
2862
  });
2128
- return new Response(null, {
2129
- status: result.status,
2130
- headers: {
2131
- Location: result.location,
2132
- "Content-Type": "text/plain"
2133
- }
2863
+ await (0, node_fs_promises.rm)(src, {
2864
+ recursive: true,
2865
+ force: true
2134
2866
  });
2135
- }
2136
- if (wantsJson) return new Response(JSON.stringify(result ?? null), {
2137
- status: 200,
2138
- headers: { "Content-Type": "application/json" }
2139
- });
2140
- const referer = request.headers.get("Referer") ?? "/";
2141
- return new Response(null, {
2142
- status: 303,
2143
- headers: {
2144
- Location: typeof result === "string" ? result : referer,
2145
- "Content-Type": "text/plain"
2146
- }
2147
- });
2148
- } catch (err) {
2149
- console.error("[elur-kit] Action error:", err);
2150
- return publicErrorResponse(err, { includeDetail: false });
2867
+ } else throw err;
2151
2868
  }
2152
2869
  }
2153
- var DEFAULT_BODY_LIMIT;
2154
- var init_server = __esmMin((() => {
2155
- init_errors();
2156
- init_origin();
2157
- init_error_store();
2158
- DEFAULT_BODY_LIMIT = 1048576;
2159
- }));
2160
- //#endregion
2161
- //#region src/cache.ts
2162
- function cachePath(cacheDir, pathname) {
2163
- const key = (0, node_crypto.createHash)("sha256").update(pathname).digest("hex");
2164
- return (0, node_path.join)(cacheDir, `${key}.html.json`);
2870
+ function isCrossDevice(err) {
2871
+ return err?.code === "EXDEV";
2165
2872
  }
2166
- async function getCachedHtml(cacheDir, pathname) {
2167
- const path = cachePath(cacheDir, pathname);
2873
+ /**
2874
+ * Copy the public directory into the output directory.
2875
+ * Returns the number of files copied.
2876
+ */
2877
+ async function copyPublicAssets(options) {
2168
2878
  try {
2169
- const raw = await (0, node_fs_promises.readFile)(path, "utf8");
2170
- const entry = JSON.parse(raw);
2171
- if (Date.now() - entry.generatedAt < entry.revalidate * 1e3) return entry;
2172
- } catch {}
2879
+ await (0, node_fs_promises.access)(options.publicDir);
2880
+ if (!(await (0, node_fs_promises.stat)(options.publicDir)).isDirectory()) return 0;
2881
+ } catch {
2882
+ return 0;
2883
+ }
2884
+ await (0, node_fs_promises.mkdir)(options.outDir, { recursive: true });
2885
+ await (0, node_fs_promises.cp)(options.publicDir, options.outDir, {
2886
+ recursive: true,
2887
+ force: true
2888
+ });
2889
+ return countFiles(options.outDir);
2173
2890
  }
2174
- async function setCachedHtml(cacheDir, pathname, html, revalidate) {
2175
- const path = cachePath(cacheDir, pathname);
2176
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
2177
- const entry = {
2178
- html,
2179
- generatedAt: Date.now(),
2180
- revalidate
2181
- };
2182
- const temporaryPath = `${path}.${process.pid}.${(0, node_crypto.randomUUID)()}.tmp`;
2183
- try {
2184
- await (0, node_fs_promises.writeFile)(temporaryPath, JSON.stringify(entry), "utf8");
2185
- await (0, node_fs_promises.rename)(temporaryPath, path);
2186
- } finally {
2187
- await (0, node_fs_promises.rm)(temporaryPath, { force: true });
2891
+ async function countFiles(dir) {
2892
+ const { readdir } = await import("node:fs/promises");
2893
+ let count = 0;
2894
+ async function walk(d) {
2895
+ const entries = await readdir(d, { withFileTypes: true });
2896
+ for (const entry of entries) {
2897
+ const path = (0, node_path.join)(d, entry.name);
2898
+ if (entry.isDirectory()) await walk(path);
2899
+ else count++;
2900
+ }
2188
2901
  }
2902
+ await walk(dir);
2903
+ return count;
2189
2904
  }
2190
- var init_cache = __esmMin((() => {}));
2905
+ var init_vite_build = __esmMin((() => {
2906
+ init_interpolation_plugin();
2907
+ }));
2191
2908
  //#endregion
2192
2909
  //#region src/ssr/match.ts
2193
2910
  /**
@@ -2228,174 +2945,53 @@ function matchApiRoute(pathname, routes) {
2228
2945
  * Safely decodes a URI component. If decoding fails (malformed % sequences),
2229
2946
  * returns the original string rather than throwing (runtime-security §10).
2230
2947
  */
2231
- function safeDecodeURIComponent(segment) {
2232
- try {
2233
- return decodeURIComponent(segment);
2234
- } catch {
2235
- return segment;
2236
- }
2237
- }
2238
- function specificity(path) {
2239
- return path.split("/").filter(Boolean).reduce((score, segment) => {
2240
- if (segment.endsWith("*")) return score;
2241
- if (segment.startsWith(":")) return score + 1;
2242
- return score + 2;
2243
- }, 0);
2244
- }
2245
- function tryMatch(requestSegments, routeSegments, optionalCatchAll = false) {
2246
- const params = {};
2247
- let i = 0;
2248
- for (let r = 0; r < routeSegments.length; r++) {
2249
- const routeSeg = routeSegments[r];
2250
- if (routeSeg.endsWith("*")) {
2251
- const name = routeSeg.slice(1, -1);
2252
- const rest = requestSegments.slice(i);
2253
- if (rest.length === 0 && !optionalCatchAll) return void 0;
2254
- params[name] = rest.length > 0 ? rest : [];
2255
- return params;
2256
- }
2257
- if (routeSeg.startsWith(":")) {
2258
- const requestSeg = requestSegments[i];
2259
- if (requestSeg === void 0) return void 0;
2260
- params[routeSeg.slice(1)] = requestSeg;
2261
- i++;
2262
- continue;
2263
- }
2264
- if (routeSeg !== requestSegments[i]) return;
2265
- i++;
2266
- }
2267
- if (i !== requestSegments.length) return void 0;
2268
- return params;
2269
- }
2270
- var init_match = __esmMin((() => {}));
2271
- //#endregion
2272
- //#region src/ssr/stream.ts
2273
- /** Builds the concrete URL path for a route pattern given matched params. */
2274
- function buildConcretePath(routePath, params) {
2275
- return routePath.replace(/:([a-zA-Z0-9_]+)(\*)?/g, (_m, name, catchAll) => {
2276
- const value = params[name];
2277
- if (value === void 0 || value === null) return "";
2278
- return catchAll ? Array.isArray(value) ? value.join("/") : String(value) : String(value);
2279
- });
2280
- }
2281
- function streamingScript(page, search) {
2282
- return `<script type="module">${`
2283
- async function __elurJsStreamRender() {
2284
- try {
2285
- const url = "/__elur-js/render?page=" + encodeURIComponent(${JSON.stringify(page)}) + "&search=" + encodeURIComponent(${JSON.stringify(search)});
2286
- const res = await fetch(url);
2287
- if (!res.ok) throw new Error("Streaming render failed: " + res.status);
2288
- const html = await res.text();
2289
- const app = document.getElementById("app");
2290
- if (app) app.innerHTML = html;
2291
- document.dispatchEvent(new CustomEvent("elur:rendered"));
2292
- } catch (err) {
2293
- console.error("[elur-kit] streaming render failed", err);
2294
- }
2295
- }
2296
- __elurJsStreamRender();
2297
- `}<\/script>`;
2298
- }
2299
- /**
2300
- * Render a page shell that shows the loading boundary while the real content
2301
- * is fetched and injected by the client.
2302
- */
2303
- async function renderStreamingPage(options) {
2304
- const { route, params, searchParams, config, importer = defaultImport, actions } = options;
2305
- if (!route.loadingPath) throw new Error("Cannot stream a page without a loading.ts boundary");
2306
- const { default: Loading } = await importer(route.loadingPath);
2307
- const body = `<div id="elur-loading">${await renderToString(() => Loading())}</div>${streamingScript(buildConcretePath(route.path, params), searchParams.toString())}`;
2308
- const htmlAttributes = {};
2309
- const headScripts = [];
2310
- const headLinks = [];
2311
- if (route.layouts.length > 0) {
2312
- const rootLayout = route.layouts[0];
2313
- const dataPath = rootLayout.replace(/layout\.ts$/, "layout.data.ts");
2314
- if (dataPath !== rootLayout) try {
2315
- const mod = await importer(dataPath);
2316
- const layoutData = mod.load ? await mod.load({
2317
- params,
2318
- searchParams,
2319
- request: options.request
2320
- }) : void 0;
2321
- if (layoutData && typeof layoutData === "object") {
2322
- const attrs = layoutData.htmlAttributes;
2323
- if (attrs) Object.assign(htmlAttributes, attrs);
2324
- const scripts = layoutData.headScripts;
2325
- if (Array.isArray(scripts)) headScripts.push(...scripts);
2326
- const links = layoutData.headLinks;
2327
- if (Array.isArray(links)) headLinks.push(...links);
2328
- }
2329
- } catch {}
2330
- }
2331
- return documentShell({
2332
- title: "Loading...",
2333
- lang: config.lang,
2334
- body,
2335
- data: {
2336
- __elur_js_streaming: true,
2337
- page: route.path
2338
- },
2339
- actions,
2340
- htmlAttributes,
2341
- headScripts,
2342
- headLinks,
2343
- clientEntry: config.clientEntry
2344
- });
2345
- }
2346
- /**
2347
- * Render only the inner HTML body for a page. Used by the streaming endpoint
2348
- * to inject the real content into the shell.
2349
- */
2350
- async function renderPageBody(options) {
2351
- const { routes, pathname, searchParams, config, actions, importer = defaultImport, request } = options;
2352
- const match = matchRoute(pathname, routes.pages);
2353
- if (!match) throw new RouteNotFoundError(pathname);
2354
- const result = await renderPage({
2355
- route: match.route,
2356
- params: match.params,
2357
- searchParams,
2358
- config,
2359
- actions,
2360
- importer,
2361
- request
2362
- });
2363
- if (result.response) return {
2364
- body: "",
2365
- title: "",
2366
- response: result.response
2367
- };
2368
- const bodyMatch = result.html.match(/<div id="app">([\s\S]*)<\/div>\s*(<script|$)/);
2369
- const body = bodyMatch ? bodyMatch[1].trim() : result.html;
2370
- const titleMatch = result.html.match(/<title[^>]*>([^<]*)<\/title>/);
2371
- return {
2372
- body,
2373
- title: titleMatch ? titleMatch[1] : result.resolvedTitle ?? "",
2374
- fullHtml: result.html,
2375
- clearActionErrorCookie: result.clearActionErrorCookie,
2376
- head: result.head
2377
- };
2948
+ function safeDecodeURIComponent(segment) {
2949
+ try {
2950
+ return decodeURIComponent(segment);
2951
+ } catch {
2952
+ return segment;
2953
+ }
2378
2954
  }
2379
- var defaultImport, RouteNotFoundError;
2380
- var init_stream = __esmMin((() => {
2381
- init_render_to_string();
2382
- init_document_shell();
2383
- init_match();
2384
- init_render();
2385
- defaultImport = (path) => import(path);
2386
- RouteNotFoundError = class extends Error {
2387
- constructor(pathname) {
2388
- super(`No route found for ${pathname}`);
2389
- this.name = "RouteNotFoundError";
2955
+ function specificity(path) {
2956
+ return path.split("/").filter(Boolean).reduce((score, segment) => {
2957
+ if (segment.endsWith("*")) return score;
2958
+ if (segment.startsWith(":")) return score + 1;
2959
+ return score + 2;
2960
+ }, 0);
2961
+ }
2962
+ function tryMatch(requestSegments, routeSegments, optionalCatchAll = false) {
2963
+ const params = {};
2964
+ let i = 0;
2965
+ for (let r = 0; r < routeSegments.length; r++) {
2966
+ const routeSeg = routeSegments[r];
2967
+ if (routeSeg.endsWith("*")) {
2968
+ const name = routeSeg.slice(1, -1);
2969
+ const rest = requestSegments.slice(i);
2970
+ if (rest.length === 0 && !optionalCatchAll) return void 0;
2971
+ params[name] = rest.length > 0 ? rest : [];
2972
+ return params;
2390
2973
  }
2391
- };
2392
- }));
2974
+ if (routeSeg.startsWith(":")) {
2975
+ const requestSeg = requestSegments[i];
2976
+ if (requestSeg === void 0) return void 0;
2977
+ params[routeSeg.slice(1)] = requestSeg;
2978
+ i++;
2979
+ continue;
2980
+ }
2981
+ if (routeSeg !== requestSegments[i]) return;
2982
+ i++;
2983
+ }
2984
+ if (i !== requestSegments.length) return void 0;
2985
+ return params;
2986
+ }
2987
+ var init_match = __esmMin((() => {}));
2393
2988
  //#endregion
2394
2989
  //#region src/middleware/index.ts
2395
- init_server();
2396
- init_cache();
2397
- init_stream();
2398
- init_match();
2990
+ var middleware_exports = /* @__PURE__ */ __exportAll({
2991
+ loadMiddleware: () => loadMiddleware,
2992
+ matchesMiddleware: () => matchesMiddleware,
2993
+ runMiddleware: () => runMiddleware
2994
+ });
2399
2995
  /**
2400
2996
  * Loads the user's `src/middleware.ts` module. Returns `null` if no middleware
2401
2997
  * file exists. Distinguishes "file not found" from "file has errors" (§6):
@@ -2484,854 +3080,731 @@ async function runMiddleware(middleware, request, params) {
2484
3080
  }
2485
3081
  }
2486
3082
  }
3083
+ var init_middleware = __esmMin((() => {
3084
+ init_match();
3085
+ }));
2487
3086
  //#endregion
2488
- //#region src/runtime/node-http.ts
2489
- var GlobalAbortController = globalThis.AbortController ?? AbortController;
2490
- function incomingMessageToRequest(req, body) {
2491
- const headers = new Headers();
2492
- for (let index = 0; index < req.rawHeaders.length; index += 2) headers.append(req.rawHeaders[index], req.rawHeaders[index + 1]);
2493
- const controller = new GlobalAbortController();
2494
- req.once("aborted", () => controller.abort());
2495
- req.once("close", () => {
2496
- if (!req.complete) controller.abort();
2497
- });
2498
- const protocol = req.socket.encrypted ? "https" : "http";
2499
- const init = {
2500
- method: req.method ?? "GET",
2501
- headers,
2502
- signal: controller.signal
2503
- };
2504
- if (body !== void 0 && body !== null && init.method !== "GET" && init.method !== "HEAD") init.body = body;
2505
- return new Request(`${protocol}://${headers.get("host") ?? "localhost"}${req.url ?? "/"}`, init);
2506
- }
2507
- //#endregion
2508
- //#region src/runtime/static.ts
2509
- function isInside(root, candidate) {
2510
- return candidate === root || candidate.startsWith(`${root}${node_path.sep}`);
2511
- }
2512
- function decodePathname(pathname) {
2513
- try {
2514
- const decoded = decodeURIComponent(pathname);
2515
- if (decoded.includes("\0") || decoded.includes("\\") || /%(?:00|2e|2f|5c)/i.test(decoded)) return null;
2516
- if (decoded.split("/").some((segment) => segment === "..")) return null;
2517
- return decoded;
2518
- } catch {
2519
- return null;
2520
- }
2521
- }
2522
- async function resolveStaticFile(root, pathname) {
2523
- const decoded = decodePathname(pathname);
2524
- if (decoded === null) return null;
2525
- const resolvedRoot = (0, node_path.resolve)(root);
2526
- const relativePath = decoded.replace(/^\/+/, "");
2527
- let candidate = (0, node_path.resolve)(resolvedRoot, relativePath);
2528
- if (!isInside(resolvedRoot, candidate)) return null;
2529
- try {
2530
- if ((await (0, node_fs_promises.stat)(candidate)).isDirectory()) candidate = (0, node_path.resolve)(candidate, "index.html");
2531
- } catch {
2532
- if (decoded.endsWith("/") || (0, node_path.extname)(decoded) === "") candidate = (0, node_path.resolve)(candidate, "index.html");
2533
- }
2534
- if (!isInside(resolvedRoot, candidate)) return null;
2535
- try {
2536
- const [canonicalRoot, canonicalCandidate, candidateStat] = await Promise.all([
2537
- (0, node_fs_promises.realpath)(resolvedRoot),
2538
- (0, node_fs_promises.realpath)(candidate),
2539
- (0, node_fs_promises.stat)(candidate)
2540
- ]);
2541
- if (!candidateStat.isFile() || !isInside(canonicalRoot, canonicalCandidate)) return null;
2542
- return canonicalCandidate;
2543
- } catch {
2544
- return null;
2545
- }
2546
- }
2547
- var init_static = __esmMin((() => {}));
2548
- //#endregion
2549
- //#region src/ssr/server.ts
2550
- init_route_scanner();
2551
- init_scan();
2552
- init_match();
2553
- init_render();
2554
- init_static();
2555
- init_errors();
3087
+ //#region src/errors.ts
2556
3088
  /**
2557
- * Create an SSR server that renders pages on demand and serves static files.
3089
+ * Type guard for action failures. Uses the marker field so it works across
3090
+ * bundling boundaries where `instanceof` fails.
2558
3091
  */
2559
- async function createSsrServer(options) {
2560
- const routes = await scanRoutes(options.appDir);
2561
- const actions = await scanActions(options.appDir);
2562
- const publicActions = actionNames(actions);
2563
- const middleware = options.root ? await loadMiddleware(options.root) : null;
2564
- const resolveAction = async (name, page) => {
2565
- const pageKey = resolveActionPageKey(page, routes);
2566
- const pageActions = pageKey ? actions[pageKey] : Object.values(actions).find((p) => p[name]) ?? void 0;
2567
- const actionPath = pageActions ? pageActions[name] : void 0;
2568
- if (!actionPath) return void 0;
2569
- const action = (await import(actionPath))[name];
2570
- if (typeof action === "function") return action;
2571
- };
2572
- const server = (0, node_http.createServer)(async (req, res) => {
2573
- let urlPath = req.url ?? "/";
2574
- if (urlPath.includes("?")) urlPath = urlPath.split("?")[0];
2575
- if (urlPath === "/__elur-js/actions" && req.method === "POST") {
2576
- try {
2577
- const response = await handleActionRequest(incomingMessageToRequest(req, await readRequestBody$1(req)), resolveAction, options.actionSecurity);
2578
- res.writeHead(response.status, Object.fromEntries(response.headers.entries()));
2579
- res.end(await response.text());
2580
- } catch (err) {
2581
- console.error("[action] error handling", err);
2582
- res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
2583
- res.end(toPublicErrorInfo(err).message);
2584
- }
2585
- return;
2586
- }
2587
- if (urlPath === "/__elur-js/render") {
2588
- const renderUrl = new URL(req.url ?? "/", "http://localhost");
2589
- const page = renderUrl.searchParams.get("page") ?? "/";
2590
- const search = renderUrl.searchParams.get("search") ?? "";
2591
- const wantsJson = (req.headers["accept"] ?? "").includes("application/json");
2592
- try {
2593
- const request = incomingMessageToRequest(req);
2594
- let body;
2595
- let title;
2596
- let lastRenderedCookie;
2597
- let lastRenderedHead;
2598
- const ttl = await resolveTtl(options, page, routes);
2599
- const cacheKey = `/__elur-js/render${page}?${search}`;
2600
- if (options.cacheDir && typeof ttl === "number" && canUsePublicCache(request)) {
2601
- const cached = await getCachedHtml(options.cacheDir, cacheKey);
2602
- if (cached) {
2603
- body = extractBody(cached.html);
2604
- title = extractTitle(cached.html);
2605
- } else {
2606
- const rendered = await renderPageBody({
2607
- routes,
2608
- pathname: page,
2609
- searchParams: new URLSearchParams(search),
2610
- config: {
2611
- lang: options.lang ?? "es",
2612
- clientEntry: options.clientEntry
2613
- },
2614
- actions: publicActions,
2615
- request
2616
- });
2617
- body = rendered.body;
2618
- title = rendered.title;
2619
- lastRenderedCookie = rendered.clearActionErrorCookie;
2620
- lastRenderedHead = rendered.head;
2621
- await setCachedHtml(options.cacheDir, cacheKey, rendered.fullHtml ?? "", ttl);
2622
- }
2623
- } else {
2624
- const rendered = await renderPageBody({
2625
- routes,
2626
- pathname: page,
2627
- searchParams: new URLSearchParams(search),
2628
- config: {
2629
- lang: options.lang ?? "es",
2630
- clientEntry: options.clientEntry
2631
- },
2632
- actions: publicActions,
2633
- request
2634
- });
2635
- body = rendered.body;
2636
- title = rendered.title;
2637
- lastRenderedCookie = rendered.clearActionErrorCookie;
2638
- lastRenderedHead = rendered.head;
2639
- }
2640
- if (wantsJson) {
2641
- const headers = { "Content-Type": "application/json; charset=utf-8" };
2642
- const setCookie = lastRenderedCookie;
2643
- if (setCookie) headers["X-Elur-Action-Clear-Cookie"] = setCookie;
2644
- res.writeHead(200, headers);
2645
- res.end(JSON.stringify({
2646
- title,
2647
- body,
2648
- head: lastRenderedHead,
2649
- clearActionErrorCookie: setCookie
2650
- }));
2651
- } else {
2652
- const headers = { "Content-Type": "text/html; charset=utf-8" };
2653
- if (lastRenderedCookie) headers["Set-Cookie"] = lastRenderedCookie;
2654
- res.writeHead(200, headers);
2655
- res.end(body);
2656
- }
2657
- } catch (err) {
2658
- if (err instanceof RouteNotFoundError) {
2659
- console.log(`[ssr] render endpoint: no route for ${page}`);
2660
- res.writeHead(404, { "Content-Type": "text/plain" });
2661
- res.end("Not Found");
2662
- return;
2663
- }
2664
- console.error("[ssr] streaming render error", err);
2665
- res.writeHead(500, { "Content-Type": "text/plain" });
2666
- res.end("Internal Server Error");
2667
- }
2668
- return;
2669
- }
2670
- let middlewareHeaders;
2671
- if (middleware && matchesMiddleware(urlPath, middleware.config)) {
2672
- const mwResult = await runMiddleware(middleware, incomingMessageToRequest(req));
2673
- if (mwResult.kind === "response") {
2674
- res.writeHead(mwResult.response.status, Object.fromEntries(mwResult.response.headers.entries()));
2675
- res.end(Buffer.from(await mwResult.response.arrayBuffer()));
2676
- return;
2677
- }
2678
- middlewareHeaders = mwResult.headers;
2679
- }
2680
- const apiMatch = matchApiRoute(urlPath, routes.api);
2681
- if (apiMatch) {
2682
- try {
2683
- const handler = (await import(apiMatch.route.routePath))[req.method ?? "GET"];
2684
- if (typeof handler !== "function") {
2685
- res.writeHead(405, { "Content-Type": "text/plain" });
2686
- res.end(`Method not allowed: ${req.method}`);
2687
- return;
2688
- }
2689
- const request = incomingMessageToRequest(req, req.method && req.method !== "GET" && req.method !== "HEAD" ? await readRequestBody$1(req) : void 0);
2690
- applyHeaders(request.headers, middlewareHeaders);
2691
- const response = await handler(request, { params: apiMatch.params });
2692
- res.writeHead(response.status, Object.fromEntries(response.headers.entries()));
2693
- res.end(Buffer.from(await response.arrayBuffer()));
2694
- } catch (err) {
2695
- console.error("[api] error handling", urlPath, err);
2696
- res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
2697
- res.end(toPublicErrorInfo(err).message);
2698
- }
2699
- return;
2700
- }
2701
- if (options.publicDir) try {
2702
- if (await tryServeStatic(res, options.publicDir, urlPath)) return;
2703
- } catch (err) {
2704
- console.error("[static] error serving", urlPath, err);
2705
- }
2706
- const match = matchRoute(urlPath, routes.pages);
2707
- const config = {
2708
- lang: options.lang ?? "es",
2709
- clientEntry: options.clientEntry
2710
- };
2711
- if (match) try {
2712
- const request = incomingMessageToRequest(req);
2713
- applyHeaders(request.headers, middlewareHeaders);
2714
- let html;
2715
- let clearActionErrorCookie;
2716
- const ttl = (match.route.dataPath ? (await import(match.route.dataPath)).revalidate : void 0) ?? options.defaultRevalidate;
2717
- if (options.streaming !== false && match.route.loadingPath) html = await renderStreamingPage({
2718
- route: match.route,
2719
- params: match.params,
2720
- searchParams: new URLSearchParams(req.url?.split("?")[1] ?? ""),
2721
- config,
2722
- actions: publicActions,
2723
- request
2724
- });
2725
- else if (options.cacheDir && typeof ttl === "number" && canUsePublicCache(request)) {
2726
- const cacheKey = new URL(request.url).pathname + new URL(request.url).search;
2727
- const cached = await getCachedHtml(options.cacheDir, cacheKey);
2728
- if (cached) html = cached.html;
2729
- else {
2730
- const result = await renderPage({
2731
- route: match.route,
2732
- params: match.params,
2733
- searchParams: new URLSearchParams(req.url?.split("?")[1] ?? ""),
2734
- config,
2735
- actions: publicActions,
2736
- request
2737
- });
2738
- html = result.html;
2739
- clearActionErrorCookie = result.clearActionErrorCookie;
2740
- await setCachedHtml(options.cacheDir, cacheKey, html, ttl);
2741
- }
2742
- } else {
2743
- const result = await renderPage({
2744
- route: match.route,
2745
- params: match.params,
2746
- searchParams: new URLSearchParams(req.url?.split("?")[1] ?? ""),
2747
- config,
2748
- actions: publicActions,
2749
- request
2750
- });
2751
- html = result.html;
2752
- clearActionErrorCookie = result.clearActionErrorCookie;
2753
- }
2754
- const responseHeaders = { "Content-Type": "text/html; charset=utf-8" };
2755
- if (clearActionErrorCookie) responseHeaders["Set-Cookie"] = clearActionErrorCookie;
2756
- res.writeHead(200, responseHeaders);
2757
- res.end(html);
2758
- return;
2759
- } catch (err) {
2760
- console.error("[ssr] error rendering", urlPath, err);
2761
- const errorResult = await renderErrorPage({
2762
- routes,
2763
- status: 500,
2764
- error: err,
2765
- config,
2766
- actions: publicActions
2767
- });
2768
- if (errorResult) {
2769
- res.writeHead(errorResult.status, { "Content-Type": "text/html; charset=utf-8" });
2770
- res.end(errorResult.html);
2771
- } else {
2772
- res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
2773
- res.end(toPublicErrorInfo(err).message);
2774
- }
2775
- return;
2776
- }
2777
- const errorResult = await renderErrorPage({
2778
- routes,
2779
- status: 404,
2780
- config,
2781
- actions: publicActions
2782
- });
2783
- if (errorResult) {
2784
- res.writeHead(errorResult.status, { "Content-Type": "text/html; charset=utf-8" });
2785
- res.end(errorResult.html);
2786
- return;
2787
- }
2788
- res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" });
2789
- res.end(`Not found: ${req.url}`);
2790
- });
2791
- return {
2792
- server,
2793
- listen() {
2794
- return new Promise((resolve) => {
2795
- server.listen(options.port ?? 3e3, options.host ?? "127.0.0.1", () => {
2796
- console.log(`\n → SSR server http://${options.host ?? "127.0.0.1"}:${options.port ?? 3e3}`);
2797
- resolve();
2798
- });
2799
- });
2800
- },
2801
- close() {
2802
- return new Promise((resolve, reject) => {
2803
- server.close((err) => err ? reject(err) : resolve());
2804
- });
2805
- }
2806
- };
2807
- }
2808
- async function tryServeStatic(res, publicDir, urlPath) {
2809
- const filePath = await resolveStaticFile(publicDir, urlPath);
2810
- if (!filePath) return false;
2811
- const contentType = guessContentType$1(filePath);
2812
- let data = await (0, node_fs_promises.readFile)(filePath);
2813
- if (contentType.includes("text/html")) data = data.toString("utf8").replace("<meta name=\"elur:render-endpoint\" content=\"off\" />", "<meta name=\"elur:render-endpoint\" content=\"on\" />");
2814
- res.writeHead(200, {
2815
- "Content-Type": contentType,
2816
- "Content-Length": Buffer.byteLength(data)
2817
- });
2818
- res.end(data);
2819
- return true;
2820
- }
2821
- function canUsePublicCache(request) {
2822
- return !request.headers.has("cookie") && !request.headers.has("authorization");
2823
- }
2824
- function applyHeaders(headers, values) {
2825
- if (!values) return;
2826
- for (const [name, value] of Object.entries(values)) headers.set(name, value);
2827
- }
2828
- function readRequestBody$1(req) {
2829
- return new Promise((resolve, reject) => {
2830
- let body = "";
2831
- req.setEncoding("utf8");
2832
- req.on("data", (chunk) => {
2833
- body += chunk;
2834
- });
2835
- req.on("end", () => resolve(body));
2836
- req.on("error", reject);
2837
- });
2838
- }
2839
- function guessContentType$1(filePath) {
2840
- switch ((0, node_path.extname)(filePath)) {
2841
- case ".html": return "text/html; charset=utf-8";
2842
- case ".js":
2843
- case ".mjs": return "application/javascript; charset=utf-8";
2844
- case ".css": return "text/css; charset=utf-8";
2845
- case ".json": return "application/json; charset=utf-8";
2846
- case ".svg": return "image/svg+xml";
2847
- case ".png": return "image/png";
2848
- case ".jpg":
2849
- case ".jpeg": return "image/jpeg";
2850
- case ".webp": return "image/webp";
2851
- case ".avif": return "image/avif";
2852
- case ".ico": return "image/x-icon";
2853
- case ".woff": return "font/woff";
2854
- case ".woff2": return "font/woff2";
2855
- case ".wasm": return "application/wasm";
2856
- default: return "application/octet-stream";
2857
- }
3092
+ function isActionFailure(value) {
3093
+ return typeof value === "object" && value !== null && value.__elur_js_action_failure === true;
2858
3094
  }
2859
3095
  /**
2860
- * Maps a concrete page path (e.g. `/movies/inception`) to the route pattern
2861
- * key used by the action registry (e.g. `/movies/:slug`). Falls back to the
2862
- * path itself when it matches an exact registry key.
3096
+ * Type guard for redirects. Uses the marker field so it works across bundling
3097
+ * boundaries where `instanceof` fails.
2863
3098
  */
2864
- function resolveActionPageKey(page, routes) {
2865
- if (!page) return void 0;
2866
- if (routes.pages.some((route) => route.path === page)) return page;
2867
- const match = matchRoute(page, routes.pages);
2868
- return match ? match.route.path : page;
2869
- }
2870
- /** Resolves the ISR TTL for a page: route `revalidate` or the default. */
2871
- async function resolveTtl(options, pathname, routes) {
2872
- const match = matchRoute(pathname, routes.pages);
2873
- if (!match) return void 0;
2874
- return (match.route.dataPath ? (await import(match.route.dataPath)).revalidate : void 0) ?? options.defaultRevalidate;
2875
- }
2876
- function extractBody(fullHtml) {
2877
- const match = fullHtml.match(/<div id="app">([\s\S]*)<\/div>\s*(<script|$)/);
2878
- return match ? match[1].trim() : fullHtml;
2879
- }
2880
- function extractTitle(fullHtml) {
2881
- const match = fullHtml.match(/<title>([^<]*)<\/title>/);
2882
- return match ? match[1] : "";
2883
- }
2884
- //#endregion
2885
- //#region src/config/index.ts
2886
- async function loadElurConfig(options = {}) {
2887
- const initialRoot = (0, node_path.resolve)(options.root ?? process.cwd());
2888
- const configFile = options.configFile ? (0, node_path.resolve)(initialRoot, options.configFile) : await findConfigFile(initialRoot);
2889
- let loaded = {};
2890
- if (configFile) {
2891
- const result = await (0, vite.loadConfigFromFile)({
2892
- command: options.command === "build" ? "build" : "serve",
2893
- mode: options.mode ?? "development"
2894
- }, configFile, initialRoot);
2895
- if (!result) throw new Error(`[elur-kit] Could not load config: ${configFile}`);
2896
- loaded = result.config;
2897
- }
2898
- const merged = mergeConfig(loaded, options.overrides ?? {});
2899
- const root = (0, node_path.resolve)(initialRoot, merged.root ?? ".");
2900
- const resolved = resolveConfig(root, merged, configFile);
2901
- await runIntegrationHook(resolved.integrations, "config", [resolved, {
2902
- root,
2903
- command: options.command ?? "dev"
2904
- }]);
2905
- return resolved;
3099
+ function isRedirectResponse(value) {
3100
+ return typeof value === "object" && value !== null && value.__elur_js_action_redirect === true;
2906
3101
  }
2907
- function resolveConfig(root, config, configFile) {
2908
- if (config.site) new URL(config.site);
2909
- const base = normalizeBase(config.base ?? "/");
2910
- const imageQuality = config.images?.quality ?? 80;
2911
- if (!Number.isFinite(imageQuality) || imageQuality < 1 || imageQuality > 100) throw new Error("[elur-kit] images.quality must be between 1 and 100");
3102
+ /**
3103
+ * Maps an arbitrary thrown value to a public-safe error info. By default the
3104
+ * public message is generic; `includeDetail` (dev/verbose mode) appends the
3105
+ * original `Error.message` for local debugging.
3106
+ */
3107
+ function toPublicErrorInfo(error, options = {}) {
3108
+ const code = "INTERNAL_SERVER_ERROR";
3109
+ const status = 500;
3110
+ if (options.includeDetail && error instanceof Error && error.message) return {
3111
+ code,
3112
+ status,
3113
+ message: error.message
3114
+ };
2912
3115
  return {
2913
- root,
2914
- appDir: resolveInside(root, config.appDir ?? "src/app", "appDir"),
2915
- islandsDir: resolveInside(root, config.islandsDir ?? "src/islands", "islandsDir"),
2916
- contentDir: resolveInside(root, config.contentDir ?? "src/content", "contentDir"),
2917
- publicDir: resolveInside(root, config.publicDir ?? "public", "publicDir"),
2918
- outDir: resolveInside(root, config.outDir ?? "dist", "outDir"),
2919
- site: config.site,
2920
- base,
2921
- trailingSlash: config.trailingSlash ?? "ignore",
2922
- output: config.output ?? "static",
2923
- adapter: config.adapter,
2924
- images: {
2925
- formats: config.images?.formats ?? ["webp", "avif"],
2926
- quality: imageQuality,
2927
- strict: config.images?.strict ?? false
2928
- },
2929
- cache: {
2930
- dir: resolveInside(root, config.cache?.dir ?? ".elur/cache", "cache.dir"),
2931
- defaultRevalidate: config.cache?.defaultRevalidate
2932
- },
2933
- security: {
2934
- allowedOrigins: config.security?.allowedOrigins ?? [],
2935
- strictOrigin: config.security?.strictOrigin ?? false,
2936
- bodyLimit: config.security?.bodyLimit ?? 1048576,
2937
- headers: config.security?.headers === false ? false : config.security?.headers ?? {}
2938
- },
2939
- router: {
2940
- enabled: config.router?.enabled ?? true,
2941
- prefetch: config.router?.prefetch ?? true
2942
- },
2943
- integrations: config.integrations ?? [],
2944
- configFile
3116
+ code,
3117
+ status,
3118
+ message: "Internal Server Error"
2945
3119
  };
2946
3120
  }
2947
- function mergeConfig(base, override) {
2948
- return {
2949
- ...base,
2950
- ...override,
2951
- images: {
2952
- ...base.images,
2953
- ...override.images
2954
- },
2955
- cache: {
2956
- ...base.cache,
2957
- ...override.cache
2958
- },
2959
- security: {
2960
- ...base.security,
2961
- ...override.security
2962
- },
2963
- router: {
2964
- ...base.router,
2965
- ...override.router
2966
- },
2967
- integrations: override.integrations ?? base.integrations
3121
+ /**
3122
+ * Builds a production-safe JSON error Response. Logs the raw error separately
3123
+ * (never reflected in the response body) and keeps the request id header.
3124
+ */
3125
+ function publicErrorResponse(error, options = {}) {
3126
+ const info = toPublicErrorInfo(error, options);
3127
+ const headers = {
3128
+ "Content-Type": "application/json; charset=utf-8",
3129
+ "Cache-Control": "no-store"
2968
3130
  };
3131
+ if (options.requestId) headers["X-Request-Id"] = options.requestId;
3132
+ return new Response(JSON.stringify({ error: info }), {
3133
+ status: info.status,
3134
+ headers
3135
+ });
2969
3136
  }
2970
- function resolveInside(root, path, name) {
2971
- const resolved = (0, node_path.isAbsolute)(path) ? (0, node_path.resolve)(path) : (0, node_path.resolve)(root, path);
2972
- const rel = (0, node_path.relative)(root, resolved);
2973
- if (rel === ".." || rel.startsWith(`..${node_path.sep}`) || (0, node_path.isAbsolute)(rel)) throw new Error(`[elur-kit] ${name} must stay inside root: ${resolved}`);
2974
- return resolved;
3137
+ var init_errors = __esmMin((() => {}));
3138
+ //#endregion
3139
+ //#region src/action/origin.ts
3140
+ /**
3141
+ * Returns the host:port of a URL string, or undefined if it cannot be parsed.
3142
+ */
3143
+ function originOf(urlString) {
3144
+ if (!urlString) return void 0;
3145
+ try {
3146
+ const url = new URL(urlString);
3147
+ if (url.protocol !== "http:" && url.protocol !== "https:") return void 0;
3148
+ return url.origin;
3149
+ } catch {
3150
+ return;
3151
+ }
2975
3152
  }
2976
- function normalizeBase(base) {
2977
- if (!base.startsWith("/")) throw new Error("[elur-kit] base must start with /");
2978
- return base === "/" ? base : `${base.replace(/\/+$/, "")}/`;
3153
+ /**
3154
+ * Verifies that a request originates from the same host (or an allow-listed
3155
+ * origin). Returns an error message when the request must be rejected, or
3156
+ * undefined when it is allowed.
3157
+ *
3158
+ * @param request The incoming Request to actions.
3159
+ * @param options Origin check configuration.
3160
+ */
3161
+ function verifyOrigin(request, options = {}) {
3162
+ const targetOrigin = originOf(request.url);
3163
+ if (!targetOrigin) return "Invalid target URL";
3164
+ const origin = request.headers.get("Origin");
3165
+ const referer = request.headers.get("Referer");
3166
+ if (!origin && !referer) return options.strictOrigin ? "Missing Origin and Referer headers" : void 0;
3167
+ const sourceOrigin = origin ? originOf(origin) : originOf(referer);
3168
+ if (!sourceOrigin) return origin ? "Invalid Origin header" : "Invalid Referer header";
3169
+ if (sourceOrigin === targetOrigin) return void 0;
3170
+ if (options.allowedOrigins?.some((allowed) => originOf(allowed) === sourceOrigin)) return void 0;
3171
+ return `Cross-origin request blocked: source "${sourceOrigin}" != target "${targetOrigin}"`;
2979
3172
  }
2980
- var PREFERRED_CONFIG_FILES = [
2981
- "elur.config.ts",
2982
- "elur.config.js",
2983
- "elur.config.mjs"
2984
- ];
2985
- var LEGACY_CONFIG_FILES = [
2986
- "elur.config.ts",
2987
- "elur.config.js",
2988
- "elur.config.mjs"
2989
- ];
2990
- async function findConfigFile(root) {
2991
- for (const name of PREFERRED_CONFIG_FILES) {
2992
- const path = (0, node_path.resolve)(root, name);
3173
+ /** Builds a 403 Response for a rejected origin. */
3174
+ function originForbidden(message) {
3175
+ return new Response(message, {
3176
+ status: 403,
3177
+ headers: { "Content-Type": "text/plain; charset=utf-8" }
3178
+ });
3179
+ }
3180
+ var init_origin = __esmMin((() => {}));
3181
+ //#endregion
3182
+ //#region src/cache/adapter.ts
3183
+ var adapter_exports = /* @__PURE__ */ __exportAll({
3184
+ cacheKey: () => cacheKey,
3185
+ createFsCacheAdapter: () => createFsCacheAdapter,
3186
+ getWithSWR: () => getWithSWR
3187
+ });
3188
+ /** Computes a SHA-256 key from a normalized identity string. */
3189
+ function cacheKey(...parts) {
3190
+ return (0, node_crypto.createHash)("sha256").update(parts.join("\n")).digest("hex");
3191
+ }
3192
+ function createFsCacheAdapter(options) {
3193
+ const { cacheDir } = options;
3194
+ const maxEntries = options.maxEntries ?? 1e3;
3195
+ const maxAgeMs = options.maxAgeMs ?? 864e5;
3196
+ const inFlight = /* @__PURE__ */ new Map();
3197
+ const tagIndexPath = (0, node_path.join)(cacheDir, "_tag-index.json");
3198
+ async function loadTagIndex() {
2993
3199
  try {
2994
- await (0, node_fs_promises.access)(path);
2995
- return path;
2996
- } catch {}
3200
+ const raw = await (0, node_fs_promises.readFile)(tagIndexPath, "utf8");
3201
+ return JSON.parse(raw);
3202
+ } catch {
3203
+ return {};
3204
+ }
2997
3205
  }
2998
- for (const name of LEGACY_CONFIG_FILES) {
2999
- const path = (0, node_path.resolve)(root, name);
3206
+ async function saveTagIndex(index) {
3207
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(tagIndexPath), { recursive: true });
3208
+ const tmp = `${tagIndexPath}.${process.pid}.${(0, node_crypto.randomUUID)()}.tmp`;
3000
3209
  try {
3001
- await (0, node_fs_promises.access)(path);
3002
- console.warn(`[elur-kit] "${name}" is deprecated and will be removed in a future release. Rename it to "elur.config.${name.split(".").slice(1).join(".")}" to keep your config working.`);
3003
- return path;
3004
- } catch {}
3005
- }
3006
- }
3007
- //#endregion
3008
- //#region src/manifest/index.ts
3009
- init_scan();
3010
- init_route_scanner();
3011
- async function createAppManifest(config) {
3012
- const [routes, actions, islands] = await Promise.all([
3013
- scanRoutes(config.appDir),
3014
- scanActions(config.appDir),
3015
- scanIslands(config.islandsDir)
3016
- ]);
3017
- validateManifestRoutes(routes);
3018
- validateIslands(islands);
3019
- const manifest = {
3020
- version: 1,
3021
- root: config.root,
3022
- routes,
3023
- actions,
3024
- islands,
3025
- base: config.base,
3026
- output: config.output
3027
- };
3028
- await runIntegrationHook(config.integrations, "routes", [manifest, {
3029
- root: config.root,
3030
- command: "build"
3031
- }]);
3032
- return manifest;
3033
- }
3034
- async function writeAppManifest(manifest, path) {
3035
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
3036
- await (0, node_fs_promises.writeFile)(path, JSON.stringify(toPortableManifest(manifest), null, 2), "utf8");
3037
- }
3038
- async function writeRouteTypes(manifest, path) {
3039
- const routePaths = manifest.routes.pages.map((route) => JSON.stringify(route.path));
3040
- const actionNames = Object.values(manifest.actions).flatMap((actions) => Object.keys(actions)).filter((name, index, names) => names.indexOf(name) === index).map((name) => JSON.stringify(name));
3041
- const source = [
3042
- `export type ElurRoutePath = ${routePaths.length ? routePaths.join(" | ") : "never"};`,
3043
- `export type ElurActionName = ${actionNames.length ? actionNames.join(" | ") : "never"};`,
3044
- "export interface ElurRouteParams { [name: string]: string | string[] | undefined }",
3045
- ""
3046
- ].join("\n");
3047
- await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
3048
- await (0, node_fs_promises.writeFile)(path, source, "utf8");
3049
- }
3050
- function validateManifestRoutes(routes) {
3051
- const seen = /* @__PURE__ */ new Map();
3052
- for (const route of routes.pages) {
3053
- registerRoute(seen, route.path, route.pagePath, "page");
3054
- assertNotReserved(route.path, route.pagePath);
3210
+ await (0, node_fs_promises.writeFile)(tmp, JSON.stringify(index), "utf8");
3211
+ await (0, node_fs_promises.rename)(tmp, tagIndexPath);
3212
+ } finally {
3213
+ await (0, node_fs_promises.rm)(tmp, { force: true });
3214
+ }
3055
3215
  }
3056
- for (const route of routes.api) {
3057
- registerRoute(seen, route.path, route.routePath, "API");
3058
- assertNotReserved(route.path, route.routePath);
3216
+ function entryPath(key) {
3217
+ return (0, node_path.join)(cacheDir, `${key}.html.json`);
3059
3218
  }
3060
- }
3061
- function registerRoute(seen, path, file, kind) {
3062
- const existing = seen.get(path);
3063
- if (existing) throw new Error(`[elur-kit] Duplicate ${kind} route "${path}": ${existing} and ${file}`);
3064
- seen.set(path, file);
3065
- }
3066
- function assertNotReserved(path, file) {
3067
- if (path === "/__elur-js" || path.startsWith("/__elur-js/") || path === "/_elur" || path.startsWith("/_elur/")) throw new Error(`[elur-kit] Reserved route "${path}" declared by ${file}`);
3068
- }
3069
- function validateIslands(islands) {
3070
- const names = /* @__PURE__ */ new Set();
3071
- for (const island of islands) {
3072
- if (names.has(island.name)) throw new Error(`[elur-kit] Duplicate island name: ${island.name}`);
3073
- names.add(island.name);
3219
+ async function get(key) {
3220
+ const existing = inFlight.get(key);
3221
+ if (existing) return existing;
3222
+ const promise = (async () => {
3223
+ try {
3224
+ const raw = await (0, node_fs_promises.readFile)(entryPath(key), "utf8");
3225
+ return JSON.parse(raw);
3226
+ } catch {
3227
+ return null;
3228
+ }
3229
+ })();
3230
+ inFlight.set(key, promise);
3231
+ try {
3232
+ return await promise;
3233
+ } finally {
3234
+ inFlight.delete(key);
3235
+ }
3236
+ }
3237
+ async function set(key, value, opts) {
3238
+ const path = entryPath(key);
3239
+ await (0, node_fs_promises.mkdir)((0, node_path.dirname)(path), { recursive: true });
3240
+ const entry = {
3241
+ html: value.html,
3242
+ generatedAt: value.generatedAt ?? Date.now(),
3243
+ revalidate: opts.revalidate,
3244
+ tags: opts.tags,
3245
+ version: opts.version
3246
+ };
3247
+ const tmp = `${path}.${process.pid}.${(0, node_crypto.randomUUID)()}.tmp`;
3248
+ try {
3249
+ await (0, node_fs_promises.writeFile)(tmp, JSON.stringify(entry), "utf8");
3250
+ await (0, node_fs_promises.rename)(tmp, path);
3251
+ } finally {
3252
+ await (0, node_fs_promises.rm)(tmp, { force: true });
3253
+ }
3254
+ if (opts.tags && opts.tags.length > 0) {
3255
+ const index = await loadTagIndex();
3256
+ for (const tag of opts.tags) {
3257
+ if (!index[tag]) index[tag] = [];
3258
+ if (!index[tag].includes(key)) index[tag].push(key);
3259
+ }
3260
+ await saveTagIndex(index);
3261
+ }
3262
+ await maybeCleanup();
3263
+ }
3264
+ async function del(key) {
3265
+ await (0, node_fs_promises.rm)(entryPath(key), { force: true });
3266
+ }
3267
+ async function invalidateTags(tags) {
3268
+ if (tags.length === 0) return;
3269
+ const index = await loadTagIndex();
3270
+ const keysToDelete = /* @__PURE__ */ new Set();
3271
+ for (const tag of tags) {
3272
+ const keys = index[tag];
3273
+ if (keys) {
3274
+ for (const key of keys) keysToDelete.add(key);
3275
+ delete index[tag];
3276
+ }
3277
+ }
3278
+ await Promise.all([...keysToDelete].map((key) => del(key)));
3279
+ await saveTagIndex(index);
3280
+ }
3281
+ let lastCleanup = 0;
3282
+ async function maybeCleanup() {
3283
+ const now = Date.now();
3284
+ if (now - lastCleanup < 6e4) return;
3285
+ lastCleanup = now;
3286
+ try {
3287
+ const files = await (0, node_fs_promises.readdir)(cacheDir);
3288
+ let entryCount = 0;
3289
+ const toDelete = [];
3290
+ for (const file of files) {
3291
+ if (!file.endsWith(".html.json")) continue;
3292
+ entryCount++;
3293
+ const filePath = (0, node_path.join)(cacheDir, file);
3294
+ try {
3295
+ if (now - (await (0, node_fs_promises.stat)(filePath)).mtimeMs > maxAgeMs) toDelete.push(filePath);
3296
+ } catch {}
3297
+ }
3298
+ if (entryCount - toDelete.length > maxEntries) {
3299
+ const candidates = [];
3300
+ for (const file of files) {
3301
+ if (!file.endsWith(".html.json")) continue;
3302
+ const filePath = (0, node_path.join)(cacheDir, file);
3303
+ if (toDelete.includes(filePath)) continue;
3304
+ try {
3305
+ const stats = await (0, node_fs_promises.stat)(filePath);
3306
+ candidates.push({
3307
+ path: filePath,
3308
+ mtime: stats.mtimeMs
3309
+ });
3310
+ } catch {}
3311
+ }
3312
+ candidates.sort((a, b) => a.mtime - b.mtime);
3313
+ const excess = entryCount - toDelete.length - maxEntries;
3314
+ for (let i = 0; i < excess && i < candidates.length; i++) toDelete.push(candidates[i].path);
3315
+ }
3316
+ await Promise.all(toDelete.map((p) => (0, node_fs_promises.rm)(p, { force: true })));
3317
+ } catch {}
3074
3318
  }
3075
- }
3076
- function toPortableManifest(manifest) {
3077
- const relativePath = (path) => path ? (0, node_path.relative)(manifest.root, path).split("\\").join("/") : void 0;
3078
- const routes = {
3079
- pages: manifest.routes.pages.map((route) => ({
3080
- ...route,
3081
- pagePath: relativePath(route.pagePath),
3082
- dataPath: relativePath(route.dataPath),
3083
- actionPath: relativePath(route.actionPath),
3084
- loadingPath: relativePath(route.loadingPath),
3085
- layouts: route.layouts.map((layout) => relativePath(layout))
3086
- })),
3087
- api: manifest.routes.api.map((route) => ({
3088
- ...route,
3089
- routePath: relativePath(route.routePath)
3090
- })),
3091
- error404: manifest.routes.error404 ? {
3092
- ...manifest.routes.error404,
3093
- pagePath: relativePath(manifest.routes.error404.pagePath),
3094
- dataPath: relativePath(manifest.routes.error404.dataPath),
3095
- actionPath: relativePath(manifest.routes.error404.actionPath),
3096
- loadingPath: relativePath(manifest.routes.error404.loadingPath),
3097
- layouts: manifest.routes.error404.layouts.map((layout) => relativePath(layout))
3098
- } : void 0,
3099
- error500: manifest.routes.error500 ? {
3100
- ...manifest.routes.error500,
3101
- pagePath: relativePath(manifest.routes.error500.pagePath),
3102
- dataPath: relativePath(manifest.routes.error500.dataPath),
3103
- actionPath: relativePath(manifest.routes.error500.actionPath),
3104
- loadingPath: relativePath(manifest.routes.error500.loadingPath),
3105
- layouts: manifest.routes.error500.layouts.map((layout) => relativePath(layout))
3106
- } : void 0
3107
- };
3108
- const actions = {};
3109
- for (const [page, pageActions] of Object.entries(manifest.actions)) actions[page] = Object.fromEntries(Object.entries(pageActions).map(([name, path]) => [name, relativePath(path)]));
3110
3319
  return {
3111
- ...manifest,
3112
- root: ".",
3113
- routes,
3114
- actions,
3115
- islands: manifest.islands.map((island) => ({
3116
- ...island,
3117
- filePath: relativePath(island.filePath)
3118
- }))
3320
+ get,
3321
+ set,
3322
+ delete: del,
3323
+ invalidateTags
3119
3324
  };
3120
3325
  }
3121
- //#endregion
3122
- //#region src/runtime/capabilities.ts
3123
- /** True when the host can write to persistent storage (for ISR/cache/image writes). */
3124
- function supportsPersistentStorage(capabilities) {
3125
- return capabilities.filesystem === "persistent";
3126
- }
3127
3326
  /**
3128
- * Validates a capability declaration and reports incompatible combinations.
3129
- * Used by the build pipeline so invalid hosts fail at build time instead of
3130
- * producing a broken runtime.
3327
+ * Gets a cached entry. If the entry is stale (past revalidate), serves it
3328
+ * immediately and triggers a background revalidation.
3329
+ *
3330
+ * @param adapter The cache adapter.
3331
+ * @param key The cache key.
3332
+ * @param revalidate The revalidation function (called if stale or missing).
3333
+ * @returns The cache entry (fresh or stale), or null if missing.
3131
3334
  */
3132
- function validateCapabilities(capabilities, features = {}) {
3133
- const problems = [];
3134
- if (features.isr && !supportsPersistentStorage(capabilities)) problems.push(`ISR requires a persistent filesystem; the host declares filesystem="${capabilities.filesystem}".`);
3135
- if (features.images && capabilities.imageRuntime === false && capabilities.filesystem === "none") problems.push("On-demand image transforms require either imageRuntime=true or a readable filesystem; the host has neither.");
3136
- if (features.streaming && capabilities.streaming === false) problems.push("Streaming was requested but the host declares streaming=false.");
3335
+ async function getWithSWR(adapter, key, revalidate) {
3336
+ const entry = await adapter.get(key);
3337
+ if (!entry) return {
3338
+ entry: await revalidate(),
3339
+ stale: false
3340
+ };
3341
+ if (Date.now() - entry.generatedAt >= entry.revalidate * 1e3) {
3342
+ revalidate().then((fresh) => {
3343
+ if (fresh) adapter.set(key, fresh, {
3344
+ revalidate: entry.revalidate,
3345
+ tags: entry.tags,
3346
+ version: entry.version
3347
+ }).catch((err) => {
3348
+ console.error("[elur-kit] background cache write failed:", err);
3349
+ });
3350
+ }, (err) => {
3351
+ console.error("[elur-kit] background revalidation failed:", err);
3352
+ });
3353
+ return {
3354
+ entry,
3355
+ stale: true
3356
+ };
3357
+ }
3137
3358
  return {
3138
- ok: problems.length === 0,
3139
- problems
3359
+ entry,
3360
+ stale: false
3140
3361
  };
3141
3362
  }
3142
- var DEFAULT_CAPABILITIES, SERVERLESS_CAPABILITIES;
3143
- var init_capabilities = __esmMin((() => {
3144
- DEFAULT_CAPABILITIES = {
3145
- streaming: true,
3146
- filesystem: "persistent",
3147
- imageRuntime: true,
3148
- backgroundWork: true
3149
- };
3150
- SERVERLESS_CAPABILITIES = {
3151
- streaming: true,
3152
- filesystem: "ephemeral",
3153
- imageRuntime: false,
3154
- backgroundWork: false,
3155
- maxBodySize: 1048576
3363
+ var init_adapter = __esmMin((() => {}));
3364
+ //#endregion
3365
+ //#region src/cache/invalidation.ts
3366
+ /**
3367
+ * Connects a CacheAdapter to the default invalidator so that tag/path
3368
+ * invalidation events from actions are dispatched to the cache.
3369
+ *
3370
+ * Returns an unsubscribe function.
3371
+ */
3372
+ function connectCacheAdapter(adapter, invalidator = defaultInvalidator) {
3373
+ return invalidator.on(async (event) => {
3374
+ if (event.tags && event.tags.length > 0) await adapter.invalidateTags(event.tags);
3375
+ if (event.paths && event.paths.length > 0 && adapter.delete) {
3376
+ const { cacheKey } = await Promise.resolve().then(() => (init_adapter(), adapter_exports));
3377
+ await Promise.all(event.paths.map((p) => adapter.delete(cacheKey(p))));
3378
+ }
3379
+ });
3380
+ }
3381
+ var CacheInvalidator, defaultInvalidator;
3382
+ var init_invalidation = __esmMin((() => {
3383
+ CacheInvalidator = class {
3384
+ listeners = /* @__PURE__ */ new Set();
3385
+ /** Registers a listener for invalidation events. Returns an unsubscribe function. */
3386
+ on(listener) {
3387
+ this.listeners.add(listener);
3388
+ return () => this.listeners.delete(listener);
3389
+ }
3390
+ /** Emits an invalidation event to all listeners. */
3391
+ async emit(event) {
3392
+ const promises = [];
3393
+ for (const listener of this.listeners) try {
3394
+ const result = listener(event);
3395
+ if (result instanceof Promise) promises.push(result.catch((err) => {
3396
+ console.error("[elur-kit] invalidation listener error:", err);
3397
+ }));
3398
+ } catch (err) {
3399
+ console.error("[elur-kit] invalidation listener error:", err);
3400
+ }
3401
+ await Promise.all(promises);
3402
+ }
3403
+ /** Convenience: invalidate by tags. */
3404
+ async invalidateTags(tags, source) {
3405
+ if (tags.length === 0) return;
3406
+ await this.emit({
3407
+ tags,
3408
+ source
3409
+ });
3410
+ }
3411
+ /** Convenience: invalidate by paths. */
3412
+ async invalidatePaths(paths, source) {
3413
+ if (paths.length === 0) return;
3414
+ await this.emit({
3415
+ paths,
3416
+ source
3417
+ });
3418
+ }
3419
+ /** Removes all listeners. */
3420
+ clear() {
3421
+ this.listeners.clear();
3422
+ }
3156
3423
  };
3424
+ defaultInvalidator = new CacheInvalidator();
3157
3425
  }));
3158
3426
  //#endregion
3159
- //#region src/build/vite-build.ts
3160
- var vite_build_exports = /* @__PURE__ */ __exportAll({
3161
- beginAtomicStage: () => beginAtomicStage,
3162
- buildClientBundle: () => buildClientBundle,
3163
- copyPublicAssets: () => copyPublicAssets
3164
- });
3427
+ //#region src/action/server.ts
3165
3428
  /**
3166
- * Build the client hydration bundle using the Vite JavaScript API.
3167
- *
3168
- * The user's config is loaded programmatically and the elur interpolation
3169
- * plugin is injected so partial attribute interpolations inside islands are
3170
- * transformed before reaching the browser.
3429
+ * Reads the request body as text, enforcing a maximum size.
3430
+ * Returns a 413 response if the body exceeds the limit.
3171
3431
  */
3172
- async function buildClientBundle(options) {
3173
- const log = options.logPrefix ?? "[client]";
3174
- console.log(`${log} Building hydration bundle...`);
3175
- const userConfig = await loadUserConfig(options.userConfigPath, options.root);
3176
- const pluginOptions = shouldUseLegacyInterpolation(options.interpolation ?? "auto") ? elurJsInterpolationPlugin({
3177
- appDir: options.appDir,
3178
- islandsDir: options.islandsDir
3179
- }) : [];
3180
- const config = {
3181
- ...userConfig,
3182
- root: options.root,
3183
- base: options.base ?? userConfig.base ?? "/",
3184
- build: {
3185
- ...userConfig.build ?? {},
3186
- outDir: options.outDir,
3187
- emptyOutDir: true
3188
- },
3189
- plugins: [...userConfig.plugins ?? [], pluginOptions],
3190
- configFile: false
3432
+ async function readBodyWithLimit(request, limit) {
3433
+ const contentLength = request.headers.get("Content-Length");
3434
+ if (contentLength && parseInt(contentLength, 10) > limit) return {
3435
+ ok: false,
3436
+ response: new Response("Request body too large", {
3437
+ status: 413,
3438
+ headers: { "Content-Type": "text/plain" }
3439
+ })
3440
+ };
3441
+ const reader = request.body?.getReader();
3442
+ if (!reader) return {
3443
+ ok: true,
3444
+ text: ""
3445
+ };
3446
+ const chunks = [];
3447
+ let totalSize = 0;
3448
+ try {
3449
+ for (;;) {
3450
+ const { done, value } = await reader.read();
3451
+ if (done) break;
3452
+ totalSize += value.byteLength;
3453
+ if (totalSize > limit) {
3454
+ try {
3455
+ reader.cancel();
3456
+ } catch {}
3457
+ return {
3458
+ ok: false,
3459
+ response: new Response("Request body too large", {
3460
+ status: 413,
3461
+ headers: { "Content-Type": "text/plain" }
3462
+ })
3463
+ };
3464
+ }
3465
+ chunks.push(value);
3466
+ }
3467
+ } finally {
3468
+ try {
3469
+ reader.releaseLock();
3470
+ } catch {}
3471
+ }
3472
+ const total = new Uint8Array(totalSize);
3473
+ let offset = 0;
3474
+ for (const chunk of chunks) {
3475
+ total.set(chunk, offset);
3476
+ offset += chunk.byteLength;
3477
+ }
3478
+ return {
3479
+ ok: true,
3480
+ text: new TextDecoder().decode(total)
3481
+ };
3482
+ }
3483
+ function parseFormBody(body) {
3484
+ const params = new URLSearchParams(body);
3485
+ const result = {};
3486
+ for (const [key, value] of params) if (result[key] === void 0) result[key] = value;
3487
+ else if (Array.isArray(result[key])) result[key].push(value);
3488
+ else result[key] = [result[key], value];
3489
+ return result;
3490
+ }
3491
+ async function parseActionRequest(request, bodyLimit = DEFAULT_BODY_LIMIT) {
3492
+ if (request.method !== "POST") return {
3493
+ ok: false,
3494
+ response: new Response("Method not allowed", {
3495
+ status: 405,
3496
+ headers: { "Content-Type": "text/plain" }
3497
+ })
3498
+ };
3499
+ const contentType = request.headers.get("Content-Type") ?? "";
3500
+ const wantsJson = (request.headers.get("Accept") ?? "").includes("application/json");
3501
+ let name;
3502
+ let page;
3503
+ let args = [];
3504
+ if (contentType.includes("application/json")) {
3505
+ const bodyResult = await readBodyWithLimit(request, bodyLimit);
3506
+ if (!bodyResult.ok) return {
3507
+ ok: false,
3508
+ response: bodyResult.response
3509
+ };
3510
+ let body;
3511
+ try {
3512
+ body = JSON.parse(bodyResult.text);
3513
+ } catch {
3514
+ return {
3515
+ ok: false,
3516
+ response: new Response("Invalid JSON body", {
3517
+ status: 400,
3518
+ headers: { "Content-Type": "text/plain" }
3519
+ })
3520
+ };
3521
+ }
3522
+ name = body.name;
3523
+ page = body.page;
3524
+ args = Array.isArray(body.args) ? body.args : [];
3525
+ } else if (contentType.includes("application/x-www-form-urlencoded") || contentType.includes("multipart/form-data")) {
3526
+ if (contentType.includes("multipart/form-data")) {
3527
+ const contentLength = request.headers.get("Content-Length");
3528
+ if (contentLength && parseInt(contentLength, 10) > bodyLimit) return {
3529
+ ok: false,
3530
+ response: new Response("Request body too large", {
3531
+ status: 413,
3532
+ headers: { "Content-Type": "text/plain" }
3533
+ })
3534
+ };
3535
+ let form;
3536
+ try {
3537
+ form = await request.formData();
3538
+ } catch {
3539
+ return {
3540
+ ok: false,
3541
+ response: new Response("Invalid form body", {
3542
+ status: 400,
3543
+ headers: { "Content-Type": "text/plain" }
3544
+ })
3545
+ };
3546
+ }
3547
+ name = form.get("__elur_js_action_name") ?? void 0;
3548
+ page = form.get("__elur_js_action_page") ?? void 0;
3549
+ const input = {};
3550
+ for (const [key, value] of form) {
3551
+ if (key === "__elur_js_action_name" || key === "__elur_js_action_page") continue;
3552
+ input[key] = value;
3553
+ }
3554
+ args = [input];
3555
+ } else {
3556
+ const bodyResult = await readBodyWithLimit(request, bodyLimit);
3557
+ if (!bodyResult.ok) return {
3558
+ ok: false,
3559
+ response: bodyResult.response
3560
+ };
3561
+ const form = parseFormBody(bodyResult.text);
3562
+ name = form.__elur_js_action_name;
3563
+ page = form.__elur_js_action_page;
3564
+ const input = {};
3565
+ for (const [key, value] of Object.entries(form)) {
3566
+ if (key === "__elur_js_action_name" || key === "__elur_js_action_page") continue;
3567
+ input[key] = value;
3568
+ }
3569
+ args = [input];
3570
+ }
3571
+ } else {
3572
+ const bodyResult = await readBodyWithLimit(request, bodyLimit);
3573
+ if (!bodyResult.ok) return {
3574
+ ok: false,
3575
+ response: bodyResult.response
3576
+ };
3577
+ const form = parseFormBody(bodyResult.text);
3578
+ name = form.__elur_js_action_name;
3579
+ page = form.__elur_js_action_page;
3580
+ const input = {};
3581
+ for (const [key, value] of Object.entries(form)) {
3582
+ if (key === "__elur_js_action_name" || key === "__elur_js_action_page") continue;
3583
+ input[key] = value;
3584
+ }
3585
+ args = [input];
3586
+ }
3587
+ if (!name || typeof name !== "string") return {
3588
+ ok: false,
3589
+ response: new Response("Missing action name", {
3590
+ status: 400,
3591
+ headers: { "Content-Type": "text/plain" }
3592
+ })
3191
3593
  };
3192
- const result = await (0, vite.build)(config);
3193
- const outputCount = (Array.isArray(result) ? result : [result]).reduce((n, r) => n + ("output" in r ? r.output?.length ?? 0 : 0), 0);
3194
- console.log(`${log} ✓ ${outputCount} asset(s) emitted → ${(0, node_path.relative)(options.root, options.outDir)}`);
3195
3594
  return {
3196
- outDir: options.outDir,
3197
- outputCount
3595
+ ok: true,
3596
+ name,
3597
+ page,
3598
+ args,
3599
+ wantsJson
3198
3600
  };
3199
3601
  }
3200
- async function loadUserConfig(path, _root) {
3201
- const mod = await import(path);
3202
- const raw = mod.default ?? mod;
3203
- const resolved = typeof raw === "function" ? await raw({
3204
- command: "build",
3205
- mode: "production"
3206
- }) : raw;
3207
- return (resolved && typeof resolved.then === "function" ? await resolved : resolved) ?? {};
3208
- }
3209
3602
  /**
3210
- * Prepare an atomic staging directory for build output.
3603
+ * Handles a POST request to the server action endpoint.
3211
3604
  *
3212
- * Usage:
3213
- * const stage = await beginAtomicStage({ outDir });
3214
- * try {
3215
- * await buildInto(stage.tempDir);
3216
- * await stage.commit();
3217
- * } catch (err) {
3218
- * await stage.rollback();
3219
- * throw err;
3220
- * }
3605
+ * Accepts both JSON requests (`{ name, page?, args }`) and HTML form submissions
3606
+ * for progressive enhancement. The provided resolver looks up the action
3607
+ * implementation, invokes it with the supplied arguments and returns the result
3608
+ * as JSON or redirects back to the request origin for form submissions.
3609
+ *
3610
+ * Origin verification (CSRF protection) runs before parsing the body: any
3611
+ * cross-origin POST is rejected with 403 unless its origin is allow-listed via
3612
+ * `security.allowedOrigins`.
3613
+ *
3614
+ * For progressive-enhancement form submissions that fail, the failure payload
3615
+ * is relayed back via a short-lived `__elur_js_action_error` cookie (SameSite=Lax,
3616
+ * Max-Age=15s) instead of a query param, so errors do not leak into browser
3617
+ * history, server logs or third-party Referer headers.
3221
3618
  */
3222
- async function beginAtomicStage(options) {
3223
- const outDir = (0, node_path.resolve)(options.outDir);
3224
- const tempDir = (0, node_path.resolve)(options.tempDir ?? (0, node_path.join)((0, node_path.dirname)(outDir), `.${basename(outDir)}.tmp-${process.pid}`));
3225
- await (0, node_fs_promises.rm)(tempDir, {
3226
- recursive: true,
3227
- force: true
3228
- });
3229
- await (0, node_fs_promises.mkdir)(tempDir, { recursive: true });
3230
- const commit = async () => {
3231
- const backup = options.keepExisting && (0, node_fs.existsSync)(outDir) ? `${outDir}.bak-${process.pid}` : void 0;
3232
- if (backup) {
3233
- await (0, node_fs_promises.rm)(backup, {
3234
- recursive: true,
3235
- force: true
3619
+ async function handleActionRequest(request, resolveAction, security = {}) {
3620
+ const originError = verifyOrigin(request, security);
3621
+ if (originError) return originForbidden(originError);
3622
+ const parsed = await parseActionRequest(request, security.bodyLimit ?? DEFAULT_BODY_LIMIT);
3623
+ if (!parsed.ok) return parsed.response;
3624
+ const { name, page, args, wantsJson } = parsed;
3625
+ try {
3626
+ const action = await resolveAction(name, page);
3627
+ if (!action) {
3628
+ const message = page ? `Action not found: ${name} (page: ${page})` : `Action not found: ${name}`;
3629
+ return new Response(message, {
3630
+ status: 404,
3631
+ headers: { "Content-Type": "text/plain" }
3236
3632
  });
3237
- await safeRename(outDir, backup);
3238
3633
  }
3239
- try {
3240
- await safeRename(tempDir, outDir);
3241
- } catch (err) {
3242
- if (isCrossDevice(err)) {
3243
- await (0, node_fs_promises.cp)(tempDir, outDir, {
3244
- recursive: true,
3245
- force: true
3246
- });
3247
- await (0, node_fs_promises.rm)(tempDir, {
3248
- recursive: true,
3249
- force: true
3250
- });
3251
- } else {
3252
- if (backup) await safeRename(backup, outDir);
3253
- throw err;
3254
- }
3634
+ const actionMeta = action.__elurAction;
3635
+ let result;
3636
+ if (actionMeta) {
3637
+ const ctx = {
3638
+ request,
3639
+ signal: request.signal,
3640
+ idempotencyKey: request.headers.get("Idempotency-Key") ?? void 0,
3641
+ params: {},
3642
+ locals: {}
3643
+ };
3644
+ result = await action(args[0], ctx);
3645
+ } else result = await action(...args);
3646
+ if (!isActionFailure(result) && actionMeta) {
3647
+ const tags = actionMeta.invalidateTags ?? [];
3648
+ const paths = actionMeta.invalidatePaths ?? [];
3649
+ if (tags.length > 0 || paths.length > 0) await defaultInvalidator.emit({
3650
+ tags,
3651
+ paths,
3652
+ source: name
3653
+ });
3255
3654
  }
3256
- if (backup) await (0, node_fs_promises.rm)(backup, {
3257
- recursive: true,
3258
- force: true
3655
+ if (isActionFailure(result)) {
3656
+ if (wantsJson) return new Response(JSON.stringify({
3657
+ __elur_js_action_failure: true,
3658
+ status: result.status,
3659
+ data: result.data
3660
+ }), {
3661
+ status: result.status,
3662
+ headers: { "Content-Type": "application/json" }
3663
+ });
3664
+ const referer = request.headers.get("Referer") ?? "/";
3665
+ const url = new URL(referer, "http://localhost");
3666
+ const { value } = encodeActionErrorCookie(result.data, result.status);
3667
+ return new Response(null, {
3668
+ status: 303,
3669
+ headers: {
3670
+ Location: url.pathname + url.search,
3671
+ "Content-Type": "text/plain",
3672
+ "Set-Cookie": setActionErrorCookieHeader(value)
3673
+ }
3674
+ });
3675
+ }
3676
+ if (isRedirectResponse(result)) {
3677
+ if (wantsJson) return new Response(JSON.stringify({
3678
+ __elur_js_action_redirect: true,
3679
+ status: result.status,
3680
+ location: result.location
3681
+ }), {
3682
+ status: 200,
3683
+ headers: { "Content-Type": "application/json" }
3684
+ });
3685
+ return new Response(null, {
3686
+ status: result.status,
3687
+ headers: {
3688
+ Location: result.location,
3689
+ "Content-Type": "text/plain"
3690
+ }
3691
+ });
3692
+ }
3693
+ if (wantsJson) return new Response(JSON.stringify(result ?? null), {
3694
+ status: 200,
3695
+ headers: { "Content-Type": "application/json" }
3259
3696
  });
3260
- };
3261
- const rollback = async () => {
3262
- await (0, node_fs_promises.rm)(tempDir, {
3263
- recursive: true,
3264
- force: true
3697
+ const referer = request.headers.get("Referer") ?? "/";
3698
+ return new Response(null, {
3699
+ status: 303,
3700
+ headers: {
3701
+ Location: typeof result === "string" ? result : referer,
3702
+ "Content-Type": "text/plain"
3703
+ }
3265
3704
  });
3266
- };
3267
- return {
3268
- tempDir,
3269
- commit,
3270
- rollback
3271
- };
3272
- }
3273
- function basename(path) {
3274
- const parts = path.split(/[\\/]+/).filter(Boolean);
3275
- return parts[parts.length - 1] ?? "output";
3276
- }
3277
- async function safeRename(src, dest) {
3278
- await (0, node_fs_promises.rm)(dest, {
3279
- recursive: true,
3280
- force: true
3281
- });
3282
- try {
3283
- await (0, node_fs_promises.rename)(src, dest);
3284
3705
  } catch (err) {
3285
- if (isCrossDevice(err)) {
3286
- await (0, node_fs_promises.cp)(src, dest, {
3287
- recursive: true,
3288
- force: true
3289
- });
3290
- await (0, node_fs_promises.rm)(src, {
3291
- recursive: true,
3292
- force: true
3293
- });
3294
- } else throw err;
3706
+ console.error("[elur-kit] Action error:", err);
3707
+ return publicErrorResponse(err, { includeDetail: false });
3295
3708
  }
3296
3709
  }
3297
- function isCrossDevice(err) {
3298
- return err?.code === "EXDEV";
3299
- }
3710
+ var DEFAULT_BODY_LIMIT;
3711
+ var init_server = __esmMin((() => {
3712
+ init_errors();
3713
+ init_origin();
3714
+ init_invalidation();
3715
+ init_error_store();
3716
+ DEFAULT_BODY_LIMIT = 1048576;
3717
+ }));
3718
+ //#endregion
3719
+ //#region src/ssr/stream.ts
3300
3720
  /**
3301
- * Copy the public directory into the output directory.
3302
- * Returns the number of files copied.
3721
+ * Render only the inner HTML body for a page. Used by the streaming endpoint
3722
+ * to inject the real content into the shell.
3303
3723
  */
3304
- async function copyPublicAssets(options) {
3724
+ async function renderPageBody(options) {
3725
+ const { routes, pathname, searchParams, config, actions, importer = defaultImport$1, request } = options;
3726
+ const match = matchRoute(pathname, routes.pages);
3727
+ if (!match) throw new RouteNotFoundError(pathname);
3728
+ const result = await renderPage({
3729
+ route: match.route,
3730
+ params: match.params,
3731
+ searchParams,
3732
+ config,
3733
+ actions,
3734
+ importer,
3735
+ request
3736
+ });
3737
+ if (result.response) return {
3738
+ body: "",
3739
+ title: "",
3740
+ response: result.response
3741
+ };
3742
+ const body = extractAppBody(result.html)?.trim() ?? result.html.match(/<div id="app">([\s\S]*)<\/div>\s*(<script|$)/)?.[1]?.trim() ?? result.html;
3743
+ const titleMatch = result.html.match(/<title[^>]*>([^<]*)<\/title>/);
3744
+ return {
3745
+ body,
3746
+ title: titleMatch ? titleMatch[1] : result.resolvedTitle ?? "",
3747
+ fullHtml: result.html,
3748
+ clearActionErrorCookie: result.clearActionErrorCookie,
3749
+ head: result.head,
3750
+ data: result.data !== void 0 ? serializeData(result.data) : void 0,
3751
+ actions: actions && Object.keys(actions).length > 0 ? serializeData(actions) : void 0
3752
+ };
3753
+ }
3754
+ var defaultImport$1, RouteNotFoundError;
3755
+ var init_stream = __esmMin((() => {
3756
+ init_document_shell();
3757
+ init_match();
3758
+ init_render();
3759
+ defaultImport$1 = (path) => import(path);
3760
+ RouteNotFoundError = class extends Error {
3761
+ constructor(pathname) {
3762
+ super(`No route found for ${pathname}`);
3763
+ this.name = "RouteNotFoundError";
3764
+ }
3765
+ };
3766
+ }));
3767
+ //#endregion
3768
+ //#region src/runtime/static.ts
3769
+ function isInside(root, candidate) {
3770
+ return candidate === root || candidate.startsWith(`${root}${node_path.sep}`);
3771
+ }
3772
+ function decodePathname(pathname) {
3305
3773
  try {
3306
- await (0, node_fs_promises.access)(options.publicDir);
3307
- if (!(await (0, node_fs_promises.stat)(options.publicDir)).isDirectory()) return 0;
3774
+ const decoded = decodeURIComponent(pathname);
3775
+ if (decoded.includes("\0") || decoded.includes("\\") || /%(?:00|2e|2f|5c)/i.test(decoded)) return null;
3776
+ if (decoded.split("/").some((segment) => segment === "..")) return null;
3777
+ return decoded;
3308
3778
  } catch {
3309
- return 0;
3779
+ return null;
3310
3780
  }
3311
- await (0, node_fs_promises.mkdir)(options.outDir, { recursive: true });
3312
- await (0, node_fs_promises.cp)(options.publicDir, options.outDir, {
3313
- recursive: true,
3314
- force: true
3315
- });
3316
- return countFiles(options.outDir);
3317
3781
  }
3318
- async function countFiles(dir) {
3319
- const { readdir } = await import("node:fs/promises");
3320
- let count = 0;
3321
- async function walk(d) {
3322
- const entries = await readdir(d, { withFileTypes: true });
3323
- for (const entry of entries) {
3324
- const path = (0, node_path.join)(d, entry.name);
3325
- if (entry.isDirectory()) await walk(path);
3326
- else count++;
3327
- }
3782
+ async function resolveStaticFile(root, pathname) {
3783
+ const decoded = decodePathname(pathname);
3784
+ if (decoded === null) return null;
3785
+ const resolvedRoot = (0, node_path.resolve)(root);
3786
+ const relativePath = decoded.replace(/^\/+/, "");
3787
+ let candidate = (0, node_path.resolve)(resolvedRoot, relativePath);
3788
+ if (!isInside(resolvedRoot, candidate)) return null;
3789
+ try {
3790
+ if ((await (0, node_fs_promises.stat)(candidate)).isDirectory()) candidate = (0, node_path.resolve)(candidate, "index.html");
3791
+ } catch {
3792
+ if (decoded.endsWith("/") || (0, node_path.extname)(decoded) === "") candidate = (0, node_path.resolve)(candidate, "index.html");
3793
+ }
3794
+ if (!isInside(resolvedRoot, candidate)) return null;
3795
+ try {
3796
+ const [canonicalRoot, canonicalCandidate, candidateStat] = await Promise.all([
3797
+ (0, node_fs_promises.realpath)(resolvedRoot),
3798
+ (0, node_fs_promises.realpath)(candidate),
3799
+ (0, node_fs_promises.stat)(candidate)
3800
+ ]);
3801
+ if (!candidateStat.isFile() || !isInside(canonicalRoot, canonicalCandidate)) return null;
3802
+ return canonicalCandidate;
3803
+ } catch {
3804
+ return null;
3328
3805
  }
3329
- await walk(dir);
3330
- return count;
3331
3806
  }
3332
- var init_vite_build = __esmMin((() => {
3333
- init_interpolation_plugin();
3334
- }));
3807
+ var init_static = __esmMin((() => {}));
3335
3808
  //#endregion
3336
3809
  //#region src/runtime/context.ts
3337
3810
  function htmlResponse(body, status = 200, headers) {
@@ -3567,6 +4040,213 @@ var init_security_headers = __esmMin((() => {
3567
4040
  };
3568
4041
  }));
3569
4042
  //#endregion
4043
+ //#region src/router/redirects.ts
4044
+ /**
4045
+ * Checks if a pathname matches a redirect rule and returns the redirect
4046
+ * Response if so.
4047
+ */
4048
+ function matchRedirect(pathname, rules) {
4049
+ for (const rule of rules) {
4050
+ const params = matchPattern(pathname, rule.from);
4051
+ if (params) {
4052
+ const location = interpolatePath(rule.to, params);
4053
+ const status = rule.status ?? 308;
4054
+ return new Response(null, {
4055
+ status,
4056
+ headers: { Location: location }
4057
+ });
4058
+ }
4059
+ }
4060
+ }
4061
+ /**
4062
+ * Checks if a pathname matches a rewrite rule and returns the rewritten
4063
+ * pathname if so.
4064
+ */
4065
+ function matchRewrite(pathname, rules) {
4066
+ for (const rule of rules) {
4067
+ const params = matchPattern(pathname, rule.from);
4068
+ if (params) return interpolatePath(rule.to, params);
4069
+ }
4070
+ }
4071
+ /**
4072
+ * Returns headers that should be applied to a response for the given pathname.
4073
+ */
4074
+ function matchRouteHeaders(pathname, rules) {
4075
+ for (const rule of rules) if (matchPattern(pathname, rule.path)) return rule.headers;
4076
+ }
4077
+ /**
4078
+ * Matches a pathname against a pattern with :param and * wildcards.
4079
+ * Returns the extracted params, or undefined if no match.
4080
+ */
4081
+ function matchPattern(pathname, pattern) {
4082
+ const requestSegments = pathname.split("?")[0].split("/").filter(Boolean);
4083
+ const patternSegments = pattern.split("/").filter(Boolean);
4084
+ const params = {};
4085
+ let i = 0;
4086
+ for (let r = 0; r < patternSegments.length; r++) {
4087
+ const seg = patternSegments[r];
4088
+ if (seg === "*") return params;
4089
+ if (seg.endsWith("*")) {
4090
+ const name = seg.slice(1, -1);
4091
+ params[name] = requestSegments.slice(i).join("/");
4092
+ return params;
4093
+ }
4094
+ if (seg.startsWith(":")) {
4095
+ const name = seg.slice(1);
4096
+ if (requestSegments[i] === void 0) return void 0;
4097
+ params[name] = requestSegments[i];
4098
+ i++;
4099
+ continue;
4100
+ }
4101
+ if (seg !== requestSegments[i]) return void 0;
4102
+ i++;
4103
+ }
4104
+ if (i !== requestSegments.length) return void 0;
4105
+ return params;
4106
+ }
4107
+ /**
4108
+ * Interpolates :param placeholders in a path with actual values.
4109
+ */
4110
+ function interpolatePath(template, params) {
4111
+ return template.replace(/:(\w+)\*?/g, (_match, name) => {
4112
+ return params[name] ?? "";
4113
+ });
4114
+ }
4115
+ var init_redirects = __esmMin((() => {}));
4116
+ //#endregion
4117
+ //#region src/middleware/stream-boundary.ts
4118
+ /**
4119
+ * Builds the resolved content chunk for a boundary ID.
4120
+ * Emits a `<template>` element with the resolved content, followed by a
4121
+ * `<script>` that replaces the fallback div with the template content
4122
+ * in-place. This is real Suspense streaming — the browser swaps the DOM
4123
+ * node without a full re-render.
4124
+ *
4125
+ * (v2.1 — Fix #4: real Suspense streaming with `<template>` replacement)
4126
+ */
4127
+ function buildResolvedChunk(boundaryId, resolvedHtml) {
4128
+ return `<template id="${boundaryId}-tpl">${resolvedHtml}</template><script>(function(){var t=document.getElementById(${JSON.stringify(boundaryId + "-tpl")});var f=document.getElementById(${JSON.stringify(boundaryId)});if(t&&f){f.replaceWith(t.content.cloneNode(true));}document.dispatchEvent(new CustomEvent("elur:rendered"));})();<\/script>`;
4129
+ }
4130
+ var init_stream_boundary = __esmMin((() => {
4131
+ new node_async_hooks.AsyncLocalStorage();
4132
+ }));
4133
+ //#endregion
4134
+ //#region src/ssr/stream-response.ts
4135
+ /**
4136
+ * Mid-stream error notice swapped into the loading boundary when the
4137
+ * background render fails after the shell was already sent. Inline styles
4138
+ * keep it self-contained (the page's CSS may assume the final layout).
4139
+ */
4140
+ function buildErrorNotice() {
4141
+ return "<div role=\"alert\" style=\"margin:2rem auto;max-width:32rem;padding:1rem 1.25rem;border:1px solid #e5484d;border-radius:8px;color:#b3373c;font-family:system-ui,sans-serif\"><strong style=\"display:block;margin-bottom:.25rem\">No se pudo cargar el contenido.</strong><span>Recarga la página para intentarlo de nuevo.</span></div>";
4142
+ }
4143
+ /**
4144
+ * Creates a streaming Response that sends the shell + loading fallback first,
4145
+ * then appends the resolved content.
4146
+ *
4147
+ * If the route has no loading boundary, falls back to a normal renderPage.
4148
+ */
4149
+ async function createStreamingResponse(options) {
4150
+ const { route, params, searchParams, config, actions, importer = defaultImport, request, signal } = options;
4151
+ if (!route.loadingPath) {
4152
+ const result = await renderPage({
4153
+ route,
4154
+ params,
4155
+ searchParams,
4156
+ config,
4157
+ actions,
4158
+ importer,
4159
+ request
4160
+ });
4161
+ if (result.response) return result.response;
4162
+ return new Response(result.html, { headers: { "Content-Type": "text/html; charset=utf-8" } });
4163
+ }
4164
+ if (signal?.aborted) return new Response("Client Closed Request", { status: 499 });
4165
+ const loadingHtml = await renderToString((await importer(route.loadingPath)).default);
4166
+ const boundaryId = `elur-stream-${(0, node_crypto.randomUUID)().slice(0, 8)}`;
4167
+ const routerCfg = config.router;
4168
+ const routerEnabled = routerCfg?.enabled !== false;
4169
+ const routerEntry = routerCfg?.entry && routerEnabled && config.js !== "legacy" ? routerCfg.entry : void 0;
4170
+ const shellHtml = documentShell({
4171
+ title: "Loading...",
4172
+ lang: config.lang,
4173
+ body: `<div id="${boundaryId}">${loadingHtml}</div>`,
4174
+ data: {
4175
+ __elur_js_streaming: true,
4176
+ page: route.path
4177
+ },
4178
+ actions,
4179
+ clientEntry: config.clientEntry,
4180
+ routerEntry,
4181
+ routerEnabled: routerCfg ? routerEnabled : void 0,
4182
+ renderEndpoint: config.renderEndpoint
4183
+ });
4184
+ let aborted = false;
4185
+ const stream = new ReadableStream({
4186
+ async start(controller) {
4187
+ const encoder = new TextEncoder();
4188
+ const onAbort = () => {
4189
+ aborted = true;
4190
+ try {
4191
+ controller.close();
4192
+ } catch {}
4193
+ };
4194
+ signal?.addEventListener("abort", onAbort, { once: true });
4195
+ /** Enqueue unless the client went away mid-render. */
4196
+ const send = (html) => {
4197
+ if (aborted) return;
4198
+ controller.enqueue(encoder.encode(html));
4199
+ };
4200
+ try {
4201
+ send(shellHtml);
4202
+ const result = await renderPage({
4203
+ route,
4204
+ params,
4205
+ searchParams,
4206
+ config,
4207
+ actions,
4208
+ importer,
4209
+ request
4210
+ });
4211
+ if (aborted) return;
4212
+ if (result.response) {
4213
+ const status = result.response.status;
4214
+ const location = result.response.headers.get("Location");
4215
+ if (location && (status === 301 || status === 302 || status === 307 || status === 308)) send(`<script>window.location.href=${JSON.stringify(location)};<\/script>`);
4216
+ else send(buildResolvedChunk(boundaryId, buildErrorNotice()) + `<script>console.error(${JSON.stringify(`Loader responded with status ${status}`)});<\/script>`);
4217
+ return;
4218
+ }
4219
+ const innerBody = extractAppBody(result.html) ?? result.html.match(/<div id="app">([\s\S]*)<\/div>\s*(<script|$)/)?.[1]?.trim() ?? result.html;
4220
+ send(buildResolvedChunk(boundaryId, innerBody));
4221
+ } catch (err) {
4222
+ const errorMsg = err instanceof Error ? err.message : String(err);
4223
+ send(buildResolvedChunk(boundaryId, buildErrorNotice()) + `<script>console.error(${JSON.stringify(errorMsg)});<\/script>`);
4224
+ } finally {
4225
+ signal?.removeEventListener("abort", onAbort);
4226
+ if (!aborted) controller.close();
4227
+ }
4228
+ },
4229
+ cancel() {
4230
+ aborted = true;
4231
+ }
4232
+ });
4233
+ return new Response(stream, { headers: STREAM_HEADERS });
4234
+ }
4235
+ var STREAM_HEADERS, defaultImport;
4236
+ var init_stream_response = __esmMin((() => {
4237
+ init_render_to_string();
4238
+ init_document_shell();
4239
+ init_render();
4240
+ init_stream_boundary();
4241
+ init_capabilities();
4242
+ STREAM_HEADERS = {
4243
+ "Content-Type": "text/html; charset=utf-8",
4244
+ "X-Accel-Buffering": "no",
4245
+ "Cache-Control": "no-store"
4246
+ };
4247
+ defaultImport = (path) => import(path);
4248
+ }));
4249
+ //#endregion
3570
4250
  //#region src/runtime/handler.ts
3571
4251
  var handler_exports = /* @__PURE__ */ __exportAll({ createWebHandler: () => createWebHandler });
3572
4252
  /**
@@ -3580,14 +4260,28 @@ function createWebHandler(routes, actions, options) {
3580
4260
  const clientEntry = options.clientEntry;
3581
4261
  const renderEndpoint = options.renderEndpoint ?? true;
3582
4262
  const noCache = options.noCache ?? false;
3583
- const cacheDir = options.cacheDir;
3584
4263
  const defaultRevalidate = options.defaultRevalidate;
3585
4264
  const renderConfig = {
3586
4265
  lang,
3587
4266
  clientEntry,
3588
- renderEndpoint
4267
+ renderEndpoint,
4268
+ router: options.router ? {
4269
+ enabled: options.router.enabled !== false,
4270
+ entry: options.router.entry
4271
+ } : void 0,
4272
+ js: options.js
3589
4273
  };
3590
4274
  const securityHeadersConfig = options.securityHeaders ?? {};
4275
+ const redirectRules = options.redirects ?? [];
4276
+ const rewriteRules = options.rewrites ?? [];
4277
+ const routeHeaderRules = options.routeHeaders ?? [];
4278
+ const capabilities = options.capabilities ?? DEFAULT_CAPABILITIES;
4279
+ const streamingEnabled = options.streaming === true && supportsStreaming(capabilities);
4280
+ const cacheAdapter = resolveCacheAdapter(options);
4281
+ if (cacheAdapter && !invalidatorConnectedAdapters.has(cacheAdapter)) {
4282
+ invalidatorConnectedAdapters.add(cacheAdapter);
4283
+ connectCacheAdapter(cacheAdapter);
4284
+ }
3591
4285
  function createActionResolver() {
3592
4286
  return async (name, page) => {
3593
4287
  const pageKey = page ? routes.pages.some((route) => route.path === page) ? page : matchRoute(page, routes.pages)?.route.path ?? page : void 0;
@@ -3604,20 +4298,29 @@ function createWebHandler(routes, actions, options) {
3604
4298
  };
3605
4299
  }
3606
4300
  const actionResolver = createActionResolver();
3607
- async function handleActions(request) {
4301
+ async function handleActions(request, logger) {
4302
+ const stopTimer = logger.startTimer("action", "Server action");
3608
4303
  try {
3609
4304
  return await handleActionRequest(request, actionResolver);
3610
4305
  } catch (err) {
3611
- console.error("[elur-kit] action error:", err);
4306
+ logger.error("[elur-kit] action error", {
4307
+ path: new URL(request.url).pathname,
4308
+ method: request.method,
4309
+ error: errorMessage(err),
4310
+ stack: errorStack(err)
4311
+ });
3612
4312
  return publicErrorResponse(err, { includeDetail: noCache });
4313
+ } finally {
4314
+ stopTimer();
3613
4315
  }
3614
4316
  }
3615
- async function handleRenderEndpoint(request, url) {
4317
+ async function handleRenderEndpoint(request, url, logger) {
3616
4318
  const page = url.searchParams.get("page") ?? "/";
3617
4319
  const search = url.searchParams.get("search") ?? "";
3618
4320
  const wantsJson = (request.headers.get("Accept") ?? "").includes("application/json");
4321
+ const stopTimer = logger.startTimer("render-endpoint", "SPA render endpoint");
3619
4322
  try {
3620
- const { body, title } = await renderPageBody({
4323
+ const result = await renderPageBody({
3621
4324
  routes,
3622
4325
  pathname: page,
3623
4326
  searchParams: new URLSearchParams(search),
@@ -3626,21 +4329,39 @@ function createWebHandler(routes, actions, options) {
3626
4329
  request,
3627
4330
  importer: options.importer
3628
4331
  });
3629
- if (wantsJson) return jsonResponse({
3630
- title,
3631
- body
3632
- });
3633
- return htmlResponse(body);
4332
+ if (result.response) return result.response;
4333
+ const { body, title, head, clearActionErrorCookie, data, actions } = result;
4334
+ if (wantsJson) {
4335
+ const headers = {};
4336
+ if (clearActionErrorCookie) headers["X-Elur-Action-Clear-Cookie"] = clearActionErrorCookie;
4337
+ return jsonResponse({
4338
+ title,
4339
+ body,
4340
+ head: head ?? null,
4341
+ data: data ?? null,
4342
+ actions: actions ?? null,
4343
+ clearActionErrorCookie: clearActionErrorCookie ?? null
4344
+ }, 200, headers);
4345
+ }
4346
+ return htmlResponse(body, 200, clearActionErrorCookie ? { "Set-Cookie": clearActionErrorCookie } : void 0);
3634
4347
  } catch (err) {
3635
4348
  if (err instanceof RouteNotFoundError) return notFound("Not Found");
3636
4349
  if (err instanceof Response) return err;
3637
- console.error("[elur-kit] render endpoint error:", err);
4350
+ logger.error("[elur-kit] render endpoint error", {
4351
+ path: url.pathname,
4352
+ page,
4353
+ error: errorMessage(err),
4354
+ stack: errorStack(err)
4355
+ });
3638
4356
  return publicErrorResponse(err, { includeDetail: noCache });
4357
+ } finally {
4358
+ stopTimer();
3639
4359
  }
3640
4360
  }
3641
- async function handleApiRoute(request, pathname) {
4361
+ async function handleApiRoute(request, pathname, logger, middlewareLocals) {
3642
4362
  const apiMatch = matchApiRoute(pathname, routes.api);
3643
4363
  if (!apiMatch) return null;
4364
+ const stopTimer = logger.startTimer("api", "API route");
3644
4365
  try {
3645
4366
  let mod;
3646
4367
  if (options.importer) mod = await options.importer(apiMatch.route.routePath);
@@ -3649,11 +4370,19 @@ function createWebHandler(routes, actions, options) {
3649
4370
  if (typeof handler !== "function") return methodNotAllowed(request.method ?? "GET");
3650
4371
  return await handler(request, {
3651
4372
  params: apiMatch.params,
3652
- locals: {}
4373
+ locals: middlewareLocals ?? {}
3653
4374
  });
3654
4375
  } catch (err) {
3655
- console.error("[elur-kit] API route error:", err);
4376
+ logger.error("[elur-kit] API route error", {
4377
+ path: pathname,
4378
+ method: request.method,
4379
+ route: apiMatch.route.path,
4380
+ error: errorMessage(err),
4381
+ stack: errorStack(err)
4382
+ });
3656
4383
  return publicErrorResponse(err, { includeDetail: noCache });
4384
+ } finally {
4385
+ stopTimer();
3657
4386
  }
3658
4387
  }
3659
4388
  async function handleStatic(pathname, request) {
@@ -3698,7 +4427,7 @@ function createWebHandler(routes, actions, options) {
3698
4427
  }
3699
4428
  return response;
3700
4429
  }
3701
- async function handleDynamicRender(request, pathname) {
4430
+ async function handleDynamicRender(request, pathname, logger) {
3702
4431
  const match = matchRoute(pathname, routes.pages);
3703
4432
  if (!match) {
3704
4433
  const errorResult = await renderErrorPage({
@@ -3711,12 +4440,44 @@ function createWebHandler(routes, actions, options) {
3711
4440
  if (errorResult) return htmlResponse(errorResult.html, errorResult.status);
3712
4441
  return notFound(`Not found: ${pathname}`);
3713
4442
  }
3714
- const cacheable = !noCache && cacheDir && isCacheable(request);
3715
- if (cacheable && cacheDir) {
3716
- const cached = await getCachedHtml(cacheDir, pathname);
3717
- if (cached) return htmlResponse(cached.html);
4443
+ if (streamingEnabled && match.route.loadingPath) {
4444
+ const stopStreamTimer = logger.startTimer("ssr", "SSR stream shell");
4445
+ try {
4446
+ return await createStreamingResponse({
4447
+ route: match.route,
4448
+ params: match.params,
4449
+ searchParams: new URLSearchParams(request.url.split("?")[1] ?? ""),
4450
+ config: renderConfig,
4451
+ actions: publicActions,
4452
+ importer: options.importer,
4453
+ request,
4454
+ signal: request.signal
4455
+ });
4456
+ } catch (err) {
4457
+ if (err instanceof Response) return err;
4458
+ logger.error("[elur-kit] SSR stream error", {
4459
+ path: pathname,
4460
+ route: match.route.path,
4461
+ error: errorMessage(err),
4462
+ stack: errorStack(err)
4463
+ });
4464
+ const errorResult = await renderErrorPage({
4465
+ routes,
4466
+ status: 500,
4467
+ error: err,
4468
+ config: renderConfig,
4469
+ actions: publicActions,
4470
+ importer: options.importer
4471
+ }).catch(() => void 0);
4472
+ if (errorResult) return htmlResponse(errorResult.html, errorResult.status);
4473
+ return publicErrorResponse(err, { includeDetail: noCache });
4474
+ } finally {
4475
+ stopStreamTimer();
4476
+ }
3718
4477
  }
3719
- try {
4478
+ const cacheable = !noCache && cacheAdapter && isCacheable(request);
4479
+ const pageCacheKey = cacheable ? cacheKey(pathname) : void 0;
4480
+ const renderAndStore = async () => {
3720
4481
  const result = await renderPage({
3721
4482
  route: match.route,
3722
4483
  params: match.params,
@@ -3727,14 +4488,43 @@ function createWebHandler(routes, actions, options) {
3727
4488
  importer: options.importer
3728
4489
  });
3729
4490
  if (result.response) return result.response;
3730
- if (cacheable && cacheDir && isResultCacheable(result, request)) {
4491
+ if (cacheable && cacheAdapter && pageCacheKey && isResultCacheable(result, request)) {
3731
4492
  const revalidateSeconds = result.revalidate ?? defaultRevalidate ?? 0;
3732
- if (revalidateSeconds > 0) await setCachedHtml(cacheDir, pathname, result.html, revalidateSeconds);
4493
+ if (revalidateSeconds > 0) await cacheAdapter.set(pageCacheKey, {
4494
+ html: result.html,
4495
+ generatedAt: Date.now(),
4496
+ revalidate: revalidateSeconds
4497
+ }, {
4498
+ revalidate: revalidateSeconds,
4499
+ tags: result.cachePolicy?.tags
4500
+ });
3733
4501
  }
3734
4502
  return htmlResponse(result.html);
4503
+ };
4504
+ if (cacheable && cacheAdapter && pageCacheKey) {
4505
+ const cached = await cacheAdapter.get(pageCacheKey);
4506
+ if (cached) {
4507
+ if (Date.now() - cached.generatedAt >= cached.revalidate * 1e3) renderAndStore().catch((err) => {
4508
+ logger.error("[elur-kit] background cache revalidation failed", {
4509
+ path: pathname,
4510
+ error: errorMessage(err),
4511
+ stack: errorStack(err)
4512
+ });
4513
+ });
4514
+ return htmlResponse(cached.html);
4515
+ }
4516
+ }
4517
+ const stopTimer = logger.startTimer("ssr", "SSR render");
4518
+ try {
4519
+ return await renderAndStore();
3735
4520
  } catch (err) {
3736
4521
  if (err instanceof Response) return err;
3737
- console.error("[elur-kit] SSR render error:", err);
4522
+ logger.error("[elur-kit] SSR render error", {
4523
+ path: pathname,
4524
+ route: match.route.path,
4525
+ error: errorMessage(err),
4526
+ stack: errorStack(err)
4527
+ });
3738
4528
  const errorResult = await renderErrorPage({
3739
4529
  routes,
3740
4530
  status: 500,
@@ -3745,22 +4535,83 @@ function createWebHandler(routes, actions, options) {
3745
4535
  }).catch(() => void 0);
3746
4536
  if (errorResult) return htmlResponse(errorResult.html, errorResult.status);
3747
4537
  return publicErrorResponse(err, { includeDetail: noCache });
4538
+ } finally {
4539
+ stopTimer();
3748
4540
  }
3749
4541
  }
4542
+ function finalizeResponse(response, logger, secHeaders, routeHeaders) {
4543
+ const secured = applySecurityHeaders(response, secHeaders);
4544
+ const headers = new Headers(secured.headers);
4545
+ if (routeHeaders) for (const [key, value] of Object.entries(routeHeaders)) headers.set(key, value);
4546
+ const timing = logger.getServerTimingHeader();
4547
+ if (timing) headers.set("Server-Timing", timing);
4548
+ headers.set("X-Request-ID", logger.getRequestId());
4549
+ return new Response(secured.body, {
4550
+ status: secured.status,
4551
+ statusText: secured.statusText,
4552
+ headers
4553
+ });
4554
+ }
3750
4555
  return async function handler(request) {
4556
+ const logger = createRequestLogger(request, options.logLevel);
3751
4557
  const url = new URL(request.url);
3752
- const pathname = url.pathname;
4558
+ const originalPathname = url.pathname;
3753
4559
  const isHttps = url.protocol === "https:";
3754
4560
  const secHeaders = securityHeadersConfig === false ? {} : buildSecurityHeaders(securityHeadersConfig, isHttps);
3755
- if (pathname === "/__elur-js/actions" && request.method === "POST") return applySecurityHeaders(await handleActions(request), secHeaders);
3756
- if (pathname === "/__elur-js/render" && renderEndpoint) return applySecurityHeaders(await handleRenderEndpoint(request, url), secHeaders);
3757
- const apiResponse = await handleApiRoute(request, pathname);
3758
- if (apiResponse) return applySecurityHeaders(apiResponse, secHeaders);
4561
+ if (redirectRules.length > 0) {
4562
+ const redirect = matchRedirect(originalPathname, redirectRules);
4563
+ if (redirect) return finalizeResponse(redirect, logger, secHeaders, matchRouteHeaders(originalPathname, routeHeaderRules));
4564
+ }
4565
+ let pathname = originalPathname;
4566
+ if (rewriteRules.length > 0) pathname = matchRewrite(originalPathname, rewriteRules) ?? originalPathname;
4567
+ const routeHeaders = matchRouteHeaders(originalPathname, routeHeaderRules);
4568
+ if (pathname === "/__elur-js/actions" && request.method === "POST") return finalizeResponse(await handleActions(request, logger), logger, secHeaders, routeHeaders);
4569
+ if (pathname === "/__elur-js/render" && renderEndpoint) return finalizeResponse(await handleRenderEndpoint(request, url, logger), logger, secHeaders, routeHeaders);
4570
+ let middlewareLocals;
4571
+ const middleware = options.middleware;
4572
+ if (middleware && matchesMiddleware(pathname, middleware.config)) {
4573
+ let mwResult;
4574
+ try {
4575
+ mwResult = await runMiddleware(middleware, request);
4576
+ } catch (err) {
4577
+ logger.error("[elur-kit] middleware error", {
4578
+ path: pathname,
4579
+ error: errorMessage(err),
4580
+ stack: errorStack(err)
4581
+ });
4582
+ return finalizeResponse(publicErrorResponse(err, { includeDetail: noCache }), logger, secHeaders, routeHeaders);
4583
+ }
4584
+ if (mwResult.kind === "response") return finalizeResponse(mwResult.response, logger, secHeaders, routeHeaders);
4585
+ middlewareLocals = mwResult.locals;
4586
+ if (mwResult.headers) {
4587
+ const merged = new Headers(request.headers);
4588
+ for (const [key, value] of Object.entries(mwResult.headers)) merged.set(key, value);
4589
+ request = new Request(request, { headers: merged });
4590
+ }
4591
+ }
4592
+ const apiResponse = await handleApiRoute(request, pathname, logger, middlewareLocals);
4593
+ if (apiResponse) return finalizeResponse(apiResponse, logger, secHeaders, routeHeaders);
3759
4594
  const staticResponse = await handleStatic(pathname, request);
3760
- if (staticResponse) return applySecurityHeaders(staticResponse, secHeaders);
3761
- return applySecurityHeaders(await handleDynamicRender(request, pathname), secHeaders);
4595
+ if (staticResponse) return finalizeResponse(staticResponse, logger, secHeaders, routeHeaders);
4596
+ return finalizeResponse(await handleDynamicRender(request, pathname, logger), logger, secHeaders, routeHeaders);
3762
4597
  };
3763
4598
  }
4599
+ function resolveCacheAdapter(options) {
4600
+ if (options.cacheAdapter) return options.cacheAdapter;
4601
+ if (!options.cacheDir) return void 0;
4602
+ let adapter = defaultCacheAdapters.get(options.cacheDir);
4603
+ if (!adapter) {
4604
+ adapter = createFsCacheAdapter({ cacheDir: options.cacheDir });
4605
+ defaultCacheAdapters.set(options.cacheDir, adapter);
4606
+ }
4607
+ return adapter;
4608
+ }
4609
+ function errorMessage(err) {
4610
+ return err instanceof Error ? err.message : String(err);
4611
+ }
4612
+ function errorStack(err) {
4613
+ return err instanceof Error ? err.stack : void 0;
4614
+ }
3764
4615
  function isCacheable(request) {
3765
4616
  if (request.method !== "GET" && request.method !== "HEAD") return false;
3766
4617
  if (request.headers.get("Cookie")) return false;
@@ -3780,6 +4631,7 @@ function isResultCacheable(result, request) {
3780
4631
  if (request.headers.get("Authorization")) return false;
3781
4632
  return true;
3782
4633
  }
4634
+ var defaultCacheAdapters, invalidatorConnectedAdapters;
3783
4635
  var init_handler = __esmMin((() => {
3784
4636
  init_match();
3785
4637
  init_server();
@@ -3788,9 +4640,16 @@ var init_handler = __esmMin((() => {
3788
4640
  init_scan();
3789
4641
  init_context();
3790
4642
  init_errors();
3791
- init_cache();
4643
+ init_adapter();
4644
+ init_invalidation();
3792
4645
  init_policy();
3793
4646
  init_security_headers();
4647
+ init_redirects();
4648
+ init_middleware();
4649
+ init_stream_response();
4650
+ init_capabilities();
4651
+ defaultCacheAdapters = /* @__PURE__ */ new Map();
4652
+ invalidatorConnectedAdapters = /* @__PURE__ */ new WeakSet();
3794
4653
  }));
3795
4654
  //#endregion
3796
4655
  //#region src/adapters/shared.ts
@@ -3878,8 +4737,10 @@ async function buildSsrEntry(routes, options, entryDir) {
3878
4737
  }
3879
4738
  if (names.length > 0) actionsRegistry[page.path] = names;
3880
4739
  }
4740
+ const routerEnabled = options.router?.enabled !== false;
4741
+ const routerEntry = routerEnabled && options.js !== "legacy" && (0, node_fs.existsSync)((0, node_path.resolve)(options.root, options.outDir, "_elur", "router.js")) ? "/_elur/router.js" : null;
3881
4742
  return `// AUTO-GENERATED by @elurjs/kit. Do not edit.
3882
- import { handleActionRequest, matchApiRoute, matchRoute, renderPage, renderErrorPage } from "@elurjs/kit";
4743
+ import { handleActionRequest, matchApiRoute, matchRoute, renderPage, renderPageBody, renderErrorPage, createStreamingResponse } from "@elurjs/kit";
3883
4744
  ${imports}
3884
4745
 
3885
4746
  const registry = new Map<string, unknown>([
@@ -3909,6 +4770,15 @@ const routes = {
3909
4770
 
3910
4771
  const clientEntry = ${JSON.stringify(options.clientEntry)};
3911
4772
  const lang = ${JSON.stringify(options.lang)};
4773
+ // Client router/JS emission rules baked at adapter build time.
4774
+ const router = ${JSON.stringify({
4775
+ enabled: routerEnabled,
4776
+ entry: routerEntry
4777
+ })};
4778
+ const jsMode = ${JSON.stringify(options.js === "legacy" ? "legacy" : "modern")};
4779
+ // Opt-in streaming SSR (experimental): routes with a loading boundary stream
4780
+ // the shell first and swap in the resolved content as a follow-up chunk.
4781
+ const streaming = ${options.streaming === true};
3912
4782
 
3913
4783
  function loadModule(path: string) {
3914
4784
  const mod = registry.get(path);
@@ -3957,37 +4827,38 @@ export default async function handler(request: Request): Promise<Response> {
3957
4827
  const search = url.searchParams.get("search") ?? "";
3958
4828
  const wantsJson = (request.headers.get("Accept") ?? "").includes("application/json");
3959
4829
  try {
3960
- const match = matchRoute(page, routes.pages);
3961
- if (!match) throw new Error(\`No route found for \${page}\`);
3962
- const { html } = await renderPage({
3963
- route: match.route,
3964
- params: match.params,
4830
+ const result = await renderPageBody({
4831
+ routes,
4832
+ pathname: page,
3965
4833
  searchParams: new URLSearchParams(search),
3966
- config: { lang, clientEntry },
4834
+ config: { lang, clientEntry, router, js: jsMode },
3967
4835
  importer: loadModule,
3968
4836
  actions,
3969
4837
  request,
3970
4838
  });
3971
- const bodyStart = html.indexOf('<div id="app">');
3972
- const bodyEnd = html.lastIndexOf("</div>");
3973
- const body = bodyStart >= 0 && bodyEnd > bodyStart
3974
- ? html.slice(bodyStart + 13, bodyEnd).trim()
3975
- : html;
3976
- const titleStart = html.indexOf("<title>");
3977
- const titleEnd = html.indexOf("</title>");
3978
- const title = titleStart >= 0 && titleEnd > titleStart
3979
- ? html.slice(titleStart + 7, titleEnd)
3980
- : "";
4839
+ // A thrown Response from a loader is a first-class response (A-22).
4840
+ if (result.response) return result.response;
4841
+ const { body, title, head, clearActionErrorCookie, data, actions: actionsPayload } = result;
3981
4842
  if (wantsJson) {
3982
- return new Response(JSON.stringify({ title, body }), {
3983
- status: 200,
3984
- headers: { "Content-Type": "application/json; charset=utf-8" },
3985
- });
4843
+ const headers = { "Content-Type": "application/json; charset=utf-8" };
4844
+ if (clearActionErrorCookie) headers["X-Elur-Action-Clear-Cookie"] = clearActionErrorCookie;
4845
+ // The ?? null fallbacks keep every key present — JSON.stringify drops
4846
+ // undefined and the SPA payload shape must be stable across runtimes.
4847
+ return new Response(
4848
+ JSON.stringify({
4849
+ title,
4850
+ body,
4851
+ head: head ?? null,
4852
+ data: data ?? null,
4853
+ actions: actionsPayload ?? null,
4854
+ clearActionErrorCookie: clearActionErrorCookie ?? null,
4855
+ }),
4856
+ { status: 200, headers },
4857
+ );
3986
4858
  }
3987
- return new Response(body, {
3988
- status: 200,
3989
- headers: { "Content-Type": "text/html; charset=utf-8" },
3990
- });
4859
+ const headers = { "Content-Type": "text/html; charset=utf-8" };
4860
+ if (clearActionErrorCookie) headers["Set-Cookie"] = clearActionErrorCookie;
4861
+ return new Response(body, { status: 200, headers });
3991
4862
  } catch (err) {
3992
4863
  if ((err as { name?: string }).name === "RouteNotFoundError") {
3993
4864
  return new Response("Not Found", {
@@ -4018,7 +4889,7 @@ export default async function handler(request: Request): Promise<Response> {
4018
4889
 
4019
4890
  const match = matchRoute(url.pathname, routes.pages);
4020
4891
  if (!match) {
4021
- const errorResult = await renderErrorPage({ routes, status: 404, config: { lang, clientEntry }, actions, importer: loadModule });
4892
+ const errorResult = await renderErrorPage({ routes, status: 404, config: { lang, clientEntry, router, js: jsMode }, actions, importer: loadModule });
4022
4893
  if (errorResult) {
4023
4894
  return new Response(errorResult.html, { status: errorResult.status, headers: { "Content-Type": "text/html; charset=utf-8" } });
4024
4895
  }
@@ -4026,19 +4897,37 @@ export default async function handler(request: Request): Promise<Response> {
4026
4897
  }
4027
4898
 
4028
4899
  try {
4029
- const { html } = await renderPage({
4900
+ if (streaming && match.route.loadingPath) {
4901
+ // Streaming SSR: shell + loading boundary first, resolved content as a
4902
+ // follow-up chunk. Streamed pages are rendered live (no cache).
4903
+ return createStreamingResponse({
4904
+ route: match.route,
4905
+ params: match.params,
4906
+ searchParams: new URLSearchParams(url.search),
4907
+ config: { lang, clientEntry, router, js: jsMode },
4908
+ importer: loadModule,
4909
+ actions,
4910
+ request,
4911
+ signal: request.signal,
4912
+ });
4913
+ }
4914
+ const result = await renderPage({
4030
4915
  route: match.route,
4031
4916
  params: match.params,
4032
4917
  searchParams: new URLSearchParams(url.search),
4033
- config: { lang, clientEntry },
4918
+ config: { lang, clientEntry, router, js: jsMode },
4034
4919
  importer: loadModule,
4035
4920
  actions,
4036
4921
  request,
4037
4922
  });
4038
- return new Response(html, { status: 200, headers: { "Content-Type": "text/html; charset=utf-8" } });
4923
+ // A thrown Response from a loader is a first-class response (A-22).
4924
+ if (result.response) return result.response;
4925
+ const headers = { "Content-Type": "text/html; charset=utf-8" };
4926
+ if (result.clearActionErrorCookie) headers["Set-Cookie"] = result.clearActionErrorCookie;
4927
+ return new Response(result.html, { status: 200, headers });
4039
4928
  } catch (err) {
4040
4929
  console.error("[elur-kit] SSR render error:", err);
4041
- const errorResult = await renderErrorPage({ routes, status: 500, error: err, config: { lang, clientEntry }, actions, importer: loadModule });
4930
+ const errorResult = await renderErrorPage({ routes, status: 500, error: err, config: { lang, clientEntry, router, js: jsMode }, actions, importer: loadModule });
4042
4931
  if (errorResult) {
4043
4932
  return new Response(errorResult.html, { status: errorResult.status, headers: { "Content-Type": "text/html; charset=utf-8" } });
4044
4933
  }
@@ -4201,6 +5090,15 @@ var init_netlify = __esmMin((() => {
4201
5090
  //#region src/adapters/bun.ts
4202
5091
  var bun_exports = /* @__PURE__ */ __exportAll({ bunAdapter: () => bunAdapter });
4203
5092
  function buildBunServerSource(outDirUrl, options) {
5093
+ const logLevelOption = options.logLevel ? `, logLevel: ${JSON.stringify(options.logLevel)}` : "";
5094
+ const routingOptions = [
5095
+ "redirects",
5096
+ "rewrites",
5097
+ "routeHeaders"
5098
+ ].map((key) => {
5099
+ const rules = options[key];
5100
+ return rules && rules.length > 0 ? `, ${key}: ${JSON.stringify(rules)}` : "";
5101
+ }).join("");
4204
5102
  return `// AUTO-GENERATED by @elurjs/kit. Do not edit.
4205
5103
  import { fileURLToPath } from "node:url";
4206
5104
  import { createWebHandler } from "@elurjs/kit/runtime";
@@ -4212,7 +5110,7 @@ const port = Number(process.env.PORT) || ${options.port ?? 3e3};
4212
5110
  const webHandler = createWebHandler(
4213
5111
  { pages: [], api: [], error404: undefined, error500: undefined },
4214
5112
  {},
4215
- { staticRoot: outDir, lang: ${JSON.stringify(options.lang)}, clientEntry: ${JSON.stringify(options.clientEntry)} },
5113
+ { staticRoot: outDir, lang: ${JSON.stringify(options.lang)}, clientEntry: ${JSON.stringify(options.clientEntry)}${logLevelOption}${routingOptions} },
4216
5114
  );
4217
5115
 
4218
5116
  Bun.serve({
@@ -4268,11 +5166,20 @@ var init_bun = __esmMin((() => {
4268
5166
  //#region src/adapters/node.ts
4269
5167
  var node_exports = /* @__PURE__ */ __exportAll({ nodeAdapter: () => nodeAdapter });
4270
5168
  function buildNodeServerSource(outDirUrl, options) {
5169
+ const logLevelOption = options.logLevel ? `, logLevel: ${JSON.stringify(options.logLevel)}` : "";
5170
+ const routingOptions = [
5171
+ "redirects",
5172
+ "rewrites",
5173
+ "routeHeaders"
5174
+ ].map((key) => {
5175
+ const rules = options[key];
5176
+ return rules && rules.length > 0 ? `, ${key}: ${JSON.stringify(rules)}` : "";
5177
+ }).join("");
4271
5178
  return `// AUTO-GENERATED by @elurjs/kit. Do not edit.
4272
5179
  import { createServer } from "node:http";
4273
5180
  import { fileURLToPath } from "node:url";
4274
5181
  import { createWebHandler } from "@elurjs/kit/runtime";
4275
- import { incomingMessageToRequest } from "@elurjs/kit/runtime";
5182
+ import { incomingMessageToRequest, sendWebResponse } from "@elurjs/kit/runtime";
4276
5183
  import handler from "./node-index.ts";
4277
5184
 
4278
5185
  const outDir = fileURLToPath(new URL(${JSON.stringify(outDirUrl)}, import.meta.url));
@@ -4284,7 +5191,7 @@ const port = Number(process.env.PORT) || ${options.port ?? 3e3};
4284
5191
  const webHandler = createWebHandler(
4285
5192
  { pages: [], api: [], error404: undefined, error500: undefined },
4286
5193
  {},
4287
- { staticRoot: outDir, lang: ${JSON.stringify(options.lang)}, clientEntry: ${JSON.stringify(options.clientEntry)} },
5194
+ { staticRoot: outDir, lang: ${JSON.stringify(options.lang)}, clientEntry: ${JSON.stringify(options.clientEntry)}${logLevelOption}${routingOptions} },
4288
5195
  );
4289
5196
 
4290
5197
  createServer(async (req, res) => {
@@ -4298,8 +5205,8 @@ createServer(async (req, res) => {
4298
5205
  if (response.status === 404) {
4299
5206
  response = await handler(request);
4300
5207
  }
4301
- res.writeHead(response.status, Object.fromEntries(response.headers.entries()));
4302
- res.end(Buffer.from(await response.arrayBuffer()));
5208
+ // Streams the body: streaming SSR chunks flush as they are produced.
5209
+ await sendWebResponse(res, response);
4303
5210
  }).listen(port, () => {
4304
5211
  console.log(\`Node server running at http://localhost:\${port}\`);
4305
5212
  });
@@ -4621,6 +5528,7 @@ var init_commands = __esmMin((() => {
4621
5528
  //#region src/cli.ts
4622
5529
  init_scan();
4623
5530
  init_route_scanner();
5531
+ init_logger();
4624
5532
  init_capabilities();
4625
5533
  function parseArgs(argv) {
4626
5534
  const args = argv.slice(2);
@@ -4649,6 +5557,7 @@ function parseArgs(argv) {
4649
5557
  let cacheDir;
4650
5558
  let defaultRevalidate;
4651
5559
  let configFile;
5560
+ let logLevel;
4652
5561
  for (let i = optionStart; i < args.length; i++) {
4653
5562
  const arg = args[i];
4654
5563
  const next = args[i + 1];
@@ -4716,6 +5625,12 @@ function parseArgs(argv) {
4716
5625
  defaultRevalidate = Number(next);
4717
5626
  i++;
4718
5627
  break;
5628
+ case "--verbose":
5629
+ if (logLevel !== "error") logLevel = "debug";
5630
+ break;
5631
+ case "--quiet":
5632
+ logLevel = "error";
5633
+ break;
4719
5634
  case "--help":
4720
5635
  case "-?":
4721
5636
  printHelp();
@@ -4741,7 +5656,8 @@ function parseArgs(argv) {
4741
5656
  clientConfig: clientConfig ? (0, node_path.resolve)(root, clientConfig) : void 0,
4742
5657
  cacheDir: cacheDir ? (0, node_path.resolve)(root, cacheDir) : void 0,
4743
5658
  defaultRevalidate,
4744
- configFile: configFile ? (0, node_path.resolve)(root, configFile) : void 0
5659
+ configFile: configFile ? (0, node_path.resolve)(root, configFile) : void 0,
5660
+ logLevel
4745
5661
  };
4746
5662
  }
4747
5663
  function printHelp() {
@@ -4773,8 +5689,23 @@ Options:
4773
5689
  --config <path> Elur config file (default: elur.config.ts/js/mjs)
4774
5690
  --cache-dir <dir> Directory for ISR cache (only used by start)
4775
5691
  --default-revalidate <s> Default ISR revalidate interval in seconds
5692
+ --verbose Debug logging (overrides logger.level)
5693
+ --quiet Only errors are printed (overrides logger.level)
4776
5694
  `);
4777
5695
  }
5696
+ /**
5697
+ * Reads the kit's own version from package.json. The CLI runs from two
5698
+ * layouts: src/cli.ts in the repo (../package.json) and dist/lib/cli.js when
5699
+ * installed (../../package.json).
5700
+ */
5701
+ function getKitVersion() {
5702
+ const require$2 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
5703
+ for (const rel of ["../package.json", "../../package.json"]) try {
5704
+ const pkg = require$2(rel);
5705
+ if (typeof pkg.version === "string") return pkg.version;
5706
+ } catch {}
5707
+ return "unknown";
5708
+ }
4778
5709
  function toBuildConfig(options) {
4779
5710
  return {
4780
5711
  root: options.root,
@@ -4788,58 +5719,96 @@ function toBuildConfig(options) {
4788
5719
  hydrateImport: options.hydrateImport,
4789
5720
  routerImport: options.routerImport,
4790
5721
  imageFormats: options.resolvedConfig?.images.formats,
4791
- integrations: options.resolvedConfig?.integrations
5722
+ integrations: options.resolvedConfig?.integrations,
5723
+ site: options.resolvedConfig?.site,
5724
+ js: options.resolvedConfig?.js,
5725
+ router: options.resolvedConfig ? {
5726
+ enabled: options.resolvedConfig.router.enabled,
5727
+ prefetch: options.resolvedConfig.router.prefetch,
5728
+ morph: options.resolvedConfig.router.morph,
5729
+ loadingIndicator: options.resolvedConfig.router.loadingIndicator,
5730
+ speculation: options.resolvedConfig.router.speculation,
5731
+ separate: options.routerSeparate,
5732
+ entry: "/_elur/router.js",
5733
+ outFile: (0, node_path.join)((0, node_path.dirname)(options.generatedEntry), "router.ts")
5734
+ } : void 0
4792
5735
  };
4793
5736
  }
4794
5737
  async function doBuild(options) {
5738
+ const buildStart = Date.now();
4795
5739
  const transformedRoot = (0, node_path.join)(options.root, ".elur", "transformed");
4796
5740
  const transformedAppDir$1 = transformedAppDir(options.root, options.appDir, options.islandsDir, transformedRoot);
5741
+ let phaseStart = performance.now();
4797
5742
  await transformProjectFiles({
4798
5743
  root: options.root,
4799
5744
  appDir: options.appDir,
4800
5745
  islandsDir: options.islandsDir,
4801
5746
  outDir: transformedRoot
4802
5747
  });
5748
+ phase("transform", performance.now() - phaseStart);
4803
5749
  const { beginAtomicStage } = await Promise.resolve().then(() => (init_vite_build(), vite_build_exports));
4804
5750
  const stage = await beginAtomicStage({ outDir: options.outDir });
4805
5751
  const tempOutDir = stage.tempDir;
5752
+ if (options.islandsDir && !options.clientConfig) {
5753
+ const autoConfig = await findClientConfig(options.root);
5754
+ if (autoConfig) options.clientConfig = autoConfig;
5755
+ }
5756
+ options.routerSeparate = await resolveRouterSeparate(options);
4806
5757
  try {
4807
5758
  const buildConfig = toBuildConfig(options);
4808
5759
  buildConfig.appDir = transformedAppDir$1;
4809
5760
  buildConfig.outDir = tempOutDir;
5761
+ buildConfig.onPhase = (name, ms) => phase(name, ms);
4810
5762
  const result = await build$3(buildConfig);
4811
- if (options.resolvedConfig) try {
4812
- const manifest = await createAppManifest(options.resolvedConfig);
4813
- await writeAppManifest(manifest, (0, node_path.join)(tempOutDir, ".elur", "manifest.json"));
4814
- await writeRouteTypes(manifest, (0, node_path.join)(options.root, ".elur", "routes.d.ts"));
4815
- console.log(` - manifest: ${(0, node_path.relative)(options.root, (0, node_path.join)(options.outDir, ".elur", "manifest.json"))}`);
4816
- } catch (err) {
4817
- console.warn("[elur-kit] manifest generation failed:", err);
4818
- }
4819
- if (options.islandsDir && !options.clientConfig) {
4820
- const autoConfig = await findClientConfig(options.root);
4821
- if (autoConfig) options.clientConfig = autoConfig;
5763
+ options.hasIslands = result.islands.length > 0;
5764
+ if (options.resolvedConfig) {
5765
+ phaseStart = performance.now();
5766
+ try {
5767
+ const manifest = await createAppManifest(options.resolvedConfig);
5768
+ await writeAppManifest(manifest, (0, node_path.join)(tempOutDir, ".elur", "manifest.json"));
5769
+ await writeRouteTypes(manifest, (0, node_path.join)(options.root, ".elur", "routes.d.ts"));
5770
+ phase("manifest", performance.now() - phaseStart);
5771
+ } catch (err) {
5772
+ warn(`manifest generation failed: ${err instanceof Error ? err.message : String(err)}`);
5773
+ }
4822
5774
  }
4823
- if (options.clientConfig) {
5775
+ const routerEnabled = options.resolvedConfig?.router.enabled !== false;
5776
+ if (options.clientConfig || options.hasIslands || routerEnabled) {
4824
5777
  const originalOutDir = options.outDir;
4825
5778
  options.outDir = tempOutDir;
4826
5779
  try {
5780
+ phaseStart = performance.now();
4827
5781
  await buildClient(options);
5782
+ phase("client bundle", performance.now() - phaseStart);
4828
5783
  } finally {
4829
5784
  options.outDir = originalOutDir;
4830
5785
  }
4831
5786
  }
4832
5787
  await stage.commit();
4833
- console.log(`✓ Build completo: ${result.pages} páginas generadas`);
4834
- for (const file of result.files) console.log(" -", (0, node_path.relative)(options.root, file));
5788
+ const elapsed = ((Date.now() - buildStart) / 1e3).toFixed(2);
5789
+ success(`${bold("Build completo")} ${dim(`en ${elapsed}s`)}`);
5790
+ info(`${result.pages} página(s), ${result.islands.length} island(s), ${result.files.length} archivo(s)`);
5791
+ const fileEntries = [];
5792
+ for (const file of result.files) {
5793
+ const finalPath = (0, node_path.join)(options.outDir, (0, node_path.relative)(tempOutDir, file));
5794
+ let bytes = 0;
5795
+ try {
5796
+ bytes = (await (0, node_fs_promises.stat)(finalPath)).size;
5797
+ } catch {}
5798
+ fileEntries.push({
5799
+ path: (0, node_path.relative)(options.root, finalPath),
5800
+ bytes
5801
+ });
5802
+ }
5803
+ fileList(fileEntries);
4835
5804
  if (result.islands.length > 0) {
4836
- console.log(`\n✓ ${result.islands.length} island(s) detectada(s):`);
4837
- for (const island of result.islands) console.log(" -", island.name);
4838
- if (result.generatedEntry) console.log(" entry:", (0, node_path.relative)(options.root, result.generatedEntry));
5805
+ success(`${result.islands.length} island(s) detectada(s):`);
5806
+ for (const island of result.islands) detail(island.name);
5807
+ if (result.generatedEntry) detail(`entry: ${(0, node_path.relative)(options.root, result.generatedEntry)}`);
4839
5808
  }
4840
5809
  if (result.skipped.length > 0) {
4841
- console.log("\nRutas dinámicas omitidas (necesitan generateStaticParams):");
4842
- for (const path of result.skipped) console.log(" -", path);
5810
+ warn("Rutas dinámicas omitidas (necesitan generateStaticParams):");
5811
+ for (const path of result.skipped) detail(path);
4843
5812
  }
4844
5813
  } catch (err) {
4845
5814
  await stage.rollback();
@@ -4859,16 +5828,32 @@ async function doDev(options) {
4859
5828
  });
4860
5829
  const actions = await scanActions(transformedAppDir$2);
4861
5830
  const routes = await scanRoutes(transformedAppDir$2);
4862
- const server = (0, node_http.createServer)((req, res) => handleRequest(req, res, options, actions, routes, true));
5831
+ const middleware = await loadUserMiddleware(options.root);
5832
+ options.routerEntry = detectRouterEntry(options);
5833
+ const server = (0, node_http.createServer)((req, res) => handleRequest(req, res, options, actions, routes, true, middleware));
4863
5834
  const shutdown = () => {
4864
5835
  server.close(() => process.exit(0));
4865
5836
  setTimeout(() => process.exit(0), 2e3).unref();
4866
5837
  };
4867
5838
  process.on("SIGTERM", shutdown);
4868
5839
  process.on("SIGINT", shutdown);
4869
- server.listen(options.port, options.host, () => {
4870
- console.log(`\n → Dev server http://${options.host}:${options.port}`);
4871
- });
5840
+ try {
5841
+ const usedPort = await listenWithFallback(server, options.host, options.port, { onFallback: (busyPort, nextPort) => warn(`Puerto ${busyPort} ocupado, usando ${nextPort}`) });
5842
+ const network = getNetworkAddress();
5843
+ serverBanner({
5844
+ name: "elur-kit",
5845
+ version: `v${getKitVersion()}`,
5846
+ command: "dev",
5847
+ localUrl: `http://${options.host}:${usedPort}/`,
5848
+ networkUrl: network ? `http://${network}:${usedPort}/` : void 0
5849
+ });
5850
+ } catch (err) {
5851
+ if (err.code === "EADDRINUSE") {
5852
+ error(`No hay puerto disponible entre ${options.port} y ${options.port + 20}.`);
5853
+ process.exit(78);
5854
+ }
5855
+ throw err;
5856
+ }
4872
5857
  }
4873
5858
  /**
4874
5859
  * Dev supervisor: runs the actual dev server in a child process and restarts
@@ -4886,7 +5871,8 @@ async function doDevSupervisor(options) {
4886
5871
  let respawnTimer = null;
4887
5872
  const startWorker = () => {
4888
5873
  intentional = false;
4889
- console.log("\n[dev] Starting dev server...");
5874
+ console.log();
5875
+ event("dev", "Starting dev server...");
4890
5876
  child = (0, node_child_process.spawn)(process.execPath, [spawnPath, ...args], {
4891
5877
  env: {
4892
5878
  ...process.env,
@@ -4902,7 +5888,11 @@ async function doDevSupervisor(options) {
4902
5888
  return;
4903
5889
  }
4904
5890
  if (code !== 0) {
4905
- console.error(`[dev] Dev server exited with code ${code}; restarting...`);
5891
+ if (code === 78) {
5892
+ error("[dev] Stopping: no available port.");
5893
+ process.exit(code);
5894
+ }
5895
+ error(`[dev] Dev server exited with code ${code}; restarting...`);
4906
5896
  respawnTimer = setTimeout(startWorker, 600);
4907
5897
  }
4908
5898
  });
@@ -4916,7 +5906,8 @@ async function doDevSupervisor(options) {
4916
5906
  if (watchedDirs.length > 0) {
4917
5907
  let timer = null;
4918
5908
  const scheduleRestart = () => {
4919
- console.log("\n[change] Restarting dev server...");
5909
+ console.log();
5910
+ event("change", "Restarting dev server...");
4920
5911
  if (timer) clearTimeout(timer);
4921
5912
  timer = setTimeout(() => restart(), 150);
4922
5913
  };
@@ -4926,7 +5917,7 @@ async function doDevSupervisor(options) {
4926
5917
  else if (filename && /\.ts$/.test(filename)) scheduleRestart();
4927
5918
  });
4928
5919
  } catch (err) {
4929
- console.error(`[dev] failed to watch ${dir}:`, err);
5920
+ error(`[dev] failed to watch ${dir}: ${err instanceof Error ? err.message : String(err)}`);
4930
5921
  }
4931
5922
  }
4932
5923
  const cleanup = () => {
@@ -4940,14 +5931,20 @@ async function doDevSupervisor(options) {
4940
5931
  process.on("SIGTERM", cleanup);
4941
5932
  startWorker();
4942
5933
  }
4943
- async function doPreview(options) {
5934
+ /**
5935
+ * Shared production-serving path for `preview` and `start`: serves the build
5936
+ * output plus dynamic SSR through the unified Web handler, with middleware,
5937
+ * streaming, port fallback and the startup banner. Both commands behave
5938
+ * identically; the label only differs in the banner.
5939
+ */
5940
+ async function startProductionServer(options, command) {
4944
5941
  try {
4945
5942
  if (!(await (0, node_fs_promises.stat)(options.outDir)).isDirectory()) throw new Error(`Output path is not a directory: ${options.outDir}`);
4946
5943
  } catch (err) {
4947
5944
  if (err.code === "ENOENT") throw new Error(`No build output found at ${options.outDir}. Run \`elur-kit build\` first.`);
4948
5945
  throw err;
4949
5946
  }
4950
- const transformedRoot = (0, node_path.join)(options.root, ".elur", "preview-transformed");
5947
+ const transformedRoot = (0, node_path.join)(options.root, ".elur", command === "preview" ? "preview-transformed" : "transformed");
4951
5948
  const transformedAppDir$3 = transformedAppDir(options.root, options.appDir, options.islandsDir, transformedRoot);
4952
5949
  await transformProjectFiles({
4953
5950
  root: options.root,
@@ -4957,32 +5954,25 @@ async function doPreview(options) {
4957
5954
  });
4958
5955
  const actions = await scanActions(transformedAppDir$3);
4959
5956
  const routes = await scanRoutes(transformedAppDir$3);
4960
- const server = (0, node_http.createServer)((req, res) => handleRequest(req, res, options, actions, routes));
4961
- server.listen(options.port, options.host, () => {
4962
- console.log(`\n → Preview server http://${options.host}:${options.port}`);
5957
+ const middleware = await loadUserMiddleware(options.root);
5958
+ options.routerEntry = detectRouterEntry(options);
5959
+ const server = (0, node_http.createServer)((req, res) => handleRequest(req, res, options, actions, routes, false, middleware));
5960
+ const usedPort = await listenWithFallback(server, options.host, options.port, { onFallback: (busyPort, nextPort) => warn(`Puerto ${busyPort} ocupado, usando ${nextPort}`) });
5961
+ const network = getNetworkAddress();
5962
+ serverBanner({
5963
+ name: "elur-kit",
5964
+ version: `v${getKitVersion()}`,
5965
+ command,
5966
+ localUrl: `http://${options.host}:${usedPort}/`,
5967
+ networkUrl: network ? `http://${network}:${usedPort}/` : void 0
4963
5968
  });
4964
5969
  return server;
4965
5970
  }
5971
+ async function doPreview(options) {
5972
+ return startProductionServer(options, "preview");
5973
+ }
4966
5974
  async function doStart(options) {
4967
- const transformedRoot = (0, node_path.join)(options.root, ".elur", "transformed");
4968
- const transformedAppDir$4 = transformedAppDir(options.root, options.appDir, options.islandsDir, transformedRoot);
4969
- await transformProjectFiles({
4970
- root: options.root,
4971
- appDir: options.appDir,
4972
- islandsDir: options.islandsDir,
4973
- outDir: transformedRoot
4974
- });
4975
- await (await createSsrServer({
4976
- root: options.root,
4977
- appDir: transformedAppDir$4,
4978
- publicDir: options.outDir,
4979
- clientEntry: options.clientEntry,
4980
- lang: options.lang,
4981
- port: options.port,
4982
- host: options.host,
4983
- cacheDir: options.cacheDir,
4984
- defaultRevalidate: options.defaultRevalidate
4985
- })).listen();
5975
+ await startProductionServer(options, "start");
4986
5976
  }
4987
5977
  async function findClientConfig(root) {
4988
5978
  for (const name of [
@@ -4996,21 +5986,71 @@ async function findClientConfig(root) {
4996
5986
  } catch {}
4997
5987
  }
4998
5988
  }
5989
+ /**
5990
+ * Decides whether the client bundle emits the router as its own chunk.
5991
+ *
5992
+ * - `js: "legacy"` or `router.enabled: false` → never split (the entry is
5993
+ * hydrate-only when the router is off; legacy embeds the router).
5994
+ * - A user-provided client config splits only when it declares the generated
5995
+ * router module (`.elur/router.ts`) as a bundle input — a single input is
5996
+ * "legacy de facto": the router stays embedded in `entry-client.js`.
5997
+ * - Without a user config, the kit synthesizes a default two-input config →
5998
+ * split.
5999
+ */
6000
+ async function resolveRouterSeparate(options) {
6001
+ const rc = options.resolvedConfig;
6002
+ if (!rc || rc.js === "legacy" || rc.router.enabled === false) return false;
6003
+ const routerFile = (0, node_path.join)((0, node_path.dirname)(options.generatedEntry), "router.ts");
6004
+ if (!options.clientConfig) return true;
6005
+ try {
6006
+ const { resolveClientInputs } = await Promise.resolve().then(() => (init_vite_build(), vite_build_exports));
6007
+ return (await resolveClientInputs(options.clientConfig, options.root)).includes(routerFile);
6008
+ } catch {
6009
+ return false;
6010
+ }
6011
+ }
6012
+ /**
6013
+ * Public URL of the router chunk when the built bundle actually contains it.
6014
+ * The file check keeps `preview`/`start` consistent with whatever layout the
6015
+ * last build produced (split or legacy single-entry).
6016
+ */
6017
+ function detectRouterEntry(options) {
6018
+ const rc = options.resolvedConfig;
6019
+ if (!rc || rc.js === "legacy" || rc.router.enabled === false) return void 0;
6020
+ return (0, node_fs.existsSync)((0, node_path.join)(options.outDir, "_elur", "router.js")) ? "/_elur/router.js" : void 0;
6021
+ }
4999
6022
  async function buildClient(options) {
5000
- if (!options.clientConfig) return;
5001
6023
  const { buildClientBundle } = await Promise.resolve().then(() => (init_vite_build(), vite_build_exports));
5002
6024
  const clientOutDir = (0, node_path.join)(options.outDir, "_elur");
6025
+ const clientBase = "/_elur/";
6026
+ const defaultInputs = { "entry-client": options.generatedEntry };
6027
+ if (options.routerSeparate) defaultInputs.router = (0, node_path.join)((0, node_path.dirname)(options.generatedEntry), "router.ts");
5003
6028
  await buildClientBundle({
5004
6029
  root: options.root,
5005
- userConfigPath: (0, node_path.resolve)(options.clientConfig),
6030
+ userConfigPath: options.clientConfig ? (0, node_path.resolve)(options.clientConfig) : void 0,
6031
+ defaultInputs,
5006
6032
  appDir: (0, node_path.join)(options.root, "src", "app"),
5007
6033
  islandsDir: (0, node_path.join)(options.root, "src", "islands"),
5008
6034
  outDir: clientOutDir,
5009
- base: "/_elur/",
5010
- logPrefix: "[client]"
6035
+ base: clientBase,
6036
+ logPrefix: "[client]",
6037
+ quiet: options.logLevel === "error"
5011
6038
  });
5012
6039
  }
5013
- async function handleRequest(req, res, options, actions, routes, noCache = false) {
6040
+ /**
6041
+ * Loads the project's `src/middleware.ts` for dev/preview/start. A missing
6042
+ * file is fine; a broken one warns but does not stop the server.
6043
+ */
6044
+ async function loadUserMiddleware(root) {
6045
+ const { loadMiddleware } = await Promise.resolve().then(() => (init_middleware(), middleware_exports));
6046
+ try {
6047
+ return await loadMiddleware(root);
6048
+ } catch (err) {
6049
+ warn(err instanceof Error ? err.message : String(err));
6050
+ return null;
6051
+ }
6052
+ }
6053
+ async function handleRequest(req, res, options, actions, routes, noCache = false, middleware) {
5014
6054
  const { createWebHandler } = await Promise.resolve().then(() => (init_handler(), handler_exports));
5015
6055
  const securityHeaders = options.resolvedConfig?.security?.headers;
5016
6056
  const webHandler = createWebHandler(routes, actions, {
@@ -5021,20 +6061,36 @@ async function handleRequest(req, res, options, actions, routes, noCache = false
5021
6061
  lang: options.lang,
5022
6062
  clientEntry: options.clientEntry,
5023
6063
  renderEndpoint: true,
5024
- securityHeaders: securityHeaders === void 0 ? false : securityHeaders
6064
+ router: {
6065
+ enabled: options.resolvedConfig?.router.enabled ?? true,
6066
+ entry: options.routerEntry
6067
+ },
6068
+ js: options.resolvedConfig?.js,
6069
+ securityHeaders: securityHeaders === void 0 ? false : securityHeaders,
6070
+ logLevel: options.resolvedConfig?.logger?.level,
6071
+ cacheAdapter: options.resolvedConfig?.cache?.adapter,
6072
+ redirects: options.resolvedConfig?.redirects,
6073
+ rewrites: options.resolvedConfig?.rewrites,
6074
+ routeHeaders: options.resolvedConfig?.headers,
6075
+ streaming: options.resolvedConfig?.streaming,
6076
+ middleware: middleware ?? void 0
5025
6077
  });
5026
6078
  const request = incomingMessageToRequest(req, req.method && req.method !== "GET" && req.method !== "HEAD" ? await readRequestBody(req) : void 0);
5027
6079
  let response;
5028
6080
  try {
5029
6081
  response = await webHandler(request);
5030
6082
  } catch (err) {
5031
- console.error("[elur-kit] request error:", err);
6083
+ createRequestLogger(request, options.resolvedConfig?.logger?.level).error("[elur-kit] request error", {
6084
+ path: new URL(request.url).pathname,
6085
+ method: request.method,
6086
+ error: err instanceof Error ? err.message : String(err),
6087
+ stack: err instanceof Error ? err.stack : void 0
6088
+ });
5032
6089
  res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
5033
6090
  res.end("Internal Server Error");
5034
6091
  return;
5035
6092
  }
5036
- res.writeHead(response.status, Object.fromEntries(response.headers.entries()));
5037
- res.end(Buffer.from(await response.arrayBuffer()));
6093
+ await sendWebResponse(res, response);
5038
6094
  }
5039
6095
  function readRequestBody(req) {
5040
6096
  return new Promise((resolve, reject) => {
@@ -5056,34 +6112,47 @@ async function doAdapter(options) {
5056
6112
  publicDir: options.publicDir,
5057
6113
  clientEntry: options.clientEntry,
5058
6114
  lang: options.lang,
5059
- hydrateImport: options.hydrateImport
6115
+ hydrateImport: options.hydrateImport,
6116
+ logLevel: options.resolvedConfig?.logger?.level,
6117
+ cacheAdapter: options.resolvedConfig?.cache?.adapter,
6118
+ redirects: options.resolvedConfig?.redirects,
6119
+ rewrites: options.resolvedConfig?.rewrites,
6120
+ routeHeaders: options.resolvedConfig?.headers,
6121
+ streaming: options.resolvedConfig?.streaming,
6122
+ router: { enabled: options.resolvedConfig?.router.enabled ?? true },
6123
+ js: options.resolvedConfig?.js
5060
6124
  };
5061
6125
  const resolvedConfig = options.resolvedConfig;
5062
6126
  const features = {
5063
6127
  isr: typeof resolvedConfig?.cache?.defaultRevalidate === "number" && resolvedConfig.cache.defaultRevalidate > 0,
5064
- images: resolvedConfig?.images?.strict === true
6128
+ images: resolvedConfig?.images?.strict === true,
6129
+ streaming: resolvedConfig?.streaming === true
5065
6130
  };
5066
6131
  let adapterName = options.adapterName;
5067
6132
  if (adapterName === "vercel") {
5068
6133
  const { vercelAdapter } = await Promise.resolve().then(() => (init_vercel(), vercel_exports));
5069
6134
  assertCapabilities(vercelAdapter, features, adapterName);
5070
6135
  await vercelAdapter.build(adapterOptions);
5071
- console.log("\n → Vercel output generated at .vercel/output");
6136
+ console.log();
6137
+ info("Vercel output generated at .vercel/output");
5072
6138
  } else if (adapterName === "netlify") {
5073
6139
  const { netlifyAdapter } = await Promise.resolve().then(() => (init_netlify(), netlify_exports));
5074
6140
  assertCapabilities(netlifyAdapter, features, adapterName);
5075
6141
  await netlifyAdapter.build(adapterOptions);
5076
- console.log("\n → Netlify output generated at netlify/functions/__elur-js-kit.mjs");
6142
+ console.log();
6143
+ info("Netlify output generated at netlify/functions/__elur-js-kit.mjs");
5077
6144
  } else if (adapterName === "bun") {
5078
6145
  const { bunAdapter } = await Promise.resolve().then(() => (init_bun(), bun_exports));
5079
6146
  assertCapabilities(bunAdapter, features, adapterName);
5080
6147
  await bunAdapter.build(adapterOptions);
5081
- console.log("\n → Bun server generated at .elur/bun-server.ts");
6148
+ console.log();
6149
+ info("Bun server generated at .elur/bun-server.ts");
5082
6150
  } else if (adapterName === "node") {
5083
6151
  const { nodeAdapter } = await Promise.resolve().then(() => (init_node(), node_exports));
5084
6152
  assertCapabilities(nodeAdapter, features, adapterName);
5085
6153
  await nodeAdapter.build(adapterOptions);
5086
- console.log("\n → Node server generated at .elur/node-server.mjs");
6154
+ console.log();
6155
+ info("Node server generated at .elur/node-server.mjs");
5087
6156
  }
5088
6157
  }
5089
6158
  function assertCapabilities(adapter, features, adapterName) {
@@ -5107,11 +6176,13 @@ async function applyProjectConfig(options, argv) {
5107
6176
  if (!has("--public")) options.publicDir = config.publicDir;
5108
6177
  if (!has("--cache-dir")) options.cacheDir = config.cache.dir;
5109
6178
  if (!has("--default-revalidate")) options.defaultRevalidate = config.cache.defaultRevalidate;
6179
+ if (options.logLevel) config.logger.level = options.logLevel;
5110
6180
  options.generatedEntry = (0, node_path.resolve)(config.root, ".elur/entry-client.ts");
5111
6181
  options.resolvedConfig = config;
5112
6182
  }
5113
6183
  async function run(argv) {
5114
6184
  const options = parseArgs(argv);
6185
+ if (options.logLevel === "error") setQuiet(true);
5115
6186
  if (options.command === "doctor") {
5116
6187
  const { doDoctor } = await Promise.resolve().then(() => (init_commands(), commands_exports));
5117
6188
  const code = await doDoctor(options);