rivetkit 0.0.0-main.72cbc7c → 0.0.0-main.78336a1

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 (288) hide show
  1. package/dist/browser/client.d.ts +821 -80
  2. package/dist/browser/client.js +852 -670
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +252 -129
  5. package/dist/browser/inspector/client.js +2079 -234
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/actor/errors.cjs +4 -2
  8. package/dist/tsup/actor/errors.cjs.map +1 -1
  9. package/dist/tsup/actor/errors.d.cts +1 -1
  10. package/dist/tsup/actor/errors.d.ts +1 -1
  11. package/dist/tsup/actor/errors.js +3 -1
  12. package/dist/tsup/agent-os/index.cjs +2420 -2093
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +821 -90
  15. package/dist/tsup/agent-os/index.d.ts +821 -90
  16. package/dist/tsup/agent-os/index.js +2405 -2078
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-QAZLM4WT.cjs → chunk-2JSYYH6P.cjs} +22 -7
  19. package/dist/tsup/chunk-2JSYYH6P.cjs.map +1 -0
  20. package/dist/tsup/{chunk-WQ4HNA4W.cjs → chunk-4KGXFC6M.cjs} +232 -18
  21. package/dist/tsup/chunk-4KGXFC6M.cjs.map +1 -0
  22. package/dist/tsup/{chunk-GDKM56PU.js → chunk-5NBLGMI2.js} +488 -16
  23. package/dist/tsup/chunk-5NBLGMI2.js.map +1 -0
  24. package/dist/tsup/{chunk-WDO5Y6PO.cjs → chunk-635UPRVQ.cjs} +18 -11
  25. package/dist/tsup/chunk-635UPRVQ.cjs.map +1 -0
  26. package/dist/tsup/{chunk-T6YVRM4K.js → chunk-6W5VGLFT.js} +231 -17
  27. package/dist/tsup/chunk-6W5VGLFT.js.map +1 -0
  28. package/dist/tsup/{chunk-YQQ2ZDKT.cjs → chunk-AIL267JK.cjs} +525 -451
  29. package/dist/tsup/chunk-AIL267JK.cjs.map +1 -0
  30. package/dist/tsup/chunk-BHXSPZ5M.cjs +243 -0
  31. package/dist/tsup/chunk-BHXSPZ5M.cjs.map +1 -0
  32. package/dist/tsup/{chunk-O25KOT5C.cjs → chunk-EHZH3KUW.cjs} +497 -25
  33. package/dist/tsup/chunk-EHZH3KUW.cjs.map +1 -0
  34. package/dist/tsup/{chunk-3YY5S6TV.js → chunk-JI6GZ2C2.js} +3 -12
  35. package/dist/tsup/chunk-JI6GZ2C2.js.map +1 -0
  36. package/dist/tsup/chunk-JRHFO6UE.js +14 -0
  37. package/dist/tsup/chunk-JRHFO6UE.js.map +1 -0
  38. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JTHHCZCZ.js} +24 -1
  39. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  40. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-KVFIONKQ.cjs} +25 -2
  41. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  42. package/dist/tsup/{chunk-PJSE5ZGN.js → chunk-MIM5VMS6.js} +6 -6
  43. package/dist/tsup/chunk-MIM5VMS6.js.map +1 -0
  44. package/dist/tsup/chunk-MLT7XFEF.js +243 -0
  45. package/dist/tsup/chunk-MLT7XFEF.js.map +1 -0
  46. package/dist/tsup/{chunk-OFP533QU.cjs → chunk-MPEC2UFV.cjs} +3 -3
  47. package/dist/tsup/chunk-MPEC2UFV.cjs.map +1 -0
  48. package/dist/tsup/{chunk-LD5YASJU.cjs → chunk-MYWZCDML.cjs} +3 -12
  49. package/dist/tsup/chunk-MYWZCDML.cjs.map +1 -0
  50. package/dist/tsup/{chunk-KIWH5H3K.js → chunk-OUQUIBVW.js} +21 -6
  51. package/dist/tsup/chunk-OUQUIBVW.js.map +1 -0
  52. package/dist/tsup/{chunk-HSTK7OBI.js → chunk-PUMX2WHE.js} +16 -9
  53. package/dist/tsup/chunk-PUMX2WHE.js.map +1 -0
  54. package/dist/tsup/{chunk-5DGOZZKE.cjs → chunk-Q6BQS3UL.cjs} +72 -10
  55. package/dist/tsup/chunk-Q6BQS3UL.cjs.map +1 -0
  56. package/dist/tsup/{chunk-OQSBGFIB.cjs → chunk-QAWP2MIM.cjs} +10 -10
  57. package/dist/tsup/chunk-QAWP2MIM.cjs.map +1 -0
  58. package/dist/tsup/{chunk-EI55QOUB.js → chunk-QU5UOJLK.js} +390 -316
  59. package/dist/tsup/chunk-QU5UOJLK.js.map +1 -0
  60. package/dist/tsup/chunk-TX5AVHTL.cjs +14 -0
  61. package/dist/tsup/chunk-TX5AVHTL.cjs.map +1 -0
  62. package/dist/tsup/{chunk-DFHHCPH7.js → chunk-XCSZTG4H.js} +70 -8
  63. package/dist/tsup/chunk-XCSZTG4H.js.map +1 -0
  64. package/dist/tsup/{chunk-4KSYSQHX.js → chunk-XKVQ3AMZ.js} +2 -2
  65. package/dist/tsup/client/mod.cjs +8 -9
  66. package/dist/tsup/client/mod.cjs.map +1 -1
  67. package/dist/tsup/client/mod.d.cts +8 -6
  68. package/dist/tsup/client/mod.d.ts +8 -6
  69. package/dist/tsup/client/mod.js +7 -8
  70. package/dist/tsup/common/log.cjs +5 -3
  71. package/dist/tsup/common/log.cjs.map +1 -1
  72. package/dist/tsup/common/log.d.cts +5 -1
  73. package/dist/tsup/common/log.d.ts +5 -1
  74. package/dist/tsup/common/log.js +6 -4
  75. package/dist/tsup/common/websocket.cjs +4 -4
  76. package/dist/tsup/common/websocket.cjs.map +1 -1
  77. package/dist/tsup/common/websocket.js +3 -3
  78. package/dist/tsup/{config-voObiSep.d.cts → config-Ug5M2MOr.d.ts} +869 -59
  79. package/dist/tsup/{config-CxjGYf4K.d.ts → config-ey2I2zz5.d.cts} +59 -4
  80. package/dist/tsup/{config-CxjGYf4K.d.cts → config-ey2I2zz5.d.ts} +59 -4
  81. package/dist/tsup/{config-CRwCN3Ok.d.ts → config-gvHwMas-.d.cts} +869 -59
  82. package/dist/tsup/context-BSCBvbfM.d.cts +129 -0
  83. package/dist/tsup/context-DererUCI.d.ts +129 -0
  84. package/dist/tsup/db/drizzle.cjs +127 -67
  85. package/dist/tsup/db/drizzle.cjs.map +1 -1
  86. package/dist/tsup/db/drizzle.d.cts +8 -4
  87. package/dist/tsup/db/drizzle.d.ts +8 -4
  88. package/dist/tsup/db/drizzle.js +127 -67
  89. package/dist/tsup/db/drizzle.js.map +1 -1
  90. package/dist/tsup/db/mod.cjs +6 -124
  91. package/dist/tsup/db/mod.cjs.map +1 -1
  92. package/dist/tsup/db/mod.d.cts +12 -4
  93. package/dist/tsup/db/mod.d.ts +12 -4
  94. package/dist/tsup/db/mod.js +5 -123
  95. package/dist/tsup/db/mod.js.map +1 -1
  96. package/dist/tsup/dynamic/mod.cjs +24 -0
  97. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  98. package/dist/tsup/dynamic/mod.d.cts +38 -0
  99. package/dist/tsup/dynamic/mod.d.ts +38 -0
  100. package/dist/tsup/dynamic/mod.js +24 -0
  101. package/dist/tsup/dynamic/mod.js.map +1 -0
  102. package/dist/tsup/inspector/mod.cjs +47 -12
  103. package/dist/tsup/inspector/mod.cjs.map +1 -1
  104. package/dist/tsup/inspector/mod.d.cts +26 -136
  105. package/dist/tsup/inspector/mod.d.ts +26 -136
  106. package/dist/tsup/inspector/mod.js +46 -11
  107. package/dist/tsup/inspector/mod.js.map +1 -1
  108. package/dist/tsup/inspector/workflow.cjs +21 -0
  109. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  110. package/dist/tsup/inspector/workflow.d.cts +144 -0
  111. package/dist/tsup/inspector/workflow.d.ts +144 -0
  112. package/dist/tsup/inspector/workflow.js +21 -0
  113. package/dist/tsup/inspector/workflow.js.map +1 -0
  114. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  115. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  116. package/dist/tsup/inspector-tab/mod.d.cts +241 -0
  117. package/dist/tsup/inspector-tab/mod.d.ts +241 -0
  118. package/dist/tsup/inspector-tab/mod.js +162 -0
  119. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  120. package/dist/tsup/mod.cjs +2754 -607
  121. package/dist/tsup/mod.cjs.map +1 -1
  122. package/dist/tsup/mod.d.cts +8 -7
  123. package/dist/tsup/mod.d.ts +8 -7
  124. package/dist/tsup/mod.js +2688 -541
  125. package/dist/tsup/mod.js.map +1 -1
  126. package/dist/tsup/test/mod.cjs +26 -21
  127. package/dist/tsup/test/mod.cjs.map +1 -1
  128. package/dist/tsup/test/mod.d.cts +6 -5
  129. package/dist/tsup/test/mod.d.ts +6 -5
  130. package/dist/tsup/test/mod.js +25 -20
  131. package/dist/tsup/test/mod.js.map +1 -1
  132. package/dist/tsup/unstable/migrations.cjs +101 -0
  133. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  134. package/dist/tsup/unstable/migrations.d.cts +29 -0
  135. package/dist/tsup/unstable/migrations.d.ts +29 -0
  136. package/dist/tsup/unstable/migrations.js +101 -0
  137. package/dist/tsup/unstable/migrations.js.map +1 -0
  138. package/dist/tsup/utils-Bbz-3411.d.cts +162 -0
  139. package/dist/tsup/utils-BqdWVlzm.d.ts +162 -0
  140. package/dist/tsup/{utils-DVekpm4I.d.cts → utils-vvJQyygr.d.cts} +7 -1
  141. package/dist/tsup/{utils-DVekpm4I.d.ts → utils-vvJQyygr.d.ts} +7 -1
  142. package/dist/tsup/utils.cjs +7 -3
  143. package/dist/tsup/utils.cjs.map +1 -1
  144. package/dist/tsup/utils.d.cts +4 -147
  145. package/dist/tsup/utils.d.ts +4 -147
  146. package/dist/tsup/utils.js +6 -2
  147. package/dist/tsup/workflow/mod.cjs +539 -424
  148. package/dist/tsup/workflow/mod.cjs.map +1 -1
  149. package/dist/tsup/workflow/mod.d.cts +10 -9
  150. package/dist/tsup/workflow/mod.d.ts +10 -9
  151. package/dist/tsup/workflow/mod.js +521 -406
  152. package/dist/tsup/workflow/mod.js.map +1 -1
  153. package/package.json +63 -16
  154. package/src/actor/actions.ts +119 -0
  155. package/src/actor/config.test.ts +78 -0
  156. package/src/actor/config.ts +505 -88
  157. package/src/actor/contexts/index.ts +7 -2
  158. package/src/actor/definition.ts +38 -26
  159. package/src/actor/errors.ts +50 -5
  160. package/src/actor/keys.ts +1 -1
  161. package/src/actor/mod.ts +32 -21
  162. package/src/actor/schema.ts +2 -2
  163. package/src/agent-os/actor/index.ts +39 -19
  164. package/src/agent-os/actor/preview.ts +1 -2
  165. package/src/agent-os/actor/session.ts +2 -2
  166. package/src/agent-os/config.ts +1 -1
  167. package/src/agent-os/fs/database-vfs.ts +1 -1
  168. package/src/agent-os/index.ts +16 -15
  169. package/src/client/actor-common.ts +80 -54
  170. package/src/client/actor-conn.ts +17 -41
  171. package/src/client/actor-handle.ts +140 -72
  172. package/src/client/actor-query.ts +13 -6
  173. package/src/client/client.ts +41 -11
  174. package/src/client/errors.ts +3 -2
  175. package/src/client/lifecycle-errors.ts +2 -4
  176. package/src/client/query.ts +3 -1
  177. package/src/client/queue.ts +8 -3
  178. package/src/client/raw-utils.ts +36 -13
  179. package/src/client/resolve-gateway-target.ts +3 -1
  180. package/src/client/utils.ts +4 -7
  181. package/src/common/actor-router-consts.ts +2 -0
  182. package/src/common/actor-websocket.ts +3 -1
  183. package/src/common/bare/actor-persist/v1.ts +205 -163
  184. package/src/common/bare/actor-persist/v2.ts +265 -213
  185. package/src/common/bare/actor-persist/v3.ts +176 -172
  186. package/src/common/bare/actor-persist/v4.ts +254 -253
  187. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  188. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  189. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  190. package/src/common/bare/transport/v1.ts +694 -542
  191. package/src/common/client-protocol-versioned.ts +66 -64
  192. package/src/common/database/config.ts +74 -9
  193. package/src/common/database/mod.test.ts +285 -58
  194. package/src/common/database/mod.ts +259 -77
  195. package/src/common/database/native-database.test.ts +9 -0
  196. package/src/common/database/native-database.ts +192 -2
  197. package/src/common/database/shared.ts +25 -0
  198. package/src/common/encoding.ts +278 -34
  199. package/src/common/engine.ts +28 -1
  200. package/src/common/eventsource.ts +1 -1
  201. package/src/common/fetch-like.ts +49 -0
  202. package/src/common/inline-websocket-adapter.ts +14 -13
  203. package/src/common/inspector-transport.ts +12 -2
  204. package/src/common/log.ts +15 -8
  205. package/src/common/router.ts +13 -17
  206. package/src/common/utils.ts +7 -150
  207. package/src/common/websocket-interface.ts +1 -1
  208. package/src/db/drizzle.test.ts +164 -0
  209. package/src/db/drizzle.ts +182 -80
  210. package/src/db/mod.ts +4 -1
  211. package/src/devtools-loader/index.ts +4 -7
  212. package/src/devtools-loader/serve-devtools.ts +26 -0
  213. package/src/dynamic/instance.ts +32 -0
  214. package/src/dynamic/internal.ts +50 -0
  215. package/src/dynamic/isolate-runtime.ts +64 -0
  216. package/src/dynamic/mod.ts +32 -0
  217. package/src/engine-client/actor-http-client.ts +8 -24
  218. package/src/engine-client/actor-websocket-client.ts +6 -5
  219. package/src/engine-client/api-endpoints.ts +51 -2
  220. package/src/engine-client/api-utils.ts +2 -2
  221. package/src/engine-client/driver.ts +5 -16
  222. package/src/engine-client/mod.ts +66 -64
  223. package/src/engine-client/ws-proxy.ts +9 -4
  224. package/src/inspector/client.browser.ts +127 -15
  225. package/src/inspector/mod.ts +2 -4
  226. package/src/inspector/workflow.ts +61 -0
  227. package/src/inspector-tab/mod.ts +301 -0
  228. package/src/registry/config/envoy.ts +1 -2
  229. package/src/registry/config/index.test.ts +25 -0
  230. package/src/registry/config/index.ts +68 -56
  231. package/src/registry/index.ts +588 -91
  232. package/src/registry/napi-runtime.ts +427 -23
  233. package/src/registry/native-http.ts +225 -0
  234. package/src/registry/native-validation.ts +10 -12
  235. package/src/registry/native.ts +1435 -459
  236. package/src/registry/process-metrics.ts +250 -0
  237. package/src/registry/run-handler-coordinator.test.ts +252 -0
  238. package/src/registry/run-handler-coordinator.ts +219 -0
  239. package/src/registry/runtime.test.ts +74 -0
  240. package/src/registry/runtime.ts +297 -9
  241. package/src/registry/wasm-runtime.ts +398 -22
  242. package/src/registry/write-through-proxy.ts +141 -0
  243. package/src/serde.ts +2 -2
  244. package/src/serverless/configure.ts +18 -7
  245. package/src/test/mod.ts +2 -17
  246. package/src/test/ready.ts +22 -0
  247. package/src/unstable/migrations.test.ts +170 -0
  248. package/src/unstable/migrations.ts +141 -0
  249. package/src/utils/endpoint-parser.ts +1 -1
  250. package/src/utils/env-vars.ts +41 -0
  251. package/src/utils/node.ts +44 -28
  252. package/src/utils/router.ts +1 -1
  253. package/src/utils.ts +4 -2
  254. package/src/workflow/context.ts +683 -242
  255. package/src/workflow/driver.test.ts +62 -0
  256. package/src/workflow/driver.ts +259 -119
  257. package/src/workflow/inspector.ts +24 -24
  258. package/src/workflow/mod.ts +76 -84
  259. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  260. package/dist/tsup/chunk-3YY5S6TV.js.map +0 -1
  261. package/dist/tsup/chunk-5DGOZZKE.cjs.map +0 -1
  262. package/dist/tsup/chunk-DFHHCPH7.js.map +0 -1
  263. package/dist/tsup/chunk-EI55QOUB.js.map +0 -1
  264. package/dist/tsup/chunk-GDKM56PU.js.map +0 -1
  265. package/dist/tsup/chunk-HSTK7OBI.js.map +0 -1
  266. package/dist/tsup/chunk-KIWH5H3K.js.map +0 -1
  267. package/dist/tsup/chunk-LD5YASJU.cjs.map +0 -1
  268. package/dist/tsup/chunk-LI5MR5BD.js +0 -268
  269. package/dist/tsup/chunk-LI5MR5BD.js.map +0 -1
  270. package/dist/tsup/chunk-NDY6IZJ3.cjs +0 -268
  271. package/dist/tsup/chunk-NDY6IZJ3.cjs.map +0 -1
  272. package/dist/tsup/chunk-O25KOT5C.cjs.map +0 -1
  273. package/dist/tsup/chunk-OFP533QU.cjs.map +0 -1
  274. package/dist/tsup/chunk-OQSBGFIB.cjs.map +0 -1
  275. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  276. package/dist/tsup/chunk-PJSE5ZGN.js.map +0 -1
  277. package/dist/tsup/chunk-QAZLM4WT.cjs.map +0 -1
  278. package/dist/tsup/chunk-T6YVRM4K.js.map +0 -1
  279. package/dist/tsup/chunk-WDO5Y6PO.cjs.map +0 -1
  280. package/dist/tsup/chunk-WQ4HNA4W.cjs.map +0 -1
  281. package/dist/tsup/chunk-YQQ2ZDKT.cjs.map +0 -1
  282. package/dist/tsup/context-BPFYVZ5g.d.ts +0 -92
  283. package/dist/tsup/context-D0YF1MQq.d.cts +0 -92
  284. package/src/actor/driver.ts +0 -141
  285. package/src/actor/instance/mod.ts +0 -2492
  286. package/src/drivers/engine/actor-driver.ts +0 -2460
  287. package/src/utils/serve.ts +0 -217
  288. /package/dist/tsup/{chunk-4KSYSQHX.js.map → chunk-XKVQ3AMZ.js.map} +0 -0
package/dist/tsup/mod.cjs CHANGED
@@ -1,24 +1,23 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } var _class; var _class2;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } var _class; var _class2; var _class3;
2
2
 
3
3
 
4
4
 
5
5
 
6
6
 
7
7
 
8
- var _chunkWQ4HNA4Wcjs = require('./chunk-WQ4HNA4W.cjs');
9
8
 
10
9
 
11
- var _chunk5DGOZZKEcjs = require('./chunk-5DGOZZKE.cjs');
12
10
 
13
11
 
14
12
 
15
13
 
16
14
 
17
15
 
16
+ var _chunk4KGXFC6Mcjs = require('./chunk-4KGXFC6M.cjs');
18
17
 
19
18
 
19
+ var _chunkQ6BQS3ULcjs = require('./chunk-Q6BQS3UL.cjs');
20
20
 
21
- var _chunkYQQ2ZDKTcjs = require('./chunk-YQQ2ZDKT.cjs');
22
21
 
23
22
 
24
23
 
@@ -26,20 +25,21 @@ var _chunkYQQ2ZDKTcjs = require('./chunk-YQQ2ZDKT.cjs');
26
25
 
27
26
 
28
27
 
29
- var _chunkLD5YASJUcjs = require('./chunk-LD5YASJU.cjs');
30
28
 
31
29
 
32
30
 
31
+ var _chunkAIL267JKcjs = require('./chunk-AIL267JK.cjs');
33
32
 
34
- var _chunkNDY6IZJ3cjs = require('./chunk-NDY6IZJ3.cjs');
35
- require('./chunk-2NDZ7JCR.cjs');
36
- require('./chunk-OFP533QU.cjs');
37
33
 
38
34
 
35
+ var _chunkMYWZCDMLcjs = require('./chunk-MYWZCDML.cjs');
36
+ require('./chunk-MPEC2UFV.cjs');
39
37
 
40
38
 
41
39
 
42
40
 
41
+ var _chunkBHXSPZ5Mcjs = require('./chunk-BHXSPZ5M.cjs');
42
+ require('./chunk-KVFIONKQ.cjs');
43
43
 
44
44
 
45
45
 
@@ -57,7 +57,6 @@ require('./chunk-OFP533QU.cjs');
57
57
 
58
58
 
59
59
 
60
- var _chunkO25KOT5Ccjs = require('./chunk-O25KOT5C.cjs');
61
60
 
62
61
 
63
62
 
@@ -68,23 +67,47 @@ var _chunkO25KOT5Ccjs = require('./chunk-O25KOT5C.cjs');
68
67
 
69
68
 
70
69
 
71
- var _chunkQAZLM4WTcjs = require('./chunk-QAZLM4WT.cjs');
70
+
71
+
72
+
73
+
74
+
75
+
76
+ var _chunkEHZH3KUWcjs = require('./chunk-EHZH3KUW.cjs');
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+ var _chunk2JSYYH6Pcjs = require('./chunk-2JSYYH6P.cjs');
72
89
 
73
90
  // src/actor/log.ts
74
91
  function loggerWithoutContext() {
75
- return _chunkO25KOT5Ccjs.getLogger.call(void 0, "actor-runtime");
92
+ return _chunkEHZH3KUWcjs.getLogger.call(void 0, "actor-runtime");
76
93
  }
77
94
 
78
95
  // src/actor/definition.ts
79
- var warnedDeprecatedTimeoutKeys = /* @__PURE__ */ new Set();
80
- function warnDeprecatedShutdownTimeoutKeys(options) {
96
+ var warnedDeprecatedOptionKeys = /* @__PURE__ */ new Set();
97
+ var DEPRECATED_OPTION_MESSAGES = {
98
+ onDestroyTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
99
+ waitUntilTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
100
+ preloadMaxWorkflowBytes: "Internal storage moved to SQLite and no longer uses KV preloading.",
101
+ preloadMaxConnectionsBytes: "Internal storage moved to SQLite and no longer uses KV preloading."
102
+ };
103
+ function warnDeprecatedOptionKeys(options) {
81
104
  if (!options || typeof options !== "object") return;
82
105
  const opts = options;
83
- for (const key of ["onDestroyTimeout", "waitUntilTimeout"]) {
84
- if (opts[key] !== void 0 && !warnedDeprecatedTimeoutKeys.has(key)) {
85
- warnedDeprecatedTimeoutKeys.add(key);
106
+ for (const [key, detail] of Object.entries(DEPRECATED_OPTION_MESSAGES)) {
107
+ if (opts[key] !== void 0 && !warnedDeprecatedOptionKeys.has(key)) {
108
+ warnedDeprecatedOptionKeys.add(key);
86
109
  loggerWithoutContext().warn({
87
- msg: `actor option \`${key}\` is deprecated and is now ignored. Configure \`sleepGracePeriod\` instead, which bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0.`
110
+ msg: `actor option \`${key}\` is deprecated and is now ignored. ${detail} Will be removed in 2.2.0.`
88
111
  });
89
112
  }
90
113
  }
@@ -102,10 +125,12 @@ function isStaticActorInstance(_actor) {
102
125
  return true;
103
126
  }
104
127
  function actor(input) {
105
- warnDeprecatedShutdownTimeoutKeys(
128
+ warnDeprecatedOptionKeys(
106
129
  input == null ? void 0 : input.options
107
130
  );
108
- const config = _chunkWQ4HNA4Wcjs.ActorConfigSchema.parse(input);
131
+ const config = _chunk4KGXFC6Mcjs.ActorConfigSchema.parse(input);
132
+ _chunk4KGXFC6Mcjs.flattenActionHandlers.call(void 0, config.actions);
133
+ _chunk4KGXFC6Mcjs.flattenActionInputSchemas.call(void 0, config.actions, config.actionInputSchemas);
109
134
  return new ActorDefinition(config);
110
135
  }
111
136
  function isStaticActorDefinition(definition) {
@@ -140,7 +165,7 @@ function hasSchemaConfigKey(schemas, key) {
140
165
  if (!schemas) {
141
166
  return false;
142
167
  }
143
- return Object.prototype.hasOwnProperty.call(schemas, key);
168
+ return Object.hasOwn(schemas, key);
144
169
  }
145
170
  function getEventCanSubscribe(schemas, key) {
146
171
  const schema = schemas == null ? void 0 : schemas[key];
@@ -187,7 +212,7 @@ function validateSchemaSync(schemas, key, data) {
187
212
  if (isStandardSchema(schema)) {
188
213
  const result = schema["~standard"].validate(data);
189
214
  if (isPromiseLike(result)) {
190
- throw _chunkQAZLM4WTcjs.unsupportedFeature.call(void 0, "async schema validation");
215
+ throw _chunk2JSYYH6Pcjs.unsupportedFeature.call(void 0, "async schema validation");
191
216
  }
192
217
  if (result.issues) {
193
218
  return { success: false, issues: [...result.issues] };
@@ -201,10 +226,10 @@ function validateSchemaSync(schemas, key, data) {
201
226
  }
202
227
 
203
228
  // src/common/inline-websocket-adapter.ts
204
- var _ws = require('hono/ws');
205
229
  var _virtualwebsocket = require('@rivetkit/virtual-websocket');
230
+ var _ws = require('hono/ws');
206
231
  function logger() {
207
- return _chunkO25KOT5Ccjs.getLogger.call(void 0, "inline-websocket-adapter");
232
+ return _chunkEHZH3KUWcjs.getLogger.call(void 0, "inline-websocket-adapter");
208
233
  }
209
234
  var InlineWebSocketAdapter = class {
210
235
  #handler;
@@ -314,24 +339,24 @@ var InlineWebSocketAdapter = class {
314
339
  this.#close(1011, "Internal error during initialization");
315
340
  }
316
341
  }
317
- #handleError(err) {
318
- console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", err);
342
+ #handleError(error) {
343
+ console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", error);
319
344
  logger().error({
320
345
  msg: "error in websocket",
321
- error: err,
322
- errorMessage: err instanceof Error ? err.message : String(err),
323
- stack: err instanceof Error ? err.stack : void 0
346
+ error,
347
+ errorMessage: error instanceof Error ? error.message : String(error),
348
+ stack: error instanceof Error ? error.stack : void 0
324
349
  });
325
350
  try {
326
- this.#handler.onError(err, this.#wsContext);
327
- } catch (handlerErr) {
351
+ this.#handler.onError(error, this.#wsContext);
352
+ } catch (error2) {
328
353
  logger().error({
329
354
  msg: "error in onError handler",
330
- error: handlerErr
355
+ error: error2
331
356
  });
332
357
  }
333
- this.#clientWs.triggerError(err);
334
- this.#actorWs.triggerError(err);
358
+ this.#clientWs.triggerError(error);
359
+ this.#actorWs.triggerError(error);
335
360
  }
336
361
  #close(code, reason) {
337
362
  if (this.#readyState === 3 || this.#readyState === 2) {
@@ -344,8 +369,8 @@ var InlineWebSocketAdapter = class {
344
369
  { code, reason, wasClean: true },
345
370
  this.#wsContext
346
371
  );
347
- } catch (err) {
348
- logger().error({ msg: "error closing websocket", error: err });
372
+ } catch (error) {
373
+ logger().error({ msg: "error closing websocket", error });
349
374
  } finally {
350
375
  this.#readyState = 3;
351
376
  this.#clientWs.triggerClose(code, reason);
@@ -355,12 +380,27 @@ var InlineWebSocketAdapter = class {
355
380
  };
356
381
 
357
382
  // src/common/engine.ts
383
+ var ENGINE_HOST = "127.0.0.1";
358
384
  var ENGINE_PORT = 6420;
359
- var ENGINE_ENDPOINT = `http://127.0.0.1:${ENGINE_PORT}`;
385
+ var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
386
+ function buildEngineEndpoint(host, port) {
387
+ const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
388
+ return `http://${urlHost}:${port}`;
389
+ }
390
+ function isLocalEngineEndpoint(endpoint) {
391
+ let url;
392
+ try {
393
+ url = new URL(endpoint);
394
+ } catch (e) {
395
+ return false;
396
+ }
397
+ const hostname = url.hostname.toLowerCase();
398
+ return hostname === "localhost" || hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]" || hostname === "::1" || hostname === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname);
399
+ }
360
400
 
361
401
  // src/registry/log.ts
362
402
  function logger2() {
363
- return _chunkO25KOT5Ccjs.getLogger.call(void 0, "registry");
403
+ return _chunkEHZH3KUWcjs.getLogger.call(void 0, "registry");
364
404
  }
365
405
 
366
406
  // src/serverless/configure.ts
@@ -371,10 +411,13 @@ function sleep(ms) {
371
411
  }
372
412
  function configureTimeoutMs() {
373
413
  const value = process.env.RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS;
374
- if (value === void 0 || value === "") return DEFAULT_CONFIGURE_TIMEOUT_MS;
414
+ if (value === void 0 || value === "")
415
+ return DEFAULT_CONFIGURE_TIMEOUT_MS;
375
416
  const parsed = Number(value);
376
417
  if (!Number.isFinite(parsed) || parsed < 0) {
377
- throw new Error("RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number");
418
+ throw new Error(
419
+ "RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number"
420
+ );
378
421
  }
379
422
  return parsed;
380
423
  }
@@ -388,17 +431,23 @@ async function configureServerlessPool(config) {
388
431
  attempts += 1;
389
432
  try {
390
433
  if (!config.namespace) {
391
- throw new Error("namespace is required for serverless configuration");
434
+ throw new Error(
435
+ "namespace is required for serverless configuration"
436
+ );
392
437
  }
393
438
  if (!config.endpoint) {
394
- throw new Error("endpoint is required for serverless configuration");
439
+ throw new Error(
440
+ "endpoint is required for serverless configuration"
441
+ );
395
442
  }
396
443
  if (!config.configurePool) {
397
- throw new Error("configurePool is required for serverless configuration");
444
+ throw new Error(
445
+ "configurePool is required for serverless configuration"
446
+ );
398
447
  }
399
448
  const customConfig = config.configurePool;
400
- const clientConfig = _chunkYQQ2ZDKTcjs.convertRegistryConfigToClientConfig.call(void 0, config);
401
- const dcsRes = await _chunkYQQ2ZDKTcjs.getDatacenters.call(void 0, clientConfig);
449
+ const clientConfig = _chunkAIL267JKcjs.convertRegistryConfigToClientConfig.call(void 0, config);
450
+ const dcsRes = await _chunkAIL267JKcjs.getDatacenters.call(void 0, clientConfig);
402
451
  const poolName = _nullishCoalesce(customConfig.name, () => ( "default"));
403
452
  const serverlessToken = _nullishCoalesce(config.token, () => ( config.publicToken));
404
453
  const headers = {
@@ -420,7 +469,7 @@ async function configureServerlessPool(config) {
420
469
  metadata: _nullishCoalesce(customConfig.metadata, () => ( {})),
421
470
  drain_on_version_upgrade: _nullishCoalesce(customConfig.drainOnVersionUpgrade, () => ( true))
422
471
  };
423
- await _chunkYQQ2ZDKTcjs.updateRunnerConfig.call(void 0, clientConfig, poolName, {
472
+ await _chunkAIL267JKcjs.updateRunnerConfig.call(void 0, clientConfig, poolName, {
424
473
  datacenters: Object.fromEntries(
425
474
  dcsRes.datacenters.map((dc) => [dc.name, serverlessConfig])
426
475
  )
@@ -437,7 +486,7 @@ async function configureServerlessPool(config) {
437
486
  logger2().warn({
438
487
  msg: "serverless pool configuration attempt failed",
439
488
  attempts,
440
- error: _chunkO25KOT5Ccjs.stringifyError.call(void 0, error)
489
+ error: _chunkEHZH3KUWcjs.stringifyError.call(void 0, error)
441
490
  });
442
491
  await sleep(CONFIGURE_RETRY_DELAY_MS);
443
492
  }
@@ -445,7 +494,7 @@ async function configureServerlessPool(config) {
445
494
  logger2().error({
446
495
  msg: "failed to configure serverless pool, validate endpoint is configured correctly then restart this process",
447
496
  attempts,
448
- error: _chunkO25KOT5Ccjs.stringifyError.call(void 0, lastError)
497
+ error: _chunkEHZH3KUWcjs.stringifyError.call(void 0, lastError)
449
498
  });
450
499
  throw lastError;
451
500
  }
@@ -457,20 +506,20 @@ var _zod = require('zod');
457
506
  var _v4 = require('zod/v4');
458
507
  var warnedMissingVersion = false;
459
508
  var EnvoyConfigSchema = _v4.z.object({
460
- poolName: _v4.z.string().default(() => _nullishCoalesce(_chunkO25KOT5Ccjs.getRivetPool.call(void 0, ), () => ( "default"))),
509
+ poolName: _v4.z.string().default(() => _nullishCoalesce(_chunkEHZH3KUWcjs.getRivetPool.call(void 0, ), () => ( "default"))),
461
510
  version: _v4.z.number().default(() => {
462
- const version = _chunkO25KOT5Ccjs.getRivetEnvoyVersion.call(void 0, );
511
+ const version = _chunkEHZH3KUWcjs.getRivetEnvoyVersion.call(void 0, );
463
512
  if (version !== void 0) return version;
464
- if (_chunkO25KOT5Ccjs.getNodeEnv.call(void 0, ) === "production" && !warnedMissingVersion) {
513
+ if (_chunkEHZH3KUWcjs.getNodeEnv.call(void 0, ) === "production" && !warnedMissingVersion) {
465
514
  warnedMissingVersion = true;
466
- _chunkO25KOT5Ccjs.getLogger.call(void 0, "rivetkit").error(
515
+ _chunkEHZH3KUWcjs.getLogger.call(void 0, "rivetkit").error(
467
516
  "RIVET_ENVOY_VERSION is not set. Actors will not be versioned, which means they won't be drained on deploy. This is only needed when self-hosting or using a custom envoy (not needed for Rivet Compute). Set this as a build arg in your Dockerfile. See https://rivet.dev/docs/actors/versions"
468
517
  );
469
518
  }
470
519
  return 1;
471
520
  }),
472
521
  // Deprecated.
473
- totalSlots: _v4.z.number().default(() => _nullishCoalesce(_chunkO25KOT5Ccjs.getRivetTotalSlots.call(void 0, ), () => ( 1e5))),
522
+ totalSlots: _v4.z.number().default(() => _nullishCoalesce(_chunkEHZH3KUWcjs.getRivetTotalSlots.call(void 0, ), () => ( 1e5))),
474
523
  envoyKey: _v4.z.string().optional()
475
524
  });
476
525
 
@@ -508,7 +557,7 @@ var ServerlessConfigSchema = _v4.z.object({
508
557
  *
509
558
  * Can also be set via RIVET_PUBLIC_ENDPOINT environment variable.
510
559
  */
511
- publicEndpoint: _v4.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkO25KOT5Ccjs.getRivetPublicEndpoint.call(void 0, )))),
560
+ publicEndpoint: _v4.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkEHZH3KUWcjs.getRivetPublicEndpoint.call(void 0, )))),
512
561
  /**
513
562
  * Token that clients should use when connecting via the public endpoint.
514
563
  *
@@ -516,7 +565,7 @@ var ServerlessConfigSchema = _v4.z.object({
516
565
  *
517
566
  * Can also be specified in the publicEndpoint URL as `https://namespace:token@host`.
518
567
  */
519
- publicToken: _v4.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkO25KOT5Ccjs.getRivetPublicToken.call(void 0, ))))
568
+ publicToken: _v4.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkEHZH3KUWcjs.getRivetPublicToken.call(void 0, ))))
520
569
  // There is no publicNamespace config option because the frontend and backend
521
570
  // cannot use different namespaces. The namespace is extracted from the
522
571
  // publicEndpoint URL auth syntax if provided.
@@ -570,7 +619,7 @@ var RegistryConfigSchema = _zod.z.object({
570
619
  * Runtime binding to use for RivetKit core.
571
620
  * */
572
621
  runtime: RuntimeKindSchema.optional().transform((val, ctx) => {
573
- const rawRuntime = _nullishCoalesce(val, () => ( _chunkO25KOT5Ccjs.getRivetkitRuntime.call(void 0, )));
622
+ const rawRuntime = _nullishCoalesce(val, () => ( _chunkEHZH3KUWcjs.getRivetkitRuntime.call(void 0, )));
574
623
  if (rawRuntime === void 0) {
575
624
  return "auto";
576
625
  }
@@ -607,7 +656,7 @@ var RegistryConfigSchema = _zod.z.object({
607
656
  * */
608
657
  logging: _zod.z.object({
609
658
  baseLogger: _zod.z.custom().optional(),
610
- level: _chunkO25KOT5Ccjs.LogLevelSchema.optional()
659
+ level: _chunkEHZH3KUWcjs.LogLevelSchema.optional()
611
660
  }).optional().default(() => ({})),
612
661
  // MARK: Routing
613
662
  // // This is a function to allow for lazy configuration of upgradeWebSocket on the
@@ -625,9 +674,9 @@ var RegistryConfigSchema = _zod.z.object({
625
674
  *
626
675
  * Can also be set via RIVET_ENDPOINT environment variables.
627
676
  */
628
- endpoint: _zod.z.string().optional().transform((val) => _nullishCoalesce(_nullishCoalesce(val, () => ( _chunkO25KOT5Ccjs.getRivetEngine.call(void 0, ))), () => ( _chunkO25KOT5Ccjs.getRivetEndpoint.call(void 0, )))),
629
- token: _zod.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkO25KOT5Ccjs.getRivetToken.call(void 0, )))),
630
- namespace: _zod.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkO25KOT5Ccjs.getRivetNamespace.call(void 0, )))),
677
+ endpoint: _zod.z.string().optional().transform((val) => _nullishCoalesce(_nullishCoalesce(val, () => ( _chunkEHZH3KUWcjs.getRivetEngine.call(void 0, ))), () => ( _chunkEHZH3KUWcjs.getRivetEndpoint.call(void 0, )))),
678
+ token: _zod.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkEHZH3KUWcjs.getRivetToken.call(void 0, )))),
679
+ namespace: _zod.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkEHZH3KUWcjs.getRivetNamespace.call(void 0, )))),
631
680
  headers: _zod.z.record(_zod.z.string(), _zod.z.string()).optional().default({}),
632
681
  // MARK: Client
633
682
  // TODO:
@@ -667,9 +716,27 @@ var RegistryConfigSchema = _zod.z.object({
667
716
  *
668
717
  * Starts the full Rust engine process locally.
669
718
  */
670
- startEngine: _zod.z.boolean().default(() => _chunkO25KOT5Ccjs.getRivetRunEngine.call(void 0, )),
719
+ startEngine: _zod.z.boolean().default(() => _chunkEHZH3KUWcjs.getRivetRunEngine.call(void 0, )),
720
+ /**
721
+ * @experimental
722
+ *
723
+ * Host to bind the spawned local engine process to.
724
+ */
725
+ engineHost: _zod.z.string().optional().default(() => _nullishCoalesce(_chunkEHZH3KUWcjs.getRivetRunEngineHost.call(void 0, ), () => ( ENGINE_HOST))),
726
+ /**
727
+ * @experimental
728
+ *
729
+ * Port to bind the spawned local engine process to.
730
+ */
731
+ enginePort: _zod.z.number().int().min(1).max(65535).optional().default(() => _nullishCoalesce(_chunkEHZH3KUWcjs.getRivetRunEnginePort.call(void 0, ), () => ( ENGINE_PORT))),
671
732
  /** @experimental */
672
- engineVersion: _zod.z.string().optional().default(() => _nullishCoalesce(_chunkO25KOT5Ccjs.getRivetRunEngineVersion.call(void 0, ), () => ( _chunkO25KOT5Ccjs.VERSION))),
733
+ engineVersion: _zod.z.string().optional().default(() => _nullishCoalesce(_chunkEHZH3KUWcjs.getRivetRunEngineVersion.call(void 0, ), () => ( _chunkEHZH3KUWcjs.VERSION))),
734
+ /**
735
+ * Starts the first-party Services actor host when RivetKit manages
736
+ * a local engine. Defaults to the local-engine decision. Set
737
+ * RIVET_RUN_SERVICES=0 or 1 to override it.
738
+ */
739
+ startServices: _zod.z.boolean().optional(),
673
740
  /**
674
741
  * @experimental
675
742
  *
@@ -700,12 +767,12 @@ var RegistryConfigSchema = _zod.z.object({
700
767
  shutdown: _zod.z.object({
701
768
  /**
702
769
  * Wait this many milliseconds for the serve promise to resolve
703
- * after calling `CoreRegistry::shutdown()`. Defaults to 30s,
704
- * matching Kubernetes `terminationGracePeriodSeconds`.
770
+ * after calling `CoreRegistry::shutdown()`. Defaults to the
771
+ * engine-provided actor stop threshold once the envoy connects.
705
772
  *
706
- * Must be >= rivetkit-core's drain timeout (20s) + margin.
773
+ * Must be long enough for rivetkit-core to drain the envoy.
707
774
  */
708
- gracePeriodMs: _zod.z.number().int().min(1e3).optional().default(3e4),
775
+ gracePeriodMs: _zod.z.number().int().min(1e3).optional(),
709
776
  /**
710
777
  * If true, rivetkit will not install SIGINT/SIGTERM handlers.
711
778
  * Use when the host application owns signal policy and will
@@ -713,12 +780,11 @@ var RegistryConfigSchema = _zod.z.object({
713
780
  */
714
781
  disableSignalHandlers: _zod.z.boolean().optional().default(false)
715
782
  }).optional().default(() => ({
716
- gracePeriodMs: 3e4,
717
783
  disableSignalHandlers: false
718
784
  }))
719
785
  }).transform((config, ctx) => {
720
786
  var _a, _b, _c;
721
- const isDevEnv = _chunkO25KOT5Ccjs.isDev.call(void 0, );
787
+ const isDevEnv = _chunkEHZH3KUWcjs.isDev.call(void 0, );
722
788
  const sqliteBackend = _nullishCoalesce(((_a = config.sqlite) == null ? void 0 : _a.backend), () => ( ((_b = config.test) == null ? void 0 : _b.sqliteBackend)));
723
789
  if (config.runtime === "wasm" && sqliteBackend === "local") {
724
790
  ctx.addIssue({
@@ -728,7 +794,7 @@ var RegistryConfigSchema = _zod.z.object({
728
794
  });
729
795
  }
730
796
  const sqlite = config.runtime === "wasm" && config.sqlite === void 0 ? { backend: "remote" } : config.sqlite;
731
- const parsedEndpoint = config.endpoint ? _chunkYQQ2ZDKTcjs.tryParseEndpoint.call(void 0, ctx, {
797
+ const parsedEndpoint = config.endpoint ? _chunkAIL267JKcjs.tryParseEndpoint.call(void 0, ctx, {
732
798
  endpoint: config.endpoint,
733
799
  path: ["endpoint"],
734
800
  namespace: config.namespace,
@@ -746,13 +812,18 @@ var RegistryConfigSchema = _zod.z.object({
746
812
  message: "configurePool requires either endpoint or startEngine"
747
813
  });
748
814
  }
749
- const endpoint = config.startEngine ? ENGINE_ENDPOINT : _nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint), () => ( (isDevEnv ? ENGINE_ENDPOINT : void 0)));
815
+ const localEngineEndpoint = buildEngineEndpoint(
816
+ config.engineHost,
817
+ config.enginePort
818
+ );
819
+ const endpoint = config.startEngine ? localEngineEndpoint : _nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint), () => ( (isDevEnv ? localEngineEndpoint : void 0)));
820
+ const startServices = _nullishCoalesce(_nullishCoalesce(config.startServices, () => ( _chunkEHZH3KUWcjs.getRivetRunServices.call(void 0, ))), () => ( Boolean(endpoint && isLocalEngineEndpoint(endpoint))));
750
821
  const validateServerlessEndpoint = Boolean(
751
822
  config.startEngine || parsedEndpoint
752
823
  );
753
824
  const namespace = _nullishCoalesce(_nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.namespace), () => ( config.namespace)), () => ( "default"));
754
- const token = _nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.token), () => ( config.token));
755
- const parsedPublicEndpoint = config.serverless.publicEndpoint ? _chunkYQQ2ZDKTcjs.tryParseEndpoint.call(void 0, ctx, {
825
+ const token = _nullishCoalesce(_nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.token), () => ( config.token)), () => ( "dev"));
826
+ const parsedPublicEndpoint = config.serverless.publicEndpoint ? _chunkAIL267JKcjs.tryParseEndpoint.call(void 0, ctx, {
756
827
  endpoint: config.serverless.publicEndpoint,
757
828
  path: ["serverless", "publicEndpoint"]
758
829
  }) : void 0;
@@ -763,13 +834,14 @@ var RegistryConfigSchema = _zod.z.object({
763
834
  path: ["serverless", "publicEndpoint"]
764
835
  });
765
836
  }
766
- const publicEndpoint = _nullishCoalesce((parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint), () => ( (isDevEnv && config.startEngine ? ENGINE_ENDPOINT : void 0)));
837
+ const publicEndpoint = _nullishCoalesce((parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint), () => ( (isDevEnv && !parsedEndpoint ? endpoint : void 0)));
767
838
  const publicNamespace = parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.namespace;
768
839
  const publicToken = _nullishCoalesce((parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.token), () => ( config.serverless.publicToken));
769
840
  return {
770
841
  ...config,
771
842
  sqlite,
772
843
  endpoint,
844
+ startServices,
773
845
  namespace,
774
846
  token,
775
847
  publicEndpoint,
@@ -787,35 +859,10 @@ function buildActorNames(config) {
787
859
  Object.keys(config.use).map((actorName) => {
788
860
  const definition = config.use[actorName];
789
861
  const options = _nullishCoalesce(definition.config.options, () => ( {}));
790
- const runMeta = _chunkWQ4HNA4Wcjs.getRunMetadata.call(void 0, definition.config.run);
862
+ const runMeta = _chunk4KGXFC6Mcjs.getRunMetadata.call(void 0, definition.config.run);
791
863
  const metadata = {};
792
864
  metadata.icon = _nullishCoalesce(options.icon, () => ( runMeta.icon));
793
865
  metadata.name = _nullishCoalesce(options.name, () => ( runMeta.name));
794
- metadata.preload = {
795
- keys: [
796
- Array.from(_chunkLD5YASJUcjs.KEYS.PERSIST_DATA),
797
- Array.from(_chunkLD5YASJUcjs.KEYS.INSPECTOR_TOKEN),
798
- Array.from(_chunkLD5YASJUcjs.queueMetadataKey.call(void 0, )),
799
- Array.from(_chunkLD5YASJUcjs.KEYS.LAST_PUSHED_ALARM)
800
- ],
801
- prefixes: [
802
- {
803
- prefix: Array.from(_chunkLD5YASJUcjs.workflowStoragePrefix.call(void 0, )),
804
- maxBytes: _nullishCoalesce(options.preloadMaxWorkflowBytes, () => ( 131072)),
805
- partial: false
806
- },
807
- {
808
- prefix: Array.from(_chunkLD5YASJUcjs.KEYS.CONN_PREFIX),
809
- maxBytes: _nullishCoalesce(options.preloadMaxConnectionsBytes, () => ( 65536)),
810
- partial: false
811
- },
812
- {
813
- prefix: Array.from(_chunkLD5YASJUcjs.queueMessagesPrefix.call(void 0, )),
814
- maxBytes: 65536,
815
- partial: false
816
- }
817
- ]
818
- };
819
866
  if (!metadata.icon) delete metadata.icon;
820
867
  if (!metadata.name) delete metadata.name;
821
868
  return [actorName, { metadata }];
@@ -880,7 +927,7 @@ var DocRegistryConfigSchema = _zod.z.object({
880
927
  noWelcome: _zod.z.boolean().optional().describe("Disable the welcome message on startup. Default: false"),
881
928
  sqlite: DocSqliteConfigSchema,
882
929
  logging: _zod.z.object({
883
- level: _chunkO25KOT5Ccjs.LogLevelSchema.optional().describe(
930
+ level: _chunkEHZH3KUWcjs.LogLevelSchema.optional().describe(
884
931
  "Log level for RivetKit. Default: 'warn'"
885
932
  )
886
933
  }).optional().describe("Logging configuration."),
@@ -908,6 +955,9 @@ var DocRegistryConfigSchema = _zod.z.object({
908
955
  engineVersion: _zod.z.string().optional().describe(
909
956
  "Version of the local engine package to use. Defaults to the current RivetKit version."
910
957
  ),
958
+ startServices: _zod.z.boolean().optional().describe(
959
+ "Starts Services when RivetKit manages a local Engine. Defaults to the local-Engine decision. Set RIVET_RUN_SERVICES=0 or 1 to override."
960
+ ),
911
961
  configurePool: DocConfigurePoolSchema.describe(
912
962
  "Automatically configure serverless runners in the engine."
913
963
  ),
@@ -925,7 +975,7 @@ function shouldAttachNativeKvError(message) {
925
975
  function enrichNativeDatabaseError(database, error) {
926
976
  var _a;
927
977
  const bridgeReason = typeof error === "string" ? error : error instanceof Error ? error.message : void 0;
928
- const bridged = bridgeReason === void 0 ? void 0 : _chunkQAZLM4WTcjs.decodeBridgeRivetError.call(void 0, bridgeReason);
978
+ const bridged = bridgeReason === void 0 ? void 0 : _chunk2JSYYH6Pcjs.decodeBridgeRivetError.call(void 0, bridgeReason);
929
979
  if (bridged) {
930
980
  throw bridged;
931
981
  }
@@ -1008,6 +1058,12 @@ function toNativeBindings(sql, params) {
1008
1058
  return toNativeBinding(value);
1009
1059
  });
1010
1060
  }
1061
+ function toNativeBatchStatement(statement) {
1062
+ return {
1063
+ sql: statement.sql,
1064
+ params: toNativeBindings(statement.sql, statement.params)
1065
+ };
1066
+ }
1011
1067
  function normalizeNativeMetrics(metrics) {
1012
1068
  if (!metrics) return null;
1013
1069
  const raw = metrics;
@@ -1121,6 +1177,82 @@ function wrapJsNativeDatabase(database) {
1121
1177
  async execute(sql, params) {
1122
1178
  return await executeNative(sql, params);
1123
1179
  },
1180
+ async executeBatch(statements) {
1181
+ const nativeStatements = statements.map(toNativeBatchStatement);
1182
+ const release = gate.enter();
1183
+ let transaction;
1184
+ try {
1185
+ const results = database.executeBatch ? await database.executeBatch(nativeStatements) : await (async () => {
1186
+ transaction = await database.beginTransaction();
1187
+ const transactionResults = [];
1188
+ for (const statement of nativeStatements) {
1189
+ transactionResults.push(
1190
+ await transaction.execute(
1191
+ statement.sql,
1192
+ statement.params
1193
+ )
1194
+ );
1195
+ }
1196
+ await transaction.commit();
1197
+ transaction = void 0;
1198
+ return transactionResults;
1199
+ })();
1200
+ for (const result of results) {
1201
+ if (result.lastInsertRowId !== void 0) {
1202
+ lastInsertRowId = result.lastInsertRowId;
1203
+ }
1204
+ }
1205
+ return results;
1206
+ } catch (error) {
1207
+ if (transaction) {
1208
+ try {
1209
+ await transaction.rollback();
1210
+ } catch (e2) {
1211
+ }
1212
+ }
1213
+ enrichNativeDatabaseError(database, error);
1214
+ } finally {
1215
+ release();
1216
+ }
1217
+ },
1218
+ async beginTransaction(timeoutMs, name) {
1219
+ const release = gate.enter();
1220
+ let transaction;
1221
+ try {
1222
+ transaction = await database.beginTransaction(timeoutMs, name);
1223
+ } catch (error) {
1224
+ enrichNativeDatabaseError(database, error);
1225
+ } finally {
1226
+ release();
1227
+ }
1228
+ return wrapTransaction(database, transaction, gate, (result) => {
1229
+ if (result.lastInsertRowId !== void 0) {
1230
+ lastInsertRowId = result.lastInsertRowId;
1231
+ }
1232
+ });
1233
+ },
1234
+ async beginStateTransaction(timeoutMs, context) {
1235
+ if (!database.beginStateTransaction) {
1236
+ throw new Error("actor state transactions are not configured");
1237
+ }
1238
+ const release = gate.enter();
1239
+ let transaction;
1240
+ try {
1241
+ transaction = await database.beginStateTransaction(
1242
+ timeoutMs,
1243
+ context
1244
+ );
1245
+ } catch (error) {
1246
+ enrichNativeDatabaseError(database, error);
1247
+ } finally {
1248
+ release();
1249
+ }
1250
+ return wrapTransaction(database, transaction, gate, (result) => {
1251
+ if (result.lastInsertRowId !== void 0) {
1252
+ lastInsertRowId = result.lastInsertRowId;
1253
+ }
1254
+ });
1255
+ },
1124
1256
  async run(sql, params) {
1125
1257
  await executeNative(sql, params);
1126
1258
  },
@@ -1138,6 +1270,59 @@ function wrapJsNativeDatabase(database) {
1138
1270
  }
1139
1271
  };
1140
1272
  }
1273
+ function wrapTransaction(database, transaction, gate, onExecute) {
1274
+ return {
1275
+ async exec(sql, callback) {
1276
+ const release = gate.enter();
1277
+ let result;
1278
+ try {
1279
+ result = await transaction.exec(sql);
1280
+ } catch (error) {
1281
+ enrichNativeDatabaseError(database, error);
1282
+ } finally {
1283
+ release();
1284
+ }
1285
+ if (callback) {
1286
+ for (const row of result.rows) callback(row, result.columns);
1287
+ }
1288
+ },
1289
+ async execute(sql, params) {
1290
+ const release = gate.enter();
1291
+ try {
1292
+ const result = await transaction.execute(
1293
+ sql,
1294
+ toNativeBindings(sql, params)
1295
+ );
1296
+ onExecute(result);
1297
+ return result;
1298
+ } catch (error) {
1299
+ enrichNativeDatabaseError(database, error);
1300
+ } finally {
1301
+ release();
1302
+ }
1303
+ },
1304
+ async commit() {
1305
+ const release = gate.enter();
1306
+ try {
1307
+ await transaction.commit();
1308
+ } catch (error) {
1309
+ enrichNativeDatabaseError(database, error);
1310
+ } finally {
1311
+ release();
1312
+ }
1313
+ },
1314
+ async rollback() {
1315
+ const release = gate.enter();
1316
+ try {
1317
+ await transaction.rollback();
1318
+ } catch (error) {
1319
+ enrichNativeDatabaseError(database, error);
1320
+ } finally {
1321
+ release();
1322
+ }
1323
+ }
1324
+ };
1325
+ }
1141
1326
  function lastInsertRowIdColumnName(sql) {
1142
1327
  const match = sql.match(
1143
1328
  /^\s*SELECT\s+last_insert_rowid\s*\(\s*\)\s*(?:AS\s+("[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))?\s*;?\s*$/i
@@ -1155,6 +1340,74 @@ function lastInsertRowIdColumnName(sql) {
1155
1340
  return alias;
1156
1341
  }
1157
1342
 
1343
+ // src/utils/node.ts
1344
+ var _module = require('module');
1345
+ var nodeCrypto;
1346
+ var nodeFsSync;
1347
+ var nodeFs;
1348
+ var nodePath;
1349
+ var nodeOs;
1350
+ var nodeChildProcess;
1351
+ var nodeStream;
1352
+ var nodeUrl;
1353
+ var hasImportedDependencies = false;
1354
+ var fallbackRequire;
1355
+ function loadNodeBuiltin(id) {
1356
+ var _a;
1357
+ const nodeProcess = globalThis.process;
1358
+ const builtin = (_a = nodeProcess == null ? void 0 : nodeProcess.getBuiltinModule) == null ? void 0 : _a.call(nodeProcess, id);
1359
+ if (builtin !== void 0) {
1360
+ return builtin;
1361
+ }
1362
+ if (!(nodeProcess == null ? void 0 : nodeProcess.execPath)) {
1363
+ throw new Error("Node.js built-ins are not available");
1364
+ }
1365
+ fallbackRequire ??= _module.createRequire.call(void 0, nodeProcess.execPath);
1366
+ return fallbackRequire(id);
1367
+ }
1368
+ function importNodeDependencies() {
1369
+ if (hasImportedDependencies) return;
1370
+ try {
1371
+ nodeCrypto = loadNodeBuiltin("node:crypto");
1372
+ nodeFsSync = loadNodeBuiltin("node:fs");
1373
+ nodeFs = loadNodeBuiltin(
1374
+ "node:fs/promises"
1375
+ );
1376
+ nodePath = loadNodeBuiltin("node:path");
1377
+ nodeOs = loadNodeBuiltin("node:os");
1378
+ nodeChildProcess = loadNodeBuiltin(
1379
+ "node:child_process"
1380
+ );
1381
+ nodeStream = loadNodeBuiltin(
1382
+ "node:stream/promises"
1383
+ );
1384
+ nodeUrl = loadNodeBuiltin("node:url");
1385
+ hasImportedDependencies = true;
1386
+ } catch (err) {
1387
+ console.warn(
1388
+ "Node.js modules not available, file system driver will not work",
1389
+ err
1390
+ );
1391
+ throw err;
1392
+ }
1393
+ }
1394
+ function getNodeFsSync() {
1395
+ if (!nodeFsSync) {
1396
+ throw new Error(
1397
+ "Node fs module not loaded. Ensure importNodeDependencies() has been called."
1398
+ );
1399
+ }
1400
+ return nodeFsSync;
1401
+ }
1402
+ function getNodePath() {
1403
+ if (!nodePath) {
1404
+ throw new Error(
1405
+ "Node path module not loaded. Ensure importNodeDependencies() has been called."
1406
+ );
1407
+ }
1408
+ return nodePath;
1409
+ }
1410
+
1158
1411
  // src/registry/runtime.ts
1159
1412
  function normalizeRuntimeSqlExecuteResult(result) {
1160
1413
  return result;
@@ -1176,6 +1429,12 @@ function asNativeConn(handle) {
1176
1429
  function asNativeWebSocket(handle) {
1177
1430
  return handle;
1178
1431
  }
1432
+ function asNativeSqlTransaction(handle) {
1433
+ return handle;
1434
+ }
1435
+ function asNativeActorStateTransaction(handle) {
1436
+ return handle;
1437
+ }
1179
1438
  function asNativeCancellationToken(handle) {
1180
1439
  return handle;
1181
1440
  }
@@ -1205,9 +1464,45 @@ function toNapiSqlBindParams(params) {
1205
1464
  }
1206
1465
  return params.map((param) => toNapiSqlBindParam(param));
1207
1466
  }
1467
+ function toNapiSqlBatchStatement(statement) {
1468
+ return {
1469
+ sql: statement.sql,
1470
+ params: _nullishCoalesce(toNapiSqlBindParams(statement.params), () => ( void 0))
1471
+ };
1472
+ }
1208
1473
  function toNapiBuffer(value) {
1209
1474
  return Buffer.from(value);
1210
1475
  }
1476
+ function toNapiApplication(application) {
1477
+ return async (error, request) => {
1478
+ if (error) throw error;
1479
+ if (!request) {
1480
+ throw new Error("application fetch callback received no request");
1481
+ }
1482
+ const response = await application(
1483
+ {
1484
+ ...request,
1485
+ body: new Uint8Array(request.body),
1486
+ cancelToken: request.cancelToken
1487
+ },
1488
+ request.responseBodyStream ? fromNapiHttpResponseBodyStream(
1489
+ request.responseBodyStream
1490
+ ) : void 0
1491
+ );
1492
+ return {
1493
+ ...response,
1494
+ body: response.body === void 0 ? void 0 : toNapiBuffer(response.body)
1495
+ };
1496
+ };
1497
+ }
1498
+ function fromNapiHttpResponseBodyStream(stream) {
1499
+ return {
1500
+ cancelled: () => stream.cancelled(),
1501
+ write: (chunk) => stream.write(Buffer.from(chunk)),
1502
+ end: () => stream.end(),
1503
+ error: (message) => stream.error(message)
1504
+ };
1505
+ }
1211
1506
  function toNapiHttpRequest(request) {
1212
1507
  if (!request) {
1213
1508
  return request;
@@ -1272,14 +1567,37 @@ var NapiCoreRuntime = (_class = class {
1272
1567
  async serveRegistry(registry, config) {
1273
1568
  await asNativeRegistry(registry).serve(config);
1274
1569
  }
1570
+ async waitRegistryReady(registry) {
1571
+ await asNativeRegistry(registry).waitReady();
1572
+ }
1275
1573
  async shutdownRegistry(registry) {
1276
1574
  await asNativeRegistry(registry).shutdown();
1277
1575
  }
1278
- async registryDiagnostics(registry) {
1279
- const diagnostics = await asNativeRegistry(registry).diagnostics();
1576
+ async registryActorStopThresholdMs(registry) {
1577
+ return await _asyncNullishCoalesce(await asNativeRegistry(registry).actorStopThresholdMs(), async () => ( void 0));
1578
+ }
1579
+ async registryHealth(registry) {
1580
+ const response = await asNativeRegistry(registry).health();
1581
+ return {
1582
+ status: response.status,
1583
+ headers: response.headers,
1584
+ body: response.body
1585
+ };
1586
+ }
1587
+ async registryMetadata(registry) {
1588
+ const response = asNativeRegistry(registry).metadata();
1589
+ return {
1590
+ status: response.status,
1591
+ headers: response.headers,
1592
+ body: response.body
1593
+ };
1594
+ }
1595
+ async registryMetrics(registry) {
1596
+ const response = asNativeRegistry(registry).metrics();
1280
1597
  return {
1281
- mode: diagnostics.mode,
1282
- envoyActiveActorCount: diagnostics.envoyActiveActorCount
1598
+ status: response.status,
1599
+ headers: response.headers,
1600
+ body: response.body
1283
1601
  };
1284
1602
  }
1285
1603
  async handleServerlessRequest(registry, req, onStreamEvent, cancelToken, config) {
@@ -1290,6 +1608,29 @@ var NapiCoreRuntime = (_class = class {
1290
1608
  config
1291
1609
  );
1292
1610
  }
1611
+ async serveListener(registry, listener, config) {
1612
+ const application = listener.application ? toNapiApplication(listener.application) : void 0;
1613
+ await asNativeRegistry(registry).serveListener(
1614
+ {
1615
+ port: listener.port,
1616
+ host: listener.host,
1617
+ publicDir: listener.publicDir
1618
+ },
1619
+ config,
1620
+ application
1621
+ );
1622
+ }
1623
+ async serveApplicationListener(registry, listener, config) {
1624
+ await asNativeRegistry(registry).serveApplicationListener(
1625
+ {
1626
+ port: listener.port,
1627
+ host: listener.host,
1628
+ publicDir: listener.publicDir
1629
+ },
1630
+ toNapiApplication(listener.application),
1631
+ config
1632
+ );
1633
+ }
1293
1634
  createActorFactory(callbacks, config) {
1294
1635
  return asActorFactoryHandle(
1295
1636
  new this.#bindings.NapiActorFactory(callbacks, config)
@@ -1298,11 +1639,16 @@ var NapiCoreRuntime = (_class = class {
1298
1639
  createCancellationToken() {
1299
1640
  return new this.#bindings.CancellationToken();
1300
1641
  }
1301
- createTestActorContext(actorId, name, region) {
1302
- return new this.#bindings.ActorContext(
1303
- actorId,
1304
- name,
1305
- region
1642
+ decodeInspectorRequest(bytes, advertisedVersion) {
1643
+ return this.#bindings.decodeInspectorRequest(
1644
+ toNapiBuffer(bytes),
1645
+ advertisedVersion
1646
+ );
1647
+ }
1648
+ encodeInspectorResponse(bytes, targetVersion) {
1649
+ return this.#bindings.encodeInspectorResponse(
1650
+ toNapiBuffer(bytes),
1651
+ targetVersion
1306
1652
  );
1307
1653
  }
1308
1654
  cancellationTokenAborted(token) {
@@ -1326,6 +1672,9 @@ var NapiCoreRuntime = (_class = class {
1326
1672
  actorSetAlarm(ctx, timestampMs) {
1327
1673
  asNativeActorContext(ctx).setAlarm(timestampMs);
1328
1674
  }
1675
+ async actorSetRunWakeAt(ctx, timestampMs) {
1676
+ await asNativeActorContext(ctx).setRunWakeAt(timestampMs);
1677
+ }
1329
1678
  actorRequestSave(ctx, opts) {
1330
1679
  asNativeActorContext(ctx).requestSave(opts);
1331
1680
  }
@@ -1366,6 +1715,14 @@ var NapiCoreRuntime = (_class = class {
1366
1715
  toNapiStateDeltaPayload(payload)
1367
1716
  );
1368
1717
  }
1718
+ async actorSaveStateAndWorkflowBatch(ctx, writes) {
1719
+ await asNativeActorContext(ctx).saveStateAndWorkflowBatch(
1720
+ writes.map((write) => ({
1721
+ key: toNapiBuffer(write.key),
1722
+ value: toNapiBuffer(write.value)
1723
+ }))
1724
+ );
1725
+ }
1369
1726
  actorId(ctx) {
1370
1727
  return asNativeActorContext(ctx).actorId();
1371
1728
  }
@@ -1405,6 +1762,9 @@ var NapiCoreRuntime = (_class = class {
1405
1762
  async actorWaitForTrackedShutdownWork(ctx) {
1406
1763
  return await asNativeActorContext(ctx).waitForTrackedShutdownWork();
1407
1764
  }
1765
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
1766
+ await asNativeActorContext(ctx).waitForTrackedShutdownWorkUnbounded();
1767
+ }
1408
1768
  actorKeepAwake(ctx, promise) {
1409
1769
  asNativeActorContext(ctx).keepAwake(promise);
1410
1770
  }
@@ -1469,6 +1829,54 @@ var NapiCoreRuntime = (_class = class {
1469
1829
  );
1470
1830
  return normalizeRuntimeSqlExecuteResult(result);
1471
1831
  }
1832
+ async actorSqlExecuteBatch(ctx, statements) {
1833
+ const results = await this.#actorSql(ctx).executeBatch(
1834
+ statements.map(toNapiSqlBatchStatement)
1835
+ );
1836
+ return results.map(normalizeRuntimeSqlExecuteResult);
1837
+ }
1838
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
1839
+ return await this.#actorSql(ctx).beginTransaction(
1840
+ timeoutMs,
1841
+ name
1842
+ );
1843
+ }
1844
+ async actorSqlTransactionExec(transaction, sql) {
1845
+ return await asNativeSqlTransaction(transaction).exec(sql);
1846
+ }
1847
+ async actorSqlTransactionExecute(transaction, sql, params) {
1848
+ const result = await asNativeSqlTransaction(transaction).execute(
1849
+ sql,
1850
+ toNapiSqlBindParams(params)
1851
+ );
1852
+ return normalizeRuntimeSqlExecuteResult(result);
1853
+ }
1854
+ async actorSqlTransactionCommit(transaction) {
1855
+ await asNativeSqlTransaction(transaction).commit();
1856
+ }
1857
+ async actorSqlTransactionRollback(transaction) {
1858
+ await asNativeSqlTransaction(transaction).rollback();
1859
+ }
1860
+ async actorBeginStateTransaction(ctx, timeoutMs) {
1861
+ return await asNativeActorContext(ctx).beginStateTransaction(
1862
+ timeoutMs
1863
+ );
1864
+ }
1865
+ async actorStateTransactionExecute(transaction, sql, params) {
1866
+ const result = await asNativeActorStateTransaction(transaction).execute(
1867
+ sql,
1868
+ toNapiSqlBindParams(params)
1869
+ );
1870
+ return normalizeRuntimeSqlExecuteResult(result);
1871
+ }
1872
+ async actorStateTransactionCommit(transaction, payload) {
1873
+ await asNativeActorStateTransaction(transaction).commit(
1874
+ toNapiStateDeltaPayload(payload)
1875
+ );
1876
+ }
1877
+ async actorStateTransactionRollback(transaction) {
1878
+ await asNativeActorStateTransaction(transaction).rollback();
1879
+ }
1472
1880
  async actorSqlQuery(ctx, sql, params) {
1473
1881
  return await this.#actorSql(ctx).query(
1474
1882
  sql,
@@ -1495,6 +1903,9 @@ var NapiCoreRuntime = (_class = class {
1495
1903
  this.#sql.delete(nativeCtx);
1496
1904
  await database.close();
1497
1905
  }
1906
+ async actorRuntimeSocketProvision(ctx) {
1907
+ return await asNativeActorContext(ctx).provisionActorRuntimeSocket();
1908
+ }
1498
1909
  async actorQueueSend(ctx, name, body) {
1499
1910
  return toNapiQueueMessage(
1500
1911
  await asNativeActorContext(ctx).queue().send(name, toNapiBuffer(body))
@@ -1516,8 +1927,19 @@ var NapiCoreRuntime = (_class = class {
1516
1927
  )
1517
1928
  );
1518
1929
  }
1519
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
1520
- await asNativeActorContext(ctx).queue().waitForNamesAvailable(names, options);
1930
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
1931
+ await asNativeActorContext(ctx).queue().waitForNamesAvailable(
1932
+ names,
1933
+ options,
1934
+ signal ? asNativeCancellationToken(signal) : signal
1935
+ );
1936
+ }
1937
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
1938
+ return await asNativeActorContext(ctx).queue().completePersisted(
1939
+ messageId,
1940
+ expectedName,
1941
+ response == null ? response : toNapiBuffer(response)
1942
+ );
1521
1943
  }
1522
1944
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1523
1945
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
@@ -1536,11 +1958,54 @@ var NapiCoreRuntime = (_class = class {
1536
1958
  async actorQueueInspectMessages(ctx) {
1537
1959
  return await asNativeActorContext(ctx).queue().inspectMessages();
1538
1960
  }
1539
- actorScheduleAfter(ctx, durationMs, actionName, args) {
1540
- asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
1961
+ async actorQueueReset(ctx) {
1962
+ await asNativeActorContext(ctx).queue().reset();
1963
+ }
1964
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
1965
+ return await asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
1966
+ }
1967
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
1968
+ return await asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
1969
+ }
1970
+ async actorScheduleCancel(ctx, id) {
1971
+ return await asNativeActorContext(ctx).schedule().cancel(id);
1972
+ }
1973
+ async actorScheduleGet(ctx, id) {
1974
+ return await _asyncNullishCoalesce(await asNativeActorContext(ctx).schedule().get(id), async () => ( void 0));
1975
+ }
1976
+ async actorScheduleList(ctx) {
1977
+ return await asNativeActorContext(ctx).schedule().list();
1978
+ }
1979
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
1980
+ await asNativeActorContext(ctx).schedule().cronSet(
1981
+ name,
1982
+ expression,
1983
+ timezone,
1984
+ actionName,
1985
+ toNapiBuffer(args),
1986
+ maxHistory
1987
+ );
1988
+ }
1989
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
1990
+ await asNativeActorContext(ctx).schedule().cronEvery(
1991
+ name,
1992
+ intervalMs,
1993
+ actionName,
1994
+ toNapiBuffer(args),
1995
+ maxHistory
1996
+ );
1997
+ }
1998
+ async actorCronGet(ctx, name) {
1999
+ return await _asyncNullishCoalesce(await asNativeActorContext(ctx).schedule().cronGet(name), async () => ( void 0));
2000
+ }
2001
+ async actorCronList(ctx) {
2002
+ return await asNativeActorContext(ctx).schedule().cronList();
1541
2003
  }
1542
- actorScheduleAt(ctx, timestampMs, actionName, args) {
1543
- asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
2004
+ async actorCronDelete(ctx, name) {
2005
+ return await asNativeActorContext(ctx).schedule().cronDelete(name);
2006
+ }
2007
+ async actorCronHistory(ctx, name, limit) {
2008
+ return await asNativeActorContext(ctx).schedule().cronHistory(name, limit);
1544
2009
  }
1545
2010
  connId(conn) {
1546
2011
  return asNativeConn(conn).id();
@@ -1581,19 +2046,162 @@ async function loadNapiRuntime() {
1581
2046
  };
1582
2047
  }
1583
2048
 
1584
- // src/registry/native-validation.ts
1585
- var CONN_PARAMS_KEY = "__conn_params__";
1586
- function validateActionArgs(schemas, name, args) {
1587
- if (!(schemas == null ? void 0 : schemas[name])) {
1588
- return args;
1589
- }
1590
- const result = validateSchemaSync(schemas, name, args);
1591
- if (!result.success) {
1592
- throw validationError(`action \`${name}\` arguments`, result.issues);
1593
- }
1594
- return Array.isArray(result.data) ? result.data : [result.data];
1595
- }
1596
- function validateConnParams(schema, params) {
2049
+ // src/registry/native-http.ts
2050
+ var HTTP_BODY_CHUNK_SIZE = 64 * 1024;
2051
+ function runtimeBytesToArrayBuffer(value) {
2052
+ return value.buffer.slice(
2053
+ value.byteOffset,
2054
+ value.byteOffset + value.byteLength
2055
+ );
2056
+ }
2057
+ function buildNativeHttpRequest(init) {
2058
+ var _a;
2059
+ const headers = new Headers(init.headers);
2060
+ const originalUrl = headers.get(_chunkAIL267JKcjs.HEADER_ORIGINAL_REQUEST_URL);
2061
+ headers.delete(_chunkAIL267JKcjs.HEADER_ORIGINAL_REQUEST_URL);
2062
+ const url = _nullishCoalesce(originalUrl, () => ( (init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString())));
2063
+ const method2 = init.method.toUpperCase();
2064
+ const bodyForbidden = method2 === "GET" || method2 === "HEAD";
2065
+ const body = bodyForbidden ? void 0 : init.bodyStream ? new ReadableStream({
2066
+ async pull(controller) {
2067
+ var _a2, _b;
2068
+ try {
2069
+ if (init.body && init.body.length > 0) {
2070
+ controller.enqueue(new Uint8Array(init.body));
2071
+ init.body = void 0;
2072
+ return;
2073
+ }
2074
+ const chunk = await ((_a2 = init.bodyStream) == null ? void 0 : _a2.read());
2075
+ if (!chunk) {
2076
+ controller.close();
2077
+ } else {
2078
+ controller.enqueue(new Uint8Array(chunk));
2079
+ }
2080
+ } catch (error) {
2081
+ (_b = init.abortController) == null ? void 0 : _b.abort(error);
2082
+ controller.error(error);
2083
+ }
2084
+ },
2085
+ async cancel() {
2086
+ var _a2;
2087
+ await ((_a2 = init.bodyStream) == null ? void 0 : _a2.cancel());
2088
+ }
2089
+ }) : init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
2090
+ const streamInit = init.bodyStream && !bodyForbidden ? { duplex: "half" } : {};
2091
+ return new Request(url, {
2092
+ method: method2,
2093
+ headers,
2094
+ body,
2095
+ signal: _nullishCoalesce(((_a = init.abortController) == null ? void 0 : _a.signal), () => ( init.signal)),
2096
+ ...streamInit
2097
+ });
2098
+ }
2099
+ async function cancelNativeHttpRequestBody(bodyStream) {
2100
+ await (bodyStream == null ? void 0 : bodyStream.cancel());
2101
+ }
2102
+ async function writeResponseChunk(stream, chunk) {
2103
+ for (let offset = 0; offset < chunk.byteLength; offset += HTTP_BODY_CHUNK_SIZE) {
2104
+ await stream.write(
2105
+ chunk.subarray(offset, offset + HTTP_BODY_CHUNK_SIZE)
2106
+ );
2107
+ }
2108
+ }
2109
+ async function pumpResponseBody(reader, stream) {
2110
+ var _a;
2111
+ const cancelled = stream.cancelled().then(() => ({ cancelled: true }));
2112
+ try {
2113
+ for (; ; ) {
2114
+ const read = reader.read().then((next2) => ({ cancelled: false, next: next2 }));
2115
+ const result = await Promise.race([read, cancelled]);
2116
+ if (result.cancelled) {
2117
+ void reader.cancel(
2118
+ new Error(
2119
+ "native http response stream receiver dropped"
2120
+ )
2121
+ ).catch((error) => {
2122
+ logger2().debug({
2123
+ msg: "failed to cancel native http response reader",
2124
+ error
2125
+ });
2126
+ });
2127
+ return;
2128
+ }
2129
+ const { next } = result;
2130
+ if (next.done) {
2131
+ await stream.end();
2132
+ return;
2133
+ }
2134
+ if ((_a = next.value) == null ? void 0 : _a.byteLength) {
2135
+ await writeResponseChunk(stream, next.value);
2136
+ }
2137
+ }
2138
+ } catch (error) {
2139
+ try {
2140
+ await stream.error(_chunkEHZH3KUWcjs.stringifyError.call(void 0, error));
2141
+ } catch (streamError) {
2142
+ logger2().debug({
2143
+ msg: "failed to report native http response stream error",
2144
+ error: streamError
2145
+ });
2146
+ }
2147
+ void reader.cancel(error).catch(() => {
2148
+ });
2149
+ } finally {
2150
+ try {
2151
+ reader.releaseLock();
2152
+ } catch (error) {
2153
+ logger2().debug({
2154
+ msg: "failed to release native http response reader lock",
2155
+ error
2156
+ });
2157
+ }
2158
+ }
2159
+ }
2160
+ async function convertNativeHttpResponse(response, responseBodyStream) {
2161
+ const headers = Object.fromEntries(response.headers.entries());
2162
+ if (!response.body) {
2163
+ return {
2164
+ response: {
2165
+ status: response.status,
2166
+ headers,
2167
+ body: new Uint8Array()
2168
+ }
2169
+ };
2170
+ }
2171
+ if (responseBodyStream) {
2172
+ const reader = response.body.getReader();
2173
+ const bodyCompletion = pumpResponseBody(reader, responseBodyStream);
2174
+ return {
2175
+ response: {
2176
+ status: response.status,
2177
+ headers,
2178
+ stream: true
2179
+ },
2180
+ bodyCompletion
2181
+ };
2182
+ }
2183
+ return {
2184
+ response: {
2185
+ status: response.status,
2186
+ headers,
2187
+ body: new Uint8Array(await response.arrayBuffer())
2188
+ }
2189
+ };
2190
+ }
2191
+
2192
+ // src/registry/native-validation.ts
2193
+ var CONN_PARAMS_KEY = "__conn_params__";
2194
+ function validateActionArgs(schemas, name, args) {
2195
+ if (!(schemas == null ? void 0 : schemas[name])) {
2196
+ return args;
2197
+ }
2198
+ const result = validateSchemaSync(schemas, name, args);
2199
+ if (!result.success) {
2200
+ throw validationError(`action \`${name}\` arguments`, result.issues);
2201
+ }
2202
+ return Array.isArray(result.data) ? result.data : [result.data];
2203
+ }
2204
+ function validateConnParams(schema, params) {
1597
2205
  if (!schema) {
1598
2206
  return params;
1599
2207
  }
@@ -1651,23 +2259,181 @@ function validateQueueComplete(schemas, name, response) {
1651
2259
  response
1652
2260
  );
1653
2261
  if (!result.success) {
1654
- throw validationError(`queue \`${name}\` completion response`, result.issues);
2262
+ throw validationError(
2263
+ `queue \`${name}\` completion response`,
2264
+ result.issues
2265
+ );
1655
2266
  }
1656
2267
  return result.data;
1657
2268
  }
1658
2269
  function validationError(target, issues) {
1659
- return new (0, _chunkQAZLM4WTcjs.RivetError)(
2270
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)("actor", "validation_error", `Invalid ${target}`, {
2271
+ public: true,
2272
+ metadata: { issues }
2273
+ });
2274
+ }
2275
+
2276
+ // src/registry/run-handler-coordinator.ts
2277
+ function runUnavailable(actorId, reason) {
2278
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)(
1660
2279
  "actor",
1661
- "validation_error",
1662
- `Invalid ${target}`,
2280
+ "run_handler_unavailable",
2281
+ `Run handler control is unavailable for actor ${actorId}: ${reason}.`,
1663
2282
  {
1664
2283
  public: true,
1665
- metadata: { issues }
2284
+ statusCode: 409,
2285
+ metadata: { actorId, reason }
1666
2286
  }
1667
2287
  );
1668
2288
  }
2289
+ function notifyStateChanged(state) {
2290
+ const waiters = [...state.waiters];
2291
+ state.waiters.clear();
2292
+ for (const waiter of waiters) {
2293
+ waiter();
2294
+ }
2295
+ }
2296
+ function waitForStateChange(state) {
2297
+ return new Promise((resolve) => {
2298
+ state.waiters.add(resolve);
2299
+ });
2300
+ }
2301
+ var RunHandlerCoordinator = class {
2302
+ #run;
2303
+ #states = /* @__PURE__ */ new Map();
2304
+ constructor(run) {
2305
+ this.#run = run;
2306
+ }
2307
+ get inspectorKind() {
2308
+ return _chunk4KGXFC6Mcjs.getRunInspectorKind.call(void 0, this.#run);
2309
+ }
2310
+ async run(actorId, restart, callback) {
2311
+ const state = this.#getOrCreate(actorId);
2312
+ state.restart = restart;
2313
+ this.#initializeInspector(actorId, state);
2314
+ state.queued += 1;
2315
+ const blockedGeneration = state.exclusive ? state.exclusiveGeneration : void 0;
2316
+ try {
2317
+ while (!state.closed && (state.exclusive || state.active)) {
2318
+ await waitForStateChange(state);
2319
+ }
2320
+ } finally {
2321
+ state.queued -= 1;
2322
+ }
2323
+ if (state.closed) {
2324
+ return "closed";
2325
+ }
2326
+ if (blockedGeneration !== void 0 && state.exclusiveGeneration === blockedGeneration && state.exclusiveOutcome === "failure") {
2327
+ return "suppressed";
2328
+ }
2329
+ state.active = true;
2330
+ try {
2331
+ await callback();
2332
+ return "ran";
2333
+ } finally {
2334
+ state.active = false;
2335
+ notifyStateChanged(state);
2336
+ }
2337
+ }
2338
+ getInspector(actorId, restart) {
2339
+ var _a;
2340
+ const state = this.#getOrCreate(actorId);
2341
+ state.restart = restart;
2342
+ this.#initializeInspector(actorId, state);
2343
+ return (_a = state.inspector) == null ? void 0 : _a.inspector;
2344
+ }
2345
+ destroy(actorId) {
2346
+ var _a, _b;
2347
+ const state = this.#states.get(actorId);
2348
+ if (!state) return;
2349
+ state.closed = true;
2350
+ (_b = (_a = state.inspector) == null ? void 0 : _a.dispose) == null ? void 0 : _b.call(_a);
2351
+ state.inspector = void 0;
2352
+ notifyStateChanged(state);
2353
+ this.#states.delete(actorId);
2354
+ }
2355
+ #control(actorId, state) {
2356
+ return {
2357
+ run: {
2358
+ withInactive: async (options, callback) => {
2359
+ if (state.closed) {
2360
+ throw runUnavailable(actorId, "actor is destroyed");
2361
+ }
2362
+ if (state.active || state.queued > 0 || state.exclusive) {
2363
+ throw runUnavailable(
2364
+ actorId,
2365
+ "the run handler is active or waiting to start"
2366
+ );
2367
+ }
2368
+ state.exclusive = true;
2369
+ state.exclusiveGeneration += 1;
2370
+ state.exclusiveOutcome = void 0;
2371
+ try {
2372
+ const result = await callback();
2373
+ if (state.closed) {
2374
+ throw runUnavailable(actorId, "actor is destroyed");
2375
+ }
2376
+ state.exclusiveOutcome = "success";
2377
+ if (options.restartOnSuccess && state.queued === 0) {
2378
+ if (!state.restart) {
2379
+ throw runUnavailable(
2380
+ actorId,
2381
+ "the runtime restart callback is not available"
2382
+ );
2383
+ }
2384
+ await state.restart();
2385
+ }
2386
+ return result;
2387
+ } catch (error) {
2388
+ state.exclusiveOutcome = "failure";
2389
+ throw error;
2390
+ } finally {
2391
+ state.exclusive = false;
2392
+ notifyStateChanged(state);
2393
+ }
2394
+ }
2395
+ }
2396
+ };
2397
+ }
2398
+ #getOrCreate(actorId) {
2399
+ let state = this.#states.get(actorId);
2400
+ if (!state) {
2401
+ state = {
2402
+ active: false,
2403
+ closed: false,
2404
+ exclusive: false,
2405
+ exclusiveGeneration: 0,
2406
+ inspectorInitialized: false,
2407
+ queued: 0,
2408
+ waiters: /* @__PURE__ */ new Set()
2409
+ };
2410
+ this.#states.set(actorId, state);
2411
+ }
2412
+ return state;
2413
+ }
2414
+ #initializeInspector(actorId, state) {
2415
+ if (state.inspectorInitialized) return;
2416
+ const inspector = _chunk4KGXFC6Mcjs.createRunInspector.call(void 0, this.#run, {
2417
+ actorId,
2418
+ control: this.#control(actorId, state)
2419
+ });
2420
+ if (this.inspectorKind === "workflow") {
2421
+ const workflow = inspector === void 0 ? void 0 : inspector.inspector.workflow;
2422
+ if (!workflow || typeof workflow.getHistory !== "function" || typeof workflow.getState !== "function" || typeof workflow.onHistoryUpdated !== "function" || typeof workflow.replayFromStep !== "function") {
2423
+ throw new TypeError(
2424
+ `defineRunHandler createInspector returned an invalid workflow adapter for actor ${actorId}`
2425
+ );
2426
+ }
2427
+ }
2428
+ state.inspector = inspector;
2429
+ state.inspectorInitialized = true;
2430
+ }
2431
+ };
1669
2432
 
1670
2433
  // src/registry/wasm-runtime.ts
2434
+ function asWasmConstructors(bindings) {
2435
+ return bindings;
2436
+ }
1671
2437
  function asWasmRegistry(handle) {
1672
2438
  return handle;
1673
2439
  }
@@ -1730,16 +2496,16 @@ function normalizeQueueMessage(message) {
1730
2496
  }
1731
2497
  function normalizeWasmBridgeError(error) {
1732
2498
  if (typeof error === "string") {
1733
- return _nullishCoalesce(_chunkQAZLM4WTcjs.decodeBridgeRivetError.call(void 0, error), () => ( error));
2499
+ return _nullishCoalesce(_chunk2JSYYH6Pcjs.decodeBridgeRivetError.call(void 0, error), () => ( error));
1734
2500
  }
1735
2501
  if (error instanceof Error) {
1736
- const bridged = _chunkQAZLM4WTcjs.decodeBridgeRivetError.call(void 0, error.message);
2502
+ const bridged = _chunk2JSYYH6Pcjs.decodeBridgeRivetError.call(void 0, error.message);
1737
2503
  if (bridged) {
1738
2504
  return bridged;
1739
2505
  }
1740
2506
  }
1741
2507
  if (typeof error === "object" && error !== null && "reason" in error && typeof error.reason === "string") {
1742
- const bridged = _chunkQAZLM4WTcjs.decodeBridgeRivetError.call(void 0, error.reason);
2508
+ const bridged = _chunk2JSYYH6Pcjs.decodeBridgeRivetError.call(void 0, error.reason);
1743
2509
  if (bridged) {
1744
2510
  return bridged;
1745
2511
  }
@@ -1761,7 +2527,7 @@ function callWasmSync(invoke) {
1761
2527
  }
1762
2528
  }
1763
2529
  function unsupportedWasmMethod(method2) {
1764
- throw new (0, _chunkQAZLM4WTcjs.RivetError)(
2530
+ throw new (0, _chunk2JSYYH6Pcjs.RivetError)(
1765
2531
  "runtime",
1766
2532
  "unsupported",
1767
2533
  `Unsupported wasm runtime method: ${method2}`,
@@ -1792,10 +2558,10 @@ function childHandle(handle, name) {
1792
2558
  }
1793
2559
  var WasmCoreRuntime = (_class2 = class {
1794
2560
  __init2() {this.kind = "wasm"}
1795
- #bindings;
2561
+ #constructors;
1796
2562
  #sql = /* @__PURE__ */ new WeakMap();
1797
2563
  constructor(bindings) {;_class2.prototype.__init2.call(this);
1798
- this.#bindings = bindings;
2564
+ this.#constructors = asWasmConstructors(bindings);
1799
2565
  }
1800
2566
  #actorSql(ctx) {
1801
2567
  const wasmCtx = asWasmActorContext(ctx);
@@ -1808,7 +2574,7 @@ var WasmCoreRuntime = (_class2 = class {
1808
2574
  }
1809
2575
  createRegistry() {
1810
2576
  return callWasmSync(
1811
- () => asRegistryHandle2(new this.#bindings.CoreRegistry())
2577
+ () => asRegistryHandle2(new this.#constructors.CoreRegistry())
1812
2578
  );
1813
2579
  }
1814
2580
  registerActor(registry, name, factory) {
@@ -1819,11 +2585,26 @@ var WasmCoreRuntime = (_class2 = class {
1819
2585
  async serveRegistry(registry, config) {
1820
2586
  await callWasm(() => asWasmRegistry(registry).serve(config));
1821
2587
  }
2588
+ async waitRegistryReady() {
2589
+ throw new Error(
2590
+ "registry.startAndWait() is not supported by the WASM runtime"
2591
+ );
2592
+ }
1822
2593
  async shutdownRegistry(registry) {
1823
2594
  await callWasm(() => asWasmRegistry(registry).shutdown());
1824
2595
  }
1825
- async registryDiagnostics() {
1826
- return { mode: "wasm", envoyActiveActorCount: null };
2596
+ async registryHealth() {
2597
+ return {
2598
+ status: 200,
2599
+ headers: { "content-type": "application/json" },
2600
+ body: new TextEncoder().encode(
2601
+ JSON.stringify({
2602
+ status: "ok",
2603
+ runtime: "rivetkit",
2604
+ version: "wasm"
2605
+ })
2606
+ )
2607
+ };
1827
2608
  }
1828
2609
  async handleServerlessRequest(registry, req, onStreamEvent, cancelToken, config) {
1829
2610
  return await callHandleAsync(
@@ -1835,16 +2616,26 @@ var WasmCoreRuntime = (_class2 = class {
1835
2616
  config
1836
2617
  );
1837
2618
  }
2619
+ async serveListener(_registry, _listener, _config) {
2620
+ throw new Error(
2621
+ "registry.listen() is not supported on the wasm runtime; use registry.serve() and mount the handler in your platform's HTTP server instead"
2622
+ );
2623
+ }
2624
+ async serveApplicationListener(_registry, _listener, _config) {
2625
+ throw new Error(
2626
+ "registry.listen() is not supported on the wasm runtime; use an application-owned HTTP server instead"
2627
+ );
2628
+ }
1838
2629
  createActorFactory(callbacks, config) {
1839
2630
  return callWasmSync(
1840
2631
  () => asActorFactoryHandle2(
1841
- new this.#bindings.ActorFactory(callbacks, config)
2632
+ new this.#constructors.ActorFactory(callbacks, config)
1842
2633
  )
1843
2634
  );
1844
2635
  }
1845
2636
  createCancellationToken() {
1846
2637
  return callWasmSync(
1847
- () => new this.#bindings.CancellationToken()
2638
+ () => new this.#constructors.CancellationToken()
1848
2639
  );
1849
2640
  }
1850
2641
  cancellationTokenAborted(token) {
@@ -1879,6 +2670,13 @@ var WasmCoreRuntime = (_class2 = class {
1879
2670
  optionalWasmNumber(timestampMs)
1880
2671
  );
1881
2672
  }
2673
+ async actorSetRunWakeAt(ctx, timestampMs) {
2674
+ await callHandleAsync(
2675
+ asWasmActorContext(ctx),
2676
+ "setRunWakeAt",
2677
+ optionalWasmNumber(timestampMs)
2678
+ );
2679
+ }
1882
2680
  actorRequestSave(ctx, opts) {
1883
2681
  callHandle(asWasmActorContext(ctx), "requestSave", opts);
1884
2682
  }
@@ -1934,6 +2732,13 @@ var WasmCoreRuntime = (_class2 = class {
1934
2732
  async actorSaveState(ctx, payload) {
1935
2733
  await callHandleAsync(asWasmActorContext(ctx), "saveState", payload);
1936
2734
  }
2735
+ async actorSaveStateAndWorkflowBatch(ctx, writes) {
2736
+ await callHandleAsync(
2737
+ asWasmActorContext(ctx),
2738
+ "saveStateAndWorkflowBatch",
2739
+ writes
2740
+ );
2741
+ }
1937
2742
  actorId(ctx) {
1938
2743
  return callHandle(asWasmActorContext(ctx), "actorId");
1939
2744
  }
@@ -1978,6 +2783,12 @@ var WasmCoreRuntime = (_class2 = class {
1978
2783
  "waitForTrackedShutdownWork"
1979
2784
  );
1980
2785
  }
2786
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
2787
+ await callHandle(
2788
+ asWasmActorContext(ctx),
2789
+ "waitForTrackedShutdownWorkUnbounded"
2790
+ );
2791
+ }
1981
2792
  actorKeepAwake(ctx, promise) {
1982
2793
  const wasmCtx = asWasmActorContext(ctx);
1983
2794
  const regionId = callHandle(wasmCtx, "beginKeepAwake");
@@ -2074,6 +2885,59 @@ var WasmCoreRuntime = (_class2 = class {
2074
2885
  );
2075
2886
  return normalizeRuntimeSqlExecuteResult(result);
2076
2887
  }
2888
+ async actorSqlExecuteBatch(ctx, statements) {
2889
+ const results = await callWasm(
2890
+ () => this.#actorSql(ctx).executeBatch(statements)
2891
+ );
2892
+ return results.map(normalizeRuntimeSqlExecuteResult);
2893
+ }
2894
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
2895
+ return await callWasm(
2896
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs, name)
2897
+ );
2898
+ }
2899
+ async actorSqlTransactionExec(transaction, sql) {
2900
+ return await callWasm(
2901
+ () => transaction.exec(sql)
2902
+ );
2903
+ }
2904
+ async actorSqlTransactionExecute(transaction, sql, params) {
2905
+ const result = await callWasm(
2906
+ () => transaction.execute(sql, params)
2907
+ );
2908
+ return normalizeRuntimeSqlExecuteResult(result);
2909
+ }
2910
+ async actorSqlTransactionCommit(transaction) {
2911
+ await callWasm(
2912
+ () => transaction.commit()
2913
+ );
2914
+ }
2915
+ async actorSqlTransactionRollback(transaction) {
2916
+ await callWasm(
2917
+ () => transaction.rollback()
2918
+ );
2919
+ }
2920
+ async actorBeginStateTransaction(ctx, timeoutMs) {
2921
+ return await callWasm(
2922
+ () => asWasmActorContext(ctx).beginStateTransaction(timeoutMs)
2923
+ );
2924
+ }
2925
+ async actorStateTransactionExecute(transaction, sql, params) {
2926
+ const result = await callWasm(
2927
+ () => transaction.execute(sql, params)
2928
+ );
2929
+ return normalizeRuntimeSqlExecuteResult(result);
2930
+ }
2931
+ async actorStateTransactionCommit(transaction, payload) {
2932
+ await callWasm(
2933
+ () => transaction.commit(payload)
2934
+ );
2935
+ }
2936
+ async actorStateTransactionRollback(transaction) {
2937
+ await callWasm(
2938
+ () => transaction.rollback()
2939
+ );
2940
+ }
2077
2941
  async actorSqlQuery(ctx, sql, params) {
2078
2942
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
2079
2943
  }
@@ -2097,6 +2961,17 @@ var WasmCoreRuntime = (_class2 = class {
2097
2961
  this.#sql.delete(wasmCtx);
2098
2962
  await callWasm(() => database.close());
2099
2963
  }
2964
+ async actorRuntimeSocketProvision(_ctx) {
2965
+ throw new (0, _chunk2JSYYH6Pcjs.RivetError)(
2966
+ "actor_runtime_socket",
2967
+ "unsupported",
2968
+ "Actor Runtime Socket is only available on Unix native runtimes.",
2969
+ {
2970
+ public: true,
2971
+ metadata: { runtime: "wasm" }
2972
+ }
2973
+ );
2974
+ }
2100
2975
  async actorQueueSend(ctx, name, body) {
2101
2976
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2102
2977
  return normalizeQueueMessage(
@@ -2125,9 +3000,25 @@ var WasmCoreRuntime = (_class2 = class {
2125
3000
  )
2126
3001
  );
2127
3002
  }
2128
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
3003
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
2129
3004
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2130
- await callHandleAsync(queue2, "waitForNamesAvailable", names, options);
3005
+ await callHandleAsync(
3006
+ queue2,
3007
+ "waitForNamesAvailable",
3008
+ names,
3009
+ options,
3010
+ signal
3011
+ );
3012
+ }
3013
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
3014
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
3015
+ return await callHandleAsync(
3016
+ queue2,
3017
+ "completePersisted",
3018
+ messageId,
3019
+ expectedName,
3020
+ response
3021
+ );
2131
3022
  }
2132
3023
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
2133
3024
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
@@ -2158,13 +3049,101 @@ var WasmCoreRuntime = (_class2 = class {
2158
3049
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2159
3050
  return await callHandleAsync(queue2, "inspectMessages");
2160
3051
  }
2161
- actorScheduleAfter(ctx, durationMs, actionName, args) {
3052
+ async actorQueueReset(ctx) {
3053
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
3054
+ await callHandleAsync(queue2, "reset");
3055
+ }
3056
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
2162
3057
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2163
- callHandle(schedule, "after", wasmNumber(durationMs), actionName, args);
3058
+ return await callHandleAsync(
3059
+ schedule,
3060
+ "after",
3061
+ wasmNumber(durationMs),
3062
+ actionName,
3063
+ args
3064
+ );
3065
+ }
3066
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
3067
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3068
+ return await callHandleAsync(
3069
+ schedule,
3070
+ "at",
3071
+ wasmNumber(timestampMs),
3072
+ actionName,
3073
+ args
3074
+ );
3075
+ }
3076
+ async actorScheduleCancel(ctx, id) {
3077
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3078
+ return await callHandleAsync(schedule, "cancel", id);
3079
+ }
3080
+ async actorScheduleGet(ctx, id) {
3081
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3082
+ return await callHandleAsync(
3083
+ schedule,
3084
+ "get",
3085
+ id
3086
+ );
3087
+ }
3088
+ async actorScheduleList(ctx) {
3089
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3090
+ return await callHandleAsync(
3091
+ schedule,
3092
+ "list"
3093
+ );
3094
+ }
3095
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
3096
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3097
+ await callHandleAsync(
3098
+ schedule,
3099
+ "cronSet",
3100
+ name,
3101
+ expression,
3102
+ timezone,
3103
+ actionName,
3104
+ args,
3105
+ maxHistory
3106
+ );
3107
+ }
3108
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
3109
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3110
+ await callHandleAsync(
3111
+ schedule,
3112
+ "cronEvery",
3113
+ name,
3114
+ intervalMs,
3115
+ actionName,
3116
+ args,
3117
+ maxHistory
3118
+ );
3119
+ }
3120
+ async actorCronGet(ctx, name) {
3121
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3122
+ return await callHandleAsync(
3123
+ schedule,
3124
+ "cronGet",
3125
+ name
3126
+ );
3127
+ }
3128
+ async actorCronList(ctx) {
3129
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3130
+ return await callHandleAsync(
3131
+ schedule,
3132
+ "cronList"
3133
+ );
3134
+ }
3135
+ async actorCronDelete(ctx, name) {
3136
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
3137
+ return await callHandleAsync(schedule, "cronDelete", name);
2164
3138
  }
2165
- actorScheduleAt(ctx, timestampMs, actionName, args) {
3139
+ async actorCronHistory(ctx, name, limit) {
2166
3140
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2167
- callHandle(schedule, "at", wasmNumber(timestampMs), actionName, args);
3141
+ return await callHandleAsync(
3142
+ schedule,
3143
+ "cronHistory",
3144
+ name,
3145
+ limit
3146
+ );
2168
3147
  }
2169
3148
  connId(conn) {
2170
3149
  return callHandle(asWasmConn(conn), "id");
@@ -2219,6 +3198,106 @@ async function loadWasmRuntime(config) {
2219
3198
  };
2220
3199
  }
2221
3200
 
3201
+ // src/registry/write-through-proxy.ts
3202
+ var _onchange = require('@rivetkit/on-change'); var _onchange2 = _interopRequireDefault(_onchange);
3203
+ function createWriteThroughProxy(value, commit, beforeChange) {
3204
+ if (!value || typeof value !== "object") {
3205
+ return value;
3206
+ }
3207
+ return _onchange2.default.call(void 0,
3208
+ value,
3209
+ () => {
3210
+ commit(value);
3211
+ },
3212
+ {
3213
+ // Rejection is throw-based: beforeChange throws to prevent the
3214
+ // mutation. We always return true so on-change applies the change
3215
+ // if beforeChange did not throw.
3216
+ onValidate(_path, newValue) {
3217
+ beforeChange == null ? void 0 : beforeChange(newValue);
3218
+ return true;
3219
+ }
3220
+ }
3221
+ );
3222
+ }
3223
+ function unwrapProxy(value) {
3224
+ let current = value;
3225
+ while (current !== null && typeof current === "object") {
3226
+ const target = _onchange2.default.target(current);
3227
+ if (target === current) {
3228
+ break;
3229
+ }
3230
+ current = target;
3231
+ }
3232
+ return current;
3233
+ }
3234
+ function isPlainObject(value) {
3235
+ const proto = Object.getPrototypeOf(value);
3236
+ return proto === Object.prototype || proto === null;
3237
+ }
3238
+ function unwrapDeep(value, seen) {
3239
+ const unwrapped = unwrapProxy(value);
3240
+ if (!unwrapped || typeof unwrapped !== "object") {
3241
+ return unwrapped;
3242
+ }
3243
+ if (seen.has(unwrapped)) {
3244
+ return unwrapped;
3245
+ }
3246
+ seen.add(unwrapped);
3247
+ if (Array.isArray(unwrapped)) {
3248
+ for (let i = 0; i < unwrapped.length; i++) {
3249
+ const child = unwrapDeep(unwrapped[i], seen);
3250
+ if (child !== unwrapped[i]) {
3251
+ unwrapped[i] = child;
3252
+ }
3253
+ }
3254
+ return unwrapped;
3255
+ }
3256
+ if (unwrapped instanceof Map) {
3257
+ const replacements = [];
3258
+ for (const [key, child] of unwrapped.entries()) {
3259
+ const nextKey = unwrapDeep(key, seen);
3260
+ const nextChild = unwrapDeep(child, seen);
3261
+ if (nextKey !== key || nextChild !== child) {
3262
+ replacements.push([key, nextKey, nextChild]);
3263
+ }
3264
+ }
3265
+ for (const [key, nextKey, nextChild] of replacements) {
3266
+ if (nextKey !== key) {
3267
+ unwrapped.delete(key);
3268
+ }
3269
+ unwrapped.set(nextKey, nextChild);
3270
+ }
3271
+ return unwrapped;
3272
+ }
3273
+ if (unwrapped instanceof Set) {
3274
+ const replacements = [];
3275
+ for (const child of unwrapped.values()) {
3276
+ const next = unwrapDeep(child, seen);
3277
+ if (next !== child) {
3278
+ replacements.push([child, next]);
3279
+ }
3280
+ }
3281
+ for (const [child, next] of replacements) {
3282
+ unwrapped.delete(child);
3283
+ unwrapped.add(next);
3284
+ }
3285
+ return unwrapped;
3286
+ }
3287
+ if (isPlainObject(unwrapped)) {
3288
+ for (const key of Object.keys(unwrapped)) {
3289
+ const child = unwrapDeep(unwrapped[key], seen);
3290
+ if (child !== unwrapped[key]) {
3291
+ unwrapped[key] = child;
3292
+ }
3293
+ }
3294
+ }
3295
+ return unwrapped;
3296
+ }
3297
+ function unwrapWriteThroughProxy(value) {
3298
+ return unwrapDeep(value, /* @__PURE__ */ new Set());
3299
+ }
3300
+
2222
3301
  // src/registry/native.ts
2223
3302
  var textEncoder = new TextEncoder();
2224
3303
  var textDecoder = new TextDecoder();
@@ -2231,7 +3310,7 @@ function trySetProcessEnv(key, value) {
2231
3310
  if (typeof process === "undefined") return;
2232
3311
  try {
2233
3312
  process.env[key] = value;
2234
- } catch (e) {
3313
+ } catch (e3) {
2235
3314
  }
2236
3315
  }
2237
3316
  function detectRuntimeHost() {
@@ -2252,7 +3331,7 @@ function loadedRuntimeKind(runtime) {
2252
3331
  case "wasm":
2253
3332
  return "wasm";
2254
3333
  }
2255
- throw new (0, _chunkQAZLM4WTcjs.RivetError)(
3334
+ throw new (0, _chunk2JSYYH6Pcjs.RivetError)(
2256
3335
  "config",
2257
3336
  "unknown_runtime",
2258
3337
  "RivetKit runtime must be NAPI or wasm.",
@@ -2266,10 +3345,28 @@ async function loadAutoRuntime(config, loaders = defaultRuntimeLoaders) {
2266
3345
  if (loaders.detectHost() === "edge-like") {
2267
3346
  return (await loaders.loadWasm(config.wasm)).runtime;
2268
3347
  }
3348
+ let nativeError;
2269
3349
  try {
2270
3350
  return (await loaders.loadNative()).runtime;
2271
- } catch (e2) {
3351
+ } catch (error) {
3352
+ nativeError = error;
3353
+ logger2().warn({
3354
+ msg: "native runtime failed to load; falling back to wasm",
3355
+ error: _chunkEHZH3KUWcjs.stringifyError.call(void 0, error)
3356
+ });
3357
+ }
3358
+ try {
2272
3359
  return (await loaders.loadWasm(config.wasm)).runtime;
3360
+ } catch (wasmError) {
3361
+ throw new (0, _chunk2JSYYH6Pcjs.RivetError)(
3362
+ "config",
3363
+ "runtime_unavailable",
3364
+ `RivetKit could not load a core runtime. Native runtime: ${_chunkEHZH3KUWcjs.stringifyError.call(void 0, nativeError)} Wasm runtime: ${_chunkEHZH3KUWcjs.stringifyError.call(void 0, wasmError)}`,
3365
+ {
3366
+ public: true,
3367
+ statusCode: 500
3368
+ }
3369
+ );
2273
3370
  }
2274
3371
  }
2275
3372
  async function loadConfiguredRuntime(config, loaders = defaultRuntimeLoaders) {
@@ -2292,7 +3389,7 @@ function normalizeRuntimeConfigForKind(config, runtimeKind) {
2292
3389
  return config;
2293
3390
  }
2294
3391
  if (sqliteBackendForConfig(config) === "local") {
2295
- throw new (0, _chunkQAZLM4WTcjs.RivetError)(
3392
+ throw new (0, _chunk2JSYYH6Pcjs.RivetError)(
2296
3393
  "config",
2297
3394
  "wasm_local_sqlite",
2298
3395
  "WebAssembly runtime cannot use local SQLite. Use remote SQLite instead.",
@@ -2358,22 +3455,46 @@ function getNativeConnPersistState(runtime, ctx, conn) {
2358
3455
  return connState;
2359
3456
  }
2360
3457
  function stateMutationReentrantError() {
2361
- return new (0, _chunkQAZLM4WTcjs.RivetError)(
3458
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)(
2362
3459
  "actor",
2363
3460
  "state_mutation_reentrant",
2364
3461
  "State mutations are not allowed inside onStateChange."
2365
3462
  );
2366
3463
  }
3464
+ function stateTransactionConflictError() {
3465
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)(
3466
+ "actor",
3467
+ "state_transaction_conflict",
3468
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
3469
+ { public: true, statusCode: 409 }
3470
+ );
3471
+ }
2367
3472
  function databaseNotConfiguredError() {
2368
- return new (0, _chunkQAZLM4WTcjs.RivetError)(
3473
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)(
2369
3474
  "actor",
2370
3475
  "database_not_configured",
2371
3476
  "database is not configured for this actor",
2372
3477
  { public: true }
2373
3478
  );
2374
3479
  }
3480
+ function databaseClientNotReadyError() {
3481
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)(
3482
+ "actor",
3483
+ "database_client_not_ready",
3484
+ "actor database client was not initialized before user code ran. this is an internal lifecycle error; the migration callback should have pre-warmed the client. file an issue if you can reproduce.",
3485
+ { public: true }
3486
+ );
3487
+ }
3488
+ function runHandlerNotConfiguredError() {
3489
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)(
3490
+ "actor",
3491
+ "run_handler_unavailable",
3492
+ "Cannot schedule a run wake because this actor does not define a run handler.",
3493
+ { public: true, statusCode: 409 }
3494
+ );
3495
+ }
2375
3496
  function stateNotEnabledError() {
2376
- return new (0, _chunkQAZLM4WTcjs.RivetError)(
3497
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)(
2377
3498
  "actor",
2378
3499
  "state_not_enabled",
2379
3500
  "State not enabled. Must implement `createState` or `state` to use state. (https://www.rivet.dev/docs/actors/state/#initializing-state)",
@@ -2381,7 +3502,7 @@ function stateNotEnabledError() {
2381
3502
  );
2382
3503
  }
2383
3504
  function nativeClientNotConfiguredError() {
2384
- return new (0, _chunkQAZLM4WTcjs.RivetError)(
3505
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)(
2385
3506
  "native",
2386
3507
  "client_not_configured",
2387
3508
  "native actor client is not configured",
@@ -2389,7 +3510,7 @@ function nativeClientNotConfiguredError() {
2389
3510
  );
2390
3511
  }
2391
3512
  function nativeEndpointNotConfiguredError() {
2392
- return new (0, _chunkQAZLM4WTcjs.RivetError)(
3513
+ return new (0, _chunk2JSYYH6Pcjs.RivetError)(
2393
3514
  "native",
2394
3515
  "endpoint_not_configured",
2395
3516
  "registry endpoint is required for native envoy startup",
@@ -2423,8 +3544,23 @@ function resolveNativeDestroy(runtime, ctx) {
2423
3544
  function clearNativeRuntimeState(runtime, ctx) {
2424
3545
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
2425
3546
  }
2426
- async function cleanupNativeSleepRuntimeState(runtime, ctx) {
2427
- await runtime.actorWaitForTrackedShutdownWork(ctx);
3547
+ async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrained) {
3548
+ const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
3549
+ if (!drained) {
3550
+ await closeNativeDatabaseClient(runtime, ctx);
3551
+ await closeNativeSqlDatabase(runtime, ctx);
3552
+ void runtime.actorWaitForTrackedShutdownWorkUnbounded(ctx).then(async () => {
3553
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
3554
+ clearNativeRuntimeState(runtime, ctx);
3555
+ }).catch((error) => {
3556
+ logger2().warn({
3557
+ msg: "deferred native sleep cleanup failed",
3558
+ error: _chunkEHZH3KUWcjs.stringifyError.call(void 0, error)
3559
+ });
3560
+ });
3561
+ return;
3562
+ }
3563
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
2428
3564
  await closeNativeDatabaseClient(runtime, ctx);
2429
3565
  await closeNativeSqlDatabase(runtime, ctx);
2430
3566
  clearNativeRuntimeState(runtime, ctx);
@@ -2458,6 +3594,56 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
2458
3594
  const database = wrapJsNativeDatabase({
2459
3595
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
2460
3596
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
3597
+ executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
3598
+ beginTransaction: async (timeoutMs, name) => {
3599
+ const transaction = await runtime.actorSqlBeginTransaction(
3600
+ ctx,
3601
+ timeoutMs,
3602
+ name
3603
+ );
3604
+ return {
3605
+ exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
3606
+ execute: (sql, params) => runtime.actorSqlTransactionExecute(
3607
+ transaction,
3608
+ sql,
3609
+ params
3610
+ ),
3611
+ commit: () => runtime.actorSqlTransactionCommit(transaction),
3612
+ rollback: () => runtime.actorSqlTransactionRollback(transaction)
3613
+ };
3614
+ },
3615
+ beginStateTransaction: async (timeoutMs, context) => {
3616
+ const scope = context;
3617
+ if (!scope) {
3618
+ throw new Error(
3619
+ "actor state transaction context is not configured"
3620
+ );
3621
+ }
3622
+ const transaction = await runtime.actorBeginStateTransaction(
3623
+ ctx,
3624
+ timeoutMs
3625
+ );
3626
+ return {
3627
+ exec: async () => {
3628
+ throw new Error(
3629
+ "actor state transactions only support single-statement execute calls"
3630
+ );
3631
+ },
3632
+ execute: (sql, params) => runtime.actorStateTransactionExecute(
3633
+ transaction,
3634
+ sql,
3635
+ params
3636
+ ),
3637
+ commit: async () => {
3638
+ await runtime.actorStateTransactionCommit(
3639
+ transaction,
3640
+ scope.actorContext.serializeForTick("save")
3641
+ );
3642
+ scope.committed = true;
3643
+ },
3644
+ rollback: () => runtime.actorStateTransactionRollback(transaction)
3645
+ };
3646
+ },
2461
3647
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
2462
3648
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
2463
3649
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -2479,7 +3665,7 @@ function toRuntimeBytes(value) {
2479
3665
  function arrayBufferViewToRuntimeBytes(value) {
2480
3666
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
2481
3667
  }
2482
- function runtimeBytesToArrayBuffer(value) {
3668
+ function runtimeBytesToArrayBuffer2(value) {
2483
3669
  return value.buffer.slice(
2484
3670
  value.byteOffset,
2485
3671
  value.byteOffset + value.byteLength
@@ -2525,14 +3711,20 @@ function decodeNativeKvValue(value, options) {
2525
3711
  async function loadEngineCli() {
2526
3712
  return Promise.resolve().then(() => _interopRequireWildcard(require(["@rivetkit", "engine-cli"].join("/"))));
2527
3713
  }
3714
+ async function loadServices() {
3715
+ return Promise.resolve().then(() => _interopRequireWildcard(require(["@rivet-dev", "services"].join("/"))));
3716
+ }
2528
3717
  function decodeValue(value) {
2529
3718
  if (!value || value.length === 0) {
2530
3719
  return void 0;
2531
3720
  }
2532
- return _chunkNDY6IZJ3cjs.decodeCborJsonCompat.call(void 0, value);
3721
+ return _chunkEHZH3KUWcjs.decodeCborCompat.call(void 0, value);
2533
3722
  }
2534
3723
  function encodeValue(value) {
2535
- return _chunkNDY6IZJ3cjs.encodeCborCompat.call(void 0, value);
3724
+ return _chunkEHZH3KUWcjs.encodeCborCompat.call(void 0, value);
3725
+ }
3726
+ function normalizeArgs(value) {
3727
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
2536
3728
  }
2537
3729
  function unwrapTsfnPayload(error, payload) {
2538
3730
  if (error !== null && error !== void 0) {
@@ -2542,16 +3734,16 @@ function unwrapTsfnPayload(error, payload) {
2542
3734
  }
2543
3735
  function normalizeNativeBridgeError(error) {
2544
3736
  if (typeof error === "string") {
2545
- return _nullishCoalesce(_chunkQAZLM4WTcjs.decodeBridgeRivetError.call(void 0, error), () => ( error));
3737
+ return _nullishCoalesce(_chunk2JSYYH6Pcjs.decodeBridgeRivetError.call(void 0, error), () => ( error));
2546
3738
  }
2547
3739
  if (error instanceof Error) {
2548
- const bridged = _chunkQAZLM4WTcjs.decodeBridgeRivetError.call(void 0, error.message);
3740
+ const bridged = _chunk2JSYYH6Pcjs.decodeBridgeRivetError.call(void 0, error.message);
2549
3741
  if (bridged) {
2550
3742
  return bridged;
2551
3743
  }
2552
3744
  }
2553
3745
  if (typeof error === "object" && error !== null && "reason" in error && typeof error.reason === "string") {
2554
- const bridged = _chunkQAZLM4WTcjs.decodeBridgeRivetError.call(void 0, error.reason);
3746
+ const bridged = _chunk2JSYYH6Pcjs.decodeBridgeRivetError.call(void 0, error.reason);
2555
3747
  if (bridged) {
2556
3748
  return bridged;
2557
3749
  }
@@ -2559,20 +3751,21 @@ function normalizeNativeBridgeError(error) {
2559
3751
  return error;
2560
3752
  }
2561
3753
  function isStructuredBridgeError(error) {
2562
- if (error instanceof _chunkQAZLM4WTcjs.RivetError) {
3754
+ if (error instanceof _chunk2JSYYH6Pcjs.RivetError) {
2563
3755
  return true;
2564
3756
  }
2565
- return _chunkQAZLM4WTcjs.isRivetErrorLike.call(void 0, error) && "__type" in error && (error.__type === "RivetError" || error.__type === "ActorError");
3757
+ return _chunk2JSYYH6Pcjs.isRivetErrorLike.call(void 0, error) && "__type" in error && (error.__type === "RivetError" || error.__type === "ActorError");
2566
3758
  }
2567
3759
  function encodeNativeCallbackError(error) {
2568
- const structuredError = isStructuredBridgeError(error) ? error : _chunkO25KOT5Ccjs.deconstructError.call(void 0, error, true);
2569
- const bridgeError = new Error(_chunkQAZLM4WTcjs.encodeBridgeRivetError.call(void 0, structuredError), {
3760
+ const structuredError = isStructuredBridgeError(error) ? error : _chunkEHZH3KUWcjs.deconstructError.call(void 0, error, true);
3761
+ const bridgeError = new Error(_chunk2JSYYH6Pcjs.encodeBridgeRivetError.call(void 0, structuredError), {
2570
3762
  cause: error instanceof Error ? error : void 0
2571
3763
  });
2572
3764
  return Object.assign(bridgeError, {
2573
3765
  group: structuredError.group,
2574
3766
  code: structuredError.code,
2575
- metadata: structuredError.metadata
3767
+ metadata: structuredError.metadata,
3768
+ rayId: structuredError.rayId
2576
3769
  });
2577
3770
  }
2578
3771
  async function callNative(invoke) {
@@ -2589,16 +3782,10 @@ function callNativeSync(invoke) {
2589
3782
  throw normalizeNativeBridgeError(error);
2590
3783
  }
2591
3784
  }
2592
- function actorAbortedError() {
2593
- return Object.assign(new Error("Actor aborted"), {
2594
- group: "actor",
2595
- code: "aborted"
2596
- });
2597
- }
2598
3785
  function isClosedTaskRegistrationError(error) {
2599
- const metadata = error instanceof _chunkQAZLM4WTcjs.RivetError ? error.metadata : void 0;
3786
+ const metadata = error instanceof _chunk2JSYYH6Pcjs.RivetError ? error.metadata : void 0;
2600
3787
  const metadataError = metadata && typeof metadata === "object" && "error" in metadata ? metadata.error : void 0;
2601
- return error instanceof _chunkQAZLM4WTcjs.RivetError && error.group === "core" && error.code === _chunkQAZLM4WTcjs.INTERNAL_ERROR_CODE && typeof metadataError === "string" && /actor task registration is (closed|not configured)/.test(metadataError);
3788
+ return error instanceof _chunk2JSYYH6Pcjs.RivetError && error.group === "core" && error.code === _chunk2JSYYH6Pcjs.INTERNAL_ERROR_CODE && typeof metadataError === "string" && /actor task registration is (closed|not configured)/.test(metadataError);
2602
3789
  }
2603
3790
  async function createCancellationTokenHandle(runtime, signal) {
2604
3791
  if (!signal) {
@@ -2621,8 +3808,8 @@ function decodeWorkflowCbor(data) {
2621
3808
  return null;
2622
3809
  }
2623
3810
  try {
2624
- return _chunkNDY6IZJ3cjs.decodeCborCompat.call(void 0, new Uint8Array(data));
2625
- } catch (e3) {
3811
+ return _chunkEHZH3KUWcjs.decodeCborCompat.call(void 0, new Uint8Array(data));
3812
+ } catch (e4) {
2626
3813
  return null;
2627
3814
  }
2628
3815
  }
@@ -2720,14 +3907,22 @@ function serializeWorkflowEntryKind(kind) {
2720
3907
  originalName: kind.val.originalName
2721
3908
  }
2722
3909
  };
3910
+ case "WorkflowVersionCheckEntry":
3911
+ return {
3912
+ tag: kind.tag,
3913
+ val: {
3914
+ resolved: kind.val.resolved,
3915
+ latest: kind.val.latest
3916
+ }
3917
+ };
2723
3918
  }
2724
3919
  }
2725
3920
  function serializeWorkflowHistoryForJson(data) {
2726
3921
  if (data === null) {
2727
3922
  return null;
2728
3923
  }
2729
- const history = _chunk5DGOZZKEcjs.decodeWorkflowHistoryTransport.call(void 0, data);
2730
- return {
3924
+ const history = _chunkQ6BQS3ULcjs.decodeWorkflowHistoryTransport.call(void 0, data);
3925
+ return jsonSafe({
2731
3926
  nameRegistry: [...history.nameRegistry],
2732
3927
  entries: history.entries.map((entry) => ({
2733
3928
  id: entry.id,
@@ -2751,7 +3946,7 @@ function serializeWorkflowHistoryForJson(data) {
2751
3946
  ]
2752
3947
  )
2753
3948
  )
2754
- };
3949
+ });
2755
3950
  }
2756
3951
  function toHttpJsonCompatible(value) {
2757
3952
  return JSON.parse(
@@ -2802,63 +3997,7 @@ function wrapNativeCallback(callback) {
2802
3997
  }
2803
3998
  function decodeArgs(value) {
2804
3999
  const decoded = decodeValue(value);
2805
- return Array.isArray(decoded) ? decoded : decoded === void 0 ? [] : [decoded];
2806
- }
2807
- function createWriteThroughProxy(value, commit, beforeChange) {
2808
- if (!value || typeof value !== "object") {
2809
- return value;
2810
- }
2811
- const proxies = /* @__PURE__ */ new WeakMap();
2812
- const wrap = (target) => {
2813
- const cached = proxies.get(target);
2814
- if (cached) {
2815
- return cached;
2816
- }
2817
- const proxy = new Proxy(target, {
2818
- get(innerTarget, property, receiver) {
2819
- const result = Reflect.get(innerTarget, property, receiver);
2820
- return result && typeof result === "object" ? wrap(result) : result;
2821
- },
2822
- set(innerTarget, property, nextValue, receiver) {
2823
- beforeChange == null ? void 0 : beforeChange();
2824
- const updated = Reflect.set(
2825
- innerTarget,
2826
- property,
2827
- nextValue,
2828
- receiver
2829
- );
2830
- commit(value);
2831
- return updated;
2832
- },
2833
- deleteProperty(innerTarget, property) {
2834
- beforeChange == null ? void 0 : beforeChange();
2835
- const updated = Reflect.deleteProperty(innerTarget, property);
2836
- commit(value);
2837
- return updated;
2838
- }
2839
- });
2840
- proxies.set(target, proxy);
2841
- return proxy;
2842
- };
2843
- return wrap(value);
2844
- }
2845
- function buildRequest(init) {
2846
- const url = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
2847
- const body = init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
2848
- return new Request(url, {
2849
- method: init.method,
2850
- headers: init.headers,
2851
- body
2852
- });
2853
- }
2854
- async function toRuntimeHttpResponse(response) {
2855
- const headers = Object.fromEntries(response.headers.entries());
2856
- const body = new Uint8Array(await response.arrayBuffer());
2857
- return {
2858
- status: response.status,
2859
- headers,
2860
- body
2861
- };
4000
+ return normalizeArgs(decoded);
2862
4001
  }
2863
4002
  function toActorKey(segments) {
2864
4003
  return segments.map(
@@ -2871,13 +4010,17 @@ var NativeConnAdapter = class {
2871
4010
  #schemas;
2872
4011
  #ctx;
2873
4012
  #queueHibernationRemoval;
2874
- constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval) {
4013
+ #assertCanMutateState;
4014
+ #stateProxy;
4015
+ #stateProxyTarget;
4016
+ constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval, assertCanMutateState) {
2875
4017
  this.#runtime = runtime;
2876
4018
  this.#conn = conn;
2877
4019
  this.#schemas = schemas;
2878
4020
  this.#ctx = ctx;
2879
4021
  this.#queueHibernationRemoval = queueHibernationRemoval;
2880
- this[_chunkWQ4HNA4Wcjs.CONN_STATE_MANAGER_SYMBOL] = {
4022
+ this.#assertCanMutateState = assertCanMutateState;
4023
+ this[_chunk4KGXFC6Mcjs.CONN_STATE_MANAGER_SYMBOL] = {
2881
4024
  stateEnabled: true,
2882
4025
  get state() {
2883
4026
  return thisConn.state;
@@ -2894,17 +4037,51 @@ var NativeConnAdapter = class {
2894
4037
  decodeValue(this.#runtime.connParams(this.#conn))
2895
4038
  );
2896
4039
  }
4040
+ [_chunk4KGXFC6Mcjs.RAW_STATE_SYMBOL]() {
4041
+ return this.#readState();
4042
+ }
2897
4043
  get state() {
2898
4044
  const nextState = this.#readState();
2899
- return createWriteThroughProxy(nextState, (nextValue) => {
2900
- this.#writeState(nextValue, { writeNative: true });
2901
- });
4045
+ if (!this.#ctx) {
4046
+ return this.#createStateProxy(nextState);
4047
+ }
4048
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
4049
+ this.#stateProxyTarget = nextState;
4050
+ this.#stateProxy = this.#createStateProxy(nextState);
4051
+ }
4052
+ return this.#stateProxy;
4053
+ }
4054
+ #createStateProxy(state) {
4055
+ const assertCurrentState = () => {
4056
+ var _a;
4057
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
4058
+ if (this.#ctx && this.#readState() !== state) {
4059
+ throw stateTransactionConflictError();
4060
+ }
4061
+ };
4062
+ return createWriteThroughProxy(
4063
+ state,
4064
+ (nextValue) => {
4065
+ assertCurrentState();
4066
+ this.#writeState(nextValue, { writeNative: true });
4067
+ },
4068
+ (newValue) => {
4069
+ assertCurrentState();
4070
+ _chunkEHZH3KUWcjs.assertJsonCompatValue.call(void 0, newValue);
4071
+ }
4072
+ );
2902
4073
  }
2903
4074
  set state(value) {
2904
- this.#writeState(value, { writeNative: true });
4075
+ var _a;
4076
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
4077
+ const nextValue = unwrapWriteThroughProxy(value);
4078
+ _chunkEHZH3KUWcjs.assertJsonCompatValue.call(void 0, nextValue);
4079
+ this.#writeState(nextValue, { writeNative: true });
2905
4080
  }
2906
4081
  initializeState(value) {
2907
- this.#writeState(value, { writeNative: false });
4082
+ this.#writeState(unwrapWriteThroughProxy(value), {
4083
+ writeNative: false
4084
+ });
2908
4085
  }
2909
4086
  get isHibernatable() {
2910
4087
  return callNativeSync(
@@ -2973,27 +4150,117 @@ var NativeScheduleAdapter = class {
2973
4150
  this.#runtime = runtime;
2974
4151
  this.#ctx = ctx;
2975
4152
  }
2976
- async after(duration, action, ...args) {
2977
- callNativeSync(
2978
- () => this.#runtime.actorScheduleAfter(
2979
- this.#ctx,
2980
- duration,
2981
- action,
2982
- encodeValue(args)
2983
- )
4153
+ async after(duration, action, ...args) {
4154
+ return await this.#runtime.actorScheduleAfter(
4155
+ this.#ctx,
4156
+ duration,
4157
+ action,
4158
+ encodeValue(args)
4159
+ );
4160
+ }
4161
+ async at(timestamp, action, ...args) {
4162
+ return await this.#runtime.actorScheduleAt(
4163
+ this.#ctx,
4164
+ timestamp,
4165
+ action,
4166
+ encodeValue(args)
4167
+ );
4168
+ }
4169
+ async cancel(id) {
4170
+ return await this.#runtime.actorScheduleCancel(this.#ctx, id);
4171
+ }
4172
+ async get(id) {
4173
+ const event2 = await this.#runtime.actorScheduleGet(this.#ctx, id);
4174
+ return event2 ? decodeScheduledEventInfo(event2) : void 0;
4175
+ }
4176
+ async list() {
4177
+ return (await this.#runtime.actorScheduleList(this.#ctx)).map(
4178
+ decodeScheduledEventInfo
4179
+ );
4180
+ }
4181
+ };
4182
+ var NativeCronAdapter = class {
4183
+ #runtime;
4184
+ #ctx;
4185
+ constructor(runtime, ctx) {
4186
+ this.#runtime = runtime;
4187
+ this.#ctx = ctx;
4188
+ }
4189
+ async set(options) {
4190
+ await this.#runtime.actorCronSet(
4191
+ this.#ctx,
4192
+ options.name,
4193
+ options.expression,
4194
+ options.timezone,
4195
+ options.action,
4196
+ encodeValue(_nullishCoalesce(options.args, () => ( []))),
4197
+ options.maxHistory
4198
+ );
4199
+ }
4200
+ async every(options) {
4201
+ await this.#runtime.actorCronEvery(
4202
+ this.#ctx,
4203
+ options.name,
4204
+ options.interval,
4205
+ options.action,
4206
+ encodeValue(_nullishCoalesce(options.args, () => ( []))),
4207
+ options.maxHistory
2984
4208
  );
2985
4209
  }
2986
- async at(timestamp, action, ...args) {
2987
- callNativeSync(
2988
- () => this.#runtime.actorScheduleAt(
2989
- this.#ctx,
2990
- timestamp,
2991
- action,
2992
- encodeValue(args)
2993
- )
4210
+ async get(name) {
4211
+ const job = await this.#runtime.actorCronGet(this.#ctx, name);
4212
+ return job ? decodeCronJobInfo(job) : void 0;
4213
+ }
4214
+ async list() {
4215
+ return (await this.#runtime.actorCronList(this.#ctx)).map(
4216
+ decodeCronJobInfo
2994
4217
  );
2995
4218
  }
4219
+ async delete(name) {
4220
+ return await this.#runtime.actorCronDelete(this.#ctx, name);
4221
+ }
4222
+ async history(name, options) {
4223
+ return (await this.#runtime.actorCronHistory(
4224
+ this.#ctx,
4225
+ name,
4226
+ options == null ? void 0 : options.limit
4227
+ )).map(decodeCronFire);
4228
+ }
2996
4229
  };
4230
+ function decodeScheduledEventInfo(event2) {
4231
+ return {
4232
+ id: event2.id,
4233
+ action: event2.action,
4234
+ args: decodeArgs(event2.args),
4235
+ runAt: event2.runAt
4236
+ };
4237
+ }
4238
+ function decodeCronJobInfo(job) {
4239
+ const base = {
4240
+ name: job.name,
4241
+ action: job.action,
4242
+ args: decodeArgs(job.args),
4243
+ nextRunAt: job.nextRunAt,
4244
+ lastRunAt: job.lastRunAt,
4245
+ maxHistory: job.maxHistory
4246
+ };
4247
+ if (job.kind === "cron") {
4248
+ return {
4249
+ ...base,
4250
+ kind: "cron",
4251
+ expression: job.expression,
4252
+ timezone: job.timezone
4253
+ };
4254
+ }
4255
+ return {
4256
+ ...base,
4257
+ kind: "every",
4258
+ interval: job.intervalMs
4259
+ };
4260
+ }
4261
+ function decodeCronFire(fire) {
4262
+ return { ...fire };
4263
+ }
2997
4264
  var NativeKvAdapter = class {
2998
4265
  #runtime;
2999
4266
  #ctx;
@@ -3005,7 +4272,7 @@ var NativeKvAdapter = class {
3005
4272
  const value = await callNative(
3006
4273
  () => this.#runtime.actorKvGet(
3007
4274
  this.#ctx,
3008
- _chunkLD5YASJUcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(key))
4275
+ _chunkMYWZCDMLcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(key))
3009
4276
  )
3010
4277
  );
3011
4278
  return value ? decodeNativeKvValue(new Uint8Array(value), options) : null;
@@ -3014,7 +4281,7 @@ var NativeKvAdapter = class {
3014
4281
  await callNative(
3015
4282
  () => this.#runtime.actorKvPut(
3016
4283
  this.#ctx,
3017
- _chunkLD5YASJUcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(key)),
4284
+ _chunkMYWZCDMLcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(key)),
3018
4285
  toRuntimeBytes(value)
3019
4286
  )
3020
4287
  );
@@ -3023,7 +4290,7 @@ var NativeKvAdapter = class {
3023
4290
  await callNative(
3024
4291
  () => this.#runtime.actorKvDelete(
3025
4292
  this.#ctx,
3026
- _chunkLD5YASJUcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(key))
4293
+ _chunkMYWZCDMLcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(key))
3027
4294
  )
3028
4295
  );
3029
4296
  }
@@ -3031,8 +4298,8 @@ var NativeKvAdapter = class {
3031
4298
  await callNative(
3032
4299
  () => this.#runtime.actorKvDeleteRange(
3033
4300
  this.#ctx,
3034
- _chunkLD5YASJUcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(start)),
3035
- _chunkLD5YASJUcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(end))
4301
+ _chunkMYWZCDMLcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(start)),
4302
+ _chunkMYWZCDMLcjs.makePrefixedKey.call(void 0, encodeNativeKvUserKey(end))
3036
4303
  )
3037
4304
  );
3038
4305
  }
@@ -3045,7 +4312,7 @@ var NativeKvAdapter = class {
3045
4312
  const entries = await callNative(
3046
4313
  () => this.#runtime.actorKvListPrefix(
3047
4314
  this.#ctx,
3048
- _chunkLD5YASJUcjs.makePrefixedKey.call(void 0,
4315
+ _chunkMYWZCDMLcjs.makePrefixedKey.call(void 0,
3049
4316
  encodeNativeKvUserKey(
3050
4317
  prefix,
3051
4318
  options == null ? void 0 : options.keyType
@@ -3059,7 +4326,7 @@ var NativeKvAdapter = class {
3059
4326
  );
3060
4327
  return entries.map((entry) => [
3061
4328
  decodeNativeKvKey(
3062
- _chunkLD5YASJUcjs.removePrefixFromKey.call(void 0, new Uint8Array(entry.key)),
4329
+ _chunkMYWZCDMLcjs.removePrefixFromKey.call(void 0, new Uint8Array(entry.key)),
3063
4330
  options == null ? void 0 : options.keyType
3064
4331
  ),
3065
4332
  decodeNativeKvValue(new Uint8Array(entry.value), options)
@@ -3078,13 +4345,13 @@ var NativeKvAdapter = class {
3078
4345
  const entries = await callNative(
3079
4346
  () => this.#runtime.actorKvListRange(
3080
4347
  this.#ctx,
3081
- _chunkLD5YASJUcjs.makePrefixedKey.call(void 0,
4348
+ _chunkMYWZCDMLcjs.makePrefixedKey.call(void 0,
3082
4349
  encodeNativeKvUserKey(
3083
4350
  start,
3084
4351
  options == null ? void 0 : options.keyType
3085
4352
  )
3086
4353
  ),
3087
- _chunkLD5YASJUcjs.makePrefixedKey.call(void 0,
4354
+ _chunkMYWZCDMLcjs.makePrefixedKey.call(void 0,
3088
4355
  encodeNativeKvUserKey(
3089
4356
  end,
3090
4357
  options == null ? void 0 : options.keyType
@@ -3098,7 +4365,7 @@ var NativeKvAdapter = class {
3098
4365
  );
3099
4366
  return entries.map((entry) => [
3100
4367
  decodeNativeKvKey(
3101
- _chunkLD5YASJUcjs.removePrefixFromKey.call(void 0, new Uint8Array(entry.key)),
4368
+ _chunkMYWZCDMLcjs.removePrefixFromKey.call(void 0, new Uint8Array(entry.key)),
3102
4369
  options == null ? void 0 : options.keyType
3103
4370
  ),
3104
4371
  decodeNativeKvValue(new Uint8Array(entry.value), options)
@@ -3132,8 +4399,9 @@ var NativeKvAdapter = class {
3132
4399
  };
3133
4400
  function wrapQueueMessage(message, schemas) {
3134
4401
  const name = callNativeSync(() => message.name());
4402
+ const id = callNativeSync(() => message.id());
3135
4403
  return {
3136
- id: Number(callNativeSync(() => message.id())),
4404
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
3137
4405
  name,
3138
4406
  body: validateQueueBody(
3139
4407
  schemas,
@@ -3190,7 +4458,7 @@ var NativeQueueAdapter = class {
3190
4458
  async nextBatch(options) {
3191
4459
  const completable = (options == null ? void 0 : options.completable) === true;
3192
4460
  if (this.#pendingCompletableMessageIds.size > 0) {
3193
- throw new (0, _chunkQAZLM4WTcjs.RivetError)(
4461
+ throw new (0, _chunk2JSYYH6Pcjs.RivetError)(
3194
4462
  "queue",
3195
4463
  "previous_message_not_completed",
3196
4464
  "Previous completable queue message is not completed. Call `message.complete(...)` before receiving the next message.",
@@ -3252,46 +4520,44 @@ var NativeQueueAdapter = class {
3252
4520
  }
3253
4521
  }
3254
4522
  async waitForNamesAvailable(names, options) {
3255
- if (!(options == null ? void 0 : options.signal)) {
4523
+ const { token, cleanup } = await createCancellationTokenHandle(
4524
+ this.#runtime,
4525
+ options == null ? void 0 : options.signal
4526
+ );
4527
+ try {
3256
4528
  await callNative(
3257
4529
  () => this.#runtime.actorQueueWaitForNamesAvailable(
3258
4530
  this.#ctx,
3259
4531
  [...names],
3260
4532
  {
3261
4533
  timeoutMs: options == null ? void 0 : options.timeout
3262
- }
4534
+ },
4535
+ token
3263
4536
  )
3264
4537
  );
3265
- return;
3266
- }
3267
- const deadline = options.timeout === void 0 ? void 0 : Date.now() + options.timeout;
3268
- for (; ; ) {
3269
- if (options.signal.aborted) {
3270
- throw actorAbortedError();
3271
- }
3272
- const remainingTimeout = deadline === void 0 ? void 0 : Math.max(0, deadline - Date.now());
3273
- const sliceTimeout = remainingTimeout === void 0 ? 100 : Math.min(remainingTimeout, 100);
3274
- try {
3275
- await callNative(
3276
- () => this.#runtime.actorQueueWaitForNamesAvailable(
3277
- this.#ctx,
3278
- [...names],
3279
- {
3280
- timeoutMs: sliceTimeout
3281
- }
3282
- )
3283
- );
3284
- return;
3285
- } catch (error) {
3286
- if (error.group === "queue" && error.code === "timed_out") {
3287
- if (remainingTimeout === void 0 || remainingTimeout > 100) {
3288
- continue;
3289
- }
3290
- }
3291
- throw error;
3292
- }
4538
+ } finally {
4539
+ cleanup == null ? void 0 : cleanup();
3293
4540
  }
3294
4541
  }
4542
+ async waitForAvailable(names, options) {
4543
+ await this.waitForNamesAvailable(_nullishCoalesce(names, () => ( [])), options);
4544
+ }
4545
+ async complete(message, response) {
4546
+ const validatedResponse = validateQueueComplete(
4547
+ this.#schemas,
4548
+ message.name,
4549
+ response
4550
+ );
4551
+ await callNative(
4552
+ () => this.#runtime.actorQueueCompletePersisted(
4553
+ this.#ctx,
4554
+ BigInt(message.id),
4555
+ message.name,
4556
+ encodeValue(validatedResponse)
4557
+ )
4558
+ );
4559
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
4560
+ }
3295
4561
  async enqueueAndWait(name, body, options) {
3296
4562
  const validatedBody = validateQueueBody(this.#schemas, name, body);
3297
4563
  const { token, cleanup } = await createCancellationTokenHandle(
@@ -3359,7 +4625,7 @@ var NativeQueueAdapter = class {
3359
4625
  }
3360
4626
  yield message;
3361
4627
  } catch (error) {
3362
- if (_chunkQAZLM4WTcjs.isRivetErrorLike.call(void 0, error) && error.group === "actor" && error.code === "aborted") {
4628
+ if (_chunk2JSYYH6Pcjs.isActorAbortedError.call(void 0, error)) {
3363
4629
  return;
3364
4630
  }
3365
4631
  throw error;
@@ -3380,7 +4646,7 @@ var NativeQueueAdapter = class {
3380
4646
  ...message,
3381
4647
  complete: async (response) => {
3382
4648
  if (typeof message.complete !== "function") {
3383
- throw new (0, _chunkQAZLM4WTcjs.RivetError)(
4649
+ throw new (0, _chunk2JSYYH6Pcjs.RivetError)(
3384
4650
  "queue",
3385
4651
  "complete_not_configured",
3386
4652
  `Queue '${message.name}' does not support completion responses.`,
@@ -3392,7 +4658,7 @@ var NativeQueueAdapter = class {
3392
4658
  );
3393
4659
  }
3394
4660
  if (completed) {
3395
- throw new (0, _chunkQAZLM4WTcjs.RivetError)(
4661
+ throw new (0, _chunk2JSYYH6Pcjs.RivetError)(
3396
4662
  "queue",
3397
4663
  "already_completed",
3398
4664
  "Queue message was already completed.",
@@ -3445,7 +4711,7 @@ var NativeWebSocketAdapter = class {
3445
4711
  this.#runtime.webSocketSetEventCallback(this.#ws, (event2) => {
3446
4712
  if (event2.kind === "message") {
3447
4713
  this.#virtual.triggerMessage(
3448
- event2.binary ? runtimeBytesToArrayBuffer(event2.data) : event2.data,
4714
+ event2.binary ? runtimeBytesToArrayBuffer2(event2.data) : event2.data,
3449
4715
  event2.messageIndex
3450
4716
  );
3451
4717
  return;
@@ -3724,6 +4990,71 @@ var TrackedWebSocketHandleAdapter = class {
3724
4990
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
3725
4991
  }
3726
4992
  };
4993
+ var NativeConnectionMap = (_class3 = class {
4994
+ #runtime;
4995
+ #ctx;
4996
+ #schemas;
4997
+ #assertCanMutateState;
4998
+ constructor(runtime, ctx, schemas, assertCanMutateState) {;_class3.prototype.__init3.call(this);
4999
+ this.#runtime = runtime;
5000
+ this.#ctx = ctx;
5001
+ this.#schemas = schemas;
5002
+ this.#assertCanMutateState = assertCanMutateState;
5003
+ }
5004
+ #connToAdapter(conn) {
5005
+ return new NativeConnAdapter(
5006
+ this.#runtime,
5007
+ conn,
5008
+ this.#schemas,
5009
+ this.#ctx,
5010
+ (connId) => callNativeSync(
5011
+ () => this.#runtime.actorQueueHibernationRemoval(
5012
+ this.#ctx,
5013
+ connId
5014
+ )
5015
+ ),
5016
+ this.#assertCanMutateState
5017
+ );
5018
+ }
5019
+ get size() {
5020
+ return callNativeSync(() => this.#runtime.actorConns(this.#ctx)).length;
5021
+ }
5022
+ get(key) {
5023
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
5024
+ const conn = conns.find((c) => this.#runtime.connId(c) === key);
5025
+ if (!conn) return void 0;
5026
+ return this.#connToAdapter(conn);
5027
+ }
5028
+ has(key) {
5029
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
5030
+ return conns.some((c) => this.#runtime.connId(c) === key);
5031
+ }
5032
+ keys() {
5033
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
5034
+ return conns.map((c) => this.#runtime.connId(c))[Symbol.iterator]();
5035
+ }
5036
+ values() {
5037
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
5038
+ return conns.map((c) => this.#connToAdapter(c))[Symbol.iterator]();
5039
+ }
5040
+ entries() {
5041
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
5042
+ return conns.map(
5043
+ (c) => [this.#runtime.connId(c), this.#connToAdapter(c)]
5044
+ )[Symbol.iterator]();
5045
+ }
5046
+ forEach(callback, thisArg) {
5047
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
5048
+ for (const conn of conns) {
5049
+ const id = this.#runtime.connId(conn);
5050
+ callback.call(thisArg, this.#connToAdapter(conn), id, this);
5051
+ }
5052
+ }
5053
+ [Symbol.iterator]() {
5054
+ return this.entries();
5055
+ }
5056
+ __init3() {this[Symbol.toStringTag] = "NativeConnectionMap"}
5057
+ }, _class3);
3727
5058
  var ActorContextHandleAdapter = class {
3728
5059
  #runtime;
3729
5060
  #ctx;
@@ -3732,32 +5063,36 @@ var ActorContextHandleAdapter = class {
3732
5063
  #abortSignalCleanup;
3733
5064
  #client;
3734
5065
  #clientFactory;
5066
+ #connMap;
5067
+ #cron;
3735
5068
  #databaseProvider;
3736
5069
  #db;
3737
- #dbProxy;
3738
5070
  #dispatchCancelToken;
3739
5071
  #kv;
3740
5072
  #queue;
3741
5073
  #request;
3742
5074
  #schedule;
3743
- #sql;
3744
- #runHandlerActiveProvider;
5075
+ #run;
5076
+ #runHandlerConfigured;
3745
5077
  #onStateChange;
3746
5078
  #stateEnabled;
3747
- constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, runHandlerActiveProvider, onStateChange, dispatchCancelToken) {
5079
+ #stateProxy;
5080
+ #stateProxyTarget;
5081
+ #stateTransactionOwner = /* @__PURE__ */ Symbol("actor-state-transaction-owner");
5082
+ constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
3748
5083
  this.#runtime = runtime;
3749
5084
  this.#ctx = ctx;
3750
5085
  this.#clientFactory = clientFactory;
3751
5086
  this.#schemas = schemas;
3752
5087
  this.#dispatchCancelToken = dispatchCancelToken;
3753
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
5088
+ this.#runHandlerConfigured = runHandlerConfigured;
3754
5089
  this.#onStateChange = onStateChange;
3755
5090
  this.#stateEnabled = stateEnabled;
3756
5091
  if (databaseProvider) {
3757
5092
  this.#databaseProvider = databaseProvider;
3758
5093
  }
3759
5094
  this.#request = request;
3760
- this[_chunkWQ4HNA4Wcjs.ACTOR_CONTEXT_INTERNAL_SYMBOL] = new NativeWorkflowRuntimeAdapter(
5095
+ this[_chunk4KGXFC6Mcjs.ACTOR_CONTEXT_INTERNAL_SYMBOL] = new NativeWorkflowRuntimeAdapter(
3761
5096
  this
3762
5097
  );
3763
5098
  }
@@ -3767,68 +5102,75 @@ var ActorContextHandleAdapter = class {
3767
5102
  }
3768
5103
  return this.#kv;
3769
5104
  }
3770
- get sql() {
3771
- if (!this.#sql) {
3772
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
3773
- }
3774
- return this.#sql;
5105
+ async actorRuntimeSocket() {
5106
+ return await callNative(
5107
+ () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
5108
+ );
3775
5109
  }
3776
5110
  get db() {
3777
5111
  if (!this.#databaseProvider) {
3778
5112
  throw databaseNotConfiguredError();
3779
5113
  }
3780
- if (!this.#dbProxy) {
3781
- this.#dbProxy = new Proxy(
3782
- {},
3783
- {
3784
- get: (_target, property) => {
3785
- if (property === "then") {
3786
- return void 0;
3787
- }
3788
- return async (...args) => {
3789
- const client = await this.ensureDatabaseClient();
3790
- const value = Reflect.get(
3791
- client,
3792
- property
3793
- );
3794
- if (typeof value !== "function") {
3795
- return value;
3796
- }
3797
- return await value.apply(client, args);
3798
- };
3799
- }
3800
- }
3801
- );
5114
+ if (this.#db) {
5115
+ return this.#db;
5116
+ }
5117
+ const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
5118
+ const cachedClient = runtimeState.databaseClient;
5119
+ if (cachedClient) {
5120
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
5121
+ return this.#db;
5122
+ }
5123
+ throw databaseClientNotReadyError();
5124
+ }
5125
+ [_chunk4KGXFC6Mcjs.RAW_STATE_SYMBOL]() {
5126
+ if (!this.#stateEnabled) {
5127
+ throw stateNotEnabledError();
3802
5128
  }
3803
- return this.#dbProxy;
5129
+ return this.#readState();
3804
5130
  }
3805
5131
  get state() {
3806
5132
  if (!this.#stateEnabled) {
3807
5133
  throw stateNotEnabledError();
3808
5134
  }
3809
5135
  const nextState = this.#readState();
3810
- return createWriteThroughProxy(
3811
- nextState,
3812
- (nextValue) => {
3813
- this.#writeState(nextValue, { scheduleSave: true });
3814
- },
3815
- () => {
5136
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
5137
+ const assertCurrentState = () => {
3816
5138
  this.#assertCanMutateState();
3817
- }
3818
- );
5139
+ if (this.#readState() !== nextState) {
5140
+ throw stateTransactionConflictError();
5141
+ }
5142
+ };
5143
+ this.#stateProxyTarget = nextState;
5144
+ this.#stateProxy = createWriteThroughProxy(
5145
+ nextState,
5146
+ (nextValue) => {
5147
+ assertCurrentState();
5148
+ this.#writeState(nextValue, { scheduleSave: true });
5149
+ },
5150
+ (newValue) => {
5151
+ assertCurrentState();
5152
+ _chunkEHZH3KUWcjs.assertJsonCompatValue.call(void 0, newValue);
5153
+ }
5154
+ );
5155
+ }
5156
+ return this.#stateProxy;
3819
5157
  }
3820
5158
  set state(value) {
3821
5159
  if (!this.#stateEnabled) {
3822
5160
  throw stateNotEnabledError();
3823
5161
  }
3824
5162
  this.#assertCanMutateState();
3825
- this.#writeState(value, { scheduleSave: true });
5163
+ const nextValue = unwrapWriteThroughProxy(value);
5164
+ _chunkEHZH3KUWcjs.assertJsonCompatValue.call(void 0, nextValue);
5165
+ this.#writeState(nextValue, { scheduleSave: true });
3826
5166
  }
3827
5167
  initializeState(value) {
3828
5168
  if (!this.#stateEnabled) {
3829
5169
  return;
3830
5170
  }
3831
- this.#writeState(value, { scheduleSave: false });
5171
+ this.#writeState(unwrapWriteThroughProxy(value), {
5172
+ scheduleSave: false
5173
+ });
3832
5174
  }
3833
5175
  get vars() {
3834
5176
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
@@ -3854,6 +5196,26 @@ var ActorContextHandleAdapter = class {
3854
5196
  }
3855
5197
  return this.#queue;
3856
5198
  }
5199
+ get run() {
5200
+ if (!this.#run) {
5201
+ this.#run = {
5202
+ setWakeAt: async (timestamp) => {
5203
+ if (timestamp !== null && !this.#runHandlerConfigured) {
5204
+ throw runHandlerNotConfiguredError();
5205
+ }
5206
+ if (timestamp !== null && (!Number.isSafeInteger(timestamp) || timestamp < 0)) {
5207
+ throw new TypeError(
5208
+ "Run wake timestamp must be a non-negative safe integer or null"
5209
+ );
5210
+ }
5211
+ await callNative(
5212
+ () => this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp)
5213
+ );
5214
+ }
5215
+ };
5216
+ }
5217
+ return this.#run;
5218
+ }
3857
5219
  get schedule() {
3858
5220
  if (!this.#schedule) {
3859
5221
  this.#schedule = new NativeScheduleAdapter(
@@ -3863,6 +5225,12 @@ var ActorContextHandleAdapter = class {
3863
5225
  }
3864
5226
  return this.#schedule;
3865
5227
  }
5228
+ get cron() {
5229
+ if (!this.#cron) {
5230
+ this.#cron = new NativeCronAdapter(this.#runtime, this.#ctx);
5231
+ }
5232
+ return this.#cron;
5233
+ }
3866
5234
  get actorId() {
3867
5235
  return callNativeSync(() => this.#runtime.actorId(this.#ctx));
3868
5236
  }
@@ -3878,25 +5246,15 @@ var ActorContextHandleAdapter = class {
3878
5246
  return callNativeSync(() => this.#runtime.actorRegion(this.#ctx));
3879
5247
  }
3880
5248
  get conns() {
3881
- return new Map(
3882
- callNativeSync(() => this.#runtime.actorConns(this.#ctx)).map(
3883
- (conn) => [
3884
- this.#runtime.connId(conn),
3885
- new NativeConnAdapter(
3886
- this.#runtime,
3887
- conn,
3888
- this.#schemas,
3889
- this.#ctx,
3890
- (connId) => callNativeSync(
3891
- () => this.#runtime.actorQueueHibernationRemoval(
3892
- this.#ctx,
3893
- connId
3894
- )
3895
- )
3896
- )
3897
- ]
3898
- )
3899
- );
5249
+ if (!this.#connMap) {
5250
+ this.#connMap = new NativeConnectionMap(
5251
+ this.#runtime,
5252
+ this.#ctx,
5253
+ this.#schemas,
5254
+ () => this.#assertCanMutateState()
5255
+ );
5256
+ }
5257
+ return this.#connMap;
3900
5258
  }
3901
5259
  get log() {
3902
5260
  return logger2();
@@ -3962,11 +5320,11 @@ var ActorContextHandleAdapter = class {
3962
5320
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
3963
5321
  const cachedClient = runtimeState.databaseClient;
3964
5322
  if (cachedClient) {
3965
- this.#db = cachedClient.client;
5323
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
3966
5324
  return this.#db;
3967
5325
  }
3968
5326
  const actorId = this.actorId;
3969
- const client = await this.#databaseProvider.createClient({
5327
+ const createdClient = await this.#databaseProvider.createClient({
3970
5328
  actorId,
3971
5329
  kv: {
3972
5330
  batchPut: async (entries) => {
@@ -3987,21 +5345,126 @@ var ActorContextHandleAdapter = class {
3987
5345
  log: {
3988
5346
  debug: (obj) => logger2().debug(obj)
3989
5347
  },
3990
- nativeDatabaseProvider: {
3991
- open: async (requestedActorId) => {
3992
- void requestedActorId;
3993
- return getOrCreateNativeSqlDatabase(
3994
- this.#runtime,
3995
- this.#ctx
3996
- );
3997
- }
3998
- }
5348
+ nativeDatabaseProvider: _chunkBHXSPZ5Mcjs.registerNativeStateTransactionOpener.call(void 0,
5349
+ {
5350
+ open: async (requestedActorId) => {
5351
+ void requestedActorId;
5352
+ return getOrCreateNativeSqlDatabase(
5353
+ this.#runtime,
5354
+ this.#ctx
5355
+ );
5356
+ }
5357
+ },
5358
+ async (timeoutMs, context) => await getOrCreateNativeSqlDatabase(
5359
+ this.#runtime,
5360
+ this.#ctx
5361
+ ).beginStateTransaction(timeoutMs, context)
5362
+ )
3999
5363
  });
4000
5364
  runtimeState.databaseClient = {
4001
- client
5365
+ client: createdClient
4002
5366
  };
4003
- this.#db = client;
4004
- return client;
5367
+ this.#db = this.#bindDatabaseClient(createdClient);
5368
+ return this.#db;
5369
+ }
5370
+ #bindDatabaseClient(client) {
5371
+ return _chunkBHXSPZ5Mcjs.bindNativeStateTransactionContext.call(void 0, client, {
5372
+ enter: async () => await this.#enterStateTransaction(),
5373
+ exit: (scope) => this.#exitStateTransaction(
5374
+ scope
5375
+ )
5376
+ });
5377
+ }
5378
+ async #enterStateTransaction() {
5379
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5380
+ let pendingOwners = actorState.pendingStateTransactionOwners;
5381
+ if (!pendingOwners) {
5382
+ pendingOwners = /* @__PURE__ */ new Set();
5383
+ actorState.pendingStateTransactionOwners = pendingOwners;
5384
+ }
5385
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner || pendingOwners.has(this.#stateTransactionOwner)) {
5386
+ throw stateTransactionConflictError();
5387
+ }
5388
+ pendingOwners.add(this.#stateTransactionOwner);
5389
+ const predecessor = _nullishCoalesce(actorState.stateTransactionTail, () => ( Promise.resolve()));
5390
+ let release;
5391
+ const hold = new Promise((resolve) => {
5392
+ release = resolve;
5393
+ });
5394
+ actorState.stateTransactionTail = predecessor.then(
5395
+ async () => await hold
5396
+ );
5397
+ try {
5398
+ await predecessor;
5399
+ pendingOwners.delete(this.#stateTransactionOwner);
5400
+ actorState.activeStateTransactionOwner = this.#stateTransactionOwner;
5401
+ return {
5402
+ actorContext: this,
5403
+ actorStateBaseline: this.#stateEnabled ? structuredClone(this.#readState()) : void 0,
5404
+ connectionStateBaselines: new Map(
5405
+ callNativeSync(
5406
+ () => this.#runtime.actorConns(this.#ctx)
5407
+ ).map((conn) => [
5408
+ callNativeSync(() => this.#runtime.connId(conn)),
5409
+ new Uint8Array(
5410
+ callNativeSync(() => this.#runtime.connState(conn))
5411
+ )
5412
+ ])
5413
+ ),
5414
+ committed: false,
5415
+ release
5416
+ };
5417
+ } catch (error) {
5418
+ pendingOwners.delete(this.#stateTransactionOwner);
5419
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5420
+ actorState.activeStateTransactionOwner = void 0;
5421
+ }
5422
+ release();
5423
+ throw error;
5424
+ }
5425
+ }
5426
+ #exitStateTransaction(scope) {
5427
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5428
+ try {
5429
+ if (!scope.committed) {
5430
+ this.#restoreStateTransactionBaseline(scope);
5431
+ }
5432
+ } finally {
5433
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5434
+ actorState.activeStateTransactionOwner = void 0;
5435
+ }
5436
+ if (actorState.stateTransactionSaveDeferred) {
5437
+ actorState.stateTransactionSaveDeferred = false;
5438
+ this.#scheduleSave();
5439
+ }
5440
+ scope.release();
5441
+ }
5442
+ }
5443
+ #restoreStateTransactionBaseline(scope) {
5444
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5445
+ if (actorState.pendingSaveHandle !== void 0) {
5446
+ clearImmediate(actorState.pendingSaveHandle);
5447
+ }
5448
+ actorState.pendingSaveHandle = void 0;
5449
+ actorState.saveScheduled = false;
5450
+ if (this.#stateEnabled) {
5451
+ actorState.state = structuredClone(scope.actorStateBaseline);
5452
+ }
5453
+ for (const conn of callNativeSync(
5454
+ () => this.#runtime.actorConns(this.#ctx)
5455
+ )) {
5456
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
5457
+ const baseline = scope.connectionStateBaselines.get(connId);
5458
+ if (baseline === void 0) {
5459
+ continue;
5460
+ }
5461
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
5462
+ const cached = actorState.connStates.get(connId);
5463
+ if (cached) {
5464
+ cached.state = decodeValue(baseline);
5465
+ }
5466
+ }
5467
+ this.#scheduleSave();
4005
5468
  }
4006
5469
  async prepare() {
4007
5470
  if (!this.#databaseProvider) {
@@ -4019,7 +5482,6 @@ var ActorContextHandleAdapter = class {
4019
5482
  }
4020
5483
  async closeDatabase() {
4021
5484
  this.#db = void 0;
4022
- this.#sql = void 0;
4023
5485
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
4024
5486
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
4025
5487
  }
@@ -4039,6 +5501,7 @@ var ActorContextHandleAdapter = class {
4039
5501
  }
4040
5502
  async saveState(opts) {
4041
5503
  if (opts == null ? void 0 : opts.immediate) {
5504
+ this.#assertCanAwaitStateSave();
4042
5505
  await callNative(
4043
5506
  () => this.#runtime.actorRequestSaveAndWait(this.#ctx, {
4044
5507
  immediate: true
@@ -4058,6 +5521,18 @@ var ActorContextHandleAdapter = class {
4058
5521
  () => this.#runtime.actorRequestSave(this.#ctx, { immediate: false })
4059
5522
  );
4060
5523
  }
5524
+ async saveStateAndWorkflowBatch(writes) {
5525
+ this.#assertCanAwaitStateSave();
5526
+ await callNative(
5527
+ () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
5528
+ );
5529
+ }
5530
+ #assertCanAwaitStateSave() {
5531
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5532
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5533
+ throw stateTransactionConflictError();
5534
+ }
5535
+ }
4061
5536
  serializeForTick(reason) {
4062
5537
  void reason;
4063
5538
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4097,7 +5572,7 @@ var ActorContextHandleAdapter = class {
4097
5572
  const trackedPromise = Promise.resolve(promise).catch((error) => {
4098
5573
  logger2().warn({
4099
5574
  msg: "keepAwake promise rejected",
4100
- error: _chunkO25KOT5Ccjs.stringifyError.call(void 0, error)
5575
+ error: _chunkEHZH3KUWcjs.stringifyError.call(void 0, error)
4101
5576
  });
4102
5577
  }).then(() => null);
4103
5578
  try {
@@ -4111,13 +5586,12 @@ var ActorContextHandleAdapter = class {
4111
5586
  }
4112
5587
  return promise;
4113
5588
  }
4114
- runHandlerActive() {
4115
- var _a;
4116
- return _nullishCoalesce(((_a = this.#runHandlerActiveProvider) == null ? void 0 : _a.call(this)), () => ( false));
4117
- }
4118
5589
  internalKeepAwake(run) {
4119
5590
  const promise = typeof run === "function" ? run() : run;
4120
- const trackedPromise = promise.then(() => null);
5591
+ const trackedPromise = promise.then(
5592
+ () => null,
5593
+ () => null
5594
+ );
4121
5595
  try {
4122
5596
  callNativeSync(
4123
5597
  () => this.#runtime.actorRegisterTask(this.#ctx, trackedPromise)
@@ -4173,6 +5647,7 @@ var ActorContextHandleAdapter = class {
4173
5647
  return false;
4174
5648
  }
4175
5649
  sleep() {
5650
+ this.#flushStateChange();
4176
5651
  callNativeSync(() => this.#runtime.actorSleep(this.#ctx));
4177
5652
  }
4178
5653
  destroy() {
@@ -4190,8 +5665,8 @@ var ActorContextHandleAdapter = class {
4190
5665
  }
4191
5666
  async dispose() {
4192
5667
  var _a;
5668
+ this.#flushStateChange();
4193
5669
  (_a = this.#abortSignalCleanup) == null ? void 0 : _a.call(this);
4194
- this.#sql = void 0;
4195
5670
  }
4196
5671
  #createActorAbortSignal() {
4197
5672
  const nativeSignal = callNativeSync(
@@ -4217,23 +5692,61 @@ var ActorContextHandleAdapter = class {
4217
5692
  return actorState.state;
4218
5693
  }
4219
5694
  #writeState(value, options) {
4220
- encodeValue(value);
4221
5695
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4222
5696
  actorState.state = value;
4223
5697
  if (!options.scheduleSave) {
4224
5698
  return;
4225
5699
  }
4226
- this.#handleStateChange();
5700
+ this.#scheduleSave();
4227
5701
  }
4228
5702
  #assertCanMutateState() {
5703
+ var _a;
4229
5704
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4230
5705
  if (actorState.isInOnStateChange) {
4231
5706
  throw stateMutationReentrantError();
4232
5707
  }
5708
+ if (actorState.activeStateTransactionOwner !== this.#stateTransactionOwner && (actorState.activeStateTransactionOwner !== void 0 || (_nullishCoalesce(((_a = actorState.pendingStateTransactionOwners) == null ? void 0 : _a.size), () => ( 0))) > 0)) {
5709
+ throw stateTransactionConflictError();
5710
+ }
5711
+ }
5712
+ /** @internal */
5713
+ assertCanMutateState() {
5714
+ this.#assertCanMutateState();
5715
+ }
5716
+ // Coalesce the request-save and onStateChange work to once per event loop
5717
+ // tick. A synchronous burst of mutations (for example
5718
+ // `Object.assign(c.state, ...)`) would otherwise cross the NAPI boundary and
5719
+ // run onStateChange once per field, re-serializing the whole state each time
5720
+ // and pinning the event loop on large state.
5721
+ #scheduleSave() {
5722
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5723
+ if (actorState.saveScheduled) {
5724
+ return;
5725
+ }
5726
+ actorState.saveScheduled = true;
5727
+ actorState.pendingSaveHandle = setImmediate(() => {
5728
+ this.#flushStateChange();
5729
+ });
4233
5730
  }
4234
- #handleStateChange() {
5731
+ #flushStateChange() {
4235
5732
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4236
- encodeValue(actorState.state);
5733
+ if (!actorState.saveScheduled) {
5734
+ return;
5735
+ }
5736
+ if (actorState.activeStateTransactionOwner !== void 0) {
5737
+ actorState.saveScheduled = false;
5738
+ if (actorState.pendingSaveHandle !== void 0) {
5739
+ clearImmediate(actorState.pendingSaveHandle);
5740
+ actorState.pendingSaveHandle = void 0;
5741
+ }
5742
+ actorState.stateTransactionSaveDeferred = true;
5743
+ return;
5744
+ }
5745
+ actorState.saveScheduled = false;
5746
+ if (actorState.pendingSaveHandle !== void 0) {
5747
+ clearImmediate(actorState.pendingSaveHandle);
5748
+ actorState.pendingSaveHandle = void 0;
5749
+ }
4237
5750
  callNativeSync(
4238
5751
  () => this.#runtime.actorRequestSave(this.#ctx, { immediate: false })
4239
5752
  );
@@ -4346,12 +5859,12 @@ var NativeWorkflowRuntimeAdapter = class {
4346
5859
  this.stateManager = {
4347
5860
  saveState: async (opts) => {
4348
5861
  await this.#ctx.saveState(opts);
5862
+ },
5863
+ saveStateAndWorkflowBatch: async (writes) => {
5864
+ await this.#ctx.saveStateAndWorkflowBatch(writes);
4349
5865
  }
4350
5866
  };
4351
5867
  }
4352
- isRunHandlerActive() {
4353
- return this.#ctx.runHandlerActive();
4354
- }
4355
5868
  async restartRunHandler() {
4356
5869
  await this.#ctx.restartRunHandler();
4357
5870
  }
@@ -4384,42 +5897,46 @@ var NativeWorkflowRuntimeAdapter = class {
4384
5897
  };
4385
5898
  }
4386
5899
  };
4387
- function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken) {
4388
- return Object.assign(
4389
- new ActorContextHandleAdapter(
5900
+ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
5901
+ const actorContext = new ActorContextHandleAdapter(
5902
+ runtime,
5903
+ ctx,
5904
+ clientFactory,
5905
+ schemas,
5906
+ databaseProvider,
5907
+ request,
5908
+ stateEnabled,
5909
+ onStateChange,
5910
+ dispatchCancelToken,
5911
+ runHandlerConfigured
5912
+ );
5913
+ return Object.assign(actorContext, {
5914
+ conn: new NativeConnAdapter(
4390
5915
  runtime,
4391
- ctx,
4392
- clientFactory,
5916
+ conn,
4393
5917
  schemas,
4394
- databaseProvider,
4395
- request,
4396
- stateEnabled,
4397
- void 0,
4398
- onStateChange,
4399
- dispatchCancelToken
4400
- ),
4401
- {
4402
- conn: new NativeConnAdapter(
4403
- runtime,
4404
- conn,
4405
- schemas,
4406
- ctx,
4407
- (connId) => callNativeSync(
4408
- () => runtime.actorQueueHibernationRemoval(ctx, connId)
4409
- )
4410
- )
4411
- }
4412
- );
5918
+ ctx,
5919
+ (connId) => callNativeSync(
5920
+ () => runtime.actorQueueHibernationRemoval(ctx, connId)
5921
+ ),
5922
+ () => actorContext.assertCanMutateState()
5923
+ )
5924
+ });
4413
5925
  }
4414
- function buildActorConfig(definition, registryConfig) {
5926
+ function buildActorConfig(definition, registryConfig, runtimeKind) {
5927
+ var _a;
4415
5928
  const config = definition.config;
4416
5929
  const options = _nullishCoalesce(config.options, () => ( {}));
4417
5930
  const canHibernate = options.canHibernateWebSocket;
5931
+ const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
5932
+ const sqliteProfiling = (_a = config.db) == null ? void 0 : _a.sqliteProfiling;
4418
5933
  return {
4419
5934
  name: options.name,
4420
5935
  icon: options.icon,
4421
- hasDatabase: config.db !== void 0,
4422
- remoteSqlite: config.db !== void 0 && sqliteBackendForConfig(registryConfig) === "remote",
5936
+ hasDatabase: true,
5937
+ remoteSqlite: usesRemoteSqlite,
5938
+ sqliteProfiling,
5939
+ enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
4423
5940
  hasState: config.state !== void 0 || typeof config.createState === "function",
4424
5941
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
4425
5942
  stateSaveIntervalMs: options.stateSaveInterval,
@@ -4435,43 +5952,112 @@ function buildActorConfig(definition, registryConfig) {
4435
5952
  connectionLivenessTimeoutMs: options.connectionLivenessTimeout,
4436
5953
  connectionLivenessIntervalMs: options.connectionLivenessInterval,
4437
5954
  maxQueueSize: options.maxQueueSize,
5955
+ maxSchedules: options.maxSchedules,
4438
5956
  maxQueueMessageSize: options.maxQueueMessageSize,
4439
5957
  maxIncomingMessageSize: registryConfig.maxIncomingMessageSize,
4440
5958
  maxOutgoingMessageSize: registryConfig.maxOutgoingMessageSize,
4441
5959
  preloadMaxWorkflowBytes: options.preloadMaxWorkflowBytes,
4442
5960
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes,
4443
- actions: Object.keys(_nullishCoalesce(config.actions, () => ( {}))).sort().map((name) => ({ name }))
5961
+ actions: Object.keys(_chunk4KGXFC6Mcjs.flattenActionHandlers.call(void 0, config.actions)).sort().map((name) => ({ name })),
5962
+ inspectorTabs: buildInspectorTabs(config.inspector, runtimeKind)
4444
5963
  };
4445
5964
  }
5965
+ function buildInspectorTabs(inspector, runtimeKind) {
5966
+ if (!inspector || typeof inspector !== "object") return void 0;
5967
+ const tabs = inspector.tabs;
5968
+ if (!Array.isArray(tabs) || tabs.length === 0) return void 0;
5969
+ return tabs.map((raw) => {
5970
+ const entry = raw;
5971
+ if (entry.hidden === true) {
5972
+ return { id: entry.id, hidden: true };
5973
+ }
5974
+ if (runtimeKind === "wasm") {
5975
+ if (entry.source !== void 0) {
5976
+ logger2().warn(
5977
+ {
5978
+ tabId: entry.id,
5979
+ runtimeKind
5980
+ },
5981
+ "inspector.tabs[].source is not supported on wasm runners (current host: wasm). Tab descriptors will still appear in the dashboard strip but the tab body will render a not-available placeholder."
5982
+ );
5983
+ }
5984
+ return {
5985
+ id: entry.id,
5986
+ label: entry.label,
5987
+ icon: entry.icon,
5988
+ source: void 0
5989
+ };
5990
+ }
5991
+ const resolved = entry.source !== void 0 ? getNodePath().resolve(entry.source) : void 0;
5992
+ if (resolved !== void 0) {
5993
+ validateInspectorTabSource(entry.id, resolved);
5994
+ }
5995
+ return {
5996
+ id: entry.id,
5997
+ label: entry.label,
5998
+ icon: entry.icon,
5999
+ source: resolved
6000
+ };
6001
+ });
6002
+ }
6003
+ function validateInspectorTabSource(tabId, resolved) {
6004
+ if (resolved === getNodePath().parse(resolved).root) {
6005
+ throw new Error(
6006
+ `inspector.tabs[id="${tabId}"].source resolves to the filesystem root (${resolved}). Point it at the tab's own static-asset directory instead.`
6007
+ );
6008
+ }
6009
+ let stat;
6010
+ try {
6011
+ stat = getNodeFsSync().statSync(resolved);
6012
+ } catch (err) {
6013
+ const code = err == null ? void 0 : err.code;
6014
+ if (code === "ENOENT") {
6015
+ throw new Error(
6016
+ `inspector.tabs[id="${tabId}"].source (${resolved}) does not exist.`
6017
+ );
6018
+ }
6019
+ if (code === "EACCES") {
6020
+ throw new Error(
6021
+ `inspector.tabs[id="${tabId}"].source (${resolved}) is not readable (EACCES).`
6022
+ );
6023
+ }
6024
+ throw new Error(
6025
+ `inspector.tabs[id="${tabId}"].source (${resolved}) could not be stat'd: ${_nullishCoalesce((err == null ? void 0 : err.message), () => ( err))}`
6026
+ );
6027
+ }
6028
+ if (!stat.isDirectory()) {
6029
+ throw new Error(
6030
+ `inspector.tabs[id="${tabId}"].source (${resolved}) must be a directory, got ${stat.isFile() ? "file" : "non-directory"}.`
6031
+ );
6032
+ }
6033
+ }
4446
6034
  function buildNativeFactory(runtime, registryConfig, definition) {
4447
6035
  var _a;
4448
6036
  const config = definition.config;
4449
- const databaseProvider = config.db;
6037
+ const databaseProvider = _nullishCoalesce(config.db, () => ( _chunkBHXSPZ5Mcjs.db.call(void 0, )));
6038
+ const actionHandlers = _chunk4KGXFC6Mcjs.flattenActionHandlers.call(void 0, config.actions);
4450
6039
  const schemaConfig = {
4451
- actionInputSchemas: config.actionInputSchemas,
6040
+ actionInputSchemas: _chunk4KGXFC6Mcjs.flattenActionInputSchemas.call(void 0,
6041
+ config.actions,
6042
+ config.actionInputSchemas
6043
+ ),
4452
6044
  connParamsSchema: config.connParamsSchema,
4453
6045
  events: config.events,
4454
6046
  queues: config.queues
4455
6047
  };
4456
- const actionHandlers = Object.fromEntries(
4457
- Object.entries(_nullishCoalesce(config.actions, () => ( {}))).map(([name, handler]) => [name, handler])
4458
- );
4459
- const createClient = () => _chunkYQQ2ZDKTcjs.createClientWithDriver.call(void 0,
4460
- new (0, _chunkYQQ2ZDKTcjs.RemoteEngineControlClient)(
4461
- _chunkYQQ2ZDKTcjs.convertRegistryConfigToClientConfig.call(void 0, registryConfig)
6048
+ const createClient = () => _chunkAIL267JKcjs.createClientWithDriver.call(void 0,
6049
+ new (0, _chunkAIL267JKcjs.RemoteEngineControlClient)(
6050
+ _chunkAIL267JKcjs.convertRegistryConfigToClientConfig.call(void 0, registryConfig)
4462
6051
  ),
4463
6052
  { encoding: "bare" }
4464
6053
  );
4465
- const nativeRunHandlerActiveByActorId = /* @__PURE__ */ new Map();
4466
- const isNativeRunHandlerActive = (ctx) => _nullishCoalesce(nativeRunHandlerActiveByActorId.get(
4467
- callNativeSync(() => runtime.actorId(ctx))
4468
- ), () => ( false));
6054
+ const run = _chunk4KGXFC6Mcjs.getRunFunction.call(void 0, config.run);
6055
+ const runHandlerCoordinator = _chunk4KGXFC6Mcjs.getRunInspectorKind.call(void 0, config.run) === "workflow" ? new RunHandlerCoordinator(config.run) : void 0;
4469
6056
  const getNativeWorkflowInspector = (ctx) => {
4470
- var _a2;
4471
- return (_a2 = _chunkWQ4HNA4Wcjs.getRunInspectorConfig.call(void 0,
4472
- config.run,
4473
- callNativeSync(() => runtime.actorId(ctx))
4474
- )) == null ? void 0 : _a2.workflow;
6057
+ var _a2, _b;
6058
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
6059
+ const restart = () => callNativeSync(() => runtime.actorRestartRunHandler(ctx));
6060
+ return _nullishCoalesce(((_a2 = runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.getInspector(actorId, restart)) == null ? void 0 : _a2.workflow), () => ( ((_b = _chunk4KGXFC6Mcjs.getRunInspectorConfig.call(void 0, config.run, actorId)) == null ? void 0 : _b.workflow)));
4475
6061
  };
4476
6062
  const onStateChange = typeof config.onStateChange === "function" ? (actorCtx, nextState) => {
4477
6063
  config.onStateChange(actorCtx, nextState);
@@ -4491,9 +6077,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4491
6077
  databaseProvider,
4492
6078
  request,
4493
6079
  stateEnabled,
4494
- () => isNativeRunHandlerActive(ctx),
4495
6080
  onStateChange,
4496
- cancelToken
6081
+ cancelToken,
6082
+ run !== void 0
4497
6083
  );
4498
6084
  const makeConnCtx = (ctx, conn, request, cancelToken) => withConnContext(
4499
6085
  runtime,
@@ -4505,14 +6091,17 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4505
6091
  request,
4506
6092
  stateEnabled,
4507
6093
  onStateChange,
4508
- cancelToken
6094
+ cancelToken,
6095
+ run !== void 0
4509
6096
  );
4510
- const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
6097
+ const maybeHandleNativeInspectorRequest = async (ctx, rawRequest) => {
4511
6098
  var _a2, _b, _c, _d;
4512
- const url = new URL(jsRequest.url);
6099
+ const rawUrl = rawRequest.uri.startsWith("http") ? rawRequest.uri : new URL(rawRequest.uri, "http://127.0.0.1").toString();
6100
+ const url = new URL(rawUrl);
4513
6101
  if (!url.pathname.startsWith("/inspector/")) {
4514
6102
  return void 0;
4515
6103
  }
6104
+ const jsRequest = buildNativeHttpRequest(rawRequest);
4516
6105
  const jsonResponse = (body, init) => new Response(JSON.stringify(body), {
4517
6106
  status: _nullishCoalesce((init == null ? void 0 : init.status), () => ( 200)),
4518
6107
  headers: {
@@ -4521,7 +6110,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4521
6110
  }
4522
6111
  });
4523
6112
  const errorResponse = (error, status) => {
4524
- const rivetError = _chunkQAZLM4WTcjs.toRivetError.call(void 0, error);
6113
+ const rivetError = _chunk2JSYYH6Pcjs.toRivetError.call(void 0, error);
4525
6114
  return jsonResponse(
4526
6115
  {
4527
6116
  group: rivetError.group,
@@ -4534,13 +6123,16 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4534
6123
  }
4535
6124
  );
4536
6125
  };
4537
- try {
4538
- await runtime.actorVerifyInspectorAuth(
4539
- ctx,
4540
- _nullishCoalesce(((_a2 = jsRequest.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")), () => ( null))
4541
- );
4542
- } catch (error) {
4543
- return errorResponse(error, 401);
6126
+ const isPublicPerActorPath = jsRequest.method === "GET" && url.pathname.startsWith("/inspector/custom-tabs/");
6127
+ if (!isPublicPerActorPath) {
6128
+ try {
6129
+ await runtime.actorVerifyInspectorAuth(
6130
+ ctx,
6131
+ _nullishCoalesce(((_a2 = jsRequest.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")), () => ( null))
6132
+ );
6133
+ } catch (error) {
6134
+ return errorResponse(error, 401);
6135
+ }
4544
6136
  }
4545
6137
  const workflowHistory = () => {
4546
6138
  var _a3;
@@ -4553,6 +6145,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4553
6145
  return await _asyncNullishCoalesce(await ((_b2 = (_a3 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3)), async () => ( null));
4554
6146
  };
4555
6147
  const actorCtx = makeActorCtx(ctx, jsRequest);
6148
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
4556
6149
  try {
4557
6150
  if (url.pathname === "/inspector/state" && jsRequest.method === "GET") {
4558
6151
  return jsonResponse({
@@ -4607,6 +6200,47 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4607
6200
  messages
4608
6201
  });
4609
6202
  }
6203
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "DELETE") {
6204
+ await runtime.actorQueueReset(ctx);
6205
+ return jsonResponse({});
6206
+ }
6207
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "POST") {
6208
+ let body;
6209
+ try {
6210
+ body = await jsRequest.json();
6211
+ } catch (e5) {
6212
+ return errorResponse(
6213
+ new (0, _chunk2JSYYH6Pcjs.RivetError)(
6214
+ "actor",
6215
+ "invalid_request",
6216
+ "Invalid inspector JSON body",
6217
+ { public: true }
6218
+ ),
6219
+ 400
6220
+ );
6221
+ }
6222
+ const name = _nullishCoalesce(body.name, () => ( ""));
6223
+ if (name === "") {
6224
+ return errorResponse(
6225
+ new (0, _chunk2JSYYH6Pcjs.RivetError)(
6226
+ "actor",
6227
+ "invalid_request",
6228
+ "Queue message name must not be empty",
6229
+ { public: true }
6230
+ ),
6231
+ 400
6232
+ );
6233
+ }
6234
+ const cbor = _chunkEHZH3KUWcjs.encodeCborCompat.call(void 0,
6235
+ _nullishCoalesce(body.body, () => ( null))
6236
+ );
6237
+ const message = await runtime.actorQueueSend(ctx, name, cbor);
6238
+ return jsonResponse({
6239
+ id: message.id().toString(),
6240
+ name: message.name(),
6241
+ createdAtMs: message.createdAt()
6242
+ });
6243
+ }
4610
6244
  if (url.pathname === "/inspector/traces" && jsRequest.method === "GET") {
4611
6245
  return jsonResponse({ otlp: [], clamped: false });
4612
6246
  }
@@ -4631,13 +6265,17 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4631
6265
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0
4632
6266
  });
4633
6267
  } catch (error) {
6268
+ logger2().error({
6269
+ msg: "error replaying workflow history",
6270
+ error
6271
+ });
4634
6272
  return errorResponse(error);
4635
6273
  }
4636
6274
  }
4637
6275
  if (url.pathname === "/inspector/database/schema" && jsRequest.method === "GET") {
4638
- const db = actorCtx.sql;
6276
+ const db2 = sql;
4639
6277
  const tables = queryRows(
4640
- await db.query(
6278
+ await db2.query(
4641
6279
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name"
4642
6280
  )
4643
6281
  );
@@ -4645,13 +6283,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4645
6283
  for (const table of tables) {
4646
6284
  const quoted = `"${table.name.replace(/"/g, '""')}"`;
4647
6285
  const columns = queryRows(
4648
- await db.query(`PRAGMA table_info(${quoted})`)
6286
+ await db2.query(`PRAGMA table_info(${quoted})`)
4649
6287
  );
4650
6288
  const foreignKeys = queryRows(
4651
- await db.query(`PRAGMA foreign_key_list(${quoted})`)
6289
+ await db2.query(`PRAGMA foreign_key_list(${quoted})`)
4652
6290
  );
4653
6291
  const countResult = queryRows(
4654
- await db.query(
6292
+ await db2.query(
4655
6293
  `SELECT COUNT(*) as count FROM ${quoted}`
4656
6294
  )
4657
6295
  );
@@ -4686,7 +6324,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4686
6324
  );
4687
6325
  const quoted = `"${table.replace(/"/g, '""')}"`;
4688
6326
  const rows = queryRows(
4689
- await actorCtx.sql.query(
6327
+ await sql.query(
4690
6328
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
4691
6329
  [
4692
6330
  Math.max(0, Math.min(limit, 500)),
@@ -4714,15 +6352,11 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4714
6352
  const bindings = normalizeSqlitePropertyBindings(
4715
6353
  body.properties
4716
6354
  );
4717
- const rows2 = queryRows(
4718
- await actorCtx.sql.query(body.sql, bindings)
4719
- );
6355
+ const rows2 = queryRows(await sql.query(body.sql, bindings));
4720
6356
  return jsonResponse({ rows: jsonSafe(rows2) });
4721
6357
  }
4722
6358
  const args = Array.isArray(body.args) ? body.args : [];
4723
- const rows = queryRows(
4724
- await actorCtx.sql.query(body.sql, args)
4725
- );
6359
+ const rows = queryRows(await sql.query(body.sql, args));
4726
6360
  return jsonResponse({ rows: jsonSafe(rows) });
4727
6361
  }
4728
6362
  if (url.pathname === "/inspector/summary" && jsRequest.method === "GET") {
@@ -4748,7 +6382,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4748
6382
  rpcs: Object.keys(actionHandlers).sort(),
4749
6383
  queueSize: inspectorSnapshot.queueSize,
4750
6384
  isStateEnabled: stateEnabled,
4751
- isDatabaseEnabled: databaseProvider !== void 0,
6385
+ isDatabaseEnabled: true,
4752
6386
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0,
4753
6387
  workflowState: await workflowState(),
4754
6388
  workflowHistory: workflowHistory()
@@ -4762,7 +6396,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4762
6396
  const action = actionHandlers[actionName];
4763
6397
  if (!action) {
4764
6398
  return errorResponse(
4765
- new (0, _chunkQAZLM4WTcjs.RivetError)(
6399
+ new (0, _chunk2JSYYH6Pcjs.RivetError)(
4766
6400
  "action",
4767
6401
  "action_not_found",
4768
6402
  `Action ${actionName} not found`
@@ -4771,17 +6405,34 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4771
6405
  );
4772
6406
  }
4773
6407
  const body = await jsRequest.json();
6408
+ if (body.args !== void 0 && body.properties !== void 0) {
6409
+ return jsonResponse(
6410
+ { error: "use either args or properties, not both" },
6411
+ { status: 400 }
6412
+ );
6413
+ }
6414
+ if (body.properties !== void 0 && (body.properties === null || typeof body.properties !== "object" || Array.isArray(body.properties))) {
6415
+ return jsonResponse(
6416
+ { error: "properties must be an object" },
6417
+ { status: 400 }
6418
+ );
6419
+ }
6420
+ const args = body.properties !== void 0 ? [body.properties] : normalizeArgs(body.args);
4774
6421
  try {
4775
6422
  const output = await action(
4776
6423
  actorCtx,
4777
6424
  ...validateActionArgs(
4778
6425
  schemaConfig.actionInputSchemas,
4779
6426
  actionName,
4780
- _nullishCoalesce(body.args, () => ( []))
6427
+ args
4781
6428
  )
4782
6429
  );
4783
6430
  return jsonResponse({ output });
4784
6431
  } catch (error) {
6432
+ logger2().error({
6433
+ msg: "Error handling inspector action request",
6434
+ error
6435
+ });
4785
6436
  return errorResponse(error);
4786
6437
  }
4787
6438
  }
@@ -4795,6 +6446,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4795
6446
  { status: 404 }
4796
6447
  );
4797
6448
  } catch (error) {
6449
+ logger2().error({
6450
+ msg: "Error handling inspector request",
6451
+ error
6452
+ });
4798
6453
  return errorResponse(error);
4799
6454
  } finally {
4800
6455
  await actorCtx.dispose();
@@ -4917,25 +6572,34 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4917
6572
  async (error, payload) => {
4918
6573
  const { ctx } = unwrapTsfnPayload(error, payload);
4919
6574
  const actorCtx = makeActorCtx(ctx);
6575
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
6576
+ const saveActorState = async () => {
6577
+ if (runtime.kind === "wasm") {
6578
+ await runtime.actorSaveState(
6579
+ ctx,
6580
+ actorCtx.serializeForTick("save")
6581
+ );
6582
+ } else {
6583
+ await actorCtx.saveState({
6584
+ immediate: true
6585
+ });
6586
+ }
6587
+ };
4920
6588
  try {
4921
6589
  if (onSleep) {
4922
- try {
4923
- await onSleep(actorCtx);
4924
- } finally {
4925
- if (runtime.kind === "wasm") {
4926
- await runtime.actorSaveState(
4927
- ctx,
4928
- actorCtx.serializeForTick("save")
4929
- );
4930
- } else {
4931
- await actorCtx.saveState({ immediate: true });
4932
- }
4933
- }
6590
+ await onSleep(actorCtx);
4934
6591
  }
6592
+ await saveActorState();
4935
6593
  } finally {
4936
6594
  try {
4937
- await cleanupNativeSleepRuntimeState(runtime, ctx);
6595
+ await cleanupNativeSleepRuntimeState(
6596
+ runtime,
6597
+ ctx,
6598
+ saveActorState
6599
+ );
4938
6600
  } finally {
6601
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
6602
+ _chunk4KGXFC6Mcjs.disposeRunInspector.call(void 0, config.run, actorId);
4939
6603
  await actorCtx.dispose();
4940
6604
  }
4941
6605
  }
@@ -4945,6 +6609,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4945
6609
  async (error, payload) => {
4946
6610
  const { ctx } = unwrapTsfnPayload(error, payload);
4947
6611
  const actorCtx = makeActorCtx(ctx);
6612
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
6613
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
6614
+ _chunk4KGXFC6Mcjs.disposeRunInspector.call(void 0, config.run, actorId);
4948
6615
  try {
4949
6616
  if (typeof config.onDestroy === "function") {
4950
6617
  await config.onDestroy(actorCtx);
@@ -4965,7 +6632,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4965
6632
  );
4966
6633
  const actorCtx = makeActorCtx(
4967
6634
  ctx,
4968
- request ? buildRequest(request) : void 0
6635
+ request ? buildNativeHttpRequest(request) : void 0
4969
6636
  );
4970
6637
  try {
4971
6638
  await config.onBeforeConnect(
@@ -4985,7 +6652,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4985
6652
  const { ctx, conn, params, request } = unwrapTsfnPayload(error, payload);
4986
6653
  const actorCtx = makeActorCtx(
4987
6654
  ctx,
4988
- request ? buildRequest(request) : void 0
6655
+ request ? buildNativeHttpRequest(request) : void 0
4989
6656
  );
4990
6657
  const connAdapter = new NativeConnAdapter(
4991
6658
  runtime,
@@ -4997,7 +6664,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4997
6664
  ctx,
4998
6665
  connId
4999
6666
  )
5000
- )
6667
+ ),
6668
+ () => actorCtx.assertCanMutateState()
5001
6669
  );
5002
6670
  try {
5003
6671
  const nextConnState = hasStaticConnState ? structuredClone(config.connState) : await config.createConnState(
@@ -5022,7 +6690,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5022
6690
  );
5023
6691
  const actorCtx = makeActorCtx(
5024
6692
  ctx,
5025
- request ? buildRequest(request) : void 0
6693
+ request ? buildNativeHttpRequest(request) : void 0
5026
6694
  );
5027
6695
  const connAdapter = new NativeConnAdapter(
5028
6696
  runtime,
@@ -5034,7 +6702,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5034
6702
  ctx,
5035
6703
  connId
5036
6704
  )
5037
- )
6705
+ ),
6706
+ () => actorCtx.assertCanMutateState()
5038
6707
  );
5039
6708
  try {
5040
6709
  await config.onConnect(
@@ -5066,7 +6735,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5066
6735
  ctx,
5067
6736
  connId
5068
6737
  )
5069
- )
6738
+ ),
6739
+ () => actorCtx.assertCanMutateState()
5070
6740
  )
5071
6741
  );
5072
6742
  }
@@ -5099,7 +6769,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5099
6769
  );
5100
6770
  }
5101
6771
  if (!result) {
5102
- throw _chunkQAZLM4WTcjs.forbiddenError.call(void 0, );
6772
+ throw _chunk2JSYYH6Pcjs.forbiddenError.call(void 0, );
5103
6773
  }
5104
6774
  } finally {
5105
6775
  await actorCtx.dispose();
@@ -5127,27 +6797,45 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5127
6797
  onRequest: wrapNativeCallback(
5128
6798
  async (error, payload) => {
5129
6799
  try {
5130
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
5131
- error,
5132
- payload
5133
- );
5134
- const jsRequest = buildRequest(request);
5135
- const inspectorResponse = await maybeHandleNativeInspectorRequest(
5136
- ctx,
5137
- request,
5138
- jsRequest
5139
- );
6800
+ const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error, payload);
6801
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(ctx, request);
5140
6802
  if (inspectorResponse) {
5141
- return await toRuntimeHttpResponse(inspectorResponse);
6803
+ await cancelNativeHttpRequestBody(request.bodyStream);
6804
+ return (await convertNativeHttpResponse(
6805
+ inspectorResponse,
6806
+ responseBodyStream
6807
+ )).response;
5142
6808
  }
5143
6809
  if (typeof config.onRequest !== "function") {
5144
- return await toRuntimeHttpResponse(
5145
- new Response(null, { status: 404 })
5146
- );
6810
+ await cancelNativeHttpRequestBody(request.bodyStream);
6811
+ return (await convertNativeHttpResponse(
6812
+ new Response(null, { status: 404 }),
6813
+ responseBodyStream
6814
+ )).response;
5147
6815
  }
5148
- const rawConnParams = jsRequest.headers.get(_chunkYQQ2ZDKTcjs.HEADER_CONN_PARAMS);
6816
+ const requestAbortController = new AbortController();
6817
+ const handlerRequest = buildNativeHttpRequest({
6818
+ ...request,
6819
+ abortController: requestAbortController
6820
+ });
6821
+ const rawConnParams = handlerRequest.headers.get(_chunkAIL267JKcjs.HEADER_CONN_PARAMS);
5149
6822
  let requestCtx;
5150
6823
  let conn;
6824
+ let removeRequestAbortListener;
6825
+ let cleanupDeferredToBody = false;
6826
+ let cleanedUp = false;
6827
+ const cleanupRequest = async () => {
6828
+ if (cleanedUp) return;
6829
+ cleanedUp = true;
6830
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
6831
+ try {
6832
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
6833
+ } finally {
6834
+ if (conn) {
6835
+ await runtime.connDisconnect(conn);
6836
+ }
6837
+ }
6838
+ };
5151
6839
  try {
5152
6840
  const connParams = validateConnParams(
5153
6841
  schemaConfig.connParamsSchema,
@@ -5163,23 +6851,56 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5163
6851
  requestCtx = makeConnCtx(
5164
6852
  ctx,
5165
6853
  conn,
5166
- jsRequest,
6854
+ handlerRequest,
5167
6855
  cancelToken
5168
6856
  );
6857
+ const ctxAbortSignal = requestCtx.abortSignal;
6858
+ const abortRequest = () => requestAbortController.abort(ctxAbortSignal.reason);
6859
+ if (ctxAbortSignal.aborted) {
6860
+ abortRequest();
6861
+ } else {
6862
+ ctxAbortSignal.addEventListener(
6863
+ "abort",
6864
+ abortRequest,
6865
+ { once: true }
6866
+ );
6867
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
6868
+ "abort",
6869
+ abortRequest
6870
+ );
6871
+ }
5169
6872
  const response = await config.onRequest(
5170
6873
  requestCtx,
5171
- jsRequest
6874
+ handlerRequest
5172
6875
  );
5173
- if (!(response instanceof Response)) {
6876
+ if (!_chunkAIL267JKcjs.isResponseLike.call(void 0, response)) {
5174
6877
  throw new Error(
5175
6878
  "onRequest handler must return a Response"
5176
6879
  );
5177
6880
  }
5178
- return await toRuntimeHttpResponse(response);
6881
+ const conversion = await convertNativeHttpResponse(
6882
+ response,
6883
+ responseBodyStream
6884
+ );
6885
+ if (conversion.bodyCompletion) {
6886
+ cleanupDeferredToBody = true;
6887
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
6888
+ logger2().error({
6889
+ msg: "failed to clean up native streaming http request",
6890
+ error: cleanupError
6891
+ });
6892
+ });
6893
+ }
6894
+ return conversion.response;
5179
6895
  } finally {
5180
- await (requestCtx == null ? void 0 : requestCtx.dispose());
5181
- if (conn) {
5182
- await runtime.connDisconnect(conn);
6896
+ try {
6897
+ await cancelNativeHttpRequestBody(
6898
+ request.bodyStream
6899
+ );
6900
+ } finally {
6901
+ if (!cleanupDeferredToBody) {
6902
+ await cleanupRequest();
6903
+ }
5183
6904
  }
5184
6905
  }
5185
6906
  } catch (error2) {
@@ -5194,7 +6915,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5194
6915
  onWebSocket: typeof config.onWebSocket === "function" ? wrapNativeCallback(
5195
6916
  async (error, payload) => {
5196
6917
  const { ctx, conn, ws, request } = unwrapTsfnPayload(error, payload);
5197
- const jsRequest = request ? buildRequest(request) : void 0;
6918
+ const jsRequest = request ? buildNativeHttpRequest(request) : void 0;
5198
6919
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
5199
6920
  try {
5200
6921
  await config.onWebSocket(
@@ -5210,7 +6931,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5210
6931
  }
5211
6932
  ) : void 0,
5212
6933
  run: (() => {
5213
- const run = _chunkWQ4HNA4Wcjs.getRunFunction.call(void 0, config.run);
5214
6934
  if (!run) {
5215
6935
  return void 0;
5216
6936
  }
@@ -5218,26 +6938,38 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5218
6938
  async (error, payload) => {
5219
6939
  const { ctx } = unwrapTsfnPayload(error, payload);
5220
6940
  const actorId = callNativeSync(() => runtime.actorId(ctx));
5221
- const actorCtx = makeActorCtx(ctx);
5222
- nativeRunHandlerActiveByActorId.set(actorId, true);
5223
- try {
5224
- await run(actorCtx);
5225
- } finally {
5226
- nativeRunHandlerActiveByActorId.set(actorId, false);
5227
- await actorCtx.dispose();
6941
+ const executeRun = async () => {
6942
+ const actorCtx = makeActorCtx(ctx);
6943
+ try {
6944
+ await run(actorCtx);
6945
+ } finally {
6946
+ await actorCtx.dispose();
6947
+ }
6948
+ };
6949
+ if (runHandlerCoordinator) {
6950
+ const outcome = await runHandlerCoordinator.run(
6951
+ actorId,
6952
+ () => callNativeSync(
6953
+ () => runtime.actorRestartRunHandler(ctx)
6954
+ ),
6955
+ executeRun
6956
+ );
6957
+ return outcome !== "suppressed";
5228
6958
  }
6959
+ await executeRun();
6960
+ return true;
5229
6961
  }
5230
6962
  );
5231
6963
  })(),
5232
- getWorkflowHistory: _chunkWQ4HNA4Wcjs.getRunInspectorConfig.call(void 0, config.run) !== void 0 ? wrapNativeCallback(
6964
+ getWorkflowHistory: _chunk4KGXFC6Mcjs.hasRunInspectorConfig.call(void 0, config.run) ? wrapNativeCallback(
5233
6965
  async (error, payload) => {
5234
6966
  var _a2;
5235
6967
  const { ctx } = unwrapTsfnPayload(error, payload);
5236
6968
  const history = (_a2 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a2.getHistory();
5237
- return history == null ? void 0 : encodeValue(history);
6969
+ return history == null ? void 0 : _chunkEHZH3KUWcjs.toUint8Array.call(void 0, history);
5238
6970
  }
5239
6971
  ) : void 0,
5240
- replayWorkflow: _chunkWQ4HNA4Wcjs.getRunInspectorConfig.call(void 0, config.run) !== void 0 ? wrapNativeCallback(
6972
+ replayWorkflow: _chunk4KGXFC6Mcjs.hasRunInspectorConfig.call(void 0, config.run) ? wrapNativeCallback(
5241
6973
  async (error, payload) => {
5242
6974
  const { ctx, entryId } = unwrapTsfnPayload(
5243
6975
  error,
@@ -5247,10 +6979,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5247
6979
  if (!(workflowInspector == null ? void 0 : workflowInspector.replayFromStep)) {
5248
6980
  return void 0;
5249
6981
  }
5250
- const history = await _asyncNullishCoalesce(await workflowInspector.replayFromStep(
5251
- entryId
5252
- ), async () => ( null));
5253
- return history == null ? void 0 : encodeValue(history);
6982
+ const history = await _asyncNullishCoalesce(await workflowInspector.replayFromStep(entryId), async () => ( null));
6983
+ return history == null ? void 0 : _chunkEHZH3KUWcjs.toUint8Array.call(void 0, history);
5254
6984
  }
5255
6985
  ) : void 0,
5256
6986
  actions: Object.fromEntries(
@@ -5258,7 +6988,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5258
6988
  name,
5259
6989
  wrapNativeCallback(
5260
6990
  async (error, payload) => {
5261
- const { ctx, conn, args, cancelToken } = unwrapTsfnPayload(error, payload);
6991
+ const { ctx, conn, args, scheduledFire, cancelToken } = unwrapTsfnPayload(error, payload);
5262
6992
  const actorCtx = conn != null ? makeConnCtx(ctx, conn, void 0, cancelToken) : makeActorCtx(ctx, void 0, cancelToken);
5263
6993
  try {
5264
6994
  return encodeValue(
@@ -5268,7 +6998,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5268
6998
  schemaConfig.actionInputSchemas,
5269
6999
  name,
5270
7000
  decodeArgs(args)
5271
- )
7001
+ ),
7002
+ ...scheduledFire ? [scheduledFire] : []
5272
7003
  )
5273
7004
  );
5274
7005
  } finally {
@@ -5290,7 +7021,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5290
7021
  timeoutMs,
5291
7022
  cancelToken
5292
7023
  } = unwrapTsfnPayload(error, payload);
5293
- const jsRequest = buildRequest(request);
7024
+ const jsRequest = buildNativeHttpRequest(request);
5294
7025
  const actorCtx = withConnContext(
5295
7026
  runtime,
5296
7027
  ctx,
@@ -5301,7 +7032,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5301
7032
  jsRequest,
5302
7033
  stateEnabled,
5303
7034
  onStateChange,
5304
- cancelToken
7035
+ cancelToken,
7036
+ run !== void 0
5305
7037
  );
5306
7038
  try {
5307
7039
  if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
@@ -5312,7 +7044,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5312
7044
  name
5313
7045
  );
5314
7046
  if (canPublish && !await canPublish(actorCtx)) {
5315
- throw _chunkQAZLM4WTcjs.forbiddenError.call(void 0, );
7047
+ throw _chunk2JSYYH6Pcjs.forbiddenError.call(void 0, );
5316
7048
  }
5317
7049
  const decodedBody = decodeValue(body);
5318
7050
  if (wait) {
@@ -5356,10 +7088,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5356
7088
  };
5357
7089
  return runtime.createActorFactory(
5358
7090
  callbacks,
5359
- buildActorConfig(definition, registryConfig)
7091
+ buildActorConfig(definition, registryConfig, runtime.kind)
5360
7092
  );
5361
7093
  }
5362
- async function buildServeConfig(config) {
7094
+ async function buildServeConfig(config, resolveServicesBinary = true) {
5363
7095
  var _a;
5364
7096
  if (!config.endpoint) {
5365
7097
  throw nativeEndpointNotConfiguredError();
@@ -5370,29 +7102,51 @@ async function buildServeConfig(config) {
5370
7102
  token: config.token,
5371
7103
  namespace: config.namespace,
5372
7104
  poolName: config.envoy.poolName,
7105
+ startServices: resolveServicesBinary && config.startServices,
5373
7106
  handleInspectorHttpInRuntime: true,
5374
7107
  serverlessBasePath: config.serverless.basePath,
5375
- serverlessPackageVersion: _chunkO25KOT5Ccjs.VERSION,
7108
+ serverlessPackageVersion: _chunkEHZH3KUWcjs.VERSION,
5376
7109
  serverlessClientEndpoint: config.publicEndpoint,
5377
7110
  serverlessClientNamespace: config.publicNamespace,
5378
7111
  serverlessClientToken: config.publicToken,
5379
7112
  serverlessValidateEndpoint: config.validateServerlessEndpoint,
5380
7113
  serverlessMaxStartPayloadBytes: config.serverless.maxStartPayloadBytes
5381
7114
  };
5382
- if (config.startEngine) {
7115
+ try {
5383
7116
  const { getEnginePath } = await loadEngineCli();
5384
7117
  serveConfig.engineBinaryPath = getEnginePath();
7118
+ } catch (error) {
7119
+ logger2().warn({
7120
+ msg: "could not resolve a local engine binary; if a local engine must be spawned it will fail with engine.binary_unavailable \u2014 set RIVET_ENGINE_BINARY_PATH or install the @rivetkit/engine-cli platform package",
7121
+ error: _chunkEHZH3KUWcjs.stringifyError.call(void 0, error)
7122
+ });
5385
7123
  }
7124
+ if (resolveServicesBinary && config.startServices) {
7125
+ try {
7126
+ const { getServicesPath } = await loadServices();
7127
+ serveConfig.servicesBinaryPath = getServicesPath();
7128
+ } catch (error) {
7129
+ logger2().warn({
7130
+ msg: "could not resolve the Services binary; a local engine will fail with services.binary_unavailable \u2014 set RIVET_RUN_SERVICES=0 to disable Services or RIVET_SERVICES_BINARY to a local rivet-services binary",
7131
+ error: _chunkEHZH3KUWcjs.stringifyError.call(void 0, error)
7132
+ });
7133
+ }
7134
+ }
7135
+ serveConfig.engineHost = config.engineHost;
7136
+ serveConfig.enginePort = config.enginePort;
5386
7137
  if ((_a = config.test) == null ? void 0 : _a.enabled) {
5387
- serveConfig.inspectorTestToken = _nullishCoalesce(_chunkO25KOT5Ccjs.getEnvUniversal.call(void 0, "_RIVET_TEST_INSPECTOR_TOKEN"), () => ( "token"));
7138
+ serveConfig.inspectorTestToken = _nullishCoalesce(_chunkEHZH3KUWcjs.getEnvUniversal.call(void 0, "_RIVET_TEST_INSPECTOR_TOKEN"), () => ( "token"));
5388
7139
  }
5389
7140
  return serveConfig;
5390
7141
  }
5391
7142
  async function buildRegistryWithRuntime(config, runtime) {
5392
7143
  var _a;
5393
- if (((_a = config.test) == null ? void 0 : _a.enabled) && _chunkO25KOT5Ccjs.getEnvUniversal.call(void 0, "_RIVET_TEST_INSPECTOR_TOKEN") === void 0) {
7144
+ if (((_a = config.test) == null ? void 0 : _a.enabled) && _chunkEHZH3KUWcjs.getEnvUniversal.call(void 0, "_RIVET_TEST_INSPECTOR_TOKEN") === void 0) {
5394
7145
  trySetProcessEnv("_RIVET_TEST_INSPECTOR_TOKEN", "token");
5395
7146
  }
7147
+ if (runtime.kind === "napi") {
7148
+ importNodeDependencies();
7149
+ }
5396
7150
  const registry = runtime.createRegistry();
5397
7151
  for (const [name, definition] of Object.entries(config.use)) {
5398
7152
  runtime.registerActor(
@@ -5404,7 +7158,7 @@ async function buildRegistryWithRuntime(config, runtime) {
5404
7158
  return {
5405
7159
  runtime,
5406
7160
  registry,
5407
- serveConfig: await buildServeConfig(config)
7161
+ serveConfig: await buildServeConfig(config, runtime.kind === "napi")
5408
7162
  };
5409
7163
  }
5410
7164
  async function buildConfiguredRegistry(config) {
@@ -5416,8 +7170,73 @@ async function buildConfiguredRegistry(config) {
5416
7170
  }
5417
7171
 
5418
7172
  // src/registry/index.ts
7173
+ var REGISTRY_READY_TIMEOUT_MS = 3e4;
7174
+ function signalExitCode(signal) {
7175
+ switch (signal) {
7176
+ case "SIGINT":
7177
+ return 130;
7178
+ case "SIGTERM":
7179
+ return 143;
7180
+ }
7181
+ }
7182
+ function finishShutdownSignal(signal) {
7183
+ if (process.pid === 1) {
7184
+ process.exit(signalExitCode(signal));
7185
+ }
7186
+ process.kill(process.pid, signal);
7187
+ }
7188
+ function createApplicationFetch(application, runtime) {
7189
+ return async (request, responseBodyStream) => {
7190
+ const method2 = request.method.toUpperCase();
7191
+ const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
7192
+ const abortController = new AbortController();
7193
+ if (request.cancelToken) {
7194
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
7195
+ abortController.abort();
7196
+ } else {
7197
+ runtime.onCancellationTokenCancelled(
7198
+ request.cancelToken,
7199
+ () => abortController.abort()
7200
+ );
7201
+ }
7202
+ }
7203
+ const response = await application.fetch(
7204
+ new Request(request.url, {
7205
+ method: method2,
7206
+ headers: request.headers,
7207
+ body,
7208
+ signal: abortController.signal
7209
+ })
7210
+ );
7211
+ if (!_chunkAIL267JKcjs.isResponseLike.call(void 0, response)) {
7212
+ throw new TypeError(
7213
+ "registry.listen() application fetch must return a Response"
7214
+ );
7215
+ }
7216
+ const conversion = await convertNativeHttpResponse(
7217
+ response,
7218
+ responseBodyStream
7219
+ );
7220
+ if (conversion.bodyCompletion) {
7221
+ void conversion.bodyCompletion.catch((error) => {
7222
+ logger2().error({
7223
+ msg: "application response stream failed",
7224
+ error
7225
+ });
7226
+ });
7227
+ }
7228
+ return {
7229
+ status: _nullishCoalesce(conversion.response.status, () => ( response.status)),
7230
+ headers: _nullishCoalesce(conversion.response.headers, () => ( Object.fromEntries(response.headers.entries()))),
7231
+ body: conversion.response.body,
7232
+ stream: conversion.response.stream
7233
+ };
7234
+ };
7235
+ }
5419
7236
  var Registry = class {
5420
7237
  #config;
7238
+ #buildConfiguredRegistry;
7239
+
5421
7240
  get config() {
5422
7241
  return this.#config;
5423
7242
  }
@@ -5425,25 +7244,44 @@ var Registry = class {
5425
7244
  return RegistryConfigSchema.parse(this.#config);
5426
7245
  }
5427
7246
  #runtimeServePromise;
7247
+ #runtimeServeLifecyclePromise;
7248
+ #runtimeReadyPromise;
5428
7249
  #runtimeServeConfiguredPromise;
5429
7250
  #runtimeServerlessPromise;
7251
+ #applicationListenerPromise;
5430
7252
  #configureServerlessPoolPromise;
5431
7253
  #welcomePrinted = false;
5432
7254
  #shutdownInstalled = false;
5433
7255
  #shutdownInFlight = null;
5434
7256
  #signalHandlers = {};
5435
- constructor(config) {
7257
+ constructor(config, deps) {
7258
+ var _a;
5436
7259
  this.#config = config;
7260
+ if ((_a = config.logging) == null ? void 0 : _a.baseLogger) {
7261
+ _chunkEHZH3KUWcjs.configureBaseLogger.call(void 0, config.logging.baseLogger);
7262
+ }
7263
+ this.#buildConfiguredRegistry = _nullishCoalesce((deps == null ? void 0 : deps.buildConfiguredRegistry), () => ( buildConfiguredRegistry));
7264
+ this.routes = {
7265
+ health: () => this.#healthRoute(),
7266
+ metadata: () => this.#metadataRoute(),
7267
+ prometheusMetrics: (request) => this.#prometheusMetricsRoute(request)
7268
+ };
5437
7269
  }
7270
+ /**
7271
+ * Fires `configureServerlessPool` once per process when the registry
7272
+ * config opts into it. Cached on the instance so repeated calls (from
7273
+ * `handler()` and `listen()`) only run the upsert once. The retry loop
7274
+ * inside `configureServerlessPool` tolerates the engine still warming up.
7275
+ */
5438
7276
  #ensureServerlessPoolConfigured(config) {
5439
7277
  if (!config.configurePool) return void 0;
5440
7278
  if (!this.#configureServerlessPoolPromise) {
5441
- this.#configureServerlessPoolPromise = configureServerlessPool(config).catch(
5442
- (error) => {
5443
- this.#configureServerlessPoolPromise = void 0;
5444
- throw error;
5445
- }
5446
- );
7279
+ this.#configureServerlessPoolPromise = configureServerlessPool(
7280
+ config
7281
+ ).catch((error) => {
7282
+ this.#configureServerlessPoolPromise = void 0;
7283
+ throw error;
7284
+ });
5447
7285
  this.#configureServerlessPoolPromise.catch(() => {
5448
7286
  });
5449
7287
  }
@@ -5464,7 +7302,7 @@ var Registry = class {
5464
7302
  const config = this.parseConfig();
5465
7303
  this.#printWelcome(config, "serverless");
5466
7304
  if (!this.#runtimeServerlessPromise) {
5467
- this.#runtimeServerlessPromise = buildConfiguredRegistry(config);
7305
+ this.#runtimeServerlessPromise = this.#buildConfiguredRegistry(config);
5468
7306
  }
5469
7307
  const { runtime, registry, serveConfig } = await this.#runtimeServerlessPromise;
5470
7308
  const isStartRequest = isServerlessStartRequest(
@@ -5479,7 +7317,7 @@ var Registry = class {
5479
7317
  if (isStartRequest) {
5480
7318
  try {
5481
7319
  await this.#ensureServerlessPoolConfigured(config);
5482
- } catch (error) {
7320
+ } catch (_error) {
5483
7321
  return new Response(
5484
7322
  JSON.stringify({
5485
7323
  group: "guard",
@@ -5593,7 +7431,7 @@ var Registry = class {
5593
7431
  if (isMetadataRequest && !isEngineMetadataRequest) {
5594
7432
  try {
5595
7433
  await this.#ensureServerlessPoolConfigured(config);
5596
- } catch (error) {
7434
+ } catch (_error) {
5597
7435
  return new Response(
5598
7436
  JSON.stringify({
5599
7437
  group: "guard",
@@ -5626,40 +7464,202 @@ var Registry = class {
5626
7464
  fetch: (request) => this.handler(request)
5627
7465
  };
5628
7466
  }
5629
- async diagnostics() {
5630
- var _a;
7467
+ /**
7468
+ * Bind an HTTP listener provided by the native (Rust) runtime and serve
7469
+ * the registry's serverless endpoints over it. Resolves only after the
7470
+ * registry is shut down (SIGINT/SIGTERM or `nativeRegistry.shutdown()`).
7471
+ *
7472
+ * @param opts.port Port to listen on. Defaults to `process.env.RIVET_PORT`
7473
+ * if set, otherwise 3000.
7474
+ * @param opts.host Address to bind. Defaults to `0.0.0.0`.
7475
+ * @param opts.publicDir If set, serves static files from this directory
7476
+ * as a fallback below the framework routes.
7477
+ * @param opts.application If set, handles requests that do not match a
7478
+ * framework route.
7479
+ *
7480
+ * @example
7481
+ * ```ts
7482
+ * await registry.listen();
7483
+ * await registry.listen({ application: app });
7484
+ * ```
7485
+ */
7486
+ async listen(opts = {}) {
7487
+ const port = _nullishCoalesce(_nullishCoalesce(opts.port, () => ( _chunkEHZH3KUWcjs.parsePortEnv.call(void 0, process.env.RIVET_PORT))), () => ( 3e3));
7488
+ const publicDir = _nullishCoalesce(opts.publicDir, () => ( _chunkEHZH3KUWcjs.getRivetkitPublicDir.call(void 0, )));
7489
+ const config = this.parseConfig();
7490
+ if (opts.application && _chunkEHZH3KUWcjs.getRivetkitRuntimeMode.call(void 0, ) !== "serverless") {
7491
+ if (config.runtime === "wasm") {
7492
+ throw new Error(
7493
+ "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
7494
+ );
7495
+ }
7496
+ this.#installSignalHandlers(config);
7497
+ this.#printWelcome(config, "serverful", {
7498
+ port,
7499
+ host: opts.host,
7500
+ publicDir
7501
+ });
7502
+ this.#startEnvoy(config, true);
7503
+ const readyPromise = this.startAndWait();
7504
+ const configuredRegistryPromise2 = this.#runtimeServeConfiguredPromise;
7505
+ if (!configuredRegistryPromise2) {
7506
+ throw new Error("registry envoy startup did not initialize");
7507
+ }
7508
+ const { runtime: runtime2, registry: registry2, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
7509
+ const application2 = createApplicationFetch(
7510
+ opts.application,
7511
+ runtime2
7512
+ );
7513
+ await readyPromise;
7514
+ const listenerPromise = runtime2.serveApplicationListener(
7515
+ registry2,
7516
+ {
7517
+ port,
7518
+ host: opts.host,
7519
+ publicDir,
7520
+ application: application2
7521
+ },
7522
+ serveConfig2
7523
+ );
7524
+ this.#applicationListenerPromise = listenerPromise;
7525
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
7526
+ if (!serveLifecyclePromise) {
7527
+ throw new Error(
7528
+ "registry envoy serve lifecycle did not initialize"
7529
+ );
7530
+ }
7531
+ await Promise.all([listenerPromise, serveLifecyclePromise]);
7532
+ return;
7533
+ }
7534
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
7535
+ this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
7536
+ this.#runtimeServerlessPromise = configuredRegistryPromise;
7537
+ this.#installSignalHandlers(config);
7538
+ this.#printWelcome(config, "serverless", {
7539
+ port,
7540
+ host: opts.host,
7541
+ publicDir
7542
+ });
7543
+ this.#ensureServerlessPoolConfigured(config);
7544
+ const { runtime, registry, serveConfig } = await configuredRegistryPromise;
7545
+ const application = opts.application ? createApplicationFetch(opts.application, runtime) : void 0;
7546
+ await runtime.serveListener(
7547
+ registry,
7548
+ {
7549
+ port,
7550
+ host: opts.host,
7551
+ publicDir,
7552
+ application
7553
+ },
7554
+ serveConfig
7555
+ );
7556
+ }
7557
+ /**
7558
+ * Returns a health response suitable for mounting in a user-owned router.
7559
+ */
7560
+ async #healthRoute() {
7561
+ const configured = await this.#activeConfiguredRegistry();
7562
+ if (!configured) {
7563
+ return jsonRouteResponse(503, {
7564
+ status: "not_started",
7565
+ runtime: "rivetkit",
7566
+ version: _chunkEHZH3KUWcjs.VERSION
7567
+ });
7568
+ }
7569
+ const { runtime, registry } = configured;
7570
+ if (!runtime.registryHealth) {
7571
+ return jsonRouteResponse(501, {
7572
+ status: "unsupported",
7573
+ runtime: "rivetkit",
7574
+ version: _chunkEHZH3KUWcjs.VERSION
7575
+ });
7576
+ }
7577
+ const response = await runtime.registryHealth(registry);
7578
+ return new Response(new Uint8Array(response.body), {
7579
+ status: response.status,
7580
+ headers: response.headers
7581
+ });
7582
+ }
7583
+ /**
7584
+ * Returns serverless metadata suitable for mounting in a user-owned router.
7585
+ */
7586
+ async #metadataRoute() {
7587
+ const configured = await this.#activeConfiguredRegistry();
7588
+ if (!configured) {
7589
+ return new Response("registry not started\n", {
7590
+ status: 503,
7591
+ headers: { "content-type": "text/plain; charset=utf-8" }
7592
+ });
7593
+ }
7594
+ const { runtime, registry } = configured;
7595
+ if (!runtime.registryMetadata) {
7596
+ return new Response("metadata is not supported by this runtime\n", {
7597
+ status: 501,
7598
+ headers: { "content-type": "text/plain; charset=utf-8" }
7599
+ });
7600
+ }
7601
+ const response = await runtime.registryMetadata(registry);
7602
+ return new Response(new Uint8Array(response.body), {
7603
+ status: response.status,
7604
+ headers: response.headers
7605
+ });
7606
+ }
7607
+ /**
7608
+ * Returns a Prometheus metrics response suitable for mounting in a user-owned router.
7609
+ */
7610
+ async #prometheusMetricsRoute(_request) {
7611
+ const configured = await this.#activeConfiguredRegistry();
7612
+ if (!configured) {
7613
+ return new Response("registry not started\n", {
7614
+ status: 503,
7615
+ headers: { "content-type": "text/plain; charset=utf-8" }
7616
+ });
7617
+ }
7618
+ const { runtime, registry } = configured;
7619
+ if (!runtime.registryMetrics) {
7620
+ return new Response("metrics are not supported by this runtime\n", {
7621
+ status: 501,
7622
+ headers: { "content-type": "text/plain; charset=utf-8" }
7623
+ });
7624
+ }
7625
+ const response = await runtime.registryMetrics(registry);
7626
+ return new Response(new Uint8Array(response.body), {
7627
+ status: response.status,
7628
+ headers: response.headers
7629
+ });
7630
+ }
7631
+ async #activeConfiguredRegistry() {
5631
7632
  const candidates = [
5632
7633
  this.#runtimeServerlessPromise,
5633
7634
  this.#runtimeServeConfiguredPromise
5634
7635
  ].filter(
5635
7636
  (candidate) => candidate !== void 0
5636
7637
  );
5637
- for (const candidate of candidates) {
5638
- const { runtime, registry } = await candidate;
5639
- const diagnostics = await ((_a = runtime.registryDiagnostics) == null ? void 0 : _a.call(runtime, registry));
5640
- if (diagnostics) return diagnostics;
5641
- }
5642
- return { mode: "not_started", envoyActiveActorCount: null };
7638
+ if (candidates.length === 0) return void 0;
7639
+ return await candidates[0];
5643
7640
  }
5644
7641
  /**
5645
7642
  * Starts an actor envoy for standalone server deployments.
5646
7643
  */
5647
7644
  #startEnvoy(config, printWelcome) {
5648
7645
  if (!this.#runtimeServePromise) {
5649
- const configuredRegistryPromise = buildConfiguredRegistry(config);
7646
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
5650
7647
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
5651
- this.#runtimeServePromise = configuredRegistryPromise.then(async ({ runtime, registry, serveConfig }) => {
5652
- await runtime.serveRegistry(registry, serveConfig);
5653
- }).catch((err) => {
5654
- logger2().warn({ err }, "runtime registry serve errored");
7648
+ this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(
7649
+ async ({ runtime, registry, serveConfig }) => {
7650
+ await runtime.serveRegistry(registry, serveConfig);
7651
+ }
7652
+ );
7653
+ this.#runtimeServePromise = this.#runtimeServeLifecyclePromise.catch((error) => {
7654
+ logger2().warn({ error }, "runtime registry serve errored");
5655
7655
  });
5656
- this.#installSignalHandlers(config, configuredRegistryPromise);
7656
+ this.#installSignalHandlers(config);
5657
7657
  }
5658
7658
  if (printWelcome) {
5659
7659
  this.#printWelcome(config, "serverful");
5660
7660
  }
5661
7661
  }
5662
- #installSignalHandlers(config, configuredRegistryPromise) {
7662
+ #installSignalHandlers(config) {
5663
7663
  var _a;
5664
7664
  if (this.#shutdownInstalled) return;
5665
7665
  if ((_a = config.shutdown) == null ? void 0 : _a.disableSignalHandlers) return;
@@ -5668,58 +7668,86 @@ var Registry = class {
5668
7668
  }
5669
7669
  this.#shutdownInstalled = true;
5670
7670
  const install = (signal) => {
5671
- const handler = () => this.#onShutdownSignal(
5672
- signal,
5673
- config,
5674
- configuredRegistryPromise
5675
- );
7671
+ const handler = () => this.#onShutdownSignal(signal, config);
5676
7672
  this.#signalHandlers[signal] = handler;
5677
7673
  process.on(signal, handler);
5678
7674
  };
5679
7675
  install("SIGINT");
5680
7676
  install("SIGTERM");
5681
7677
  }
5682
- #onShutdownSignal(signal, config, configuredRegistryPromise) {
7678
+ #onShutdownSignal(signal, config) {
5683
7679
  if (this.#shutdownInFlight !== null) {
5684
7680
  this.#removeSignalHandlers();
5685
- process.kill(process.pid, signal);
7681
+ finishShutdownSignal(signal);
5686
7682
  return;
5687
7683
  }
5688
- this.#shutdownInFlight = this.#runShutdown(
5689
- signal,
5690
- config,
5691
- configuredRegistryPromise
5692
- ).catch((err) => {
7684
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
7685
+ logger2().warn({ err }, "shutdown error");
7686
+ }).then(() => {
7687
+ this.#removeSignalHandlers();
7688
+ finishShutdownSignal(signal);
7689
+ });
7690
+ }
7691
+ /**
7692
+ * Gracefully drains all live registries.
7693
+ *
7694
+ * Programmatic counterpart to the SIGINT/SIGTERM handlers: tears down
7695
+ * every live `CoreRegistry` (both `start()` and `handler()` modes) and
7696
+ * waits for the serve promise to resolve, all bounded by the shutdown
7697
+ * grace period. Unlike a signal-driven shutdown, this does not re-raise a
7698
+ * signal or exit the process. The caller owns process lifetime.
7699
+ *
7700
+ * Idempotent: concurrent or repeated calls share a single drain. Safe to
7701
+ * call even if nothing has been started.
7702
+ *
7703
+ * @example
7704
+ * ```ts
7705
+ * const registry = setup({ use: { counter } });
7706
+ * registry.start();
7707
+ * // ...later, on your own shutdown trigger:
7708
+ * await registry.shutdown();
7709
+ * ```
7710
+ */
7711
+ async shutdown() {
7712
+ if (this.#shutdownInFlight !== null) return this.#shutdownInFlight;
7713
+ const config = this.parseConfig();
7714
+ this.#removeSignalHandlers();
7715
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
5693
7716
  logger2().warn({ err }, "shutdown error");
5694
7717
  });
7718
+ return this.#shutdownInFlight;
5695
7719
  }
5696
- async #runShutdown(signal, config, configuredRegistryPromise) {
7720
+ async #drain(config) {
5697
7721
  var _a;
5698
- const gracePeriodMs = _nullishCoalesce(((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs), () => ( 3e4));
7722
+ const modeAPromise = this.#runtimeServeConfiguredPromise;
7723
+ const modeBPromise = this.#runtimeServerlessPromise;
7724
+ const gracePeriodMs = await _asyncNullishCoalesce(await _asyncNullishCoalesce(((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs), async () => ( await this.#actorStopThresholdMs(_nullishCoalesce(modeAPromise, () => ( modeBPromise))))), async () => ( 30 * 60 * 1e3));
5699
7725
  const drain = async () => {
5700
- const registries = [
5701
- (async () => {
5702
- try {
5703
- const { runtime, registry } = await configuredRegistryPromise;
5704
- await runtime.shutdownRegistry(registry);
5705
- } catch (err) {
5706
- logger2().warn(
5707
- { err },
5708
- "runtime registry shutdown errored (mode A)"
5709
- );
5710
- }
5711
- })()
5712
- ];
5713
- const runtimeServerlessPromise = this.#runtimeServerlessPromise;
5714
- if (runtimeServerlessPromise !== void 0) {
7726
+ const registries = [];
7727
+ if (modeAPromise !== void 0) {
5715
7728
  registries.push(
5716
7729
  (async () => {
5717
7730
  try {
5718
- const { runtime, registry } = await runtimeServerlessPromise;
7731
+ const { runtime, registry } = await modeAPromise;
5719
7732
  await runtime.shutdownRegistry(registry);
5720
7733
  } catch (err) {
5721
7734
  logger2().warn(
5722
7735
  { err },
7736
+ "runtime registry shutdown errored (mode A)"
7737
+ );
7738
+ }
7739
+ })()
7740
+ );
7741
+ }
7742
+ if (modeBPromise !== void 0) {
7743
+ registries.push(
7744
+ (async () => {
7745
+ try {
7746
+ const { runtime, registry } = await modeBPromise;
7747
+ await runtime.shutdownRegistry(registry);
7748
+ } catch (err) {
7749
+ logger2().warn(
7750
+ { error: err },
5723
7751
  "runtime registry shutdown errored (mode B)"
5724
7752
  );
5725
7753
  }
@@ -5731,6 +7759,9 @@ var Registry = class {
5731
7759
  if (runtimeServePromise !== void 0) {
5732
7760
  await runtimeServePromise.catch(() => void 0);
5733
7761
  }
7762
+ if (this.#applicationListenerPromise !== void 0) {
7763
+ await this.#applicationListenerPromise.catch(() => void 0);
7764
+ }
5734
7765
  };
5735
7766
  await Promise.race([
5736
7767
  drain(),
@@ -5741,8 +7772,23 @@ var Registry = class {
5741
7772
  }
5742
7773
  )
5743
7774
  ]);
5744
- this.#removeSignalHandlers();
5745
- process.kill(process.pid, signal);
7775
+ }
7776
+ async #actorStopThresholdMs(configuredRegistryPromise) {
7777
+ var _a;
7778
+ if (configuredRegistryPromise === void 0) return void 0;
7779
+ try {
7780
+ const { runtime, registry } = await configuredRegistryPromise;
7781
+ const thresholdMs = await ((_a = runtime.registryActorStopThresholdMs) == null ? void 0 : _a.call(runtime, registry));
7782
+ if (thresholdMs !== void 0 && Number.isFinite(thresholdMs) && thresholdMs > 0) {
7783
+ return thresholdMs;
7784
+ }
7785
+ } catch (err) {
7786
+ logger2().warn(
7787
+ { err },
7788
+ "failed to read actor stop threshold for shutdown grace"
7789
+ );
7790
+ }
7791
+ return void 0;
5746
7792
  }
5747
7793
  #removeSignalHandlers() {
5748
7794
  for (const [signal, handler] of Object.entries(
@@ -5755,9 +7801,86 @@ var Registry = class {
5755
7801
  startEnvoy() {
5756
7802
  this.#startEnvoy(this.parseConfig(), true);
5757
7803
  }
7804
+ /**
7805
+ * Starts the serverful registry if needed and waits until its envoy has
7806
+ * registered with the Engine. Repeated and concurrent calls share one
7807
+ * startup lifecycle and readiness promise.
7808
+ *
7809
+ * Unlike {@link start}, this reports startup failures and does not resolve
7810
+ * merely because an HTTP health endpoint is listening.
7811
+ */
7812
+ startAndWait() {
7813
+ if (this.#shutdownInFlight !== null) {
7814
+ return Promise.reject(
7815
+ new Error(
7816
+ "registry.startAndWait() cannot run after shutdown has begun"
7817
+ )
7818
+ );
7819
+ }
7820
+ if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
7821
+ if (_chunkEHZH3KUWcjs.getRivetkitRuntimeMode.call(void 0, ) === "serverless") {
7822
+ return Promise.reject(
7823
+ new Error(
7824
+ "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request"
7825
+ )
7826
+ );
7827
+ }
7828
+ const config = this.parseConfig();
7829
+ if (config.runtime === "wasm") {
7830
+ return Promise.reject(
7831
+ new Error(
7832
+ "registry.startAndWait() requires the native runtime; WebAssembly registries do not host an envoy"
7833
+ )
7834
+ );
7835
+ }
7836
+ this.#startEnvoy(config, true);
7837
+ const configuredRegistryPromise = this.#runtimeServeConfiguredPromise;
7838
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
7839
+ if (!configuredRegistryPromise || !serveLifecyclePromise) {
7840
+ throw new Error("registry envoy startup did not initialize");
7841
+ }
7842
+ let timeout;
7843
+ const timeoutPromise = new Promise((_resolve, reject) => {
7844
+ var _a;
7845
+ timeout = setTimeout(
7846
+ () => reject(
7847
+ new Error(
7848
+ `RivetKit registry did not register with the Engine within ${REGISTRY_READY_TIMEOUT_MS}ms`
7849
+ )
7850
+ ),
7851
+ REGISTRY_READY_TIMEOUT_MS
7852
+ );
7853
+ (_a = timeout.unref) == null ? void 0 : _a.call(timeout);
7854
+ });
7855
+ const readinessPromise = (async () => {
7856
+ const { runtime, registry } = await configuredRegistryPromise;
7857
+ const stoppedBeforeReady = serveLifecyclePromise.then(() => {
7858
+ throw new Error(
7859
+ "RivetKit registry stopped before becoming ready"
7860
+ );
7861
+ });
7862
+ await Promise.race([
7863
+ runtime.waitRegistryReady(registry),
7864
+ stoppedBeforeReady
7865
+ ]);
7866
+ })();
7867
+ this.#runtimeReadyPromise = Promise.race([
7868
+ readinessPromise,
7869
+ timeoutPromise
7870
+ ]).finally(() => {
7871
+ if (timeout !== void 0) clearTimeout(timeout);
7872
+ });
7873
+ this.#runtimeReadyPromise.catch(() => {
7874
+ });
7875
+ return this.#runtimeReadyPromise;
7876
+ }
5758
7877
  /**
5759
7878
  * Starts the actor envoy for standalone server deployments.
5760
7879
  *
7880
+ * Set `RIVETKIT_RUNTIME_MODE=serverless` to instead bind an HTTP listener
7881
+ * via `listen()` (Mode B). Mode A (envoy) and Mode B (listener) are
7882
+ * mutually exclusive per registry instance.
7883
+ *
5761
7884
  * @example
5762
7885
  * ```ts
5763
7886
  * const registry = setup({ use: { counter } });
@@ -5765,10 +7888,20 @@ var Registry = class {
5765
7888
  * ```
5766
7889
  */
5767
7890
  start() {
7891
+ if (_chunkEHZH3KUWcjs.getRivetkitRuntimeMode.call(void 0, ) === "serverless") {
7892
+ const publicDir = _nullishCoalesce(_chunkEHZH3KUWcjs.getRivetkitPublicDir.call(void 0, ), () => ( "/public"));
7893
+ this.listen({ publicDir }).catch((error) => {
7894
+ logger2().error({ error }, "auto-listen failed; exiting");
7895
+ if (typeof process !== "undefined" && typeof process.exit === "function") {
7896
+ process.exit(1);
7897
+ }
7898
+ });
7899
+ return;
7900
+ }
5768
7901
  const config = this.parseConfig();
5769
7902
  this.#startEnvoy(config, true);
5770
7903
  }
5771
- #printWelcome(config, kind) {
7904
+ #printWelcome(config, kind, listener) {
5772
7905
  if (config.noWelcome || this.#welcomePrinted) return;
5773
7906
  this.#welcomePrinted = true;
5774
7907
  const logLine = (label, value) => {
@@ -5777,19 +7910,26 @@ var Registry = class {
5777
7910
  };
5778
7911
  console.log();
5779
7912
  console.log(
5780
- ` RivetKit ${_chunkO25KOT5Ccjs.VERSION} (Engine - ${kind === "serverless" ? "Serverless" : "Serverful"})`
7913
+ ` RivetKit ${_chunkEHZH3KUWcjs.VERSION} (Engine - ${kind === "serverless" ? "Serverless" : "Serverful"})`
5781
7914
  );
5782
7915
  if (config.namespace !== "default") {
5783
7916
  logLine("Namespace", config.namespace);
5784
7917
  }
5785
7918
  if (config.endpoint) {
5786
- const endpointType = config.endpoint === ENGINE_ENDPOINT ? "local native" : "remote";
7919
+ const endpointType = config.startEngine || isLocalEngineEndpoint(config.endpoint) ? "local native" : "remote";
5787
7920
  logLine("Endpoint", `${config.endpoint} (${endpointType})`);
5788
7921
  }
5789
7922
  if (kind === "serverless" && config.publicEndpoint) {
5790
7923
  logLine("Client", config.publicEndpoint);
5791
7924
  }
5792
7925
  logLine("Actors", Object.keys(config.use).length.toString());
7926
+ if (listener) {
7927
+ const host = _nullishCoalesce(listener.host, () => ( "0.0.0.0"));
7928
+ logLine("Listening", `http://${host}:${listener.port}`);
7929
+ if (listener.publicDir) {
7930
+ logLine("Public Dir", listener.publicDir);
7931
+ }
7932
+ }
5793
7933
  console.log();
5794
7934
  }
5795
7935
  };
@@ -5805,6 +7945,12 @@ function isServerlessMetadataRequest(request, basePath) {
5805
7945
  const normalizedBase = basePath === "/" ? "" : `/${basePath.replace(/^\/+|\/+$/g, "")}`;
5806
7946
  return parsed.pathname === `${normalizedBase}/metadata`;
5807
7947
  }
7948
+ function jsonRouteResponse(status, body) {
7949
+ return new Response(JSON.stringify(body), {
7950
+ status,
7951
+ headers: { "content-type": "application/json" }
7952
+ });
7953
+ }
5808
7954
  function setup(input) {
5809
7955
  return new Registry(input);
5810
7956
  }
@@ -5839,5 +7985,6 @@ function setup(input) {
5839
7985
 
5840
7986
 
5841
7987
 
5842
- exports.ALLOWED_PUBLIC_HEADERS = _chunkYQQ2ZDKTcjs.ALLOWED_PUBLIC_HEADERS; exports.ActorDefinition = ActorDefinition; exports.ActorError = _chunkQAZLM4WTcjs.RivetError; exports.ActorsSchema = ActorsSchema; exports.DocConfigurePoolSchema = DocConfigurePoolSchema; exports.DocEnvoyConfigSchema = DocEnvoyConfigSchema; exports.DocRegistryConfigSchema = DocRegistryConfigSchema; exports.DocServerlessConfigSchema = DocServerlessConfigSchema; exports.DocSqliteConfigSchema = DocSqliteConfigSchema; exports.InlineWebSocketAdapter = InlineWebSocketAdapter; exports.Registry = Registry; exports.RegistryConfigSchema = RegistryConfigSchema; exports.RivetError = _chunkQAZLM4WTcjs.RivetError; exports.RuntimeKindSchema = RuntimeKindSchema; exports.SqliteBackendSchema = SqliteBackendSchema; exports.SqliteConfigSchema = SqliteConfigSchema; exports.TestConfigSchema = TestConfigSchema; exports.UserError = _chunkQAZLM4WTcjs.UserError; exports.WasmRuntimeConfigSchema = WasmRuntimeConfigSchema; exports.actor = actor; exports.buildActorNames = buildActorNames; exports.createClientWithDriver = _chunkYQQ2ZDKTcjs.createClientWithDriver; exports.event = event; exports.isStaticActorDefinition = isStaticActorDefinition; exports.isStaticActorInstance = isStaticActorInstance; exports.lookupInRegistry = lookupInRegistry; exports.noopNext = _chunkO25KOT5Ccjs.noopNext; exports.queue = queue; exports.setup = setup; exports.toUint8Array = _chunkO25KOT5Ccjs.toUint8Array;
7988
+
7989
+ exports.ALLOWED_PUBLIC_HEADERS = _chunkAIL267JKcjs.ALLOWED_PUBLIC_HEADERS; exports.ActorDefinition = ActorDefinition; exports.ActorError = _chunk2JSYYH6Pcjs.RivetError; exports.ActorsSchema = ActorsSchema; exports.DocConfigurePoolSchema = DocConfigurePoolSchema; exports.DocEnvoyConfigSchema = DocEnvoyConfigSchema; exports.DocRegistryConfigSchema = DocRegistryConfigSchema; exports.DocServerlessConfigSchema = DocServerlessConfigSchema; exports.DocSqliteConfigSchema = DocSqliteConfigSchema; exports.InlineWebSocketAdapter = InlineWebSocketAdapter; exports.Registry = Registry; exports.RegistryConfigSchema = RegistryConfigSchema; exports.RivetError = _chunk2JSYYH6Pcjs.RivetError; exports.RuntimeKindSchema = RuntimeKindSchema; exports.SqliteBackendSchema = SqliteBackendSchema; exports.SqliteConfigSchema = SqliteConfigSchema; exports.TestConfigSchema = TestConfigSchema; exports.UserError = _chunk2JSYYH6Pcjs.UserError; exports.WasmRuntimeConfigSchema = WasmRuntimeConfigSchema; exports.actor = actor; exports.buildActorNames = buildActorNames; exports.createClientWithDriver = _chunkAIL267JKcjs.createClientWithDriver; exports.defineRunHandler = _chunk4KGXFC6Mcjs.defineRunHandler; exports.event = event; exports.isStaticActorDefinition = isStaticActorDefinition; exports.isStaticActorInstance = isStaticActorInstance; exports.lookupInRegistry = lookupInRegistry; exports.noopNext = _chunkEHZH3KUWcjs.noopNext; exports.queue = queue; exports.setup = setup; exports.toUint8Array = _chunkEHZH3KUWcjs.toUint8Array;
5843
7990
  //# sourceMappingURL=mod.cjs.map