theokit 0.77.1 → 0.77.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/README.md +7 -2
  2. package/dist/{actions-virtual-module-UIX5YWZR.js → actions-virtual-module-CA4YEAL3.js} +3 -3
  3. package/dist/{actions-virtual-module-V5Q4XVL5.js → actions-virtual-module-QRTV4NHS.js} +2 -2
  4. package/dist/{agent-MJWQRSJ2.js → agent-IBDE65UJ.js} +2 -2
  5. package/dist/{app-typed-client-6FQB5FQO.js → app-typed-client-ZCLFXBEC.js} +3 -3
  6. package/dist/{app-typed-client-JCBQGPMP.js → app-typed-client-ZCMCBS45.js} +2 -2
  7. package/dist/{aws-lambda-XT7ZDJ6B.js → aws-lambda-JXUPC5QM.js} +17 -6
  8. package/dist/aws-lambda-JXUPC5QM.js.map +1 -0
  9. package/dist/boot/index.js +3 -3
  10. package/dist/{build-Y457R5HE.js → build-2VOQOWZE.js} +7 -7
  11. package/dist/{bun-PJLDELDT.js → bun-73JZLCKU.js} +16 -5
  12. package/dist/bun-73JZLCKU.js.map +1 -0
  13. package/dist/{chunk-35OI2TKT.js → chunk-5UJRZC4J.js} +37 -19
  14. package/dist/chunk-5UJRZC4J.js.map +1 -0
  15. package/dist/{chunk-EQJF2EH5.js → chunk-DDWF3UUI.js} +32 -1
  16. package/dist/chunk-DDWF3UUI.js.map +1 -0
  17. package/dist/{chunk-OSSNCUS6.js → chunk-FCBRWSBH.js} +4 -4
  18. package/dist/{chunk-BFDEEJOK.js → chunk-GNQKV2NP.js} +1 -1
  19. package/dist/{chunk-BFDEEJOK.js.map → chunk-GNQKV2NP.js.map} +1 -1
  20. package/dist/{chunk-KQBY62AE.js → chunk-HWRZUQPE.js} +31 -25
  21. package/dist/chunk-HWRZUQPE.js.map +1 -0
  22. package/dist/{chunk-OKFRGAYZ.js → chunk-IBZITTK7.js} +47 -27
  23. package/dist/chunk-IBZITTK7.js.map +1 -0
  24. package/dist/{chunk-3TCWOHLY.js → chunk-JZLNZOEL.js} +1 -1
  25. package/dist/{chunk-G3DDIEYE.js → chunk-MQCXYZEV.js} +4 -2
  26. package/dist/chunk-MQCXYZEV.js.map +1 -0
  27. package/dist/{chunk-E22GPCCO.js → chunk-MSSUMKFR.js} +61 -55
  28. package/dist/chunk-MSSUMKFR.js.map +1 -0
  29. package/dist/{chunk-XLFDYTWO.js → chunk-N7KDDYDB.js} +5 -3
  30. package/dist/chunk-N7KDDYDB.js.map +1 -0
  31. package/dist/{chunk-TODO6J42.js → chunk-PV6IO25S.js} +1 -1
  32. package/dist/chunk-PV6IO25S.js.map +1 -0
  33. package/dist/{chunk-N5YHENWJ.js → chunk-SHBPXX5E.js} +2 -2
  34. package/dist/{chunk-HZAXFD55.js → chunk-VSK5Y4ET.js} +2 -2
  35. package/dist/{chunk-GNV34JMI.js → chunk-XCPM72D6.js} +2 -2
  36. package/dist/{chunk-HNALEGOL.js → chunk-YM6ONZYE.js} +12 -10
  37. package/dist/chunk-YM6ONZYE.js.map +1 -0
  38. package/dist/cli/index.js +12 -12
  39. package/dist/{cloudflare-F7KLBOU4.js → cloudflare-6ONK5HCO.js} +11 -3
  40. package/dist/cloudflare-6ONK5HCO.js.map +1 -0
  41. package/dist/{config-support-2TER2BYD.js → config-support-ZJIRVUWZ.js} +10 -5
  42. package/dist/config-support-ZJIRVUWZ.js.map +1 -0
  43. package/dist/{db-5WOK6HA2.js → db-72T47G5S.js} +2 -2
  44. package/dist/{deno-deploy-LJ5JQQVR.js → deno-deploy-ZM2UR5ZI.js} +16 -5
  45. package/dist/deno-deploy-ZM2UR5ZI.js.map +1 -0
  46. package/dist/{dev-N5LQFLBR.js → dev-AE7EWSB7.js} +6 -6
  47. package/dist/{docker-OTV3M54A.js → docker-3ARABEZ2.js} +2 -2
  48. package/dist/{generate-4DY3MEYB.js → generate-DAVXE5RV.js} +2 -2
  49. package/dist/{index-C2lcEI-4.d.ts → index-CY_llLI7.d.ts} +4 -1
  50. package/dist/index.js +4 -4
  51. package/dist/{info-ELSPSCXK.js → info-AYTNH6YT.js} +2 -2
  52. package/dist/{internal-api-H3C2ID6N.js → internal-api-JFA4JI3Z.js} +3 -3
  53. package/dist/{internal-api-5FTPYSEQ.js → internal-api-KQQHFTCG.js} +2 -2
  54. package/dist/{load-config-SKLFH7YL.js → load-config-YU5E76DL.js} +2 -2
  55. package/dist/{mcp-3ENI2IPS.js → mcp-UBGNYDMW.js} +3 -3
  56. package/dist/{netlify-ZPQNREFH.js → netlify-GRVT3MTT.js} +53 -10
  57. package/dist/netlify-GRVT3MTT.js.map +1 -0
  58. package/dist/{node-3EV3CVWB.js → node-UYRQNJNF.js} +2 -2
  59. package/dist/{openapi-OVXYHZ2S.js → openapi-ICJB2RBE.js} +2 -2
  60. package/dist/{preview-Y3JNYOFK.js → preview-XQJZ75QE.js} +3 -3
  61. package/dist/registry-JHWY7JRY.js +34 -0
  62. package/dist/{routes-UNJ77IQU.js → routes-XYXXR72Z.js} +2 -2
  63. package/dist/server/define/index.d.ts +7 -2
  64. package/dist/server/define/index.js +1 -1
  65. package/dist/server/http/index.d.ts +2 -1
  66. package/dist/server/http/index.js +8 -2
  67. package/dist/server/index.d.ts +1 -1
  68. package/dist/server/index.js +10 -10
  69. package/dist/{server-boundary-5ZTBC2KF.js → server-boundary-JA3UOKJS.js} +2 -2
  70. package/dist/{server-boundary-DTF6ZEUO.js → server-boundary-OJ6YIPQT.js} +3 -3
  71. package/dist/{start-EJFYT7ZU.js → start-AE5YCDVS.js} +7 -6
  72. package/dist/{start-EJFYT7ZU.js.map → start-AE5YCDVS.js.map} +1 -1
  73. package/dist/{static-VNN4HYRN.js → static-C7PWUTQO.js} +2 -2
  74. package/dist/{theo-cloud-243SPOIA.js → theo-cloud-NKZUJO3H.js} +2 -2
  75. package/dist/{vercel-EXKSZ2OQ.js → vercel-MRZXLOIQ.js} +19 -5
  76. package/dist/vercel-MRZXLOIQ.js.map +1 -0
  77. package/dist/vite-plugin/index.js +4 -4
  78. package/dist/{vite-plugin-MNZHNOM4.js → vite-plugin-JMWUVMP3.js} +5 -5
  79. package/package.json +3 -3
  80. package/dist/aws-lambda-XT7ZDJ6B.js.map +0 -1
  81. package/dist/bun-PJLDELDT.js.map +0 -1
  82. package/dist/chunk-35OI2TKT.js.map +0 -1
  83. package/dist/chunk-E22GPCCO.js.map +0 -1
  84. package/dist/chunk-EQJF2EH5.js.map +0 -1
  85. package/dist/chunk-G3DDIEYE.js.map +0 -1
  86. package/dist/chunk-HNALEGOL.js.map +0 -1
  87. package/dist/chunk-KQBY62AE.js.map +0 -1
  88. package/dist/chunk-OKFRGAYZ.js.map +0 -1
  89. package/dist/chunk-TODO6J42.js.map +0 -1
  90. package/dist/chunk-XLFDYTWO.js.map +0 -1
  91. package/dist/cloudflare-F7KLBOU4.js.map +0 -1
  92. package/dist/config-support-2TER2BYD.js.map +0 -1
  93. package/dist/deno-deploy-LJ5JQQVR.js.map +0 -1
  94. package/dist/netlify-ZPQNREFH.js.map +0 -1
  95. package/dist/registry-3D2KR7UE.js +0 -34
  96. package/dist/vercel-EXKSZ2OQ.js.map +0 -1
  97. /package/dist/{actions-virtual-module-UIX5YWZR.js.map → actions-virtual-module-CA4YEAL3.js.map} +0 -0
  98. /package/dist/{actions-virtual-module-V5Q4XVL5.js.map → actions-virtual-module-QRTV4NHS.js.map} +0 -0
  99. /package/dist/{agent-MJWQRSJ2.js.map → agent-IBDE65UJ.js.map} +0 -0
  100. /package/dist/{app-typed-client-6FQB5FQO.js.map → app-typed-client-ZCLFXBEC.js.map} +0 -0
  101. /package/dist/{app-typed-client-JCBQGPMP.js.map → app-typed-client-ZCMCBS45.js.map} +0 -0
  102. /package/dist/{build-Y457R5HE.js.map → build-2VOQOWZE.js.map} +0 -0
  103. /package/dist/{chunk-OSSNCUS6.js.map → chunk-FCBRWSBH.js.map} +0 -0
  104. /package/dist/{chunk-3TCWOHLY.js.map → chunk-JZLNZOEL.js.map} +0 -0
  105. /package/dist/{chunk-N5YHENWJ.js.map → chunk-SHBPXX5E.js.map} +0 -0
  106. /package/dist/{chunk-HZAXFD55.js.map → chunk-VSK5Y4ET.js.map} +0 -0
  107. /package/dist/{chunk-GNV34JMI.js.map → chunk-XCPM72D6.js.map} +0 -0
  108. /package/dist/{db-5WOK6HA2.js.map → db-72T47G5S.js.map} +0 -0
  109. /package/dist/{dev-N5LQFLBR.js.map → dev-AE7EWSB7.js.map} +0 -0
  110. /package/dist/{docker-OTV3M54A.js.map → docker-3ARABEZ2.js.map} +0 -0
  111. /package/dist/{generate-4DY3MEYB.js.map → generate-DAVXE5RV.js.map} +0 -0
  112. /package/dist/{info-ELSPSCXK.js.map → info-AYTNH6YT.js.map} +0 -0
  113. /package/dist/{internal-api-H3C2ID6N.js.map → internal-api-JFA4JI3Z.js.map} +0 -0
  114. /package/dist/{internal-api-5FTPYSEQ.js.map → internal-api-KQQHFTCG.js.map} +0 -0
  115. /package/dist/{load-config-SKLFH7YL.js.map → load-config-YU5E76DL.js.map} +0 -0
  116. /package/dist/{mcp-3ENI2IPS.js.map → mcp-UBGNYDMW.js.map} +0 -0
  117. /package/dist/{node-3EV3CVWB.js.map → node-UYRQNJNF.js.map} +0 -0
  118. /package/dist/{openapi-OVXYHZ2S.js.map → openapi-ICJB2RBE.js.map} +0 -0
  119. /package/dist/{preview-Y3JNYOFK.js.map → preview-XQJZ75QE.js.map} +0 -0
  120. /package/dist/{registry-3D2KR7UE.js.map → registry-JHWY7JRY.js.map} +0 -0
  121. /package/dist/{routes-UNJ77IQU.js.map → routes-XYXXR72Z.js.map} +0 -0
  122. /package/dist/{server-boundary-5ZTBC2KF.js.map → server-boundary-JA3UOKJS.js.map} +0 -0
  123. /package/dist/{server-boundary-DTF6ZEUO.js.map → server-boundary-OJ6YIPQT.js.map} +0 -0
  124. /package/dist/{static-VNN4HYRN.js.map → static-C7PWUTQO.js.map} +0 -0
  125. /package/dist/{theo-cloud-243SPOIA.js.map → theo-cloud-NKZUJO3H.js.map} +0 -0
  126. /package/dist/{vite-plugin-MNZHNOM4.js.map → vite-plugin-JMWUVMP3.js.map} +0 -0
@@ -14,7 +14,7 @@ import {
14
14
  import "./chunk-Z7CJHDLS.js";
15
15
  import {
16
16
  loadConfig
17
- } from "./chunk-35OI2TKT.js";
17
+ } from "./chunk-5UJRZC4J.js";
18
18
  import "./chunk-3QPVEJ7D.js";
19
19
  import "./chunk-O5JZ6ROY.js";
20
20
  import "./chunk-PQWVT6JC.js";
@@ -1068,4 +1068,4 @@ export {
1068
1068
  generate,
1069
1069
  generateCommand
1070
1070
  };
1071
- //# sourceMappingURL=generate-4DY3MEYB.js.map
1071
+ //# sourceMappingURL=generate-DAVXE5RV.js.map
@@ -1,4 +1,5 @@
1
1
  import { a as TheoErrorCode, T as TheoErrorEnvelope } from './error-envelope-DG47lt8E.js';
2
+ import './health-route-CYI7z5g3.js';
2
3
  import { IncomingMessage, ServerResponse } from 'node:http';
3
4
  import { P as PluginContext, W as WebOnRequestHook, g as WebPreHandlerHook, h as WebOnResponseHook, i as WebOnErrorHook } from './plugin-types-BUVfUQ0V.js';
4
5
  import { P as PluginRunner } from './plugin-runner-BVMOSxvb.js';
@@ -21,8 +22,10 @@ interface ExecuteActionOptions {
21
22
  pluginRunner?: PluginRunner;
22
23
  csrfMode?: CsrfMode;
23
24
  disallowed?: DisallowedConfig;
25
+ /** `theo.config.ts > jobs.backend`. Present, the handler gets `ctx.queue`, as a route does. */
26
+ jobBackend?: JobBackend;
24
27
  }
25
- declare function executeAction(filePath: string, exportName: string, req: IncomingMessage, res: ServerResponse, loadModule: LoadModule, serverDir?: string, requestId?: string, pluginRunner?: PluginRunner, csrfMode?: CsrfMode, disallowed?: DisallowedConfig): Promise<void>;
28
+ declare function executeAction(filePath: string, exportName: string, req: IncomingMessage, res: ServerResponse, loadModule: LoadModule, serverDir?: string, requestId?: string, pluginRunner?: PluginRunner, csrfMode?: CsrfMode, disallowed?: DisallowedConfig, jobBackend?: JobBackend): Promise<void>;
26
29
 
27
30
  /**
28
31
  * T5.2 — pluggable response/request transformer.
package/dist/index.js CHANGED
@@ -8,10 +8,10 @@ import {
8
8
  scanRoutes,
9
9
  theoConfigSchema,
10
10
  theoPlugin
11
- } from "./chunk-OKFRGAYZ.js";
11
+ } from "./chunk-IBZITTK7.js";
12
12
  import "./chunk-7NRFZBAL.js";
13
13
  import "./chunk-SSYDEKWF.js";
14
- import "./chunk-N5YHENWJ.js";
14
+ import "./chunk-SHBPXX5E.js";
15
15
  import "./chunk-7MCEJVGV.js";
16
16
  import "./chunk-4XZOUS5G.js";
17
17
  import "./chunk-OIGJOYX6.js";
@@ -19,7 +19,7 @@ import "./chunk-U3SPBLJF.js";
19
19
  import "./chunk-WSOAN4KN.js";
20
20
  import "./chunk-ENSFCKP6.js";
21
21
  import "./chunk-OGLS76RN.js";
22
- import "./chunk-KQBY62AE.js";
22
+ import "./chunk-HWRZUQPE.js";
23
23
  import "./chunk-36ZACTF3.js";
24
24
  import "./chunk-P6OS7652.js";
25
25
  import "./chunk-ZDUO4IYN.js";
@@ -36,9 +36,9 @@ import "./chunk-7HGZ3CKL.js";
36
36
  import "./chunk-A6UFN6QQ.js";
37
37
  import "./chunk-DV34VG3N.js";
38
38
  import "./chunk-V6Y2SMRG.js";
39
- import "./chunk-TRCJHFAX.js";
40
39
  import "./chunk-ACKBVBUI.js";
41
40
  import "./chunk-IZ3TIL6K.js";
41
+ import "./chunk-TRCJHFAX.js";
42
42
  import "./chunk-TQEE36VD.js";
43
43
  import "./chunk-54BIQFP4.js";
44
44
  import "./chunk-ZICY2CD7.js";
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-47MM2JUK.js";
6
6
  import {
7
7
  loadConfig
8
- } from "./chunk-35OI2TKT.js";
8
+ } from "./chunk-5UJRZC4J.js";
9
9
  import "./chunk-3QPVEJ7D.js";
10
10
  import "./chunk-O5JZ6ROY.js";
11
11
  import "./chunk-PQWVT6JC.js";
@@ -103,4 +103,4 @@ export {
103
103
  buildInfo,
104
104
  infoCommand
105
105
  };
106
- //# sourceMappingURL=info-ELSPSCXK.js.map
106
+ //# sourceMappingURL=info-AYTNH6YT.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  dispatchControllerRequest
3
- } from "./chunk-N5YHENWJ.js";
3
+ } from "./chunk-SHBPXX5E.js";
4
4
  import {
5
5
  mountAgent
6
6
  } from "./chunk-4XZOUS5G.js";
@@ -18,7 +18,7 @@ import {
18
18
  executeAction,
19
19
  executeRoute,
20
20
  handleBatchRequest
21
- } from "./chunk-KQBY62AE.js";
21
+ } from "./chunk-HWRZUQPE.js";
22
22
  import {
23
23
  incomingMessageToHandlerRequest,
24
24
  sendError
@@ -111,4 +111,4 @@ export {
111
111
  scanWebSocketRoutes,
112
112
  sendError
113
113
  };
114
- //# sourceMappingURL=internal-api-H3C2ID6N.js.map
114
+ //# sourceMappingURL=internal-api-JFA4JI3Z.js.map
@@ -16,7 +16,7 @@ import {
16
16
  handleCspReport,
17
17
  handleCsrfReadiness,
18
18
  mountAgent
19
- } from "./chunk-E22GPCCO.js";
19
+ } from "./chunk-MSSUMKFR.js";
20
20
  import {
21
21
  resolveProvider
22
22
  } from "./chunk-4JRXZTVQ.js";
@@ -88,4 +88,4 @@ export {
88
88
  scanWebSocketRoutes,
89
89
  sendError
90
90
  };
91
- //# sourceMappingURL=internal-api-5FTPYSEQ.js.map
91
+ //# sourceMappingURL=internal-api-KQQHFTCG.js.map
@@ -3,7 +3,7 @@ import "tsx/esm";
3
3
  import {
4
4
  deepMerge,
5
5
  loadConfig
6
- } from "./chunk-35OI2TKT.js";
6
+ } from "./chunk-5UJRZC4J.js";
7
7
  import "./chunk-3QPVEJ7D.js";
8
8
  import "./chunk-O5JZ6ROY.js";
9
9
  import "./chunk-PQWVT6JC.js";
@@ -13,4 +13,4 @@ export {
13
13
  deepMerge,
14
14
  loadConfig
15
15
  };
16
- //# sourceMappingURL=load-config-SKLFH7YL.js.map
16
+ //# sourceMappingURL=load-config-YU5E76DL.js.map
@@ -2,7 +2,7 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  createAgentSsrLoader
5
- } from "./chunk-OSSNCUS6.js";
5
+ } from "./chunk-FCBRWSBH.js";
6
6
  import {
7
7
  extractAppResources,
8
8
  handleMcpJsonRpc
@@ -47,7 +47,7 @@ async function serveMcpStdio(mod, name, appResources, streams) {
47
47
  // src/cli/commands/mcp.ts
48
48
  async function mcpCommand(name, deps = {}) {
49
49
  const projectRoot = deps.projectRoot ?? process.cwd();
50
- const agentsDir = deps.agentsDir ?? (await (await import("./load-config-SKLFH7YL.js")).loadConfig(projectRoot)).agentsDir;
50
+ const agentsDir = deps.agentsDir ?? (await (await import("./load-config-YU5E76DL.js")).loadConfig(projectRoot)).agentsDir;
51
51
  const agent = scanAgents(projectRoot, agentsDir).find((a) => a.name === name);
52
52
  if (!agent) {
53
53
  const names = scanAgents(projectRoot, agentsDir).map((a) => a.name).join(", ");
@@ -76,4 +76,4 @@ async function mcpCommand(name, deps = {}) {
76
76
  export {
77
77
  mcpCommand
78
78
  };
79
- //# sourceMappingURL=mcp-3ENI2IPS.js.map
79
+ //# sourceMappingURL=mcp-UBGNYDMW.js.map
@@ -9,20 +9,22 @@ import {
9
9
  } from "./chunk-72RSCKMW.js";
10
10
  import {
11
11
  deployedEntryPreamble
12
- } from "./chunk-XLFDYTWO.js";
12
+ } from "./chunk-N7KDDYDB.js";
13
13
  import {
14
14
  JSON_NOT_FOUND_RESPONSE,
15
15
  deployedAgentsFragment,
16
16
  deployedRateLimitFragment,
17
+ deployedReservedRoutesFragment,
17
18
  deployedRuntimeConfigFragment,
18
19
  deployedTraceFragment,
19
20
  describeDeployedSecurityHeaders,
20
21
  rateLimitCheckFragment,
22
+ reservedRouteBranch,
21
23
  serverDirLiteral
22
- } from "./chunk-EQJF2EH5.js";
24
+ } from "./chunk-DDWF3UUI.js";
23
25
  import {
24
26
  nodeAdapter
25
- } from "./chunk-G3DDIEYE.js";
27
+ } from "./chunk-MQCXYZEV.js";
26
28
  import {
27
29
  buildSecurityHeaders
28
30
  } from "./chunk-WSMLSIS5.js";
@@ -85,7 +87,13 @@ import { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHan
85
87
  `// theo.config.ts to read. The netlify.toml redirect routes only /api/* here,`,
86
88
  `// so this covers the API and not the document Netlify's static host serves`,
87
89
  `// (usetheokit/theokit#412).`,
88
- ...deployedEntryPreamble(runtimeConfig, agentsFragment, opts, "netlify"),
90
+ ...deployedEntryPreamble(
91
+ runtimeConfig,
92
+ agentsFragment,
93
+ opts,
94
+ "netlify",
95
+ deployedReservedRoutesFragment(opts)
96
+ ),
89
97
  ``,
90
98
  // B-027 — emitted only when a limit is declared.
91
99
  ...opts.rateLimit === void 0 ? [] : [
@@ -121,6 +129,7 @@ import { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHan
121
129
  ``,
122
130
  `async function handleRequest(request) {`,
123
131
  ` const url = new URL(request.url)`,
132
+ ...reservedRouteBranch("url.pathname", " "),
124
133
  ` if (!url.pathname.startsWith('/api/')${agentsFragment.hostBypass}) {`,
125
134
  ` return new Response('Not Found', { status: 404 })`,
126
135
  ` }`,
@@ -195,6 +204,32 @@ var THEO_SPA_FALLBACK_TARGET = [
195
204
  ' to = "/index.html"',
196
205
  " status = 200"
197
206
  ].join("\n");
207
+ var THEO_RESERVED_FROM = "/__theo/*";
208
+ var THEO_RESERVED_TARGET = [
209
+ "[[redirects]]",
210
+ ` from = "${THEO_RESERVED_FROM}"`,
211
+ ` to = "${THEO_REDIRECT_TO}"`,
212
+ " status = 200",
213
+ " force = true"
214
+ ].join("\n");
215
+ function withReservedRoutesRedirect(source) {
216
+ const lines = source.split(/\r?\n/);
217
+ const blocks = parseRedirectBlocks(lines);
218
+ if (blocks.some((b) => b.from === THEO_RESERVED_FROM)) return source;
219
+ const fallback = blocks.find((b) => b.from === THEO_SPA_FALLBACK_FROM);
220
+ if (fallback === void 0) {
221
+ const sep = source.endsWith("\n") ? "" : "\n";
222
+ return `${source}${sep}
223
+ ${THEO_RESERVED_TARGET}
224
+ `;
225
+ }
226
+ return [
227
+ ...lines.slice(0, fallback.startLine),
228
+ THEO_RESERVED_TARGET,
229
+ "",
230
+ ...lines.slice(fallback.startLine)
231
+ ].join("\n");
232
+ }
198
233
  function withSpaFallback(source) {
199
234
  const declared = parseRedirectBlocks(source.split(/\r?\n/)).some(
200
235
  (b) => b.from === THEO_SPA_FALLBACK_FROM
@@ -271,10 +306,12 @@ ${THEO_FUNCTIONS_TARGET}
271
306
  function mergeNetlifyToml(existing, securityHeaders) {
272
307
  const headersBlock = renderHeadersBlock(securityHeaders);
273
308
  if (existing === null || existing.trim().length === 0) {
274
- return withFunctionsDeclared(withSpaFallback(`${THEO_REDIRECT_TARGET}
309
+ return withFunctionsDeclared(
310
+ withSpaFallback(withReservedRoutesRedirect(`${THEO_REDIRECT_TARGET}
275
311
 
276
312
  ${headersBlock}
277
- `));
313
+ `))
314
+ );
278
315
  }
279
316
  existing = withoutGeneratedHeaders(existing);
280
317
  const blocks = parseRedirectBlocks(existing.split(/\r?\n/));
@@ -282,19 +319,23 @@ ${headersBlock}
282
319
  if (b.from !== THEO_REDIRECT_FROM) continue;
283
320
  if (b.to === THEO_REDIRECT_TO) {
284
321
  const sep2 = existing.endsWith("\n") ? "" : "\n";
285
- return withFunctionsDeclared(withSpaFallback(`${existing}${sep2}
322
+ return withFunctionsDeclared(
323
+ withSpaFallback(withReservedRoutesRedirect(`${existing}${sep2}
286
324
  ${headersBlock}
287
- `));
325
+ `))
326
+ );
288
327
  }
289
328
  throw new NetlifyConflictError(b.from, b.to ?? "(unknown)");
290
329
  }
291
330
  const sep = existing.endsWith("\n") ? "" : "\n";
292
331
  return withFunctionsDeclared(
293
- withSpaFallback(`${existing}${sep}
332
+ withSpaFallback(
333
+ withReservedRoutesRedirect(`${existing}${sep}
294
334
  ${THEO_REDIRECT_TARGET}
295
335
 
296
336
  ${headersBlock}
297
337
  `)
338
+ )
298
339
  );
299
340
  }
300
341
  function resolveNetlifyDeps(cwd, deps) {
@@ -341,6 +382,8 @@ async function buildNetlify(config, cwd, deps = {}, ctx) {
341
382
  csrf: config.security?.csrf,
342
383
  disallowed: config.security?.disallowed,
343
384
  cors: config.security?.cors,
385
+ // #1097 — a probe cannot ride as a literal; the entry fails `/__theo/ready` closed instead.
386
+ readyProbeDeclared: config.ready !== void 0,
344
387
  // #425 — a selector, not a transformer, so it rides as a literal like the values above.
345
388
  serialization: config.serialization
346
389
  }),
@@ -398,4 +441,4 @@ export {
398
441
  netlifyAdapter,
399
442
  renderNetlifyFunction
400
443
  };
401
- //# sourceMappingURL=netlify-ZPQNREFH.js.map
444
+ //# sourceMappingURL=netlify-GRVT3MTT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/adapters/netlify.ts"],"sourcesContent":["/* eslint-disable security/detect-non-literal-fs-filename --\n * Netlify deploy adapter. All paths derived from `cwd` and a fixed\n * `.theokit/netlify/` output layout. Build-time tool — no HTTP input.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport type { TheoConfig } from '../config/schema.js'\nimport type { SecurityHeadersConfig } from '../core/contracts/security-headers.js'\nimport { assertServicesUnsupported, readManifest } from '../services/index.js'\n\nimport {\n bundleDeployedFunction,\n type BundleDeployedFunctionOptions,\n} from './bundle-deployed-function.js'\nimport { deployedAgentsFragment, JSON_NOT_FOUND_RESPONSE } from './deployed-agents.js'\nimport { renderBakedRoutes, routeRuntimeLines, type BakedRoute } from './deployed-baked-routes.js'\nimport { type DeployedCorsOptions } from './deployed-cors.js'\nimport { type DeployedCsrfOptions } from './deployed-csrf.js'\nimport { deployedEntryPreamble } from './deployed-preamble.js'\nimport { deployedRateLimitFragment, rateLimitCheckFragment } from './deployed-rate-limit.js'\nimport type { DeployedRateLimitOptions } from './deployed-rate-limit.js'\nimport { deployedReservedRoutesFragment, reservedRouteBranch } from './deployed-reserved-routes.js'\nimport type { DeployedReservedRoutesOptions } from './deployed-reserved-routes.js'\nimport {\n deployedRuntimeConfigFragment,\n type DeployedRuntimeConfigOptions,\n serverDirLiteral,\n type DeployedServerDirOptions,\n} from './deployed-runtime-config.js'\nimport { deployedTraceFragment } from './deployed-trace.js'\nimport { nodeAdapter } from './node.js'\nimport { buildSecurityHeaders, describeDeployedSecurityHeaders } from './security-headers.js'\nimport type { AdapterBuildContext, DeployAdapter } from './types.js'\n\nexport class NetlifyConflictError extends Error {\n constructor(path: string, currentTo: string) {\n super(\n `netlify.toml has a conflicting redirect: \"${path}\" → \"${currentTo}\". ` +\n `Remove it manually or edit it to point to \"/.netlify/functions/theo\" ` +\n `before running the Netlify adapter again.`,\n )\n this.name = 'NetlifyConflictError'\n }\n}\n\nexport class NetlifyFunctionsConflictError extends Error {\n constructor(key: string, declared: string, required: string) {\n super(\n `netlify.toml declares \\`[functions] ${key} = \"${declared}\"\\`, and this adapter needs ` +\n `\"${required}\". Measured on the Netlify emulator: \\`directory\\` is what makes the generated ` +\n `function discoverable at all (without it the redirect answers \"Function not found\"), and ` +\n `\\`node_bundler = \"none\"\\` is what stops Netlify re-bundling a function theokit already ` +\n `bundled — which produces a SyntaxError. Change the value, or remove the key and let this ` +\n `adapter write it.`,\n )\n this.name = 'NetlifyFunctionsConflictError'\n }\n}\n\nexport interface NetlifyBuildDeps {\n runNodeBuild?: (config: TheoConfig, cwd: string, ctx?: AdapterBuildContext) => Promise<void>\n writeFile?: (path: string, content: string) => void\n ensureDir?: (path: string) => void\n readTomlIfExists?: () => string | null\n /**\n * Seam for the bundling step, alongside `runNodeBuild` above.\n *\n * The entry cannot be written as source: it imports `theokit/server/scan` and five sibling\n * sub-paths by bare specifier, and Netlify's own bundler breaks on the result (measured on the\n * emulator — see `the-netlify-function-ships-pre-bundled.test.ts`). Bundling here rather than\n * through `writeFile` is what lets the toml then say `node_bundler = \"none\"`.\n */\n bundleFunction?: (options: BundleDeployedFunctionOptions) => Promise<void>\n}\n\nexport function renderNetlifyFunction(\n opts: { securityHeaders?: SecurityHeadersConfig } & DeployedCsrfOptions &\n DeployedRuntimeConfigOptions &\n DeployedCorsOptions &\n DeployedRateLimitOptions &\n DeployedReservedRoutesOptions &\n DeployedServerDirOptions & {\n routes?: readonly BakedRoute[]\n /**\n * The agents, baked at build time — for the same reason the routes are (B-339).\n *\n * Netlify uploads a BUNDLE now, so the runtime scan cannot work here at any value: there is no\n * source tree to read, and `createProductionLoader()` would `import()` a path that was never\n * shipped. Vercel's own comment on this says it best — a fallback \"would preserve a behaviour\n * that is broken by construction: an entry that scans, finds nothing, and answers 404 while\n * looking like it tried.\"\n */\n agents?: readonly { filePath: string; agentPath: string; name: string }[]\n contextModule?: string\n } = {},\n): string {\n // B-338 — the routes are baked, not scanned. The scan was a `readdirSync` over the server directory,\n // and on the Netlify emulator it FOUND `src/server/routes/health.ts` and answered 500\n // `SyntaxError: Unexpected token ')'` — a TypeScript source a plain JS runtime cannot compile. On a real\n // deploy it finds nothing at all, because Netlify uploads the bundled function. The fix B-319 made for\n // Vercel and #369 for Cloudflare, on the fourth target; the emitter is shared and its own docblock says\n // \"the target only supplies what its own error message says\".\n const { routeImports, routeModuleEntries, routeTableEntries } = renderBakedRoutes(\n opts.routes ?? [],\n )\n const runtimeConfig = deployedRuntimeConfigFragment(opts)\n // B-235. Netlify's handler is `(request, context)` and already RECEIVES a Web `Request`, which\n // is the shape this branch needs — the item filed against it counted `new Request` occurrences\n // and concluded the opposite, measuring how the entry OBTAINS a request rather than whether it\n // has one. It used to take `scannedFromLoaderCache` with Deno as the model — same `loaderCache`,\n // same filesystem `serverDir`. That stopped being right when this target began bundling: the\n // emitted `if (!loaderCache) loaderCache = createProductionLoader()` referenced two names the\n // host no longer declared, which is a ReferenceError on the first /api/agents/<name> request and\n // is what `a-generated-entry-declares-every-identifier.test.ts` was written to catch.\n const agentsFragment = deployedAgentsFragment(\n { kind: 'baked', agents: opts.agents ?? [], contextModule: opts.contextModule },\n {\n // Netlify answers its own 404 inline rather than through a helper, so the fragment is given\n // the expression instead of a call it would have to declare.\n notFound: `new Response('Not Found', { status: 404 })`,\n },\n )\n return [\n `// Generated by Theo — Netlify Functions adapter`,\n `import { resolve } from 'node:path'`,\n `import { matchRoute, compilePattern } from 'theokit/server/scan'\\nimport { executeRoute, extractTraceIdFromRequest, TRACE_HEADER, createCorsWebHandler } from 'theokit/server/http'`,\n ...routeImports,\n `import { createWebShim } from 'theokit/adapters/web-shim'`,\n `import { buildSecurityHeaders, withSecurityHeaders } from 'theokit/adapters/security-headers'`,\n ``,\n `const cwd = process.cwd()`,\n // B-338 — was `resolve(cwd, 'server')`, a literal. A project declaring `src/server` got a function\n // scanning a directory that does not exist, and every `/api/*` answered 404 — measured on the Netlify\n // emulator. The FOURTH target with this shape: B-185 (bun, deno), B-235 (agentsDir here), B-315\n // (vercel, aws-lambda, cloudflare), and this file's own call site already names two of them.\n `const serverDir = resolve(cwd, ${serverDirLiteral(opts)})`,\n ...routeRuntimeLines(routeModuleEntries, routeTableEntries, 'netlify'),\n ``,\n `// #410 — the security baseline \\`theokit start\\` puts on every response,`,\n `// carried here as a literal because the deployed function has no`,\n `// theo.config.ts to read. The netlify.toml redirect routes only /api/* here,`,\n `// so this covers the API and not the document Netlify's static host serves`,\n `// (usetheokit/theokit#412).`,\n ...deployedEntryPreamble(\n runtimeConfig,\n agentsFragment,\n opts,\n 'netlify',\n deployedReservedRoutesFragment(opts),\n ),\n ``,\n // B-027 — emitted only when a limit is declared.\n ...(opts.rateLimit === undefined\n ? []\n : [\n // B-338 — the sub-path, not the umbrella. The umbrella re-exports the whole server half and\n // @swc/core's native .node addon is down that graph; the guard against it could not see this\n // adapter, because the shared comment stripper read this file's \"/*\" redirect glob as a\n // comment opener and deleted 36% of it before the sweep looked.\n `import { createRateLimiterWeb } from 'theokit/server/rate-limit'`,\n `import { resolveClientIpFromRequest } from 'theokit/server/rate-limit'`,\n ``,\n ]),\n ...deployedRateLimitFragment(\n opts.rateLimit,\n 'netlify',\n // `context.ip` is the platform's own answer, read from the handler context Netlify passes.\n // The forwarded fallback covers a function shape that carries no context, and returns\n // `undefined` unless a `trustProxy` was declared — which is the named 503, not a shared key.\n `context?.ip ?? resolveClientIpFromRequest(request, TRUST_PROXY)`,\n // Both names are bound in the OUTER handler, which is where the check runs. Threading\n // `context` into `handleRequest` — which the plan called for — buys nothing: the limiter\n // never runs in there.\n 'request, context',\n ),\n ``,\n `export default async (request, context) => {`,\n ` // #409 — the preflight is answered BEFORE anything routes: an OPTIONS the router`,\n ` // handles is an OPTIONS the browser never gets a CORS answer to.`,\n ` const preflight = corsPreflight(request)`,\n ` if (preflight !== null) return withSecurityHeaders(preflight, SECURITY_HEADERS)`,\n ...rateLimitCheckFragment(opts.rateLimit, ' ', 'request, context'),\n ` return withCors(request, withSecurityHeaders(await handleRequest(request), SECURITY_HEADERS))`,\n `}`,\n ``,\n `async function handleRequest(request) {`,\n ` const url = new URL(request.url)`,\n ...reservedRouteBranch('url.pathname', ' '),\n ` if (!url.pathname.startsWith('/api/')${agentsFragment.hostBypass}) {`,\n ` return new Response('Not Found', { status: 404 })`,\n ` }`,\n ``,\n\n ``,\n ...agentsFragment.branch,\n ``,\n ` const match = matchRoute(url.pathname, routes)`,\n ` if (!match) return ${JSON_NOT_FOUND_RESPONSE}`,\n ``,\n ` const { req, res, toResponse } = createWebShim(request)`,\n ...deployedTraceFragment('request', ' '),\n ` const method = request.method.toUpperCase()`,\n ` // #382 — the run is not awaited: toResponse() settles at the headers and`,\n ` // carries a live body, so Netlify streams while the handler writes.`,\n ` return toResponse(executeRoute({ route: match.route, method, params: match.params, req, res, loadModule, serverDir, requestId, ...CSRF_CONFIG, ${runtimeConfig.executeRouteSpread} }))`,\n `}`,\n ].join('\\n')\n}\n\nconst THEO_REDIRECT_FROM = '/api/*'\nconst THEO_REDIRECT_TO = '/.netlify/functions/theo'\n\n/**\n * TOML merge (EC-2) — non-destructive.\n *\n * We avoid adding a TOML parser dependency by working at the line level. The\n * supported subset is sufficient for the Netlify use case:\n * - detect existing `[[redirects]]` blocks\n * - find a block whose `from = \"...\"` matches our target\n * - error if such a block points elsewhere\n * - otherwise append our block\n *\n * Unknown sections (e.g. `[build]`, `[[headers]]`, `[context.production.environment]`)\n * are preserved as-is.\n */\ninterface NetlifyRedirectBlock {\n startLine: number\n endLine: number\n from?: string\n to?: string\n}\n\nfunction parseRedirectBlocks(lines: readonly string[]): NetlifyRedirectBlock[] {\n const blocks: NetlifyRedirectBlock[] = []\n let current: NetlifyRedirectBlock | null = null\n\n for (let i = 0; i < lines.length; i++) {\n const trimmed = lines[i].trim()\n if (trimmed === '[[redirects]]') {\n if (current) {\n current.endLine = i - 1\n blocks.push(current)\n }\n current = { startLine: i, endLine: i }\n continue\n }\n if (current && /^\\[(\\[|[^[])/.test(trimmed)) {\n // Entering another section — close current.\n current.endLine = i - 1\n blocks.push(current)\n current = null\n }\n if (current) {\n const fromMatch = /^from\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (fromMatch) current.from = fromMatch[1]\n const toMatch = /^to\\s*=\\s*\"([^\"]+)\"/.exec(trimmed)\n if (toMatch) current.to = toMatch[1]\n current.endLine = i\n }\n }\n if (current) blocks.push(current)\n return blocks\n}\n\n/**\n * The `[functions]` keys this adapter requires, and why each one is not optional.\n *\n * `directory` — measured on the Netlify emulator 2026-09-29: without it the CLI scans its default\n * `netlify/functions/`, finds nothing, and `/api/*` answers `Function not found...` with a 404. The\n * adapter writes to `.netlify/functions/` deliberately (generated output belongs in an ignored\n * directory, not in the source tree the project commits), so the location has to be declared.\n *\n * `node_bundler` — the entry is already bundled here. Netlify re-bundling it produced\n * `SyntaxError: Invalid left-hand side in assignment`.\n */\nconst THEO_FUNCTIONS_DIR = '.netlify/functions'\nconst THEO_FUNCTION_NAME = 'theo'\nconst THEO_FUNCTIONS_KEYS: readonly (readonly [string, string])[] = [\n ['directory', THEO_FUNCTIONS_DIR],\n ['node_bundler', 'none'],\n]\nconst THEO_FUNCTIONS_TARGET = [\n '[functions]',\n ...THEO_FUNCTIONS_KEYS.map(([key, value]) => ` ${key} = \"${value}\"`),\n].join('\\n')\n\nconst THEO_REDIRECT_TARGET = [\n '[[redirects]]',\n ' from = \"/api/*\"',\n ' to = \"/.netlify/functions/theo\"',\n ' status = 200',\n ' force = true',\n].join('\\n')\n\n/**\n * The client router's fallback: a path that no file and no earlier rule answers gets the document.\n *\n * #949 — measured 2026-10-03 on Netlify production: `GET /about` answered 404 while the same build\n * answered 200 on Vercel and Cloudflare (whose `wrangler.toml` carries `not_found_handling =\n * \"single-page-application\"` for this). Unforced, so a real file such as `/assets/*.js` still wins,\n * and appended after `/api/*` because Netlify applies the first rule that matches.\n */\nconst THEO_SPA_FALLBACK_FROM = '/*'\nconst THEO_SPA_FALLBACK_TARGET = [\n '[[redirects]]',\n ' from = \"/*\"',\n ' to = \"/index.html\"',\n ' status = 200',\n].join('\\n')\n\n/**\n * #1097 — the reserved routes the function answers. No file matches them, so without this rule\n * they reached the SPA fallback and were answered with the document.\n */\nconst THEO_RESERVED_FROM = '/__theo/*'\nconst THEO_RESERVED_TARGET = [\n '[[redirects]]',\n ` from = \"${THEO_RESERVED_FROM}\"`,\n ` to = \"${THEO_REDIRECT_TO}\"`,\n ' status = 200',\n ' force = true',\n].join('\\n')\n\n/**\n * Add the reserved-routes rule unless one exists, AHEAD of any `/*` rule: Netlify applies the\n * first rule that matches, so a rule appended after a project's own fallback would never fire.\n */\nfunction withReservedRoutesRedirect(source: string): string {\n const lines = source.split(/\\r?\\n/)\n const blocks = parseRedirectBlocks(lines)\n if (blocks.some((b) => b.from === THEO_RESERVED_FROM)) return source\n const fallback = blocks.find((b) => b.from === THEO_SPA_FALLBACK_FROM)\n if (fallback === undefined) {\n const sep = source.endsWith('\\n') ? '' : '\\n'\n return `${source}${sep}\\n${THEO_RESERVED_TARGET}\\n`\n }\n return [\n ...lines.slice(0, fallback.startLine),\n THEO_RESERVED_TARGET,\n '',\n ...lines.slice(fallback.startLine),\n ].join('\\n')\n}\n\n/** Append the fallback unless some `/*` rule exists — the project's own wins. */\nfunction withSpaFallback(source: string): string {\n const declared = parseRedirectBlocks(source.split(/\\r?\\n/)).some(\n (b) => b.from === THEO_SPA_FALLBACK_FROM,\n )\n if (declared) return source\n const sep = source.endsWith('\\n') ? '' : '\\n'\n return `${source}${sep}\\n${THEO_SPA_FALLBACK_TARGET}\\n`\n}\n\n/**\n * Marks the block this build owns, so it can be REGENERATED rather than merely not duplicated.\n *\n * Idempotence alone would be the wrong contract here: the block carries configuration, so a\n * `security.headers` change has to reach the file. Leaving an existing block in place — which is\n * what the redirect above correctly does, because its content is fixed — would silently pin the\n * baseline to whatever the first build emitted.\n */\nconst THEO_HEADERS_MARKER = '# Generated by Theo — security baseline (usetheokit/theokit#412)'\n\n/**\n * The `[[headers]]` block telling Netlify's static host the baseline.\n *\n * The emitted function applies these to every response IT returns, and it never returns the HTML\n * document: the `[[redirects]]` block routes only `/api/*`, so the page comes from Netlify's static\n * host and carried none of them. The values come from `buildSecurityHeaders` — the same function\n * the handler calls — rather than being written out here, because two lists of headers that must\n * agree are two lists that eventually do not.\n */\nfunction renderHeadersBlock(securityHeaders: SecurityHeadersConfig | undefined): string {\n const values = buildSecurityHeaders(securityHeaders ?? {}, { production: true })\n return [\n THEO_HEADERS_MARKER,\n '[[headers]]',\n ' for = \"/*\"',\n ' [headers.values]',\n ...Object.entries(values).map(([k, v]) => ` ${k} = ${JSON.stringify(v)}`),\n ].join('\\n')\n}\n\n/**\n * Drop a previously generated block, so the next one replaces it.\n *\n * Bounded by the marker and the next top-level section at column 0 (or EOF) — the shape TOML gives\n * a block. A user's own `[[headers]]` is untouched because it does not carry the marker: their\n * file, their rules, and Netlify applies both.\n */\nfunction withoutGeneratedHeaders(source: string): string {\n const lines = source.split(/\\r?\\n/)\n const start = lines.indexOf(THEO_HEADERS_MARKER)\n if (start < 0) return source\n\n const opensSection = (line: string | undefined): boolean => (line ?? '').startsWith('[')\n\n let end = start + 1\n while (end < lines.length && !opensSection(lines[end])) end += 1\n // The marker line itself opens the block, so `end` now sits on the NEXT section — but the block's\n // own `[[headers]]` is the first `[` after the marker, so step past it before scanning again.\n end += 1\n while (end < lines.length && !opensSection(lines[end])) end += 1\n\n return [...lines.slice(0, start), ...lines.slice(end)].join('\\n').replace(/\\n{3,}/gu, '\\n\\n')\n}\n\n/**\n * Declare the `[functions]` keys this adapter requires, without emitting a second table.\n *\n * A duplicate table is a TOML parse error, so this is not tidiness: a project that already declares\n * `[functions]` for `directory`, `included_files` or `external_node_modules` must keep it and gain\n * one key. Line-level like the rest of this merge, and for the same reason — no TOML parser\n * dependency. `[functions.\"name\"]` is a DIFFERENT table and is left alone, which is why the match\n * is exact rather than a prefix.\n *\n * An explicit conflicting value is refused rather than overwritten, on the same argument\n * `NetlifyConflictError` makes about a `/api/*` redirect pointing elsewhere: it is a deliberate\n * declaration, and silently replacing it breaks their build for a reason nothing states.\n */\n/**\n * Read a TOML scalar exactly as written, with no parser.\n *\n * Neither \"strip the quotes\" nor \"cut at the first #\" is correct alone: TOML allows an inline\n * comment after a value, and a `#` INSIDE a quoted value is legal. Stripping quotes alone read\n * `node_bundler = \"none\" # keep` as `none\" # keep` and refused a legal file; cutting at `#` alone\n * would mangle `directory = \"a#b\"`. Both cases are asserted, in both directions, in\n * `the-netlify-function-ships-pre-bundled.test.ts`.\n */\nfunction readTomlScalar(raw: string): string {\n for (const quote of ['\"', \"'\"]) {\n if (!raw.startsWith(quote)) continue\n const close = raw.indexOf(quote, 1)\n return close < 0 ? raw.slice(1) : raw.slice(1, close)\n }\n const hash = raw.indexOf('#')\n return (hash < 0 ? raw : raw.slice(0, hash)).trim()\n}\n\n/**\n * The value a key carries inside one table's line range, or `null` when the table does not set it.\n *\n * Split rather than matched: the rest of this merge is line-level by design, and a regex with `\\s*`\n * either side of a lazy group backtracks (sonarjs/slow-regex) for no gain here. A commented-out\n * `# node_bundler = …` reads as the key `# node_bundler`, which matches nothing — correct, and free.\n */\nfunction declaredIn(\n lines: readonly string[],\n from: number,\n to: number,\n key: string,\n): string | null {\n for (let i = from; i < to; i += 1) {\n const line = lines[i] ?? ''\n const eq = line.indexOf('=')\n if (eq < 0 || line.slice(0, eq).trim() !== key) continue\n return readTomlScalar(line.slice(eq + 1).trim())\n }\n return null\n}\n\nfunction withFunctionsDeclared(source: string): string {\n const lines = source.split(/\\r?\\n/)\n const at = lines.findIndex((line) => line.trimEnd() === '[functions]')\n\n if (at < 0) {\n const sep = source.endsWith('\\n') ? '' : '\\n'\n return `${source}${sep}\\n${THEO_FUNCTIONS_TARGET}\\n`\n }\n\n let end = at + 1\n while (end < lines.length && !(lines[end] ?? '').startsWith('[')) end += 1\n\n const missing: string[] = []\n for (const [key, required] of THEO_FUNCTIONS_KEYS) {\n const declared = declaredIn(lines, at + 1, end, key)\n if (declared === null) {\n missing.push(` ${key} = \"${required}\"`)\n continue\n }\n if (declared !== required) throw new NetlifyFunctionsConflictError(key, declared, required)\n }\n\n if (missing.length === 0) return source\n return [...lines.slice(0, at + 1), ...missing, ...lines.slice(at + 1)].join('\\n')\n}\n\nexport function mergeNetlifyToml(\n existing: string | null,\n securityHeaders?: SecurityHeadersConfig,\n): string {\n const headersBlock = renderHeadersBlock(securityHeaders)\n\n if (existing === null || existing.trim().length === 0) {\n return withFunctionsDeclared(\n withSpaFallback(withReservedRoutesRedirect(`${THEO_REDIRECT_TARGET}\\n\\n${headersBlock}\\n`)),\n )\n }\n\n existing = withoutGeneratedHeaders(existing)\n\n const blocks = parseRedirectBlocks(existing.split(/\\r?\\n/))\n\n // Detect conflict: every `/api/*` block must point at our function.\n for (const b of blocks) {\n if (b.from !== THEO_REDIRECT_FROM) continue\n if (b.to === THEO_REDIRECT_TO) {\n // The redirect is already there. The headers block is regenerated regardless, because it\n // carries configuration and the redirect does not.\n const sep = existing.endsWith('\\n') ? '' : '\\n'\n return withFunctionsDeclared(\n withSpaFallback(withReservedRoutesRedirect(`${existing}${sep}\\n${headersBlock}\\n`)),\n )\n }\n throw new NetlifyConflictError(b.from, b.to ?? '(unknown)')\n }\n\n // No conflict — append target block.\n const sep = existing.endsWith('\\n') ? '' : '\\n'\n return withFunctionsDeclared(\n withSpaFallback(\n withReservedRoutesRedirect(`${existing}${sep}\\n${THEO_REDIRECT_TARGET}\\n\\n${headersBlock}\\n`),\n ),\n )\n}\n\n/**\n * Resolve the build's effective dependencies once.\n *\n * Extracted when `buildNetlify` crossed the complexity ceiling after B-339 added a fifth seam. The\n * defaults are a separate concern from the build's sequence (SRP), and the sequence is the part a\n * reader comes here to follow.\n */\nfunction resolveNetlifyDeps(\n cwd: string,\n deps: NetlifyBuildDeps,\n): {\n runNodeBuild: NonNullable<NetlifyBuildDeps['runNodeBuild']>\n writeFile: NonNullable<NetlifyBuildDeps['writeFile']>\n ensureDir: NonNullable<NetlifyBuildDeps['ensureDir']>\n readTomlIfExists: NonNullable<NetlifyBuildDeps['readTomlIfExists']>\n bundleFunction: NonNullable<NetlifyBuildDeps['bundleFunction']>\n} {\n return {\n runNodeBuild: deps.runNodeBuild ?? nodeAdapter.build.bind(nodeAdapter),\n writeFile:\n deps.writeFile ??\n ((path, content) => {\n writeFileSync(path, content)\n }),\n ensureDir: deps.ensureDir ?? ((path: string) => mkdirSync(path, { recursive: true })),\n readTomlIfExists:\n deps.readTomlIfExists ??\n (() => {\n const path = resolve(cwd, 'netlify.toml')\n return existsSync(path) ? readFileSync(path, 'utf-8') : null\n }),\n bundleFunction: deps.bundleFunction ?? bundleDeployedFunction,\n }\n}\n\nexport async function buildNetlify(\n config: TheoConfig,\n cwd: string,\n deps: NetlifyBuildDeps = {},\n ctx?: AdapterBuildContext,\n): Promise<void> {\n // Wave 2 (T2.2) — reject polyglot services on this adapter.\n assertServicesUnsupported('netlify', readManifest(cwd))\n\n const { runNodeBuild, writeFile, ensureDir, readTomlIfExists, bundleFunction } =\n resolveNetlifyDeps(cwd, deps)\n\n const merged = mergeNetlifyToml(readTomlIfExists(), config.security?.headers)\n\n await runNodeBuild(config, cwd, ctx)\n\n const scanned = ctx?.scanRoutes?.(config.serverDir)\n\n const fnDir = resolve(cwd, THEO_FUNCTIONS_DIR)\n ensureDir(fnDir)\n // B-339 — bundled, not written as source. The entry imports `theokit/server/scan` and five\n // sibling sub-paths by bare specifier; Netlify's own bundler produced a `ReferenceError` on\n // an identifier that was base64 of the source, and re-bundled an already-bundled file into a\n // `SyntaxError`. Measured on the emulator: bundled here plus `node_bundler = \"none\"` below,\n // `GET /api/health` answers 200. Cloudflare and Vercel already bundle; this was the target\n // shipping raw source and trusting the platform to resolve it.\n await bundleFunction({\n projectRoot: cwd,\n entrySource: renderNetlifyFunction({\n routes: scanned?.routes,\n // B-339 — from the same scan as the routes, for the same reason: this target bundles, so a\n // runtime agents scan has no source tree to read.\n agents: scanned?.agents,\n contextModule: scanned?.contextModule,\n securityHeaders: config.security?.headers,\n // B-235 wired `agentsDir` through to this renderer, and B-339 made it unreadable here: the\n // agents are baked from the BUILD's scan now, so the entry never resolves a directory. An\n // option a renderer accepts and ignores is the defect `rules/foreign-config-surfaces.md` is\n // about, so it is dropped rather than left looking wired. The scan the build performs still\n // honours `config.agentsDir` — that is where the option belongs.\n // B-338 — the same pillar as the comment above, one option over. The sweep in\n // `every-deployed-entry-is-told-its-server-dir.test.ts` could not see this adapter: its\n // population was the adapters that CALL `serverDirLiteral(opts)`, so the one that never\n // adopted it was outside the population the case iterates.\n serverDir: config.serverDir,\n csrf: config.security?.csrf,\n disallowed: config.security?.disallowed,\n cors: config.security?.cors,\n // #1097 — a probe cannot ride as a literal; the entry fails `/__theo/ready` closed instead.\n readyProbeDeclared: config.ready !== undefined,\n // #425 — a selector, not a transformer, so it rides as a literal like the values above.\n serialization: config.serialization,\n }),\n stagePath: '.theokit/netlify/entry.mjs',\n // A DIRECTORY, not a bare file. The bundler code-splits: this project emitted `theo.mjs` plus\n // 40 chunks under `assets/`, which `theo.mjs` imports. Netlify zips a directory-shaped function\n // whole, so the chunks travel; a bare `theo.mjs` with a sibling `assets/` loads in `netlify dev`\n // (it reads from disk) and would reach a deploy without them. Vercel already uses a dedicated\n // `functions/api.func` for the same reason.\n outDir: resolve(fnDir, THEO_FUNCTION_NAME),\n entryFileName: `${THEO_FUNCTION_NAME}.mjs`,\n })\n\n writeFile(resolve(cwd, 'netlify.toml'), merged)\n\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(`\\n ✓ Netlify output → ${THEO_FUNCTIONS_DIR}/${THEO_FUNCTION_NAME}/ + netlify.toml`)\n // eslint-disable-next-line no-console -- CLI build progress\n console.log(\n `${describeDeployedSecurityHeaders({\n target: 'netlify',\n securityHeaders: config.security?.headers,\n mintsNonce: false,\n documentHeaders: 'platform-configured',\n })}\\n`,\n )\n}\n\nexport const netlifyAdapter: DeployAdapter = {\n // B-339 / B-341 / B-343 — measured on the Netlify emulator. Its own bundler turned the raw\n // source into a `ReferenceError`, and re-bundled an already-bundled file into a `SyntaxError`;\n // the toml declares `node_bundler = \"none\"` so the bundle this adapter produces ships intact.\n readsSourceAtRunTime: false,\n specifiersResolvedBy: 'this-adapter',\n name: 'netlify',\n streamsResponses: true,\n // #409 / #410 — the generated entry calls `executeRoute` with routes, loader\n // and serverDir only. CSRF, route policy, file middleware and Zod validation\n // still run because they live inside `executeRoute`; none of the remaining\n // configurable concerns reach it. Declared explicitly rather than omitted so\n // the gap is a statement in the source and not an absence.\n //\n // `securityHeaders` IS applied -- to every response this function returns.\n // The document is served by Netlify's static host and does not pass through\n // it (usetheokit/theokit#412).\n appliesConfig: ['securityHeaders', 'csrf', 'disallowed', 'cors', 'serialization'],\n // B-257 — per-invocation: an in-process counter does not survive, so a declared limit needs a durable store.\n enforcesRateLimit: 'with-a-store',\n build(config, cwd, ctx) {\n return buildNetlify(config, cwd, {}, ctx)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AA8BjB,IAAM,uBAAN,cAA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AAAA,IACzC,eAAe,GAAG,kBAAkB;AAAA,EACtC,CAAC;AAED,YAAU,QAAQ,KAAK,cAAc,GAAG,MAAM;AAG9C,UAAQ,IAAI;AAAA,iCAA0B,kBAAkB,IAAI,kBAAkB,kBAAkB;AAEhG,UAAQ;AAAA,IACN,GAAG,gCAAgC;AAAA,MACjC,QAAQ;AAAA,MACR,iBAAiB,OAAO,UAAU;AAAA,MAClC,YAAY;AAAA,MACZ,iBAAiB;AAAA,IACnB,CAAC,CAAC;AAAA;AAAA,EACJ;AACF;AAEO,IAAM,iBAAgC;AAAA;AAAA;AAAA;AAAA,EAI3C,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,EACtB,MAAM;AAAA,EACN,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUlB,eAAe,CAAC,mBAAmB,QAAQ,cAAc,QAAQ,eAAe;AAAA;AAAA,EAEhF,mBAAmB;AAAA,EACnB,MAAM,QAAQ,KAAK,KAAK;AACtB,WAAO,aAAa,QAAQ,KAAK,CAAC,GAAG,GAAG;AAAA,EAC1C;AACF;","names":["sep"]}
@@ -2,9 +2,9 @@
2
2
  import "tsx/esm";
3
3
  import {
4
4
  nodeAdapter
5
- } from "./chunk-G3DDIEYE.js";
5
+ } from "./chunk-MQCXYZEV.js";
6
6
  import "./chunk-L4V5V2TI.js";
7
7
  export {
8
8
  nodeAdapter
9
9
  };
10
- //# sourceMappingURL=node-3EV3CVWB.js.map
10
+ //# sourceMappingURL=node-UYRQNJNF.js.map
@@ -12,7 +12,7 @@ import "./chunk-4WP7A7RX.js";
12
12
  import "./chunk-Z7CJHDLS.js";
13
13
  import {
14
14
  loadConfig
15
- } from "./chunk-35OI2TKT.js";
15
+ } from "./chunk-5UJRZC4J.js";
16
16
  import "./chunk-3QPVEJ7D.js";
17
17
  import "./chunk-O5JZ6ROY.js";
18
18
  import "./chunk-PQWVT6JC.js";
@@ -84,4 +84,4 @@ function emitOpenApiInMemory(manifest, config) {
84
84
  export {
85
85
  openapiCommand
86
86
  };
87
- //# sourceMappingURL=openapi-OVXYHZ2S.js.map
87
+ //# sourceMappingURL=openapi-ICJB2RBE.js.map
@@ -4,8 +4,8 @@ import "tsx/esm";
4
4
  // src/cli/commands/preview.ts
5
5
  async function defaultSteps() {
6
6
  const [{ buildCommand }, { startCommand }] = await Promise.all([
7
- import("./build-Y457R5HE.js"),
8
- import("./start-EJFYT7ZU.js")
7
+ import("./build-2VOQOWZE.js"),
8
+ import("./start-AE5YCDVS.js")
9
9
  ]);
10
10
  return {
11
11
  build: (opts) => buildCommand(opts),
@@ -20,4 +20,4 @@ async function previewCommand(options = {}, steps) {
20
20
  export {
21
21
  previewCommand
22
22
  };
23
- //# sourceMappingURL=preview-Y3JNYOFK.js.map
23
+ //# sourceMappingURL=preview-XQJZ75QE.js.map
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ import "tsx/esm";
3
+ import {
4
+ VALID_TARGETS
5
+ } from "./chunk-PV6IO25S.js";
6
+
7
+ // src/adapters/registry.ts
8
+ var adapterRegistry = {
9
+ node: async () => (await import("./node-UYRQNJNF.js")).nodeAdapter,
10
+ vercel: async () => (await import("./vercel-MRZXLOIQ.js")).vercelAdapter,
11
+ cloudflare: async () => (await import("./cloudflare-6ONK5HCO.js")).cloudflareAdapter,
12
+ static: async () => (await import("./static-C7PWUTQO.js")).staticAdapter,
13
+ bun: async () => (await import("./bun-73JZLCKU.js")).bunAdapter,
14
+ "deno-deploy": async () => (await import("./deno-deploy-ZM2UR5ZI.js")).denoDeployAdapter,
15
+ netlify: async () => (await import("./netlify-GRVT3MTT.js")).netlifyAdapter,
16
+ "aws-lambda": async () => (await import("./aws-lambda-JXUPC5QM.js")).awsLambdaAdapter,
17
+ "theo-cloud": async () => (await import("./theo-cloud-NKZUJO3H.js")).theoCloudAdapter
18
+ };
19
+ async function resolveAdapter(target) {
20
+ const factory = adapterRegistry[target];
21
+ return factory();
22
+ }
23
+ async function streamingTargets() {
24
+ const out = [];
25
+ for (const target of VALID_TARGETS) {
26
+ if ((await resolveAdapter(target)).streamsResponses === true) out.push(target);
27
+ }
28
+ return out;
29
+ }
30
+ export {
31
+ resolveAdapter,
32
+ streamingTargets
33
+ };
34
+ //# sourceMappingURL=registry-JHWY7JRY.js.map
@@ -11,7 +11,7 @@ import {
11
11
  import "./chunk-Z7CJHDLS.js";
12
12
  import {
13
13
  loadConfig
14
- } from "./chunk-35OI2TKT.js";
14
+ } from "./chunk-5UJRZC4J.js";
15
15
  import "./chunk-3QPVEJ7D.js";
16
16
  import "./chunk-O5JZ6ROY.js";
17
17
  import "./chunk-PQWVT6JC.js";
@@ -64,4 +64,4 @@ async function routesCommand() {
64
64
  export {
65
65
  routesCommand
66
66
  };
67
- //# sourceMappingURL=routes-UNJ77IQU.js.map
67
+ //# sourceMappingURL=routes-XYXXR72Z.js.map
@@ -20,7 +20,12 @@ export { H as HEALTH_PATH, a as HealthRouteConfig, b as READY_PATH, c as ReadyRo
20
20
  * against the `input` schema via `formDataToObject` (Astro pattern).
21
21
  */
22
22
  type ActionAccept = 'form' | 'json';
23
- interface ActionConfig<TInput extends z.ZodType, TCtx = unknown> {
23
+ /**
24
+ * `TCtx` defaults to {@link RouteContext}, the augmentable interface route handlers use: the
25
+ * action executor builds `ctx` the same way (middleware, plugin decorations, `ctx.queue` when
26
+ * `jobs.backend` is set), so one declaration types both (usetheokit/theokit#1096).
27
+ */
28
+ interface ActionConfig<TInput extends z.ZodType, TCtx = RouteContext> {
24
29
  /**
25
30
  * Zod input schema. Required: every action declares its input contract via
26
31
  * Zod (architecture rule: zod-is-SSOT). The shape becomes the handler's
@@ -147,7 +152,7 @@ type UnsetMarker$1 = 'theokit.unset' & {
147
152
  * The fluent action builder. `TInput` tracks the Zod schema (drives `ctx.input` inference);
148
153
  * `THandlerSet` gates `.build()`.
149
154
  */
150
- interface ActionBuilder<TInput extends z.ZodType | UnsetMarker$1 = UnsetMarker$1, TCtx = unknown, THandlerSet extends boolean = false> {
155
+ interface ActionBuilder<TInput extends z.ZodType | UnsetMarker$1 = UnsetMarker$1, TCtx = RouteContext, THandlerSet extends boolean = false> {
151
156
  /** Set the Zod input schema. Required — every action declares its input contract (zod-is-SSOT). */
152
157
  input<S extends z.ZodType>(schema: S): ActionBuilder<S, TCtx, THandlerSet>;
153
158
  /** Wire-protocol accept mode (`'json'` default, `'form'` for FormData multipart). */
@@ -8,7 +8,7 @@ import {
8
8
  tool,
9
9
  uiMessageStreamResponse,
10
10
  websocket
11
- } from "../../chunk-BFDEEJOK.js";
11
+ } from "../../chunk-GNQKV2NP.js";
12
12
  import {
13
13
  evaluateRoutePolicy,
14
14
  requireOwner,
@@ -1,4 +1,5 @@
1
- export { B as BATCH_PATH, a as BatchExecuteFn, b as BatchPathConflictError, c as BatchPayload, d as BatchRequestItem, e as BatchResponse, f as BatchResultItem, C as CookieOptions, h as CorsConfig, i as CorsHandler, j as CorsOrigin, k as CorsWebHandler, l as CustomErrorPages, E as ExecuteActionOptions, m as ExecuteRouteContext, F as FileTooLargeError, H as HandleBatchOptions, M as MAX_ERROR_HTML_BYTES, n as MiddlewareNextUnavailableError, o as MiddlewareResult, N as NotFoundError, q as ProcedureInputError, r as ProcedureOutputError, S as STRIPPED_HEADERS, v as SendErrorInput, w as SendErrorOptions, T as TRACE_HEADER, x as TRACE_PARENT_HEADER, y as TheoError, W as W3CTraceContext, _ as _resetMiddlewareCacheForTests, A as _resetUninvocableWarningsForTests, D as appendCookieToHeaders, G as appendDeleteCookieToHeaders, I as callProcedure, J as createCorsHandler, K as createCorsWebHandler, L as createOpenApiHandler, Q as createServerContext, V as deleteCookie, X as envelopeCodeToStatus, Y as executeAction, Z as executeRoute, $ as executeWebRequest, a0 as extractTraceId, a1 as extractTraceIdFromRequest, a2 as extractW3CTraceContext, a3 as fromUnknown, a4 as getCookie, a5 as getCookieFromRequest, a6 as handleBatchRequest, a7 as handleRequestError, a8 as handleWebRequestError, a9 as injectModulePreloads, aa as jsonTransformer, ab as loadCustomErrorPages, ac as matchesOrigin, ad as parseCookieHeader, ae as parseRequestBody, af as parseTraceparent, ag as parseTraceparentContext, ah as resolveTransformer, ai as resolveUserModule, aj as runMiddlewareAndContext, ak as sendError, al as sendJson, am as serializeCookie, an as serveStaticFile, ao as serverErrorToEnvelope, ap as setCookie, aq as superjsonTransformer, ar as validateRouteInput } from '../../index-C2lcEI-4.js';
1
+ export { B as BATCH_PATH, a as BatchExecuteFn, b as BatchPathConflictError, c as BatchPayload, d as BatchRequestItem, e as BatchResponse, f as BatchResultItem, C as CookieOptions, h as CorsConfig, i as CorsHandler, j as CorsOrigin, k as CorsWebHandler, l as CustomErrorPages, E as ExecuteActionOptions, m as ExecuteRouteContext, F as FileTooLargeError, H as HandleBatchOptions, M as MAX_ERROR_HTML_BYTES, n as MiddlewareNextUnavailableError, o as MiddlewareResult, N as NotFoundError, q as ProcedureInputError, r as ProcedureOutputError, S as STRIPPED_HEADERS, v as SendErrorInput, w as SendErrorOptions, T as TRACE_HEADER, x as TRACE_PARENT_HEADER, y as TheoError, W as W3CTraceContext, _ as _resetMiddlewareCacheForTests, A as _resetUninvocableWarningsForTests, D as appendCookieToHeaders, G as appendDeleteCookieToHeaders, I as callProcedure, J as createCorsHandler, K as createCorsWebHandler, L as createOpenApiHandler, Q as createServerContext, V as deleteCookie, X as envelopeCodeToStatus, Y as executeAction, Z as executeRoute, $ as executeWebRequest, a0 as extractTraceId, a1 as extractTraceIdFromRequest, a2 as extractW3CTraceContext, a3 as fromUnknown, a4 as getCookie, a5 as getCookieFromRequest, a6 as handleBatchRequest, a7 as handleRequestError, a8 as handleWebRequestError, a9 as injectModulePreloads, aa as jsonTransformer, ab as loadCustomErrorPages, ac as matchesOrigin, ad as parseCookieHeader, ae as parseRequestBody, af as parseTraceparent, ag as parseTraceparentContext, ah as resolveTransformer, ai as resolveUserModule, aj as runMiddlewareAndContext, ak as sendError, al as sendJson, am as serializeCookie, an as serveStaticFile, ao as serverErrorToEnvelope, ap as setCookie, aq as superjsonTransformer, ar as validateRouteInput } from '../../index-CY_llLI7.js';
2
+ export { f as defineReadyRoute, s as serveReservedRoute } from '../../health-route-CYI7z5g3.js';
2
3
  export { A as ActionError, b as ActionInputError, f as extractUniversalIssues, i as isActionError, d as isInputError } from '../../action-protocol-tGm3NKRg.js';
3
4
  import '../../error-envelope-DG47lt8E.js';
4
5
  import 'node:http';
@@ -7,7 +7,7 @@ import {
7
7
  injectModulePreloads,
8
8
  loadCustomErrorPages,
9
9
  serveStaticFile
10
- } from "../../chunk-3TCWOHLY.js";
10
+ } from "../../chunk-JZLNZOEL.js";
11
11
  import "../../chunk-O2KGDLA7.js";
12
12
  import {
13
13
  jsonTransformer,
@@ -26,7 +26,7 @@ import {
26
26
  handleRequestError,
27
27
  handleWebRequestError,
28
28
  matchesOrigin
29
- } from "../../chunk-KQBY62AE.js";
29
+ } from "../../chunk-HWRZUQPE.js";
30
30
  import {
31
31
  MiddlewareNextUnavailableError,
32
32
  _resetMiddlewareCacheForTests,
@@ -69,6 +69,10 @@ import {
69
69
  fromUnknown,
70
70
  serverErrorToEnvelope
71
71
  } from "../../chunk-IZ3TIL6K.js";
72
+ import {
73
+ defineReadyRoute,
74
+ serveReservedRoute
75
+ } from "../../chunk-TRCJHFAX.js";
72
76
  import {
73
77
  appendCookieToHeaders,
74
78
  appendDeleteCookieToHeaders,
@@ -110,6 +114,7 @@ export {
110
114
  createCorsWebHandler,
111
115
  createOpenApiHandler,
112
116
  createServerContext,
117
+ defineReadyRoute,
113
118
  deleteCookie,
114
119
  envelopeCodeToStatus,
115
120
  executeAction,
@@ -141,6 +146,7 @@ export {
141
146
  sendError,
142
147
  sendJson,
143
148
  serializeCookie,
149
+ serveReservedRoute,
144
150
  serveStaticFile,
145
151
  serverErrorToEnvelope,
146
152
  setCookie,
@@ -6,7 +6,7 @@ export { C as CustomTool, D as DefineAgentToolSpec, T as ToolContextMessage, a a
6
6
  export { A as AccessDecision, R as RoutePolicy, b as RoutePolicyInput, a as RouteSubject, e as evaluateRoutePolicy, r as requireOwner, s as subjectFromContext } from '../route-policy-BHXQDzBF.js';
7
7
  export { b as HookName, H as HookResult, O as OnErrorHook, c as OnRequestHook, d as OnResponseHook, P as PluginContext, e as PluginErrorContext, f as PreHandlerHook, R as RunHookOptions, a as TheoApp, T as TheoPlugin } from '../plugin-types-BUVfUQ0V.js';
8
8
  export { H as HEALTH_PATH, a as HealthRouteConfig, b as READY_PATH, c as ReadyRouteConfig, d as ReservedResponse, R as ReservedRoutes, e as defineHealthRoute, f as defineReadyRoute, s as serveReservedRoute } from '../health-route-CYI7z5g3.js';
9
- export { B as BATCH_PATH, a as BatchExecuteFn, b as BatchPathConflictError, c as BatchPayload, d as BatchRequestItem, e as BatchResponse, f as BatchResultItem, g as BodyParserOptions, C as CookieOptions, h as CorsConfig, i as CorsHandler, j as CorsOrigin, k as CorsWebHandler, l as CustomErrorPages, E as ExecuteActionOptions, m as ExecuteRouteContext, F as FileTooLargeError, H as HandleBatchOptions, M as MAX_ERROR_HTML_BYTES, n as MiddlewareNextUnavailableError, o as MiddlewareResult, N as NotFoundError, O as OpenApiDocsOptions, P as ParsedBody, p as ProcedureInput, q as ProcedureInputError, r as ProcedureOutputError, R as RawRouteInput, s as RouteInputChannel, t as RouteInputSchemas, u as RouteInputValidation, S as STRIPPED_HEADERS, v as SendErrorInput, w as SendErrorOptions, T as TRACE_HEADER, x as TRACE_PARENT_HEADER, y as TheoError, z as TheoTransformer, U as UploadedFile, W as W3CTraceContext, _ as _resetMiddlewareCacheForTests, A as _resetUninvocableWarningsForTests, D as appendCookieToHeaders, G as appendDeleteCookieToHeaders, I as callProcedure, J as createCorsHandler, K as createCorsWebHandler, L as createOpenApiHandler, Q as createServerContext, V as deleteCookie, X as envelopeCodeToStatus, Y as executeAction, Z as executeRoute, $ as executeWebRequest, a0 as extractTraceId, a1 as extractTraceIdFromRequest, a2 as extractW3CTraceContext, a3 as fromUnknown, a4 as getCookie, a5 as getCookieFromRequest, a6 as handleBatchRequest, a7 as handleRequestError, a8 as handleWebRequestError, a9 as injectModulePreloads, aa as jsonTransformer, ab as loadCustomErrorPages, ac as matchesOrigin, ad as parseCookieHeader, ae as parseRequestBody, af as parseTraceparent, ag as parseTraceparentContext, ah as resolveTransformer, ai as resolveUserModule, aj as runMiddlewareAndContext, ak as sendError, al as sendJson, am as serializeCookie, an as serveStaticFile, ao as serverErrorToEnvelope, ap as setCookie, aq as superjsonTransformer, ar as validateRouteInput } from '../index-C2lcEI-4.js';
9
+ export { B as BATCH_PATH, a as BatchExecuteFn, b as BatchPathConflictError, c as BatchPayload, d as BatchRequestItem, e as BatchResponse, f as BatchResultItem, g as BodyParserOptions, C as CookieOptions, h as CorsConfig, i as CorsHandler, j as CorsOrigin, k as CorsWebHandler, l as CustomErrorPages, E as ExecuteActionOptions, m as ExecuteRouteContext, F as FileTooLargeError, H as HandleBatchOptions, M as MAX_ERROR_HTML_BYTES, n as MiddlewareNextUnavailableError, o as MiddlewareResult, N as NotFoundError, O as OpenApiDocsOptions, P as ParsedBody, p as ProcedureInput, q as ProcedureInputError, r as ProcedureOutputError, R as RawRouteInput, s as RouteInputChannel, t as RouteInputSchemas, u as RouteInputValidation, S as STRIPPED_HEADERS, v as SendErrorInput, w as SendErrorOptions, T as TRACE_HEADER, x as TRACE_PARENT_HEADER, y as TheoError, z as TheoTransformer, U as UploadedFile, W as W3CTraceContext, _ as _resetMiddlewareCacheForTests, A as _resetUninvocableWarningsForTests, D as appendCookieToHeaders, G as appendDeleteCookieToHeaders, I as callProcedure, J as createCorsHandler, K as createCorsWebHandler, L as createOpenApiHandler, Q as createServerContext, V as deleteCookie, X as envelopeCodeToStatus, Y as executeAction, Z as executeRoute, $ as executeWebRequest, a0 as extractTraceId, a1 as extractTraceIdFromRequest, a2 as extractW3CTraceContext, a3 as fromUnknown, a4 as getCookie, a5 as getCookieFromRequest, a6 as handleBatchRequest, a7 as handleRequestError, a8 as handleWebRequestError, a9 as injectModulePreloads, aa as jsonTransformer, ab as loadCustomErrorPages, ac as matchesOrigin, ad as parseCookieHeader, ae as parseRequestBody, af as parseTraceparent, ag as parseTraceparentContext, ah as resolveTransformer, ai as resolveUserModule, aj as runMiddlewareAndContext, ak as sendError, al as sendJson, am as serializeCookie, an as serveStaticFile, ao as serverErrorToEnvelope, ap as setCookie, aq as superjsonTransformer, ar as validateRouteInput } from '../index-CY_llLI7.js';
10
10
  export { A as ActionError, a as ActionErrorCode, b as ActionInputError, e as ActionManifestEntry, c as ActionResult, S as SerializedActionResult, U as UniversalZodIssue, f as extractUniversalIssues, i as isActionError, d as isInputError } from '../action-protocol-tGm3NKRg.js';
11
11
  export { ACTION_SCHEMAS_DIR, ActionNode, ActionScanError, LoadedManifest, ManifestAction, ManifestAgent, ManifestRoute, ManifestWebSocket, TheoManifest, WebSocketRouteNode, _resetRouteScanCacheForTests, compareRouteSpecificity, generateManifest, loadManifest, scanMiddlewares, scanServerActions, scanServerActionsEnriched, scanServerRoutes, scanWebSocketRoutes, writeManifest } from './scan/index.js';
12
12
  export { S as ServerRouteNode, c as compilePattern, m as matchRoute } from '../match-DaKsL73w.js';