stitchkit 0.93.0 → 0.94.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 (1082) hide show
  1. package/CHANGELOG.md +198 -0
  2. package/README.md +5 -2
  3. package/dist/agent-runtime/children-control.d.ts +6 -0
  4. package/dist/agent-runtime/children-control.d.ts.map +1 -0
  5. package/dist/agent-runtime/children-spawn.d.ts +6 -0
  6. package/dist/agent-runtime/children-spawn.d.ts.map +1 -0
  7. package/dist/agent-runtime/children-state.d.ts +46 -0
  8. package/dist/agent-runtime/children-state.d.ts.map +1 -0
  9. package/dist/agent-runtime/children-usage.d.ts +8 -0
  10. package/dist/agent-runtime/children-usage.d.ts.map +1 -0
  11. package/dist/agent-runtime/children.d.ts +11 -14
  12. package/dist/agent-runtime/children.d.ts.map +1 -1
  13. package/dist/agent-runtime/coding-shell-process.d.ts.map +1 -1
  14. package/dist/agent-runtime/coding-tool-contract.d.ts +2 -1
  15. package/dist/agent-runtime/coding-tool-contract.d.ts.map +1 -1
  16. package/dist/agent-runtime/coding-tool-listing.d.ts.map +1 -1
  17. package/dist/agent-runtime/coding-tool-search-patch.d.ts.map +1 -1
  18. package/dist/agent-runtime/contained-darwin.d.ts +38 -0
  19. package/dist/agent-runtime/contained-darwin.d.ts.map +1 -0
  20. package/dist/agent-runtime/contained-files.d.ts +11 -26
  21. package/dist/agent-runtime/contained-files.d.ts.map +1 -1
  22. package/dist/agent-runtime/contained-scan.d.ts +21 -0
  23. package/dist/agent-runtime/contained-scan.d.ts.map +1 -0
  24. package/dist/agent-runtime/contained-write.d.ts +9 -0
  25. package/dist/agent-runtime/contained-write.d.ts.map +1 -0
  26. package/dist/agent-runtime/deferred-tool-types.d.ts +4 -3
  27. package/dist/agent-runtime/deferred-tool-types.d.ts.map +1 -1
  28. package/dist/agent-runtime/events.d.ts +1 -1
  29. package/dist/agent-runtime/events.d.ts.map +1 -1
  30. package/dist/agent-runtime/harness-control.d.ts +0 -1
  31. package/dist/agent-runtime/harness-control.d.ts.map +1 -1
  32. package/dist/agent-runtime/harness.d.ts +0 -5
  33. package/dist/agent-runtime/harness.d.ts.map +1 -1
  34. package/dist/agent-runtime/managed-tools.d.ts +3 -2
  35. package/dist/agent-runtime/managed-tools.d.ts.map +1 -1
  36. package/dist/agent-runtime/observability.d.ts +1 -1
  37. package/dist/agent-runtime/observability.d.ts.map +1 -1
  38. package/dist/agent-runtime/openrouter.d.ts +29 -0
  39. package/dist/agent-runtime/openrouter.d.ts.map +1 -0
  40. package/dist/agent-runtime/projections.d.ts +1 -1
  41. package/dist/agent-runtime/projections.d.ts.map +1 -1
  42. package/dist/agent-runtime/run-acquisition.d.ts +17 -0
  43. package/dist/agent-runtime/run-acquisition.d.ts.map +1 -0
  44. package/dist/agent-runtime/run-execution-state.d.ts +133 -0
  45. package/dist/agent-runtime/run-execution-state.d.ts.map +1 -0
  46. package/dist/agent-runtime/run-execution.d.ts +17 -33
  47. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  48. package/dist/agent-runtime/run-failure.d.ts +18 -0
  49. package/dist/agent-runtime/run-failure.d.ts.map +1 -0
  50. package/dist/agent-runtime/run-model-attempts.d.ts +6 -0
  51. package/dist/agent-runtime/run-model-attempts.d.ts.map +1 -0
  52. package/dist/agent-runtime/run-prompt-history.d.ts +58 -0
  53. package/dist/agent-runtime/run-prompt-history.d.ts.map +1 -0
  54. package/dist/agent-runtime/run-provider-ledger.d.ts +26 -0
  55. package/dist/agent-runtime/run-provider-ledger.d.ts.map +1 -0
  56. package/dist/agent-runtime/run-stream-parts.d.ts +17 -0
  57. package/dist/agent-runtime/run-stream-parts.d.ts.map +1 -0
  58. package/dist/agent-runtime/run-terminal.d.ts +11 -0
  59. package/dist/agent-runtime/run-terminal.d.ts.map +1 -0
  60. package/dist/agent-runtime/run-turn-preparation.d.ts +22 -0
  61. package/dist/agent-runtime/run-turn-preparation.d.ts.map +1 -0
  62. package/dist/agent-runtime/runtime-admission-gate.d.ts +29 -0
  63. package/dist/agent-runtime/runtime-admission-gate.d.ts.map +1 -0
  64. package/dist/agent-runtime/runtime-control.d.ts +9 -0
  65. package/dist/agent-runtime/runtime-control.d.ts.map +1 -0
  66. package/dist/agent-runtime/runtime-recovery.d.ts +10 -0
  67. package/dist/agent-runtime/runtime-recovery.d.ts.map +1 -0
  68. package/dist/agent-runtime/runtime-state.d.ts +36 -0
  69. package/dist/agent-runtime/runtime-state.d.ts.map +1 -0
  70. package/dist/agent-runtime/runtime-submit.d.ts +5 -0
  71. package/dist/agent-runtime/runtime-submit.d.ts.map +1 -0
  72. package/dist/agent-runtime/runtime.d.ts +10 -5
  73. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  74. package/dist/agent-runtime/schedule-records.d.ts +34 -0
  75. package/dist/agent-runtime/schedule-records.d.ts.map +1 -0
  76. package/dist/agent-runtime/schedules.d.ts +34 -0
  77. package/dist/agent-runtime/schedules.d.ts.map +1 -1
  78. package/dist/agent-runtime/sqlite-bun.d.ts +12 -0
  79. package/dist/agent-runtime/sqlite-bun.d.ts.map +1 -0
  80. package/dist/agent-runtime/sqlite-events.d.ts +5 -0
  81. package/dist/agent-runtime/sqlite-events.d.ts.map +1 -0
  82. package/dist/agent-runtime/sqlite-history.d.ts +7 -0
  83. package/dist/agent-runtime/sqlite-history.d.ts.map +1 -0
  84. package/dist/agent-runtime/sqlite-ledger.d.ts +7 -0
  85. package/dist/agent-runtime/sqlite-ledger.d.ts.map +1 -0
  86. package/dist/agent-runtime/sqlite-node.d.ts +12 -0
  87. package/dist/agent-runtime/sqlite-node.d.ts.map +1 -0
  88. package/dist/agent-runtime/sqlite-reads.d.ts +14 -0
  89. package/dist/agent-runtime/sqlite-reads.d.ts.map +1 -0
  90. package/dist/agent-runtime/sqlite-rows.d.ts +178 -0
  91. package/dist/agent-runtime/sqlite-rows.d.ts.map +1 -0
  92. package/dist/agent-runtime/sqlite-schema.d.ts +7 -0
  93. package/dist/agent-runtime/sqlite-schema.d.ts.map +1 -0
  94. package/dist/agent-runtime/sqlite-transactions.d.ts +25 -0
  95. package/dist/agent-runtime/sqlite-transactions.d.ts.map +1 -0
  96. package/dist/agent-runtime/sqlite.d.ts +10 -6
  97. package/dist/agent-runtime/sqlite.d.ts.map +1 -1
  98. package/dist/agent-runtime/store-archive.d.ts +16 -0
  99. package/dist/agent-runtime/store-archive.d.ts.map +1 -0
  100. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +434 -0
  101. package/dist/agent-runtime/store-conformance-lifecycle.d.ts.map +1 -0
  102. package/dist/agent-runtime/store-conformance-ordering.d.ts +18 -0
  103. package/dist/agent-runtime/store-conformance-ordering.d.ts.map +1 -0
  104. package/dist/agent-runtime/store-conformance-support.d.ts +130 -0
  105. package/dist/agent-runtime/store-conformance-support.d.ts.map +1 -0
  106. package/dist/agent-runtime/store-conformance-terminal.d.ts +12 -0
  107. package/dist/agent-runtime/store-conformance-terminal.d.ts.map +1 -0
  108. package/dist/agent-runtime/store-conformance.d.ts +40 -0
  109. package/dist/agent-runtime/store-conformance.d.ts.map +1 -0
  110. package/dist/agent-runtime/store-create.d.ts +11 -0
  111. package/dist/agent-runtime/store-create.d.ts.map +1 -0
  112. package/dist/agent-runtime/store-driver-contract.d.ts +814 -0
  113. package/dist/agent-runtime/store-driver-contract.d.ts.map +1 -0
  114. package/dist/agent-runtime/store-events.d.ts +7 -89
  115. package/dist/agent-runtime/store-events.d.ts.map +1 -1
  116. package/dist/agent-runtime/store-memory.d.ts +4 -0
  117. package/dist/agent-runtime/store-memory.d.ts.map +1 -0
  118. package/dist/agent-runtime/store-mutate.d.ts +13 -0
  119. package/dist/agent-runtime/store-mutate.d.ts.map +1 -0
  120. package/dist/agent-runtime/store-purge.d.ts +1 -1
  121. package/dist/agent-runtime/store-purge.d.ts.map +1 -1
  122. package/dist/agent-runtime/store-reads.d.ts +29 -0
  123. package/dist/agent-runtime/store-reads.d.ts.map +1 -0
  124. package/dist/agent-runtime/store-reduce-history.d.ts +10 -0
  125. package/dist/agent-runtime/store-reduce-history.d.ts.map +1 -0
  126. package/dist/agent-runtime/store-reduce-run.d.ts +14 -0
  127. package/dist/agent-runtime/store-reduce-run.d.ts.map +1 -0
  128. package/dist/agent-runtime/store-reduce-shared.d.ts +76 -0
  129. package/dist/agent-runtime/store-reduce-shared.d.ts.map +1 -0
  130. package/dist/agent-runtime/store-reduce-terminal.d.ts +6 -0
  131. package/dist/agent-runtime/store-reduce-terminal.d.ts.map +1 -0
  132. package/dist/agent-runtime/store-reducer.d.ts +24 -0
  133. package/dist/agent-runtime/store-reducer.d.ts.map +1 -0
  134. package/dist/agent-runtime/store-snapshot.d.ts +19 -0
  135. package/dist/agent-runtime/store-snapshot.d.ts.map +1 -0
  136. package/dist/agent-runtime/store.d.ts +1 -1
  137. package/dist/agent-runtime/store.d.ts.map +1 -1
  138. package/dist/application/admission-rate.d.ts +21 -0
  139. package/dist/application/admission-rate.d.ts.map +1 -0
  140. package/dist/application/admission-run.d.ts +8 -0
  141. package/dist/application/admission-run.d.ts.map +1 -0
  142. package/dist/application/admission.d.ts +1 -1
  143. package/dist/application/admission.d.ts.map +1 -1
  144. package/dist/application/diagnostic-journal-lock.d.ts +9 -34
  145. package/dist/application/diagnostic-journal-lock.d.ts.map +1 -1
  146. package/dist/application/diagnostic-journal-manager.d.ts.map +1 -1
  147. package/dist/application/diagnostic-journal-storage.d.ts.map +1 -1
  148. package/dist/application/events.d.ts +1 -1
  149. package/dist/application/events.d.ts.map +1 -1
  150. package/dist/application/file-state-store.d.ts +23 -0
  151. package/dist/application/file-state-store.d.ts.map +1 -0
  152. package/dist/application/health.d.ts +1 -1
  153. package/dist/application/health.d.ts.map +1 -1
  154. package/dist/application/kernel-admission.d.ts +8 -0
  155. package/dist/application/kernel-admission.d.ts.map +1 -0
  156. package/dist/application/kernel-contract.d.ts +142 -0
  157. package/dist/application/kernel-contract.d.ts.map +1 -0
  158. package/dist/application/kernel-resource-context.d.ts +24 -0
  159. package/dist/application/kernel-resource-context.d.ts.map +1 -0
  160. package/dist/application/kernel-restart.d.ts +5 -0
  161. package/dist/application/kernel-restart.d.ts.map +1 -0
  162. package/dist/application/kernel-rollback.d.ts +4 -0
  163. package/dist/application/kernel-rollback.d.ts.map +1 -0
  164. package/dist/application/kernel-shutdown.d.ts +6 -0
  165. package/dist/application/kernel-shutdown.d.ts.map +1 -0
  166. package/dist/application/kernel-start.d.ts +20 -0
  167. package/dist/application/kernel-start.d.ts.map +1 -0
  168. package/dist/application/kernel-state.d.ts +116 -0
  169. package/dist/application/kernel-state.d.ts.map +1 -0
  170. package/dist/application/kernel.d.ts +9 -140
  171. package/dist/application/kernel.d.ts.map +1 -1
  172. package/dist/application/latest-sink.d.ts +1 -1
  173. package/dist/application/latest-sink.d.ts.map +1 -1
  174. package/dist/application/notification-outbox.d.ts.map +1 -1
  175. package/dist/application/opentelemetry.d.ts +1 -1
  176. package/dist/application/opentelemetry.d.ts.map +1 -1
  177. package/dist/application/schedule.d.ts +0 -1
  178. package/dist/application/schedule.d.ts.map +1 -1
  179. package/dist/application/watch-hub-core.d.ts +122 -0
  180. package/dist/application/watch-hub-core.d.ts.map +1 -0
  181. package/dist/application/watch-hub.d.ts +3 -3
  182. package/dist/application/watch-hub.d.ts.map +1 -1
  183. package/dist/browser/client-executors.d.ts +14 -0
  184. package/dist/browser/client-executors.d.ts.map +1 -0
  185. package/dist/browser/client-multipart.d.ts +1 -1
  186. package/dist/browser/client-multipart.d.ts.map +1 -1
  187. package/dist/browser/client-url.d.ts +1 -1
  188. package/dist/browser/client-url.d.ts.map +1 -1
  189. package/dist/browser/client.d.ts +3 -2
  190. package/dist/browser/client.d.ts.map +1 -1
  191. package/dist/browser/contract-stream.d.ts +1 -1
  192. package/dist/browser/contract-stream.d.ts.map +1 -1
  193. package/dist/browser/http-fetch.d.ts +22 -0
  194. package/dist/browser/http-fetch.d.ts.map +1 -0
  195. package/dist/browser/http.d.ts +2 -4
  196. package/dist/browser/http.d.ts.map +1 -1
  197. package/dist/browser/live-state-core.d.ts +63 -0
  198. package/dist/browser/live-state-core.d.ts.map +1 -0
  199. package/dist/browser/live-state.d.ts.map +1 -1
  200. package/dist/browser/realtime-client.d.ts +26 -0
  201. package/dist/browser/realtime-client.d.ts.map +1 -0
  202. package/dist/browser/resumable.d.ts +1 -28
  203. package/dist/browser/resumable.d.ts.map +1 -1
  204. package/dist/browser/retained.d.ts.map +1 -0
  205. package/dist/browser/socket-io-connection.d.ts +82 -0
  206. package/dist/browser/socket-io-connection.d.ts.map +1 -0
  207. package/dist/browser/socket-io-peer.d.ts +20 -0
  208. package/dist/browser/socket-io-peer.d.ts.map +1 -0
  209. package/dist/browser/socket-io-trace.d.ts +31 -0
  210. package/dist/browser/socket-io-trace.d.ts.map +1 -0
  211. package/dist/browser/socket-io.d.ts +24 -18
  212. package/dist/browser/socket-io.d.ts.map +1 -1
  213. package/dist/browser/stream.d.ts +14 -2
  214. package/dist/browser/stream.d.ts.map +1 -1
  215. package/dist/contract/client-types.d.ts +134 -0
  216. package/dist/contract/client-types.d.ts.map +1 -0
  217. package/dist/contract/define-validation.d.ts +30 -0
  218. package/dist/contract/define-validation.d.ts.map +1 -0
  219. package/dist/contract/define.d.ts +47 -394
  220. package/dist/contract/define.d.ts.map +1 -1
  221. package/dist/contract/normalize.d.ts +56 -0
  222. package/dist/contract/normalize.d.ts.map +1 -0
  223. package/dist/contract/runtime-context.d.ts +131 -0
  224. package/dist/contract/runtime-context.d.ts.map +1 -0
  225. package/dist/contract/tool-options.d.ts +105 -0
  226. package/dist/contract/tool-options.d.ts.map +1 -0
  227. package/dist/contract/tool-view.d.ts +148 -0
  228. package/dist/contract/tool-view.d.ts.map +1 -0
  229. package/dist/declaration/declaration.d.ts.map +1 -0
  230. package/dist/durability/contract.d.ts +259 -0
  231. package/dist/durability/contract.d.ts.map +1 -0
  232. package/dist/durability/effect.d.ts +24 -0
  233. package/dist/durability/effect.d.ts.map +1 -0
  234. package/dist/durability/engine.d.ts +14 -0
  235. package/dist/durability/engine.d.ts.map +1 -0
  236. package/dist/durability/events.d.ts +103 -0
  237. package/dist/durability/events.d.ts.map +1 -0
  238. package/dist/durability/json.d.ts +3 -0
  239. package/dist/durability/json.d.ts.map +1 -0
  240. package/dist/durability/ledger.d.ts +27 -0
  241. package/dist/durability/ledger.d.ts.map +1 -0
  242. package/dist/durability/parks.d.ts +22 -0
  243. package/dist/durability/parks.d.ts.map +1 -0
  244. package/dist/durability/scheduler.d.ts +30 -0
  245. package/dist/durability/scheduler.d.ts.map +1 -0
  246. package/dist/entrypoints/agent-runtime/browser.d.ts +5 -0
  247. package/dist/entrypoints/agent-runtime/browser.d.ts.map +1 -0
  248. package/dist/entrypoints/agent-runtime/browser.js +124 -0
  249. package/dist/entrypoints/agent-runtime/coding-tools.d.ts +2 -0
  250. package/dist/entrypoints/agent-runtime/coding-tools.d.ts.map +1 -0
  251. package/dist/entrypoints/agent-runtime/coding-tools.js +22 -0
  252. package/dist/entrypoints/agent-runtime/harness.d.ts +2 -0
  253. package/dist/entrypoints/agent-runtime/harness.d.ts.map +1 -0
  254. package/dist/entrypoints/agent-runtime/harness.js +739 -0
  255. package/dist/entrypoints/agent-runtime/openrouter.d.ts +2 -0
  256. package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -0
  257. package/dist/entrypoints/agent-runtime/openrouter.js +270 -0
  258. package/dist/entrypoints/agent-runtime/sandbox.d.ts +5 -0
  259. package/dist/entrypoints/agent-runtime/sandbox.d.ts.map +1 -0
  260. package/dist/entrypoints/agent-runtime/sandbox.js +797 -0
  261. package/dist/entrypoints/agent-runtime/sqlite/bun.d.ts +2 -0
  262. package/dist/entrypoints/agent-runtime/sqlite/bun.d.ts.map +1 -0
  263. package/dist/entrypoints/agent-runtime/sqlite/bun.js +44 -0
  264. package/dist/entrypoints/agent-runtime/sqlite/node.d.ts +2 -0
  265. package/dist/entrypoints/agent-runtime/sqlite/node.d.ts.map +1 -0
  266. package/dist/entrypoints/agent-runtime/sqlite/node.js +46 -0
  267. package/dist/entrypoints/agent-runtime/testing.d.ts +4 -0
  268. package/dist/entrypoints/agent-runtime/testing.d.ts.map +1 -0
  269. package/dist/entrypoints/agent-runtime/testing.js +1116 -0
  270. package/dist/entrypoints/agent-runtime.d.ts +42 -0
  271. package/dist/entrypoints/agent-runtime.d.ts.map +1 -0
  272. package/dist/entrypoints/agent-runtime.js +2670 -0
  273. package/dist/entrypoints/application/diagnostic-journal.d.ts +21 -0
  274. package/dist/entrypoints/application/diagnostic-journal.d.ts.map +1 -0
  275. package/dist/entrypoints/application/diagnostic-journal.js +492 -0
  276. package/dist/entrypoints/application/grammy.d.ts +2 -0
  277. package/dist/entrypoints/application/grammy.d.ts.map +1 -0
  278. package/dist/entrypoints/application/grammy.js +169 -0
  279. package/dist/entrypoints/application/opentelemetry.d.ts +2 -0
  280. package/dist/entrypoints/application/opentelemetry.d.ts.map +1 -0
  281. package/dist/entrypoints/application/opentelemetry.js +250 -0
  282. package/dist/entrypoints/application/schemas.d.ts +15 -0
  283. package/dist/entrypoints/application/schemas.d.ts.map +1 -0
  284. package/dist/entrypoints/application/schemas.js +27 -0
  285. package/dist/entrypoints/application.d.ts +23 -0
  286. package/dist/entrypoints/application.d.ts.map +1 -0
  287. package/dist/entrypoints/application.js +2016 -0
  288. package/dist/entrypoints/bin/upgrade-cli.d.ts.map +1 -0
  289. package/dist/entrypoints/bin/upgrade-cli.js +177 -0
  290. package/dist/entrypoints/cli.d.ts +44 -0
  291. package/dist/entrypoints/cli.d.ts.map +1 -0
  292. package/dist/entrypoints/cli.js +773 -0
  293. package/dist/entrypoints/contract.d.ts +12 -0
  294. package/dist/entrypoints/contract.d.ts.map +1 -0
  295. package/dist/entrypoints/contract.js +64 -0
  296. package/dist/entrypoints/declaration.d.ts +2 -0
  297. package/dist/entrypoints/declaration.d.ts.map +1 -0
  298. package/dist/entrypoints/declaration.js +183 -0
  299. package/dist/entrypoints/files.d.ts +5 -0
  300. package/dist/entrypoints/files.d.ts.map +1 -0
  301. package/dist/entrypoints/files.js +111 -0
  302. package/dist/entrypoints/geo.d.ts +3 -0
  303. package/dist/entrypoints/geo.d.ts.map +1 -0
  304. package/dist/entrypoints/geo.js +245 -0
  305. package/dist/entrypoints/google.d.ts +2 -0
  306. package/dist/entrypoints/google.d.ts.map +1 -0
  307. package/dist/entrypoints/google.js +175 -0
  308. package/dist/entrypoints/index.d.ts +17 -0
  309. package/dist/entrypoints/index.d.ts.map +1 -0
  310. package/dist/entrypoints/index.js +764 -0
  311. package/dist/entrypoints/live.d.ts +19 -0
  312. package/dist/entrypoints/live.d.ts.map +1 -0
  313. package/dist/entrypoints/live.js +302 -0
  314. package/dist/entrypoints/node.d.ts +19 -0
  315. package/dist/entrypoints/node.d.ts.map +1 -0
  316. package/dist/entrypoints/node.js +308 -0
  317. package/dist/entrypoints/oauth.d.ts +2 -0
  318. package/dist/entrypoints/oauth.d.ts.map +1 -0
  319. package/dist/entrypoints/oauth.js +170 -0
  320. package/dist/entrypoints/observability.d.ts +19 -0
  321. package/dist/entrypoints/observability.d.ts.map +1 -0
  322. package/dist/entrypoints/observability.js +567 -0
  323. package/dist/entrypoints/primitives.d.ts +3 -0
  324. package/dist/entrypoints/primitives.d.ts.map +1 -0
  325. package/dist/entrypoints/primitives.js +749 -0
  326. package/dist/entrypoints/react.d.ts +5 -0
  327. package/dist/entrypoints/react.d.ts.map +1 -0
  328. package/dist/entrypoints/react.js +403 -0
  329. package/dist/entrypoints/release.d.ts +15 -0
  330. package/dist/entrypoints/release.d.ts.map +1 -0
  331. package/dist/entrypoints/release.js +196 -0
  332. package/dist/entrypoints/remote.d.ts +9 -0
  333. package/dist/entrypoints/remote.d.ts.map +1 -0
  334. package/dist/entrypoints/remote.js +66 -0
  335. package/dist/entrypoints/server.d.ts +39 -0
  336. package/dist/entrypoints/server.d.ts.map +1 -0
  337. package/dist/entrypoints/server.js +2009 -0
  338. package/dist/entrypoints/telegram.d.ts +3 -0
  339. package/dist/entrypoints/telegram.d.ts.map +1 -0
  340. package/dist/entrypoints/telegram.js +224 -0
  341. package/dist/entrypoints/testing.d.ts +10 -0
  342. package/dist/entrypoints/testing.d.ts.map +1 -0
  343. package/dist/entrypoints/testing.js +1377 -0
  344. package/dist/entrypoints/tools/connections.d.ts +19 -0
  345. package/dist/entrypoints/tools/connections.d.ts.map +1 -0
  346. package/dist/entrypoints/tools/connections.js +1110 -0
  347. package/dist/entrypoints/tools/contract.d.ts +29 -0
  348. package/dist/entrypoints/tools/contract.d.ts.map +1 -0
  349. package/dist/entrypoints/tools/contract.js +24 -0
  350. package/dist/entrypoints/tools/invoker.d.ts +9 -0
  351. package/dist/entrypoints/tools/invoker.d.ts.map +1 -0
  352. package/dist/entrypoints/tools/invoker.js +20 -0
  353. package/dist/entrypoints/tools.d.ts +54 -0
  354. package/dist/entrypoints/tools.d.ts.map +1 -0
  355. package/dist/entrypoints/tools.js +3009 -0
  356. package/dist/entrypoints/tracking/server.d.ts +15 -0
  357. package/dist/entrypoints/tracking/server.d.ts.map +1 -0
  358. package/dist/entrypoints/tracking.d.ts +24 -0
  359. package/dist/entrypoints/tracking.d.ts.map +1 -0
  360. package/dist/entrypoints/tracking.js +1140 -0
  361. package/dist/files/boundary.d.ts.map +1 -1
  362. package/dist/files/file-io.d.ts +14 -0
  363. package/dist/files/file-io.d.ts.map +1 -0
  364. package/dist/google/google.d.ts.map +1 -0
  365. package/dist/index-0b1ess5e.js +38 -0
  366. package/dist/index-1j8pm5t0.js +412 -0
  367. package/dist/index-1zbbzgfh.js +89 -0
  368. package/dist/index-2bxbyab0.js +47 -0
  369. package/dist/index-2gxzjvyr.js +266 -0
  370. package/dist/index-35mh5bhj.js +177 -0
  371. package/dist/index-48ffdxgk.js +6 -0
  372. package/dist/index-4gcnakhx.js +82 -0
  373. package/dist/index-55hkhm67.js +343 -0
  374. package/dist/index-79z7m7dt.js +675 -0
  375. package/dist/index-7f68ghdn.js +3618 -0
  376. package/dist/index-7p1f0vp2.js +154 -0
  377. package/dist/index-83bdg97s.js +16 -0
  378. package/dist/index-863ea9jb.js +154 -0
  379. package/dist/index-8p52kd5p.js +242 -0
  380. package/dist/index-d9pk3td4.js +326 -0
  381. package/dist/index-dce5wxcq.js +63 -0
  382. package/dist/index-e01r054k.js +105 -0
  383. package/dist/index-ensd0r74.js +595 -0
  384. package/dist/index-eqqvgdb3.js +46 -0
  385. package/dist/index-gxrt5h6v.js +341 -0
  386. package/dist/index-h6eeys1v.js +211 -0
  387. package/dist/index-ham5sz8m.js +734 -0
  388. package/dist/index-het2he5g.js +1387 -0
  389. package/dist/index-hffjpmq9.js +30 -0
  390. package/dist/index-hmp4800j.js +51 -0
  391. package/dist/index-k30h66yd.js +317 -0
  392. package/dist/index-k5hsfc3j.js +31 -0
  393. package/dist/index-khtgb21r.js +92 -0
  394. package/dist/index-m9zn6cpq.js +51 -0
  395. package/dist/index-ndddxtyx.js +324 -0
  396. package/dist/index-ngfhvfpd.js +30 -0
  397. package/dist/index-np4m8hd3.js +1205 -0
  398. package/dist/index-p3vsv1fb.js +3493 -0
  399. package/dist/index-p5r7qpdd.js +85 -0
  400. package/dist/index-p9e0w8hs.js +1084 -0
  401. package/dist/index-p9sh0xx4.js +64 -0
  402. package/dist/index-paz6sgdp.js +371 -0
  403. package/dist/index-px2gm2jp.js +448 -0
  404. package/dist/index-qwhynv6x.js +103 -0
  405. package/dist/index-s812ycat.js +65 -0
  406. package/dist/index-sp1tzwnb.js +281 -0
  407. package/dist/index-t9rhjr9f.js +2306 -0
  408. package/dist/index-v260df89.js +342 -0
  409. package/dist/index-w906953s.js +946 -0
  410. package/dist/index-wdkt63w3.js +214 -0
  411. package/dist/index-wqgjfstn.js +18 -0
  412. package/dist/index-wsm5w4ee.js +1023 -0
  413. package/dist/index-xw3s75nj.js +100 -0
  414. package/dist/index-yw4fzmdz.js +268 -0
  415. package/dist/index-zfrhfn82.js +85 -0
  416. package/dist/index-znfs20ss.js +98 -0
  417. package/dist/internal/atomic-file.d.ts +23 -2
  418. package/dist/internal/atomic-file.d.ts.map +1 -1
  419. package/dist/internal/backoff.d.ts +29 -0
  420. package/dist/internal/backoff.d.ts.map +1 -0
  421. package/dist/internal/canonical-json.d.ts +21 -11
  422. package/dist/internal/canonical-json.d.ts.map +1 -1
  423. package/dist/internal/channel.d.ts.map +1 -0
  424. package/dist/internal/exclusive-lock.d.ts +51 -0
  425. package/dist/internal/exclusive-lock.d.ts.map +1 -0
  426. package/dist/internal/logger.d.ts.map +1 -0
  427. package/dist/internal/process-identity.d.ts +47 -0
  428. package/dist/internal/process-identity.d.ts.map +1 -0
  429. package/dist/internal/request.d.ts.map +1 -0
  430. package/dist/internal/stable-digest.d.ts +0 -43
  431. package/dist/internal/stable-digest.d.ts.map +1 -1
  432. package/dist/internal/typed.d.ts +0 -8
  433. package/dist/internal/typed.d.ts.map +1 -1
  434. package/dist/internal/with-exclusive-lock.d.ts +67 -0
  435. package/dist/internal/with-exclusive-lock.d.ts.map +1 -0
  436. package/dist/internal/zod-issues.d.ts +38 -0
  437. package/dist/internal/zod-issues.d.ts.map +1 -0
  438. package/dist/json-schema/dialect.d.ts +17 -0
  439. package/dist/json-schema/dialect.d.ts.map +1 -0
  440. package/dist/json-schema/json-schema.d.ts.map +1 -0
  441. package/dist/live/watch-client.d.ts.map +1 -1
  442. package/dist/live/watch-delta.d.ts.map +1 -1
  443. package/dist/oauth/authorization-code.d.ts +57 -0
  444. package/dist/oauth/authorization-code.d.ts.map +1 -0
  445. package/dist/observability/audit.d.ts +3 -3
  446. package/dist/observability/audit.d.ts.map +1 -1
  447. package/dist/observability/bounded-logger.d.ts +1 -1
  448. package/dist/observability/bounded-logger.d.ts.map +1 -1
  449. package/dist/observability/bounded-sink.d.ts +81 -0
  450. package/dist/observability/bounded-sink.d.ts.map +1 -0
  451. package/dist/observability/context.d.ts +1 -1
  452. package/dist/observability/context.d.ts.map +1 -1
  453. package/dist/observability/event.d.ts +2 -1
  454. package/dist/observability/event.d.ts.map +1 -1
  455. package/dist/observability/work.d.ts +1 -1
  456. package/dist/observability/work.d.ts.map +1 -1
  457. package/dist/primitives/audit.d.ts +1 -1
  458. package/dist/primitives/audit.d.ts.map +1 -1
  459. package/dist/primitives/export-operation.d.ts +4 -2
  460. package/dist/primitives/export-operation.d.ts.map +1 -1
  461. package/dist/realtime/registry.d.ts +0 -5
  462. package/dist/realtime/registry.d.ts.map +1 -1
  463. package/dist/realtime/socket.d.ts +1 -1
  464. package/dist/realtime/socket.d.ts.map +1 -1
  465. package/dist/server/bun.d.ts +0 -1
  466. package/dist/server/bun.d.ts.map +1 -1
  467. package/dist/server/context-contribution.d.ts +1 -1
  468. package/dist/server/context-contribution.d.ts.map +1 -1
  469. package/dist/server/context.d.ts +2 -2
  470. package/dist/server/context.d.ts.map +1 -1
  471. package/dist/server/contract-method.d.ts +15 -0
  472. package/dist/server/contract-method.d.ts.map +1 -0
  473. package/dist/server/contract-stream.d.ts +1 -1
  474. package/dist/server/contract-stream.d.ts.map +1 -1
  475. package/dist/server/create.d.ts +8 -0
  476. package/dist/server/create.d.ts.map +1 -1
  477. package/dist/server/endpoint-dispatch.d.ts +10 -0
  478. package/dist/server/endpoint-dispatch.d.ts.map +1 -0
  479. package/dist/server/endpoint-response.d.ts +19 -0
  480. package/dist/server/endpoint-response.d.ts.map +1 -0
  481. package/dist/server/error-dispatch.d.ts +17 -1
  482. package/dist/server/error-dispatch.d.ts.map +1 -1
  483. package/dist/server/error-hook.d.ts +2 -2
  484. package/dist/server/error-hook.d.ts.map +1 -1
  485. package/dist/server/handler-state.d.ts +44 -0
  486. package/dist/server/handler-state.d.ts.map +1 -0
  487. package/dist/server/implement-registry.d.ts +54 -0
  488. package/dist/server/implement-registry.d.ts.map +1 -0
  489. package/dist/server/implement.d.ts +9 -55
  490. package/dist/server/implement.d.ts.map +1 -1
  491. package/dist/server/middleware/auth.d.ts +1 -31
  492. package/dist/server/middleware/auth.d.ts.map +1 -1
  493. package/dist/server/middleware/cors.d.ts +17 -0
  494. package/dist/server/middleware/cors.d.ts.map +1 -1
  495. package/dist/server/middleware/jwt.d.ts +31 -0
  496. package/dist/server/middleware/jwt.d.ts.map +1 -0
  497. package/dist/server/middleware/trust-fence.d.ts +1 -1
  498. package/dist/server/middleware/trust-fence.d.ts.map +1 -1
  499. package/dist/server/multipart-reader.d.ts +22 -0
  500. package/dist/server/multipart-reader.d.ts.map +1 -0
  501. package/dist/server/multipart.d.ts +1 -1
  502. package/dist/server/multipart.d.ts.map +1 -1
  503. package/dist/server/oauth/cimd.d.ts +88 -0
  504. package/dist/server/oauth/cimd.d.ts.map +1 -0
  505. package/dist/server/oauth/endpoints.d.ts +39 -0
  506. package/dist/server/oauth/endpoints.d.ts.map +1 -0
  507. package/dist/server/oauth/metadata.d.ts +28 -0
  508. package/dist/server/oauth/metadata.d.ts.map +1 -0
  509. package/dist/server/oauth/provider.d.ts +117 -0
  510. package/dist/server/oauth/provider.d.ts.map +1 -0
  511. package/dist/server/realtime.d.ts +1 -1
  512. package/dist/server/realtime.d.ts.map +1 -1
  513. package/dist/server/request-completion.d.ts +16 -0
  514. package/dist/server/request-completion.d.ts.map +1 -0
  515. package/dist/server/response-metadata.d.ts +1 -1
  516. package/dist/server/response-metadata.d.ts.map +1 -1
  517. package/dist/server/route-table.d.ts +9 -0
  518. package/dist/server/route-table.d.ts.map +1 -0
  519. package/dist/server/stream.d.ts +0 -13
  520. package/dist/server/stream.d.ts.map +1 -1
  521. package/dist/server/streaming-pump.d.ts +66 -0
  522. package/dist/server/streaming-pump.d.ts.map +1 -0
  523. package/dist/server/streaming-route.d.ts +12 -5
  524. package/dist/server/streaming-route.d.ts.map +1 -1
  525. package/dist/server/types.d.ts +10 -4
  526. package/dist/server/types.d.ts.map +1 -1
  527. package/dist/server/unix-client-bun.d.ts.map +1 -1
  528. package/dist/server/unix-client-http1.d.ts +76 -0
  529. package/dist/server/unix-client-http1.d.ts.map +1 -0
  530. package/dist/server/unix-client.d.ts.map +1 -1
  531. package/dist/testing/handler-clients.d.ts +32 -0
  532. package/dist/testing/handler-clients.d.ts.map +1 -0
  533. package/dist/testing/managed-resource-conformance-scenarios.d.ts.map +1 -1
  534. package/dist/testing/realtime-probe.d.ts +33 -0
  535. package/dist/testing/realtime-probe.d.ts.map +1 -0
  536. package/dist/testing/surface-conformance.d.ts +2 -32
  537. package/dist/testing/surface-conformance.d.ts.map +1 -1
  538. package/dist/testing/surface-manifest-digest.d.ts +44 -0
  539. package/dist/testing/surface-manifest-digest.d.ts.map +1 -0
  540. package/dist/testing/surface-manifest.d.ts +30 -4
  541. package/dist/testing/surface-manifest.d.ts.map +1 -1
  542. package/dist/tools/agent.d.ts +1 -1
  543. package/dist/tools/agent.d.ts.map +1 -1
  544. package/dist/tools/cli/args-fields.d.ts +31 -0
  545. package/dist/tools/cli/args-fields.d.ts.map +1 -0
  546. package/dist/tools/cli/args-route.d.ts +42 -0
  547. package/dist/tools/cli/args-route.d.ts.map +1 -0
  548. package/dist/tools/cli/args-view.d.ts +32 -0
  549. package/dist/tools/cli/args-view.d.ts.map +1 -0
  550. package/dist/tools/cli/args.d.ts +80 -0
  551. package/dist/tools/cli/args.d.ts.map +1 -0
  552. package/dist/tools/cli/argument-error.d.ts +5 -0
  553. package/dist/tools/cli/argument-error.d.ts.map +1 -0
  554. package/dist/tools/cli/checkpoint.d.ts +24 -0
  555. package/dist/tools/cli/checkpoint.d.ts.map +1 -0
  556. package/dist/tools/cli/command.d.ts +70 -0
  557. package/dist/tools/cli/command.d.ts.map +1 -0
  558. package/dist/tools/cli/config.d.ts +90 -0
  559. package/dist/tools/cli/config.d.ts.map +1 -0
  560. package/dist/tools/cli/create-cli.d.ts +36 -0
  561. package/dist/tools/cli/create-cli.d.ts.map +1 -0
  562. package/dist/tools/cli/download.d.ts +8 -0
  563. package/dist/tools/cli/download.d.ts.map +1 -0
  564. package/dist/tools/cli/format.d.ts +50 -0
  565. package/dist/tools/cli/format.d.ts.map +1 -0
  566. package/dist/tools/cli/help.d.ts +24 -0
  567. package/dist/tools/cli/help.d.ts.map +1 -0
  568. package/dist/tools/cli/installer.d.ts +34 -0
  569. package/dist/tools/cli/installer.d.ts.map +1 -0
  570. package/dist/tools/cli/invoke.d.ts +144 -0
  571. package/dist/tools/cli/invoke.d.ts.map +1 -0
  572. package/dist/tools/cli/io.d.ts +10 -0
  573. package/dist/tools/cli/io.d.ts.map +1 -0
  574. package/dist/tools/cli/managed-surface.d.ts +30 -0
  575. package/dist/tools/cli/managed-surface.d.ts.map +1 -0
  576. package/dist/tools/cli/manifest.d.ts +80 -0
  577. package/dist/tools/cli/manifest.d.ts.map +1 -0
  578. package/dist/tools/cli/policy.d.ts +27 -0
  579. package/dist/tools/cli/policy.d.ts.map +1 -0
  580. package/dist/tools/cli/prepare.d.ts +14 -0
  581. package/dist/tools/cli/prepare.d.ts.map +1 -0
  582. package/dist/tools/cli/profile.d.ts +40 -0
  583. package/dist/tools/cli/profile.d.ts.map +1 -0
  584. package/dist/tools/cli/run-managed.d.ts +5 -0
  585. package/dist/tools/cli/run-managed.d.ts.map +1 -0
  586. package/dist/tools/cli/run-native.d.ts +9 -0
  587. package/dist/tools/cli/run-native.d.ts.map +1 -0
  588. package/dist/tools/cli/session.d.ts +40 -0
  589. package/dist/tools/cli/session.d.ts.map +1 -0
  590. package/dist/tools/cli/signature.d.ts +81 -0
  591. package/dist/tools/cli/signature.d.ts.map +1 -0
  592. package/dist/tools/cli/stream.d.ts +93 -0
  593. package/dist/tools/cli/stream.d.ts.map +1 -0
  594. package/dist/tools/cli/update.d.ts +145 -0
  595. package/dist/tools/cli/update.d.ts.map +1 -0
  596. package/dist/tools/cli/view.d.ts +12 -0
  597. package/dist/tools/cli/view.d.ts.map +1 -0
  598. package/dist/tools/cli/wait.d.ts +54 -0
  599. package/dist/tools/cli/wait.d.ts.map +1 -0
  600. package/dist/tools/connections/runtime.d.ts +1 -1
  601. package/dist/tools/connections/runtime.d.ts.map +1 -1
  602. package/dist/tools/connections/types.d.ts +3 -3
  603. package/dist/tools/connections/types.d.ts.map +1 -1
  604. package/dist/tools/durability-context.d.ts +1 -1
  605. package/dist/tools/durability-context.d.ts.map +1 -1
  606. package/dist/tools/execute-args.d.ts +23 -0
  607. package/dist/tools/execute-args.d.ts.map +1 -0
  608. package/dist/tools/execute-hooks.d.ts +146 -0
  609. package/dist/tools/execute-hooks.d.ts.map +1 -0
  610. package/dist/tools/execute-result.d.ts +40 -0
  611. package/dist/tools/execute-result.d.ts.map +1 -0
  612. package/dist/tools/execute.d.ts +31 -193
  613. package/dist/tools/execute.d.ts.map +1 -1
  614. package/dist/tools/internal/surface-projector.d.ts +9 -6
  615. package/dist/tools/internal/surface-projector.d.ts.map +1 -1
  616. package/dist/tools/internal/tool-view.d.ts +41 -0
  617. package/dist/tools/internal/tool-view.d.ts.map +1 -0
  618. package/dist/tools/invoker.d.ts +13 -4
  619. package/dist/tools/invoker.d.ts.map +1 -1
  620. package/dist/tools/lifecycle.d.ts +1 -1
  621. package/dist/tools/lifecycle.d.ts.map +1 -1
  622. package/dist/tools/list-names.d.ts +3 -3
  623. package/dist/tools/list-names.d.ts.map +1 -1
  624. package/dist/tools/manifest.d.ts +2 -2
  625. package/dist/tools/manifest.d.ts.map +1 -1
  626. package/dist/tools/mcp/app.d.ts +62 -0
  627. package/dist/tools/mcp/app.d.ts.map +1 -0
  628. package/dist/tools/mcp/catalog.d.ts +68 -0
  629. package/dist/tools/mcp/catalog.d.ts.map +1 -0
  630. package/dist/tools/mcp/handler.d.ts +46 -0
  631. package/dist/tools/mcp/handler.d.ts.map +1 -0
  632. package/dist/tools/mcp/mount.d.ts +152 -0
  633. package/dist/tools/mcp/mount.d.ts.map +1 -0
  634. package/dist/tools/mcp/prepare.d.ts +76 -0
  635. package/dist/tools/mcp/prepare.d.ts.map +1 -0
  636. package/dist/tools/mcp/progress.d.ts +46 -0
  637. package/dist/tools/mcp/progress.d.ts.map +1 -0
  638. package/dist/tools/mcp/register.d.ts +36 -0
  639. package/dist/tools/mcp/register.d.ts.map +1 -0
  640. package/dist/tools/mcp/round-context.d.ts +38 -0
  641. package/dist/tools/mcp/round-context.d.ts.map +1 -0
  642. package/dist/tools/mcp/round-policy.d.ts +33 -0
  643. package/dist/tools/mcp/round-policy.d.ts.map +1 -0
  644. package/dist/tools/mcp/round.d.ts +53 -0
  645. package/dist/tools/mcp/round.d.ts.map +1 -0
  646. package/dist/tools/mcp/runtime-tools.d.ts +25 -0
  647. package/dist/tools/mcp/runtime-tools.d.ts.map +1 -0
  648. package/dist/tools/mcp/stdio-signals.d.ts +33 -0
  649. package/dist/tools/mcp/stdio-signals.d.ts.map +1 -0
  650. package/dist/tools/mcp/stdio.d.ts +20 -0
  651. package/dist/tools/mcp/stdio.d.ts.map +1 -0
  652. package/dist/tools/mcp/trace.d.ts +12 -0
  653. package/dist/tools/mcp/trace.d.ts.map +1 -0
  654. package/dist/tools/mount.d.ts +14 -7
  655. package/dist/tools/mount.d.ts.map +1 -1
  656. package/dist/tools/native-definition.d.ts +4 -3
  657. package/dist/tools/native-definition.d.ts.map +1 -1
  658. package/dist/tools/operations/async-operation-binding-types.d.ts +127 -0
  659. package/dist/tools/operations/async-operation-binding-types.d.ts.map +1 -0
  660. package/dist/tools/operations/async-operation-binding.d.ts +28 -0
  661. package/dist/tools/operations/async-operation-binding.d.ts.map +1 -0
  662. package/dist/tools/operations/async-operation-canonical-types.d.ts +110 -0
  663. package/dist/tools/operations/async-operation-canonical-types.d.ts.map +1 -0
  664. package/dist/tools/operations/async-operation-canonical.d.ts +7 -0
  665. package/dist/tools/operations/async-operation-canonical.d.ts.map +1 -0
  666. package/dist/tools/operations/async-operation-contract.d.ts.map +1 -0
  667. package/dist/tools/operations/async-operation-id.d.ts +23 -0
  668. package/dist/tools/operations/async-operation-id.d.ts.map +1 -0
  669. package/dist/tools/operations/async-operation-runtime-tools.d.ts +41 -0
  670. package/dist/tools/operations/async-operation-runtime-tools.d.ts.map +1 -0
  671. package/dist/tools/operations/async-operation-runtime-types.d.ts +69 -0
  672. package/dist/tools/operations/async-operation-runtime-types.d.ts.map +1 -0
  673. package/dist/tools/operations/async-operation-runtime.d.ts +5 -0
  674. package/dist/tools/operations/async-operation-runtime.d.ts.map +1 -0
  675. package/dist/tools/operations/define-wait-tool.d.ts +22 -0
  676. package/dist/tools/operations/define-wait-tool.d.ts.map +1 -0
  677. package/dist/tools/operations/mount-wait.d.ts.map +1 -0
  678. package/dist/tools/operations/wait-core.d.ts.map +1 -0
  679. package/dist/tools/remote.d.ts +1 -1
  680. package/dist/tools/remote.d.ts.map +1 -1
  681. package/dist/tools/runtime-tool.d.ts +13 -4
  682. package/dist/tools/runtime-tool.d.ts.map +1 -1
  683. package/dist/tools/schema/coerce.d.ts.map +1 -0
  684. package/dist/tools/schema/flatten-join.d.ts.map +1 -0
  685. package/dist/tools/schema/flatten.d.ts.map +1 -0
  686. package/dist/tools/schema/portable-formats.d.ts.map +1 -0
  687. package/dist/tools/schema/presentation.d.ts +24 -0
  688. package/dist/tools/schema/presentation.d.ts.map +1 -0
  689. package/dist/tools/schema/schema.d.ts.map +1 -0
  690. package/dist/tools/schema/untyped-properties.d.ts.map +1 -0
  691. package/dist/tools/surface.d.ts +2 -3
  692. package/dist/tools/surface.d.ts.map +1 -1
  693. package/dist/tools/tool-logger.d.ts +1 -1
  694. package/dist/tools/tool-logger.d.ts.map +1 -1
  695. package/dist/tools/toolkit.d.ts +4 -4
  696. package/dist/tools/toolkit.d.ts.map +1 -1
  697. package/dist/tools/transfer/define-download-tool.d.ts +18 -0
  698. package/dist/tools/transfer/define-download-tool.d.ts.map +1 -0
  699. package/dist/tools/transfer/define-upload-tool.d.ts +16 -0
  700. package/dist/tools/transfer/define-upload-tool.d.ts.map +1 -0
  701. package/dist/tools/transfer/define-view-file-tool.d.ts +10 -0
  702. package/dist/tools/transfer/define-view-file-tool.d.ts.map +1 -0
  703. package/dist/tools/transfer/download-core.d.ts +20 -0
  704. package/dist/tools/transfer/download-core.d.ts.map +1 -0
  705. package/dist/tools/transfer/managed-file-error.d.ts +6 -0
  706. package/dist/tools/transfer/managed-file-error.d.ts.map +1 -0
  707. package/dist/tools/transfer/mount-download.d.ts +41 -0
  708. package/dist/tools/transfer/mount-download.d.ts.map +1 -0
  709. package/dist/tools/transfer/mount-upload.d.ts +21 -0
  710. package/dist/tools/transfer/mount-upload.d.ts.map +1 -0
  711. package/dist/tools/transfer/native-result.d.ts.map +1 -0
  712. package/dist/tools/transfer/upload-core.d.ts +4 -0
  713. package/dist/tools/transfer/upload-core.d.ts.map +1 -0
  714. package/dist/tools/transfer/view-file-contract.d.ts.map +1 -0
  715. package/dist/tools/transfer/view-file.d.ts +62 -0
  716. package/dist/tools/transfer/view-file.d.ts.map +1 -0
  717. package/dist/tools/transports.d.ts +1 -1
  718. package/dist/tools/transports.d.ts.map +1 -1
  719. package/dist/tracking/client-listeners.d.ts +30 -0
  720. package/dist/tracking/client-listeners.d.ts.map +1 -0
  721. package/dist/tracking/client-visit.d.ts +61 -0
  722. package/dist/tracking/client-visit.d.ts.map +1 -0
  723. package/dist/tracking/client.d.ts +3 -2
  724. package/dist/tracking/client.d.ts.map +1 -1
  725. package/dist/tracking/contract.d.ts +1 -1
  726. package/dist/tracking/contract.d.ts.map +1 -1
  727. package/llms/agent-runtime-browser.txt +33 -0
  728. package/llms/agent-runtime-coding-tools.txt +58 -0
  729. package/llms/agent-runtime-harness.txt +45 -0
  730. package/llms/agent-runtime-openrouter.txt +22 -0
  731. package/llms/agent-runtime-sandbox.txt +159 -0
  732. package/llms/agent-runtime-sqlite-bun.txt +29 -0
  733. package/llms/agent-runtime-sqlite-node.txt +26 -0
  734. package/llms/agent-runtime-testing.txt +30 -0
  735. package/llms/agent-runtime.2.txt +550 -0
  736. package/llms/agent-runtime.3.txt +311 -0
  737. package/llms/agent-runtime.txt +893 -0
  738. package/llms/application-diagnostic-journal.txt +30 -0
  739. package/llms/application-grammy.txt +27 -0
  740. package/llms/application-opentelemetry.txt +27 -0
  741. package/llms/application-schemas.txt +42 -0
  742. package/llms/application.2.txt +487 -0
  743. package/llms/application.txt +886 -0
  744. package/llms/cli.2.txt +80 -0
  745. package/llms/cli.txt +948 -0
  746. package/llms/contract.txt +606 -0
  747. package/llms/declaration.txt +286 -0
  748. package/llms/files.txt +33 -0
  749. package/llms/geo.txt +114 -0
  750. package/llms/google.txt +27 -0
  751. package/llms/live.txt +471 -0
  752. package/llms/node.txt +43 -0
  753. package/llms/oauth.txt +136 -0
  754. package/llms/observability.txt +893 -0
  755. package/llms/primitives.txt +158 -0
  756. package/llms/react.txt +184 -0
  757. package/llms/release.txt +176 -0
  758. package/llms/remote.txt +25 -0
  759. package/llms/server.2.txt +361 -0
  760. package/llms/server.3.txt +1031 -0
  761. package/llms/server.4.txt +905 -0
  762. package/llms/server.5.txt +250 -0
  763. package/llms/server.txt +996 -0
  764. package/llms/stitchkit.2.txt +836 -0
  765. package/llms/stitchkit.3.txt +147 -0
  766. package/llms/stitchkit.txt +260 -0
  767. package/llms/telegram.txt +30 -0
  768. package/llms/testing.txt +676 -0
  769. package/llms/tools-connections.txt +45 -0
  770. package/llms/tools-contract.txt +9 -0
  771. package/llms/tools-invoker.txt +9 -0
  772. package/llms/tools.2.txt +647 -0
  773. package/llms/tools.3.txt +288 -0
  774. package/llms/tools.txt +966 -0
  775. package/llms/tracking-server.txt +32 -0
  776. package/llms/tracking.txt +263 -0
  777. package/llms/upgrading-0.37.0-0.50.0.txt +947 -0
  778. package/llms/upgrading-0.53.0-0.67.0.txt +1174 -0
  779. package/llms/upgrading-0.68.0-0.94.0.txt +1159 -0
  780. package/llms/upgrading.txt +215 -0
  781. package/llms-full.txt +312 -77
  782. package/llms.txt +54 -5
  783. package/package.json +84 -83
  784. package/dist/agent-runtime/durability-contract.d.ts +0 -176
  785. package/dist/agent-runtime/durability-contract.d.ts.map +0 -1
  786. package/dist/agent-runtime/durability-json.d.ts +0 -3
  787. package/dist/agent-runtime/durability-json.d.ts.map +0 -1
  788. package/dist/agent-runtime/durability-ledger.d.ts +0 -16
  789. package/dist/agent-runtime/durability-ledger.d.ts.map +0 -1
  790. package/dist/agent-runtime/durability-scheduler.d.ts +0 -29
  791. package/dist/agent-runtime/durability-scheduler.d.ts.map +0 -1
  792. package/dist/agent-runtime/durability.d.ts +0 -14
  793. package/dist/agent-runtime/durability.d.ts.map +0 -1
  794. package/dist/agent-runtime/store-driver.d.ts +0 -814
  795. package/dist/agent-runtime/store-driver.d.ts.map +0 -1
  796. package/dist/agent-runtime-browser.d.ts +0 -5
  797. package/dist/agent-runtime-browser.d.ts.map +0 -1
  798. package/dist/agent-runtime-browser.js +0 -124
  799. package/dist/agent-runtime-coding-tools.d.ts +0 -2
  800. package/dist/agent-runtime-coding-tools.d.ts.map +0 -1
  801. package/dist/agent-runtime-coding-tools.js +0 -23
  802. package/dist/agent-runtime-harness.d.ts +0 -2
  803. package/dist/agent-runtime-harness.d.ts.map +0 -1
  804. package/dist/agent-runtime-harness.js +0 -729
  805. package/dist/agent-runtime-openrouter.d.ts +0 -29
  806. package/dist/agent-runtime-openrouter.d.ts.map +0 -1
  807. package/dist/agent-runtime-openrouter.js +0 -270
  808. package/dist/agent-runtime-sandbox.d.ts +0 -5
  809. package/dist/agent-runtime-sandbox.d.ts.map +0 -1
  810. package/dist/agent-runtime-sandbox.js +0 -798
  811. package/dist/agent-runtime-sqlite-bun.d.ts +0 -11
  812. package/dist/agent-runtime-sqlite-bun.d.ts.map +0 -1
  813. package/dist/agent-runtime-sqlite-bun.js +0 -42
  814. package/dist/agent-runtime-sqlite-node.d.ts +0 -11
  815. package/dist/agent-runtime-sqlite-node.d.ts.map +0 -1
  816. package/dist/agent-runtime-sqlite-node.js +0 -44
  817. package/dist/agent-runtime-testing.d.ts +0 -3
  818. package/dist/agent-runtime-testing.d.ts.map +0 -1
  819. package/dist/agent-runtime-testing.js +0 -156
  820. package/dist/agent-runtime.d.ts +0 -38
  821. package/dist/agent-runtime.d.ts.map +0 -1
  822. package/dist/agent-runtime.js +0 -2607
  823. package/dist/application/channel.d.ts.map +0 -1
  824. package/dist/application-diagnostic-journal.d.ts +0 -21
  825. package/dist/application-diagnostic-journal.d.ts.map +0 -1
  826. package/dist/application-diagnostic-journal.js +0 -632
  827. package/dist/application-grammy.d.ts +0 -2
  828. package/dist/application-grammy.d.ts.map +0 -1
  829. package/dist/application-grammy.js +0 -169
  830. package/dist/application-opentelemetry.d.ts +0 -2
  831. package/dist/application-opentelemetry.d.ts.map +0 -1
  832. package/dist/application-opentelemetry.js +0 -250
  833. package/dist/application-schemas.d.ts +0 -15
  834. package/dist/application-schemas.d.ts.map +0 -1
  835. package/dist/application-schemas.js +0 -27
  836. package/dist/application.d.ts +0 -22
  837. package/dist/application.d.ts.map +0 -1
  838. package/dist/application.js +0 -1977
  839. package/dist/cli.d.ts +0 -41
  840. package/dist/cli.d.ts.map +0 -1
  841. package/dist/cli.js +0 -753
  842. package/dist/contract/index.d.ts +0 -8
  843. package/dist/contract/index.d.ts.map +0 -1
  844. package/dist/contract/index.js +0 -55
  845. package/dist/declaration.d.ts.map +0 -1
  846. package/dist/declaration.js +0 -183
  847. package/dist/files.d.ts +0 -3
  848. package/dist/files.d.ts.map +0 -1
  849. package/dist/files.js +0 -15
  850. package/dist/geo.d.ts +0 -3
  851. package/dist/geo.d.ts.map +0 -1
  852. package/dist/geo.js +0 -245
  853. package/dist/google.d.ts.map +0 -1
  854. package/dist/google.js +0 -175
  855. package/dist/index-0a349c33.js +0 -470
  856. package/dist/index-0j3vcp5m.js +0 -28
  857. package/dist/index-2c2bjw3s.js +0 -51
  858. package/dist/index-2na0qrfn.js +0 -214
  859. package/dist/index-2qzskm8h.js +0 -63
  860. package/dist/index-3bmnp41g.js +0 -2169
  861. package/dist/index-3xwxfj4z.js +0 -334
  862. package/dist/index-4fpa9dy2.js +0 -51
  863. package/dist/index-6kyksz9y.js +0 -268
  864. package/dist/index-77fekveh.js +0 -44
  865. package/dist/index-7gnkny4z.js +0 -326
  866. package/dist/index-7zbps32p.js +0 -89
  867. package/dist/index-9f8ztey6.js +0 -588
  868. package/dist/index-a11g2kry.js +0 -866
  869. package/dist/index-a916km3r.js +0 -45
  870. package/dist/index-actkayzn.js +0 -367
  871. package/dist/index-bn2cjajt.js +0 -524
  872. package/dist/index-bx75zwt7.js +0 -63
  873. package/dist/index-cby4ar3v.js +0 -46
  874. package/dist/index-cnyk6te3.js +0 -77
  875. package/dist/index-cxqhvq21.js +0 -413
  876. package/dist/index-e0znv5gn.js +0 -176
  877. package/dist/index-e42wzzz5.js +0 -154
  878. package/dist/index-f477k430.js +0 -324
  879. package/dist/index-f9mb610r.js +0 -177
  880. package/dist/index-fadnxwna.js +0 -1046
  881. package/dist/index-fq77yfzc.js +0 -1303
  882. package/dist/index-h9etkkyk.js +0 -1126
  883. package/dist/index-hrbajay7.js +0 -1196
  884. package/dist/index-kw9t5ayn.js +0 -507
  885. package/dist/index-mzvgxp0n.js +0 -80
  886. package/dist/index-n0f51dfn.js +0 -3170
  887. package/dist/index-p13mwz16.js +0 -16
  888. package/dist/index-s8cnx02s.js +0 -90
  889. package/dist/index-sr93cwf9.js +0 -325
  890. package/dist/index-tmwcrptx.js +0 -85
  891. package/dist/index-v5573g1k.js +0 -142
  892. package/dist/index-vjpvjqpn.js +0 -86
  893. package/dist/index-vk3kq9sb.js +0 -3344
  894. package/dist/index-wc4x00bn.js +0 -103
  895. package/dist/index-wnfk50r0.js +0 -211
  896. package/dist/index-yewwh1w4.js +0 -647
  897. package/dist/index-yn8remb1.js +0 -290
  898. package/dist/index-ywd0y6m1.js +0 -394
  899. package/dist/index-zwkgfq1s.js +0 -345
  900. package/dist/index.d.ts +0 -14
  901. package/dist/index.d.ts.map +0 -1
  902. package/dist/index.js +0 -632
  903. package/dist/internal/errors.d.ts +0 -92
  904. package/dist/internal/errors.d.ts.map +0 -1
  905. package/dist/internal/observability-sink.d.ts +0 -81
  906. package/dist/internal/observability-sink.d.ts.map +0 -1
  907. package/dist/live.d.ts +0 -19
  908. package/dist/live.d.ts.map +0 -1
  909. package/dist/live.js +0 -282
  910. package/dist/logger.d.ts.map +0 -1
  911. package/dist/node.d.ts +0 -18
  912. package/dist/node.d.ts.map +0 -1
  913. package/dist/node.js +0 -303
  914. package/dist/oauth.d.ts +0 -57
  915. package/dist/oauth.d.ts.map +0 -1
  916. package/dist/oauth.js +0 -170
  917. package/dist/observability/index.d.ts +0 -19
  918. package/dist/observability/index.d.ts.map +0 -1
  919. package/dist/observability/index.js +0 -569
  920. package/dist/primitives.d.ts +0 -3
  921. package/dist/primitives.d.ts.map +0 -1
  922. package/dist/primitives.js +0 -754
  923. package/dist/react.d.ts +0 -5
  924. package/dist/react.d.ts.map +0 -1
  925. package/dist/react.js +0 -403
  926. package/dist/release.d.ts +0 -15
  927. package/dist/release.d.ts.map +0 -1
  928. package/dist/release.js +0 -196
  929. package/dist/remote.d.ts +0 -9
  930. package/dist/remote.d.ts.map +0 -1
  931. package/dist/remote.js +0 -88
  932. package/dist/retained.d.ts.map +0 -1
  933. package/dist/server/file-state-store.d.ts +0 -23
  934. package/dist/server/file-state-store.d.ts.map +0 -1
  935. package/dist/server/index.d.ts +0 -36
  936. package/dist/server/index.d.ts.map +0 -1
  937. package/dist/server/index.js +0 -1745
  938. package/dist/server/request.d.ts.map +0 -1
  939. package/dist/telegram.d.ts +0 -3
  940. package/dist/telegram.d.ts.map +0 -1
  941. package/dist/telegram.js +0 -224
  942. package/dist/testing/agent-store-conformance.d.ts +0 -40
  943. package/dist/testing/agent-store-conformance.d.ts.map +0 -1
  944. package/dist/testing.d.ts +0 -39
  945. package/dist/testing.d.ts.map +0 -1
  946. package/dist/testing.js +0 -2209
  947. package/dist/tool-invoker.d.ts +0 -9
  948. package/dist/tool-invoker.d.ts.map +0 -1
  949. package/dist/tool-invoker.js +0 -21
  950. package/dist/tools/async-operation-contract.d.ts.map +0 -1
  951. package/dist/tools/async-operation.d.ts +0 -332
  952. package/dist/tools/async-operation.d.ts.map +0 -1
  953. package/dist/tools/cli-args.d.ts +0 -143
  954. package/dist/tools/cli-args.d.ts.map +0 -1
  955. package/dist/tools/cli-checkpoint.d.ts +0 -24
  956. package/dist/tools/cli-checkpoint.d.ts.map +0 -1
  957. package/dist/tools/cli-command.d.ts +0 -70
  958. package/dist/tools/cli-command.d.ts.map +0 -1
  959. package/dist/tools/cli-format.d.ts +0 -49
  960. package/dist/tools/cli-format.d.ts.map +0 -1
  961. package/dist/tools/cli-installer.d.ts +0 -34
  962. package/dist/tools/cli-installer.d.ts.map +0 -1
  963. package/dist/tools/cli-invoke.d.ts +0 -143
  964. package/dist/tools/cli-invoke.d.ts.map +0 -1
  965. package/dist/tools/cli-manifest.d.ts +0 -80
  966. package/dist/tools/cli-manifest.d.ts.map +0 -1
  967. package/dist/tools/cli-policy.d.ts +0 -27
  968. package/dist/tools/cli-policy.d.ts.map +0 -1
  969. package/dist/tools/cli-profile.d.ts +0 -40
  970. package/dist/tools/cli-profile.d.ts.map +0 -1
  971. package/dist/tools/cli-signature.d.ts +0 -81
  972. package/dist/tools/cli-signature.d.ts.map +0 -1
  973. package/dist/tools/cli-stream.d.ts +0 -93
  974. package/dist/tools/cli-stream.d.ts.map +0 -1
  975. package/dist/tools/cli-update.d.ts +0 -126
  976. package/dist/tools/cli-update.d.ts.map +0 -1
  977. package/dist/tools/cli-view.d.ts +0 -12
  978. package/dist/tools/cli-view.d.ts.map +0 -1
  979. package/dist/tools/cli-wait.d.ts +0 -54
  980. package/dist/tools/cli-wait.d.ts.map +0 -1
  981. package/dist/tools/cli.d.ts +0 -94
  982. package/dist/tools/cli.d.ts.map +0 -1
  983. package/dist/tools/coerce.d.ts.map +0 -1
  984. package/dist/tools/connections/index.d.ts +0 -20
  985. package/dist/tools/connections/index.d.ts.map +0 -1
  986. package/dist/tools/connections/index.js +0 -1107
  987. package/dist/tools/define-download-tool.d.ts +0 -18
  988. package/dist/tools/define-download-tool.d.ts.map +0 -1
  989. package/dist/tools/define-upload-tool.d.ts +0 -16
  990. package/dist/tools/define-upload-tool.d.ts.map +0 -1
  991. package/dist/tools/define-view-file-tool.d.ts +0 -10
  992. package/dist/tools/define-view-file-tool.d.ts.map +0 -1
  993. package/dist/tools/define-wait-tool.d.ts +0 -22
  994. package/dist/tools/define-wait-tool.d.ts.map +0 -1
  995. package/dist/tools/download-core.d.ts +0 -20
  996. package/dist/tools/download-core.d.ts.map +0 -1
  997. package/dist/tools/flatten-join.d.ts.map +0 -1
  998. package/dist/tools/flatten.d.ts.map +0 -1
  999. package/dist/tools/json-schema-dialect.d.ts +0 -17
  1000. package/dist/tools/json-schema-dialect.d.ts.map +0 -1
  1001. package/dist/tools/json-schema.d.ts.map +0 -1
  1002. package/dist/tools/managed-file-error.d.ts +0 -6
  1003. package/dist/tools/managed-file-error.d.ts.map +0 -1
  1004. package/dist/tools/mcp-app.d.ts +0 -62
  1005. package/dist/tools/mcp-app.d.ts.map +0 -1
  1006. package/dist/tools/mcp-catalog.d.ts +0 -68
  1007. package/dist/tools/mcp-catalog.d.ts.map +0 -1
  1008. package/dist/tools/mcp-handler.d.ts +0 -46
  1009. package/dist/tools/mcp-handler.d.ts.map +0 -1
  1010. package/dist/tools/mcp-prepare.d.ts +0 -75
  1011. package/dist/tools/mcp-prepare.d.ts.map +0 -1
  1012. package/dist/tools/mcp-progress.d.ts +0 -46
  1013. package/dist/tools/mcp-progress.d.ts.map +0 -1
  1014. package/dist/tools/mcp-round-policy.d.ts +0 -33
  1015. package/dist/tools/mcp-round-policy.d.ts.map +0 -1
  1016. package/dist/tools/mcp-round.d.ts +0 -61
  1017. package/dist/tools/mcp-round.d.ts.map +0 -1
  1018. package/dist/tools/mcp-stdio-signals.d.ts +0 -33
  1019. package/dist/tools/mcp-stdio-signals.d.ts.map +0 -1
  1020. package/dist/tools/mcp-stdio.d.ts +0 -20
  1021. package/dist/tools/mcp-stdio.d.ts.map +0 -1
  1022. package/dist/tools/mcp-trace.d.ts +0 -12
  1023. package/dist/tools/mcp-trace.d.ts.map +0 -1
  1024. package/dist/tools/mcp.d.ts +0 -152
  1025. package/dist/tools/mcp.d.ts.map +0 -1
  1026. package/dist/tools/mount-download.d.ts +0 -41
  1027. package/dist/tools/mount-download.d.ts.map +0 -1
  1028. package/dist/tools/mount-upload.d.ts +0 -21
  1029. package/dist/tools/mount-upload.d.ts.map +0 -1
  1030. package/dist/tools/mount-wait.d.ts.map +0 -1
  1031. package/dist/tools/native-mcp.d.ts +0 -20
  1032. package/dist/tools/native-mcp.d.ts.map +0 -1
  1033. package/dist/tools/native-result.d.ts.map +0 -1
  1034. package/dist/tools/oauth-metadata.d.ts +0 -28
  1035. package/dist/tools/oauth-metadata.d.ts.map +0 -1
  1036. package/dist/tools/oauth-provider.d.ts +0 -184
  1037. package/dist/tools/oauth-provider.d.ts.map +0 -1
  1038. package/dist/tools/portable-formats.d.ts.map +0 -1
  1039. package/dist/tools/presentation.d.ts +0 -22
  1040. package/dist/tools/presentation.d.ts.map +0 -1
  1041. package/dist/tools/schema.d.ts.map +0 -1
  1042. package/dist/tools/untyped-properties.d.ts.map +0 -1
  1043. package/dist/tools/upload-core.d.ts +0 -4
  1044. package/dist/tools/upload-core.d.ts.map +0 -1
  1045. package/dist/tools/view-file-contract.d.ts.map +0 -1
  1046. package/dist/tools/view-file.d.ts +0 -62
  1047. package/dist/tools/view-file.d.ts.map +0 -1
  1048. package/dist/tools/wait-core.d.ts.map +0 -1
  1049. package/dist/tools-contract.d.ts +0 -29
  1050. package/dist/tools-contract.d.ts.map +0 -1
  1051. package/dist/tools-contract.js +0 -24
  1052. package/dist/tools.d.ts +0 -50
  1053. package/dist/tools.d.ts.map +0 -1
  1054. package/dist/tools.js +0 -2930
  1055. package/dist/tracking-server.d.ts +0 -15
  1056. package/dist/tracking-server.d.ts.map +0 -1
  1057. package/dist/tracking.d.ts +0 -24
  1058. package/dist/tracking.d.ts.map +0 -1
  1059. package/dist/tracking.js +0 -1092
  1060. package/dist/upgrade-cli.d.ts.map +0 -1
  1061. package/dist/upgrade-cli.js +0 -177
  1062. /package/dist/{retained.d.ts → browser/retained.d.ts} +0 -0
  1063. /package/dist/{declaration.d.ts → declaration/declaration.d.ts} +0 -0
  1064. /package/dist/{upgrade-cli.d.ts → entrypoints/bin/upgrade-cli.d.ts} +0 -0
  1065. /package/dist/{tracking-server.js → entrypoints/tracking/server.js} +0 -0
  1066. /package/dist/{google.d.ts → google/google.d.ts} +0 -0
  1067. /package/dist/{index-pq95qkbf.js → index-5jm36zv1.js} +0 -0
  1068. /package/dist/{application → internal}/channel.d.ts +0 -0
  1069. /package/dist/{logger.d.ts → internal/logger.d.ts} +0 -0
  1070. /package/dist/{server → internal}/request.d.ts +0 -0
  1071. /package/dist/{tools → json-schema}/json-schema.d.ts +0 -0
  1072. /package/dist/tools/{async-operation-contract.d.ts → operations/async-operation-contract.d.ts} +0 -0
  1073. /package/dist/tools/{mount-wait.d.ts → operations/mount-wait.d.ts} +0 -0
  1074. /package/dist/tools/{wait-core.d.ts → operations/wait-core.d.ts} +0 -0
  1075. /package/dist/tools/{coerce.d.ts → schema/coerce.d.ts} +0 -0
  1076. /package/dist/tools/{flatten-join.d.ts → schema/flatten-join.d.ts} +0 -0
  1077. /package/dist/tools/{flatten.d.ts → schema/flatten.d.ts} +0 -0
  1078. /package/dist/tools/{portable-formats.d.ts → schema/portable-formats.d.ts} +0 -0
  1079. /package/dist/tools/{schema.d.ts → schema/schema.d.ts} +0 -0
  1080. /package/dist/tools/{untyped-properties.d.ts → schema/untyped-properties.d.ts} +0 -0
  1081. /package/dist/tools/{native-result.d.ts → transfer/native-result.d.ts} +0 -0
  1082. /package/dist/tools/{view-file-contract.d.ts → transfer/view-file-contract.d.ts} +0 -0
@@ -0,0 +1,3493 @@
1
+ import {
2
+ RELEASE_HEADER
3
+ } from "./index-y91ry9h2.js";
4
+ import {
5
+ ShutdownOptionsSchema,
6
+ isStreamCancellation,
7
+ ownHttpStream,
8
+ settleStreamCleanup
9
+ } from "./index-3z73fh2c.js";
10
+ import {
11
+ createValidatedRealtimeSocket,
12
+ isModuleNotFound
13
+ } from "./index-ndddxtyx.js";
14
+ import {
15
+ DEFAULT_CONTRACT_STREAM_FRAME_BYTES
16
+ } from "./index-wqgjfstn.js";
17
+ import {
18
+ DEFAULT_PROCESS_SIGNALS,
19
+ applyCors,
20
+ assertCorsConfig,
21
+ bindContract,
22
+ corsPreflightResponse,
23
+ defaultSignalSource,
24
+ guardSignalCallback,
25
+ isOriginAllowed,
26
+ mediaTypeEssence,
27
+ reportSignalError,
28
+ requestCorsHeaders
29
+ } from "./index-2gxzjvyr.js";
30
+ import {
31
+ joinRoutePath,
32
+ parseTrailingWildcard
33
+ } from "./index-4gcnakhx.js";
34
+ import {
35
+ getRequestContext,
36
+ runWithRequestContext,
37
+ setRequestEndpoint,
38
+ setRequestError
39
+ } from "./index-zfrhfn82.js";
40
+ import {
41
+ extractIp,
42
+ getClientInfo,
43
+ parseQueryParams,
44
+ resolveSocketIp,
45
+ resolveTraceId
46
+ } from "./index-35mh5bhj.js";
47
+ import {
48
+ resolveTraceContext
49
+ } from "./index-zcgf3gqf.js";
50
+ import {
51
+ errorCode,
52
+ normalizeError,
53
+ recordedErrorMessage,
54
+ validateDeclaredOutput
55
+ } from "./index-znfs20ss.js";
56
+ import {
57
+ AppError,
58
+ badRequest,
59
+ forbidden
60
+ } from "./index-2vtcmrj9.js";
61
+ import {
62
+ isUnsafeKey,
63
+ safeJsonParse
64
+ } from "./index-kzfs85xp.js";
65
+ import {
66
+ isRecord,
67
+ transportResult
68
+ } from "./index-hffjpmq9.js";
69
+
70
+ // src/server/multipart-reader.ts
71
+ var DEFAULT_MAX_HEADER_BYTES = 64 * 1024;
72
+ var CRLF = new Uint8Array([13, 10]);
73
+ var HEADER_END = new Uint8Array([13, 10, 13, 10]);
74
+ var decoder = new TextDecoder;
75
+ var headerDecoder = new TextDecoder("utf-8", { fatal: true });
76
+ var encoder = new TextEncoder;
77
+ var TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
78
+ function hasControl(value, allowTab = false) {
79
+ for (let index = 0;index < value.length; index++) {
80
+ const code = value.charCodeAt(index);
81
+ if (code < 32 && !(allowTab && code === 9) || code === 127)
82
+ return true;
83
+ }
84
+ return false;
85
+ }
86
+ function trimWhitespace(value) {
87
+ return value.replace(/^[ \t]+|[ \t]+$/g, "");
88
+ }
89
+ function indexOfBytes(haystack, needle) {
90
+ outer:
91
+ for (let index = 0;index <= haystack.length - needle.length; index += 1) {
92
+ for (let offset = 0;offset < needle.length; offset += 1) {
93
+ if (haystack[index + offset] !== needle[offset])
94
+ continue outer;
95
+ }
96
+ return index;
97
+ }
98
+ return -1;
99
+ }
100
+ function startsWithBytes(value, prefix) {
101
+ if (value.length < prefix.length)
102
+ return false;
103
+ for (let index = 0;index < prefix.length; index += 1) {
104
+ if (value[index] !== prefix[index])
105
+ return false;
106
+ }
107
+ return true;
108
+ }
109
+ function concatBytes(left, right) {
110
+ if (left.length === 0)
111
+ return right.slice();
112
+ if (right.length === 0)
113
+ return left.slice();
114
+ const joined = new Uint8Array(left.length + right.length);
115
+ joined.set(left);
116
+ joined.set(right, left.length);
117
+ return joined;
118
+ }
119
+ function parseBoundary(req) {
120
+ const contentType = req.headers.get("content-type") ?? "";
121
+ if (!contentType.toLowerCase().startsWith("multipart/form-data")) {
122
+ badRequest("Request body must be multipart/form-data");
123
+ }
124
+ const match = /(?:^|;)\s*boundary=(?:"([^"]+)"|([^;\s]+))/i.exec(contentType);
125
+ const boundary = match?.[1] ?? match?.[2];
126
+ if (!boundary || boundary.length > 200)
127
+ badRequest("Invalid multipart boundary");
128
+ return boundary;
129
+ }
130
+ function parseDisposition(value) {
131
+ if (!value)
132
+ badRequest("Invalid multipart disposition");
133
+ const separator = value.indexOf(";");
134
+ const kind = separator < 0 ? value : value.slice(0, separator);
135
+ if (trimWhitespace(kind).toLowerCase() !== "form-data") {
136
+ badRequest("Invalid multipart disposition");
137
+ }
138
+ const parameters = new Map;
139
+ let rest = separator < 0 ? "" : value.slice(separator);
140
+ while (rest.length > 0) {
141
+ const match = /^;[ \t]*([^=; \t]+)[ \t]*=[ \t]*(?:"((?:[^"\\]|\\.)*)"|([^; \t]+))[ \t]*/.exec(rest);
142
+ if (!match?.[1])
143
+ badRequest("Invalid multipart disposition parameter");
144
+ const key = match[1].toLowerCase();
145
+ if (!TOKEN.test(key) || parameters.has(key)) {
146
+ badRequest("Invalid or duplicate multipart disposition parameter");
147
+ }
148
+ const quoted = match[2];
149
+ const raw = match[3] ?? "";
150
+ if (quoted === undefined && !TOKEN.test(raw)) {
151
+ badRequest("Invalid multipart disposition parameter");
152
+ }
153
+ const decoded = quoted === undefined ? raw : quoted.replace(/\\(.)/g, "$1");
154
+ if (hasControl(decoded))
155
+ badRequest("Invalid multipart disposition parameter");
156
+ parameters.set(key, decoded);
157
+ rest = rest.slice(match[0].length);
158
+ }
159
+ const name = parameters.get("name");
160
+ let filename = parameters.get("filename");
161
+ const extended = parameters.get("filename*");
162
+ if (extended !== undefined) {
163
+ const match = /^utf-8'[A-Za-z0-9-]*'((?:[!#$&+.^_`|~0-9A-Za-z-]|%[0-9A-Fa-f]{2})*)$/i.exec(extended);
164
+ if (!match)
165
+ badRequest("Invalid multipart extended filename");
166
+ try {
167
+ filename = decodeURIComponent(match[1] ?? "");
168
+ } catch {
169
+ badRequest("Invalid multipart extended filename");
170
+ }
171
+ if (hasControl(filename))
172
+ badRequest("Invalid multipart extended filename");
173
+ }
174
+ if (!name || isUnsafeKey(name))
175
+ badRequest("Invalid multipart field name");
176
+ return filename === undefined ? { name } : { name, filename };
177
+ }
178
+ function parsePartHeaders(bytes) {
179
+ let text;
180
+ try {
181
+ text = headerDecoder.decode(bytes);
182
+ } catch {
183
+ badRequest("Invalid multipart headers");
184
+ }
185
+ const headers = new Map;
186
+ for (const line of text.split(`\r
187
+ `)) {
188
+ const separator = line.indexOf(":");
189
+ if (separator <= 0)
190
+ badRequest("Invalid multipart header");
191
+ const name = line.slice(0, separator).toLowerCase();
192
+ const value = trimWhitespace(line.slice(separator + 1));
193
+ if (!TOKEN.test(name) || hasControl(value, true)) {
194
+ badRequest("Invalid multipart header");
195
+ }
196
+ if (headers.has(name))
197
+ badRequest("Duplicate multipart header");
198
+ headers.set(name, value);
199
+ }
200
+ const disposition = parseDisposition(headers.get("content-disposition") ?? undefined);
201
+ const rawContentType = headers.get("content-type");
202
+ const contentType = rawContentType?.split(";", 1)[0]?.trim().toLowerCase();
203
+ const rawSize = headers.get("content-length");
204
+ if (rawSize !== undefined && !/^[0-9]+$/.test(rawSize)) {
205
+ badRequest("Invalid multipart part content-length");
206
+ }
207
+ const declaredSize = rawSize === undefined ? undefined : Number(rawSize);
208
+ if (declaredSize !== undefined && (!Number.isSafeInteger(declaredSize) || declaredSize < 0)) {
209
+ badRequest("Invalid multipart part content-length");
210
+ }
211
+ return { ...disposition, contentType, declaredSize };
212
+ }
213
+
214
+ class MultipartStreamReader {
215
+ #reader;
216
+ #delimiter;
217
+ #initialBoundary;
218
+ #maxRequestBytes;
219
+ #buffer = new Uint8Array;
220
+ #readBytes = 0;
221
+ #sourceDone = false;
222
+ #terminal = false;
223
+ #activePart = false;
224
+ constructor(req, boundary, maxRequestBytes) {
225
+ if (!req.body)
226
+ badRequest("Multipart request body is empty");
227
+ this.#reader = req.body.getReader();
228
+ this.#delimiter = encoder.encode(`\r
229
+ --${boundary}`);
230
+ this.#initialBoundary = encoder.encode(`--${boundary}`);
231
+ this.#maxRequestBytes = maxRequestBytes;
232
+ }
233
+ async start() {
234
+ await this.#ensure(this.#initialBoundary.length + 2);
235
+ if (!startsWithBytes(this.#buffer, this.#initialBoundary)) {
236
+ badRequest("Malformed multipart body");
237
+ }
238
+ this.#consume(this.#initialBoundary.length);
239
+ await this.#consumeBoundarySuffix();
240
+ }
241
+ async nextPart() {
242
+ if (this.#activePart)
243
+ badRequest("Multipart part stream was not fully consumed");
244
+ if (this.#terminal)
245
+ return null;
246
+ const header = await this.#readUntil(HEADER_END, DEFAULT_MAX_HEADER_BYTES);
247
+ const parsed = parsePartHeaders(header);
248
+ this.#activePart = true;
249
+ let ended = false;
250
+ const stream = new ReadableStream({
251
+ pull: async (controller) => {
252
+ if (ended) {
253
+ controller.close();
254
+ return;
255
+ }
256
+ try {
257
+ const chunk = await this.#readPartChunk();
258
+ if (chunk.value.length > 0)
259
+ controller.enqueue(chunk.value);
260
+ if (chunk.end) {
261
+ ended = true;
262
+ controller.close();
263
+ }
264
+ } catch (error) {
265
+ controller.error(error);
266
+ this.cancel(error);
267
+ }
268
+ },
269
+ cancel: (reason) => {
270
+ this.cancel(reason);
271
+ }
272
+ });
273
+ return { ...parsed, stream, consumed: () => ended };
274
+ }
275
+ cancel(reason) {
276
+ this.#reader.cancel(reason).catch(() => {});
277
+ }
278
+ release() {
279
+ this.#reader.releaseLock();
280
+ }
281
+ async#readPartChunk() {
282
+ while (true) {
283
+ const boundaryIndex = indexOfBytes(this.#buffer, this.#delimiter);
284
+ if (boundaryIndex >= 0) {
285
+ const value = this.#buffer.slice(0, boundaryIndex);
286
+ this.#consume(boundaryIndex + this.#delimiter.length);
287
+ await this.#consumeBoundarySuffix();
288
+ this.#activePart = false;
289
+ return { value, end: true };
290
+ }
291
+ const retained = this.#delimiter.length - 1;
292
+ if (this.#buffer.length > retained) {
293
+ const emitLength = this.#buffer.length - retained;
294
+ const value = this.#buffer.slice(0, emitLength);
295
+ this.#consume(emitLength);
296
+ return { value, end: false };
297
+ }
298
+ if (this.#sourceDone)
299
+ badRequest("Incomplete multipart body");
300
+ await this.#readMore();
301
+ }
302
+ }
303
+ async#consumeBoundarySuffix() {
304
+ await this.#ensure(2);
305
+ if (this.#buffer[0] === 45 && this.#buffer[1] === 45) {
306
+ this.#consume(2);
307
+ this.#terminal = true;
308
+ if (startsWithBytes(this.#buffer, CRLF))
309
+ this.#consume(2);
310
+ return;
311
+ }
312
+ if (!startsWithBytes(this.#buffer, CRLF))
313
+ badRequest("Malformed multipart boundary");
314
+ this.#consume(2);
315
+ }
316
+ async#readUntil(marker, maxBytes) {
317
+ while (true) {
318
+ const index = indexOfBytes(this.#buffer, marker);
319
+ if (index >= 0) {
320
+ if (index > maxBytes)
321
+ badRequest("Multipart part headers are too large");
322
+ const value = this.#buffer.slice(0, index);
323
+ this.#consume(index + marker.length);
324
+ return value;
325
+ }
326
+ if (this.#buffer.length > maxBytes)
327
+ badRequest("Multipart part headers are too large");
328
+ if (this.#sourceDone)
329
+ badRequest("Incomplete multipart headers");
330
+ await this.#readMore();
331
+ }
332
+ }
333
+ async#ensure(length) {
334
+ while (this.#buffer.length < length && !this.#sourceDone)
335
+ await this.#readMore();
336
+ if (this.#buffer.length < length)
337
+ badRequest("Incomplete multipart body");
338
+ }
339
+ async#readMore() {
340
+ const result = await this.#reader.read();
341
+ if (result.done) {
342
+ this.#sourceDone = true;
343
+ return;
344
+ }
345
+ this.#readBytes += result.value.length;
346
+ if (this.#readBytes > this.#maxRequestBytes) {
347
+ this.cancel();
348
+ badRequest(`Multipart request exceeds ${this.#maxRequestBytes} bytes`);
349
+ }
350
+ this.#buffer = concatBytes(this.#buffer, result.value);
351
+ }
352
+ #consume(length) {
353
+ this.#buffer = this.#buffer.slice(length);
354
+ }
355
+ }
356
+
357
+ // src/server/multipart.ts
358
+ var DEFAULT_MAX_REQUEST_BYTES = 25 * 1024 * 1024;
359
+ var DEFAULT_MAX_FIELD_BYTES = 1024 * 1024;
360
+ var DEFAULT_MAX_PARTS = 1000;
361
+ function matchesContentType(contentType, accepted) {
362
+ const normalized = contentType.toLowerCase();
363
+ return accepted.some((candidate) => {
364
+ const policy = candidate.toLowerCase();
365
+ return policy.endsWith("/*") ? normalized.startsWith(policy.slice(0, -1)) : normalized === policy;
366
+ });
367
+ }
368
+ function limitedStream(stream, maxBytes, label, signal) {
369
+ const reader = stream.getReader();
370
+ let total = 0;
371
+ const cancelReader = (reason) => {
372
+ reader.cancel(reason).catch(() => {});
373
+ };
374
+ return new ReadableStream({
375
+ async pull(controller) {
376
+ if (signal.aborted) {
377
+ cancelReader(signal.reason);
378
+ controller.error(signal.reason ?? new DOMException("Aborted", "AbortError"));
379
+ return;
380
+ }
381
+ try {
382
+ const result = await reader.read();
383
+ if (result.done) {
384
+ controller.close();
385
+ reader.releaseLock();
386
+ return;
387
+ }
388
+ total += result.value.length;
389
+ if (total > maxBytes) {
390
+ cancelReader();
391
+ badRequest(`${label} exceeds ${maxBytes} bytes`);
392
+ }
393
+ controller.enqueue(result.value);
394
+ } catch (error) {
395
+ controller.error(error);
396
+ }
397
+ },
398
+ cancel(reason) {
399
+ cancelReader(reason);
400
+ }
401
+ });
402
+ }
403
+ async function collectFile(part, stream) {
404
+ const chunks = [];
405
+ const reader = stream.getReader();
406
+ while (true) {
407
+ const result = await reader.read();
408
+ if (result.done)
409
+ break;
410
+ chunks.push(Uint8Array.from(result.value).buffer);
411
+ }
412
+ return new File(chunks, part.filename ?? "upload", {
413
+ type: part.contentType ?? "application/octet-stream"
414
+ });
415
+ }
416
+ async function readText(stream, maxBytes) {
417
+ const chunks = [];
418
+ const reader = stream.getReader();
419
+ let total = 0;
420
+ while (true) {
421
+ const result = await reader.read();
422
+ if (result.done)
423
+ break;
424
+ total += result.value.length;
425
+ if (total > maxBytes) {
426
+ await reader.cancel();
427
+ badRequest(`Multipart text field exceeds ${maxBytes} bytes`);
428
+ }
429
+ chunks.push(result.value);
430
+ }
431
+ const value = new Uint8Array(total);
432
+ let offset = 0;
433
+ for (const chunk of chunks) {
434
+ value.set(chunk, offset);
435
+ offset += chunk.length;
436
+ }
437
+ return decoder.decode(value);
438
+ }
439
+ function required(policy) {
440
+ return policy.required !== false;
441
+ }
442
+ async function parseMultipart(req, descriptor, fieldsSchema, receivers) {
443
+ const maxRequestBytes = descriptor.maxRequestBytes ?? DEFAULT_MAX_REQUEST_BYTES;
444
+ const contentLength = Number(req.headers.get("content-length"));
445
+ if (Number.isFinite(contentLength) && contentLength > maxRequestBytes) {
446
+ badRequest(`Multipart request exceeds ${maxRequestBytes} bytes`);
447
+ }
448
+ const boundary = parseBoundary(req);
449
+ const parser = new MultipartStreamReader(req, boundary, maxRequestBytes);
450
+ const fields = {};
451
+ const files = {};
452
+ const counts = new Map;
453
+ const cleanups = [];
454
+ let rolledBack = false;
455
+ const rollback = async () => {
456
+ if (rolledBack)
457
+ return;
458
+ rolledBack = true;
459
+ for (let index = cleanups.length - 1;index >= 0; index -= 1) {
460
+ try {
461
+ await cleanups[index]?.();
462
+ } catch (error) {
463
+ console.error("[stitchkit] multipart receiver cleanup failed", error);
464
+ }
465
+ }
466
+ };
467
+ try {
468
+ await parser.start();
469
+ let partCount = 0;
470
+ while (true) {
471
+ const part = await parser.nextPart();
472
+ if (!part)
473
+ break;
474
+ partCount += 1;
475
+ if (partCount > DEFAULT_MAX_PARTS)
476
+ badRequest("Too many multipart parts");
477
+ const policy = descriptor.files[part.name];
478
+ const isFile = part.filename !== undefined || part.contentType !== undefined;
479
+ if (!isFile) {
480
+ if (policy)
481
+ badRequest(`Multipart file field "${part.name}" must contain a file`);
482
+ if (Object.hasOwn(fields, part.name)) {
483
+ badRequest(`Duplicate multipart text field: ${part.name}`);
484
+ }
485
+ fields[part.name] = await readText(part.stream, descriptor.maxFieldBytes ?? DEFAULT_MAX_FIELD_BYTES);
486
+ continue;
487
+ }
488
+ if (!policy)
489
+ badRequest(`Unexpected multipart file field: ${part.name}`);
490
+ const count = (counts.get(part.name) ?? 0) + 1;
491
+ counts.set(part.name, count);
492
+ const maxFiles = policy.multiple === true ? policy.maxFiles ?? DEFAULT_MAX_PARTS : 1;
493
+ if (count > maxFiles)
494
+ badRequest(`Too many files for multipart field: ${part.name}`);
495
+ const contentType = part.contentType ?? "";
496
+ if (policy.contentTypes && !matchesContentType(contentType, policy.contentTypes)) {
497
+ badRequest(`Unsupported content type for multipart field "${part.name}"`);
498
+ }
499
+ const maxFileBytes = policy.maxBytes ?? maxRequestBytes;
500
+ if (part.declaredSize !== undefined && part.declaredSize > maxFileBytes) {
501
+ badRequest(`Multipart field "${part.name}" exceeds ${maxFileBytes} bytes`);
502
+ }
503
+ const stream = limitedStream(part.stream, maxFileBytes, `Multipart field "${part.name}"`, req.signal);
504
+ let value;
505
+ if (descriptor.delivery === "stream") {
506
+ const receiver = receivers?.[part.name];
507
+ if (!receiver)
508
+ badRequest(`Missing multipart receiver for field: ${part.name}`);
509
+ const result = await receiver({
510
+ metadata: {
511
+ field: part.name,
512
+ filename: part.filename ?? "upload",
513
+ contentType: contentType || "application/octet-stream",
514
+ size: part.declaredSize
515
+ },
516
+ stream,
517
+ signal: req.signal
518
+ });
519
+ cleanups.push(result.cleanup);
520
+ if (!part.consumed()) {
521
+ await stream.cancel();
522
+ badRequest(`Multipart receiver for "${part.name}" did not consume its stream`);
523
+ }
524
+ value = result.value;
525
+ } else {
526
+ value = await collectFile(part, stream);
527
+ }
528
+ if (policy.multiple === true) {
529
+ const existing = files[part.name];
530
+ if (Array.isArray(existing))
531
+ existing.push(value);
532
+ else
533
+ files[part.name] = [value];
534
+ } else {
535
+ files[part.name] = value;
536
+ }
537
+ }
538
+ for (const [field, policy] of Object.entries(descriptor.files)) {
539
+ const count = counts.get(field) ?? 0;
540
+ if (required(policy) && count === 0)
541
+ badRequest(`Missing multipart file field: ${field}`);
542
+ if (policy.multiple === true && count === 0 && !required(policy))
543
+ files[field] = [];
544
+ }
545
+ return {
546
+ files,
547
+ fields: fieldsSchema ? fieldsSchema.parse(fields) : fields,
548
+ rollback
549
+ };
550
+ } catch (error) {
551
+ parser.cancel(error);
552
+ await rollback();
553
+ throw error;
554
+ } finally {
555
+ parser.release();
556
+ }
557
+ }
558
+
559
+ // src/server/streaming-pump.ts
560
+ async function pumpFrames(p) {
561
+ let sinceYield = 0;
562
+ try {
563
+ for (;; ) {
564
+ await p.awaitDemand();
565
+ if (p.isClosed())
566
+ return;
567
+ const next = await p.iterator.next();
568
+ if (p.isClosed())
569
+ return;
570
+ if (next.done)
571
+ break;
572
+ if (!p.send(p.framing.frame(next.value)))
573
+ return;
574
+ sinceYield += 1;
575
+ if (sinceYield >= MAX_BUFFERED_FRAMES) {
576
+ sinceYield = 0;
577
+ await new Promise((resolve) => {
578
+ setTimeout(resolve, 0);
579
+ });
580
+ if (p.isClosed())
581
+ return;
582
+ }
583
+ }
584
+ if (p.framing.done)
585
+ p.send(p.framing.done);
586
+ } catch (error) {
587
+ if (p.isClosed()) {
588
+ if (!isStreamCancellation(error, p.departed))
589
+ p.pumped.reject(error);
590
+ } else
591
+ p.send(p.framing.frame(normalizeError(error).toJSON()));
592
+ } finally {
593
+ p.pumped.resolve();
594
+ p.end();
595
+ }
596
+ }
597
+
598
+ // src/server/streaming-route.ts
599
+ var DEFAULT_STREAM_HEARTBEAT_MS = 5000;
600
+ var FRAMINGS = {
601
+ ndjson: {
602
+ contentType: "application/x-ndjson",
603
+ keepAlive: `
604
+ `,
605
+ frame: (value) => `${JSON.stringify(value)}
606
+ `
607
+ },
608
+ sse: {
609
+ contentType: "text/event-stream",
610
+ keepAlive: `: keep-alive
611
+
612
+ `,
613
+ frame: (value) => `data: ${JSON.stringify(value)}
614
+
615
+ `,
616
+ done: `data: [DONE]
617
+
618
+ `
619
+ }
620
+ };
621
+ function applyIdleTimeout(server, request, seconds) {
622
+ if (typeof server !== "object" || server === null)
623
+ return;
624
+ const timeout = Reflect.get(server, "timeout");
625
+ if (typeof timeout !== "function")
626
+ return;
627
+ try {
628
+ Reflect.apply(timeout, server, [request, seconds]);
629
+ } catch {}
630
+ }
631
+ function unrefTimer(timer) {
632
+ if (typeof timer !== "object" || timer === null)
633
+ return;
634
+ const unref = Reflect.get(timer, "unref");
635
+ if (typeof unref === "function")
636
+ Reflect.apply(unref, timer, []);
637
+ }
638
+ var MAX_BUFFERED_FRAMES = 16;
639
+ function responseHeaders(framing, extra) {
640
+ const headers = new Headers(extra);
641
+ headers.set("Content-Type", framing.contentType);
642
+ headers.set("Cache-Control", "no-cache");
643
+ headers.set("Connection", "keep-alive");
644
+ headers.set("X-Accel-Buffering", "no");
645
+ return headers;
646
+ }
647
+ function streamingTimings(options) {
648
+ const heartbeatMs = options.heartbeatMs ?? DEFAULT_STREAM_HEARTBEAT_MS;
649
+ if (!Number.isFinite(heartbeatMs) || heartbeatMs <= 0) {
650
+ throw new TypeError("heartbeatMs must be a finite positive number of milliseconds");
651
+ }
652
+ const idleTimeoutSeconds = options.idleTimeoutSeconds ?? 0;
653
+ if (!Number.isInteger(idleTimeoutSeconds) || idleTimeoutSeconds < 0) {
654
+ throw new TypeError("idleTimeoutSeconds must be a non-negative integer");
655
+ }
656
+ return { heartbeatMs, idleTimeoutSeconds };
657
+ }
658
+ function streamingRoute(options) {
659
+ const { heartbeatMs, idleTimeoutSeconds } = streamingTimings(options);
660
+ const framing = FRAMINGS[options.format ?? "ndjson"];
661
+ return {
662
+ method: options.method ?? "GET",
663
+ path: options.path,
664
+ handler: async (request, context) => {
665
+ applyIdleTimeout(context.server, request, idleTimeoutSeconds);
666
+ const departed = new AbortController;
667
+ const settled = Promise.withResolvers();
668
+ settled.promise.catch(() => {
669
+ return;
670
+ });
671
+ const pumped = Promise.withResolvers();
672
+ pumped.promise.catch(() => {
673
+ return;
674
+ });
675
+ let cancel = () => departed.abort();
676
+ ownHttpStream(request, { cancel: () => cancel(), settled: settled.promise });
677
+ let iterator;
678
+ try {
679
+ const iterable = await options.source(request, {
680
+ ...context,
681
+ signal: departed.signal
682
+ });
683
+ iterator = iterable[Symbol.asyncIterator]();
684
+ } catch (error) {
685
+ departed.abort();
686
+ settled.reject(error);
687
+ throw error;
688
+ }
689
+ const encoder2 = new TextEncoder;
690
+ let heartbeat = null;
691
+ let closed = false;
692
+ const stopHeartbeat = () => {
693
+ if (heartbeat === null)
694
+ return;
695
+ clearInterval(heartbeat);
696
+ heartbeat = null;
697
+ };
698
+ const release = () => {
699
+ if (closed)
700
+ return;
701
+ closed = true;
702
+ stopHeartbeat();
703
+ signalDemand();
704
+ request.signal.removeEventListener("abort", onRequestAbort);
705
+ departed.abort();
706
+ const hook = Promise.withResolvers();
707
+ try {
708
+ options.onClose?.();
709
+ hook.resolve();
710
+ } catch (error) {
711
+ hook.reject(error);
712
+ }
713
+ settleStreamCleanup([
714
+ hook.promise,
715
+ pumped.promise,
716
+ Promise.resolve().then(() => iterator.return?.(undefined))
717
+ ]).then(() => settled.resolve(), (error) => settled.reject(error));
718
+ };
719
+ let demand = null;
720
+ const signalDemand = () => {
721
+ const resolve = demand;
722
+ demand = null;
723
+ resolve?.();
724
+ };
725
+ const onRequestAbort = () => cancel();
726
+ const stream = new ReadableStream({
727
+ start(controller) {
728
+ const send = (text) => {
729
+ if (closed)
730
+ return false;
731
+ try {
732
+ controller.enqueue(encoder2.encode(text));
733
+ return true;
734
+ } catch {
735
+ release();
736
+ return false;
737
+ }
738
+ };
739
+ const finish = () => {
740
+ try {
741
+ controller.close();
742
+ } catch {}
743
+ };
744
+ cancel = () => {
745
+ release();
746
+ finish();
747
+ };
748
+ if (request.signal.aborted || departed.signal.aborted) {
749
+ pumped.resolve();
750
+ cancel();
751
+ return;
752
+ }
753
+ request.signal.addEventListener("abort", onRequestAbort, { once: true });
754
+ send(framing.keepAlive);
755
+ heartbeat = setInterval(() => {
756
+ if ((controller.desiredSize ?? 1) > 0)
757
+ send(framing.keepAlive);
758
+ }, heartbeatMs);
759
+ unrefTimer(heartbeat);
760
+ const awaitDemand = async () => {
761
+ while (!closed && (controller.desiredSize ?? 1) <= 0) {
762
+ await new Promise((resolve) => {
763
+ demand = resolve;
764
+ });
765
+ }
766
+ };
767
+ pumpFrames({
768
+ iterator,
769
+ framing,
770
+ send,
771
+ awaitDemand,
772
+ isClosed: () => closed,
773
+ departed: departed.signal,
774
+ pumped,
775
+ end: () => {
776
+ release();
777
+ finish();
778
+ }
779
+ });
780
+ },
781
+ pull() {
782
+ signalDemand();
783
+ },
784
+ cancel() {
785
+ release();
786
+ }
787
+ }, { highWaterMark: MAX_BUFFERED_FRAMES });
788
+ return new Response(stream, { headers: responseHeaders(framing, options.headers) });
789
+ }
790
+ };
791
+ }
792
+ function ndjsonRoute(options) {
793
+ return streamingRoute({ ...options, format: "ndjson" });
794
+ }
795
+ function sseRoute(options) {
796
+ return streamingRoute({ ...options, format: "sse" });
797
+ }
798
+
799
+ // src/server/context-contribution.ts
800
+ var RUNTIME_CONTEXT_RESERVED_KEYS = new Set([
801
+ "params",
802
+ "input",
803
+ "files",
804
+ "rawBody",
805
+ "source",
806
+ "req",
807
+ "url",
808
+ "headers",
809
+ "traceId",
810
+ "spanId",
811
+ "ipAddress",
812
+ "userAgent",
813
+ "signal",
814
+ "mcp",
815
+ "reportProgress"
816
+ ]);
817
+ function contributionError(scope, reason) {
818
+ return new TypeError(`[stitchkit] auth: invalid context contribution for scope ${JSON.stringify(scope)}: ${reason}`);
819
+ }
820
+ function descriptorsEqual(left, right) {
821
+ if (!left || !right)
822
+ return left === right;
823
+ if (left.enumerable !== right.enumerable || left.configurable !== right.configurable || left.writable !== right.writable) {
824
+ return false;
825
+ }
826
+ if ("value" in left || "value" in right) {
827
+ return "value" in left && "value" in right && Object.is(left.value, right.value);
828
+ }
829
+ return left.get === right.get && left.set === right.set;
830
+ }
831
+ function contextContributionDelta(original, shadow, scope) {
832
+ if (Object.getPrototypeOf(shadow) !== Object.getPrototypeOf(original)) {
833
+ throw contributionError(scope, "context prototype changes are not supported");
834
+ }
835
+ const originalKeys = Reflect.ownKeys(original);
836
+ const shadowKeys = Reflect.ownKeys(shadow);
837
+ const shadowKeySet = new Set(shadowKeys);
838
+ for (const key of originalKeys) {
839
+ if (!shadowKeySet.has(key)) {
840
+ const printable = typeof key === "string" ? JSON.stringify(key) : "a symbol key";
841
+ throw contributionError(scope, `context key ${printable} may not be deleted`);
842
+ }
843
+ }
844
+ const contribution = Object.create(null);
845
+ for (const key of shadowKeys) {
846
+ const originalDescriptor = Object.getOwnPropertyDescriptor(original, key);
847
+ const shadowDescriptor = Object.getOwnPropertyDescriptor(shadow, key);
848
+ if (!shadowDescriptor || descriptorsEqual(originalDescriptor, shadowDescriptor))
849
+ continue;
850
+ Object.defineProperty(contribution, key, shadowDescriptor);
851
+ }
852
+ return contribution;
853
+ }
854
+ function prepareContextContribution(value, scope) {
855
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
856
+ throw contributionError(scope, "expected a plain record");
857
+ }
858
+ let prototype;
859
+ let descriptors;
860
+ let keys;
861
+ try {
862
+ prototype = Object.getPrototypeOf(value);
863
+ descriptors = Object.getOwnPropertyDescriptors(value);
864
+ keys = Reflect.ownKeys(value);
865
+ } catch {
866
+ throw contributionError(scope, "record inspection failed");
867
+ }
868
+ if (prototype !== Object.prototype && prototype !== null) {
869
+ throw contributionError(scope, "expected Object.prototype or null prototype");
870
+ }
871
+ const prepared = Object.create(null);
872
+ for (const key of keys) {
873
+ if (typeof key !== "string") {
874
+ throw contributionError(scope, "symbol keys are not supported");
875
+ }
876
+ if (isUnsafeKey(key)) {
877
+ throw contributionError(scope, `unsafe key ${JSON.stringify(key)}`);
878
+ }
879
+ if (RUNTIME_CONTEXT_RESERVED_KEYS.has(key)) {
880
+ throw contributionError(scope, `reserved key ${JSON.stringify(key)}`);
881
+ }
882
+ const descriptor = descriptors[key];
883
+ if (!descriptor?.enumerable || !("value" in descriptor)) {
884
+ throw contributionError(scope, `key ${JSON.stringify(key)} must be enumerable data`);
885
+ }
886
+ prepared[key] = descriptor.value;
887
+ }
888
+ return prepared;
889
+ }
890
+ function mergeContextContribution(ctx, value, scope) {
891
+ Object.assign(ctx, prepareContextContribution(value, scope));
892
+ }
893
+
894
+ // src/server/request-body.ts
895
+ function requestAbortReason(req) {
896
+ return req.signal.reason ?? new DOMException("The connection was closed", "AbortError");
897
+ }
898
+ function throwIfRequestAborted(req) {
899
+ if (req.signal.aborted)
900
+ throw requestAbortReason(req);
901
+ }
902
+ function assertJsonBodyLimit(maxBytes, owner) {
903
+ if (maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) {
904
+ throw new Error(`${owner} must be a positive safe integer, received ${maxBytes}`);
905
+ }
906
+ }
907
+ async function readRequestText(req, maxBytes) {
908
+ throwIfRequestAborted(req);
909
+ if (maxBytes === undefined)
910
+ return req.text();
911
+ assertJsonBodyLimit(maxBytes, "maxJsonBodyBytes");
912
+ const reader = req.body?.getReader();
913
+ if (!reader)
914
+ return "";
915
+ const chunks = [];
916
+ let total = 0;
917
+ let rejectAbortedRead = (_reason) => {
918
+ return;
919
+ };
920
+ const abortedRead = new Promise((_resolve, reject) => {
921
+ rejectAbortedRead = reject;
922
+ });
923
+ const onAbort = () => {
924
+ const reason = requestAbortReason(req);
925
+ rejectAbortedRead(reason);
926
+ reader.cancel(reason).catch(() => {
927
+ return;
928
+ });
929
+ };
930
+ req.signal.addEventListener("abort", onAbort, { once: true });
931
+ if (req.signal.aborted)
932
+ onAbort();
933
+ try {
934
+ while (true) {
935
+ const { done, value } = await Promise.race([reader.read(), abortedRead]);
936
+ if (done)
937
+ break;
938
+ total += value.byteLength;
939
+ if (total > maxBytes) {
940
+ await reader.cancel();
941
+ badRequest(`JSON body exceeds the ${maxBytes}-byte limit`);
942
+ }
943
+ chunks.push(value);
944
+ }
945
+ } finally {
946
+ req.signal.removeEventListener("abort", onAbort);
947
+ if (!req.signal.aborted)
948
+ reader.releaseLock();
949
+ }
950
+ const bytes = new Uint8Array(total);
951
+ let offset = 0;
952
+ for (const chunk of chunks) {
953
+ bytes.set(chunk, offset);
954
+ offset += chunk.byteLength;
955
+ }
956
+ return new TextDecoder().decode(bytes);
957
+ }
958
+
959
+ // src/server/context.ts
960
+ function parseJsonBody(req, text, method, cors) {
961
+ if (text.trim() === "")
962
+ return {};
963
+ const essence = mediaTypeEssence(req.headers.get("content-type"));
964
+ if (essence !== "application/json") {
965
+ if (!method.safelistedBody || essence !== "text/plain") {
966
+ badRequest("Request body must be application/json");
967
+ }
968
+ const origin = req.headers.get("origin");
969
+ if (!cors || cors.origin === undefined || cors.origin === "*") {
970
+ forbidden("A text/plain body requires an explicit cors.origin allow-list on the server");
971
+ }
972
+ if (!origin)
973
+ forbidden("A text/plain body requires an Origin header");
974
+ if (!isOriginAllowed(cors, origin)) {
975
+ forbidden("A text/plain body is accepted only from an allowed origin");
976
+ }
977
+ }
978
+ try {
979
+ return safeJsonParse(text);
980
+ } catch {
981
+ badRequest("Invalid JSON body");
982
+ }
983
+ }
984
+ function buildBaseContext(req, url, pathParams, traceId, clientIp) {
985
+ const safePathParams = {};
986
+ for (const [k, v] of Object.entries(pathParams)) {
987
+ if (!RUNTIME_CONTEXT_RESERVED_KEYS.has(k) && !isUnsafeKey(k))
988
+ safePathParams[k] = v;
989
+ }
990
+ return {
991
+ params: pathParams,
992
+ input: undefined,
993
+ source: "http",
994
+ req,
995
+ url,
996
+ headers: req.headers,
997
+ signal: req.signal,
998
+ ...safePathParams,
999
+ traceId,
1000
+ ...getClientInfo(req, clientIp)
1001
+ };
1002
+ }
1003
+ function parsePathParamsInto(ctx, method) {
1004
+ if (method.paramsSchema) {
1005
+ ctx.params = method.paramsSchema.parse(ctx.params);
1006
+ }
1007
+ }
1008
+ async function parseRequestPayloadInto(ctx, req, url, method, maxJsonBodyBytes, cors) {
1009
+ if (method.multipart) {
1010
+ const multipart = await parseMultipart(req, method.multipart, method.inputSchema, method.multipartReceivers);
1011
+ ctx.input = multipart.fields;
1012
+ ctx.files = multipart.files;
1013
+ return multipart;
1014
+ }
1015
+ if (method.inputSchema) {
1016
+ if (req.method === "GET") {
1017
+ ctx.input = method.inputSchema.parse(parseQueryParams(url));
1018
+ } else if (req.method === "DELETE") {
1019
+ if (mediaTypeEssence(req.headers.get("content-type")) === "application/json") {
1020
+ const text = await readRequestText(req, method.maxJsonBodyBytes ?? maxJsonBodyBytes);
1021
+ if (method.rawBody)
1022
+ ctx.rawBody = text;
1023
+ ctx.input = method.inputSchema.parse(parseJsonBody(req, text, method, cors));
1024
+ } else {
1025
+ ctx.input = method.inputSchema.parse(parseQueryParams(url));
1026
+ }
1027
+ } else {
1028
+ const text = await readRequestText(req, method.maxJsonBodyBytes ?? maxJsonBodyBytes);
1029
+ if (method.rawBody)
1030
+ ctx.rawBody = text;
1031
+ ctx.input = method.inputSchema.parse(parseJsonBody(req, text, method, cors));
1032
+ }
1033
+ }
1034
+ return;
1035
+ }
1036
+ function buildErrorContext(req, url, traceId, clientIp) {
1037
+ return {
1038
+ params: undefined,
1039
+ input: undefined,
1040
+ source: "http",
1041
+ req,
1042
+ url,
1043
+ headers: req.headers,
1044
+ signal: req.signal,
1045
+ traceId,
1046
+ ...getClientInfo(req, clientIp)
1047
+ };
1048
+ }
1049
+
1050
+ // src/server/contract-stream.ts
1051
+ function encodedBytes(value, format) {
1052
+ const json = JSON.stringify(value);
1053
+ if (json === undefined)
1054
+ throw new TypeError("Streaming item is not JSON serializable");
1055
+ const framing = format === "sse" ? `data: ${json}
1056
+
1057
+ ` : `${json}
1058
+ `;
1059
+ return new TextEncoder().encode(framing).byteLength;
1060
+ }
1061
+ function waitForAbort(signal) {
1062
+ return new Promise((_resolve, reject) => {
1063
+ const rejectAborted = () => reject(signal.reason ?? new Error("Stream aborted"));
1064
+ if (signal.aborted)
1065
+ rejectAborted();
1066
+ else
1067
+ signal.addEventListener("abort", rejectAborted, { once: true });
1068
+ });
1069
+ }
1070
+ function contractStreamResponse(request, context, source, descriptor, operationAbort) {
1071
+ const format = descriptor.format ?? "ndjson";
1072
+ const maxFrameBytes = descriptor.maxFrameBytes ?? DEFAULT_CONTRACT_STREAM_FRAME_BYTES;
1073
+ const iterator = source[Symbol.asyncIterator]();
1074
+ let pendingNext;
1075
+ const settled = Promise.withResolvers();
1076
+ settled.promise.catch(() => {
1077
+ return;
1078
+ });
1079
+ let lifetime;
1080
+ let lifetimeExpired = false;
1081
+ let closing = false;
1082
+ const closeSource = (cancelled = operationAbort.signal.aborted) => {
1083
+ if (closing)
1084
+ return;
1085
+ closing = true;
1086
+ if (lifetime !== undefined)
1087
+ clearTimeout(lifetime);
1088
+ operationAbort.abort();
1089
+ settleStreamCleanup([
1090
+ Promise.resolve(pendingNext).catch((error) => {
1091
+ if (cancelled && !isStreamCancellation(error, operationAbort.signal))
1092
+ throw error;
1093
+ }),
1094
+ Promise.resolve().then(() => iterator.return?.(undefined))
1095
+ ]).then(() => settled.resolve(), (error) => settled.reject(error));
1096
+ };
1097
+ ownHttpStream(request, { cancel: () => closeSource(true), settled: settled.promise });
1098
+ if (descriptor.lifetimeMs !== undefined && !closing) {
1099
+ lifetime = setTimeout(() => {
1100
+ lifetimeExpired = true;
1101
+ operationAbort.abort(new Error("Stream lifetime expired"));
1102
+ }, descriptor.lifetimeMs);
1103
+ lifetime.unref?.();
1104
+ }
1105
+ const frames = async function* () {
1106
+ if (closing)
1107
+ return;
1108
+ const aborted = waitForAbort(operationAbort.signal);
1109
+ let terminalSeen = descriptor.terminal === undefined;
1110
+ try {
1111
+ for (;; ) {
1112
+ pendingNext = Promise.resolve(iterator.next());
1113
+ const next = await Promise.race([pendingNext, aborted]);
1114
+ if (next.done)
1115
+ break;
1116
+ const parsed = descriptor.item.safeParse(next.value);
1117
+ if (!parsed.success) {
1118
+ console.error("[stitchkit] contract stream item failed validation:", parsed.error);
1119
+ throw new AppError("STREAM_ITEM_INVALID", "Stream item did not match its contract", 500);
1120
+ }
1121
+ const item = parsed.data;
1122
+ const terminal = descriptor.terminal?.safeParse(item).success ?? false;
1123
+ if (terminal)
1124
+ terminalSeen = true;
1125
+ const frame = descriptor.framing === "item" ? item : { type: "data", data: item };
1126
+ if (encodedBytes(frame, format) > maxFrameBytes) {
1127
+ console.error(`[stitchkit] contract stream frame exceeded its ${maxFrameBytes} byte limit`);
1128
+ throw new AppError("STREAM_FRAME_TOO_LARGE", "Stream item exceeded its declared frame limit", 500);
1129
+ }
1130
+ yield frame;
1131
+ if (terminal && descriptor.completion === "terminal")
1132
+ return;
1133
+ }
1134
+ if (!terminalSeen) {
1135
+ throw new AppError("STREAM_TERMINAL_MISSING", "Stream completed before its declared terminal item", 500);
1136
+ }
1137
+ if (descriptor.framing !== "item")
1138
+ yield { type: "end" };
1139
+ } catch (error) {
1140
+ if (operationAbort.signal.aborted && !lifetimeExpired)
1141
+ return;
1142
+ if (lifetimeExpired) {
1143
+ if (descriptor.framing === "item")
1144
+ return;
1145
+ yield {
1146
+ type: "error",
1147
+ error: new AppError("STREAM_LIFETIME_EXCEEDED", "Stream exceeded its declared lifetime", 408).toJSON().error
1148
+ };
1149
+ return;
1150
+ }
1151
+ if (descriptor.framing === "item") {
1152
+ console.error("[stitchkit] item-framed contract stream failed:", normalizeError(error));
1153
+ return;
1154
+ }
1155
+ yield { type: "error", error: normalizeError(error).toJSON().error };
1156
+ } finally {
1157
+ if (lifetime !== undefined)
1158
+ clearTimeout(lifetime);
1159
+ closeSource();
1160
+ }
1161
+ };
1162
+ const route = streamingRoute({
1163
+ path: "/",
1164
+ format,
1165
+ heartbeatMs: descriptor.heartbeatMs,
1166
+ idleTimeoutSeconds: descriptor.idleTimeoutSeconds,
1167
+ source: () => frames(),
1168
+ onClose: () => operationAbort.abort()
1169
+ });
1170
+ return Promise.resolve(route.handler(request, context));
1171
+ }
1172
+
1173
+ // src/server/response-metadata.ts
1174
+ var RESERVED_HEADERS = new Set(["content-type", "content-length", "x-request-id"]);
1175
+ function hasGetSetCookie(headers) {
1176
+ return "getSetCookie" in headers && typeof headers.getSetCookie === "function";
1177
+ }
1178
+ function isReservedHeader(name) {
1179
+ const normalized = name.toLowerCase();
1180
+ return RESERVED_HEADERS.has(normalized) || normalized.startsWith("access-control-");
1181
+ }
1182
+ function createResponseMetadata() {
1183
+ return { headers: new Headers };
1184
+ }
1185
+ function applyResponseMetadata(target, metadata, endpointIdentity) {
1186
+ if (!metadata)
1187
+ return;
1188
+ for (const [name] of metadata.headers) {
1189
+ if (isReservedHeader(name)) {
1190
+ throw new Error(`${endpointIdentity} cannot set framework-owned response header "${name}"`);
1191
+ }
1192
+ }
1193
+ const preservesSetCookie = hasGetSetCookie(metadata.headers);
1194
+ for (const [name, value] of metadata.headers) {
1195
+ if (name.toLowerCase() === "set-cookie" && preservesSetCookie)
1196
+ continue;
1197
+ target.append(name, value);
1198
+ }
1199
+ if (preservesSetCookie) {
1200
+ for (const cookie of metadata.headers.getSetCookie()) {
1201
+ target.append("Set-Cookie", cookie);
1202
+ }
1203
+ }
1204
+ }
1205
+
1206
+ // src/server/endpoint-response.ts
1207
+ function isAsyncIterable(value) {
1208
+ if (typeof value !== "object" && typeof value !== "function" || value === null) {
1209
+ return false;
1210
+ }
1211
+ return typeof Reflect.get(value, Symbol.asyncIterator) === "function";
1212
+ }
1213
+ async function endpointResponse(state, request, outcome) {
1214
+ const { method } = outcome.match;
1215
+ if (method.rawResponse)
1216
+ return rawEndpointResponse(state, request, outcome);
1217
+ if (method.stream)
1218
+ return streamEndpointResponse(state, request, outcome);
1219
+ return dataEndpointResponse(state, request, outcome);
1220
+ }
1221
+ function rawEndpointResponse(state, request, { match: { method }, result }) {
1222
+ if (!(result instanceof Response)) {
1223
+ throw new AppError("INTERNAL_SERVER_ERROR", `Raw endpoint ${method.serviceName}.${method.key} must return a Response`, 500);
1224
+ }
1225
+ const response = method.method === "HEAD" ? new Response(null, {
1226
+ status: result.status,
1227
+ statusText: result.statusText,
1228
+ headers: result.headers
1229
+ }) : result;
1230
+ const rawRes = applyCors(response, state.cors, request.req);
1231
+ request.complete(rawRes.status);
1232
+ return rawRes;
1233
+ }
1234
+ async function streamEndpointResponse(state, request, { match: { method, pathParams }, result, streamAbort }) {
1235
+ const { req, server, clientIp } = request;
1236
+ if (!method.stream || !streamAbort || !isAsyncIterable(result)) {
1237
+ streamAbort?.abort();
1238
+ throw new AppError("INTERNAL_SERVER_ERROR", `Streaming endpoint ${method.serviceName}.${method.key} must return an AsyncIterable`, 500);
1239
+ }
1240
+ const response = await contractStreamResponse(req, { params: pathParams, server, ipAddress: clientIp.socketIp }, result, method.stream, streamAbort);
1241
+ const withCors = applyCors(response, state.cors, req);
1242
+ request.complete(withCors.status);
1243
+ return withCors;
1244
+ }
1245
+ async function dataEndpointResponse(state, request, {
1246
+ ctx,
1247
+ match: { method, groupHooks },
1248
+ result: handlerResult,
1249
+ responseMetadata
1250
+ }) {
1251
+ const { hooks, config, cors, warn } = state;
1252
+ const { req } = request;
1253
+ let result = handlerResult;
1254
+ if (groupHooks?.afterHandle) {
1255
+ const transformed = await groupHooks.afterHandle(ctx, result, method);
1256
+ if (transformed !== undefined)
1257
+ result = transformed;
1258
+ }
1259
+ if (hooks?.afterHandle) {
1260
+ const transformed = await hooks.afterHandle(ctx, result, method);
1261
+ if (transformed !== undefined)
1262
+ result = transformed;
1263
+ }
1264
+ if (result instanceof Response) {
1265
+ throw new AppError("INTERNAL_SERVER_ERROR", `${method.serviceName}.${method.key} produced a Response on the data path — only a \`rawResponse: true\` endpoint may return one (an afterHandle hook must return data)`, 500);
1266
+ }
1267
+ const checked = validateDeclaredOutput(method.outputSchema, result, config.warnOnOutputStrip && method.outputSchema ? (paths) => {
1268
+ warn(`[stitchkit] output strip ${method.serviceName}.${method.key}: ${paths.join(", ")}`);
1269
+ } : undefined);
1270
+ if (!checked.ok) {
1271
+ throw new AppError("INTERNAL_SERVER_ERROR", checked.message, 500);
1272
+ }
1273
+ result = checked.data;
1274
+ const responseStatus = method.responseMeta?.status ?? (method.outputSchema ? 200 : 204);
1275
+ if (method.outputSchema && (responseStatus === 204 || responseStatus === 205)) {
1276
+ throw new AppError("INTERNAL_SERVER_ERROR", `${method.serviceName}.${method.key} cannot combine output with bodyless status ${responseStatus}`, 500);
1277
+ }
1278
+ const responseHeaders2 = new Headers(requestCorsHeaders(cors, req));
1279
+ applyResponseMetadata(responseHeaders2, responseMetadata, `${method.serviceName}.${method.key}`);
1280
+ if (!method.outputSchema) {
1281
+ const empty = new Response(null, { status: responseStatus, headers: responseHeaders2 });
1282
+ request.complete(responseStatus);
1283
+ return empty;
1284
+ }
1285
+ const body = Response.json(result, { status: responseStatus, headers: responseHeaders2 });
1286
+ request.complete(responseStatus);
1287
+ return body;
1288
+ }
1289
+
1290
+ // src/server/endpoint-dispatch.ts
1291
+ async function dispatchEndpoint(state, request, match) {
1292
+ const { hooks, config, cors } = state;
1293
+ const { req, url, traceId, clientIp } = request;
1294
+ const { method, pathParams, groupHooks } = match;
1295
+ const ctx = buildBaseContext(req, url, pathParams, traceId, clientIp);
1296
+ setRequestEndpoint(method.serviceName, method.key);
1297
+ let multipartLifecycle;
1298
+ try {
1299
+ parsePathParamsInto(ctx, method);
1300
+ if (hooks?.authorize) {
1301
+ await hooks.authorize(ctx, method);
1302
+ }
1303
+ if (groupHooks?.authorize) {
1304
+ await groupHooks.authorize(ctx, method);
1305
+ }
1306
+ multipartLifecycle = await parseRequestPayloadInto(ctx, req, url, method, config.maxJsonBodyBytes, cors);
1307
+ if (hooks?.beforeHandle) {
1308
+ await hooks.beforeHandle(ctx, method);
1309
+ }
1310
+ if (groupHooks?.beforeHandle) {
1311
+ await groupHooks.beforeHandle(ctx, method);
1312
+ }
1313
+ const responseMetadata = method.responseMeta ? createResponseMetadata() : undefined;
1314
+ if (responseMetadata)
1315
+ ctx.response = responseMetadata;
1316
+ const streamAbort = method.stream ? new AbortController : undefined;
1317
+ if (streamAbort) {
1318
+ if (req.signal.aborted)
1319
+ streamAbort.abort(req.signal.reason);
1320
+ else {
1321
+ req.signal.addEventListener("abort", () => streamAbort.abort(req.signal.reason), {
1322
+ once: true
1323
+ });
1324
+ }
1325
+ ctx.signal = streamAbort.signal;
1326
+ }
1327
+ const result = await method.handler(ctx);
1328
+ return await endpointResponse(state, request, {
1329
+ ctx,
1330
+ match,
1331
+ result,
1332
+ responseMetadata,
1333
+ streamAbort
1334
+ });
1335
+ } catch (err) {
1336
+ await multipartLifecycle?.rollback();
1337
+ return request.respondError(err, ctx, method, groupHooks);
1338
+ }
1339
+ }
1340
+
1341
+ // src/server/error-dispatch.ts
1342
+ var MAX_REQUEST_ABORT_CAUSE_DEPTH = 8;
1343
+ function containsRequestAbortReason(error, reason) {
1344
+ let current = error;
1345
+ const visited = new Set;
1346
+ for (let depth = 0;depth <= MAX_REQUEST_ABORT_CAUSE_DEPTH; depth += 1) {
1347
+ if (current === reason)
1348
+ return true;
1349
+ if (depth === MAX_REQUEST_ABORT_CAUSE_DEPTH || !isRecord(current))
1350
+ return false;
1351
+ if (visited.has(current))
1352
+ return false;
1353
+ visited.add(current);
1354
+ current = current.cause;
1355
+ }
1356
+ return false;
1357
+ }
1358
+ function isClientClosedRequest(req, error) {
1359
+ if (!req.signal.aborted)
1360
+ return false;
1361
+ if (isRecord(error) && error.name === "AbortError")
1362
+ return true;
1363
+ return req.signal.reason !== undefined && containsRequestAbortReason(error, req.signal.reason);
1364
+ }
1365
+ function createErrorResponder(state, request) {
1366
+ const { cors, hooks, customLogger } = state;
1367
+ const { req, url, traceId, clientIp, complete } = request;
1368
+ return async (err, errCtx, endpoint, group) => {
1369
+ if (isClientClosedRequest(req, err)) {
1370
+ const response = applyCors(new Response(null, { status: 499, statusText: "Client Closed Request" }), cors, req);
1371
+ complete(response.status, undefined, "cancelled");
1372
+ return response;
1373
+ }
1374
+ const recordFailure = (normalized) => {
1375
+ if (getRequestContext()?.error !== undefined)
1376
+ return;
1377
+ const known = AppError.is(err) ? err : normalized;
1378
+ const code = known?.code ?? errorCode(err) ?? "INTERNAL_SERVER_ERROR";
1379
+ setRequestError({
1380
+ code,
1381
+ message: recordedErrorMessage(code, known?.message, err),
1382
+ details: known?.details
1383
+ });
1384
+ };
1385
+ const customResponse = await dispatchErrorHooks({
1386
+ context: errCtx ?? buildErrorContext(req, url, traceId, clientIp),
1387
+ error: err,
1388
+ endpoint,
1389
+ group,
1390
+ global: hooks,
1391
+ logger: customLogger,
1392
+ respond: (response) => {
1393
+ recordFailure();
1394
+ const withCors = applyCors(response, cors, req);
1395
+ complete(withCors.status, errorCode(err));
1396
+ return withCors;
1397
+ }
1398
+ });
1399
+ if (customResponse)
1400
+ return customResponse;
1401
+ const appErr = normalizeError(err);
1402
+ recordFailure(appErr);
1403
+ complete(appErr.status, appErr.code);
1404
+ return Response.json(appErr.toJSON(), {
1405
+ status: appErr.status,
1406
+ headers: requestCorsHeaders(cors, req)
1407
+ });
1408
+ };
1409
+ }
1410
+ async function dispatchErrorHooks(config) {
1411
+ for (const [scope, hooks] of [
1412
+ ["group", config.group],
1413
+ ["global", config.global]
1414
+ ]) {
1415
+ if (!hooks?.onError)
1416
+ continue;
1417
+ try {
1418
+ const response = await hooks.onError(config.context, config.error, config.endpoint);
1419
+ if (response instanceof Response)
1420
+ return config.respond(response);
1421
+ } catch (error) {
1422
+ const message = `[stitchkit] ${scope} onError failed`;
1423
+ try {
1424
+ if (config.logger) {
1425
+ config.logger.error(message, { error, traceId: config.context.traceId });
1426
+ } else
1427
+ console.error(message, error);
1428
+ } catch {}
1429
+ }
1430
+ }
1431
+ return;
1432
+ }
1433
+
1434
+ // src/server/logging.ts
1435
+ var LOGGER_METHODS = ["info", "warn", "error", "debug"];
1436
+ function isBareLogger(value) {
1437
+ if (value.logger !== undefined || value.skip !== undefined || value.enrich !== undefined) {
1438
+ return false;
1439
+ }
1440
+ return LOGGER_METHODS.every((method) => typeof value[method] === "function");
1441
+ }
1442
+ function resolveLoggingConfig(logging) {
1443
+ if (logging === false)
1444
+ return null;
1445
+ if (logging === true)
1446
+ return {};
1447
+ if (isRecord(logging) && isBareLogger(logging)) {
1448
+ throw new Error("[stitchkit] `logging` no longer takes a StitchLogger directly — nest it: " + "`logging: { logger: myLogger }`.");
1449
+ }
1450
+ return logging;
1451
+ }
1452
+ function shouldSkipLog(config, req, url) {
1453
+ if (!config.skip)
1454
+ return false;
1455
+ try {
1456
+ return config.skip(req, url);
1457
+ } catch {
1458
+ return false;
1459
+ }
1460
+ }
1461
+ function collectExtraLogFields(config, req, url, outcome) {
1462
+ const fields = {};
1463
+ const enrichKeys = [];
1464
+ const ctx = getRequestContext();
1465
+ if (ctx) {
1466
+ if (ctx.userId)
1467
+ fields.userId = ctx.userId;
1468
+ if (ctx.serviceName)
1469
+ fields.serviceName = ctx.serviceName;
1470
+ if (ctx.action)
1471
+ fields.action = ctx.action;
1472
+ if (ctx.dimensions)
1473
+ fields.dimensions = ctx.dimensions;
1474
+ }
1475
+ if (config.enrich) {
1476
+ try {
1477
+ const extra = config.enrich(req, url, outcome);
1478
+ if (extra) {
1479
+ enrichKeys.push(...Object.keys(extra));
1480
+ Object.assign(fields, extra);
1481
+ }
1482
+ } catch {}
1483
+ }
1484
+ return { fields, enrichKeys };
1485
+ }
1486
+
1487
+ // src/server/router.ts
1488
+ function routeSegments(path) {
1489
+ return path.split("/").filter(Boolean);
1490
+ }
1491
+ function rawRouteShape(path) {
1492
+ parseTrailingWildcard(path);
1493
+ const segments = routeSegments(path).map((segment) => {
1494
+ if (segment.startsWith(":"))
1495
+ return { kind: "param" };
1496
+ if (segment.startsWith("*"))
1497
+ return { kind: "wildcard" };
1498
+ return { kind: "static", value: segment };
1499
+ });
1500
+ return {
1501
+ segments,
1502
+ signature: segments.map((segment) => segment.kind === "static" ? segment.value : `:${segment.kind}`).join("/"),
1503
+ wildcard: segments.at(-1)?.kind === "wildcard"
1504
+ };
1505
+ }
1506
+ function segmentCovers(earlier, later) {
1507
+ if (earlier.kind === "param")
1508
+ return later.kind !== "wildcard";
1509
+ if (earlier.kind === "wildcard")
1510
+ return true;
1511
+ return later.kind === "static" && earlier.value === later.value;
1512
+ }
1513
+ function routeShapeCovers(earlier, later) {
1514
+ const earlierPrefixLength = earlier.wildcard ? earlier.segments.length - 1 : earlier.segments.length;
1515
+ const laterPrefixLength = later.wildcard ? later.segments.length - 1 : later.segments.length;
1516
+ if (earlier.wildcard) {
1517
+ if (earlierPrefixLength > laterPrefixLength)
1518
+ return false;
1519
+ } else {
1520
+ if (later.wildcard || earlierPrefixLength !== laterPrefixLength)
1521
+ return false;
1522
+ }
1523
+ for (let index = 0;index < earlierPrefixLength; index++) {
1524
+ const earlierSegment = earlier.segments[index];
1525
+ const laterSegment = later.segments[index];
1526
+ if (!earlierSegment || !laterSegment || !segmentCovers(earlierSegment, laterSegment)) {
1527
+ return false;
1528
+ }
1529
+ }
1530
+ return true;
1531
+ }
1532
+ function matchSegments(patternSegments, requestSegments) {
1533
+ const wildcardSegment = patternSegments.at(-1);
1534
+ const wildcardName = wildcardSegment?.startsWith("*") ? wildcardSegment.slice(1) : null;
1535
+ const prefixLength = wildcardName ? patternSegments.length - 1 : patternSegments.length;
1536
+ if (wildcardName) {
1537
+ if (requestSegments.length < prefixLength)
1538
+ return null;
1539
+ } else if (patternSegments.length !== requestSegments.length) {
1540
+ return null;
1541
+ }
1542
+ const params = {};
1543
+ for (const [i, pattern] of patternSegments.slice(0, prefixLength).entries()) {
1544
+ const actual = requestSegments[i];
1545
+ if (actual === undefined)
1546
+ return null;
1547
+ if (pattern.startsWith(":")) {
1548
+ const decoded = decodeSegment(actual);
1549
+ if (decoded === null)
1550
+ return null;
1551
+ params[pattern.slice(1)] = decoded;
1552
+ } else if (pattern !== actual) {
1553
+ return null;
1554
+ }
1555
+ }
1556
+ if (wildcardName) {
1557
+ const decoded = requestSegments.slice(prefixLength).map(decodeSegment);
1558
+ if (decoded.some((segment) => segment === null))
1559
+ return null;
1560
+ params[wildcardName] = decoded.join("/");
1561
+ }
1562
+ return params;
1563
+ }
1564
+ function decodeSegment(segment) {
1565
+ try {
1566
+ return decodeURIComponent(segment);
1567
+ } catch {
1568
+ return null;
1569
+ }
1570
+ }
1571
+ function segmentRank(segment) {
1572
+ if (segment?.startsWith("*"))
1573
+ return 2;
1574
+ if (segment?.startsWith(":"))
1575
+ return 1;
1576
+ return 0;
1577
+ }
1578
+ function buildRouteMap(groups) {
1579
+ const map = new Map;
1580
+ for (const { prefix, service, hooks } of groups) {
1581
+ for (const [, method] of Object.entries(service.methods)) {
1582
+ if (method.expose && !method.expose.includes("HTTP"))
1583
+ continue;
1584
+ const servicePath = joinRoutePath("/", service.prefix, method.path === "/" ? "" : method.path);
1585
+ const fullPath = prefix ? joinRoutePath(prefix, servicePath) : servicePath;
1586
+ const segments = routeSegments(fullPath);
1587
+ const entries = map.get(method.method) ?? [];
1588
+ entries.push({ method, pattern: fullPath, segments, groupHooks: hooks });
1589
+ map.set(method.method, entries);
1590
+ }
1591
+ }
1592
+ for (const [, entries] of map) {
1593
+ entries.sort((a, b) => {
1594
+ const len = Math.min(a.segments.length, b.segments.length);
1595
+ for (let i = 0;i < len; i++) {
1596
+ const rankDifference = segmentRank(a.segments[i]) - segmentRank(b.segments[i]);
1597
+ if (rankDifference !== 0)
1598
+ return rankDifference;
1599
+ }
1600
+ return a.segments.length - b.segments.length;
1601
+ });
1602
+ }
1603
+ return map;
1604
+ }
1605
+ function matchRoute(routeMap, httpMethod, pathname) {
1606
+ const entries = routeMap.get(httpMethod);
1607
+ if (!entries)
1608
+ return null;
1609
+ const requestSegments = routeSegments(pathname);
1610
+ for (const entry of entries) {
1611
+ const pathParams = matchSegments(entry.segments, requestSegments);
1612
+ if (pathParams) {
1613
+ return {
1614
+ method: entry.method,
1615
+ pathParams,
1616
+ groupHooks: entry.groupHooks
1617
+ };
1618
+ }
1619
+ }
1620
+ return null;
1621
+ }
1622
+ function allowedMethods(routeMap, pathname) {
1623
+ const requestSegments = routeSegments(pathname);
1624
+ const methods = [];
1625
+ for (const [method, entries] of routeMap) {
1626
+ for (const entry of entries) {
1627
+ if (matchSegments(entry.segments, requestSegments)) {
1628
+ methods.push(method);
1629
+ break;
1630
+ }
1631
+ }
1632
+ }
1633
+ return methods;
1634
+ }
1635
+ function validateRoutes(routeMap) {
1636
+ for (const [method, entries] of routeMap) {
1637
+ const seen = new Map;
1638
+ for (const entry of entries) {
1639
+ parseTrailingWildcard(entry.pattern);
1640
+ const normalized = entry.segments.map((s) => s.startsWith(":") ? ":param" : s.startsWith("*") ? "*wildcard" : s).join("/");
1641
+ const key = `${method} /${normalized}`;
1642
+ const existing = seen.get(key);
1643
+ if (existing) {
1644
+ throw new Error(`Duplicate route: ${method} ${entry.pattern} conflicts with ${existing}`);
1645
+ }
1646
+ seen.set(key, entry.pattern);
1647
+ }
1648
+ }
1649
+ }
1650
+ function findShadowedRoutes(routeMap, rawRoutes) {
1651
+ if (!rawRoutes || rawRoutes.length === 0)
1652
+ return [];
1653
+ const shadowed = [];
1654
+ for (const [httpMethod, entries] of routeMap) {
1655
+ for (const entry of entries) {
1656
+ const probe = `/${entry.segments.map((segment) => {
1657
+ if (segment.startsWith(":"))
1658
+ return "__param__";
1659
+ if (segment.startsWith("*"))
1660
+ return "__wildcard__";
1661
+ return segment;
1662
+ }).join("/")}`;
1663
+ const match = matchRawRoute(rawRoutes, httpMethod, probe);
1664
+ if (!match)
1665
+ continue;
1666
+ shadowed.push({
1667
+ pattern: `${httpMethod} ${entry.pattern}`,
1668
+ endpoint: `${entry.method.serviceName}.${entry.method.key}`,
1669
+ rawRoute: `${match.route.method} ${match.route.path}`,
1670
+ scope: entry.method.scope
1671
+ });
1672
+ }
1673
+ }
1674
+ return shadowed;
1675
+ }
1676
+ function matchRawRoute(rawRoutes, httpMethod, pathname) {
1677
+ for (const route of rawRoutes) {
1678
+ if (route.method !== "ALL" && route.method !== httpMethod)
1679
+ continue;
1680
+ if (parseTrailingWildcard(route.path)) {
1681
+ const routeSegs = routeSegments(route.path);
1682
+ const pathSegs = routeSegments(pathname);
1683
+ const params = matchSegments(routeSegs, pathSegs);
1684
+ if (params)
1685
+ return { route, params };
1686
+ continue;
1687
+ }
1688
+ if (route.path.includes("/:")) {
1689
+ const routeSegs = routeSegments(route.path);
1690
+ const pathSegs = routeSegments(pathname);
1691
+ const params = matchSegments(routeSegs, pathSegs);
1692
+ if (params)
1693
+ return { route, params };
1694
+ continue;
1695
+ }
1696
+ if (route.path === pathname)
1697
+ return { route, params: {} };
1698
+ }
1699
+ return null;
1700
+ }
1701
+ function validateRawRoutes(rawRoutes) {
1702
+ const routes = rawRoutes ?? [];
1703
+ for (const route of routes) {
1704
+ if (route.serviceName !== undefined && route.serviceName.trim().length === 0) {
1705
+ throw new Error(`Raw route ${route.method} ${route.path} has an empty serviceName`);
1706
+ }
1707
+ if (route.action !== undefined && route.action.trim().length === 0) {
1708
+ throw new Error(`Raw route ${route.method} ${route.path} has an empty action`);
1709
+ }
1710
+ if (route.action !== undefined && route.serviceName === undefined) {
1711
+ throw new Error(`Raw route ${route.method} ${route.path} declares action without serviceName`);
1712
+ }
1713
+ }
1714
+ const shapes = routes.map((route) => rawRouteShape(route.path));
1715
+ const conflicts = [];
1716
+ for (const [laterIndex, later] of routes.entries()) {
1717
+ const laterShape = shapes[laterIndex];
1718
+ if (!laterShape)
1719
+ continue;
1720
+ for (let earlierIndex = 0;earlierIndex < laterIndex; earlierIndex++) {
1721
+ const earlier = routes[earlierIndex];
1722
+ const earlierShape = shapes[earlierIndex];
1723
+ if (!earlier || !earlierShape)
1724
+ continue;
1725
+ if (earlier.method === later.method && earlier.path === later.path) {
1726
+ conflicts.push(`${later.method} ${later.path} duplicates earlier ${earlier.method} ${earlier.path}`);
1727
+ continue;
1728
+ }
1729
+ if (earlier.method === later.method && earlierShape.signature === laterShape.signature) {
1730
+ conflicts.push(`${later.method} ${later.path} has the same parameter shape as earlier ${earlier.method} ${earlier.path}`);
1731
+ continue;
1732
+ }
1733
+ const methodCovered = earlier.method === "ALL" || earlier.method === later.method;
1734
+ if (methodCovered && routeShapeCovers(earlierShape, laterShape)) {
1735
+ conflicts.push(`${later.method} ${later.path} is unreachable because earlier ${earlier.method} ${earlier.path} matches every request it could receive`);
1736
+ }
1737
+ }
1738
+ }
1739
+ if (conflicts.length > 0) {
1740
+ throw new Error(`[stitchkit] conflicting raw routes:
1741
+ - ${conflicts.join(`
1742
+ - `)}`);
1743
+ }
1744
+ }
1745
+
1746
+ // src/server/route-table.ts
1747
+ function compileRouteTable(config, warn) {
1748
+ for (const group of config.groups ?? []) {
1749
+ if (group.hooks && "onRequest" in group.hooks) {
1750
+ throw new Error("[stitchkit] a route group cannot declare `onRequest` — it runs before routing, so the group it belongs to is not known yet and the hook would never be dispatched. Refuse before dispatch with the server-level `hooks.onRequest`, or gate the group with its `authorize`, which runs once the endpoint is known.");
1751
+ }
1752
+ }
1753
+ const routeMap = buildRouteMap(normalizeGroups(config));
1754
+ validateRoutes(routeMap);
1755
+ validateRawRoutes(config.rawRoutes);
1756
+ for (const shadow of findShadowedRoutes(routeMap, config.rawRoutes)) {
1757
+ const gate = shadow.scope && shadow.scope !== "public" ? ` (scope "${shadow.scope}")` : "";
1758
+ const line = `[stitchkit] raw route ${shadow.rawRoute} shadows contract route ${shadow.pattern}` + ` → ${shadow.endpoint}${gate} will never run, and its hooks never apply`;
1759
+ warn(line);
1760
+ }
1761
+ return routeMap;
1762
+ }
1763
+ function normalizeGroups(config) {
1764
+ const result = [];
1765
+ if (config.services) {
1766
+ for (const service of config.services) {
1767
+ const prefix = config.scopePrefixes?.[service.scope] ?? "";
1768
+ result.push({ prefix, service });
1769
+ }
1770
+ }
1771
+ if (config.groups) {
1772
+ for (const group of config.groups) {
1773
+ for (const service of group.services) {
1774
+ result.push({ prefix: group.pathPrefix ?? "", service, hooks: group.hooks });
1775
+ }
1776
+ }
1777
+ }
1778
+ return result;
1779
+ }
1780
+
1781
+ // src/server/handler-state.ts
1782
+ function createHandlerState(config) {
1783
+ const { cors, hooks, logging = false, observability } = config;
1784
+ if (cors)
1785
+ assertCorsConfig(cors);
1786
+ assertJsonBodyLimit(config.maxJsonBodyBytes, "HandlerConfig.maxJsonBodyBytes");
1787
+ const logConfig = resolveLoggingConfig(logging);
1788
+ const customLogger = logConfig?.logger ?? null;
1789
+ const useDefaultLog = logConfig !== null && !logConfig.logger;
1790
+ const warn = (line) => {
1791
+ try {
1792
+ if (customLogger)
1793
+ customLogger.warn(line);
1794
+ else
1795
+ console.warn(line);
1796
+ } catch {}
1797
+ };
1798
+ return {
1799
+ config,
1800
+ cors,
1801
+ hooks,
1802
+ observability,
1803
+ logConfig,
1804
+ customLogger,
1805
+ useDefaultLog,
1806
+ warnedEnrichKeys: new Set,
1807
+ warn,
1808
+ resolveId: createTraceIdResolver(config.traceId, warn),
1809
+ routeMap: compileRouteTable(config, warn)
1810
+ };
1811
+ }
1812
+ function createTraceIdResolver(customTraceId, warn) {
1813
+ let traceResolverBroken = false;
1814
+ return (req, fallback) => {
1815
+ if (!customTraceId)
1816
+ return fallback ?? resolveTraceId(req);
1817
+ try {
1818
+ return customTraceId(req) ?? fallback ?? resolveTraceId(req);
1819
+ } catch (err) {
1820
+ if (!traceResolverBroken) {
1821
+ traceResolverBroken = true;
1822
+ warn("[stitchkit] `traceId` resolver threw — falling back to the framework resolver. " + "Ids will not match your observability context until it is fixed: " + `${err instanceof Error ? err.message : String(err)}`);
1823
+ }
1824
+ return fallback ?? resolveTraceId(req);
1825
+ }
1826
+ };
1827
+ }
1828
+
1829
+ // src/server/logger.ts
1830
+ var c = {
1831
+ reset: "\x1B[0m",
1832
+ dim: "\x1B[2m",
1833
+ red: "\x1B[31m",
1834
+ green: "\x1B[32m",
1835
+ yellow: "\x1B[33m",
1836
+ blue: "\x1B[34m",
1837
+ magenta: "\x1B[35m",
1838
+ cyan: "\x1B[36m",
1839
+ gray: "\x1B[90m"
1840
+ };
1841
+ var METHOD_COLOR = {
1842
+ GET: c.green,
1843
+ POST: c.yellow,
1844
+ PUT: c.blue,
1845
+ PATCH: c.cyan,
1846
+ DELETE: c.red,
1847
+ OPTIONS: c.gray
1848
+ };
1849
+ var runtimeEnv = process.env;
1850
+ function resolveLogFormat(preference) {
1851
+ if (preference)
1852
+ return preference;
1853
+ return runtimeEnv.NODE_ENV === "production" ? "json" : "pretty";
1854
+ }
1855
+ function timestamp() {
1856
+ const now = new Date;
1857
+ const t = now.toLocaleTimeString("en-US", {
1858
+ hour12: false,
1859
+ hour: "2-digit",
1860
+ minute: "2-digit",
1861
+ second: "2-digit"
1862
+ });
1863
+ return `${t}.${now.getMilliseconds().toString().padStart(3, "0")}`;
1864
+ }
1865
+ function safePath(pathname) {
1866
+ let out = "";
1867
+ for (let i = 0;i < pathname.length; i++) {
1868
+ const code = pathname.charCodeAt(i);
1869
+ if (code > 31 && code !== 127)
1870
+ out += pathname.charAt(i);
1871
+ }
1872
+ return out;
1873
+ }
1874
+ function levelForStatus(status) {
1875
+ if (status === 499)
1876
+ return "info";
1877
+ if (status >= 500)
1878
+ return "error";
1879
+ if (status >= 400)
1880
+ return "warn";
1881
+ return "info";
1882
+ }
1883
+ function buildLogFields(method, path, status, durationMs, traceId, errorCode2) {
1884
+ const fields = { traceId, method, path, status, durationMs };
1885
+ if (errorCode2 === undefined && status >= 400)
1886
+ return fields;
1887
+ return { ...fields, errorCode: errorCode2 };
1888
+ }
1889
+ function formatMs(ms) {
1890
+ if (ms >= 1000)
1891
+ return `${(ms / 1000).toFixed(2)}s`;
1892
+ if (ms >= 1)
1893
+ return `${Math.round(ms)}ms`;
1894
+ return `${Math.round(ms * 1000)}µs`;
1895
+ }
1896
+ function durationColor(ms) {
1897
+ if (ms >= 1000)
1898
+ return c.red;
1899
+ if (ms > 300)
1900
+ return c.yellow;
1901
+ return c.green;
1902
+ }
1903
+ function statusColor(status) {
1904
+ if (status >= 500)
1905
+ return c.red;
1906
+ if (status >= 400)
1907
+ return c.yellow;
1908
+ if (status >= 300)
1909
+ return c.cyan;
1910
+ return c.green;
1911
+ }
1912
+ function ipLabel(ip) {
1913
+ if (!ip || ip === "::1" || ip === "127.0.0.1")
1914
+ return `${c.magenta}local${c.reset}`;
1915
+ return `${c.dim}${ip}${c.reset}`;
1916
+ }
1917
+ var SKIP_PREFIXES = ["/_bun/", "/_bundle", "/favicon"];
1918
+ function shouldLog(pathname, method) {
1919
+ if (method === "OPTIONS")
1920
+ return false;
1921
+ return !SKIP_PREFIXES.some((prefix) => pathname.startsWith(prefix));
1922
+ }
1923
+ function logIncoming(req, pathname, traceId, format, ipAddress) {
1924
+ const log = { traceId };
1925
+ if (format === "pretty") {
1926
+ const mc = METHOD_COLOR[req.method] ?? c.dim;
1927
+ console.log(`${c.gray}[${timestamp()}]${c.reset} ${mc}${req.method}${c.reset} ${c.dim}${traceId}${c.reset} ${c.cyan}→${c.reset} ${safePath(pathname)} ${ipLabel(ipAddress ?? "")}`);
1928
+ }
1929
+ return log;
1930
+ }
1931
+ function structuredLine(own, extra) {
1932
+ try {
1933
+ return JSON.stringify({ ...extra, ...own });
1934
+ } catch {
1935
+ return JSON.stringify(own);
1936
+ }
1937
+ }
1938
+ function logOutgoing(entry) {
1939
+ const { req, pathname, status, log, ipAddress, errorCode: errorCode2, durationMs, format, extra } = entry;
1940
+ const ms = durationMs;
1941
+ if (format === "json") {
1942
+ const own = {
1943
+ ts: new Date().toISOString(),
1944
+ level: levelForStatus(status),
1945
+ msg: `${req.method} ${pathname} ${status}`,
1946
+ ...buildLogFields(req.method, pathname, status, durationMs, log.traceId, errorCode2),
1947
+ ip: ipAddress
1948
+ };
1949
+ console.log(structuredLine(own, extra));
1950
+ return;
1951
+ }
1952
+ const mc = METHOD_COLOR[req.method] ?? c.dim;
1953
+ const code = errorCode2 ? ` ${c.red}${errorCode2}${c.reset}` : "";
1954
+ console.log(`${c.gray}[${timestamp()}]${c.reset} ${mc}${req.method}${c.reset} ${c.dim}${log.traceId}${c.reset} ${c.cyan}←${c.reset} ${safePath(pathname)} ${statusColor(status)}${status}${c.reset}${code} ${durationColor(ms)}${formatMs(ms)}${c.reset} ${ipLabel(ipAddress ?? "")}`);
1955
+ }
1956
+
1957
+ // src/server/request-completion.ts
1958
+ var BODY_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
1959
+ function openRequestCompletion(state, window) {
1960
+ const { logConfig, customLogger, useDefaultLog, observability } = state;
1961
+ const { req, url, traceId, startedAt, ipAddress } = window;
1962
+ const shouldLogRequest = logConfig !== null && shouldLog(url.pathname, req.method) && !shouldSkipLog(logConfig, req, url);
1963
+ const payload = observability?.includePayload && BODY_METHODS.has(req.method) ? req.clone().json().catch(() => {
1964
+ return;
1965
+ }) : undefined;
1966
+ const logFormat = resolveLogFormat(logConfig?.format);
1967
+ let reqLog;
1968
+ if (shouldLogRequest && useDefaultLog) {
1969
+ reqLog = logIncoming(req, url.pathname, traceId, logFormat, ipAddress);
1970
+ }
1971
+ if (shouldLogRequest && customLogger) {
1972
+ reqLog = { traceId };
1973
+ try {
1974
+ customLogger.debug(`${req.method} ${url.pathname}`, {
1975
+ traceId,
1976
+ method: req.method,
1977
+ path: url.pathname,
1978
+ ip: ipAddress
1979
+ });
1980
+ } catch {}
1981
+ }
1982
+ let completed = false;
1983
+ return (status, errorCode2, outcome) => {
1984
+ if (completed)
1985
+ return;
1986
+ completed = true;
1987
+ const durationMs = Math.round(Number(process.hrtime.bigint() - startedAt) / 1e6);
1988
+ if (reqLog && logConfig) {
1989
+ try {
1990
+ writeCompletionLine(state, logConfig, window, {
1991
+ reqLog,
1992
+ status,
1993
+ durationMs,
1994
+ errorCode: errorCode2,
1995
+ logFormat
1996
+ });
1997
+ } catch {}
1998
+ }
1999
+ const context = getRequestContext();
2000
+ if (observability && context) {
2001
+ try {
2002
+ observability.complete({
2003
+ context,
2004
+ statusCode: status,
2005
+ durationMs,
2006
+ payload,
2007
+ ...outcome !== undefined && { outcome }
2008
+ });
2009
+ } catch {}
2010
+ }
2011
+ };
2012
+ }
2013
+ function writeCompletionLine(state, logConfig, window, line) {
2014
+ const { customLogger, useDefaultLog, warnedEnrichKeys, warn } = state;
2015
+ const { req, url, ipAddress } = window;
2016
+ const { reqLog, status, durationMs, errorCode: errorCode2, logFormat } = line;
2017
+ const collected = collectExtraLogFields(logConfig, req, url, {
2018
+ status,
2019
+ durationMs,
2020
+ errorCode: errorCode2
2021
+ });
2022
+ const frameworkFields = buildLogFields(req.method, url.pathname, status, durationMs, reqLog.traceId, errorCode2);
2023
+ const ownedFields = { ...frameworkFields, ip: ipAddress };
2024
+ for (const key of collected.enrichKeys) {
2025
+ const ownedByActiveSink = Object.hasOwn(ownedFields, key) || useDefaultLog && (key === "ts" || key === "level" || key === "msg");
2026
+ if (ownedByActiveSink && !warnedEnrichKeys.has(key)) {
2027
+ warnedEnrichKeys.add(key);
2028
+ warn(`[stitchkit] logging.enrich field "${key}" was discarded because the framework owns it`);
2029
+ }
2030
+ }
2031
+ const extra = collected.fields;
2032
+ if (useDefaultLog) {
2033
+ logOutgoing({
2034
+ req,
2035
+ pathname: url.pathname,
2036
+ status,
2037
+ log: reqLog,
2038
+ ipAddress,
2039
+ errorCode: errorCode2,
2040
+ durationMs,
2041
+ format: logFormat,
2042
+ extra
2043
+ });
2044
+ }
2045
+ if (customLogger) {
2046
+ const level = levelForStatus(status);
2047
+ customLogger[level](`${req.method} ${url.pathname} ${status}${errorCode2 ? ` ${errorCode2}` : ""} ${durationMs}ms`, {
2048
+ ...extra,
2049
+ ...frameworkFields,
2050
+ ip: ipAddress
2051
+ });
2052
+ }
2053
+ }
2054
+
2055
+ // src/server/create.ts
2056
+ function createHandler(config) {
2057
+ const { trustProxy = false, observability } = config;
2058
+ const state = createHandlerState(config);
2059
+ return async (req, server) => {
2060
+ const url = new URL(req.url, "http://localhost");
2061
+ const requestStartedAt = process.hrtime.bigint();
2062
+ const clientIp = {
2063
+ trustProxy,
2064
+ socketIp: resolveSocketIp(req, server)
2065
+ };
2066
+ const run = async (traceId2, startedAt) => {
2067
+ const response = await dispatch(state, req, url, traceId2, server, clientIp, startedAt);
2068
+ try {
2069
+ response.headers.set("x-request-id", traceId2);
2070
+ const buildId = config.release?.current();
2071
+ if (buildId)
2072
+ response.headers.set(RELEASE_HEADER, buildId);
2073
+ } catch {}
2074
+ return response;
2075
+ };
2076
+ const activeContext = getRequestContext();
2077
+ if (activeContext) {
2078
+ return run(activeContext.trace.traceId, activeContext.startedAt);
2079
+ }
2080
+ if (!observability)
2081
+ return run(state.resolveId(req), requestStartedAt);
2082
+ const trace = resolveTraceContext(req);
2083
+ const traceId = state.resolveId(req, trace.traceId);
2084
+ const ipAddress = extractIp(req, clientIp) || undefined;
2085
+ const userAgent = req.headers.get("user-agent") ?? undefined;
2086
+ return runWithRequestContext({
2087
+ source: "http",
2088
+ method: req.method,
2089
+ path: url.pathname,
2090
+ startedAt: requestStartedAt,
2091
+ trace: { ...trace, traceId },
2092
+ ...ipAddress !== undefined && { ipAddress },
2093
+ ...userAgent !== undefined && { userAgent }
2094
+ }, () => run(traceId, requestStartedAt));
2095
+ };
2096
+ }
2097
+ async function dispatch(state, req, url, traceId, server, clientIp, startedAt) {
2098
+ const { cors, hooks, config, routeMap } = state;
2099
+ const ipAddress = extractIp(req, clientIp) || undefined;
2100
+ const complete = openRequestCompletion(state, { req, url, traceId, startedAt, ipAddress });
2101
+ const respondError = createErrorResponder(state, { req, url, traceId, clientIp, complete });
2102
+ const request = {
2103
+ req,
2104
+ url,
2105
+ traceId,
2106
+ server,
2107
+ clientIp,
2108
+ ipAddress,
2109
+ complete,
2110
+ respondError
2111
+ };
2112
+ if (cors && req.method === "OPTIONS") {
2113
+ const response = corsPreflightResponse(cors, req);
2114
+ complete(response.status);
2115
+ return response;
2116
+ }
2117
+ try {
2118
+ if (hooks?.onRequest) {
2119
+ const earlyResponse = await hooks.onRequest(req);
2120
+ if (earlyResponse instanceof Response) {
2121
+ const withCors = applyCors(earlyResponse, cors, req);
2122
+ complete(withCors.status);
2123
+ return withCors;
2124
+ }
2125
+ }
2126
+ } catch (err) {
2127
+ return respondError(err);
2128
+ }
2129
+ if (config.rawRoutes) {
2130
+ const rawMatch = matchRawRoute(config.rawRoutes, req.method, url.pathname);
2131
+ if (rawMatch) {
2132
+ if (rawMatch.route.serviceName !== undefined) {
2133
+ setRequestEndpoint(rawMatch.route.serviceName, rawMatch.route.action);
2134
+ }
2135
+ try {
2136
+ const res = await rawMatch.route.handler(req, {
2137
+ params: rawMatch.params,
2138
+ server,
2139
+ ipAddress
2140
+ });
2141
+ const withCors = applyCors(res, cors, req);
2142
+ complete(withCors.status);
2143
+ return withCors;
2144
+ } catch (err) {
2145
+ return respondError(err);
2146
+ }
2147
+ }
2148
+ }
2149
+ const match = matchRoute(routeMap, req.method, url.pathname);
2150
+ if (!match) {
2151
+ const allow = allowedMethods(routeMap, url.pathname);
2152
+ if (allow.length > 0) {
2153
+ const res = await respondError(new AppError("METHOD_NOT_ALLOWED", `Method ${req.method} not allowed`, 405));
2154
+ res.headers.set("Allow", allow.join(", "));
2155
+ return res;
2156
+ }
2157
+ return respondError(new AppError("NOT_FOUND", "Not found", 404));
2158
+ }
2159
+ return dispatchEndpoint(state, request, match);
2160
+ }
2161
+
2162
+ // src/server/implement-registry.ts
2163
+ function createScopedImplementRegistry() {
2164
+ return (contracts, handlers, options) => transportResult(bindRegistry(contracts, handlers, options));
2165
+ }
2166
+ function isImplementationContract(value) {
2167
+ return isRecord(value) && isRecord(value.meta) && typeof value.meta.prefix === "string" && isRecord(value.endpoints);
2168
+ }
2169
+ function bindRegistry(contracts, handlers, options) {
2170
+ const contractKeys = Object.keys(contracts);
2171
+ const handlerKeys = Object.keys(handlers);
2172
+ const missing = contractKeys.filter((key) => !Object.hasOwn(handlers, key));
2173
+ const extra = handlerKeys.filter((key) => !Object.hasOwn(contracts, key));
2174
+ if (missing.length > 0 || extra.length > 0) {
2175
+ if (options?.onMissingHandler !== "stub") {
2176
+ throw new Error(`[stitchkit] implementRegistry: registry mismatch (missing: ${missing.join(", ") || "none"}; extra: ${extra.join(", ") || "none"})`);
2177
+ }
2178
+ console.warn(`[stitchkit] implementRegistry: registry mismatch (missing: ${missing.join(", ") || "none"}; extra: ${extra.join(", ") || "none"}) — missing contracts are mounted as 501 stubs and extra handlers are ignored`);
2179
+ }
2180
+ const prefixes = new Map;
2181
+ const services = [];
2182
+ const byKey = {};
2183
+ for (const [key, candidate] of Object.entries(contracts)) {
2184
+ if (!isImplementationContract(candidate)) {
2185
+ throw new TypeError(`[stitchkit] implementRegistry: registry entry "${key}" must be one contract; composed arrays and namespaces are not supported`);
2186
+ }
2187
+ const contract = candidate;
2188
+ const groupScope = contract.meta.scope ?? "public";
2189
+ const identity = `${groupScope}\x00${contract.meta.prefix}`;
2190
+ const previousKey = prefixes.get(identity);
2191
+ if (previousKey !== undefined) {
2192
+ throw new Error(`[stitchkit] implementRegistry: duplicate contract prefix "${contract.meta.prefix}" in scope "${groupScope}" at "${previousKey}" and "${key}"`);
2193
+ }
2194
+ prefixes.set(identity, key);
2195
+ const entryHandlers = handlers[key] === undefined && options?.onMissingHandler === "stub" ? {} : handlers[key];
2196
+ if (!isRecord(entryHandlers)) {
2197
+ throw new TypeError(`[stitchkit] implementRegistry: handlers for "${key}" must be an object`);
2198
+ }
2199
+ const endpointKeys = Object.keys(contract.endpoints);
2200
+ const handlerEntryKeys = Object.keys(entryHandlers);
2201
+ const missingEndpoints = endpointKeys.filter((endpointKey) => !Object.hasOwn(entryHandlers, endpointKey));
2202
+ const extraEndpoints = handlerEntryKeys.filter((endpointKey) => !Object.hasOwn(contract.endpoints, endpointKey));
2203
+ if (missingEndpoints.length > 0 || extraEndpoints.length > 0) {
2204
+ const detail = `handlers for "${key}" mismatch (missing: ${missingEndpoints.join(", ") || "none"}; extra: ${extraEndpoints.join(", ") || "none"})`;
2205
+ if (options?.onMissingHandler !== "stub") {
2206
+ throw new Error(`[stitchkit] implementRegistry: ${detail}`);
2207
+ }
2208
+ console.warn(`[stitchkit] implementRegistry: ${detail} — missing endpoints are mounted as 501 stubs and extra handlers are ignored`);
2209
+ }
2210
+ const service = bindContract(contract, entryHandlers, options);
2211
+ services.push(service);
2212
+ byKey[key] = service;
2213
+ }
2214
+ Object.defineProperty(services, "byKey", { value: byKey, enumerable: false });
2215
+ return transportResult(services);
2216
+ }
2217
+ function implementRegistry(contracts, handlers, options) {
2218
+ return transportResult(bindRegistry(contracts, handlers, options));
2219
+ }
2220
+ function createImplementRegistry() {
2221
+ return (contracts, handlers, options) => transportResult(bindRegistry(contracts, handlers, options));
2222
+ }
2223
+
2224
+ // src/server/process-signals.ts
2225
+ var bound = new WeakSet;
2226
+ function bindProcessSignals(handle, options = {}) {
2227
+ if (bound.has(handle)) {
2228
+ throw new Error("[stitchkit] bindProcessSignals: this server is already bound; close the first binding before creating another");
2229
+ }
2230
+ bound.add(handle);
2231
+ const signals = [...new Set(options.signals ?? DEFAULT_PROCESS_SIGNALS)];
2232
+ const source = options.signalSource ?? defaultSignalSource;
2233
+ const requested = options.shutdown ?? {};
2234
+ const validated = ShutdownOptionsSchema.omit({ signal: true }).parse(requested);
2235
+ const budgets = {
2236
+ ...requested.gracePeriodMs !== undefined && { gracePeriodMs: validated.gracePeriodMs },
2237
+ ...requested.forceTimeoutMs !== undefined && {
2238
+ forceTimeoutMs: validated.forceTimeoutMs
2239
+ },
2240
+ ...requested.realtimeCloseTimeoutMs !== undefined && {
2241
+ realtimeCloseTimeoutMs: validated.realtimeCloseTimeoutMs
2242
+ },
2243
+ ...requested.retryAfterSeconds !== undefined && {
2244
+ retryAfterSeconds: validated.retryAfterSeconds
2245
+ }
2246
+ };
2247
+ const controller = new AbortController;
2248
+ const handlers = [];
2249
+ let started = false;
2250
+ let sameTurnAsStart = false;
2251
+ let settled = false;
2252
+ let closed = false;
2253
+ let resolveChain = () => {
2254
+ return;
2255
+ };
2256
+ let rejectChain = () => {
2257
+ return;
2258
+ };
2259
+ const promise = new Promise((resolve, reject) => {
2260
+ resolveChain = resolve;
2261
+ rejectChain = reject;
2262
+ });
2263
+ promise.catch(() => {
2264
+ return;
2265
+ });
2266
+ const removeListeners = () => {
2267
+ if (closed)
2268
+ return;
2269
+ closed = true;
2270
+ for (const [signal, handler] of handlers)
2271
+ source.off(signal, handler);
2272
+ if (!started)
2273
+ bound.delete(handle);
2274
+ };
2275
+ const close = () => {
2276
+ const hadStarted = started;
2277
+ removeListeners();
2278
+ if (!hadStarted)
2279
+ resolveChain(undefined);
2280
+ };
2281
+ const run = async (signal) => {
2282
+ try {
2283
+ await options.onShutdown?.(signal);
2284
+ } catch (error) {
2285
+ reportSignalError("prepare", error, options.onError);
2286
+ }
2287
+ let result;
2288
+ try {
2289
+ result = await handle.shutdown({ ...budgets, signal: controller.signal });
2290
+ } catch (error) {
2291
+ settled = true;
2292
+ rejectChain(error);
2293
+ reportSignalError("shutdown", error, options.onError);
2294
+ removeListeners();
2295
+ return;
2296
+ }
2297
+ settled = true;
2298
+ resolveChain(result);
2299
+ try {
2300
+ await options.onComplete?.(result);
2301
+ } catch (error) {
2302
+ reportSignalError("complete", error, options.onError);
2303
+ } finally {
2304
+ removeListeners();
2305
+ }
2306
+ };
2307
+ const onSignal = (signal) => {
2308
+ if (!started) {
2309
+ started = true;
2310
+ sameTurnAsStart = true;
2311
+ queueMicrotask(() => {
2312
+ sameTurnAsStart = false;
2313
+ });
2314
+ run(signal).catch((error) => reportSignalError("shutdown", error, options.onError));
2315
+ return;
2316
+ }
2317
+ if (sameTurnAsStart)
2318
+ return;
2319
+ if (!settled && !controller.signal.aborted) {
2320
+ controller.abort();
2321
+ guardSignalCallback(() => options.onRepeatedSignal?.(signal, "force"), "shutdown", options.onError);
2322
+ return;
2323
+ }
2324
+ removeListeners();
2325
+ guardSignalCallback(() => options.onRepeatedSignal?.(signal, "escalate"), "shutdown", options.onError);
2326
+ let restored = false;
2327
+ try {
2328
+ restored = source.raiseDefault(signal);
2329
+ } catch (error) {
2330
+ reportSignalError("shutdown", error, options.onError);
2331
+ }
2332
+ if (!restored) {
2333
+ guardSignalCallback(() => options.onEscalationBlocked?.(signal), "shutdown", options.onError);
2334
+ }
2335
+ };
2336
+ for (const signal of signals) {
2337
+ const handler = () => onSignal(signal);
2338
+ handlers.push([signal, handler]);
2339
+ source.on(signal, handler);
2340
+ }
2341
+ return { promise, close };
2342
+ }
2343
+
2344
+ // src/server/realtime.ts
2345
+ function bindRealtimeServer(contract, handle, options = {}) {
2346
+ const outbound = (target) => createValidatedRealtimeSocket({
2347
+ target,
2348
+ inbound: {},
2349
+ outbound: contract.serverToClient,
2350
+ inboundDirection: "server-inbound",
2351
+ outboundDirection: "server-outbound",
2352
+ onRejected: options.onRejected,
2353
+ logger: options.logger
2354
+ });
2355
+ const broadcast = outbound(handle.io);
2356
+ return {
2357
+ onConnection: (handler) => {
2358
+ const listener = (raw) => {
2359
+ const events = createValidatedRealtimeSocket({
2360
+ target: raw,
2361
+ inbound: contract.clientToServer,
2362
+ outbound: contract.serverToClient,
2363
+ inboundDirection: "server-inbound",
2364
+ outboundDirection: "server-outbound",
2365
+ onRejected: options.onRejected,
2366
+ logger: options.logger
2367
+ });
2368
+ handler({
2369
+ raw,
2370
+ events,
2371
+ to: (room) => outbound(raw.to(room))
2372
+ });
2373
+ };
2374
+ handle.io.on("connection", listener);
2375
+ return () => {
2376
+ handle.io.off("connection", listener);
2377
+ };
2378
+ },
2379
+ emit: broadcast.emit,
2380
+ to: (room) => outbound(handle.io.to(room))
2381
+ };
2382
+ }
2383
+
2384
+ // src/server/websocket.ts
2385
+ function webSocketLane(lane) {
2386
+ const { match, handlers } = lane;
2387
+ return {
2388
+ match,
2389
+ handlers: {
2390
+ message(ws, message) {
2391
+ if (match(ws))
2392
+ handlers.message(ws, message);
2393
+ },
2394
+ open(ws) {
2395
+ if (match(ws))
2396
+ handlers.open?.(ws);
2397
+ },
2398
+ close(ws, code, reason) {
2399
+ if (match(ws))
2400
+ handlers.close?.(ws, code, reason);
2401
+ },
2402
+ drain(ws) {
2403
+ if (match(ws))
2404
+ handlers.drain?.(ws);
2405
+ },
2406
+ ping(ws, data) {
2407
+ if (match(ws))
2408
+ handlers.ping?.(ws, data);
2409
+ },
2410
+ pong(ws, data) {
2411
+ if (match(ws))
2412
+ handlers.pong?.(ws, data);
2413
+ }
2414
+ }
2415
+ };
2416
+ }
2417
+ function composeWebSocketHandlers(lanes, config) {
2418
+ const pick = (ws) => lanes.find((lane) => lane.match(ws));
2419
+ return {
2420
+ ...config,
2421
+ message(ws, message) {
2422
+ pick(ws)?.handlers.message(ws, message);
2423
+ },
2424
+ open(ws) {
2425
+ pick(ws)?.handlers.open?.(ws);
2426
+ },
2427
+ close(ws, code, reason) {
2428
+ pick(ws)?.handlers.close?.(ws, code, reason);
2429
+ },
2430
+ drain(ws) {
2431
+ pick(ws)?.handlers.drain?.(ws);
2432
+ },
2433
+ ping(ws, data) {
2434
+ pick(ws)?.handlers.ping?.(ws, data);
2435
+ },
2436
+ pong(ws, data) {
2437
+ pick(ws)?.handlers.pong?.(ws, data);
2438
+ }
2439
+ };
2440
+ }
2441
+
2442
+ // src/server/socket-io.ts
2443
+ var SOCKET_IO_SERVER = "socket.io";
2444
+ var SOCKET_IO_BUN_ENGINE = "@socket.io/bun-engine";
2445
+ var noop = () => {};
2446
+ async function importPeer(load, pkg, injected) {
2447
+ try {
2448
+ return await load();
2449
+ } catch (err) {
2450
+ if (isModuleNotFound(err)) {
2451
+ throw new Error(injected ? `[stitchkit] createSocketIOServer could not load the optional peer "${pkg}" through the loader passed in \`peers\` — the artifact does not contain it. Check that the loader is a literal \`import('${pkg}')\` your bundler can follow, and that "${pkg}" is a dependency of the package being bundled.` : `[stitchkit] createSocketIOServer needs the optional peer "${pkg}" — install it: bun add ${pkg}. Shipping one self-contained artifact instead? Pass \`peers: { … }\` so your bundler puts it inside.`, { cause: err });
2452
+ }
2453
+ throw err;
2454
+ }
2455
+ }
2456
+ function isBunEngineModule(value) {
2457
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "Server") === "function";
2458
+ }
2459
+ function handshakeRejection(message) {
2460
+ const error = new Error(message);
2461
+ error.data = { code: "handshake_rejected" };
2462
+ return error;
2463
+ }
2464
+ function handshakeMiddleware(handshake) {
2465
+ return (socket, next) => {
2466
+ let parsed;
2467
+ try {
2468
+ parsed = handshake.schema.safeParse(socket.handshake.auth);
2469
+ } catch (error) {
2470
+ console.error("[stitchkit] handshake schema threw — use a synchronous schema", error);
2471
+ next(handshakeRejection("handshake auth failed validation"));
2472
+ return;
2473
+ }
2474
+ if (!parsed.success) {
2475
+ next(handshakeRejection("handshake auth failed validation"));
2476
+ return;
2477
+ }
2478
+ const verify = handshake.verify;
2479
+ Promise.resolve().then(() => {
2480
+ if (verify)
2481
+ return verify(parsed.data, { handshake: socket.handshake });
2482
+ return transportResult(parsed.data);
2483
+ }).then((identity) => {
2484
+ if (identity === null || identity === undefined) {
2485
+ next(handshakeRejection("handshake rejected"));
2486
+ return;
2487
+ }
2488
+ socket.data = identity;
2489
+ next();
2490
+ }, (error) => {
2491
+ console.error("[stitchkit] handshake verify rejected", error);
2492
+ next(handshakeRejection("handshake rejected"));
2493
+ });
2494
+ };
2495
+ }
2496
+ async function createSocketIOServer(config) {
2497
+ const path = config.path ?? "/socket.io/";
2498
+ const onBun = "Bun" in globalThis;
2499
+ const transports = config.transports ?? (onBun ? ["websocket", "polling"] : ["websocket"]);
2500
+ const pingTimeout = config.pingTimeout ?? 20000;
2501
+ const pingInterval = config.pingInterval ?? 1e4;
2502
+ const cors = config.cors ? {
2503
+ origin: config.cors.origin,
2504
+ credentials: config.cors.credentials ?? true,
2505
+ methods: ["GET", "POST"]
2506
+ } : undefined;
2507
+ let accepting = true;
2508
+ let attached = false;
2509
+ let closePromise;
2510
+ const consumerAllowRequest = config.allowRequest;
2511
+ const checkRequest = async (request) => {
2512
+ if (onBun) {
2513
+ const requested = new URL(request.url).searchParams.get("transport");
2514
+ if (!transports.some((transport) => transport === requested)) {
2515
+ throw new Error("Transport rejected by the configured Socket.IO policy");
2516
+ }
2517
+ }
2518
+ if (consumerAllowRequest && !await consumerAllowRequest(request)) {
2519
+ throw new Error("Request rejected by the configured Socket.IO policy");
2520
+ }
2521
+ if (!accepting)
2522
+ throw new Error("Server is shutting down");
2523
+ };
2524
+ const allowRequest = (request, done) => {
2525
+ const headers = new Headers;
2526
+ for (const [name, value] of Object.entries(request.headers)) {
2527
+ if (Array.isArray(value)) {
2528
+ for (const item of value)
2529
+ headers.append(name, item);
2530
+ } else if (value !== undefined) {
2531
+ headers.set(name, value);
2532
+ }
2533
+ }
2534
+ const host = headers.get("host") ?? "localhost";
2535
+ const webRequest = new Request(new URL(request.url ?? "/", `http://${host}`), {
2536
+ method: request.method,
2537
+ headers
2538
+ });
2539
+ checkRequest(webRequest).then(() => done(null, true), (error) => done(error instanceof Error ? error.message : "Request rejected", false));
2540
+ };
2541
+ const injectedServer = config.peers?.server;
2542
+ const { Server } = await importPeer(injectedServer ?? (() => import(SOCKET_IO_SERVER).then((module) => module)), SOCKET_IO_SERVER, injectedServer !== undefined);
2543
+ const io = new Server({
2544
+ ...config.serverOptions,
2545
+ path,
2546
+ cors,
2547
+ transports,
2548
+ pingTimeout,
2549
+ pingInterval,
2550
+ allowRequest
2551
+ });
2552
+ if (config.handshake)
2553
+ io.use(handshakeMiddleware(config.handshake));
2554
+ const lifecycle = {
2555
+ beginShutdown() {
2556
+ accepting = false;
2557
+ },
2558
+ close() {
2559
+ if (closePromise)
2560
+ return closePromise;
2561
+ closePromise = onBun || attached ? io.close() : Promise.resolve();
2562
+ return closePromise;
2563
+ },
2564
+ connections() {
2565
+ return io.engine?.clientsCount ?? 0;
2566
+ }
2567
+ };
2568
+ if (onBun) {
2569
+ const injectedEngine = config.peers?.bunEngine;
2570
+ const engineModule = await importPeer(injectedEngine ?? (() => import(SOCKET_IO_BUN_ENGINE).then((module) => module)), SOCKET_IO_BUN_ENGINE, injectedEngine !== undefined);
2571
+ if (!isBunEngineModule(engineModule)) {
2572
+ throw new Error(`[stitchkit] the loader passed in \`peers.bunEngine\` did not return the "${SOCKET_IO_BUN_ENGINE}" module — it must resolve to the module itself, as \`() => import('${SOCKET_IO_BUN_ENGINE}')\`.`);
2573
+ }
2574
+ const { Server: Engine } = engineModule;
2575
+ const engineOpts = {
2576
+ path,
2577
+ cors,
2578
+ pingTimeout,
2579
+ pingInterval,
2580
+ allowRequest: checkRequest
2581
+ };
2582
+ if (config.serverOptions?.maxHttpBufferSize !== undefined) {
2583
+ engineOpts.maxHttpBufferSize = config.serverOptions.maxHttpBufferSize;
2584
+ }
2585
+ if (config.serverOptions?.upgradeTimeout !== undefined) {
2586
+ engineOpts.upgradeTimeout = config.serverOptions.upgradeTimeout;
2587
+ }
2588
+ const engine = new Engine(engineOpts);
2589
+ io.bind(engine);
2590
+ const { websocket } = engine.handler();
2591
+ const route = {
2592
+ method: "ALL",
2593
+ path: `${path.replace(/\/+$/, "")}/*socketPath`,
2594
+ handler: (req, ctx) => {
2595
+ if (!ctx.server) {
2596
+ throw new Error("[stitchkit] createSocketIOServer route needs a running Bun server — mount it via createServer.");
2597
+ }
2598
+ return engine.handleRequest(req, ctx.server);
2599
+ }
2600
+ };
2601
+ return { io, websocket, route, attach: noop, ...lifecycle };
2602
+ }
2603
+ return {
2604
+ io,
2605
+ attach: (server) => {
2606
+ io.attach(server);
2607
+ attached = true;
2608
+ },
2609
+ websocket: { open: noop, message: noop, close: noop, maxPayloadLength: 0 },
2610
+ route: {
2611
+ method: "ALL",
2612
+ path: `${path.replace(/\/+$/, "")}/*socketPath`,
2613
+ handler: () => {
2614
+ throw new Error("[stitchkit] On Node, Socket.IO attaches via serveNode({ socket }) — this route is not mounted.");
2615
+ }
2616
+ },
2617
+ ...lifecycle
2618
+ };
2619
+ }
2620
+ function socketIoLane(websocket) {
2621
+ return webSocketLane({
2622
+ match: (_ws) => true,
2623
+ handlers: websocket
2624
+ });
2625
+ }
2626
+
2627
+ // src/server/unix-client-error.ts
2628
+ class UnixClientTransportError extends Error {
2629
+ code;
2630
+ delivery;
2631
+ constructor(code, message, delivery = "possibly-dispatched", options) {
2632
+ super(message, options);
2633
+ this.code = code;
2634
+ this.delivery = delivery;
2635
+ this.name = "UnixClientTransportError";
2636
+ }
2637
+ }
2638
+
2639
+ // src/server/unix-client.ts
2640
+ import {
2641
+ Agent,
2642
+ request as httpRequest
2643
+ } from "node:http";
2644
+
2645
+ // src/server/unix-client-body.ts
2646
+ async function readBoundedRequestBody(request, maxBytes) {
2647
+ const body = request.body;
2648
+ if (!body)
2649
+ return;
2650
+ const declared = request.headers.get("content-length");
2651
+ if (declared !== null && Number(declared) > maxBytes) {
2652
+ throw new UnixClientTransportError("UNIX_REQUEST_TOO_LARGE", `Unix request body exceeds the ${maxBytes} byte limit`, "not-dispatched");
2653
+ }
2654
+ const reader = body.getReader();
2655
+ const chunks = [];
2656
+ let total = 0;
2657
+ try {
2658
+ for (;; ) {
2659
+ if (request.signal.aborted)
2660
+ throw request.signal.reason;
2661
+ const chunk = await reader.read();
2662
+ if (chunk.done)
2663
+ break;
2664
+ total += chunk.value.byteLength;
2665
+ if (total > maxBytes) {
2666
+ throw new UnixClientTransportError("UNIX_REQUEST_TOO_LARGE", `Unix request body exceeds the ${maxBytes} byte limit`, "not-dispatched");
2667
+ }
2668
+ chunks.push(chunk.value);
2669
+ }
2670
+ } finally {
2671
+ reader.releaseLock();
2672
+ }
2673
+ const result = new Uint8Array(total);
2674
+ let offset = 0;
2675
+ for (const chunk of chunks) {
2676
+ result.set(chunk, offset);
2677
+ offset += chunk.byteLength;
2678
+ }
2679
+ return result;
2680
+ }
2681
+ function incomingResponseBody(response, maxBytes, onDone) {
2682
+ let finished = false;
2683
+ let received = 0;
2684
+ const finish = () => {
2685
+ if (finished)
2686
+ return;
2687
+ finished = true;
2688
+ onDone();
2689
+ };
2690
+ return new ReadableStream({
2691
+ start(controller) {
2692
+ response.pause();
2693
+ response.on("data", (chunk) => {
2694
+ if (finished)
2695
+ return;
2696
+ if (maxBytes !== undefined)
2697
+ received += chunk.byteLength;
2698
+ if (maxBytes !== undefined && received > maxBytes) {
2699
+ controller.error(new UnixClientTransportError("UNIX_RESPONSE_TOO_LARGE", `Unix response body exceeds the ${maxBytes} byte limit`, "response-received"));
2700
+ response.destroy();
2701
+ finish();
2702
+ return;
2703
+ }
2704
+ controller.enqueue(new Uint8Array(chunk));
2705
+ response.pause();
2706
+ });
2707
+ response.once("end", () => {
2708
+ if (finished)
2709
+ return;
2710
+ controller.close();
2711
+ finish();
2712
+ });
2713
+ response.once("aborted", () => {
2714
+ if (finished)
2715
+ return;
2716
+ controller.error(new UnixClientTransportError("UNIX_RESPONSE_ABORTED", "Unix response was aborted before completion", "response-received"));
2717
+ finish();
2718
+ });
2719
+ response.once("error", (error) => {
2720
+ if (finished)
2721
+ return;
2722
+ controller.error(new UnixClientTransportError("UNIX_RESPONSE_ABORTED", "Unix response failed before completion", "response-received", { cause: error }));
2723
+ finish();
2724
+ });
2725
+ },
2726
+ pull() {
2727
+ response.resume();
2728
+ },
2729
+ cancel() {
2730
+ response.destroy();
2731
+ finish();
2732
+ }
2733
+ }, { highWaterMark: 1 });
2734
+ }
2735
+
2736
+ // src/server/unix-client-http1.ts
2737
+ var MAX_BODY_CHUNK_BYTES = 64 * 1024;
2738
+ var MAX_CHUNK_HEADER_BYTES = 1024;
2739
+ var CRLF2 = [13, 10];
2740
+ var CRLFCRLF = [13, 10, 13, 10];
2741
+ function concatBytes2(left, right) {
2742
+ if (left.byteLength === 0)
2743
+ return right.slice();
2744
+ const combined = new Uint8Array(left.byteLength + right.byteLength);
2745
+ combined.set(left);
2746
+ combined.set(right, left.byteLength);
2747
+ return combined;
2748
+ }
2749
+ function indexOfSequence(bytes, sequence) {
2750
+ outer:
2751
+ for (let index = 0;index <= bytes.byteLength - sequence.length; index += 1) {
2752
+ for (let offset = 0;offset < sequence.length; offset += 1) {
2753
+ if (bytes[index + offset] !== sequence[offset])
2754
+ continue outer;
2755
+ }
2756
+ return index;
2757
+ }
2758
+ return -1;
2759
+ }
2760
+
2761
+ class WireBuffer {
2762
+ bytes = new Uint8Array;
2763
+ get byteLength() {
2764
+ return this.bytes.byteLength;
2765
+ }
2766
+ append(data) {
2767
+ this.bytes = concatBytes2(this.bytes, data);
2768
+ }
2769
+ take(count) {
2770
+ const value = this.bytes.slice(0, count);
2771
+ this.bytes = this.bytes.slice(count);
2772
+ return value;
2773
+ }
2774
+ indexOf(sequence) {
2775
+ return indexOfSequence(this.bytes, sequence);
2776
+ }
2777
+ startsWith(sequence) {
2778
+ return sequence.every((byte, index) => this.bytes[index] === byte);
2779
+ }
2780
+ }
2781
+ function requestBytes(request, body) {
2782
+ const url = new URL(request.url);
2783
+ const headers = new Headers(request.headers);
2784
+ headers.set("host", url.host);
2785
+ headers.set("connection", "close");
2786
+ headers.set("accept-encoding", "identity");
2787
+ headers.delete("transfer-encoding");
2788
+ headers.delete("content-length");
2789
+ if (body !== undefined)
2790
+ headers.set("content-length", String(body.byteLength));
2791
+ const lines = [`${request.method} ${url.pathname}${url.search} HTTP/1.1`];
2792
+ for (const [name, value] of headers)
2793
+ lines.push(`${name}: ${value}`);
2794
+ const head = new TextEncoder().encode(`${lines.join(`\r
2795
+ `)}\r
2796
+ \r
2797
+ `);
2798
+ return body === undefined ? head : concatBytes2(head, body);
2799
+ }
2800
+ function parseContentLength(headers) {
2801
+ const raw = headers.get("content-length");
2802
+ if (raw === null)
2803
+ return;
2804
+ if (!/^\d+$/.test(raw))
2805
+ throw new Error("Unix response has an invalid Content-Length");
2806
+ const value = Number(raw);
2807
+ if (!Number.isSafeInteger(value)) {
2808
+ throw new Error("Unix response Content-Length is not a safe integer");
2809
+ }
2810
+ return value;
2811
+ }
2812
+ function readResponseHead(wire, maxHeaderBytes) {
2813
+ const headerEnd = wire.indexOf(CRLFCRLF);
2814
+ if (headerEnd < 0) {
2815
+ return wire.byteLength > maxHeaderBytes ? { kind: "too-large" } : { kind: "more" };
2816
+ }
2817
+ if (headerEnd + 4 > maxHeaderBytes)
2818
+ return { kind: "too-large" };
2819
+ let text;
2820
+ try {
2821
+ text = new TextDecoder("utf-8", { fatal: true }).decode(wire.take(headerEnd));
2822
+ } catch (error) {
2823
+ return { kind: "malformed", error };
2824
+ }
2825
+ wire.take(4);
2826
+ const lines = text.split(`\r
2827
+ `);
2828
+ const statusLine = lines.shift() ?? "";
2829
+ const matched = /^HTTP\/1\.[01] (\d{3})(?: (.*))?$/.exec(statusLine);
2830
+ if (!matched) {
2831
+ return {
2832
+ kind: "malformed",
2833
+ error: new Error("Unix response has an invalid HTTP status line")
2834
+ };
2835
+ }
2836
+ const headers = new Headers;
2837
+ let contentLength;
2838
+ try {
2839
+ for (const line of lines) {
2840
+ const separator = line.indexOf(":");
2841
+ if (separator <= 0)
2842
+ throw new Error("Unix response has an invalid header line");
2843
+ headers.append(line.slice(0, separator).trim(), line.slice(separator + 1).trim());
2844
+ }
2845
+ contentLength = parseContentLength(headers);
2846
+ } catch (error) {
2847
+ return { kind: "malformed", error };
2848
+ }
2849
+ return {
2850
+ kind: "head",
2851
+ status: Number(matched[1]),
2852
+ statusText: matched[2] ?? "",
2853
+ headers,
2854
+ contentLength,
2855
+ chunked: headers.get("transfer-encoding")?.toLowerCase().includes("chunked") ?? false
2856
+ };
2857
+ }
2858
+ var malformed = (message) => ({
2859
+ kind: "malformed",
2860
+ error: new Error(message)
2861
+ });
2862
+
2863
+ class BodyDecoder {
2864
+ chunked;
2865
+ remainingLength;
2866
+ maxHeaderBytes;
2867
+ chunkRemaining;
2868
+ expectChunkCrlf = false;
2869
+ trailers = false;
2870
+ constructor(chunked, remainingLength, maxHeaderBytes) {
2871
+ this.chunked = chunked;
2872
+ this.remainingLength = remainingLength;
2873
+ this.maxHeaderBytes = maxHeaderBytes;
2874
+ }
2875
+ next(wire, peerEnded) {
2876
+ return this.chunked ? this.nextChunked(wire, peerEnded) : this.nextPlain(wire, peerEnded);
2877
+ }
2878
+ nextPlain(wire, peerEnded) {
2879
+ if (wire.byteLength > 0) {
2880
+ const permitted = this.remainingLength ?? wire.byteLength;
2881
+ const bytes = Math.min(permitted, wire.byteLength, MAX_BODY_CHUNK_BYTES);
2882
+ if (this.remainingLength !== undefined)
2883
+ this.remainingLength -= bytes;
2884
+ return { kind: "data", value: wire.take(bytes) };
2885
+ }
2886
+ if (this.remainingLength === 0)
2887
+ return { kind: "complete" };
2888
+ if (!peerEnded)
2889
+ return { kind: "more" };
2890
+ return this.remainingLength !== undefined && this.remainingLength > 0 ? malformed("Unix response ended before Content-Length bytes arrived") : { kind: "complete" };
2891
+ }
2892
+ get plainComplete() {
2893
+ return !this.chunked && this.remainingLength === 0;
2894
+ }
2895
+ nextChunked(wire, peerEnded) {
2896
+ for (;; ) {
2897
+ if (this.trailers)
2898
+ return this.readTrailers(wire, peerEnded);
2899
+ if (this.expectChunkCrlf) {
2900
+ if (wire.byteLength < 2) {
2901
+ return peerEnded ? malformed("Unix chunked response ended before chunk delimiter") : { kind: "more" };
2902
+ }
2903
+ if (!wire.startsWith(CRLF2)) {
2904
+ return malformed("Unix chunked response has an invalid chunk delimiter");
2905
+ }
2906
+ wire.take(2);
2907
+ this.expectChunkCrlf = false;
2908
+ }
2909
+ if (this.chunkRemaining === undefined) {
2910
+ const header = this.readChunkHeader(wire, peerEnded);
2911
+ if (header !== undefined)
2912
+ return header;
2913
+ if (this.trailers)
2914
+ continue;
2915
+ }
2916
+ const remaining = this.chunkRemaining ?? 0;
2917
+ if (wire.byteLength === 0) {
2918
+ return peerEnded ? malformed("Unix chunked response ended inside a chunk") : { kind: "more" };
2919
+ }
2920
+ const bytes = Math.min(remaining, wire.byteLength, MAX_BODY_CHUNK_BYTES);
2921
+ const value = wire.take(bytes);
2922
+ this.chunkRemaining = remaining - bytes;
2923
+ if (this.chunkRemaining === 0) {
2924
+ this.chunkRemaining = undefined;
2925
+ this.expectChunkCrlf = true;
2926
+ }
2927
+ return { kind: "data", value };
2928
+ }
2929
+ }
2930
+ readChunkHeader(wire, peerEnded) {
2931
+ const lineEnd = wire.indexOf(CRLF2);
2932
+ if (lineEnd < 0) {
2933
+ if (wire.byteLength > MAX_CHUNK_HEADER_BYTES)
2934
+ return malformed("Unix chunk header is too large");
2935
+ return peerEnded ? malformed("Unix chunked response ended inside chunk header") : { kind: "more" };
2936
+ }
2937
+ const line = new TextDecoder("ascii", { fatal: true }).decode(wire.take(lineEnd));
2938
+ wire.take(2);
2939
+ const sizeText = line.split(";", 1)[0]?.trim() ?? "";
2940
+ if (!/^[0-9a-f]+$/i.test(sizeText)) {
2941
+ return malformed("Unix chunked response has an invalid chunk size");
2942
+ }
2943
+ const size = Number.parseInt(sizeText, 16);
2944
+ if (!Number.isSafeInteger(size))
2945
+ return malformed("Unix chunk size is not a safe integer");
2946
+ if (size === 0)
2947
+ this.trailers = true;
2948
+ else
2949
+ this.chunkRemaining = size;
2950
+ return;
2951
+ }
2952
+ readTrailers(wire, peerEnded) {
2953
+ if (wire.byteLength >= 2 && wire.startsWith(CRLF2)) {
2954
+ wire.take(2);
2955
+ return { kind: "complete" };
2956
+ }
2957
+ const trailerEnd = wire.indexOf(CRLFCRLF);
2958
+ if (trailerEnd < 0) {
2959
+ if (wire.byteLength > this.maxHeaderBytes)
2960
+ return { kind: "trailers-too-large" };
2961
+ return peerEnded ? malformed("Unix chunked response ended inside trailers") : { kind: "more" };
2962
+ }
2963
+ wire.take(trailerEnd + 4);
2964
+ return { kind: "complete" };
2965
+ }
2966
+ }
2967
+
2968
+ // src/server/unix-client-bun.ts
2969
+ function isBunUnixRuntime(candidate) {
2970
+ if (typeof candidate !== "object" || candidate === null)
2971
+ return false;
2972
+ return typeof Reflect.get(candidate, "connect") === "function";
2973
+ }
2974
+ function runtimeBun() {
2975
+ const candidate = Reflect.get(globalThis, "Bun");
2976
+ return isBunUnixRuntime(candidate) ? candidate : undefined;
2977
+ }
2978
+ function hasBunUnixRuntime() {
2979
+ return runtimeBun() !== undefined;
2980
+ }
2981
+ function classifyTransportFailure(error, headersReceived, dispatched) {
2982
+ if (error instanceof UnixClientTransportError)
2983
+ return error;
2984
+ if (headersReceived) {
2985
+ return new UnixClientTransportError("UNIX_RESPONSE_ABORTED", "Unix response failed before completion", "response-received", { cause: error });
2986
+ }
2987
+ return new UnixClientTransportError(dispatched ? "UNIX_DELIVERY_UNCERTAIN" : "UNIX_CONNECT_FAILED", dispatched ? "Unix request transport failed after dispatch may have begun" : "Unix socket connection failed before request dispatch", dispatched ? "possibly-dispatched" : "not-dispatched", { cause: error });
2988
+ }
2989
+ function limitError(limit, what, bytes) {
2990
+ return limit === "body" ? new UnixClientTransportError("UNIX_RESPONSE_TOO_LARGE", `Unix response body exceeds the ${bytes} byte limit`, "response-received") : new UnixClientTransportError("UNIX_HEADERS_TOO_LARGE", `Unix response ${what} exceed the ${bytes} byte limit`, "response-received");
2991
+ }
2992
+ function socketHandlers(events) {
2993
+ return {
2994
+ binaryType: "uint8array",
2995
+ open: events.open,
2996
+ drain: events.flush,
2997
+ data(active, data) {
2998
+ active.pause();
2999
+ events.data(data);
3000
+ },
3001
+ end: () => events.ended(undefined, "ended"),
3002
+ close: (_active, error) => events.ended(error, "closed"),
3003
+ error: (_active, error) => events.failed(error),
3004
+ connectError: (_active, error) => events.failed(error)
3005
+ };
3006
+ }
3007
+ function writeAvailable(active, bytes, offset) {
3008
+ let written = offset;
3009
+ while (written < bytes.byteLength) {
3010
+ const count = active.write(bytes, written, bytes.byteLength - written);
3011
+ if (count < 0)
3012
+ return "closed";
3013
+ if (count === 0)
3014
+ break;
3015
+ written += count;
3016
+ }
3017
+ return written;
3018
+ }
3019
+ function bunUnixRequest(options) {
3020
+ const outgoing = requestBytes(options.request, options.body);
3021
+ const bun = runtimeBun();
3022
+ if (!bun)
3023
+ throw new Error("Bun Unix runtime is unavailable");
3024
+ let socket;
3025
+ let controller;
3026
+ const wire = new WireBuffer;
3027
+ let decoder2;
3028
+ let responseResolved = false;
3029
+ let headersReceived = false;
3030
+ let settled = false;
3031
+ let bodyComplete = false;
3032
+ let peerEnded = false;
3033
+ let received = 0;
3034
+ let writeOffset = 0;
3035
+ let resolveResponse = () => {
3036
+ return;
3037
+ };
3038
+ let rejectResponse = () => {
3039
+ return;
3040
+ };
3041
+ const response = new Promise((resolve, reject) => {
3042
+ resolveResponse = resolve;
3043
+ rejectResponse = reject;
3044
+ });
3045
+ const transportFailure = (error) => classifyTransportFailure(error, headersReceived, writeOffset > 0);
3046
+ const clearRegistration = options.registerAbort(() => {
3047
+ fail(new UnixClientTransportError("UNIX_CLIENT_CLOSED", "Unix client transport is closed"));
3048
+ });
3049
+ const timer = setTimeout(() => {
3050
+ fail(new UnixClientTransportError("UNIX_HEADERS_TIMEOUT", `Unix response headers did not arrive within ${options.headersTimeoutMs}ms`));
3051
+ }, options.headersTimeoutMs);
3052
+ timer.unref();
3053
+ const removeRequestAbort = () => {
3054
+ options.request.signal.removeEventListener("abort", abortRequest);
3055
+ };
3056
+ const finish = (terminate = true) => {
3057
+ if (settled)
3058
+ return;
3059
+ settled = true;
3060
+ clearTimeout(timer);
3061
+ clearRegistration();
3062
+ removeRequestAbort();
3063
+ if (terminate)
3064
+ socket?.terminate();
3065
+ };
3066
+ function fail(error) {
3067
+ if (settled)
3068
+ return;
3069
+ if (responseResolved)
3070
+ controller?.error(error);
3071
+ else
3072
+ rejectResponse(error);
3073
+ finish();
3074
+ }
3075
+ function abortRequest() {
3076
+ fail(options.request.signal.reason ?? new DOMException("Request aborted", "AbortError"));
3077
+ }
3078
+ const enqueue = (value) => {
3079
+ if (options.maxResponseBytes !== undefined)
3080
+ received += value.byteLength;
3081
+ if (options.maxResponseBytes !== undefined && received > options.maxResponseBytes) {
3082
+ fail(limitError("body", "body", options.maxResponseBytes));
3083
+ return;
3084
+ }
3085
+ controller?.enqueue(value);
3086
+ };
3087
+ const completeBody = () => {
3088
+ if (bodyComplete || settled)
3089
+ return;
3090
+ bodyComplete = true;
3091
+ controller?.close();
3092
+ finish();
3093
+ };
3094
+ const resumeForData = () => {
3095
+ if (settled || bodyComplete || peerEnded)
3096
+ return;
3097
+ socket?.resume();
3098
+ };
3099
+ const headersTooLarge = (what) => limitError("headers", what, options.maxHeaderBytes);
3100
+ const pump = () => {
3101
+ while (controller && decoder2 && !settled && !bodyComplete) {
3102
+ if ((controller.desiredSize ?? 1) <= 0)
3103
+ return;
3104
+ const step = decoder2.next(wire, peerEnded);
3105
+ if (step.kind === "data") {
3106
+ enqueue(step.value);
3107
+ if (!settled && decoder2.plainComplete)
3108
+ completeBody();
3109
+ } else if (step.kind === "more")
3110
+ resumeForData();
3111
+ else if (step.kind === "complete")
3112
+ completeBody();
3113
+ else if (step.kind === "malformed")
3114
+ fail(transportFailure(step.error));
3115
+ else
3116
+ fail(headersTooLarge("trailers"));
3117
+ return;
3118
+ }
3119
+ };
3120
+ const parseHeaders = () => {
3121
+ const head = readResponseHead(wire, options.maxHeaderBytes);
3122
+ if (head.kind !== "head") {
3123
+ if (head.kind === "malformed")
3124
+ headersReceived = true;
3125
+ if (head.kind === "more")
3126
+ socket?.resume();
3127
+ else if (head.kind === "too-large")
3128
+ fail(headersTooLarge("headers"));
3129
+ else
3130
+ fail(transportFailure(head.error));
3131
+ return;
3132
+ }
3133
+ headersReceived = true;
3134
+ const { status, statusText, headers, contentLength } = head;
3135
+ if (options.maxResponseBytes !== undefined && contentLength !== undefined && contentLength > options.maxResponseBytes) {
3136
+ fail(limitError("body", "body", options.maxResponseBytes));
3137
+ return;
3138
+ }
3139
+ decoder2 = new BodyDecoder(head.chunked, contentLength, options.maxHeaderBytes);
3140
+ const bodyless = options.request.method === "HEAD" || status === 204 || status === 205 || status === 304;
3141
+ clearTimeout(timer);
3142
+ responseResolved = true;
3143
+ if (bodyless || contentLength === 0) {
3144
+ resolveResponse(new Response(null, { status, statusText, headers }));
3145
+ finish();
3146
+ return;
3147
+ }
3148
+ const body = new ReadableStream({
3149
+ start(value) {
3150
+ controller = value;
3151
+ pump();
3152
+ },
3153
+ pull() {
3154
+ pump();
3155
+ },
3156
+ cancel() {
3157
+ finish();
3158
+ }
3159
+ }, { highWaterMark: 1 });
3160
+ resolveResponse(new Response(body, { status, statusText, headers }));
3161
+ };
3162
+ const flushRequest = (active) => {
3163
+ const next = writeAvailable(active, outgoing, writeOffset);
3164
+ if (next === "closed") {
3165
+ fail(transportFailure(new Error("Unix request socket closed while writing")));
3166
+ } else
3167
+ writeOffset = next;
3168
+ };
3169
+ if (options.request.signal.aborted) {
3170
+ fail(options.request.signal.reason ?? new DOMException("Request aborted", "AbortError"));
3171
+ return response;
3172
+ }
3173
+ options.request.signal.addEventListener("abort", abortRequest, { once: true });
3174
+ bun.connect({
3175
+ unix: options.socketPath,
3176
+ socket: socketHandlers({
3177
+ open(active) {
3178
+ socket = active;
3179
+ if (settled)
3180
+ active.terminate();
3181
+ else
3182
+ flushRequest(active);
3183
+ },
3184
+ flush: flushRequest,
3185
+ data(data) {
3186
+ wire.append(data);
3187
+ if (!responseResolved)
3188
+ parseHeaders();
3189
+ else
3190
+ pump();
3191
+ },
3192
+ ended(error, how) {
3193
+ peerEnded = true;
3194
+ if (settled)
3195
+ return;
3196
+ if (error)
3197
+ fail(transportFailure(error));
3198
+ else if (!responseResolved) {
3199
+ fail(transportFailure(new Error(`Unix connection ${how} before response headers`)));
3200
+ } else
3201
+ pump();
3202
+ },
3203
+ failed: (error) => fail(transportFailure(error))
3204
+ })
3205
+ }).catch((error) => fail(transportFailure(error)));
3206
+ return response;
3207
+ }
3208
+
3209
+ // src/server/unix-client.ts
3210
+ var DEFAULT_MAX_BODY_BYTES = 16 * 1024 * 1024;
3211
+ var DEFAULT_HEADERS_TIMEOUT_MS = 30000;
3212
+ var DEFAULT_MAX_CONNECTIONS = 8;
3213
+ var DEFAULT_MAX_REDIRECTS = 5;
3214
+ var DEFAULT_MAX_HEADER_BYTES2 = 64 * 1024;
3215
+ function positiveInteger(value, fallback, name) {
3216
+ const resolved = value ?? fallback;
3217
+ if (!Number.isSafeInteger(resolved) || resolved <= 0) {
3218
+ throw new TypeError(`${name} must be a positive safe integer`);
3219
+ }
3220
+ return resolved;
3221
+ }
3222
+ function nonNegativeInteger(value, fallback, name) {
3223
+ const resolved = value ?? fallback;
3224
+ if (!Number.isSafeInteger(resolved) || resolved < 0) {
3225
+ throw new TypeError(`${name} must be a non-negative safe integer`);
3226
+ }
3227
+ return resolved;
3228
+ }
3229
+ function isRedirect(status) {
3230
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
3231
+ }
3232
+ function requestBody(body) {
3233
+ if (body === undefined)
3234
+ return;
3235
+ const copy = new ArrayBuffer(body.byteLength);
3236
+ new Uint8Array(copy).set(body);
3237
+ return copy;
3238
+ }
3239
+ function responseHeaders2(response) {
3240
+ const headers = new Headers;
3241
+ for (let index = 0;index < response.rawHeaders.length; index += 2) {
3242
+ const name = response.rawHeaders[index];
3243
+ const value = response.rawHeaders[index + 1];
3244
+ if (name !== undefined && value !== undefined)
3245
+ headers.append(name, value);
3246
+ }
3247
+ return headers;
3248
+ }
3249
+ function isNodeHeaderOverflow(error) {
3250
+ return typeof error === "object" && error !== null && Reflect.get(error, "code") === "HPE_HEADER_OVERFLOW";
3251
+ }
3252
+ function redirectedRequest(request, location, status, body) {
3253
+ const url = new URL(location, request.url);
3254
+ const changesToGet = status === 303 || (status === 301 || status === 302) && request.method === "POST";
3255
+ const headers = new Headers(request.headers);
3256
+ if (changesToGet) {
3257
+ headers.delete("content-length");
3258
+ headers.delete("content-type");
3259
+ }
3260
+ return new Request(url, {
3261
+ method: changesToGet ? "GET" : request.method,
3262
+ headers,
3263
+ ...!changesToGet && body !== undefined && { body: requestBody(body) },
3264
+ redirect: request.redirect,
3265
+ signal: request.signal
3266
+ });
3267
+ }
3268
+ function resolveUnixClientLimits(config) {
3269
+ if (!config.socketPath.startsWith("/") || config.socketPath.includes("\x00")) {
3270
+ throw new TypeError("socketPath must be an absolute Unix socket path");
3271
+ }
3272
+ const maxRequestBytes = positiveInteger(config.maxRequestBytes, DEFAULT_MAX_BODY_BYTES, "maxRequestBytes");
3273
+ if (config.responseBodyMode === "streaming" && config.maxResponseBytes !== undefined) {
3274
+ throw new TypeError("maxResponseBytes cannot be combined with responseBodyMode streaming");
3275
+ }
3276
+ const maxResponseBytes = config.responseBodyMode === "streaming" ? undefined : positiveInteger(config.maxResponseBytes, DEFAULT_MAX_BODY_BYTES, "maxResponseBytes");
3277
+ const headersTimeoutMs = positiveInteger(config.headersTimeoutMs, DEFAULT_HEADERS_TIMEOUT_MS, "headersTimeoutMs");
3278
+ const maxConnections = positiveInteger(config.maxConnections, DEFAULT_MAX_CONNECTIONS, "maxConnections");
3279
+ const maxHeaderBytes = positiveInteger(config.maxHeaderBytes, DEFAULT_MAX_HEADER_BYTES2, "maxHeaderBytes");
3280
+ const maxRedirects = nonNegativeInteger(config.maxRedirects, DEFAULT_MAX_REDIRECTS, "maxRedirects");
3281
+ return {
3282
+ maxRequestBytes,
3283
+ maxResponseBytes,
3284
+ headersTimeoutMs,
3285
+ maxConnections,
3286
+ maxHeaderBytes,
3287
+ maxRedirects
3288
+ };
3289
+ }
3290
+ function redirectStep(request, status, location, redirectCount, maxRedirects) {
3291
+ if (!location || !isRedirect(status))
3292
+ return "return";
3293
+ if (request.redirect === "error" || redirectCount >= maxRedirects) {
3294
+ throw new UnixClientTransportError("UNIX_REDIRECT_REFUSED", redirectCount >= maxRedirects ? `Unix redirect limit ${maxRedirects} exceeded` : "Unix request redirect mode is error", "response-received");
3295
+ }
3296
+ return request.redirect === "follow" ? "follow" : "return";
3297
+ }
3298
+ function nodeUnixRequest(input) {
3299
+ const { request, url, headersTimeoutMs, maxHeaderBytes, activeRequests } = input;
3300
+ return new Promise((resolve, reject) => {
3301
+ let settled = false;
3302
+ const resolveOnce = (response) => {
3303
+ if (settled)
3304
+ return;
3305
+ settled = true;
3306
+ resolve(response);
3307
+ };
3308
+ const rejectOnce = (error) => {
3309
+ if (settled)
3310
+ return;
3311
+ settled = true;
3312
+ reject(error);
3313
+ };
3314
+ const outgoing = httpRequest({
3315
+ socketPath: input.socketPath,
3316
+ path: `${url.pathname}${url.search}`,
3317
+ method: request.method,
3318
+ headers: input.headers,
3319
+ agent: input.agent,
3320
+ signal: request.signal,
3321
+ maxHeaderSize: maxHeaderBytes
3322
+ }, resolveOnce);
3323
+ let connected = false;
3324
+ let requestStartBytes = 0;
3325
+ outgoing.once("socket", (socket) => {
3326
+ requestStartBytes = socket.bytesWritten;
3327
+ if (!socket.connecting && !socket.destroyed)
3328
+ connected = true;
3329
+ else {
3330
+ socket.once("connect", () => {
3331
+ connected = true;
3332
+ });
3333
+ }
3334
+ });
3335
+ activeRequests.add(outgoing);
3336
+ const timer = setTimeout(() => {
3337
+ const error = new UnixClientTransportError("UNIX_HEADERS_TIMEOUT", `Unix response headers did not arrive within ${headersTimeoutMs}ms`);
3338
+ rejectOnce(error);
3339
+ outgoing.destroy(error);
3340
+ }, headersTimeoutMs);
3341
+ timer.unref();
3342
+ outgoing.once("response", () => clearTimeout(timer));
3343
+ outgoing.once("error", (error) => {
3344
+ if (isNodeHeaderOverflow(error)) {
3345
+ rejectOnce(new UnixClientTransportError("UNIX_HEADERS_TOO_LARGE", `Unix response headers exceed the ${maxHeaderBytes} byte limit`, "response-received", { cause: error }));
3346
+ return;
3347
+ }
3348
+ const dispatched = connected && (outgoing.socket?.bytesWritten ?? requestStartBytes) > requestStartBytes;
3349
+ rejectOnce(new UnixClientTransportError(dispatched ? "UNIX_DELIVERY_UNCERTAIN" : "UNIX_CONNECT_FAILED", dispatched ? "Unix request transport failed after dispatch may have begun" : "Unix socket connection failed before request dispatch", dispatched ? "possibly-dispatched" : "not-dispatched", { cause: error }));
3350
+ });
3351
+ outgoing.once("close", () => {
3352
+ clearTimeout(timer);
3353
+ activeRequests.delete(outgoing);
3354
+ });
3355
+ outgoing.end(input.body);
3356
+ });
3357
+ }
3358
+ function createUnixClientTransport(config) {
3359
+ const {
3360
+ maxRequestBytes,
3361
+ maxResponseBytes,
3362
+ headersTimeoutMs,
3363
+ maxConnections,
3364
+ maxHeaderBytes,
3365
+ maxRedirects
3366
+ } = resolveUnixClientLimits(config);
3367
+ const agent = new Agent({ keepAlive: true, maxSockets: maxConnections });
3368
+ const activeRequests = new Set;
3369
+ const activeResponses = new Set;
3370
+ const bunAborters = new Set;
3371
+ let closed = false;
3372
+ const dispatch2 = async (request, redirectCount) => {
3373
+ if (closed) {
3374
+ throw new UnixClientTransportError("UNIX_CLIENT_CLOSED", "Unix client transport is closed", "not-dispatched");
3375
+ }
3376
+ if (request.signal.aborted)
3377
+ throw request.signal.reason;
3378
+ const url = new URL(request.url);
3379
+ if (url.protocol !== "http:") {
3380
+ throw new TypeError("Unix client transport accepts only http: request URLs");
3381
+ }
3382
+ const body = await readBoundedRequestBody(request, maxRequestBytes);
3383
+ if (hasBunUnixRuntime()) {
3384
+ if (bunAborters.size >= maxConnections) {
3385
+ throw new UnixClientTransportError("UNIX_CONNECTION_LIMIT", `Unix client connection limit ${maxConnections} reached`, "not-dispatched");
3386
+ }
3387
+ const response = await bunUnixRequest({
3388
+ socketPath: config.socketPath,
3389
+ request,
3390
+ body,
3391
+ maxResponseBytes,
3392
+ maxHeaderBytes,
3393
+ headersTimeoutMs,
3394
+ registerAbort(abort) {
3395
+ bunAborters.add(abort);
3396
+ return () => void bunAborters.delete(abort);
3397
+ }
3398
+ });
3399
+ const location2 = response.headers.get("location");
3400
+ let step2;
3401
+ try {
3402
+ step2 = redirectStep(request, response.status, location2, redirectCount, maxRedirects);
3403
+ } catch (error) {
3404
+ await response.body?.cancel();
3405
+ throw error;
3406
+ }
3407
+ if (step2 === "follow" && location2) {
3408
+ await response.body?.cancel();
3409
+ return dispatch2(redirectedRequest(request, location2, response.status, body), redirectCount + 1);
3410
+ }
3411
+ return response;
3412
+ }
3413
+ const headers = Object.fromEntries(request.headers.entries());
3414
+ if (!Object.keys(headers).some((name) => name.toLowerCase() === "host")) {
3415
+ headers.host = url.host;
3416
+ }
3417
+ const incoming = await nodeUnixRequest({
3418
+ socketPath: config.socketPath,
3419
+ url,
3420
+ request,
3421
+ headers,
3422
+ body,
3423
+ agent,
3424
+ maxHeaderBytes,
3425
+ headersTimeoutMs,
3426
+ activeRequests
3427
+ });
3428
+ activeResponses.add(incoming);
3429
+ const releaseResponse = () => void activeResponses.delete(incoming);
3430
+ const status = incoming.statusCode ?? 0;
3431
+ const responseHeadersValue = responseHeaders2(incoming);
3432
+ const declaredResponseBytes = responseHeadersValue.get("content-length");
3433
+ if (declaredResponseBytes !== null && /^\d+$/.test(declaredResponseBytes) && maxResponseBytes !== undefined && Number(declaredResponseBytes) > maxResponseBytes) {
3434
+ incoming.destroy();
3435
+ releaseResponse();
3436
+ throw new UnixClientTransportError("UNIX_RESPONSE_TOO_LARGE", `Unix response body exceeds the ${maxResponseBytes} byte limit`, "response-received");
3437
+ }
3438
+ const location = responseHeadersValue.get("location");
3439
+ let step;
3440
+ try {
3441
+ step = redirectStep(request, status, location, redirectCount, maxRedirects);
3442
+ } catch (error) {
3443
+ incoming.destroy();
3444
+ releaseResponse();
3445
+ throw error;
3446
+ }
3447
+ if (step === "follow" && location) {
3448
+ incoming.destroy();
3449
+ releaseResponse();
3450
+ return dispatch2(redirectedRequest(request, location, status, body), redirectCount + 1);
3451
+ }
3452
+ const bodyless = request.method === "HEAD" || status === 204 || status === 205 || status === 304;
3453
+ if (bodyless) {
3454
+ incoming.resume();
3455
+ incoming.once("end", releaseResponse);
3456
+ return new Response(null, {
3457
+ status,
3458
+ statusText: incoming.statusMessage,
3459
+ headers: responseHeadersValue
3460
+ });
3461
+ }
3462
+ return new Response(incomingResponseBody(incoming, maxResponseBytes, releaseResponse), {
3463
+ status,
3464
+ statusText: incoming.statusMessage,
3465
+ headers: responseHeadersValue
3466
+ });
3467
+ };
3468
+ return {
3469
+ fetch(input, init) {
3470
+ return dispatch2(new Request(input, init), 0);
3471
+ },
3472
+ get closed() {
3473
+ return closed;
3474
+ },
3475
+ async close() {
3476
+ if (closed)
3477
+ return;
3478
+ closed = true;
3479
+ for (const request of activeRequests)
3480
+ request.destroy();
3481
+ for (const response of activeResponses)
3482
+ response.destroy();
3483
+ for (const abort of [...bunAborters])
3484
+ abort();
3485
+ activeRequests.clear();
3486
+ activeResponses.clear();
3487
+ bunAborters.clear();
3488
+ agent.destroy();
3489
+ }
3490
+ };
3491
+ }
3492
+
3493
+ export { contextContributionDelta, prepareContextContribution, mergeContextContribution, parseMultipart, DEFAULT_STREAM_HEARTBEAT_MS, streamingRoute, ndjsonRoute, sseRoute, createHandler, createScopedImplementRegistry, implementRegistry, createImplementRegistry, bindProcessSignals, bindRealtimeServer, webSocketLane, composeWebSocketHandlers, createSocketIOServer, socketIoLane, UnixClientTransportError, createUnixClientTransport };