theokit 0.73.0 → 0.74.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 (131) hide show
  1. package/README.md +2 -0
  2. package/dist/{actions-virtual-module-OHENNMQG.js → actions-virtual-module-J2HYO7QZ.js} +4 -4
  3. package/dist/{actions-virtual-module-QCDKQ6QD.js → actions-virtual-module-JV7URROJ.js} +5 -5
  4. package/dist/adapters/agent-mount.js +3 -3
  5. package/dist/adapters/security-headers.js +9 -4
  6. package/dist/adapters/security-headers.js.map +1 -1
  7. package/dist/{agent-OWJ5A7W5.js → agent-5J7CQAYR.js} +3 -3
  8. package/dist/{app-typed-client-ILLQYTXP.js → app-typed-client-EOA3A2AR.js} +5 -5
  9. package/dist/{app-typed-client-ILLQYTXP.js.map → app-typed-client-EOA3A2AR.js.map} +1 -1
  10. package/dist/{app-typed-client-2PTK2SJH.js → app-typed-client-XD4DZBV7.js} +6 -6
  11. package/dist/app-typed-client-XD4DZBV7.js.map +1 -0
  12. package/dist/{aws-lambda-OP2L5RKZ.js → aws-lambda-ZYSPTD3O.js} +61 -27
  13. package/dist/aws-lambda-ZYSPTD3O.js.map +1 -0
  14. package/dist/{build-CVP2XU5M.js → build-7YZSJGP2.js} +79 -72
  15. package/dist/build-7YZSJGP2.js.map +1 -0
  16. package/dist/{bun-CZXHPK2W.js → bun-I7YM3RDB.js} +81 -20
  17. package/dist/bun-I7YM3RDB.js.map +1 -0
  18. package/dist/{chunk-WBB3MEEN.js → chunk-2NG5T77O.js} +47 -12
  19. package/dist/{chunk-WBB3MEEN.js.map → chunk-2NG5T77O.js.map} +1 -1
  20. package/dist/{chunk-NO6HA4FG.js → chunk-4WP7A7RX.js} +41 -35
  21. package/dist/chunk-4WP7A7RX.js.map +1 -0
  22. package/dist/chunk-4X43VTST.js +31 -0
  23. package/dist/chunk-4X43VTST.js.map +1 -0
  24. package/dist/{chunk-FHQP23Z5.js → chunk-6R5F5YF2.js} +17 -14
  25. package/dist/chunk-6R5F5YF2.js.map +1 -0
  26. package/dist/chunk-72RSCKMW.js +53 -0
  27. package/dist/chunk-72RSCKMW.js.map +1 -0
  28. package/dist/{chunk-SEGD3JUC.js → chunk-EQJF2EH5.js} +8 -7
  29. package/dist/chunk-EQJF2EH5.js.map +1 -0
  30. package/dist/{chunk-6U67SO5U.js → chunk-HK57MPSZ.js} +2 -2
  31. package/dist/{chunk-R7G2B2WH.js → chunk-HKF6YNY4.js} +17 -14
  32. package/dist/{chunk-R7G2B2WH.js.map → chunk-HKF6YNY4.js.map} +1 -1
  33. package/dist/chunk-IJQQNHL7.js +34 -0
  34. package/dist/chunk-IJQQNHL7.js.map +1 -0
  35. package/dist/chunk-NPQ5A3RU.js +53 -0
  36. package/dist/chunk-NPQ5A3RU.js.map +1 -0
  37. package/dist/{chunk-D3M7LPHY.js → chunk-NQZIQJFH.js} +57 -17
  38. package/dist/{chunk-D3M7LPHY.js.map → chunk-NQZIQJFH.js.map} +1 -1
  39. package/dist/{chunk-M3DT6EMK.js → chunk-QAS5SKZP.js} +2 -2
  40. package/dist/{chunk-WRHT5NAJ.js → chunk-QX5Q3FBJ.js} +57 -17
  41. package/dist/chunk-QX5Q3FBJ.js.map +1 -0
  42. package/dist/{chunk-HDAILYVM.js → chunk-SG62LZOJ.js} +3 -3
  43. package/dist/{chunk-EDBQM6RB.js → chunk-SHIXTMQE.js} +47 -12
  44. package/dist/{chunk-EDBQM6RB.js.map → chunk-SHIXTMQE.js.map} +1 -1
  45. package/dist/{chunk-G7U7FQVC.js → chunk-UFBBFP75.js} +13 -3
  46. package/dist/chunk-UFBBFP75.js.map +1 -0
  47. package/dist/{chunk-4CIHLTSI.js → chunk-V7ISZGNS.js} +45 -39
  48. package/dist/chunk-V7ISZGNS.js.map +1 -0
  49. package/dist/{chunk-RCFD5W5V.js → chunk-WR5B2XNT.js} +6 -6
  50. package/dist/chunk-WR5B2XNT.js.map +1 -0
  51. package/dist/{chunk-R36YNWBU.js → chunk-XLFDYTWO.js} +2 -2
  52. package/dist/cli/index.js +8 -8
  53. package/dist/{cloudflare-2SVRRVV5.js → cloudflare-Q5SUXRXY.js} +184 -82
  54. package/dist/cloudflare-Q5SUXRXY.js.map +1 -0
  55. package/dist/{config-support-SB5NDQZB.js → config-support-MOZYHRWG.js} +13 -2
  56. package/dist/{config-support-SB5NDQZB.js.map → config-support-MOZYHRWG.js.map} +1 -1
  57. package/dist/{deno-deploy-OK4QFJIZ.js → deno-deploy-XW3Q6OMD.js} +109 -11
  58. package/dist/deno-deploy-XW3Q6OMD.js.map +1 -0
  59. package/dist/{dev-B2IZEVAD.js → dev-FZ4OTCPT.js} +7 -7
  60. package/dist/{dev-emit-7KZFUA7M.js → dev-emit-T3X6RR7M.js} +5 -5
  61. package/dist/{dev-emit-7KZFUA7M.js.map → dev-emit-T3X6RR7M.js.map} +1 -1
  62. package/dist/{dev-emit-JPJJFBXL.js → dev-emit-ZK5GCHXN.js} +6 -6
  63. package/dist/dev-emit-ZK5GCHXN.js.map +1 -0
  64. package/dist/index.js +5 -5
  65. package/dist/{internal-api-5Y3MLZH4.js → internal-api-GKPJYL3G.js} +5 -5
  66. package/dist/{internal-api-6XNLCNI5.js → internal-api-ZUBUYGCQ.js} +4 -4
  67. package/dist/{mcp-GJQIREYC.js → mcp-VUHRRX36.js} +3 -3
  68. package/dist/{netlify-IAC53FVZ.js → netlify-ALPCTQFO.js} +158 -48
  69. package/dist/netlify-ALPCTQFO.js.map +1 -0
  70. package/dist/{node-QUGTW6XV.js → node-4HQO6KKZ.js} +2 -2
  71. package/dist/{openapi-Q53YOBIU.js → openapi-C4UX2SFV.js} +5 -5
  72. package/dist/openapi-C4UX2SFV.js.map +1 -0
  73. package/dist/{preview-XBP622HM.js → preview-II33QNAC.js} +3 -3
  74. package/dist/registry-WVUO2WNR.js +34 -0
  75. package/dist/registry-WVUO2WNR.js.map +1 -0
  76. package/dist/{routes-FDF4SLOB.js → routes-3PTNISSO.js} +2 -2
  77. package/dist/server/index.js +2 -2
  78. package/dist/server/scan/index.d.ts +38 -2
  79. package/dist/server/scan/index.js +2 -2
  80. package/dist/{server-boundary-IFIYNGTA.js → server-boundary-QCJNECJP.js} +5 -5
  81. package/dist/{server-boundary-E5GFVPLB.js → server-boundary-RTRPHX5I.js} +4 -4
  82. package/dist/{start-JGNBTTG2.js → start-EREUCSN6.js} +6 -6
  83. package/dist/{static-NQPLPAB6.js → static-7LP7LPGN.js} +2 -2
  84. package/dist/theo-cloud-GIA67L4Q.js +40 -0
  85. package/dist/theo-cloud-GIA67L4Q.js.map +1 -0
  86. package/dist/{vercel-EHAOKPF7.js → vercel-VLR52RXT.js} +173 -73
  87. package/dist/vercel-VLR52RXT.js.map +1 -0
  88. package/dist/vite-plugin/index.d.ts +10 -1
  89. package/dist/vite-plugin/index.js +7 -5
  90. package/dist/{vite-plugin-54XIRMKT.js → vite-plugin-3LTZJTUM.js} +9 -7
  91. package/package.json +5 -5
  92. package/dist/app-typed-client-2PTK2SJH.js.map +0 -1
  93. package/dist/aws-lambda-OP2L5RKZ.js.map +0 -1
  94. package/dist/build-CVP2XU5M.js.map +0 -1
  95. package/dist/bun-CZXHPK2W.js.map +0 -1
  96. package/dist/chunk-4CIHLTSI.js.map +0 -1
  97. package/dist/chunk-FHQP23Z5.js.map +0 -1
  98. package/dist/chunk-G7U7FQVC.js.map +0 -1
  99. package/dist/chunk-NO6HA4FG.js.map +0 -1
  100. package/dist/chunk-RCFD5W5V.js.map +0 -1
  101. package/dist/chunk-SEGD3JUC.js.map +0 -1
  102. package/dist/chunk-WRHT5NAJ.js.map +0 -1
  103. package/dist/cloudflare-2SVRRVV5.js.map +0 -1
  104. package/dist/deno-deploy-OK4QFJIZ.js.map +0 -1
  105. package/dist/dev-emit-JPJJFBXL.js.map +0 -1
  106. package/dist/netlify-IAC53FVZ.js.map +0 -1
  107. package/dist/openapi-Q53YOBIU.js.map +0 -1
  108. package/dist/registry-L6JG75LY.js +0 -23
  109. package/dist/registry-L6JG75LY.js.map +0 -1
  110. package/dist/theo-cloud-HMFNZ3FS.js +0 -33
  111. package/dist/theo-cloud-HMFNZ3FS.js.map +0 -1
  112. package/dist/vercel-EHAOKPF7.js.map +0 -1
  113. /package/dist/{actions-virtual-module-OHENNMQG.js.map → actions-virtual-module-J2HYO7QZ.js.map} +0 -0
  114. /package/dist/{actions-virtual-module-QCDKQ6QD.js.map → actions-virtual-module-JV7URROJ.js.map} +0 -0
  115. /package/dist/{agent-OWJ5A7W5.js.map → agent-5J7CQAYR.js.map} +0 -0
  116. /package/dist/{chunk-6U67SO5U.js.map → chunk-HK57MPSZ.js.map} +0 -0
  117. /package/dist/{chunk-M3DT6EMK.js.map → chunk-QAS5SKZP.js.map} +0 -0
  118. /package/dist/{chunk-HDAILYVM.js.map → chunk-SG62LZOJ.js.map} +0 -0
  119. /package/dist/{chunk-R36YNWBU.js.map → chunk-XLFDYTWO.js.map} +0 -0
  120. /package/dist/{dev-B2IZEVAD.js.map → dev-FZ4OTCPT.js.map} +0 -0
  121. /package/dist/{internal-api-5Y3MLZH4.js.map → internal-api-GKPJYL3G.js.map} +0 -0
  122. /package/dist/{internal-api-6XNLCNI5.js.map → internal-api-ZUBUYGCQ.js.map} +0 -0
  123. /package/dist/{mcp-GJQIREYC.js.map → mcp-VUHRRX36.js.map} +0 -0
  124. /package/dist/{node-QUGTW6XV.js.map → node-4HQO6KKZ.js.map} +0 -0
  125. /package/dist/{preview-XBP622HM.js.map → preview-II33QNAC.js.map} +0 -0
  126. /package/dist/{routes-FDF4SLOB.js.map → routes-3PTNISSO.js.map} +0 -0
  127. /package/dist/{server-boundary-IFIYNGTA.js.map → server-boundary-QCJNECJP.js.map} +0 -0
  128. /package/dist/{server-boundary-E5GFVPLB.js.map → server-boundary-RTRPHX5I.js.map} +0 -0
  129. /package/dist/{start-JGNBTTG2.js.map → start-EREUCSN6.js.map} +0 -0
  130. /package/dist/{static-NQPLPAB6.js.map → static-7LP7LPGN.js.map} +0 -0
  131. /package/dist/{vite-plugin-54XIRMKT.js.map → vite-plugin-3LTZJTUM.js.map} +0 -0
@@ -1,5 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
+ import {
4
+ VALID_TARGETS,
5
+ targetRendersDocument
6
+ } from "./chunk-4X43VTST.js";
3
7
  import {
4
8
  describeControllerArtifacts,
5
9
  emitControllerArtifacts
@@ -20,14 +24,14 @@ import {
20
24
  import {
21
25
  generateManifest,
22
26
  writeManifest as writeManifest2
23
- } from "./chunk-RCFD5W5V.js";
27
+ } from "./chunk-WR5B2XNT.js";
24
28
  import {
25
29
  scanAgents
26
- } from "./chunk-R7G2B2WH.js";
30
+ } from "./chunk-HKF6YNY4.js";
27
31
  import {
28
32
  scanServerRoutes,
29
33
  scanWebSocketRoutes
30
- } from "./chunk-NO6HA4FG.js";
34
+ } from "./chunk-4WP7A7RX.js";
31
35
  import {
32
36
  compareByCodeUnit,
33
37
  walkSourceFiles
@@ -49,21 +53,8 @@ import {
49
53
  import "./chunk-D2R5SJEL.js";
50
54
 
51
55
  // src/cli/commands/build.ts
52
- import { existsSync as existsSync4 } from "fs";
53
- import { dirname as dirname2, join, relative, resolve, sep as sep2 } from "path";
54
-
55
- // src/adapters/types.ts
56
- var VALID_TARGETS = [
57
- "node",
58
- "vercel",
59
- "cloudflare",
60
- "static",
61
- "bun",
62
- "deno-deploy",
63
- "netlify",
64
- "aws-lambda",
65
- "theo-cloud"
66
- ];
56
+ import { existsSync as existsSync5 } from "fs";
57
+ import { resolve as resolve2 } from "path";
67
58
 
68
59
  // src/server/cron/adapter-translators.ts
69
60
  import { existsSync, readFileSync } from "fs";
@@ -472,6 +463,48 @@ async function cleanOutDir(opts) {
472
463
  return { deleted, kept };
473
464
  }
474
465
 
466
+ // src/cli/commands/build-scan-routes.ts
467
+ import { existsSync as existsSync4 } from "fs";
468
+ import { join, relative, resolve, sep as sep2 } from "path";
469
+ function createBuildScanRoutes(projectRoot, config) {
470
+ return (serverDir) => {
471
+ const abs = resolve(projectRoot, serverDir);
472
+ const toProjectRelative = (p) => relative(projectRoot, p).split(sep2).join("/");
473
+ return {
474
+ routes: scanServerRoutes(abs).map((route) => ({
475
+ filePath: toProjectRelative(route.filePath),
476
+ routePath: route.routePath,
477
+ methods: route.methods ?? []
478
+ })),
479
+ wsRoutes: scanWebSocketRoutes(abs).map(
480
+ (ws) => toProjectRelative(typeof ws === "string" ? ws : ws.filePath)
481
+ ),
482
+ // #367 — agents are a DIFFERENT scan served by a DIFFERENT function, which is why no adapter
483
+ // had ever heard of them: the entries route `/api/` through `scanServerRoutes` +
484
+ // `executeRoute` alone, so `/api/agents/<name>` matched nothing and 404'd on every target.
485
+ // Scanned here, beside the routes, because the same inversion argument applies verbatim.
486
+ //
487
+ // B-312 — the root is the PROJECT ROOT, and was `dirname(abs)`. `config.agentsDir` is
488
+ // documented and declared relative to the project root, while `dirname(serverDir)` is the
489
+ // root only when `serverDir` is a direct child of it. The scaffold's own nested layout
490
+ // (`serverDir: 'src/server'`, `agentsDir: 'src/server/agents'`) made the two disagree, and
491
+ // `join()` produced `<root>/src/src/server/agents` — so `scanAgents` returned `[]` and every
492
+ // `/api/agents/*` route 404'd on every scanned target. Measured on a live Cloudflare deploy,
493
+ // 2026-09-26. Every other caller in the tree already passes the project root.
494
+ agents: scanAgents(projectRoot, config.agentsDir).map((agent) => ({
495
+ filePath: toProjectRelative(agent.filePath),
496
+ agentPath: agent.agentPath,
497
+ name: agent.name
498
+ })),
499
+ // B-185 — the identity module, decided here for the same reason the agents are: this provider
500
+ // is handed `serverDir`, and a Worker has no filesystem to look for it on. An app with no
501
+ // `server/context.ts` yields `undefined`, and the generator then emits no import — importing
502
+ // a file that is not there would fail the BUILD rather than one request.
503
+ contextModule: existsSync4(join(abs, "context.ts")) ? toProjectRelative(join(abs, "context.ts")) : void 0
504
+ };
505
+ };
506
+ }
507
+
475
508
  // src/cli/commands/build.ts
476
509
  var CRON_NA_TARGETS = /* @__PURE__ */ new Set(["bun", "netlify", "static"]);
477
510
  var CRON_SUPPORTED_TARGETS = VALID_TARGETS.filter((t) => !CRON_NA_TARGETS.has(t));
@@ -481,14 +514,19 @@ async function buildCommand(options) {
481
514
  loadEnv({ cwd, mode: "production" });
482
515
  const config = await loadConfig(cwd);
483
516
  validateProjectStructure(cwd, config.appDir);
484
- const distDirAbs = resolve(cwd, config.distDir);
485
- await cleanOutDir({ dir: distDirAbs });
486
517
  const target = options?.target ?? "node";
487
518
  if (!VALID_TARGETS.includes(target)) {
488
519
  throw new Error(
489
520
  `Invalid build target "${target}". Available targets: ${VALID_TARGETS.join(", ")}`
490
521
  );
491
522
  }
523
+ const { resolveAdapter, streamingTargets } = await import("./registry-WVUO2WNR.js");
524
+ const adapter = await resolveAdapter(target);
525
+ const { assertRateLimitEnforceable, assertStreamingSupported } = await import("./config-support-MOZYHRWG.js");
526
+ assertRateLimitEnforceable(config, adapter, target);
527
+ assertStreamingSupported(config, adapter, target, await streamingTargets());
528
+ const distDirAbs = resolve2(cwd, config.distDir);
529
+ await cleanOutDir({ dir: distDirAbs });
492
530
  const configAdapters = config.adapters;
493
531
  if (configAdapters && configAdapters.length > 0) {
494
532
  const otherAdapters = configAdapters.filter((a) => a !== target);
@@ -502,7 +540,7 @@ async function buildCommand(options) {
502
540
  console.log(`
503
541
  Building for ${target}...
504
542
  `);
505
- const serverDir = resolve(cwd, config.serverDir);
543
+ const serverDir = resolve2(cwd, config.serverDir);
506
544
  const distDir = distDirAbs;
507
545
  const manifest = generateManifest(serverDir, cwd, config.agentsDir);
508
546
  writeManifest2(manifest, distDir);
@@ -538,9 +576,9 @@ async function buildCommand(options) {
538
576
  });
539
577
  console.log(` \u2713 OpenAPI: ${String(hydrated.length)} ops \u2192 ${devResult.path}`);
540
578
  }
541
- await runAdapterBuild(target, config, cwd);
579
+ await runAdapterBuild(target, config, cwd, adapter);
542
580
  if (config.openapi !== void 0) {
543
- const distOut = resolve(cwd, "dist");
581
+ const distOut = resolve2(cwd, "dist");
544
582
  const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes });
545
583
  const distResult = emitOpenApi({
546
584
  manifest: hydrated,
@@ -548,13 +586,13 @@ async function buildCommand(options) {
548
586
  });
549
587
  console.log(` \u2713 OpenAPI (dist): ${distResult.path}`);
550
588
  }
551
- const ssrNote = config.ssr ? " (SSR)" : "";
589
+ const ssrNote = config.ssr && targetRendersDocument(target) ? " (SSR)" : "";
552
590
  console.log(`
553
591
  \u2713 Build complete \u2192 ${target}${ssrNote}
554
592
  `);
555
593
  }
556
- async function runAdapterBuild(target, config, cwd) {
557
- const { theoPluginAsync } = await import("./vite-plugin-54XIRMKT.js");
594
+ async function runAdapterBuild(target, config, cwd, adapter) {
595
+ const { theoPluginAsync } = await import("./vite-plugin-3LTZJTUM.js");
558
596
  const { default: react } = await import("@vitejs/plugin-react");
559
597
  const ctx = {
560
598
  // `react()` may return Plugin or Plugin[] depending on version; spread the
@@ -576,52 +614,21 @@ async function runAdapterBuild(target, config, cwd) {
576
614
  // `adapters → server` edge that `adapters-may-only-depend-on-core-router-services` refuses. The
577
615
  // CLI already imports both sides, so it composes the scan and hands over the result.
578
616
  //
579
- // Paths are made relative to the project root here, where `cwd` is known: that string is both
580
- // the emitted import specifier and the key the executor looks a module up by, and the scanners
581
- // return absolute paths.
582
- scanRoutes: (serverDir) => {
583
- const abs = resolve(cwd, serverDir);
584
- const toProjectRelative = (p) => relative(cwd, p).split(sep2).join("/");
585
- return {
586
- routes: scanServerRoutes(abs).map((route) => ({
587
- filePath: toProjectRelative(route.filePath),
588
- routePath: route.routePath,
589
- methods: route.methods ?? []
590
- })),
591
- wsRoutes: scanWebSocketRoutes(abs).map(
592
- (ws) => toProjectRelative(typeof ws === "string" ? ws : ws.filePath)
593
- ),
594
- // #367 — agents are a DIFFERENT scan served by a DIFFERENT function, which is why no
595
- // adapter had ever heard of them: the entries route `/api/` through `scanServerRoutes` +
596
- // `executeRoute` alone, so `/api/agents/<name>` matched nothing and 404'd on every target.
597
- // Scanned here, beside the routes, because the same inversion argument applies verbatim.
598
- agents: scanAgents(dirname2(abs), config.agentsDir).map((agent) => ({
599
- filePath: toProjectRelative(agent.filePath),
600
- agentPath: agent.agentPath,
601
- name: agent.name
602
- })),
603
- // B-185 — the identity module, decided here for the same reason the agents are: this
604
- // provider is handed `serverDir`, and a Worker has no filesystem to look for it on. An app
605
- // with no `server/context.ts` yields `undefined`, and the generator then emits no import —
606
- // importing a file that is not there would fail the BUILD rather than one request.
607
- contextModule: existsSync4(join(abs, "context.ts")) ? toProjectRelative(join(abs, "context.ts")) : void 0
608
- };
609
- }
617
+ // A module rather than a closure since B-312: the wrong argument it carried was unreachable from
618
+ // any test while it lived in here, because reaching it meant running the whole build.
619
+ scanRoutes: createBuildScanRoutes(cwd, config)
610
620
  };
611
- const { resolveAdapter } = await import("./registry-L6JG75LY.js");
612
- const adapter = await resolveAdapter(target);
613
- const { warnUnappliedConfig, assertRateLimitEnforceable } = await import("./config-support-SB5NDQZB.js");
614
- assertRateLimitEnforceable(config, adapter, target);
621
+ const { warnUnappliedConfig } = await import("./config-support-MOZYHRWG.js");
615
622
  warnUnappliedConfig(config, adapter, target, (message) => {
616
623
  console.log(message);
617
624
  });
618
625
  await adapter.build(config, cwd, ctx);
619
626
  }
620
627
  async function emitCronArtifacts(opts) {
621
- const cronsDir = resolve(opts.serverDir, "crons");
622
- const agentsSchedulesDir = resolve(opts.cwd, opts.agentsDir, "schedules");
628
+ const cronsDir = resolve2(opts.serverDir, "crons");
629
+ const agentsSchedulesDir = resolve2(opts.cwd, opts.agentsDir, "schedules");
623
630
  const cronNodes = await scanCronDirs([cronsDir, agentsSchedulesDir]);
624
- const manifestPath = resolve(opts.distDir, "crons.json");
631
+ const manifestPath = resolve2(opts.distDir, "crons.json");
625
632
  writeCronManifest(manifestPath, cronNodes, opts.cwd);
626
633
  console.log(` \u2713 Crons: ${cronNodes.length} declared`);
627
634
  if (cronNodes.length === 0) return;
@@ -640,19 +647,19 @@ async function emitCronArtifacts(opts) {
640
647
  try {
641
648
  switch (opts.target) {
642
649
  case "vercel":
643
- translateCronToVercel(resolve(opts.cwd, "vercel.json"), manifestEntries);
650
+ translateCronToVercel(resolve2(opts.cwd, "vercel.json"), manifestEntries);
644
651
  console.log(` \u2713 Cron \u2192 vercel.json crons[] (${cronNodes.length} entries)`);
645
652
  break;
646
653
  case "cloudflare":
647
- translateCronToCloudflare(resolve(opts.cwd, "wrangler.toml"), manifestEntries);
654
+ translateCronToCloudflare(resolve2(opts.cwd, "wrangler.toml"), manifestEntries);
648
655
  console.log(` \u2713 Cron \u2192 wrangler.toml [triggers] (${cronNodes.length})`);
649
656
  break;
650
657
  case "aws-lambda":
651
- translateCronToAws(resolve(opts.cwd, "serverless.yml"), manifestEntries);
658
+ translateCronToAws(resolve2(opts.cwd, "serverless.yml"), manifestEntries);
652
659
  console.log(` \u2713 Cron \u2192 serverless.yml functions (${cronNodes.length})`);
653
660
  break;
654
661
  case "deno-deploy":
655
- translateCronToDeno(resolve(opts.distDir, "crons-entry.ts"), manifestEntries);
662
+ translateCronToDeno(resolve2(opts.distDir, "crons-entry.ts"), manifestEntries);
656
663
  console.log(` \u2713 Cron \u2192 ${opts.distDir}/crons-entry.ts (Deno.cron)`);
657
664
  break;
658
665
  case "node":
@@ -665,9 +672,9 @@ async function emitCronArtifacts(opts) {
665
672
  }
666
673
  }
667
674
  async function emitJobArtifacts(opts) {
668
- const jobsDir = resolve(opts.serverDir, "jobs");
669
- const jobNodes = existsSync4(jobsDir) ? await scanJobs(jobsDir) : [];
670
- const manifestPath = resolve(opts.distDir, "jobs.json");
675
+ const jobsDir = resolve2(opts.serverDir, "jobs");
676
+ const jobNodes = existsSync5(jobsDir) ? await scanJobs(jobsDir) : [];
677
+ const manifestPath = resolve2(opts.distDir, "jobs.json");
671
678
  writeJobManifest(manifestPath, jobNodes, opts.cwd);
672
679
  console.log(` \u2713 Jobs: ${jobNodes.length} declared`);
673
680
  }
@@ -681,4 +688,4 @@ function relativize3(absPath, root) {
681
688
  export {
682
689
  buildCommand
683
690
  };
684
- //# sourceMappingURL=build-CVP2XU5M.js.map
691
+ //# sourceMappingURL=build-7YZSJGP2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/commands/build.ts","../src/server/cron/adapter-translators.ts","../src/server/_internal/atomic-write.ts","../src/server/cron/cron-manifest.ts","../src/server/cron/cron-scan.ts","../src/server/jobs/job-manifest.ts","../src/server/jobs/job-scan.ts","../src/cli/cleanup/cleanup.ts","../src/cli/commands/build-scan-routes.ts"],"sourcesContent":["import { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\n// T1.1 (architecture-medium-deferrals) — nodeAdapter no longer static-imported.\n// All adapters dispatch via `adapterRegistry` (lazy-imported within runAdapterBuild).\nimport {\n VALID_TARGETS,\n targetRendersDocument,\n type BuildTarget,\n type AdapterBuildContext,\n type DeployAdapter,\n} from '../../adapters/types.js'\nimport { loadConfig } from '../../config/load-config.js'\nimport { loadEnv } from '../../config/load-env.js'\nimport { validateProjectStructure } from '../../config/validate-structure.js'\nimport {\n ExistingConfigUnparseableError,\n translateCronToAws,\n translateCronToCloudflare,\n translateCronToDeno,\n translateCronToVercel,\n} from '../../server/cron/adapter-translators.js'\nimport { writeCronManifest } from '../../server/cron/cron-manifest.js'\nimport { scanCronDirs } from '../../server/cron/cron-scan.js'\nimport { writeJobManifest } from '../../server/jobs/job-manifest.js'\nimport { scanJobs } from '../../server/jobs/job-scan.js'\nimport { generateManifest, writeManifest } from '../../server/scan/manifest.js'\nimport {\n buildManifest as buildServicesManifest,\n writeManifest as writeServicesManifest,\n} from '../../services/index.js'\n// G2 T2.2 — OpenAPI emit. Opt-in via `config.openapi`. Dual output:\n// 1. <distDir>/openapi.json (pre-Vite, dev surface + manifests sibling)\n// 2. dist/openapi.json (post-Vite, build artifact)\n// The dist emit awaits runAdapterBuild — if Vite fails, the second emit\n// never runs (EC-2 absorbed: no stale dist artifact).\nimport { emitOpenApi } from '../../vite-plugin/openapi-emit/emit.js'\nimport { loadRoutesForOpenApi } from '../../vite-plugin/openapi-emit/load-routes.js'\nimport { cleanOutDir } from '../cleanup/cleanup.js'\nimport { preflightNodeAndBindings } from '../preflight-node-version.js'\n\nimport { describeControllerArtifacts, emitControllerArtifacts } from './build/emit-controllers.js'\nimport { createBuildScanRoutes } from './build-scan-routes.js'\n\n// Adapters that do NOT support cron triggers natively. Build still\n// succeeds with crons declared, but emits a warning + skip note.\nconst CRON_NA_TARGETS = new Set<BuildTarget>(['bun', 'netlify', 'static'])\n\n// DERIVED, never restated. A hand-written list here went stale and told users\n// that three working targets were unsupported: it named node/vercel/cloudflare\n// while aws-lambda, deno-deploy and theo-cloud also translate crons. Deriving\n// from the two constants means adding a target cannot desynchronise the message.\nconst CRON_SUPPORTED_TARGETS = VALID_TARGETS.filter((t) => !CRON_NA_TARGETS.has(t))\n\nexport async function buildCommand(options?: { target?: string }): Promise<void> {\n const cwd = process.cwd()\n // Preflight (FIRST — BEFORE anything that touches native bindings).\n preflightNodeAndBindings(cwd)\n // Phase 1 (T1.2) — Load .env BEFORE config load.\n loadEnv({ cwd, mode: 'production' })\n\n const config = await loadConfig(cwd)\n // #95 — honor config.appDir so a custom frontend dir (e.g. apps/web) passes the structure gate.\n validateProjectStructure(cwd, config.appDir)\n\n // B-336 — EVERY refusal that is decidable from the target and the config alone runs BEFORE the\n // clean. `cleanOutDir` used to sit here, above even the check that the target EXISTS: measured on a\n // real project, `theokit build --target nao-existe` destroyed 302 files in `.theokit/client/assets`\n // and answered with a message about the typo. The comment above\n // `assertRateLimitEnforceable` already stated this intent in its own words — \"refused by name,\n // BEFORE the build writes anything\" — and the order defeated it.\n const target = (options?.target ?? 'node') as BuildTarget\n\n if (!VALID_TARGETS.includes(target)) {\n throw new Error(\n `Invalid build target \"${target}\". Available targets: ${VALID_TARGETS.join(', ')}`,\n )\n }\n\n const { resolveAdapter, streamingTargets } = await import('../../adapters/registry.js')\n const adapter = await resolveAdapter(target)\n const { assertRateLimitEnforceable, assertStreamingSupported } =\n await import('../../adapters/config-support.js')\n\n // #461 — a dropped `cors` degrades where someone can see it; a dropped RATE LIMIT looks exactly like\n // success until the abuse it was meant to stop. Refused by name, and now genuinely before anything is\n // written or destroyed.\n assertRateLimitEnforceable(config, adapter, target)\n assertStreamingSupported(config, adapter, target, await streamingTargets())\n\n // T2.2 — Clean .theokit/ at build start (Astro pattern). Skip .git*.\n const distDirAbs = resolve(cwd, config.distDir)\n await cleanOutDir({ dir: distDirAbs })\n\n // EC-201 — cross-reference note when config.adapters[] diverges from\n // the --target flag. --target is authoritative per ADR D2.\n const configAdapters = (config as { adapters?: readonly string[] }).adapters\n if (configAdapters && configAdapters.length > 0) {\n const otherAdapters = configAdapters.filter((a) => a !== target)\n if (otherAdapters.length > 0) {\n console.log(\n `\\n Note: theo.config.ts.adapters lists [${otherAdapters.join(', ')}]; ` +\n `this build translates for ${target} only. ` +\n `Run \\`theokit build --target=<adapter>\\` separately for each (cross-reference).`,\n )\n }\n }\n\n console.log(`\\n Building for ${target}...\\n`)\n\n // Manifests emit BEFORE adapter bundling (Vite). Why: manifests are\n // fast + deterministic + don't depend on Vite. If Vite fails (missing\n // dep, malformed entry), the user still gets manifests for diagnostics.\n const serverDir = resolve(cwd, config.serverDir)\n const distDir = distDirAbs\n // #95 follow-up — pass projectRoot (cwd) + config.agentsDir so agents scan honors a custom dir.\n const manifest = generateManifest(serverDir, cwd, config.agentsDir)\n writeManifest(manifest, distDir)\n\n const totalEndpoints =\n manifest.routes.length + manifest.actions.length + manifest.websockets.length\n console.log(\n ` ✓ Manifest: ${manifest.routes.length} routes, ${manifest.actions.length} actions, ${manifest.websockets.length} ws (${totalEndpoints} total)`,\n )\n\n // T1.1 — cron scan + manifest + per-target adapter translation\n await emitCronArtifacts({ cwd, serverDir, agentsDir: config.agentsDir, distDir, target })\n\n // T1.2 — job scan + manifest (no per-target translation needed)\n await emitJobArtifacts({ cwd, serverDir, distDir })\n\n // theokit#123 — compile `server/controllers/**` so `theokit start` can serve them.\n //\n // #122 made controllers first-class in dev, where Vite's swc transform compiles them on the fly.\n // Production has neither, so an uncompiled `.controller.ts` cannot load and its routes 404'd —\n // working in dev and failing in prod, which is the worst place for a gap to live.\n //\n // Deliberately NOT folded into `generateManifest` (ADR-5): the manifest is the deploy-adapter\n // contract, and a parallel route source in it would ripple through every adapter. This writes a\n // separate artifact only the Node start path reads. No controllers ⇒ no artifact at all.\n const controllerManifest = await emitControllerArtifacts({ serverDir, distDir })\n if (controllerManifest !== null) {\n console.log(` ${describeControllerArtifacts(controllerManifest)}`)\n }\n\n // Wave 2 (T1.2) — services manifest at <cwd>/.theokit/services.json. Always\n // emit (empty array when services: {} is empty) so adapters can rely on\n // the file existing. Topological order preserved by buildServicesManifest.\n //\n // Plan v1.2 T2.1 — when theo.config.ts declares `name`, emit services.json\n // v2 with that project identifier. Falling back to v1 (no project field)\n // keeps TheoCloud's deprecation warning path intact (services-bundle).\n const projectName = config.name\n const servicesManifest = buildServicesManifest(config.services, projectName)\n writeServicesManifest(cwd, servicesManifest)\n if (servicesManifest.services.length > 0) {\n const versionLabel = `v${String(servicesManifest.version)}`\n const projectLabel =\n servicesManifest.version === 2 ? ` project=\"${servicesManifest.project}\"` : ''\n console.log(\n ` ✓ Services manifest (${versionLabel}${projectLabel}): ${String(servicesManifest.services.length)} service(s) ` +\n `(${servicesManifest.services.map((s) => s.name).join(', ')})`,\n )\n } else if (servicesManifest.version === 1) {\n console.log(\n ' ⚠ services.json emitted as v1 (no `name` in theo.config.ts). ' +\n 'TheoCloud will accept this with a deprecation warning; sunset in theokit 0.6.0. ' +\n 'Run `theokit migrate services-json-v1-to-v2` to upgrade.',\n )\n }\n\n // G2 T2.2 — OpenAPI dev-surface emit (pre-Vite, sibling of manifests).\n // Opt-in: only when config.openapi is defined. Best-effort: a route load\n // failure produces a warning, not a build abort.\n if (config.openapi !== undefined) {\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const devResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distDir },\n })\n console.log(` ✓ OpenAPI: ${String(hydrated.length)} ops → ${devResult.path}`)\n }\n\n // Now run the adapter-specific bundling (Vite + adapter-specific work).\n await runAdapterBuild(target, config, cwd, adapter)\n\n // G2 T2.2 — OpenAPI build-artifact emit (post-Vite, EC-2 gated on success).\n // If runAdapterBuild threw, execution never reaches this point — no stale\n // dist/openapi.json is written.\n if (config.openapi !== undefined) {\n const distOut = resolve(cwd, 'dist')\n const hydrated = await loadRoutesForOpenApi({ serverDir, routes: manifest.routes })\n const distResult = emitOpenApi({\n manifest: hydrated,\n config: { ...config.openapi, outDir: distOut },\n })\n console.log(` ✓ OpenAPI (dist): ${distResult.path}`)\n }\n\n // Derived, not asserted. This read `config.ssr` alone, so a target whose entry delegates the\n // document to a static host was announced as server-rendering — measured on `--target bun`, which\n // printed `(SSR)` and served an empty `<div id=\"root\">` (B-334).\n const ssrNote = config.ssr && targetRendersDocument(target) ? ' (SSR)' : ''\n console.log(`\\n ✓ Build complete → ${target}${ssrNote}\\n`)\n}\n\nasync function runAdapterBuild(\n target: BuildTarget,\n config: Awaited<ReturnType<typeof loadConfig>>,\n cwd: string,\n // Resolved by the caller, which needs it before `cleanOutDir` to run the refusals (B-336). Passing it\n // in rather than resolving again keeps one answer to \"which adapter is this build\".\n adapter: DeployAdapter,\n): Promise<void> {\n // T1.1 (architecture-cleanup) — CLI composes the Vite Plugin[] and INJECTS it into\n // the adapter via ctx.makeVitePlugins. This inverts the previous `adapters → vite-plugin`\n // edge — adapters no longer import from vite-plugin/ directly.\n //\n // theoPlugin AND `@vitejs/plugin-react` are dynamically imported so the deps are\n // materialized only when needed (adapter is `node`). This keeps the CLI's startup\n // path independent of optional build-time deps (so e.g. `theokit build --target=static`\n // does not need react installed). dep-cruiser's per-module rule allows `cli → vite-plugin`.\n //\n // 0.2.2 regression fix: switched sync `theoPlugin()` → `theoPluginAsync()` so the\n // returned Plugin[] includes the @theo/actions virtual module + typed-client +\n // services + @theokit/ui auto-chain. Without async, build-time Rollup couldn't\n // resolve `@theo/actions` even though dev-time Vite (which already used async)\n // could. See https://github.com/usetheo/theokit/commits — 0.2.2 changelog.\n const { theoPluginAsync } = await import('../../vite-plugin/index.js')\n const { default: react } = await import('@vitejs/plugin-react')\n const ctx: AdapterBuildContext = {\n // `react()` may return Plugin or Plugin[] depending on version; spread the\n // async chain so the contract returns a flat Plugin[] (AdapterBuildContext\n // type updated to `Plugin[] | Promise<Plugin[]>`).\n // #95 — inject the config dirs so the client build's router/entry + typed-client codegen honor\n // custom appDir/serverDir/agentsDir (e.g. \"apps/web\" / \"core\" / \"core/agents\").\n makeVitePlugins: async (opts) =>\n [\n react(),\n ...(await theoPluginAsync({\n ...opts,\n appDir: config.appDir,\n serverDir: config.serverDir,\n agentsDir: config.agentsDir,\n })),\n ].flat(),\n\n // #369 — the same inversion, for the same reason. A Worker has no filesystem, so the Cloudflare\n // entry bakes its routes at build time; importing the scanner from `adapters/` would add the\n // `adapters → server` edge that `adapters-may-only-depend-on-core-router-services` refuses. The\n // CLI already imports both sides, so it composes the scan and hands over the result.\n //\n // A module rather than a closure since B-312: the wrong argument it carried was unreachable from\n // any test while it lived in here, because reaching it meant running the whole build.\n scanRoutes: createBuildScanRoutes(cwd, config),\n }\n\n // T1.1 (architecture-medium-deferrals, ADR D1) — Adapter Registry replaces\n // the previous 9-case switch. New adapters add 1 line in `adapters/registry.ts`;\n // CLI is closed for modification (OCP).\n // #409 / #410 — a config key that validates and is then never read makes the\n // deployed app behave as if the operator had not written it, with nothing\n // anywhere saying so. Name it before the build output scrolls past.\n const { warnUnappliedConfig } = await import('../../adapters/config-support.js')\n\n // #461 / #321 / #322 — the rate-limit refusal moved to `buildCommand`, above `cleanOutDir`, because\n // this position made its own comment false: it claimed the combination was refused \"BEFORE the build\n // writes anything\" and it is reached a hundred lines after the output has been emptied (B-336).\n\n warnUnappliedConfig(config, adapter, target, (message) => {\n console.log(message)\n })\n\n await adapter.build(config, cwd, ctx)\n}\n\nasync function emitCronArtifacts(opts: {\n cwd: string\n serverDir: string\n agentsDir: string\n distDir: string\n target: BuildTarget\n}): Promise<void> {\n // Crons live in two conventional homes: `server/crons/` (a backend trigger) and\n // `agents/schedules/` (a scheduled agent run, kept in the agent domain). Both feed one manifest.\n const cronsDir = resolve(opts.serverDir, 'crons')\n const agentsSchedulesDir = resolve(opts.cwd, opts.agentsDir, 'schedules')\n\n const cronNodes = await scanCronDirs([cronsDir, agentsSchedulesDir])\n const manifestPath = resolve(opts.distDir, 'crons.json')\n writeCronManifest(manifestPath, cronNodes, opts.cwd)\n\n console.log(` ✓ Crons: ${cronNodes.length} declared`)\n\n if (cronNodes.length === 0) return\n\n // EC-201: target-specific translation. N/A targets emit a warning + skip.\n if (CRON_NA_TARGETS.has(opts.target)) {\n console.log(\n ` ⚠ Cron not supported by target \"${opts.target}\" — declared crons skipped. ` +\n `Supported targets: ${CRON_SUPPORTED_TARGETS.join(', ')}.`,\n )\n return\n }\n\n const manifestEntries = cronNodes.map((n) => ({\n name: n.name,\n filePath: relativize(n.filePath, opts.cwd),\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n\n try {\n switch (opts.target) {\n case 'vercel':\n translateCronToVercel(resolve(opts.cwd, 'vercel.json'), manifestEntries)\n console.log(` ✓ Cron → vercel.json crons[] (${cronNodes.length} entries)`)\n break\n case 'cloudflare':\n translateCronToCloudflare(resolve(opts.cwd, 'wrangler.toml'), manifestEntries)\n console.log(` ✓ Cron → wrangler.toml [triggers] (${cronNodes.length})`)\n break\n case 'aws-lambda':\n translateCronToAws(resolve(opts.cwd, 'serverless.yml'), manifestEntries)\n console.log(` ✓ Cron → serverless.yml functions (${cronNodes.length})`)\n break\n case 'deno-deploy':\n translateCronToDeno(resolve(opts.distDir, 'crons-entry.ts'), manifestEntries)\n console.log(` ✓ Cron → ${opts.distDir}/crons-entry.ts (Deno.cron)`)\n break\n case 'node':\n console.log(` ✓ Cron → in-process scheduler (theokit start)`)\n break\n }\n } catch (err) {\n if (err instanceof ExistingConfigUnparseableError) throw err\n throw err\n }\n}\n\nasync function emitJobArtifacts(opts: {\n cwd: string\n serverDir: string\n distDir: string\n}): Promise<void> {\n const jobsDir = resolve(opts.serverDir, 'jobs')\n\n const jobNodes = existsSync(jobsDir) ? await scanJobs(jobsDir) : []\n const manifestPath = resolve(opts.distDir, 'jobs.json')\n writeJobManifest(manifestPath, jobNodes, opts.cwd)\n console.log(` ✓ Jobs: ${jobNodes.length} declared`)\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time adapter translators: caller-controlled paths only.\n */\nimport { existsSync, readFileSync } from 'node:fs'\n\nimport { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronManifestEntry } from './cron-manifest.js'\n\n/**\n * Thrown when an existing platform-config file (vercel.json, wrangler.toml,\n * serverless.yml) cannot be parsed. Caller must fix the file before\n * re-running `theokit build`. We NEVER silently overwrite a user's config.\n */\nexport class ExistingConfigUnparseableError extends Error {\n readonly code = 'EXISTING_CONFIG_UNPARSEABLE'\n constructor(\n public readonly filePath: string,\n public readonly parseError: string,\n ) {\n super(\n `Existing config \"${filePath}\" could not be parsed: ${parseError}. ` +\n 'Fix or remove the file before re-running build — TheoKit never silently overwrites user configuration.',\n )\n this.name = 'ExistingConfigUnparseableError'\n }\n}\n\n// ──────────────────────────────────────────────────────────\n// Vercel — vercel.json crons[]\n// ──────────────────────────────────────────────────────────\n\ninterface VercelJson {\n crons?: { path: string; schedule: string }[]\n [key: string]: unknown\n}\n\n/**\n * Translate a TheoKit cron manifest into `vercel.json crons[]`.\n *\n * EC-105: existing fields (functions, headers, redirects, rewrites, env,\n * etc.) are preserved verbatim — ONLY the `crons[]` slice is replaced.\n */\nexport function translateCronToVercel(\n vercelJsonPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n let existing: VercelJson = {}\n if (existsSync(vercelJsonPath)) {\n const raw = readFileSync(vercelJsonPath, 'utf8')\n try {\n existing = JSON.parse(raw) as VercelJson\n } catch (err) {\n throw new ExistingConfigUnparseableError(\n vercelJsonPath,\n err instanceof Error ? err.message : String(err),\n )\n }\n }\n const merged: VercelJson = {\n ...existing,\n crons: crons.map((c) => ({\n path: `/api/__crons/${c.name}`,\n schedule: c.schedule,\n })),\n }\n writeAtomic(vercelJsonPath, JSON.stringify(merged, null, 2))\n}\n\n// ──────────────────────────────────────────────────────────\n// Cloudflare — wrangler.toml [triggers] crons\n// ──────────────────────────────────────────────────────────\n\n/**\n * Translate a TheoKit cron manifest into `wrangler.toml [triggers] crons`.\n *\n * EC-105: regex-based mutation that preserves comments + other sections\n * verbatim. Replaces only the `[triggers]` block (or appends if absent).\n */\nexport function translateCronToCloudflare(\n wranglerTomlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const schedules = crons.map((c) => `\"${c.schedule}\"`).join(', ')\n const triggersBlock = `[triggers]\\ncrons = [${schedules}]\\n`\n\n if (!existsSync(wranglerTomlPath)) {\n writeAtomic(wranglerTomlPath, triggersBlock)\n return\n }\n\n const existing = readFileSync(wranglerTomlPath, 'utf8')\n\n // Replace existing [triggers] section if present. Strategy: split into\n // line array, find the [triggers] header line, drop subsequent lines\n // until the next section header (line starting with `[`) or EOF.\n const lines = existing.split('\\n')\n const triggersIdx = lines.findIndex((l) => l.trim() === '[triggers]')\n\n let next: string\n if (triggersIdx !== -1) {\n let endIdx = lines.length\n for (let i = triggersIdx + 1; i < lines.length; i++) {\n if (lines[i].trim().startsWith('[')) {\n endIdx = i\n break\n }\n }\n const before = lines.slice(0, triggersIdx).join('\\n')\n const after = lines.slice(endIdx).join('\\n')\n next = `${before}\\n${triggersBlock.trimEnd()}\\n${after}`.replace(/\\n{3,}/g, '\\n\\n')\n } else {\n next = existing.endsWith('\\n')\n ? `${existing}\\n${triggersBlock}`\n : `${existing}\\n\\n${triggersBlock}`\n }\n writeAtomic(wranglerTomlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// AWS Lambda — serverless.yml functions.<fn>.events: schedule\n// ──────────────────────────────────────────────────────────\n\n/**\n * Convert TheoKit's 5-field UTC cron to AWS EventBridge's 6-field format.\n * EventBridge requires `?` in EITHER day-of-month OR day-of-week (not both `*`).\n *\n * Algorithm:\n * - If DOM is \"*\" and DOW is \"*\" → insert ? in DOW (default)\n * - If DOM is \"*\" and DOW is specific → insert ? in DOM\n * - If DOM is specific and DOW is \"*\" → insert ? in DOW\n * - Append \"*\" year field at end.\n */\nexport function convertToAwsCron(schedule: string): string {\n const parts = schedule.trim().split(/\\s+/)\n if (parts.length !== 5) {\n throw new Error(`Invalid 5-field schedule for AWS conversion: \"${schedule}\"`)\n }\n const [minute, hour, dom, month, dow] = parts\n let awsDom = dom\n let awsDow = dow\n if (dom === '*' && dow === '*') {\n awsDow = '?'\n } else if (dom === '*') {\n awsDom = '?'\n } else if (dow === '*') {\n awsDow = '?'\n }\n return `cron(${minute} ${hour} ${awsDom} ${month} ${awsDow} *)`\n}\n\n/**\n * Translate a TheoKit cron manifest into a `serverless.yml` functions\n * map with `events: - schedule: cron(...)` entries.\n *\n * EC-105: appends to `functions:` block, preserving all existing\n * functions/sections. Cron functions are named `cron_<name>` to avoid\n * collision with user-declared functions.\n */\nexport function translateCronToAws(\n serverlessYmlPath: string,\n crons: readonly CronManifestEntry[],\n): void {\n const cronFunctionsYaml = crons\n .map(\n (c) => ` cron_${c.name}:\n handler: .theokit/server/crons/${c.name}.handler\n events:\n - schedule: ${convertToAwsCron(c.schedule)}`,\n )\n .join('\\n')\n\n const block = `\\nfunctions:\\n${cronFunctionsYaml}\\n`\n\n if (!existsSync(serverlessYmlPath)) {\n // Minimal serverless.yml scaffold\n writeAtomic(\n serverlessYmlPath,\n `service: theokit-app\\nprovider:\\n name: aws\\n runtime: nodejs22.x\\n${block}`,\n )\n return\n }\n\n const existing = readFileSync(serverlessYmlPath, 'utf8')\n\n // Look for an existing top-level `functions:` block; if present, append our\n // cron entries under it (don't replace user-declared functions).\n const functionsRe = /^functions:\\s*\\n/m\n let next: string\n if (functionsRe.test(existing)) {\n next = existing.replace(functionsRe, (match) => `${match}${cronFunctionsYaml}\\n`)\n } else {\n next = existing.endsWith('\\n') ? `${existing}${block}` : `${existing}\\n${block}`\n }\n writeAtomic(serverlessYmlPath, next)\n}\n\n// ──────────────────────────────────────────────────────────\n// Deno Deploy — Deno.cron registrations\n// ──────────────────────────────────────────────────────────\n\n/**\n * Emit a Deno entry file that registers each cron via `Deno.cron`.\n *\n * Unlike Vercel/CF/AWS, Deno.cron is an in-process runtime API — the\n * entry file is a managed artifact (overwritten each build), not a user\n * config (so EC-105 doesn't apply here).\n */\nexport function translateCronToDeno(entryPath: string, crons: readonly CronManifestEntry[]): void {\n const lines = crons.map(\n (c) =>\n `Deno.cron(\"${c.name}\", \"${c.schedule}\", async () => {\n const mod = await import(\"../${c.filePath}\");\n const def = mod.default;\n await def.handler({\n traceId: crypto.randomUUID().replace(/-/g, \"\"),\n scheduledAt: new Date(),\n signal: AbortSignal.timeout(60_000),\n });\n});`,\n )\n const content = `// AUTOGENERATED by TheoKit cron build — DO NOT EDIT.\n// Source: server/crons/*.ts → .theokit/crons.json → this file.\n${lines.join('\\n\\n')}\n`\n writeAtomic(entryPath, content)\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time atomic write: caller-controlled paths only. No HTTP input\n * reaches these fs calls.\n */\n// T5a.1b — Web Crypto migration. Build-time only; node:fs + node:path stay\n// because this is a manifest-write leaf (e.g. .theokit/jobs.json) and per\n// ADR-0028 the runtime-portable boundary is the request handler, not the\n// scanner. Only node:crypto is swapped out — Web Crypto's\n// getRandomValues works in every supported runtime.\nimport { mkdirSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\n\n/**\n * Write `content` to `path` atomically via the tmp + rename pattern.\n *\n * Two concurrent calls to `writeAtomic(path, ...)` are guaranteed to\n * leave `path` containing valid content from ONE of the calls (never\n * truncated, never interleaved). POSIX rename is atomic on the same\n * filesystem.\n *\n * EC-106 (jobs-crons-webhooks-cost-tracking-plan) — shared helper for\n * `.theokit/crons.json` and `.theokit/jobs.json` manifest writes so a\n * concurrent dev-server scan + build manifest emit never produces\n * partial JSON.\n *\n * @param path destination path\n * @param content bytes (UTF-8 string) to write\n */\nexport function writeAtomic(path: string, content: string): void {\n mkdirSync(dirname(path), { recursive: true })\n // Include a random suffix so two concurrent writes don't trample each\n // other's tmp file. Web Crypto getRandomValues is non-blocking +\n // collision-safe for the tiny entropy we need (8 hex chars = 32 bits).\n // Hex-encoded manually to avoid Buffer (runtime-agnostic per ADR-0028).\n const randBuf = new Uint8Array(4)\n globalThis.crypto.getRandomValues(randBuf)\n let suffix = ''\n for (const b of randBuf) suffix += b.toString(16).padStart(2, '0')\n const tmp = `${path}.tmp-${process.pid}-${suffix}`\n writeFileSync(tmp, content, 'utf8')\n renameSync(tmp, path)\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { CronNode } from './cron-scan.js'\n\nexport const CRON_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface CronManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: 'forbid' | 'allow'\n}\n\nexport interface CronManifest {\n readonly schemaVersion: typeof CRON_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly crons: readonly CronManifestEntry[]\n}\n\n/**\n * Build a `CronManifest` from scanned `CronNode[]`. Filepaths are kept\n * relative to the caller's project root for portability.\n */\nexport function buildCronManifest(nodes: readonly CronNode[], projectRoot?: string): CronManifest {\n const crons: CronManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n schedule: n.schedule,\n concurrency: n.concurrency,\n }))\n return {\n schemaVersion: CRON_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n crons,\n }\n}\n\n/**\n * Write the cron manifest to `path` atomically (EC-106).\n *\n * Accepts either a pre-built `CronManifest` OR an array of `CronNode[]`\n * (which gets converted via `buildCronManifest`). The atomic-write\n * helper guarantees `path` always contains valid JSON, even under\n * concurrent writes (e.g., dev-server rescan + build).\n */\nexport function writeCronManifest(\n path: string,\n input: readonly CronNode[] | CronManifest,\n projectRoot?: string,\n): void {\n const manifest: CronManifest = isManifest(input) ? input : buildCronManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is CronManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'crons' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only. No HTTP\n * input ever reaches these fs calls.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport { importUserModule } from '../../config/import-user-module.js'\nimport { compareByCodeUnit } from '../_internal/compare-by-code-unit.js'\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { CronConcurrencyPolicy, CronDefinition } from './cron-types.js'\n\n/**\n * One discovered cron from build-time scan. The handler is intentionally\n * NOT included — manifest is platform-neutral and consumed by adapters\n * that emit static config. Runtime dispatch loads the handler at fire time.\n */\nexport interface CronNode {\n readonly name: string\n readonly filePath: string\n readonly schedule: string\n readonly concurrency: CronConcurrencyPolicy\n}\n\nexport class DuplicateCronNameError extends Error {\n readonly code = 'DUPLICATE_CRON_NAME'\n constructor(\n public readonly cronName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate cron name \"${cronName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Cron names must be unique across server/crons/ and agents/schedules/.',\n )\n this.name = 'DuplicateCronNameError'\n }\n}\n\nconst CRON_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface CronModule {\n default?: unknown\n}\n\nfunction isCronDefinition(value: unknown): value is CronDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.schedule === 'string' &&\n typeof def.handler === 'function' &&\n (def.concurrency === 'forbid' || def.concurrency === 'allow')\n )\n}\n\n/**\n * Scan a directory for cron definition files and return the discovered\n * `CronNode[]` sorted by name. Throws `DuplicateCronNameError` on name\n * collision and `Error` on missing default export.\n *\n * Sequential by design — module imports are awaited one-by-one to keep\n * error messages anchored to the file that failed.\n */\nexport async function scanCrons(cronsDir: string): Promise<CronNode[]> {\n return scanCronDirs([cronsDir])\n}\n\n/**\n * Scan MULTIPLE cron directories and merge the results with a UNIFIED\n * duplicate-name guard across all of them. The framework discovers crons in\n * two conventional homes: `server/crons/` (a backend trigger) and\n * `agents/schedules/` (a scheduled agent run — kept in the agent domain). Both\n * feed the same manifest + deploy translation; a name may not collide across\n * the two dirs. Missing dirs are skipped (no error). Nodes are returned sorted\n * by name for a stable manifest.\n */\nexport async function scanCronDirs(dirs: readonly string[]): Promise<CronNode[]> {\n const filePaths: string[] = []\n for (const dir of dirs) {\n if (!existsSync(dir)) continue\n walkSourceFiles(dir, { extensions: CRON_EXTENSIONS }, (p) => {\n const base = basename(p)\n // Skip private helpers (`_helper.ts`) and OS junk (`.DS_Store`).\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n }\n\n const nodes: CronNode[] = []\n for (const filePath of filePaths) {\n let mod: CronModule\n try {\n mod = await importUserModule(filePath)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import cron file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isCronDefinition(exported)) {\n throw new Error(\n `Cron file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineCron(name, { schedule, handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n schedule: exported.schedule,\n concurrency: exported.concurrency,\n })\n }\n\n // Dup-name detection (unified across every scanned dir).\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateCronNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => compareByCodeUnit(a.name, b.name))\n}\n","import { writeAtomic } from '../_internal/atomic-write.js'\n\nimport type { JobNode } from './job-scan.js'\n\nexport const JOB_MANIFEST_SCHEMA_VERSION = 1 as const\n\nexport interface JobManifestEntry {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport interface JobManifest {\n readonly schemaVersion: typeof JOB_MANIFEST_SCHEMA_VERSION\n readonly generatedAt: string\n readonly jobs: readonly JobManifestEntry[]\n}\n\nexport function buildJobManifest(nodes: readonly JobNode[], projectRoot?: string): JobManifest {\n const jobs: JobManifestEntry[] = nodes.map((n) => ({\n name: n.name,\n filePath: projectRoot ? relativize(n.filePath, projectRoot) : n.filePath,\n maxAttempts: n.maxAttempts,\n hasInputSchema: n.hasInputSchema,\n }))\n return {\n schemaVersion: JOB_MANIFEST_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n jobs,\n }\n}\n\nexport function writeJobManifest(\n path: string,\n input: readonly JobNode[] | JobManifest,\n projectRoot?: string,\n): void {\n const manifest: JobManifest = isManifest(input) ? input : buildJobManifest(input, projectRoot)\n writeAtomic(path, JSON.stringify(manifest, null, 2))\n}\n\nfunction isManifest(value: unknown): value is JobManifest {\n return typeof value === 'object' && value !== null && 'schemaVersion' in value && 'jobs' in value\n}\n\nfunction relativize(absPath: string, root: string): string {\n if (absPath.startsWith(root)) {\n const trimmed = absPath.slice(root.length)\n return trimmed.startsWith('/') ? trimmed.slice(1) : trimmed\n }\n return absPath\n}\n","/* eslint-disable security/detect-non-literal-fs-filename --\n * Build-time scanner: caller-controlled directory paths only.\n */\nimport { existsSync } from 'node:fs'\nimport { basename } from 'node:path'\n\nimport { importUserModule } from '../../config/import-user-module.js'\nimport { compareByCodeUnit } from '../_internal/compare-by-code-unit.js'\nimport { walkSourceFiles } from '../_internal/scan-walker.js'\n\nimport type { JobDefinition } from './job-types.js'\n\nexport interface JobNode {\n readonly name: string\n readonly filePath: string\n readonly maxAttempts: number\n readonly hasInputSchema: boolean\n}\n\nexport class DuplicateJobNameError extends Error {\n readonly code = 'DUPLICATE_JOB_NAME'\n constructor(\n public readonly jobName: string,\n public readonly filePaths: readonly string[],\n ) {\n super(\n `Duplicate job name \"${jobName}\" defined in: ${filePaths.join(', ')}. ` +\n 'Job names must be unique across server/jobs/.',\n )\n this.name = 'DuplicateJobNameError'\n }\n}\n\nconst JOB_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.mjs'])\n\ninterface JobModule {\n default?: unknown\n}\n\nfunction isJobDefinition(value: unknown): value is JobDefinition {\n if (typeof value !== 'object' || value === null) return false\n const def = value as Record<string, unknown>\n return (\n typeof def.name === 'string' &&\n typeof def.handler === 'function' &&\n typeof def.maxAttempts === 'number' &&\n typeof def.hasInputSchema === 'boolean'\n )\n}\n\nexport async function scanJobs(jobsDir: string): Promise<JobNode[]> {\n if (!existsSync(jobsDir)) return []\n\n const filePaths: string[] = []\n walkSourceFiles(jobsDir, { extensions: JOB_EXTENSIONS }, (p) => {\n const base = basename(p)\n if (base.startsWith('_') || base.startsWith('.')) return\n filePaths.push(p)\n })\n\n const nodes: JobNode[] = []\n for (const filePath of filePaths) {\n let mod: JobModule\n try {\n mod = await importUserModule(filePath)\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err)\n throw new Error(`Failed to import job file \"${filePath}\": ${reason}`)\n }\n const exported = mod.default\n if (!isJobDefinition(exported)) {\n throw new Error(\n `Job file \"${filePath}\" is missing a valid default export. ` +\n 'Expected `export default defineJob(name, { handler })`.',\n )\n }\n nodes.push({\n name: exported.name,\n filePath,\n maxAttempts: exported.maxAttempts,\n hasInputSchema: exported.hasInputSchema,\n })\n }\n\n const byName = new Map<string, string[]>()\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? []\n bucket.push(node.filePath)\n byName.set(node.name, bucket)\n }\n for (const [name, paths] of byName) {\n if (paths.length > 1) {\n throw new DuplicateJobNameError(name, paths)\n }\n }\n\n return nodes.sort((a, b) => compareByCodeUnit(a.name, b.name))\n}\n","/**\n * State cleanup utilities (Phase 2 of\n *\n * - `cleanOutDir` — Astro pattern: empty a directory except a skip list,\n * used at `theokit build` start.\n * - `gcAgentRegistry` — Nuxt LRU pattern: delete oldest agent dirs when\n * count exceeds cap, used at `theokit dev` startup.\n *\n * EC-3 (MUST FIX, CRITICAL): cleanOutDir refuses to wipe anything outside\n * the current cwd. Prevents catastrophic `distDir: '/'` data loss.\n * EC-9 (SHOULD TEST): gcAgentRegistry handles dirs with mtime=0 (Docker overlay).\n * EC-11 (SHOULD TEST): cleanOutDir normalizes trailing-slash in skip basenames.\n * EC-12 (SHOULD TEST): cleanOutDir catches EROFS and continues.\n */\n\nimport { promises as fs } from 'node:fs'\nimport { basename, resolve as resolvePath, sep } from 'node:path'\n\nimport type {\n CleanOutDirOptions,\n CleanOutDirResult,\n GcAgentRegistryOptions,\n GcAgentRegistryResult,\n} from './cleanup-types.js'\n\nconst DEFAULT_SKIP = ['.git', '.gitkeep', '.gitignore']\n// DEFAULT_MAX_AGENTS removed in Phase 7 — gcAgentRegistry is a tombstone.\n\nfunction normalizeSkipName(name: string): string {\n // EC-11 — strip trailing slash + leading `./`\n return basename(name.replace(/\\/$/, ''))\n}\n\n/**\n * Empty a directory, preserving entries in the skip list.\n *\n * Throws if `opts.dir` is not inside `process.cwd()` (EC-3 path safety).\n * Returns `{deleted:0, kept:0}` when the directory does not exist.\n */\nexport async function cleanOutDir(opts: CleanOutDirOptions): Promise<CleanOutDirResult> {\n const resolvedDir = resolvePath(opts.dir)\n const resolvedCwd = resolvePath(process.cwd())\n\n // EC-3 — path safety guard. CRITICAL.\n if (resolvedDir === resolvedCwd) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be a child of cwd, not cwd itself`,\n )\n }\n if (!resolvedDir.startsWith(resolvedCwd + sep)) {\n throw new Error(\n `cleanOutDir refused to wipe ${resolvedDir} — must be inside cwd (${resolvedCwd})`,\n )\n }\n\n const skip = new Set((opts.skip ?? DEFAULT_SKIP).map(normalizeSkipName))\n\n let entries: { name: string }[]\n try {\n entries = await fs.readdir(resolvedDir, { withFileTypes: true })\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') return { deleted: 0, kept: 0 }\n throw err\n }\n\n let deleted = 0\n let kept = 0\n for (const entry of entries) {\n const name = entry.name\n if (skip.has(name)) {\n kept++\n continue\n }\n const fullPath = resolvePath(resolvedDir, name)\n try {\n await fs.rm(fullPath, { recursive: true, force: true, maxRetries: 3 })\n deleted++\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n deleted++ // already gone\n continue\n }\n // EC-12 — EROFS or other rm failure: warn + continue, don't crash.\n console.warn(\n `[theokit] cleanOutDir could not remove ${fullPath} (${code ?? 'unknown'}); skipping`,\n )\n kept++\n }\n }\n\n return { deleted, kept }\n}\n\n/**\n * Phase 7 — TOMBSTONE for backward-compat. The SDK v1.1.0's `Agent.registry`\n * handles GC natively; this function is a no-op + emits a deprecation warning\n * ONCE per process (EC-10).\n *\n * Will be deleted entirely in TheoKit 0.4.0. Marked deprecated via runtime\n * warning rather than `@deprecated` JSDoc tag to avoid the eslint\n * sonarjs/deprecation flagging our own internal symbols.\n */\nlet warnedOnce = false\nexport async function gcAgentRegistry(\n _opts: GcAgentRegistryOptions,\n): Promise<GcAgentRegistryResult> {\n if (!warnedOnce) {\n warnedOnce = true\n console.warn(\n '[theokit] gcAgentRegistry is deprecated; SDK Agent.registry handles GC natively (configure via theo.config.ts > agents.registry)',\n )\n }\n return Promise.resolve({ deleted: 0, kept: 0 })\n}\n\n/**\n * @internal — testing helper. Resets the module-scoped warnedOnce flag.\n */\nexport function __resetGcDeprecationWarnedForTests(): void {\n warnedOnce = false\n}\n","import { existsSync } from 'node:fs'\nimport { join, relative, resolve, sep } from 'node:path'\n\nimport type { AdapterBuildContext } from '../../adapters/types.js'\nimport { scanAgents } from '../../server/scan/agent-scan.js'\nimport { scanServerRoutes } from '../../server/scan/scan.js'\nimport { scanWebSocketRoutes } from '../../server/scan/ws-scan.js'\n\n/**\n * What a scanned deploy target is handed instead of a filesystem.\n *\n * #369 — a Worker has no filesystem at request time, so the Cloudflare entry bakes its routes at\n * build time. Importing the scanner from `adapters/` would add the `adapters → server` edge that\n * `adapters-may-only-depend-on-core-router-services` refuses, so the CLI composes the scan and\n * hands over the result.\n *\n * ## Why this is a module rather than a closure inside `buildCommand`\n *\n * It was a closure, and the defect it carried was invisible to every test: `buildCommand` loads a\n * config, runs vite twice and writes a tree, so nothing could ask it one question about one call.\n * Extracted at B-312, whose whole content was a single argument being wrong.\n *\n * Paths are made relative to the project root here, where `projectRoot` is known: that string is\n * both the emitted import specifier and the key the executor looks a module up by, and the scanners\n * return absolute paths.\n */\nexport function createBuildScanRoutes(\n projectRoot: string,\n config: { agentsDir?: string },\n): NonNullable<AdapterBuildContext['scanRoutes']> {\n return (serverDir: string) => {\n const abs = resolve(projectRoot, serverDir)\n const toProjectRelative = (p: string): string => relative(projectRoot, p).split(sep).join('/')\n\n return {\n routes: scanServerRoutes(abs).map((route) => ({\n filePath: toProjectRelative(route.filePath),\n routePath: route.routePath,\n methods: route.methods ?? [],\n })),\n wsRoutes: scanWebSocketRoutes(abs).map((ws) =>\n toProjectRelative(typeof ws === 'string' ? ws : ws.filePath),\n ),\n // #367 — agents are a DIFFERENT scan served by a DIFFERENT function, which is why no adapter\n // had ever heard of them: the entries route `/api/` through `scanServerRoutes` +\n // `executeRoute` alone, so `/api/agents/<name>` matched nothing and 404'd on every target.\n // Scanned here, beside the routes, because the same inversion argument applies verbatim.\n //\n // B-312 — the root is the PROJECT ROOT, and was `dirname(abs)`. `config.agentsDir` is\n // documented and declared relative to the project root, while `dirname(serverDir)` is the\n // root only when `serverDir` is a direct child of it. The scaffold's own nested layout\n // (`serverDir: 'src/server'`, `agentsDir: 'src/server/agents'`) made the two disagree, and\n // `join()` produced `<root>/src/src/server/agents` — so `scanAgents` returned `[]` and every\n // `/api/agents/*` route 404'd on every scanned target. Measured on a live Cloudflare deploy,\n // 2026-09-26. Every other caller in the tree already passes the project root.\n agents: scanAgents(projectRoot, config.agentsDir).map((agent) => ({\n filePath: toProjectRelative(agent.filePath),\n agentPath: agent.agentPath,\n name: agent.name,\n })),\n // B-185 — the identity module, decided here for the same reason the agents are: this provider\n // is handed `serverDir`, and a Worker has no filesystem to look for it on. An app with no\n // `server/context.ts` yields `undefined`, and the generator then emits no import — importing\n // a file that is not there would fail the BUILD rather than one request.\n contextModule: existsSync(join(abs, 'context.ts'))\n ? toProjectRelative(join(abs, 'context.ts'))\n : undefined,\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAAA,mBAAkB;AAC3B,SAAS,WAAAC,gBAAe;;;ACExB,SAAS,YAAY,oBAAoB;;;ACMzC,SAAS,WAAW,YAAY,qBAAqB;AACrD,SAAS,eAAe;AAkBjB,SAAS,YAAY,MAAc,SAAuB;AAC/D,YAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;AAK5C,QAAM,UAAU,IAAI,WAAW,CAAC;AAChC,aAAW,OAAO,gBAAgB,OAAO;AACzC,MAAI,SAAS;AACb,aAAW,KAAK,QAAS,WAAU,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AACjE,QAAM,MAAM,GAAG,IAAI,QAAQ,QAAQ,GAAG,IAAI,MAAM;AAChD,gBAAc,KAAK,SAAS,MAAM;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;AAChB,QAAM,UAAUA,SAAQ,KAAK,WAAW,MAAM;AAE9C,QAAM,WAAWG,YAAW,OAAO,IAAI,MAAM,SAAS,OAAO,IAAI,CAAC;AAClE,QAAM,eAAeH,SAAQ,KAAK,SAAS,WAAW;AACtD,mBAAiB,cAAc,UAAU,KAAK,GAAG;AACjD,UAAQ,IAAI,kBAAa,SAAS,MAAM,WAAW;AACrD;AAEA,SAASE,YAAW,SAAiB,MAAsB;AACzD,MAAI,QAAQ,WAAW,IAAI,GAAG;AAC5B,UAAM,UAAU,QAAQ,MAAM,KAAK,MAAM;AACzC,WAAO,QAAQ,WAAW,GAAG,IAAI,QAAQ,MAAM,CAAC,IAAI;AAAA,EACtD;AACA,SAAO;AACT;","names":["existsSync","resolve","existsSync","existsSync","relativize","isManifest","existsSync","basename","existsSync","basename","basename","existsSync","sep","sep","existsSync","resolve","writeManifest","relativize","existsSync"]}
@@ -1,11 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import "tsx/esm";
3
+ import {
4
+ readDocumentShell
5
+ } from "./chunk-IJQQNHL7.js";
3
6
  import {
4
7
  planDeployedPlugins
5
8
  } from "./chunk-C43AHOHI.js";
6
9
  import {
7
10
  deployedEntryPreamble
8
- } from "./chunk-R36YNWBU.js";
11
+ } from "./chunk-XLFDYTWO.js";
9
12
  import {
10
13
  agentsDirLiteral,
11
14
  deployedAgentsFragment,
@@ -15,10 +18,11 @@ import {
15
18
  describeDeployedSecurityHeaders,
16
19
  rateLimitCheckFragment,
17
20
  serverDirLiteral
18
- } from "./chunk-SEGD3JUC.js";
21
+ } from "./chunk-EQJF2EH5.js";
19
22
  import {
20
23
  nodeAdapter
21
- } from "./chunk-G7U7FQVC.js";
24
+ } from "./chunk-UFBBFP75.js";
25
+ import "./chunk-3PWQQWT6.js";
22
26
  import "./chunk-WSMLSIS5.js";
23
27
  import {
24
28
  assertServicesUnsupported,
@@ -49,7 +53,8 @@ var RUNTIME_GUARDS = [
49
53
  `}`
50
54
  ];
51
55
  function renderBunEntry(port, opts = {}) {
52
- const streamingComment = opts.ssrStreaming ? `// T2.3 \u2014 ssrStreaming on; renderStreamingWeb may be consumed by app code` : `// (ssrStreaming off)`;
56
+ const document = opts.ssr === true ? { htmlHead: opts.htmlHead, htmlTail: opts.htmlTail } : void 0;
57
+ const streamingComment = document !== void 0 ? `// ssr on \u2014 the document is rendered by this handler, not read from .theokit/client` : `// ssr off \u2014 the document is the built client shell, served from disk`;
53
58
  const runtimeConfig = deployedRuntimeConfigFragment(opts);
54
59
  const agentsFragment = deployedAgentsFragment(
55
60
  {
@@ -77,12 +82,25 @@ function renderBunEntry(port, opts = {}) {
77
82
  ``,
78
83
  `import { resolve, join } from 'node:path'`,
79
84
  `import { existsSync } from 'node:fs'`,
80
- `import { scanServerRoutes, matchRoute, executeRoute, createProductionLoader, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler${opts.rateLimit === void 0 ? "" : ", createRateLimiterWeb"} } from 'theokit/server'`,
85
+ // One element per emitted line, like every neighbour, and the conditional import is a spread
86
+ // rather than an interpolated `\n`. That is not a style preference: this line carried the
87
+ // fragment inside a nested double-quoted string, where an escaped backslash is a backslash, so
88
+ // the import reached the module joined by two characters and Bun refused it. A construct that
89
+ // cannot express a malformed line beats one escaped correctly (B-325), and `sonarjs` refuses the
90
+ // nesting outright — the lint was naming the cause.
91
+ `import { scanServerRoutes, matchRoute, createProductionLoader } from 'theokit/server/scan'`,
92
+ `import { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'`,
93
+ ...opts.rateLimit === void 0 ? [] : [`import { createRateLimiterWeb } from 'theokit/server/rate-limit'`],
81
94
  `import { createWebShim } from 'theokit/adapters/web-shim'`,
82
95
  `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,
96
+ // The renderer the node build already emits for this target and nothing imported. Its own header
97
+ // names Bun: "Web Standards streaming entry for edge runtimes (Cloudflare, Bun, Deno, Vercel
98
+ // Edge)". Measured on a real build: `.theokit/server/entry-server.js` is 95513 bytes and exports
99
+ // the render, and `.theokit/bun/server.mjs` referenced it zero times.
100
+ ...document === void 0 ? [] : [`import { renderStreamingWeb } from '../server/entry-server.js'`],
83
101
  `// T3.2 \u2014 WS bridge for Bun runtime`,
84
102
  `import { createBunWsBridge } from 'theokit/adapters/ws-shim'`,
85
- `import { scanWebSocketRoutes } from 'theokit/server'`,
103
+ `import { scanWebSocketRoutes } from 'theokit/server/scan'`,
86
104
  ``,
87
105
  `const cwd = process.cwd()`,
88
106
  `const clientDir = resolve(cwd, '.theokit/client')`,
@@ -134,22 +152,35 @@ function renderBunEntry(port, opts = {}) {
134
152
  ` },`,
135
153
  `})`,
136
154
  ``,
137
- ...bunHandleRequestFragment(runtimeConfig.executeRouteSpread, agentsFragment.branch)
155
+ ...bunHandleRequestFragment(runtimeConfig.executeRouteSpread, agentsFragment.branch, document)
138
156
  ].join("\n");
139
157
  }
140
- function bunHandleRequestFragment(runtimeSpread, agentBranch) {
158
+ function bunHandleRequestFragment(runtimeSpread, agentBranch, document) {
141
159
  return [
142
160
  `async function handleRequest(request) {`,
143
161
  ` const url = new URL(request.url)`,
144
162
  ` const pathname = url.pathname`,
145
163
  ``,
146
164
  ` // 1) Static assets`,
147
- ` const staticPath = pathname === '/' ? '/index.html' : pathname`,
148
- ` const fullStatic = join(clientDir, staticPath)`,
149
- ` if (existsSync(fullStatic)) {`,
150
- ` const file = Bun.file(fullStatic)`,
151
- ` if (await file.exists()) return new Response(file)`,
152
- ` }`,
165
+ ...document === void 0 ? [
166
+ ` const staticPath = pathname === '/' ? '/index.html' : pathname`,
167
+ ` const fullStatic = join(clientDir, staticPath)`,
168
+ ` if (existsSync(fullStatic)) {`,
169
+ ` const file = Bun.file(fullStatic)`,
170
+ ` if (await file.exists()) return new Response(file)`,
171
+ ` }`
172
+ ] : [
173
+ ` // \`/\` is deliberately NOT mapped to index.html here: that file is the client shell,`,
174
+ ` // and answering the document from it is what served an empty <div id="root"> on an`,
175
+ ` // ssr build. Real assets still come from disk; the document falls through to (3).`,
176
+ ` if (pathname !== '/') {`,
177
+ ` const fullStatic = join(clientDir, pathname)`,
178
+ ` if (existsSync(fullStatic)) {`,
179
+ ` const file = Bun.file(fullStatic)`,
180
+ ` if (await file.exists()) return new Response(file)`,
181
+ ` }`,
182
+ ` }`
183
+ ],
153
184
  ``,
154
185
  ` // 2) API routes through the full executeRoute pipeline via the shim`,
155
186
  ` if (pathname.startsWith('/api/') || __theoIsAgentCardPath(pathname)) {`,
@@ -165,9 +196,22 @@ function bunHandleRequestFragment(runtimeSpread, agentBranch) {
165
196
  ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeSpread} }))`,
166
197
  ` }`,
167
198
  ``,
168
- ` // 3) SPA fallback`,
169
- ` const indexPath = join(clientDir, 'index.html')`,
170
- ` if (existsSync(indexPath)) return new Response(Bun.file(indexPath))`,
199
+ ...document === void 0 ? [
200
+ ` // 3) SPA fallback`,
201
+ ` const indexPath = join(clientDir, 'index.html')`,
202
+ ` if (existsSync(indexPath)) return new Response(Bun.file(indexPath))`
203
+ ] : [
204
+ ` // 3) The document, rendered here rather than read from disk.`,
205
+ ` //`,
206
+ ` // No nonce is minted: the outer wrapper applies a precomputed SECURITY_HEADERS constant,`,
207
+ ` // so a per-request value would have to be threaded through it. That is a separate change`,
208
+ ` // with its own blast radius, and the shell this replaces carries only external`,
209
+ ` // <script src> tags, which \`script-src 'self'\` already allows.`,
210
+ ` return await renderStreamingWeb(request, {`,
211
+ ` htmlHead: ${JSON.stringify(document.htmlHead ?? "")},`,
212
+ ` htmlTail: ${JSON.stringify(document.htmlTail ?? "")},`,
213
+ ` })`
214
+ ],
171
215
  ``,
172
216
  ` return notFoundResponse()`,
173
217
  `}`,
@@ -185,6 +229,12 @@ async function buildBun(config, cwd, deps = {}, ctx) {
185
229
  const pluginsPlan = planDeployedPlugins(config.plugins, "bun");
186
230
  const entry = renderBunEntry(config.port, {
187
231
  ssrStreaming: config.ssrStreaming,
232
+ // B-334 — the sixth time this shape has been fixed one target at a time: the renderer honoured an
233
+ // option no build passed (B-185, B-235, B-312, B-315, B-317). Here it was worse — the option only
234
+ // changed a comment. The shell is read HERE rather than in the emitter, because reading a file is
235
+ // the build's job and not a string emitter's.
236
+ ssr: config.ssr,
237
+ ...readDocumentShell(cwd, config.ssr),
188
238
  securityHeaders: config.security?.headers,
189
239
  csrf: config.security?.csrf,
190
240
  disallowed: config.security?.disallowed,
@@ -213,8 +263,14 @@ async function buildBun(config, cwd, deps = {}, ctx) {
213
263
  `${describeDeployedSecurityHeaders({
214
264
  target: "bun",
215
265
  securityHeaders: config.security?.headers,
216
- // No deploy target other than the streamed Cloudflare worker renders HTML
217
- // at request time, so none of the rest can mint a nonce.
266
+ // Bun renders the document at request time when `ssr` is on (B-334), and still mints no nonce:
267
+ // the outer wrapper applies a precomputed SECURITY_HEADERS constant, so a per-request value
268
+ // would have to be threaded through it.
269
+ //
270
+ // This used to read "No deploy target other than the streamed Cloudflare worker renders HTML at
271
+ // request time, so none of the rest can mint a nonce." True when written, false the moment B-317
272
+ // shipped — a CONSEQUENCE of the fleet at the time, never a prohibition, which is why rendering
273
+ // here is consistent with the intent rather than against it.
218
274
  mintsNonce: false,
219
275
  // Bun serves `.theokit/client` itself, so the document DOES pass through
220
276
  // the handler these headers are attached to.
@@ -224,6 +280,11 @@ async function buildBun(config, cwd, deps = {}, ctx) {
224
280
  );
225
281
  }
226
282
  var bunAdapter = {
283
+ // The entry runs IN the project: it resolves `serverDir` against `cwd`, so `node_modules` is
284
+ // present and the scan has a tree to read. `docs/adr/0020` leaves this target alone for exactly
285
+ // that reason.
286
+ readsSourceAtRunTime: true,
287
+ specifiersResolvedBy: "the-project-at-run-time",
227
288
  name: "bun",
228
289
  streamsResponses: true,
229
290
  // #409 / #410 — the generated entry calls `executeRoute` with routes, loader
@@ -259,4 +320,4 @@ export {
259
320
  bunAdapter,
260
321
  renderBunEntry
261
322
  };
262
- //# sourceMappingURL=bun-CZXHPK2W.js.map
323
+ //# sourceMappingURL=bun-I7YM3RDB.js.map