rivetkit 0.0.0-main.72cbc7c → 0.0.0-main.79e97f1

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 (265) hide show
  1. package/dist/browser/client.d.ts +721 -88
  2. package/dist/browser/client.js +684 -604
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +121 -2
  5. package/dist/browser/inspector/client.js +2064 -232
  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 +2355 -2099
  13. package/dist/tsup/agent-os/index.cjs.map +1 -1
  14. package/dist/tsup/agent-os/index.d.cts +719 -87
  15. package/dist/tsup/agent-os/index.d.ts +719 -87
  16. package/dist/tsup/agent-os/index.js +2343 -2087
  17. package/dist/tsup/agent-os/index.js.map +1 -1
  18. package/dist/tsup/{chunk-OFP533QU.cjs → chunk-42QKF4NL.cjs} +3 -3
  19. package/dist/tsup/{chunk-OFP533QU.cjs.map → chunk-42QKF4NL.cjs.map} +1 -1
  20. package/dist/tsup/{chunk-QAZLM4WT.cjs → chunk-4FC7TVS6.cjs} +8 -4
  21. package/dist/tsup/chunk-4FC7TVS6.cjs.map +1 -0
  22. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-7AFZMFPQ.js} +15 -1
  23. package/dist/tsup/chunk-7AFZMFPQ.js.map +1 -0
  24. package/dist/tsup/{chunk-HSTK7OBI.js → chunk-AXDEBZFM.js} +13 -7
  25. package/dist/tsup/chunk-AXDEBZFM.js.map +1 -0
  26. package/dist/tsup/{chunk-WQ4HNA4W.cjs → chunk-HNHLBM3Y.cjs} +192 -15
  27. package/dist/tsup/chunk-HNHLBM3Y.cjs.map +1 -0
  28. package/dist/tsup/{chunk-EI55QOUB.js → chunk-J2TA4HLA.js} +235 -245
  29. package/dist/tsup/chunk-J2TA4HLA.js.map +1 -0
  30. package/dist/tsup/{chunk-3YY5S6TV.js → chunk-JI6GZ2C2.js} +3 -12
  31. package/dist/tsup/chunk-JI6GZ2C2.js.map +1 -0
  32. package/dist/tsup/{chunk-4KSYSQHX.js → chunk-KUWK4UNH.js} +2 -2
  33. package/dist/tsup/{chunk-YQQ2ZDKT.cjs → chunk-L3YK4JAQ.cjs} +378 -388
  34. package/dist/tsup/chunk-L3YK4JAQ.cjs.map +1 -0
  35. package/dist/tsup/{chunk-WDO5Y6PO.cjs → chunk-LSLRMWDP.cjs} +17 -11
  36. package/dist/tsup/chunk-LSLRMWDP.cjs.map +1 -0
  37. package/dist/tsup/{chunk-LD5YASJU.cjs → chunk-MYWZCDML.cjs} +3 -12
  38. package/dist/tsup/chunk-MYWZCDML.cjs.map +1 -0
  39. package/dist/tsup/{chunk-T6YVRM4K.js → chunk-QWLJCP3X.js} +190 -13
  40. package/dist/tsup/chunk-QWLJCP3X.js.map +1 -0
  41. package/dist/tsup/{chunk-OQSBGFIB.cjs → chunk-ROANIJSQ.cjs} +10 -10
  42. package/dist/tsup/chunk-ROANIJSQ.cjs.map +1 -0
  43. package/dist/tsup/{chunk-5DGOZZKE.cjs → chunk-SHGGJE3M.cjs} +44 -9
  44. package/dist/tsup/chunk-SHGGJE3M.cjs.map +1 -0
  45. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-UEULFXUI.cjs} +16 -2
  46. package/dist/tsup/chunk-UEULFXUI.cjs.map +1 -0
  47. package/dist/tsup/{chunk-O25KOT5C.cjs → chunk-ULWCXOND.cjs} +475 -24
  48. package/dist/tsup/chunk-ULWCXOND.cjs.map +1 -0
  49. package/dist/tsup/{chunk-DFHHCPH7.js → chunk-ULYPJPHB.js} +42 -7
  50. package/dist/tsup/chunk-ULYPJPHB.js.map +1 -0
  51. package/dist/tsup/{chunk-GDKM56PU.js → chunk-Y5BCFECV.js} +466 -15
  52. package/dist/tsup/chunk-Y5BCFECV.js.map +1 -0
  53. package/dist/tsup/{chunk-PJSE5ZGN.js → chunk-YTE3YP7Q.js} +6 -6
  54. package/dist/tsup/chunk-YTE3YP7Q.js.map +1 -0
  55. package/dist/tsup/{chunk-KIWH5H3K.js → chunk-ZZ3WBRPD.js} +7 -3
  56. package/dist/tsup/chunk-ZZ3WBRPD.js.map +1 -0
  57. package/dist/tsup/client/mod.cjs +8 -9
  58. package/dist/tsup/client/mod.cjs.map +1 -1
  59. package/dist/tsup/client/mod.d.cts +7 -6
  60. package/dist/tsup/client/mod.d.ts +7 -6
  61. package/dist/tsup/client/mod.js +7 -8
  62. package/dist/tsup/common/log.cjs +5 -3
  63. package/dist/tsup/common/log.cjs.map +1 -1
  64. package/dist/tsup/common/log.d.cts +5 -1
  65. package/dist/tsup/common/log.d.ts +5 -1
  66. package/dist/tsup/common/log.js +6 -4
  67. package/dist/tsup/common/websocket.cjs +4 -4
  68. package/dist/tsup/common/websocket.js +3 -3
  69. package/dist/tsup/{config-CxjGYf4K.d.cts → config-BxOimoGX.d.cts} +17 -2
  70. package/dist/tsup/{config-CxjGYf4K.d.ts → config-BxOimoGX.d.ts} +17 -2
  71. package/dist/tsup/{config-CRwCN3Ok.d.ts → config-CUymbyM6.d.ts} +758 -56
  72. package/dist/tsup/{config-voObiSep.d.cts → config-CpB-e4I9.d.cts} +758 -56
  73. package/dist/tsup/context-YBUBTwTS.d.ts +129 -0
  74. package/dist/tsup/context-c-6G4mjk.d.cts +129 -0
  75. package/dist/tsup/db/drizzle.cjs +120 -68
  76. package/dist/tsup/db/drizzle.cjs.map +1 -1
  77. package/dist/tsup/db/drizzle.d.cts +8 -3
  78. package/dist/tsup/db/drizzle.d.ts +8 -3
  79. package/dist/tsup/db/drizzle.js +120 -68
  80. package/dist/tsup/db/drizzle.js.map +1 -1
  81. package/dist/tsup/db/mod.cjs +74 -22
  82. package/dist/tsup/db/mod.cjs.map +1 -1
  83. package/dist/tsup/db/mod.d.cts +4 -3
  84. package/dist/tsup/db/mod.d.ts +4 -3
  85. package/dist/tsup/db/mod.js +74 -22
  86. package/dist/tsup/db/mod.js.map +1 -1
  87. package/dist/tsup/dynamic/mod.cjs +24 -0
  88. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  89. package/dist/tsup/dynamic/mod.d.cts +37 -0
  90. package/dist/tsup/dynamic/mod.d.ts +37 -0
  91. package/dist/tsup/dynamic/mod.js +24 -0
  92. package/dist/tsup/dynamic/mod.js.map +1 -0
  93. package/dist/tsup/inspector/mod.cjs +46 -12
  94. package/dist/tsup/inspector/mod.cjs.map +1 -1
  95. package/dist/tsup/inspector/mod.d.cts +37 -15
  96. package/dist/tsup/inspector/mod.d.ts +37 -15
  97. package/dist/tsup/inspector/mod.js +45 -11
  98. package/dist/tsup/inspector/mod.js.map +1 -1
  99. package/dist/tsup/inspector-tab/mod.cjs +162 -0
  100. package/dist/tsup/inspector-tab/mod.cjs.map +1 -0
  101. package/dist/tsup/inspector-tab/mod.d.cts +240 -0
  102. package/dist/tsup/inspector-tab/mod.d.ts +240 -0
  103. package/dist/tsup/inspector-tab/mod.js +162 -0
  104. package/dist/tsup/inspector-tab/mod.js.map +1 -0
  105. package/dist/tsup/mod.cjs +2031 -533
  106. package/dist/tsup/mod.cjs.map +1 -1
  107. package/dist/tsup/mod.d.cts +6 -6
  108. package/dist/tsup/mod.d.ts +6 -6
  109. package/dist/tsup/mod.js +1953 -455
  110. package/dist/tsup/mod.js.map +1 -1
  111. package/dist/tsup/test/mod.cjs +26 -21
  112. package/dist/tsup/test/mod.cjs.map +1 -1
  113. package/dist/tsup/test/mod.d.cts +5 -5
  114. package/dist/tsup/test/mod.d.ts +5 -5
  115. package/dist/tsup/test/mod.js +25 -20
  116. package/dist/tsup/test/mod.js.map +1 -1
  117. package/dist/tsup/unstable/migrations.cjs +101 -0
  118. package/dist/tsup/unstable/migrations.cjs.map +1 -0
  119. package/dist/tsup/unstable/migrations.d.cts +29 -0
  120. package/dist/tsup/unstable/migrations.d.ts +29 -0
  121. package/dist/tsup/unstable/migrations.js +101 -0
  122. package/dist/tsup/unstable/migrations.js.map +1 -0
  123. package/dist/tsup/utils-CV0akuDD.d.ts +162 -0
  124. package/dist/tsup/{utils-DVekpm4I.d.cts → utils-CqDnC_PS.d.cts} +2 -1
  125. package/dist/tsup/{utils-DVekpm4I.d.ts → utils-CqDnC_PS.d.ts} +2 -1
  126. package/dist/tsup/utils-DQDCphrl.d.cts +162 -0
  127. package/dist/tsup/utils.cjs +7 -3
  128. package/dist/tsup/utils.cjs.map +1 -1
  129. package/dist/tsup/utils.d.cts +4 -147
  130. package/dist/tsup/utils.d.ts +4 -147
  131. package/dist/tsup/utils.js +6 -2
  132. package/dist/tsup/workflow/mod.cjs +486 -375
  133. package/dist/tsup/workflow/mod.cjs.map +1 -1
  134. package/dist/tsup/workflow/mod.d.cts +9 -9
  135. package/dist/tsup/workflow/mod.d.ts +9 -9
  136. package/dist/tsup/workflow/mod.js +478 -367
  137. package/dist/tsup/workflow/mod.js.map +1 -1
  138. package/package.json +45 -14
  139. package/src/actor/actions.ts +119 -0
  140. package/src/actor/config.test.ts +14 -0
  141. package/src/actor/config.ts +338 -85
  142. package/src/actor/contexts/index.ts +7 -2
  143. package/src/actor/definition.ts +38 -26
  144. package/src/actor/errors.ts +20 -3
  145. package/src/actor/keys.ts +1 -1
  146. package/src/actor/mod.ts +22 -20
  147. package/src/actor/schema.ts +2 -2
  148. package/src/agent-os/actor/index.ts +39 -19
  149. package/src/agent-os/actor/preview.ts +1 -2
  150. package/src/agent-os/actor/session.ts +2 -2
  151. package/src/agent-os/config.ts +1 -1
  152. package/src/agent-os/fs/database-vfs.ts +1 -1
  153. package/src/agent-os/index.ts +16 -15
  154. package/src/client/actor-common.ts +89 -54
  155. package/src/client/actor-conn.ts +11 -36
  156. package/src/client/actor-handle.ts +72 -52
  157. package/src/client/actor-query.ts +5 -5
  158. package/src/client/client.ts +24 -11
  159. package/src/client/errors.ts +1 -1
  160. package/src/client/lifecycle-errors.ts +2 -4
  161. package/src/client/query.ts +1 -1
  162. package/src/client/queue.ts +8 -3
  163. package/src/client/raw-utils.ts +19 -8
  164. package/src/client/resolve-gateway-target.ts +1 -1
  165. package/src/client/utils.ts +2 -7
  166. package/src/common/actor-router-consts.ts +1 -0
  167. package/src/common/actor-websocket.ts +3 -1
  168. package/src/common/bare/actor-persist/v1.ts +205 -163
  169. package/src/common/bare/actor-persist/v2.ts +265 -213
  170. package/src/common/bare/actor-persist/v3.ts +176 -172
  171. package/src/common/bare/actor-persist/v4.ts +254 -253
  172. package/src/common/bare/generated/actor-runtime-socket-protocol/v1.ts +848 -0
  173. package/src/common/bare/generated/inspector/v5.ts +1016 -0
  174. package/src/common/bare/generated/inspector/v6.ts +1367 -0
  175. package/src/common/bare/transport/v1.ts +694 -542
  176. package/src/common/client-protocol-versioned.ts +66 -64
  177. package/src/common/database/config.ts +26 -8
  178. package/src/common/database/mod.test.ts +148 -59
  179. package/src/common/database/mod.ts +93 -23
  180. package/src/common/database/native-database.test.ts +9 -0
  181. package/src/common/database/native-database.ts +152 -1
  182. package/src/common/database/shared.ts +16 -0
  183. package/src/common/encoding.ts +278 -34
  184. package/src/common/engine.ts +28 -1
  185. package/src/common/eventsource.ts +1 -1
  186. package/src/common/fetch-like.ts +49 -0
  187. package/src/common/inline-websocket-adapter.ts +14 -13
  188. package/src/common/log.ts +15 -8
  189. package/src/common/router.ts +13 -17
  190. package/src/common/utils.ts +1 -150
  191. package/src/common/websocket-interface.ts +1 -1
  192. package/src/db/drizzle.test.ts +157 -0
  193. package/src/db/drizzle.ts +170 -79
  194. package/src/db/mod.ts +1 -1
  195. package/src/devtools-loader/index.ts +4 -7
  196. package/src/devtools-loader/serve-devtools.ts +26 -0
  197. package/src/dynamic/instance.ts +32 -0
  198. package/src/dynamic/internal.ts +50 -0
  199. package/src/dynamic/isolate-runtime.ts +64 -0
  200. package/src/dynamic/mod.ts +32 -0
  201. package/src/engine-client/actor-http-client.ts +8 -24
  202. package/src/engine-client/actor-websocket-client.ts +6 -5
  203. package/src/engine-client/api-endpoints.ts +51 -2
  204. package/src/engine-client/api-utils.ts +2 -2
  205. package/src/engine-client/driver.ts +1 -16
  206. package/src/engine-client/mod.ts +6 -44
  207. package/src/engine-client/ws-proxy.ts +9 -4
  208. package/src/inspector/client.browser.ts +127 -15
  209. package/src/inspector/mod.ts +2 -4
  210. package/src/inspector-tab/mod.ts +301 -0
  211. package/src/registry/config/envoy.ts +1 -2
  212. package/src/registry/config/index.ts +41 -55
  213. package/src/registry/index.ts +595 -92
  214. package/src/registry/napi-runtime.ts +359 -23
  215. package/src/registry/native-http.ts +208 -0
  216. package/src/registry/native-validation.ts +10 -12
  217. package/src/registry/native.ts +879 -311
  218. package/src/registry/process-metrics.ts +250 -0
  219. package/src/registry/runtime.ts +249 -8
  220. package/src/registry/wasm-runtime.ts +280 -9
  221. package/src/registry/write-through-proxy.ts +40 -0
  222. package/src/serde.ts +2 -2
  223. package/src/serverless/configure.ts +18 -7
  224. package/src/test/mod.ts +2 -17
  225. package/src/test/ready.ts +22 -0
  226. package/src/unstable/migrations.test.ts +170 -0
  227. package/src/unstable/migrations.ts +141 -0
  228. package/src/utils/endpoint-parser.ts +1 -1
  229. package/src/utils/env-vars.ts +37 -0
  230. package/src/utils/router.ts +1 -1
  231. package/src/utils.ts +4 -2
  232. package/src/workflow/context.ts +683 -242
  233. package/src/workflow/driver.test.ts +62 -0
  234. package/src/workflow/driver.ts +248 -119
  235. package/src/workflow/inspector.ts +12 -3
  236. package/src/workflow/mod.ts +39 -25
  237. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  238. package/dist/tsup/chunk-3YY5S6TV.js.map +0 -1
  239. package/dist/tsup/chunk-5DGOZZKE.cjs.map +0 -1
  240. package/dist/tsup/chunk-DFHHCPH7.js.map +0 -1
  241. package/dist/tsup/chunk-EI55QOUB.js.map +0 -1
  242. package/dist/tsup/chunk-GDKM56PU.js.map +0 -1
  243. package/dist/tsup/chunk-HSTK7OBI.js.map +0 -1
  244. package/dist/tsup/chunk-KIWH5H3K.js.map +0 -1
  245. package/dist/tsup/chunk-LD5YASJU.cjs.map +0 -1
  246. package/dist/tsup/chunk-LI5MR5BD.js +0 -268
  247. package/dist/tsup/chunk-LI5MR5BD.js.map +0 -1
  248. package/dist/tsup/chunk-NDY6IZJ3.cjs +0 -268
  249. package/dist/tsup/chunk-NDY6IZJ3.cjs.map +0 -1
  250. package/dist/tsup/chunk-O25KOT5C.cjs.map +0 -1
  251. package/dist/tsup/chunk-OQSBGFIB.cjs.map +0 -1
  252. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  253. package/dist/tsup/chunk-PJSE5ZGN.js.map +0 -1
  254. package/dist/tsup/chunk-QAZLM4WT.cjs.map +0 -1
  255. package/dist/tsup/chunk-T6YVRM4K.js.map +0 -1
  256. package/dist/tsup/chunk-WDO5Y6PO.cjs.map +0 -1
  257. package/dist/tsup/chunk-WQ4HNA4W.cjs.map +0 -1
  258. package/dist/tsup/chunk-YQQ2ZDKT.cjs.map +0 -1
  259. package/dist/tsup/context-BPFYVZ5g.d.ts +0 -92
  260. package/dist/tsup/context-D0YF1MQq.d.cts +0 -92
  261. package/src/actor/driver.ts +0 -141
  262. package/src/actor/instance/mod.ts +0 -2492
  263. package/src/drivers/engine/actor-driver.ts +0 -2460
  264. package/src/utils/serve.ts +0 -217
  265. /package/dist/tsup/{chunk-4KSYSQHX.js.map → chunk-KUWK4UNH.js.map} +0 -0
package/dist/tsup/mod.js CHANGED
@@ -1,43 +1,44 @@
1
+ import {
2
+ decodeWorkflowHistoryTransport
3
+ } from "./chunk-ULYPJPHB.js";
1
4
  import {
2
5
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
3
6
  ActorConfigSchema,
4
7
  CONN_STATE_MANAGER_SYMBOL,
8
+ RAW_STATE_SYMBOL,
9
+ disposeRunInspector,
10
+ flattenActionHandlers,
11
+ flattenActionInputSchemas,
5
12
  getRunFunction,
6
13
  getRunInspectorConfig,
7
14
  getRunMetadata
8
- } from "./chunk-T6YVRM4K.js";
9
- import {
10
- decodeWorkflowHistoryTransport
11
- } from "./chunk-DFHHCPH7.js";
15
+ } from "./chunk-QWLJCP3X.js";
12
16
  import {
13
17
  ALLOWED_PUBLIC_HEADERS,
14
18
  HEADER_CONN_PARAMS,
19
+ HEADER_ORIGINAL_REQUEST_URL,
15
20
  RemoteEngineControlClient,
16
21
  convertRegistryConfigToClientConfig,
17
22
  createClientWithDriver,
18
23
  getDatacenters,
24
+ isResponseLike,
19
25
  tryParseEndpoint,
20
26
  updateRunnerConfig
21
- } from "./chunk-EI55QOUB.js";
27
+ } from "./chunk-J2TA4HLA.js";
22
28
  import {
23
- KEYS,
24
29
  makePrefixedKey,
25
- queueMessagesPrefix,
26
- queueMetadataKey,
27
- removePrefixFromKey,
28
- workflowStoragePrefix
29
- } from "./chunk-3YY5S6TV.js";
30
- import {
31
- decodeCborCompat,
32
- decodeCborJsonCompat,
33
- encodeCborCompat
34
- } from "./chunk-LI5MR5BD.js";
35
- import "./chunk-PCBNKI2J.js";
36
- import "./chunk-4KSYSQHX.js";
30
+ removePrefixFromKey
31
+ } from "./chunk-JI6GZ2C2.js";
32
+ import "./chunk-7AFZMFPQ.js";
33
+ import "./chunk-KUWK4UNH.js";
37
34
  import {
38
35
  LogLevelSchema,
39
36
  VERSION,
37
+ assertJsonCompatValue,
38
+ configureBaseLogger,
39
+ decodeCborCompat,
40
40
  deconstructError,
41
+ encodeCborCompat,
41
42
  getEnvUniversal,
42
43
  getLogger,
43
44
  getNodeEnv,
@@ -49,15 +50,20 @@ import {
49
50
  getRivetPublicEndpoint,
50
51
  getRivetPublicToken,
51
52
  getRivetRunEngine,
53
+ getRivetRunEngineHost,
54
+ getRivetRunEnginePort,
52
55
  getRivetRunEngineVersion,
53
56
  getRivetToken,
54
57
  getRivetTotalSlots,
58
+ getRivetkitPublicDir,
55
59
  getRivetkitRuntime,
60
+ getRivetkitRuntimeMode,
56
61
  isDev,
57
62
  noopNext,
63
+ parsePortEnv,
58
64
  stringifyError,
59
65
  toUint8Array
60
- } from "./chunk-GDKM56PU.js";
66
+ } from "./chunk-Y5BCFECV.js";
61
67
  import {
62
68
  INTERNAL_ERROR_CODE,
63
69
  RivetError,
@@ -65,10 +71,11 @@ import {
65
71
  decodeBridgeRivetError,
66
72
  encodeBridgeRivetError,
67
73
  forbiddenError,
74
+ isActorAbortedError,
68
75
  isRivetErrorLike,
69
76
  toRivetError,
70
77
  unsupportedFeature
71
- } from "./chunk-KIWH5H3K.js";
78
+ } from "./chunk-ZZ3WBRPD.js";
72
79
 
73
80
  // src/actor/log.ts
74
81
  function loggerWithoutContext() {
@@ -76,15 +83,21 @@ function loggerWithoutContext() {
76
83
  }
77
84
 
78
85
  // src/actor/definition.ts
79
- var warnedDeprecatedTimeoutKeys = /* @__PURE__ */ new Set();
80
- function warnDeprecatedShutdownTimeoutKeys(options) {
86
+ var warnedDeprecatedOptionKeys = /* @__PURE__ */ new Set();
87
+ var DEPRECATED_OPTION_MESSAGES = {
88
+ onDestroyTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
89
+ waitUntilTimeout: "Configure `sleepGracePeriod` instead, which bounds the entire graceful shutdown window for both sleep and destroy.",
90
+ preloadMaxWorkflowBytes: "Internal storage moved to SQLite and no longer uses KV preloading.",
91
+ preloadMaxConnectionsBytes: "Internal storage moved to SQLite and no longer uses KV preloading."
92
+ };
93
+ function warnDeprecatedOptionKeys(options) {
81
94
  if (!options || typeof options !== "object") return;
82
95
  const opts = options;
83
- for (const key of ["onDestroyTimeout", "waitUntilTimeout"]) {
84
- if (opts[key] !== void 0 && !warnedDeprecatedTimeoutKeys.has(key)) {
85
- warnedDeprecatedTimeoutKeys.add(key);
96
+ for (const [key, detail] of Object.entries(DEPRECATED_OPTION_MESSAGES)) {
97
+ if (opts[key] !== void 0 && !warnedDeprecatedOptionKeys.has(key)) {
98
+ warnedDeprecatedOptionKeys.add(key);
86
99
  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.`
100
+ msg: `actor option \`${key}\` is deprecated and is now ignored. ${detail} Will be removed in 2.2.0.`
88
101
  });
89
102
  }
90
103
  }
@@ -102,10 +115,12 @@ function isStaticActorInstance(_actor) {
102
115
  return true;
103
116
  }
104
117
  function actor(input) {
105
- warnDeprecatedShutdownTimeoutKeys(
118
+ warnDeprecatedOptionKeys(
106
119
  input == null ? void 0 : input.options
107
120
  );
108
121
  const config = ActorConfigSchema.parse(input);
122
+ flattenActionHandlers(config.actions);
123
+ flattenActionInputSchemas(config.actions, config.actionInputSchemas);
109
124
  return new ActorDefinition(config);
110
125
  }
111
126
  function isStaticActorDefinition(definition) {
@@ -140,7 +155,7 @@ function hasSchemaConfigKey(schemas, key) {
140
155
  if (!schemas) {
141
156
  return false;
142
157
  }
143
- return Object.prototype.hasOwnProperty.call(schemas, key);
158
+ return Object.hasOwn(schemas, key);
144
159
  }
145
160
  function getEventCanSubscribe(schemas, key) {
146
161
  const schema = schemas == null ? void 0 : schemas[key];
@@ -201,8 +216,8 @@ function validateSchemaSync(schemas, key, data) {
201
216
  }
202
217
 
203
218
  // src/common/inline-websocket-adapter.ts
204
- import { WSContext } from "hono/ws";
205
219
  import { VirtualWebSocket } from "@rivetkit/virtual-websocket";
220
+ import { WSContext } from "hono/ws";
206
221
  function logger() {
207
222
  return getLogger("inline-websocket-adapter");
208
223
  }
@@ -314,24 +329,24 @@ var InlineWebSocketAdapter = class {
314
329
  this.#close(1011, "Internal error during initialization");
315
330
  }
316
331
  }
317
- #handleError(err) {
318
- console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", err);
332
+ #handleError(error) {
333
+ console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", error);
319
334
  logger().error({
320
335
  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
336
+ error,
337
+ errorMessage: error instanceof Error ? error.message : String(error),
338
+ stack: error instanceof Error ? error.stack : void 0
324
339
  });
325
340
  try {
326
- this.#handler.onError(err, this.#wsContext);
327
- } catch (handlerErr) {
341
+ this.#handler.onError(error, this.#wsContext);
342
+ } catch (error2) {
328
343
  logger().error({
329
344
  msg: "error in onError handler",
330
- error: handlerErr
345
+ error: error2
331
346
  });
332
347
  }
333
- this.#clientWs.triggerError(err);
334
- this.#actorWs.triggerError(err);
348
+ this.#clientWs.triggerError(error);
349
+ this.#actorWs.triggerError(error);
335
350
  }
336
351
  #close(code, reason) {
337
352
  if (this.#readyState === 3 || this.#readyState === 2) {
@@ -344,8 +359,8 @@ var InlineWebSocketAdapter = class {
344
359
  { code, reason, wasClean: true },
345
360
  this.#wsContext
346
361
  );
347
- } catch (err) {
348
- logger().error({ msg: "error closing websocket", error: err });
362
+ } catch (error) {
363
+ logger().error({ msg: "error closing websocket", error });
349
364
  } finally {
350
365
  this.#readyState = 3;
351
366
  this.#clientWs.triggerClose(code, reason);
@@ -355,8 +370,23 @@ var InlineWebSocketAdapter = class {
355
370
  };
356
371
 
357
372
  // src/common/engine.ts
373
+ var ENGINE_HOST = "127.0.0.1";
358
374
  var ENGINE_PORT = 6420;
359
- var ENGINE_ENDPOINT = `http://127.0.0.1:${ENGINE_PORT}`;
375
+ var ENGINE_ENDPOINT = buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT);
376
+ function buildEngineEndpoint(host, port) {
377
+ const urlHost = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
378
+ return `http://${urlHost}:${port}`;
379
+ }
380
+ function isLocalEngineEndpoint(endpoint) {
381
+ let url;
382
+ try {
383
+ url = new URL(endpoint);
384
+ } catch {
385
+ return false;
386
+ }
387
+ const hostname = url.hostname.toLowerCase();
388
+ return hostname === "localhost" || hostname === "0.0.0.0" || hostname === "::" || hostname === "[::]" || hostname === "::1" || hostname === "[::1]" || /^127(?:\.\d{1,3}){0,3}$/.test(hostname);
389
+ }
360
390
 
361
391
  // src/registry/log.ts
362
392
  function logger2() {
@@ -371,10 +401,13 @@ function sleep(ms) {
371
401
  }
372
402
  function configureTimeoutMs() {
373
403
  const value = process.env.RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS;
374
- if (value === void 0 || value === "") return DEFAULT_CONFIGURE_TIMEOUT_MS;
404
+ if (value === void 0 || value === "")
405
+ return DEFAULT_CONFIGURE_TIMEOUT_MS;
375
406
  const parsed = Number(value);
376
407
  if (!Number.isFinite(parsed) || parsed < 0) {
377
- throw new Error("RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number");
408
+ throw new Error(
409
+ "RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number"
410
+ );
378
411
  }
379
412
  return parsed;
380
413
  }
@@ -388,13 +421,19 @@ async function configureServerlessPool(config) {
388
421
  attempts += 1;
389
422
  try {
390
423
  if (!config.namespace) {
391
- throw new Error("namespace is required for serverless configuration");
424
+ throw new Error(
425
+ "namespace is required for serverless configuration"
426
+ );
392
427
  }
393
428
  if (!config.endpoint) {
394
- throw new Error("endpoint is required for serverless configuration");
429
+ throw new Error(
430
+ "endpoint is required for serverless configuration"
431
+ );
395
432
  }
396
433
  if (!config.configurePool) {
397
- throw new Error("configurePool is required for serverless configuration");
434
+ throw new Error(
435
+ "configurePool is required for serverless configuration"
436
+ );
398
437
  }
399
438
  const customConfig = config.configurePool;
400
439
  const clientConfig = convertRegistryConfigToClientConfig(config);
@@ -668,6 +707,18 @@ var RegistryConfigSchema = z3.object({
668
707
  * Starts the full Rust engine process locally.
669
708
  */
670
709
  startEngine: z3.boolean().default(() => getRivetRunEngine()),
710
+ /**
711
+ * @experimental
712
+ *
713
+ * Host to bind the spawned local engine process to.
714
+ */
715
+ engineHost: z3.string().optional().default(() => getRivetRunEngineHost() ?? ENGINE_HOST),
716
+ /**
717
+ * @experimental
718
+ *
719
+ * Port to bind the spawned local engine process to.
720
+ */
721
+ enginePort: z3.number().int().min(1).max(65535).optional().default(() => getRivetRunEnginePort() ?? ENGINE_PORT),
671
722
  /** @experimental */
672
723
  engineVersion: z3.string().optional().default(() => getRivetRunEngineVersion() ?? VERSION),
673
724
  /**
@@ -700,12 +751,12 @@ var RegistryConfigSchema = z3.object({
700
751
  shutdown: z3.object({
701
752
  /**
702
753
  * Wait this many milliseconds for the serve promise to resolve
703
- * after calling `CoreRegistry::shutdown()`. Defaults to 30s,
704
- * matching Kubernetes `terminationGracePeriodSeconds`.
754
+ * after calling `CoreRegistry::shutdown()`. Defaults to the
755
+ * engine-provided actor stop threshold once the envoy connects.
705
756
  *
706
- * Must be >= rivetkit-core's drain timeout (20s) + margin.
757
+ * Must be long enough for rivetkit-core to drain the envoy.
707
758
  */
708
- gracePeriodMs: z3.number().int().min(1e3).optional().default(3e4),
759
+ gracePeriodMs: z3.number().int().min(1e3).optional(),
709
760
  /**
710
761
  * If true, rivetkit will not install SIGINT/SIGTERM handlers.
711
762
  * Use when the host application owns signal policy and will
@@ -713,7 +764,6 @@ var RegistryConfigSchema = z3.object({
713
764
  */
714
765
  disableSignalHandlers: z3.boolean().optional().default(false)
715
766
  }).optional().default(() => ({
716
- gracePeriodMs: 3e4,
717
767
  disableSignalHandlers: false
718
768
  }))
719
769
  }).transform((config, ctx) => {
@@ -746,7 +796,11 @@ var RegistryConfigSchema = z3.object({
746
796
  message: "configurePool requires either endpoint or startEngine"
747
797
  });
748
798
  }
749
- const endpoint = config.startEngine ? ENGINE_ENDPOINT : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? ENGINE_ENDPOINT : void 0);
799
+ const localEngineEndpoint = buildEngineEndpoint(
800
+ config.engineHost,
801
+ config.enginePort
802
+ );
803
+ const endpoint = config.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? localEngineEndpoint : void 0);
750
804
  const validateServerlessEndpoint = Boolean(
751
805
  config.startEngine || parsedEndpoint
752
806
  );
@@ -763,7 +817,7 @@ var RegistryConfigSchema = z3.object({
763
817
  path: ["serverless", "publicEndpoint"]
764
818
  });
765
819
  }
766
- const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && config.startEngine ? ENGINE_ENDPOINT : void 0);
820
+ const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && !parsedEndpoint ? endpoint : void 0);
767
821
  const publicNamespace = parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.namespace;
768
822
  const publicToken = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.token) ?? config.serverless.publicToken;
769
823
  return {
@@ -791,31 +845,6 @@ function buildActorNames(config) {
791
845
  const metadata = {};
792
846
  metadata.icon = options.icon ?? runMeta.icon;
793
847
  metadata.name = options.name ?? runMeta.name;
794
- metadata.preload = {
795
- keys: [
796
- Array.from(KEYS.PERSIST_DATA),
797
- Array.from(KEYS.INSPECTOR_TOKEN),
798
- Array.from(queueMetadataKey()),
799
- Array.from(KEYS.LAST_PUSHED_ALARM)
800
- ],
801
- prefixes: [
802
- {
803
- prefix: Array.from(workflowStoragePrefix()),
804
- maxBytes: options.preloadMaxWorkflowBytes ?? 131072,
805
- partial: false
806
- },
807
- {
808
- prefix: Array.from(KEYS.CONN_PREFIX),
809
- maxBytes: options.preloadMaxConnectionsBytes ?? 65536,
810
- partial: false
811
- },
812
- {
813
- prefix: Array.from(queueMessagesPrefix()),
814
- maxBytes: 65536,
815
- partial: false
816
- }
817
- ]
818
- };
819
848
  if (!metadata.icon) delete metadata.icon;
820
849
  if (!metadata.name) delete metadata.name;
821
850
  return [actorName, { metadata }];
@@ -1008,6 +1037,12 @@ function toNativeBindings(sql, params) {
1008
1037
  return toNativeBinding(value);
1009
1038
  });
1010
1039
  }
1040
+ function toNativeBatchStatement(statement) {
1041
+ return {
1042
+ sql: statement.sql,
1043
+ params: toNativeBindings(statement.sql, statement.params)
1044
+ };
1045
+ }
1011
1046
  function normalizeNativeMetrics(metrics) {
1012
1047
  if (!metrics) return null;
1013
1048
  const raw = metrics;
@@ -1121,6 +1156,60 @@ function wrapJsNativeDatabase(database) {
1121
1156
  async execute(sql, params) {
1122
1157
  return await executeNative(sql, params);
1123
1158
  },
1159
+ async executeBatch(statements) {
1160
+ const nativeStatements = statements.map(toNativeBatchStatement);
1161
+ const release = gate.enter();
1162
+ let transaction;
1163
+ try {
1164
+ const results = database.executeBatch ? await database.executeBatch(nativeStatements) : await (async () => {
1165
+ transaction = await database.beginTransaction();
1166
+ const transactionResults = [];
1167
+ for (const statement of nativeStatements) {
1168
+ transactionResults.push(
1169
+ await transaction.execute(
1170
+ statement.sql,
1171
+ statement.params
1172
+ )
1173
+ );
1174
+ }
1175
+ await transaction.commit();
1176
+ transaction = void 0;
1177
+ return transactionResults;
1178
+ })();
1179
+ for (const result of results) {
1180
+ if (result.lastInsertRowId !== void 0) {
1181
+ lastInsertRowId = result.lastInsertRowId;
1182
+ }
1183
+ }
1184
+ return results;
1185
+ } catch (error) {
1186
+ if (transaction) {
1187
+ try {
1188
+ await transaction.rollback();
1189
+ } catch {
1190
+ }
1191
+ }
1192
+ enrichNativeDatabaseError(database, error);
1193
+ } finally {
1194
+ release();
1195
+ }
1196
+ },
1197
+ async beginTransaction(timeoutMs) {
1198
+ const release = gate.enter();
1199
+ let transaction;
1200
+ try {
1201
+ transaction = await database.beginTransaction(timeoutMs);
1202
+ } catch (error) {
1203
+ enrichNativeDatabaseError(database, error);
1204
+ } finally {
1205
+ release();
1206
+ }
1207
+ return wrapTransaction(database, transaction, gate, (result) => {
1208
+ if (result.lastInsertRowId !== void 0) {
1209
+ lastInsertRowId = result.lastInsertRowId;
1210
+ }
1211
+ });
1212
+ },
1124
1213
  async run(sql, params) {
1125
1214
  await executeNative(sql, params);
1126
1215
  },
@@ -1138,6 +1227,59 @@ function wrapJsNativeDatabase(database) {
1138
1227
  }
1139
1228
  };
1140
1229
  }
1230
+ function wrapTransaction(database, transaction, gate, onExecute) {
1231
+ return {
1232
+ async exec(sql, callback) {
1233
+ const release = gate.enter();
1234
+ let result;
1235
+ try {
1236
+ result = await transaction.exec(sql);
1237
+ } catch (error) {
1238
+ enrichNativeDatabaseError(database, error);
1239
+ } finally {
1240
+ release();
1241
+ }
1242
+ if (callback) {
1243
+ for (const row of result.rows) callback(row, result.columns);
1244
+ }
1245
+ },
1246
+ async execute(sql, params) {
1247
+ const release = gate.enter();
1248
+ try {
1249
+ const result = await transaction.execute(
1250
+ sql,
1251
+ toNativeBindings(sql, params)
1252
+ );
1253
+ onExecute(result);
1254
+ return result;
1255
+ } catch (error) {
1256
+ enrichNativeDatabaseError(database, error);
1257
+ } finally {
1258
+ release();
1259
+ }
1260
+ },
1261
+ async commit() {
1262
+ const release = gate.enter();
1263
+ try {
1264
+ await transaction.commit();
1265
+ } catch (error) {
1266
+ enrichNativeDatabaseError(database, error);
1267
+ } finally {
1268
+ release();
1269
+ }
1270
+ },
1271
+ async rollback() {
1272
+ const release = gate.enter();
1273
+ try {
1274
+ await transaction.rollback();
1275
+ } catch (error) {
1276
+ enrichNativeDatabaseError(database, error);
1277
+ } finally {
1278
+ release();
1279
+ }
1280
+ }
1281
+ };
1282
+ }
1141
1283
  function lastInsertRowIdColumnName(sql) {
1142
1284
  const match = sql.match(
1143
1285
  /^\s*SELECT\s+last_insert_rowid\s*\(\s*\)\s*(?:AS\s+("[^"]+"|`[^`]+`|\[[^\]]+\]|\w+))?\s*;?\s*$/i
@@ -1155,6 +1297,82 @@ function lastInsertRowIdColumnName(sql) {
1155
1297
  return alias;
1156
1298
  }
1157
1299
 
1300
+ // src/utils/node.ts
1301
+ import { createRequire } from "module";
1302
+ var nodeCrypto;
1303
+ var nodeFsSync;
1304
+ var nodeFs;
1305
+ var nodePath;
1306
+ var nodeOs;
1307
+ var nodeChildProcess;
1308
+ var nodeStream;
1309
+ var nodeUrl;
1310
+ var hasImportedDependencies = false;
1311
+ function getRequireFn() {
1312
+ return createRequire(import.meta.url);
1313
+ }
1314
+ function importNodeDependencies() {
1315
+ if (hasImportedDependencies) return;
1316
+ try {
1317
+ const requireFn = getRequireFn();
1318
+ nodeCrypto = requireFn(
1319
+ /* webpackIgnore: true */
1320
+ "node:crypto"
1321
+ );
1322
+ nodeFsSync = requireFn(
1323
+ /* webpackIgnore: true */
1324
+ "node:fs"
1325
+ );
1326
+ nodeFs = requireFn(
1327
+ /* webpackIgnore: true */
1328
+ "node:fs/promises"
1329
+ );
1330
+ nodePath = requireFn(
1331
+ /* webpackIgnore: true */
1332
+ "node:path"
1333
+ );
1334
+ nodeOs = requireFn(
1335
+ /* webpackIgnore: true */
1336
+ "node:os"
1337
+ );
1338
+ nodeChildProcess = requireFn(
1339
+ /* webpackIgnore: true */
1340
+ "node:child_process"
1341
+ );
1342
+ nodeStream = requireFn(
1343
+ /* webpackIgnore: true */
1344
+ "node:stream/promises"
1345
+ );
1346
+ nodeUrl = requireFn(
1347
+ /* webpackIgnore: true */
1348
+ "node:url"
1349
+ );
1350
+ hasImportedDependencies = true;
1351
+ } catch (err) {
1352
+ console.warn(
1353
+ "Node.js modules not available, file system driver will not work",
1354
+ err
1355
+ );
1356
+ throw err;
1357
+ }
1358
+ }
1359
+ function getNodeFsSync() {
1360
+ if (!nodeFsSync) {
1361
+ throw new Error(
1362
+ "Node fs module not loaded. Ensure importNodeDependencies() has been called."
1363
+ );
1364
+ }
1365
+ return nodeFsSync;
1366
+ }
1367
+ function getNodePath() {
1368
+ if (!nodePath) {
1369
+ throw new Error(
1370
+ "Node path module not loaded. Ensure importNodeDependencies() has been called."
1371
+ );
1372
+ }
1373
+ return nodePath;
1374
+ }
1375
+
1158
1376
  // src/registry/runtime.ts
1159
1377
  function normalizeRuntimeSqlExecuteResult(result) {
1160
1378
  return result;
@@ -1176,6 +1394,9 @@ function asNativeConn(handle) {
1176
1394
  function asNativeWebSocket(handle) {
1177
1395
  return handle;
1178
1396
  }
1397
+ function asNativeSqlTransaction(handle) {
1398
+ return handle;
1399
+ }
1179
1400
  function asNativeCancellationToken(handle) {
1180
1401
  return handle;
1181
1402
  }
@@ -1205,9 +1426,45 @@ function toNapiSqlBindParams(params) {
1205
1426
  }
1206
1427
  return params.map((param) => toNapiSqlBindParam(param));
1207
1428
  }
1429
+ function toNapiSqlBatchStatement(statement) {
1430
+ return {
1431
+ sql: statement.sql,
1432
+ params: toNapiSqlBindParams(statement.params) ?? void 0
1433
+ };
1434
+ }
1208
1435
  function toNapiBuffer(value) {
1209
1436
  return Buffer.from(value);
1210
1437
  }
1438
+ function toNapiApplication(application) {
1439
+ return async (error, request) => {
1440
+ if (error) throw error;
1441
+ if (!request) {
1442
+ throw new Error("application fetch callback received no request");
1443
+ }
1444
+ const response = await application(
1445
+ {
1446
+ ...request,
1447
+ body: new Uint8Array(request.body),
1448
+ cancelToken: request.cancelToken
1449
+ },
1450
+ request.responseBodyStream ? fromNapiHttpResponseBodyStream(
1451
+ request.responseBodyStream
1452
+ ) : void 0
1453
+ );
1454
+ return {
1455
+ ...response,
1456
+ body: response.body === void 0 ? void 0 : toNapiBuffer(response.body)
1457
+ };
1458
+ };
1459
+ }
1460
+ function fromNapiHttpResponseBodyStream(stream) {
1461
+ return {
1462
+ cancelled: () => stream.cancelled(),
1463
+ write: (chunk) => stream.write(Buffer.from(chunk)),
1464
+ end: () => stream.end(),
1465
+ error: (message) => stream.error(message)
1466
+ };
1467
+ }
1211
1468
  function toNapiHttpRequest(request) {
1212
1469
  if (!request) {
1213
1470
  return request;
@@ -1272,14 +1529,37 @@ var NapiCoreRuntime = class {
1272
1529
  async serveRegistry(registry, config) {
1273
1530
  await asNativeRegistry(registry).serve(config);
1274
1531
  }
1532
+ async waitRegistryReady(registry) {
1533
+ await asNativeRegistry(registry).waitReady();
1534
+ }
1275
1535
  async shutdownRegistry(registry) {
1276
1536
  await asNativeRegistry(registry).shutdown();
1277
1537
  }
1278
- async registryDiagnostics(registry) {
1279
- const diagnostics = await asNativeRegistry(registry).diagnostics();
1538
+ async registryActorStopThresholdMs(registry) {
1539
+ return await asNativeRegistry(registry).actorStopThresholdMs() ?? void 0;
1540
+ }
1541
+ async registryHealth(registry) {
1542
+ const response = await asNativeRegistry(registry).health();
1543
+ return {
1544
+ status: response.status,
1545
+ headers: response.headers,
1546
+ body: response.body
1547
+ };
1548
+ }
1549
+ async registryMetadata(registry) {
1550
+ const response = asNativeRegistry(registry).metadata();
1280
1551
  return {
1281
- mode: diagnostics.mode,
1282
- envoyActiveActorCount: diagnostics.envoyActiveActorCount
1552
+ status: response.status,
1553
+ headers: response.headers,
1554
+ body: response.body
1555
+ };
1556
+ }
1557
+ async registryMetrics(registry) {
1558
+ const response = asNativeRegistry(registry).metrics();
1559
+ return {
1560
+ status: response.status,
1561
+ headers: response.headers,
1562
+ body: response.body
1283
1563
  };
1284
1564
  }
1285
1565
  async handleServerlessRequest(registry, req, onStreamEvent, cancelToken, config) {
@@ -1290,6 +1570,29 @@ var NapiCoreRuntime = class {
1290
1570
  config
1291
1571
  );
1292
1572
  }
1573
+ async serveListener(registry, listener, config) {
1574
+ const application = listener.application ? toNapiApplication(listener.application) : void 0;
1575
+ await asNativeRegistry(registry).serveListener(
1576
+ {
1577
+ port: listener.port,
1578
+ host: listener.host,
1579
+ publicDir: listener.publicDir
1580
+ },
1581
+ config,
1582
+ application
1583
+ );
1584
+ }
1585
+ async serveApplicationListener(registry, listener, config) {
1586
+ await asNativeRegistry(registry).serveApplicationListener(
1587
+ {
1588
+ port: listener.port,
1589
+ host: listener.host,
1590
+ publicDir: listener.publicDir
1591
+ },
1592
+ toNapiApplication(listener.application),
1593
+ config
1594
+ );
1595
+ }
1293
1596
  createActorFactory(callbacks, config) {
1294
1597
  return asActorFactoryHandle(
1295
1598
  new this.#bindings.NapiActorFactory(callbacks, config)
@@ -1298,11 +1601,16 @@ var NapiCoreRuntime = class {
1298
1601
  createCancellationToken() {
1299
1602
  return new this.#bindings.CancellationToken();
1300
1603
  }
1301
- createTestActorContext(actorId, name, region) {
1302
- return new this.#bindings.ActorContext(
1303
- actorId,
1304
- name,
1305
- region
1604
+ decodeInspectorRequest(bytes, advertisedVersion) {
1605
+ return this.#bindings.decodeInspectorRequest(
1606
+ toNapiBuffer(bytes),
1607
+ advertisedVersion
1608
+ );
1609
+ }
1610
+ encodeInspectorResponse(bytes, targetVersion) {
1611
+ return this.#bindings.encodeInspectorResponse(
1612
+ toNapiBuffer(bytes),
1613
+ targetVersion
1306
1614
  );
1307
1615
  }
1308
1616
  cancellationTokenAborted(token) {
@@ -1366,6 +1674,14 @@ var NapiCoreRuntime = class {
1366
1674
  toNapiStateDeltaPayload(payload)
1367
1675
  );
1368
1676
  }
1677
+ async actorSaveStateAndWorkflowBatch(ctx, writes) {
1678
+ await asNativeActorContext(ctx).saveStateAndWorkflowBatch(
1679
+ writes.map((write) => ({
1680
+ key: toNapiBuffer(write.key),
1681
+ value: toNapiBuffer(write.value)
1682
+ }))
1683
+ );
1684
+ }
1369
1685
  actorId(ctx) {
1370
1686
  return asNativeActorContext(ctx).actorId();
1371
1687
  }
@@ -1405,6 +1721,9 @@ var NapiCoreRuntime = class {
1405
1721
  async actorWaitForTrackedShutdownWork(ctx) {
1406
1722
  return await asNativeActorContext(ctx).waitForTrackedShutdownWork();
1407
1723
  }
1724
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
1725
+ await asNativeActorContext(ctx).waitForTrackedShutdownWorkUnbounded();
1726
+ }
1408
1727
  actorKeepAwake(ctx, promise) {
1409
1728
  asNativeActorContext(ctx).keepAwake(promise);
1410
1729
  }
@@ -1469,6 +1788,33 @@ var NapiCoreRuntime = class {
1469
1788
  );
1470
1789
  return normalizeRuntimeSqlExecuteResult(result);
1471
1790
  }
1791
+ async actorSqlExecuteBatch(ctx, statements) {
1792
+ const results = await this.#actorSql(ctx).executeBatch(
1793
+ statements.map(toNapiSqlBatchStatement)
1794
+ );
1795
+ return results.map(normalizeRuntimeSqlExecuteResult);
1796
+ }
1797
+ async actorSqlBeginTransaction(ctx, timeoutMs) {
1798
+ return await this.#actorSql(ctx).beginTransaction(
1799
+ timeoutMs
1800
+ );
1801
+ }
1802
+ async actorSqlTransactionExec(transaction, sql) {
1803
+ return await asNativeSqlTransaction(transaction).exec(sql);
1804
+ }
1805
+ async actorSqlTransactionExecute(transaction, sql, params) {
1806
+ const result = await asNativeSqlTransaction(transaction).execute(
1807
+ sql,
1808
+ toNapiSqlBindParams(params)
1809
+ );
1810
+ return normalizeRuntimeSqlExecuteResult(result);
1811
+ }
1812
+ async actorSqlTransactionCommit(transaction) {
1813
+ await asNativeSqlTransaction(transaction).commit();
1814
+ }
1815
+ async actorSqlTransactionRollback(transaction) {
1816
+ await asNativeSqlTransaction(transaction).rollback();
1817
+ }
1472
1818
  async actorSqlQuery(ctx, sql, params) {
1473
1819
  return await this.#actorSql(ctx).query(
1474
1820
  sql,
@@ -1495,6 +1841,9 @@ var NapiCoreRuntime = class {
1495
1841
  this.#sql.delete(nativeCtx);
1496
1842
  await database.close();
1497
1843
  }
1844
+ async actorRuntimeSocketProvision(ctx) {
1845
+ return await asNativeActorContext(ctx).provisionActorRuntimeSocket();
1846
+ }
1498
1847
  async actorQueueSend(ctx, name, body) {
1499
1848
  return toNapiQueueMessage(
1500
1849
  await asNativeActorContext(ctx).queue().send(name, toNapiBuffer(body))
@@ -1516,8 +1865,12 @@ var NapiCoreRuntime = class {
1516
1865
  )
1517
1866
  );
1518
1867
  }
1519
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
1520
- await asNativeActorContext(ctx).queue().waitForNamesAvailable(names, options);
1868
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
1869
+ await asNativeActorContext(ctx).queue().waitForNamesAvailable(
1870
+ names,
1871
+ options,
1872
+ signal ? asNativeCancellationToken(signal) : signal
1873
+ );
1521
1874
  }
1522
1875
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1523
1876
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
@@ -1536,11 +1889,54 @@ var NapiCoreRuntime = class {
1536
1889
  async actorQueueInspectMessages(ctx) {
1537
1890
  return await asNativeActorContext(ctx).queue().inspectMessages();
1538
1891
  }
1539
- actorScheduleAfter(ctx, durationMs, actionName, args) {
1540
- asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
1892
+ async actorQueueReset(ctx) {
1893
+ await asNativeActorContext(ctx).queue().reset();
1894
+ }
1895
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
1896
+ return await asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
1897
+ }
1898
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
1899
+ return await asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
1900
+ }
1901
+ async actorScheduleCancel(ctx, id) {
1902
+ return await asNativeActorContext(ctx).schedule().cancel(id);
1903
+ }
1904
+ async actorScheduleGet(ctx, id) {
1905
+ return await asNativeActorContext(ctx).schedule().get(id) ?? void 0;
1541
1906
  }
1542
- actorScheduleAt(ctx, timestampMs, actionName, args) {
1543
- asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
1907
+ async actorScheduleList(ctx) {
1908
+ return await asNativeActorContext(ctx).schedule().list();
1909
+ }
1910
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
1911
+ await asNativeActorContext(ctx).schedule().cronSet(
1912
+ name,
1913
+ expression,
1914
+ timezone,
1915
+ actionName,
1916
+ toNapiBuffer(args),
1917
+ maxHistory
1918
+ );
1919
+ }
1920
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
1921
+ await asNativeActorContext(ctx).schedule().cronEvery(
1922
+ name,
1923
+ intervalMs,
1924
+ actionName,
1925
+ toNapiBuffer(args),
1926
+ maxHistory
1927
+ );
1928
+ }
1929
+ async actorCronGet(ctx, name) {
1930
+ return await asNativeActorContext(ctx).schedule().cronGet(name) ?? void 0;
1931
+ }
1932
+ async actorCronList(ctx) {
1933
+ return await asNativeActorContext(ctx).schedule().cronList();
1934
+ }
1935
+ async actorCronDelete(ctx, name) {
1936
+ return await asNativeActorContext(ctx).schedule().cronDelete(name);
1937
+ }
1938
+ async actorCronHistory(ctx, name, limit) {
1939
+ return await asNativeActorContext(ctx).schedule().cronHistory(name, limit);
1544
1940
  }
1545
1941
  connId(conn) {
1546
1942
  return asNativeConn(conn).id();
@@ -1581,42 +1977,173 @@ async function loadNapiRuntime() {
1581
1977
  };
1582
1978
  }
1583
1979
 
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) {
1597
- if (!schema) {
1598
- return params;
1599
- }
1600
- const result = validateSchemaSync(
1601
- { [CONN_PARAMS_KEY]: schema },
1602
- CONN_PARAMS_KEY,
1603
- params
1980
+ // src/registry/native-http.ts
1981
+ var HTTP_BODY_CHUNK_SIZE = 64 * 1024;
1982
+ function runtimeBytesToArrayBuffer(value) {
1983
+ return value.buffer.slice(
1984
+ value.byteOffset,
1985
+ value.byteOffset + value.byteLength
1604
1986
  );
1605
- if (!result.success) {
1606
- throw validationError("connection params", result.issues);
1607
- }
1608
- return result.data;
1609
1987
  }
1610
- function validateEventArgs(schemas, name, args) {
1611
- if (!(schemas == null ? void 0 : schemas[name])) {
1612
- return args;
1613
- }
1614
- const payload = args.length <= 1 ? args[0] : args;
1615
- const result = validateSchemaSync(schemas, name, payload);
1616
- if (!result.success) {
1617
- throw validationError(`event \`${name}\` payload`, result.issues);
1988
+ function buildNativeHttpRequest(init) {
1989
+ var _a;
1990
+ const headers = new Headers(init.headers);
1991
+ const originalUrl = headers.get(HEADER_ORIGINAL_REQUEST_URL);
1992
+ headers.delete(HEADER_ORIGINAL_REQUEST_URL);
1993
+ const url = originalUrl ?? (init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString());
1994
+ const method2 = init.method.toUpperCase();
1995
+ const bodyForbidden = method2 === "GET" || method2 === "HEAD";
1996
+ const body = bodyForbidden ? void 0 : init.bodyStream ? new ReadableStream({
1997
+ async pull(controller) {
1998
+ var _a2, _b;
1999
+ try {
2000
+ if (init.body && init.body.length > 0) {
2001
+ controller.enqueue(new Uint8Array(init.body));
2002
+ init.body = void 0;
2003
+ return;
2004
+ }
2005
+ const chunk = await ((_a2 = init.bodyStream) == null ? void 0 : _a2.read());
2006
+ if (!chunk) {
2007
+ controller.close();
2008
+ } else {
2009
+ controller.enqueue(new Uint8Array(chunk));
2010
+ }
2011
+ } catch (error) {
2012
+ (_b = init.abortController) == null ? void 0 : _b.abort(error);
2013
+ controller.error(error);
2014
+ }
2015
+ },
2016
+ async cancel() {
2017
+ var _a2;
2018
+ await ((_a2 = init.bodyStream) == null ? void 0 : _a2.cancel());
2019
+ }
2020
+ }) : init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
2021
+ const streamInit = init.bodyStream && !bodyForbidden ? { duplex: "half" } : {};
2022
+ return new Request(url, {
2023
+ method: method2,
2024
+ headers,
2025
+ body,
2026
+ signal: ((_a = init.abortController) == null ? void 0 : _a.signal) ?? init.signal,
2027
+ ...streamInit
2028
+ });
2029
+ }
2030
+ async function cancelNativeHttpRequestBody(bodyStream) {
2031
+ await (bodyStream == null ? void 0 : bodyStream.cancel());
2032
+ }
2033
+ async function writeResponseChunk(stream, chunk) {
2034
+ for (let offset = 0; offset < chunk.byteLength; offset += HTTP_BODY_CHUNK_SIZE) {
2035
+ await stream.write(
2036
+ chunk.subarray(offset, offset + HTTP_BODY_CHUNK_SIZE)
2037
+ );
1618
2038
  }
1619
- return args.length <= 1 ? [result.data] : Array.isArray(result.data) ? result.data : [result.data];
2039
+ }
2040
+ async function pumpResponseBody(reader, stream) {
2041
+ var _a;
2042
+ const cancelled = stream.cancelled().then(() => ({ cancelled: true }));
2043
+ try {
2044
+ for (; ; ) {
2045
+ const read = reader.read().then((next2) => ({ cancelled: false, next: next2 }));
2046
+ const result = await Promise.race([read, cancelled]);
2047
+ if (result.cancelled) {
2048
+ await reader.cancel(
2049
+ new Error("native http response stream receiver dropped")
2050
+ );
2051
+ return;
2052
+ }
2053
+ const { next } = result;
2054
+ if (next.done) {
2055
+ await stream.end();
2056
+ return;
2057
+ }
2058
+ if ((_a = next.value) == null ? void 0 : _a.byteLength) {
2059
+ await writeResponseChunk(stream, next.value);
2060
+ }
2061
+ }
2062
+ } catch (error) {
2063
+ try {
2064
+ await stream.error(stringifyError(error));
2065
+ } catch (streamError) {
2066
+ logger2().debug({
2067
+ msg: "failed to report native http response stream error",
2068
+ error: streamError
2069
+ });
2070
+ }
2071
+ try {
2072
+ await reader.cancel(error);
2073
+ } catch {
2074
+ }
2075
+ } finally {
2076
+ reader.releaseLock();
2077
+ }
2078
+ }
2079
+ async function convertNativeHttpResponse(response, responseBodyStream) {
2080
+ const headers = Object.fromEntries(response.headers.entries());
2081
+ if (!response.body) {
2082
+ return {
2083
+ response: {
2084
+ status: response.status,
2085
+ headers,
2086
+ body: new Uint8Array()
2087
+ }
2088
+ };
2089
+ }
2090
+ if (responseBodyStream) {
2091
+ const reader = response.body.getReader();
2092
+ const bodyCompletion = pumpResponseBody(reader, responseBodyStream);
2093
+ return {
2094
+ response: {
2095
+ status: response.status,
2096
+ headers,
2097
+ stream: true
2098
+ },
2099
+ bodyCompletion
2100
+ };
2101
+ }
2102
+ return {
2103
+ response: {
2104
+ status: response.status,
2105
+ headers,
2106
+ body: new Uint8Array(await response.arrayBuffer())
2107
+ }
2108
+ };
2109
+ }
2110
+
2111
+ // src/registry/native-validation.ts
2112
+ var CONN_PARAMS_KEY = "__conn_params__";
2113
+ function validateActionArgs(schemas, name, args) {
2114
+ if (!(schemas == null ? void 0 : schemas[name])) {
2115
+ return args;
2116
+ }
2117
+ const result = validateSchemaSync(schemas, name, args);
2118
+ if (!result.success) {
2119
+ throw validationError(`action \`${name}\` arguments`, result.issues);
2120
+ }
2121
+ return Array.isArray(result.data) ? result.data : [result.data];
2122
+ }
2123
+ function validateConnParams(schema, params) {
2124
+ if (!schema) {
2125
+ return params;
2126
+ }
2127
+ const result = validateSchemaSync(
2128
+ { [CONN_PARAMS_KEY]: schema },
2129
+ CONN_PARAMS_KEY,
2130
+ params
2131
+ );
2132
+ if (!result.success) {
2133
+ throw validationError("connection params", result.issues);
2134
+ }
2135
+ return result.data;
2136
+ }
2137
+ function validateEventArgs(schemas, name, args) {
2138
+ if (!(schemas == null ? void 0 : schemas[name])) {
2139
+ return args;
2140
+ }
2141
+ const payload = args.length <= 1 ? args[0] : args;
2142
+ const result = validateSchemaSync(schemas, name, payload);
2143
+ if (!result.success) {
2144
+ throw validationError(`event \`${name}\` payload`, result.issues);
2145
+ }
2146
+ return args.length <= 1 ? [result.data] : Array.isArray(result.data) ? result.data : [result.data];
1620
2147
  }
1621
2148
  function validateQueueBody(schemas, name, body) {
1622
2149
  if (!(schemas == null ? void 0 : schemas[name])) {
@@ -1651,20 +2178,18 @@ function validateQueueComplete(schemas, name, response) {
1651
2178
  response
1652
2179
  );
1653
2180
  if (!result.success) {
1654
- throw validationError(`queue \`${name}\` completion response`, result.issues);
2181
+ throw validationError(
2182
+ `queue \`${name}\` completion response`,
2183
+ result.issues
2184
+ );
1655
2185
  }
1656
2186
  return result.data;
1657
2187
  }
1658
2188
  function validationError(target, issues) {
1659
- return new RivetError(
1660
- "actor",
1661
- "validation_error",
1662
- `Invalid ${target}`,
1663
- {
1664
- public: true,
1665
- metadata: { issues }
1666
- }
1667
- );
2189
+ return new RivetError("actor", "validation_error", `Invalid ${target}`, {
2190
+ public: true,
2191
+ metadata: { issues }
2192
+ });
1668
2193
  }
1669
2194
 
1670
2195
  // src/registry/wasm-runtime.ts
@@ -1819,11 +2344,26 @@ var WasmCoreRuntime = class {
1819
2344
  async serveRegistry(registry, config) {
1820
2345
  await callWasm(() => asWasmRegistry(registry).serve(config));
1821
2346
  }
2347
+ async waitRegistryReady() {
2348
+ throw new Error(
2349
+ "registry.startAndWait() is not supported by the WASM runtime"
2350
+ );
2351
+ }
1822
2352
  async shutdownRegistry(registry) {
1823
2353
  await callWasm(() => asWasmRegistry(registry).shutdown());
1824
2354
  }
1825
- async registryDiagnostics() {
1826
- return { mode: "wasm", envoyActiveActorCount: null };
2355
+ async registryHealth() {
2356
+ return {
2357
+ status: 200,
2358
+ headers: { "content-type": "application/json" },
2359
+ body: new TextEncoder().encode(
2360
+ JSON.stringify({
2361
+ status: "ok",
2362
+ runtime: "rivetkit",
2363
+ version: "wasm"
2364
+ })
2365
+ )
2366
+ };
1827
2367
  }
1828
2368
  async handleServerlessRequest(registry, req, onStreamEvent, cancelToken, config) {
1829
2369
  return await callHandleAsync(
@@ -1835,6 +2375,16 @@ var WasmCoreRuntime = class {
1835
2375
  config
1836
2376
  );
1837
2377
  }
2378
+ async serveListener(_registry, _listener, _config) {
2379
+ throw new Error(
2380
+ "registry.listen() is not supported on the wasm runtime; use registry.serve() and mount the handler in your platform's HTTP server instead"
2381
+ );
2382
+ }
2383
+ async serveApplicationListener(_registry, _listener, _config) {
2384
+ throw new Error(
2385
+ "registry.listen() is not supported on the wasm runtime; use an application-owned HTTP server instead"
2386
+ );
2387
+ }
1838
2388
  createActorFactory(callbacks, config) {
1839
2389
  return callWasmSync(
1840
2390
  () => asActorFactoryHandle2(
@@ -1934,6 +2484,13 @@ var WasmCoreRuntime = class {
1934
2484
  async actorSaveState(ctx, payload) {
1935
2485
  await callHandleAsync(asWasmActorContext(ctx), "saveState", payload);
1936
2486
  }
2487
+ async actorSaveStateAndWorkflowBatch(ctx, writes) {
2488
+ await callHandleAsync(
2489
+ asWasmActorContext(ctx),
2490
+ "saveStateAndWorkflowBatch",
2491
+ writes
2492
+ );
2493
+ }
1937
2494
  actorId(ctx) {
1938
2495
  return callHandle(asWasmActorContext(ctx), "actorId");
1939
2496
  }
@@ -1978,6 +2535,12 @@ var WasmCoreRuntime = class {
1978
2535
  "waitForTrackedShutdownWork"
1979
2536
  );
1980
2537
  }
2538
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
2539
+ await callHandle(
2540
+ asWasmActorContext(ctx),
2541
+ "waitForTrackedShutdownWorkUnbounded"
2542
+ );
2543
+ }
1981
2544
  actorKeepAwake(ctx, promise) {
1982
2545
  const wasmCtx = asWasmActorContext(ctx);
1983
2546
  const regionId = callHandle(wasmCtx, "beginKeepAwake");
@@ -2074,6 +2637,38 @@ var WasmCoreRuntime = class {
2074
2637
  );
2075
2638
  return normalizeRuntimeSqlExecuteResult(result);
2076
2639
  }
2640
+ async actorSqlExecuteBatch(ctx, statements) {
2641
+ const results = await callWasm(
2642
+ () => this.#actorSql(ctx).executeBatch(statements)
2643
+ );
2644
+ return results.map(normalizeRuntimeSqlExecuteResult);
2645
+ }
2646
+ async actorSqlBeginTransaction(ctx, timeoutMs) {
2647
+ return await callWasm(
2648
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs)
2649
+ );
2650
+ }
2651
+ async actorSqlTransactionExec(transaction, sql) {
2652
+ return await callWasm(
2653
+ () => transaction.exec(sql)
2654
+ );
2655
+ }
2656
+ async actorSqlTransactionExecute(transaction, sql, params) {
2657
+ const result = await callWasm(
2658
+ () => transaction.execute(sql, params)
2659
+ );
2660
+ return normalizeRuntimeSqlExecuteResult(result);
2661
+ }
2662
+ async actorSqlTransactionCommit(transaction) {
2663
+ await callWasm(
2664
+ () => transaction.commit()
2665
+ );
2666
+ }
2667
+ async actorSqlTransactionRollback(transaction) {
2668
+ await callWasm(
2669
+ () => transaction.rollback()
2670
+ );
2671
+ }
2077
2672
  async actorSqlQuery(ctx, sql, params) {
2078
2673
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
2079
2674
  }
@@ -2097,6 +2692,17 @@ var WasmCoreRuntime = class {
2097
2692
  this.#sql.delete(wasmCtx);
2098
2693
  await callWasm(() => database.close());
2099
2694
  }
2695
+ async actorRuntimeSocketProvision(_ctx) {
2696
+ throw new RivetError(
2697
+ "actor_runtime_socket",
2698
+ "unsupported",
2699
+ "Actor Runtime Socket is only available on Unix native runtimes.",
2700
+ {
2701
+ public: true,
2702
+ metadata: { runtime: "wasm" }
2703
+ }
2704
+ );
2705
+ }
2100
2706
  async actorQueueSend(ctx, name, body) {
2101
2707
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2102
2708
  return normalizeQueueMessage(
@@ -2125,9 +2731,15 @@ var WasmCoreRuntime = class {
2125
2731
  )
2126
2732
  );
2127
2733
  }
2128
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
2734
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
2129
2735
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2130
- await callHandleAsync(queue2, "waitForNamesAvailable", names, options);
2736
+ await callHandleAsync(
2737
+ queue2,
2738
+ "waitForNamesAvailable",
2739
+ names,
2740
+ options,
2741
+ signal
2742
+ );
2131
2743
  }
2132
2744
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
2133
2745
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
@@ -2158,13 +2770,101 @@ var WasmCoreRuntime = class {
2158
2770
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2159
2771
  return await callHandleAsync(queue2, "inspectMessages");
2160
2772
  }
2161
- actorScheduleAfter(ctx, durationMs, actionName, args) {
2773
+ async actorQueueReset(ctx) {
2774
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2775
+ await callHandleAsync(queue2, "reset");
2776
+ }
2777
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
2778
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2779
+ return await callHandleAsync(
2780
+ schedule,
2781
+ "after",
2782
+ wasmNumber(durationMs),
2783
+ actionName,
2784
+ args
2785
+ );
2786
+ }
2787
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
2788
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2789
+ return await callHandleAsync(
2790
+ schedule,
2791
+ "at",
2792
+ wasmNumber(timestampMs),
2793
+ actionName,
2794
+ args
2795
+ );
2796
+ }
2797
+ async actorScheduleCancel(ctx, id) {
2798
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2799
+ return await callHandleAsync(schedule, "cancel", id);
2800
+ }
2801
+ async actorScheduleGet(ctx, id) {
2802
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2803
+ return await callHandleAsync(
2804
+ schedule,
2805
+ "get",
2806
+ id
2807
+ );
2808
+ }
2809
+ async actorScheduleList(ctx) {
2810
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2811
+ return await callHandleAsync(
2812
+ schedule,
2813
+ "list"
2814
+ );
2815
+ }
2816
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
2817
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2818
+ await callHandleAsync(
2819
+ schedule,
2820
+ "cronSet",
2821
+ name,
2822
+ expression,
2823
+ timezone,
2824
+ actionName,
2825
+ args,
2826
+ maxHistory
2827
+ );
2828
+ }
2829
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
2830
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2831
+ await callHandleAsync(
2832
+ schedule,
2833
+ "cronEvery",
2834
+ name,
2835
+ intervalMs,
2836
+ actionName,
2837
+ args,
2838
+ maxHistory
2839
+ );
2840
+ }
2841
+ async actorCronGet(ctx, name) {
2842
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2843
+ return await callHandleAsync(
2844
+ schedule,
2845
+ "cronGet",
2846
+ name
2847
+ );
2848
+ }
2849
+ async actorCronList(ctx) {
2850
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2851
+ return await callHandleAsync(
2852
+ schedule,
2853
+ "cronList"
2854
+ );
2855
+ }
2856
+ async actorCronDelete(ctx, name) {
2162
2857
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2163
- callHandle(schedule, "after", wasmNumber(durationMs), actionName, args);
2858
+ return await callHandleAsync(schedule, "cronDelete", name);
2164
2859
  }
2165
- actorScheduleAt(ctx, timestampMs, actionName, args) {
2860
+ async actorCronHistory(ctx, name, limit) {
2166
2861
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
2167
- callHandle(schedule, "at", wasmNumber(timestampMs), actionName, args);
2862
+ return await callHandleAsync(
2863
+ schedule,
2864
+ "cronHistory",
2865
+ name,
2866
+ limit
2867
+ );
2168
2868
  }
2169
2869
  connId(conn) {
2170
2870
  return callHandle(asWasmConn(conn), "id");
@@ -2219,6 +2919,29 @@ async function loadWasmRuntime(config) {
2219
2919
  };
2220
2920
  }
2221
2921
 
2922
+ // src/registry/write-through-proxy.ts
2923
+ import onChange from "@rivetkit/on-change";
2924
+ function createWriteThroughProxy(value, commit, beforeChange) {
2925
+ if (!value || typeof value !== "object") {
2926
+ return value;
2927
+ }
2928
+ return onChange(
2929
+ value,
2930
+ () => {
2931
+ commit(value);
2932
+ },
2933
+ {
2934
+ // Rejection is throw-based: beforeChange throws to prevent the
2935
+ // mutation. We always return true so on-change applies the change
2936
+ // if beforeChange did not throw.
2937
+ onValidate(_path, newValue) {
2938
+ beforeChange == null ? void 0 : beforeChange(newValue);
2939
+ return true;
2940
+ }
2941
+ }
2942
+ );
2943
+ }
2944
+
2222
2945
  // src/registry/native.ts
2223
2946
  var textEncoder = new TextEncoder();
2224
2947
  var textDecoder = new TextDecoder();
@@ -2372,6 +3095,14 @@ function databaseNotConfiguredError() {
2372
3095
  { public: true }
2373
3096
  );
2374
3097
  }
3098
+ function databaseClientNotReadyError() {
3099
+ return new RivetError(
3100
+ "actor",
3101
+ "database_client_not_ready",
3102
+ "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.",
3103
+ { public: true }
3104
+ );
3105
+ }
2375
3106
  function stateNotEnabledError() {
2376
3107
  return new RivetError(
2377
3108
  "actor",
@@ -2423,8 +3154,23 @@ function resolveNativeDestroy(runtime, ctx) {
2423
3154
  function clearNativeRuntimeState(runtime, ctx) {
2424
3155
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
2425
3156
  }
2426
- async function cleanupNativeSleepRuntimeState(runtime, ctx) {
2427
- await runtime.actorWaitForTrackedShutdownWork(ctx);
3157
+ async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrained) {
3158
+ const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
3159
+ if (!drained) {
3160
+ await closeNativeDatabaseClient(runtime, ctx);
3161
+ await closeNativeSqlDatabase(runtime, ctx);
3162
+ void runtime.actorWaitForTrackedShutdownWorkUnbounded(ctx).then(async () => {
3163
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
3164
+ clearNativeRuntimeState(runtime, ctx);
3165
+ }).catch((error) => {
3166
+ logger2().warn({
3167
+ msg: "deferred native sleep cleanup failed",
3168
+ error: stringifyError(error)
3169
+ });
3170
+ });
3171
+ return;
3172
+ }
3173
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
2428
3174
  await closeNativeDatabaseClient(runtime, ctx);
2429
3175
  await closeNativeSqlDatabase(runtime, ctx);
2430
3176
  clearNativeRuntimeState(runtime, ctx);
@@ -2458,6 +3204,23 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
2458
3204
  const database = wrapJsNativeDatabase({
2459
3205
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
2460
3206
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
3207
+ executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
3208
+ beginTransaction: async (timeoutMs) => {
3209
+ const transaction = await runtime.actorSqlBeginTransaction(
3210
+ ctx,
3211
+ timeoutMs
3212
+ );
3213
+ return {
3214
+ exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
3215
+ execute: (sql, params) => runtime.actorSqlTransactionExecute(
3216
+ transaction,
3217
+ sql,
3218
+ params
3219
+ ),
3220
+ commit: () => runtime.actorSqlTransactionCommit(transaction),
3221
+ rollback: () => runtime.actorSqlTransactionRollback(transaction)
3222
+ };
3223
+ },
2461
3224
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
2462
3225
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
2463
3226
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -2479,7 +3242,7 @@ function toRuntimeBytes(value) {
2479
3242
  function arrayBufferViewToRuntimeBytes(value) {
2480
3243
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
2481
3244
  }
2482
- function runtimeBytesToArrayBuffer(value) {
3245
+ function runtimeBytesToArrayBuffer2(value) {
2483
3246
  return value.buffer.slice(
2484
3247
  value.byteOffset,
2485
3248
  value.byteOffset + value.byteLength
@@ -2529,11 +3292,14 @@ function decodeValue(value) {
2529
3292
  if (!value || value.length === 0) {
2530
3293
  return void 0;
2531
3294
  }
2532
- return decodeCborJsonCompat(value);
3295
+ return decodeCborCompat(value);
2533
3296
  }
2534
3297
  function encodeValue(value) {
2535
3298
  return encodeCborCompat(value);
2536
3299
  }
3300
+ function normalizeArgs(value) {
3301
+ return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
3302
+ }
2537
3303
  function unwrapTsfnPayload(error, payload) {
2538
3304
  if (error !== null && error !== void 0) {
2539
3305
  throw error;
@@ -2589,12 +3355,6 @@ function callNativeSync(invoke) {
2589
3355
  throw normalizeNativeBridgeError(error);
2590
3356
  }
2591
3357
  }
2592
- function actorAbortedError() {
2593
- return Object.assign(new Error("Actor aborted"), {
2594
- group: "actor",
2595
- code: "aborted"
2596
- });
2597
- }
2598
3358
  function isClosedTaskRegistrationError(error) {
2599
3359
  const metadata = error instanceof RivetError ? error.metadata : void 0;
2600
3360
  const metadataError = metadata && typeof metadata === "object" && "error" in metadata ? metadata.error : void 0;
@@ -2720,6 +3480,14 @@ function serializeWorkflowEntryKind(kind) {
2720
3480
  originalName: kind.val.originalName
2721
3481
  }
2722
3482
  };
3483
+ case "WorkflowVersionCheckEntry":
3484
+ return {
3485
+ tag: kind.tag,
3486
+ val: {
3487
+ resolved: kind.val.resolved,
3488
+ latest: kind.val.latest
3489
+ }
3490
+ };
2723
3491
  }
2724
3492
  }
2725
3493
  function serializeWorkflowHistoryForJson(data) {
@@ -2727,7 +3495,7 @@ function serializeWorkflowHistoryForJson(data) {
2727
3495
  return null;
2728
3496
  }
2729
3497
  const history = decodeWorkflowHistoryTransport(data);
2730
- return {
3498
+ return jsonSafe({
2731
3499
  nameRegistry: [...history.nameRegistry],
2732
3500
  entries: history.entries.map((entry) => ({
2733
3501
  id: entry.id,
@@ -2751,7 +3519,7 @@ function serializeWorkflowHistoryForJson(data) {
2751
3519
  ]
2752
3520
  )
2753
3521
  )
2754
- };
3522
+ });
2755
3523
  }
2756
3524
  function toHttpJsonCompatible(value) {
2757
3525
  return JSON.parse(
@@ -2802,63 +3570,7 @@ function wrapNativeCallback(callback) {
2802
3570
  }
2803
3571
  function decodeArgs(value) {
2804
3572
  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
- };
3573
+ return normalizeArgs(decoded);
2862
3574
  }
2863
3575
  function toActorKey(segments) {
2864
3576
  return segments.map(
@@ -2894,13 +3606,23 @@ var NativeConnAdapter = class {
2894
3606
  decodeValue(this.#runtime.connParams(this.#conn))
2895
3607
  );
2896
3608
  }
3609
+ [RAW_STATE_SYMBOL]() {
3610
+ return this.#readState();
3611
+ }
2897
3612
  get state() {
2898
3613
  const nextState = this.#readState();
2899
- return createWriteThroughProxy(nextState, (nextValue) => {
2900
- this.#writeState(nextValue, { writeNative: true });
2901
- });
3614
+ return createWriteThroughProxy(
3615
+ nextState,
3616
+ (nextValue) => {
3617
+ this.#writeState(nextValue, { writeNative: true });
3618
+ },
3619
+ (newValue) => {
3620
+ assertJsonCompatValue(newValue);
3621
+ }
3622
+ );
2902
3623
  }
2903
3624
  set state(value) {
3625
+ assertJsonCompatValue(value);
2904
3626
  this.#writeState(value, { writeNative: true });
2905
3627
  }
2906
3628
  initializeState(value) {
@@ -2974,47 +3696,137 @@ var NativeScheduleAdapter = class {
2974
3696
  this.#ctx = ctx;
2975
3697
  }
2976
3698
  async after(duration, action, ...args) {
2977
- callNativeSync(
2978
- () => this.#runtime.actorScheduleAfter(
2979
- this.#ctx,
2980
- duration,
2981
- action,
2982
- encodeValue(args)
2983
- )
3699
+ return await this.#runtime.actorScheduleAfter(
3700
+ this.#ctx,
3701
+ duration,
3702
+ action,
3703
+ encodeValue(args)
2984
3704
  );
2985
3705
  }
2986
3706
  async at(timestamp, action, ...args) {
2987
- callNativeSync(
2988
- () => this.#runtime.actorScheduleAt(
2989
- this.#ctx,
2990
- timestamp,
2991
- action,
2992
- encodeValue(args)
2993
- )
3707
+ return await this.#runtime.actorScheduleAt(
3708
+ this.#ctx,
3709
+ timestamp,
3710
+ action,
3711
+ encodeValue(args)
3712
+ );
3713
+ }
3714
+ async cancel(id) {
3715
+ return await this.#runtime.actorScheduleCancel(this.#ctx, id);
3716
+ }
3717
+ async get(id) {
3718
+ const event2 = await this.#runtime.actorScheduleGet(this.#ctx, id);
3719
+ return event2 ? decodeScheduledEventInfo(event2) : void 0;
3720
+ }
3721
+ async list() {
3722
+ return (await this.#runtime.actorScheduleList(this.#ctx)).map(
3723
+ decodeScheduledEventInfo
2994
3724
  );
2995
3725
  }
2996
3726
  };
2997
- var NativeKvAdapter = class {
3727
+ var NativeCronAdapter = class {
2998
3728
  #runtime;
2999
3729
  #ctx;
3000
3730
  constructor(runtime, ctx) {
3001
3731
  this.#runtime = runtime;
3002
3732
  this.#ctx = ctx;
3003
3733
  }
3004
- async get(key, options) {
3005
- const value = await callNative(
3006
- () => this.#runtime.actorKvGet(
3007
- this.#ctx,
3008
- makePrefixedKey(encodeNativeKvUserKey(key))
3009
- )
3734
+ async set(options) {
3735
+ await this.#runtime.actorCronSet(
3736
+ this.#ctx,
3737
+ options.name,
3738
+ options.expression,
3739
+ options.timezone,
3740
+ options.action,
3741
+ encodeValue(options.args ?? []),
3742
+ options.maxHistory
3010
3743
  );
3011
- return value ? decodeNativeKvValue(new Uint8Array(value), options) : null;
3012
3744
  }
3013
- async put(key, value, _options) {
3014
- await callNative(
3015
- () => this.#runtime.actorKvPut(
3016
- this.#ctx,
3017
- makePrefixedKey(encodeNativeKvUserKey(key)),
3745
+ async every(options) {
3746
+ await this.#runtime.actorCronEvery(
3747
+ this.#ctx,
3748
+ options.name,
3749
+ options.interval,
3750
+ options.action,
3751
+ encodeValue(options.args ?? []),
3752
+ options.maxHistory
3753
+ );
3754
+ }
3755
+ async get(name) {
3756
+ const job = await this.#runtime.actorCronGet(this.#ctx, name);
3757
+ return job ? decodeCronJobInfo(job) : void 0;
3758
+ }
3759
+ async list() {
3760
+ return (await this.#runtime.actorCronList(this.#ctx)).map(
3761
+ decodeCronJobInfo
3762
+ );
3763
+ }
3764
+ async delete(name) {
3765
+ return await this.#runtime.actorCronDelete(this.#ctx, name);
3766
+ }
3767
+ async history(name, options) {
3768
+ return (await this.#runtime.actorCronHistory(
3769
+ this.#ctx,
3770
+ name,
3771
+ options == null ? void 0 : options.limit
3772
+ )).map(decodeCronFire);
3773
+ }
3774
+ };
3775
+ function decodeScheduledEventInfo(event2) {
3776
+ return {
3777
+ id: event2.id,
3778
+ action: event2.action,
3779
+ args: decodeArgs(event2.args),
3780
+ runAt: event2.runAt
3781
+ };
3782
+ }
3783
+ function decodeCronJobInfo(job) {
3784
+ const base = {
3785
+ name: job.name,
3786
+ action: job.action,
3787
+ args: decodeArgs(job.args),
3788
+ nextRunAt: job.nextRunAt,
3789
+ lastRunAt: job.lastRunAt,
3790
+ maxHistory: job.maxHistory
3791
+ };
3792
+ if (job.kind === "cron") {
3793
+ return {
3794
+ ...base,
3795
+ kind: "cron",
3796
+ expression: job.expression,
3797
+ timezone: job.timezone
3798
+ };
3799
+ }
3800
+ return {
3801
+ ...base,
3802
+ kind: "every",
3803
+ interval: job.intervalMs
3804
+ };
3805
+ }
3806
+ function decodeCronFire(fire) {
3807
+ return { ...fire };
3808
+ }
3809
+ var NativeKvAdapter = class {
3810
+ #runtime;
3811
+ #ctx;
3812
+ constructor(runtime, ctx) {
3813
+ this.#runtime = runtime;
3814
+ this.#ctx = ctx;
3815
+ }
3816
+ async get(key, options) {
3817
+ const value = await callNative(
3818
+ () => this.#runtime.actorKvGet(
3819
+ this.#ctx,
3820
+ makePrefixedKey(encodeNativeKvUserKey(key))
3821
+ )
3822
+ );
3823
+ return value ? decodeNativeKvValue(new Uint8Array(value), options) : null;
3824
+ }
3825
+ async put(key, value, _options) {
3826
+ await callNative(
3827
+ () => this.#runtime.actorKvPut(
3828
+ this.#ctx,
3829
+ makePrefixedKey(encodeNativeKvUserKey(key)),
3018
3830
  toRuntimeBytes(value)
3019
3831
  )
3020
3832
  );
@@ -3252,44 +4064,23 @@ var NativeQueueAdapter = class {
3252
4064
  }
3253
4065
  }
3254
4066
  async waitForNamesAvailable(names, options) {
3255
- if (!(options == null ? void 0 : options.signal)) {
4067
+ const { token, cleanup } = await createCancellationTokenHandle(
4068
+ this.#runtime,
4069
+ options == null ? void 0 : options.signal
4070
+ );
4071
+ try {
3256
4072
  await callNative(
3257
4073
  () => this.#runtime.actorQueueWaitForNamesAvailable(
3258
4074
  this.#ctx,
3259
4075
  [...names],
3260
4076
  {
3261
4077
  timeoutMs: options == null ? void 0 : options.timeout
3262
- }
4078
+ },
4079
+ token
3263
4080
  )
3264
4081
  );
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
- }
4082
+ } finally {
4083
+ cleanup == null ? void 0 : cleanup();
3293
4084
  }
3294
4085
  }
3295
4086
  async enqueueAndWait(name, body, options) {
@@ -3359,7 +4150,7 @@ var NativeQueueAdapter = class {
3359
4150
  }
3360
4151
  yield message;
3361
4152
  } catch (error) {
3362
- if (isRivetErrorLike(error) && error.group === "actor" && error.code === "aborted") {
4153
+ if (isActorAbortedError(error)) {
3363
4154
  return;
3364
4155
  }
3365
4156
  throw error;
@@ -3445,7 +4236,7 @@ var NativeWebSocketAdapter = class {
3445
4236
  this.#runtime.webSocketSetEventCallback(this.#ws, (event2) => {
3446
4237
  if (event2.kind === "message") {
3447
4238
  this.#virtual.triggerMessage(
3448
- event2.binary ? runtimeBytesToArrayBuffer(event2.data) : event2.data,
4239
+ event2.binary ? runtimeBytesToArrayBuffer2(event2.data) : event2.data,
3449
4240
  event2.messageIndex
3450
4241
  );
3451
4242
  return;
@@ -3724,6 +4515,68 @@ var TrackedWebSocketHandleAdapter = class {
3724
4515
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
3725
4516
  }
3726
4517
  };
4518
+ var NativeConnectionMap = class {
4519
+ #runtime;
4520
+ #ctx;
4521
+ #schemas;
4522
+ constructor(runtime, ctx, schemas) {
4523
+ this.#runtime = runtime;
4524
+ this.#ctx = ctx;
4525
+ this.#schemas = schemas;
4526
+ }
4527
+ #connToAdapter(conn) {
4528
+ return new NativeConnAdapter(
4529
+ this.#runtime,
4530
+ conn,
4531
+ this.#schemas,
4532
+ this.#ctx,
4533
+ (connId) => callNativeSync(
4534
+ () => this.#runtime.actorQueueHibernationRemoval(
4535
+ this.#ctx,
4536
+ connId
4537
+ )
4538
+ )
4539
+ );
4540
+ }
4541
+ get size() {
4542
+ return callNativeSync(() => this.#runtime.actorConns(this.#ctx)).length;
4543
+ }
4544
+ get(key) {
4545
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4546
+ const conn = conns.find((c) => this.#runtime.connId(c) === key);
4547
+ if (!conn) return void 0;
4548
+ return this.#connToAdapter(conn);
4549
+ }
4550
+ has(key) {
4551
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4552
+ return conns.some((c) => this.#runtime.connId(c) === key);
4553
+ }
4554
+ keys() {
4555
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4556
+ return conns.map((c) => this.#runtime.connId(c))[Symbol.iterator]();
4557
+ }
4558
+ values() {
4559
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4560
+ return conns.map((c) => this.#connToAdapter(c))[Symbol.iterator]();
4561
+ }
4562
+ entries() {
4563
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4564
+ return conns.map(
4565
+ (c) => [this.#runtime.connId(c), this.#connToAdapter(c)]
4566
+ )[Symbol.iterator]();
4567
+ }
4568
+ forEach(callback, thisArg) {
4569
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
4570
+ for (const conn of conns) {
4571
+ const id = this.#runtime.connId(conn);
4572
+ callback.call(thisArg, this.#connToAdapter(conn), id, this);
4573
+ }
4574
+ }
4575
+ [Symbol.iterator]() {
4576
+ return this.entries();
4577
+ }
4578
+ [Symbol.toStringTag] = "NativeConnectionMap";
4579
+ };
3727
4580
  var ActorContextHandleAdapter = class {
3728
4581
  #runtime;
3729
4582
  #ctx;
@@ -3732,9 +4585,10 @@ var ActorContextHandleAdapter = class {
3732
4585
  #abortSignalCleanup;
3733
4586
  #client;
3734
4587
  #clientFactory;
4588
+ #connMap;
4589
+ #cron;
3735
4590
  #databaseProvider;
3736
4591
  #db;
3737
- #dbProxy;
3738
4592
  #dispatchCancelToken;
3739
4593
  #kv;
3740
4594
  #queue;
@@ -3773,55 +4627,59 @@ var ActorContextHandleAdapter = class {
3773
4627
  }
3774
4628
  return this.#sql;
3775
4629
  }
4630
+ async actorRuntimeSocket() {
4631
+ return await callNative(
4632
+ () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
4633
+ );
4634
+ }
3776
4635
  get db() {
3777
4636
  if (!this.#databaseProvider) {
3778
4637
  throw databaseNotConfiguredError();
3779
4638
  }
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
- );
4639
+ if (this.#db) {
4640
+ return this.#db;
4641
+ }
4642
+ const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4643
+ const cachedClient = runtimeState.databaseClient;
4644
+ if (cachedClient) {
4645
+ this.#db = cachedClient.client;
4646
+ return this.#db;
3802
4647
  }
3803
- return this.#dbProxy;
4648
+ throw databaseClientNotReadyError();
4649
+ }
4650
+ [RAW_STATE_SYMBOL]() {
4651
+ if (!this.#stateEnabled) {
4652
+ throw stateNotEnabledError();
4653
+ }
4654
+ return this.#readState();
3804
4655
  }
3805
4656
  get state() {
3806
4657
  if (!this.#stateEnabled) {
3807
4658
  throw stateNotEnabledError();
3808
4659
  }
4660
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
3809
4661
  const nextState = this.#readState();
3810
- return createWriteThroughProxy(
3811
- nextState,
3812
- (nextValue) => {
3813
- this.#writeState(nextValue, { scheduleSave: true });
3814
- },
3815
- () => {
3816
- this.#assertCanMutateState();
3817
- }
3818
- );
4662
+ if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
4663
+ actorState.stateProxyTarget = nextState;
4664
+ actorState.stateProxy = createWriteThroughProxy(
4665
+ nextState,
4666
+ (nextValue) => {
4667
+ this.#writeState(nextValue, { scheduleSave: true });
4668
+ },
4669
+ (newValue) => {
4670
+ this.#assertCanMutateState();
4671
+ assertJsonCompatValue(newValue);
4672
+ }
4673
+ );
4674
+ }
4675
+ return actorState.stateProxy;
3819
4676
  }
3820
4677
  set state(value) {
3821
4678
  if (!this.#stateEnabled) {
3822
4679
  throw stateNotEnabledError();
3823
4680
  }
3824
4681
  this.#assertCanMutateState();
4682
+ assertJsonCompatValue(value);
3825
4683
  this.#writeState(value, { scheduleSave: true });
3826
4684
  }
3827
4685
  initializeState(value) {
@@ -3863,6 +4721,12 @@ var ActorContextHandleAdapter = class {
3863
4721
  }
3864
4722
  return this.#schedule;
3865
4723
  }
4724
+ get cron() {
4725
+ if (!this.#cron) {
4726
+ this.#cron = new NativeCronAdapter(this.#runtime, this.#ctx);
4727
+ }
4728
+ return this.#cron;
4729
+ }
3866
4730
  get actorId() {
3867
4731
  return callNativeSync(() => this.#runtime.actorId(this.#ctx));
3868
4732
  }
@@ -3878,25 +4742,14 @@ var ActorContextHandleAdapter = class {
3878
4742
  return callNativeSync(() => this.#runtime.actorRegion(this.#ctx));
3879
4743
  }
3880
4744
  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
- );
4745
+ if (!this.#connMap) {
4746
+ this.#connMap = new NativeConnectionMap(
4747
+ this.#runtime,
4748
+ this.#ctx,
4749
+ this.#schemas
4750
+ );
4751
+ }
4752
+ return this.#connMap;
3900
4753
  }
3901
4754
  get log() {
3902
4755
  return logger2();
@@ -4058,6 +4911,11 @@ var ActorContextHandleAdapter = class {
4058
4911
  () => this.#runtime.actorRequestSave(this.#ctx, { immediate: false })
4059
4912
  );
4060
4913
  }
4914
+ async saveStateAndWorkflowBatch(writes) {
4915
+ await callNative(
4916
+ () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
4917
+ );
4918
+ }
4061
4919
  serializeForTick(reason) {
4062
4920
  void reason;
4063
4921
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4117,7 +4975,10 @@ var ActorContextHandleAdapter = class {
4117
4975
  }
4118
4976
  internalKeepAwake(run) {
4119
4977
  const promise = typeof run === "function" ? run() : run;
4120
- const trackedPromise = promise.then(() => null);
4978
+ const trackedPromise = promise.then(
4979
+ () => null,
4980
+ () => null
4981
+ );
4121
4982
  try {
4122
4983
  callNativeSync(
4123
4984
  () => this.#runtime.actorRegisterTask(this.#ctx, trackedPromise)
@@ -4173,6 +5034,7 @@ var ActorContextHandleAdapter = class {
4173
5034
  return false;
4174
5035
  }
4175
5036
  sleep() {
5037
+ this.#flushStateChange();
4176
5038
  callNativeSync(() => this.#runtime.actorSleep(this.#ctx));
4177
5039
  }
4178
5040
  destroy() {
@@ -4190,6 +5052,7 @@ var ActorContextHandleAdapter = class {
4190
5052
  }
4191
5053
  async dispose() {
4192
5054
  var _a;
5055
+ this.#flushStateChange();
4193
5056
  (_a = this.#abortSignalCleanup) == null ? void 0 : _a.call(this);
4194
5057
  this.#sql = void 0;
4195
5058
  }
@@ -4217,13 +5080,12 @@ var ActorContextHandleAdapter = class {
4217
5080
  return actorState.state;
4218
5081
  }
4219
5082
  #writeState(value, options) {
4220
- encodeValue(value);
4221
5083
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4222
5084
  actorState.state = value;
4223
5085
  if (!options.scheduleSave) {
4224
5086
  return;
4225
5087
  }
4226
- this.#handleStateChange();
5088
+ this.#scheduleSave();
4227
5089
  }
4228
5090
  #assertCanMutateState() {
4229
5091
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4231,9 +5093,31 @@ var ActorContextHandleAdapter = class {
4231
5093
  throw stateMutationReentrantError();
4232
5094
  }
4233
5095
  }
4234
- #handleStateChange() {
5096
+ // Coalesce the request-save and onStateChange work to once per event loop
5097
+ // tick. A synchronous burst of mutations (for example
5098
+ // `Object.assign(c.state, ...)`) would otherwise cross the NAPI boundary and
5099
+ // run onStateChange once per field, re-serializing the whole state each time
5100
+ // and pinning the event loop on large state.
5101
+ #scheduleSave() {
5102
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5103
+ if (actorState.saveScheduled) {
5104
+ return;
5105
+ }
5106
+ actorState.saveScheduled = true;
5107
+ actorState.pendingSaveHandle = setImmediate(() => {
5108
+ this.#flushStateChange();
5109
+ });
5110
+ }
5111
+ #flushStateChange() {
4235
5112
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4236
- encodeValue(actorState.state);
5113
+ if (!actorState.saveScheduled) {
5114
+ return;
5115
+ }
5116
+ actorState.saveScheduled = false;
5117
+ if (actorState.pendingSaveHandle !== void 0) {
5118
+ clearImmediate(actorState.pendingSaveHandle);
5119
+ actorState.pendingSaveHandle = void 0;
5120
+ }
4237
5121
  callNativeSync(
4238
5122
  () => this.#runtime.actorRequestSave(this.#ctx, { immediate: false })
4239
5123
  );
@@ -4346,6 +5230,9 @@ var NativeWorkflowRuntimeAdapter = class {
4346
5230
  this.stateManager = {
4347
5231
  saveState: async (opts) => {
4348
5232
  await this.#ctx.saveState(opts);
5233
+ },
5234
+ saveStateAndWorkflowBatch: async (writes) => {
5235
+ await this.#ctx.saveStateAndWorkflowBatch(writes);
4349
5236
  }
4350
5237
  };
4351
5238
  }
@@ -4411,15 +5298,17 @@ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databa
4411
5298
  }
4412
5299
  );
4413
5300
  }
4414
- function buildActorConfig(definition, registryConfig) {
5301
+ function buildActorConfig(definition, registryConfig, runtimeKind) {
4415
5302
  const config = definition.config;
4416
5303
  const options = config.options ?? {};
4417
5304
  const canHibernate = options.canHibernateWebSocket;
5305
+ const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
4418
5306
  return {
4419
5307
  name: options.name,
4420
5308
  icon: options.icon,
4421
- hasDatabase: config.db !== void 0,
4422
- remoteSqlite: config.db !== void 0 && sqliteBackendForConfig(registryConfig) === "remote",
5309
+ hasDatabase: config.db !== void 0 || usesRemoteSqlite,
5310
+ remoteSqlite: usesRemoteSqlite,
5311
+ enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
4423
5312
  hasState: config.state !== void 0 || typeof config.createState === "function",
4424
5313
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
4425
5314
  stateSaveIntervalMs: options.stateSaveInterval,
@@ -4435,27 +5324,99 @@ function buildActorConfig(definition, registryConfig) {
4435
5324
  connectionLivenessTimeoutMs: options.connectionLivenessTimeout,
4436
5325
  connectionLivenessIntervalMs: options.connectionLivenessInterval,
4437
5326
  maxQueueSize: options.maxQueueSize,
5327
+ maxSchedules: options.maxSchedules,
4438
5328
  maxQueueMessageSize: options.maxQueueMessageSize,
4439
5329
  maxIncomingMessageSize: registryConfig.maxIncomingMessageSize,
4440
5330
  maxOutgoingMessageSize: registryConfig.maxOutgoingMessageSize,
4441
5331
  preloadMaxWorkflowBytes: options.preloadMaxWorkflowBytes,
4442
5332
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes,
4443
- actions: Object.keys(config.actions ?? {}).sort().map((name) => ({ name }))
5333
+ actions: Object.keys(flattenActionHandlers(config.actions)).sort().map((name) => ({ name })),
5334
+ inspectorTabs: buildInspectorTabs(config.inspector, runtimeKind)
4444
5335
  };
4445
5336
  }
5337
+ function buildInspectorTabs(inspector, runtimeKind) {
5338
+ if (!inspector || typeof inspector !== "object") return void 0;
5339
+ const tabs = inspector.tabs;
5340
+ if (!Array.isArray(tabs) || tabs.length === 0) return void 0;
5341
+ return tabs.map((raw) => {
5342
+ const entry = raw;
5343
+ if (entry.hidden === true) {
5344
+ return { id: entry.id, hidden: true };
5345
+ }
5346
+ if (runtimeKind === "wasm") {
5347
+ if (entry.source !== void 0) {
5348
+ logger2().warn(
5349
+ {
5350
+ tabId: entry.id,
5351
+ runtimeKind
5352
+ },
5353
+ "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."
5354
+ );
5355
+ }
5356
+ return {
5357
+ id: entry.id,
5358
+ label: entry.label,
5359
+ icon: entry.icon,
5360
+ source: void 0
5361
+ };
5362
+ }
5363
+ const resolved = entry.source !== void 0 ? getNodePath().resolve(entry.source) : void 0;
5364
+ if (resolved !== void 0) {
5365
+ validateInspectorTabSource(entry.id, resolved);
5366
+ }
5367
+ return {
5368
+ id: entry.id,
5369
+ label: entry.label,
5370
+ icon: entry.icon,
5371
+ source: resolved
5372
+ };
5373
+ });
5374
+ }
5375
+ function validateInspectorTabSource(tabId, resolved) {
5376
+ if (resolved === getNodePath().parse(resolved).root) {
5377
+ throw new Error(
5378
+ `inspector.tabs[id="${tabId}"].source resolves to the filesystem root (${resolved}). Point it at the tab's own static-asset directory instead.`
5379
+ );
5380
+ }
5381
+ let stat;
5382
+ try {
5383
+ stat = getNodeFsSync().statSync(resolved);
5384
+ } catch (err) {
5385
+ const code = err == null ? void 0 : err.code;
5386
+ if (code === "ENOENT") {
5387
+ throw new Error(
5388
+ `inspector.tabs[id="${tabId}"].source (${resolved}) does not exist.`
5389
+ );
5390
+ }
5391
+ if (code === "EACCES") {
5392
+ throw new Error(
5393
+ `inspector.tabs[id="${tabId}"].source (${resolved}) is not readable (EACCES).`
5394
+ );
5395
+ }
5396
+ throw new Error(
5397
+ `inspector.tabs[id="${tabId}"].source (${resolved}) could not be stat'd: ${(err == null ? void 0 : err.message) ?? err}`
5398
+ );
5399
+ }
5400
+ if (!stat.isDirectory()) {
5401
+ throw new Error(
5402
+ `inspector.tabs[id="${tabId}"].source (${resolved}) must be a directory, got ${stat.isFile() ? "file" : "non-directory"}.`
5403
+ );
5404
+ }
5405
+ }
4446
5406
  function buildNativeFactory(runtime, registryConfig, definition) {
4447
5407
  var _a;
4448
5408
  const config = definition.config;
4449
5409
  const databaseProvider = config.db;
5410
+ const actionHandlers = flattenActionHandlers(config.actions);
4450
5411
  const schemaConfig = {
4451
- actionInputSchemas: config.actionInputSchemas,
5412
+ actionInputSchemas: flattenActionInputSchemas(
5413
+ config.actions,
5414
+ config.actionInputSchemas
5415
+ ),
4452
5416
  connParamsSchema: config.connParamsSchema,
4453
5417
  events: config.events,
4454
5418
  queues: config.queues
4455
5419
  };
4456
- const actionHandlers = Object.fromEntries(
4457
- Object.entries(config.actions ?? {}).map(([name, handler]) => [name, handler])
4458
- );
4459
5420
  const createClient = () => createClientWithDriver(
4460
5421
  new RemoteEngineControlClient(
4461
5422
  convertRegistryConfigToClientConfig(registryConfig)
@@ -4507,12 +5468,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4507
5468
  onStateChange,
4508
5469
  cancelToken
4509
5470
  );
4510
- const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
5471
+ const maybeHandleNativeInspectorRequest = async (ctx, rawRequest) => {
4511
5472
  var _a2, _b, _c, _d;
4512
- const url = new URL(jsRequest.url);
5473
+ const rawUrl = rawRequest.uri.startsWith("http") ? rawRequest.uri : new URL(rawRequest.uri, "http://127.0.0.1").toString();
5474
+ const url = new URL(rawUrl);
4513
5475
  if (!url.pathname.startsWith("/inspector/")) {
4514
5476
  return void 0;
4515
5477
  }
5478
+ const jsRequest = buildNativeHttpRequest(rawRequest);
4516
5479
  const jsonResponse = (body, init) => new Response(JSON.stringify(body), {
4517
5480
  status: (init == null ? void 0 : init.status) ?? 200,
4518
5481
  headers: {
@@ -4534,13 +5497,16 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4534
5497
  }
4535
5498
  );
4536
5499
  };
4537
- try {
4538
- await runtime.actorVerifyInspectorAuth(
4539
- ctx,
4540
- ((_a2 = jsRequest.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) ?? null
4541
- );
4542
- } catch (error) {
4543
- return errorResponse(error, 401);
5500
+ const isPublicPerActorPath = jsRequest.method === "GET" && url.pathname.startsWith("/inspector/custom-tabs/");
5501
+ if (!isPublicPerActorPath) {
5502
+ try {
5503
+ await runtime.actorVerifyInspectorAuth(
5504
+ ctx,
5505
+ ((_a2 = jsRequest.headers.get("authorization")) == null ? void 0 : _a2.replace(/^Bearer\s+/i, "")) ?? null
5506
+ );
5507
+ } catch (error) {
5508
+ return errorResponse(error, 401);
5509
+ }
4544
5510
  }
4545
5511
  const workflowHistory = () => {
4546
5512
  var _a3;
@@ -4607,6 +5573,47 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4607
5573
  messages
4608
5574
  });
4609
5575
  }
5576
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "DELETE") {
5577
+ await runtime.actorQueueReset(ctx);
5578
+ return jsonResponse({});
5579
+ }
5580
+ if (url.pathname === "/inspector/queue" && jsRequest.method === "POST") {
5581
+ let body;
5582
+ try {
5583
+ body = await jsRequest.json();
5584
+ } catch {
5585
+ return errorResponse(
5586
+ new RivetError(
5587
+ "actor",
5588
+ "invalid_request",
5589
+ "Invalid inspector JSON body",
5590
+ { public: true }
5591
+ ),
5592
+ 400
5593
+ );
5594
+ }
5595
+ const name = body.name ?? "";
5596
+ if (name === "") {
5597
+ return errorResponse(
5598
+ new RivetError(
5599
+ "actor",
5600
+ "invalid_request",
5601
+ "Queue message name must not be empty",
5602
+ { public: true }
5603
+ ),
5604
+ 400
5605
+ );
5606
+ }
5607
+ const cbor = encodeCborCompat(
5608
+ body.body ?? null
5609
+ );
5610
+ const message = await runtime.actorQueueSend(ctx, name, cbor);
5611
+ return jsonResponse({
5612
+ id: message.id().toString(),
5613
+ name: message.name(),
5614
+ createdAtMs: message.createdAt()
5615
+ });
5616
+ }
4610
5617
  if (url.pathname === "/inspector/traces" && jsRequest.method === "GET") {
4611
5618
  return jsonResponse({ otlp: [], clamped: false });
4612
5619
  }
@@ -4631,6 +5638,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4631
5638
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0
4632
5639
  });
4633
5640
  } catch (error) {
5641
+ logger2().error({
5642
+ msg: "error replaying workflow history",
5643
+ error
5644
+ });
4634
5645
  return errorResponse(error);
4635
5646
  }
4636
5647
  }
@@ -4771,17 +5782,34 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4771
5782
  );
4772
5783
  }
4773
5784
  const body = await jsRequest.json();
5785
+ if (body.args !== void 0 && body.properties !== void 0) {
5786
+ return jsonResponse(
5787
+ { error: "use either args or properties, not both" },
5788
+ { status: 400 }
5789
+ );
5790
+ }
5791
+ if (body.properties !== void 0 && (body.properties === null || typeof body.properties !== "object" || Array.isArray(body.properties))) {
5792
+ return jsonResponse(
5793
+ { error: "properties must be an object" },
5794
+ { status: 400 }
5795
+ );
5796
+ }
5797
+ const args = body.properties !== void 0 ? [body.properties] : normalizeArgs(body.args);
4774
5798
  try {
4775
5799
  const output = await action(
4776
5800
  actorCtx,
4777
5801
  ...validateActionArgs(
4778
5802
  schemaConfig.actionInputSchemas,
4779
5803
  actionName,
4780
- body.args ?? []
5804
+ args
4781
5805
  )
4782
5806
  );
4783
5807
  return jsonResponse({ output });
4784
5808
  } catch (error) {
5809
+ logger2().error({
5810
+ msg: "Error handling inspector action request",
5811
+ error
5812
+ });
4785
5813
  return errorResponse(error);
4786
5814
  }
4787
5815
  }
@@ -4795,6 +5823,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4795
5823
  { status: 404 }
4796
5824
  );
4797
5825
  } catch (error) {
5826
+ logger2().error({
5827
+ msg: "Error handling inspector request",
5828
+ error
5829
+ });
4798
5830
  return errorResponse(error);
4799
5831
  } finally {
4800
5832
  await actorCtx.dispose();
@@ -4917,24 +5949,30 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4917
5949
  async (error, payload) => {
4918
5950
  const { ctx } = unwrapTsfnPayload(error, payload);
4919
5951
  const actorCtx = makeActorCtx(ctx);
5952
+ const saveActorState = async () => {
5953
+ if (runtime.kind === "wasm") {
5954
+ await runtime.actorSaveState(
5955
+ ctx,
5956
+ actorCtx.serializeForTick("save")
5957
+ );
5958
+ } else {
5959
+ await actorCtx.saveState({
5960
+ immediate: true
5961
+ });
5962
+ }
5963
+ };
4920
5964
  try {
4921
5965
  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
- }
5966
+ await onSleep(actorCtx);
4934
5967
  }
5968
+ await saveActorState();
4935
5969
  } finally {
4936
5970
  try {
4937
- await cleanupNativeSleepRuntimeState(runtime, ctx);
5971
+ await cleanupNativeSleepRuntimeState(
5972
+ runtime,
5973
+ ctx,
5974
+ saveActorState
5975
+ );
4938
5976
  } finally {
4939
5977
  await actorCtx.dispose();
4940
5978
  }
@@ -4950,6 +5988,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4950
5988
  await config.onDestroy(actorCtx);
4951
5989
  }
4952
5990
  } finally {
5991
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5992
+ nativeRunHandlerActiveByActorId.delete(actorId);
5993
+ disposeRunInspector(config.run, actorId);
4953
5994
  resolveNativeDestroy(runtime, ctx);
4954
5995
  await actorCtx.closeDatabase();
4955
5996
  clearNativeRuntimeState(runtime, ctx);
@@ -4965,7 +6006,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4965
6006
  );
4966
6007
  const actorCtx = makeActorCtx(
4967
6008
  ctx,
4968
- request ? buildRequest(request) : void 0
6009
+ request ? buildNativeHttpRequest(request) : void 0
4969
6010
  );
4970
6011
  try {
4971
6012
  await config.onBeforeConnect(
@@ -4985,7 +6026,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4985
6026
  const { ctx, conn, params, request } = unwrapTsfnPayload(error, payload);
4986
6027
  const actorCtx = makeActorCtx(
4987
6028
  ctx,
4988
- request ? buildRequest(request) : void 0
6029
+ request ? buildNativeHttpRequest(request) : void 0
4989
6030
  );
4990
6031
  const connAdapter = new NativeConnAdapter(
4991
6032
  runtime,
@@ -5022,7 +6063,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5022
6063
  );
5023
6064
  const actorCtx = makeActorCtx(
5024
6065
  ctx,
5025
- request ? buildRequest(request) : void 0
6066
+ request ? buildNativeHttpRequest(request) : void 0
5026
6067
  );
5027
6068
  const connAdapter = new NativeConnAdapter(
5028
6069
  runtime,
@@ -5127,27 +6168,45 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5127
6168
  onRequest: wrapNativeCallback(
5128
6169
  async (error, payload) => {
5129
6170
  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
- );
6171
+ const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error, payload);
6172
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(ctx, request);
5140
6173
  if (inspectorResponse) {
5141
- return await toRuntimeHttpResponse(inspectorResponse);
6174
+ await cancelNativeHttpRequestBody(request.bodyStream);
6175
+ return (await convertNativeHttpResponse(
6176
+ inspectorResponse,
6177
+ responseBodyStream
6178
+ )).response;
5142
6179
  }
5143
6180
  if (typeof config.onRequest !== "function") {
5144
- return await toRuntimeHttpResponse(
5145
- new Response(null, { status: 404 })
5146
- );
6181
+ await cancelNativeHttpRequestBody(request.bodyStream);
6182
+ return (await convertNativeHttpResponse(
6183
+ new Response(null, { status: 404 }),
6184
+ responseBodyStream
6185
+ )).response;
5147
6186
  }
5148
- const rawConnParams = jsRequest.headers.get(HEADER_CONN_PARAMS);
6187
+ const requestAbortController = new AbortController();
6188
+ const handlerRequest = buildNativeHttpRequest({
6189
+ ...request,
6190
+ abortController: requestAbortController
6191
+ });
6192
+ const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
5149
6193
  let requestCtx;
5150
6194
  let conn;
6195
+ let removeRequestAbortListener;
6196
+ let cleanupDeferredToBody = false;
6197
+ let cleanedUp = false;
6198
+ const cleanupRequest = async () => {
6199
+ if (cleanedUp) return;
6200
+ cleanedUp = true;
6201
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
6202
+ try {
6203
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
6204
+ } finally {
6205
+ if (conn) {
6206
+ await runtime.connDisconnect(conn);
6207
+ }
6208
+ }
6209
+ };
5151
6210
  try {
5152
6211
  const connParams = validateConnParams(
5153
6212
  schemaConfig.connParamsSchema,
@@ -5163,23 +6222,56 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5163
6222
  requestCtx = makeConnCtx(
5164
6223
  ctx,
5165
6224
  conn,
5166
- jsRequest,
6225
+ handlerRequest,
5167
6226
  cancelToken
5168
6227
  );
6228
+ const ctxAbortSignal = requestCtx.abortSignal;
6229
+ const abortRequest = () => requestAbortController.abort(ctxAbortSignal.reason);
6230
+ if (ctxAbortSignal.aborted) {
6231
+ abortRequest();
6232
+ } else {
6233
+ ctxAbortSignal.addEventListener(
6234
+ "abort",
6235
+ abortRequest,
6236
+ { once: true }
6237
+ );
6238
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
6239
+ "abort",
6240
+ abortRequest
6241
+ );
6242
+ }
5169
6243
  const response = await config.onRequest(
5170
6244
  requestCtx,
5171
- jsRequest
6245
+ handlerRequest
5172
6246
  );
5173
- if (!(response instanceof Response)) {
6247
+ if (!isResponseLike(response)) {
5174
6248
  throw new Error(
5175
6249
  "onRequest handler must return a Response"
5176
6250
  );
5177
6251
  }
5178
- return await toRuntimeHttpResponse(response);
6252
+ const conversion = await convertNativeHttpResponse(
6253
+ response,
6254
+ responseBodyStream
6255
+ );
6256
+ if (conversion.bodyCompletion) {
6257
+ cleanupDeferredToBody = true;
6258
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
6259
+ logger2().error({
6260
+ msg: "failed to clean up native streaming http request",
6261
+ error: cleanupError
6262
+ });
6263
+ });
6264
+ }
6265
+ return conversion.response;
5179
6266
  } finally {
5180
- await (requestCtx == null ? void 0 : requestCtx.dispose());
5181
- if (conn) {
5182
- await runtime.connDisconnect(conn);
6267
+ try {
6268
+ await cancelNativeHttpRequestBody(
6269
+ request.bodyStream
6270
+ );
6271
+ } finally {
6272
+ if (!cleanupDeferredToBody) {
6273
+ await cleanupRequest();
6274
+ }
5183
6275
  }
5184
6276
  }
5185
6277
  } catch (error2) {
@@ -5194,7 +6286,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5194
6286
  onWebSocket: typeof config.onWebSocket === "function" ? wrapNativeCallback(
5195
6287
  async (error, payload) => {
5196
6288
  const { ctx, conn, ws, request } = unwrapTsfnPayload(error, payload);
5197
- const jsRequest = request ? buildRequest(request) : void 0;
6289
+ const jsRequest = request ? buildNativeHttpRequest(request) : void 0;
5198
6290
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
5199
6291
  try {
5200
6292
  await config.onWebSocket(
@@ -5223,7 +6315,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5223
6315
  try {
5224
6316
  await run(actorCtx);
5225
6317
  } finally {
5226
- nativeRunHandlerActiveByActorId.set(actorId, false);
6318
+ nativeRunHandlerActiveByActorId.delete(actorId);
5227
6319
  await actorCtx.dispose();
5228
6320
  }
5229
6321
  }
@@ -5258,7 +6350,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5258
6350
  name,
5259
6351
  wrapNativeCallback(
5260
6352
  async (error, payload) => {
5261
- const { ctx, conn, args, cancelToken } = unwrapTsfnPayload(error, payload);
6353
+ const { ctx, conn, args, scheduledFire, cancelToken } = unwrapTsfnPayload(error, payload);
5262
6354
  const actorCtx = conn != null ? makeConnCtx(ctx, conn, void 0, cancelToken) : makeActorCtx(ctx, void 0, cancelToken);
5263
6355
  try {
5264
6356
  return encodeValue(
@@ -5268,7 +6360,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5268
6360
  schemaConfig.actionInputSchemas,
5269
6361
  name,
5270
6362
  decodeArgs(args)
5271
- )
6363
+ ),
6364
+ ...scheduledFire ? [scheduledFire] : []
5272
6365
  )
5273
6366
  );
5274
6367
  } finally {
@@ -5290,7 +6383,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5290
6383
  timeoutMs,
5291
6384
  cancelToken
5292
6385
  } = unwrapTsfnPayload(error, payload);
5293
- const jsRequest = buildRequest(request);
6386
+ const jsRequest = buildNativeHttpRequest(request);
5294
6387
  const actorCtx = withConnContext(
5295
6388
  runtime,
5296
6389
  ctx,
@@ -5356,7 +6449,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5356
6449
  };
5357
6450
  return runtime.createActorFactory(
5358
6451
  callbacks,
5359
- buildActorConfig(definition, registryConfig)
6452
+ buildActorConfig(definition, registryConfig, runtime.kind)
5360
6453
  );
5361
6454
  }
5362
6455
  async function buildServeConfig(config) {
@@ -5379,10 +6472,17 @@ async function buildServeConfig(config) {
5379
6472
  serverlessValidateEndpoint: config.validateServerlessEndpoint,
5380
6473
  serverlessMaxStartPayloadBytes: config.serverless.maxStartPayloadBytes
5381
6474
  };
5382
- if (config.startEngine) {
6475
+ try {
5383
6476
  const { getEnginePath } = await loadEngineCli();
5384
6477
  serveConfig.engineBinaryPath = getEnginePath();
6478
+ } catch (error) {
6479
+ logger2().warn({
6480
+ 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",
6481
+ error: stringifyError(error)
6482
+ });
5385
6483
  }
6484
+ serveConfig.engineHost = config.engineHost;
6485
+ serveConfig.enginePort = config.enginePort;
5386
6486
  if ((_a = config.test) == null ? void 0 : _a.enabled) {
5387
6487
  serveConfig.inspectorTestToken = getEnvUniversal("_RIVET_TEST_INSPECTOR_TOKEN") ?? "token";
5388
6488
  }
@@ -5393,6 +6493,9 @@ async function buildRegistryWithRuntime(config, runtime) {
5393
6493
  if (((_a = config.test) == null ? void 0 : _a.enabled) && getEnvUniversal("_RIVET_TEST_INSPECTOR_TOKEN") === void 0) {
5394
6494
  trySetProcessEnv("_RIVET_TEST_INSPECTOR_TOKEN", "token");
5395
6495
  }
6496
+ if (runtime.kind === "napi") {
6497
+ importNodeDependencies();
6498
+ }
5396
6499
  const registry = runtime.createRegistry();
5397
6500
  for (const [name, definition] of Object.entries(config.use)) {
5398
6501
  runtime.registerActor(
@@ -5416,8 +6519,73 @@ async function buildConfiguredRegistry(config) {
5416
6519
  }
5417
6520
 
5418
6521
  // src/registry/index.ts
6522
+ var REGISTRY_READY_TIMEOUT_MS = 3e4;
6523
+ function signalExitCode(signal) {
6524
+ switch (signal) {
6525
+ case "SIGINT":
6526
+ return 130;
6527
+ case "SIGTERM":
6528
+ return 143;
6529
+ }
6530
+ }
6531
+ function finishShutdownSignal(signal) {
6532
+ if (process.pid === 1) {
6533
+ process.exit(signalExitCode(signal));
6534
+ }
6535
+ process.kill(process.pid, signal);
6536
+ }
6537
+ function createApplicationFetch(application, runtime) {
6538
+ return async (request, responseBodyStream) => {
6539
+ const method2 = request.method.toUpperCase();
6540
+ const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
6541
+ const abortController = new AbortController();
6542
+ if (request.cancelToken) {
6543
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
6544
+ abortController.abort();
6545
+ } else {
6546
+ runtime.onCancellationTokenCancelled(
6547
+ request.cancelToken,
6548
+ () => abortController.abort()
6549
+ );
6550
+ }
6551
+ }
6552
+ const response = await application.fetch(
6553
+ new Request(request.url, {
6554
+ method: method2,
6555
+ headers: request.headers,
6556
+ body,
6557
+ signal: abortController.signal
6558
+ })
6559
+ );
6560
+ if (!isResponseLike(response)) {
6561
+ throw new TypeError(
6562
+ "registry.listen() application fetch must return a Response"
6563
+ );
6564
+ }
6565
+ const conversion = await convertNativeHttpResponse(
6566
+ response,
6567
+ responseBodyStream
6568
+ );
6569
+ if (conversion.bodyCompletion) {
6570
+ void conversion.bodyCompletion.catch((error) => {
6571
+ logger2().error({
6572
+ msg: "application response stream failed",
6573
+ error
6574
+ });
6575
+ });
6576
+ }
6577
+ return {
6578
+ status: conversion.response.status ?? response.status,
6579
+ headers: conversion.response.headers ?? Object.fromEntries(response.headers.entries()),
6580
+ body: conversion.response.body,
6581
+ stream: conversion.response.stream
6582
+ };
6583
+ };
6584
+ }
5419
6585
  var Registry = class {
5420
6586
  #config;
6587
+ #buildConfiguredRegistry;
6588
+ routes;
5421
6589
  get config() {
5422
6590
  return this.#config;
5423
6591
  }
@@ -5425,25 +6593,44 @@ var Registry = class {
5425
6593
  return RegistryConfigSchema.parse(this.#config);
5426
6594
  }
5427
6595
  #runtimeServePromise;
6596
+ #runtimeServeLifecyclePromise;
6597
+ #runtimeReadyPromise;
5428
6598
  #runtimeServeConfiguredPromise;
5429
6599
  #runtimeServerlessPromise;
6600
+ #applicationListenerPromise;
5430
6601
  #configureServerlessPoolPromise;
5431
6602
  #welcomePrinted = false;
5432
6603
  #shutdownInstalled = false;
5433
6604
  #shutdownInFlight = null;
5434
6605
  #signalHandlers = {};
5435
- constructor(config) {
6606
+ constructor(config, deps) {
6607
+ var _a;
5436
6608
  this.#config = config;
6609
+ if ((_a = config.logging) == null ? void 0 : _a.baseLogger) {
6610
+ configureBaseLogger(config.logging.baseLogger);
6611
+ }
6612
+ this.#buildConfiguredRegistry = (deps == null ? void 0 : deps.buildConfiguredRegistry) ?? buildConfiguredRegistry;
6613
+ this.routes = {
6614
+ health: () => this.#healthRoute(),
6615
+ metadata: () => this.#metadataRoute(),
6616
+ prometheusMetrics: (request) => this.#prometheusMetricsRoute(request)
6617
+ };
5437
6618
  }
6619
+ /**
6620
+ * Fires `configureServerlessPool` once per process when the registry
6621
+ * config opts into it. Cached on the instance so repeated calls (from
6622
+ * `handler()` and `listen()`) only run the upsert once. The retry loop
6623
+ * inside `configureServerlessPool` tolerates the engine still warming up.
6624
+ */
5438
6625
  #ensureServerlessPoolConfigured(config) {
5439
6626
  if (!config.configurePool) return void 0;
5440
6627
  if (!this.#configureServerlessPoolPromise) {
5441
- this.#configureServerlessPoolPromise = configureServerlessPool(config).catch(
5442
- (error) => {
5443
- this.#configureServerlessPoolPromise = void 0;
5444
- throw error;
5445
- }
5446
- );
6628
+ this.#configureServerlessPoolPromise = configureServerlessPool(
6629
+ config
6630
+ ).catch((error) => {
6631
+ this.#configureServerlessPoolPromise = void 0;
6632
+ throw error;
6633
+ });
5447
6634
  this.#configureServerlessPoolPromise.catch(() => {
5448
6635
  });
5449
6636
  }
@@ -5464,7 +6651,7 @@ var Registry = class {
5464
6651
  const config = this.parseConfig();
5465
6652
  this.#printWelcome(config, "serverless");
5466
6653
  if (!this.#runtimeServerlessPromise) {
5467
- this.#runtimeServerlessPromise = buildConfiguredRegistry(config);
6654
+ this.#runtimeServerlessPromise = this.#buildConfiguredRegistry(config);
5468
6655
  }
5469
6656
  const { runtime, registry, serveConfig } = await this.#runtimeServerlessPromise;
5470
6657
  const isStartRequest = isServerlessStartRequest(
@@ -5479,7 +6666,7 @@ var Registry = class {
5479
6666
  if (isStartRequest) {
5480
6667
  try {
5481
6668
  await this.#ensureServerlessPoolConfigured(config);
5482
- } catch (error) {
6669
+ } catch (_error) {
5483
6670
  return new Response(
5484
6671
  JSON.stringify({
5485
6672
  group: "guard",
@@ -5593,7 +6780,7 @@ var Registry = class {
5593
6780
  if (isMetadataRequest && !isEngineMetadataRequest) {
5594
6781
  try {
5595
6782
  await this.#ensureServerlessPoolConfigured(config);
5596
- } catch (error) {
6783
+ } catch (_error) {
5597
6784
  return new Response(
5598
6785
  JSON.stringify({
5599
6786
  group: "guard",
@@ -5626,40 +6813,205 @@ var Registry = class {
5626
6813
  fetch: (request) => this.handler(request)
5627
6814
  };
5628
6815
  }
5629
- async diagnostics() {
5630
- var _a;
6816
+ /**
6817
+ * Bind an HTTP listener provided by the native (Rust) runtime and serve
6818
+ * the registry's serverless endpoints over it. Resolves only after the
6819
+ * registry is shut down (SIGINT/SIGTERM or `nativeRegistry.shutdown()`).
6820
+ *
6821
+ * @param opts.port Port to listen on. Defaults to `process.env.RIVET_PORT`
6822
+ * if set, otherwise 3000.
6823
+ * @param opts.host Address to bind. Defaults to `0.0.0.0`.
6824
+ * @param opts.publicDir If set, serves static files from this directory
6825
+ * as a fallback below the framework routes.
6826
+ * @param opts.application If set, handles requests that do not match a
6827
+ * framework route.
6828
+ *
6829
+ * @example
6830
+ * ```ts
6831
+ * await registry.listen();
6832
+ * await registry.listen({ application: app });
6833
+ * ```
6834
+ */
6835
+ async listen(opts = {}) {
6836
+ const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
6837
+ const publicDir = opts.publicDir ?? getRivetkitPublicDir();
6838
+ const config = this.parseConfig();
6839
+ if (opts.application && getRivetkitRuntimeMode() !== "serverless") {
6840
+ if (config.runtime === "wasm") {
6841
+ throw new Error(
6842
+ "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
6843
+ );
6844
+ }
6845
+ this.#installSignalHandlers(config);
6846
+ this.#printWelcome(config, "serverful", {
6847
+ port,
6848
+ host: opts.host,
6849
+ publicDir
6850
+ });
6851
+ this.#startEnvoy(config, true);
6852
+ const readyPromise = this.startAndWait();
6853
+ const configuredRegistryPromise2 = this.#runtimeServeConfiguredPromise;
6854
+ if (!configuredRegistryPromise2) {
6855
+ throw new Error("registry envoy startup did not initialize");
6856
+ }
6857
+ const { runtime: runtime2, registry: registry2, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
6858
+ const application2 = createApplicationFetch(
6859
+ opts.application,
6860
+ runtime2
6861
+ );
6862
+ await readyPromise;
6863
+ const listenerPromise = runtime2.serveApplicationListener(
6864
+ registry2,
6865
+ {
6866
+ port,
6867
+ host: opts.host,
6868
+ publicDir,
6869
+ application: application2
6870
+ },
6871
+ serveConfig2
6872
+ );
6873
+ this.#applicationListenerPromise = listenerPromise;
6874
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
6875
+ if (!serveLifecyclePromise) {
6876
+ throw new Error(
6877
+ "registry envoy serve lifecycle did not initialize"
6878
+ );
6879
+ }
6880
+ await Promise.all([
6881
+ listenerPromise,
6882
+ serveLifecyclePromise
6883
+ ]);
6884
+ return;
6885
+ }
6886
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
6887
+ this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
6888
+ this.#runtimeServerlessPromise = configuredRegistryPromise;
6889
+ this.#installSignalHandlers(config);
6890
+ this.#printWelcome(config, "serverless", {
6891
+ port,
6892
+ host: opts.host,
6893
+ publicDir
6894
+ });
6895
+ this.#ensureServerlessPoolConfigured(config);
6896
+ const { runtime, registry, serveConfig } = await configuredRegistryPromise;
6897
+ const application = opts.application ? createApplicationFetch(opts.application, runtime) : void 0;
6898
+ await runtime.serveListener(
6899
+ registry,
6900
+ {
6901
+ port,
6902
+ host: opts.host,
6903
+ publicDir,
6904
+ application
6905
+ },
6906
+ serveConfig
6907
+ );
6908
+ }
6909
+ /**
6910
+ * Returns a health response suitable for mounting in a user-owned router.
6911
+ */
6912
+ async #healthRoute() {
6913
+ const configured = await this.#activeConfiguredRegistry();
6914
+ if (!configured) {
6915
+ return jsonRouteResponse(503, {
6916
+ status: "not_started",
6917
+ runtime: "rivetkit",
6918
+ version: VERSION
6919
+ });
6920
+ }
6921
+ const { runtime, registry } = configured;
6922
+ if (!runtime.registryHealth) {
6923
+ return jsonRouteResponse(501, {
6924
+ status: "unsupported",
6925
+ runtime: "rivetkit",
6926
+ version: VERSION
6927
+ });
6928
+ }
6929
+ const response = await runtime.registryHealth(registry);
6930
+ return new Response(new Uint8Array(response.body), {
6931
+ status: response.status,
6932
+ headers: response.headers
6933
+ });
6934
+ }
6935
+ /**
6936
+ * Returns serverless metadata suitable for mounting in a user-owned router.
6937
+ */
6938
+ async #metadataRoute() {
6939
+ const configured = await this.#activeConfiguredRegistry();
6940
+ if (!configured) {
6941
+ return new Response("registry not started\n", {
6942
+ status: 503,
6943
+ headers: { "content-type": "text/plain; charset=utf-8" }
6944
+ });
6945
+ }
6946
+ const { runtime, registry } = configured;
6947
+ if (!runtime.registryMetadata) {
6948
+ return new Response("metadata is not supported by this runtime\n", {
6949
+ status: 501,
6950
+ headers: { "content-type": "text/plain; charset=utf-8" }
6951
+ });
6952
+ }
6953
+ const response = await runtime.registryMetadata(registry);
6954
+ return new Response(new Uint8Array(response.body), {
6955
+ status: response.status,
6956
+ headers: response.headers
6957
+ });
6958
+ }
6959
+ /**
6960
+ * Returns a Prometheus metrics response suitable for mounting in a user-owned router.
6961
+ */
6962
+ async #prometheusMetricsRoute(_request) {
6963
+ const configured = await this.#activeConfiguredRegistry();
6964
+ if (!configured) {
6965
+ return new Response("registry not started\n", {
6966
+ status: 503,
6967
+ headers: { "content-type": "text/plain; charset=utf-8" }
6968
+ });
6969
+ }
6970
+ const { runtime, registry } = configured;
6971
+ if (!runtime.registryMetrics) {
6972
+ return new Response("metrics are not supported by this runtime\n", {
6973
+ status: 501,
6974
+ headers: { "content-type": "text/plain; charset=utf-8" }
6975
+ });
6976
+ }
6977
+ const response = await runtime.registryMetrics(registry);
6978
+ return new Response(new Uint8Array(response.body), {
6979
+ status: response.status,
6980
+ headers: response.headers
6981
+ });
6982
+ }
6983
+ async #activeConfiguredRegistry() {
5631
6984
  const candidates = [
5632
6985
  this.#runtimeServerlessPromise,
5633
6986
  this.#runtimeServeConfiguredPromise
5634
6987
  ].filter(
5635
6988
  (candidate) => candidate !== void 0
5636
6989
  );
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 };
6990
+ if (candidates.length === 0) return void 0;
6991
+ return await candidates[0];
5643
6992
  }
5644
6993
  /**
5645
6994
  * Starts an actor envoy for standalone server deployments.
5646
6995
  */
5647
6996
  #startEnvoy(config, printWelcome) {
5648
6997
  if (!this.#runtimeServePromise) {
5649
- const configuredRegistryPromise = buildConfiguredRegistry(config);
6998
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
5650
6999
  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");
7000
+ this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(
7001
+ async ({ runtime, registry, serveConfig }) => {
7002
+ await runtime.serveRegistry(registry, serveConfig);
7003
+ }
7004
+ );
7005
+ this.#runtimeServePromise = this.#runtimeServeLifecyclePromise.catch((error) => {
7006
+ logger2().warn({ error }, "runtime registry serve errored");
5655
7007
  });
5656
- this.#installSignalHandlers(config, configuredRegistryPromise);
7008
+ this.#installSignalHandlers(config);
5657
7009
  }
5658
7010
  if (printWelcome) {
5659
7011
  this.#printWelcome(config, "serverful");
5660
7012
  }
5661
7013
  }
5662
- #installSignalHandlers(config, configuredRegistryPromise) {
7014
+ #installSignalHandlers(config) {
5663
7015
  var _a;
5664
7016
  if (this.#shutdownInstalled) return;
5665
7017
  if ((_a = config.shutdown) == null ? void 0 : _a.disableSignalHandlers) return;
@@ -5668,58 +7020,86 @@ var Registry = class {
5668
7020
  }
5669
7021
  this.#shutdownInstalled = true;
5670
7022
  const install = (signal) => {
5671
- const handler = () => this.#onShutdownSignal(
5672
- signal,
5673
- config,
5674
- configuredRegistryPromise
5675
- );
7023
+ const handler = () => this.#onShutdownSignal(signal, config);
5676
7024
  this.#signalHandlers[signal] = handler;
5677
7025
  process.on(signal, handler);
5678
7026
  };
5679
7027
  install("SIGINT");
5680
7028
  install("SIGTERM");
5681
7029
  }
5682
- #onShutdownSignal(signal, config, configuredRegistryPromise) {
7030
+ #onShutdownSignal(signal, config) {
5683
7031
  if (this.#shutdownInFlight !== null) {
5684
7032
  this.#removeSignalHandlers();
5685
- process.kill(process.pid, signal);
7033
+ finishShutdownSignal(signal);
5686
7034
  return;
5687
7035
  }
5688
- this.#shutdownInFlight = this.#runShutdown(
5689
- signal,
5690
- config,
5691
- configuredRegistryPromise
5692
- ).catch((err) => {
7036
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
7037
+ logger2().warn({ err }, "shutdown error");
7038
+ }).then(() => {
7039
+ this.#removeSignalHandlers();
7040
+ finishShutdownSignal(signal);
7041
+ });
7042
+ }
7043
+ /**
7044
+ * Gracefully drains all live registries.
7045
+ *
7046
+ * Programmatic counterpart to the SIGINT/SIGTERM handlers: tears down
7047
+ * every live `CoreRegistry` (both `start()` and `handler()` modes) and
7048
+ * waits for the serve promise to resolve, all bounded by the shutdown
7049
+ * grace period. Unlike a signal-driven shutdown, this does not re-raise a
7050
+ * signal or exit the process. The caller owns process lifetime.
7051
+ *
7052
+ * Idempotent: concurrent or repeated calls share a single drain. Safe to
7053
+ * call even if nothing has been started.
7054
+ *
7055
+ * @example
7056
+ * ```ts
7057
+ * const registry = setup({ use: { counter } });
7058
+ * registry.start();
7059
+ * // ...later, on your own shutdown trigger:
7060
+ * await registry.shutdown();
7061
+ * ```
7062
+ */
7063
+ async shutdown() {
7064
+ if (this.#shutdownInFlight !== null) return this.#shutdownInFlight;
7065
+ const config = this.parseConfig();
7066
+ this.#removeSignalHandlers();
7067
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
5693
7068
  logger2().warn({ err }, "shutdown error");
5694
7069
  });
7070
+ return this.#shutdownInFlight;
5695
7071
  }
5696
- async #runShutdown(signal, config, configuredRegistryPromise) {
7072
+ async #drain(config) {
5697
7073
  var _a;
5698
- const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? 3e4;
7074
+ const modeAPromise = this.#runtimeServeConfiguredPromise;
7075
+ const modeBPromise = this.#runtimeServerlessPromise;
7076
+ const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? await this.#actorStopThresholdMs(modeAPromise ?? modeBPromise) ?? 30 * 60 * 1e3;
5699
7077
  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) {
7078
+ const registries = [];
7079
+ if (modeAPromise !== void 0) {
5715
7080
  registries.push(
5716
7081
  (async () => {
5717
7082
  try {
5718
- const { runtime, registry } = await runtimeServerlessPromise;
7083
+ const { runtime, registry } = await modeAPromise;
5719
7084
  await runtime.shutdownRegistry(registry);
5720
7085
  } catch (err) {
5721
7086
  logger2().warn(
5722
7087
  { err },
7088
+ "runtime registry shutdown errored (mode A)"
7089
+ );
7090
+ }
7091
+ })()
7092
+ );
7093
+ }
7094
+ if (modeBPromise !== void 0) {
7095
+ registries.push(
7096
+ (async () => {
7097
+ try {
7098
+ const { runtime, registry } = await modeBPromise;
7099
+ await runtime.shutdownRegistry(registry);
7100
+ } catch (err) {
7101
+ logger2().warn(
7102
+ { error: err },
5723
7103
  "runtime registry shutdown errored (mode B)"
5724
7104
  );
5725
7105
  }
@@ -5731,6 +7111,9 @@ var Registry = class {
5731
7111
  if (runtimeServePromise !== void 0) {
5732
7112
  await runtimeServePromise.catch(() => void 0);
5733
7113
  }
7114
+ if (this.#applicationListenerPromise !== void 0) {
7115
+ await this.#applicationListenerPromise.catch(() => void 0);
7116
+ }
5734
7117
  };
5735
7118
  await Promise.race([
5736
7119
  drain(),
@@ -5741,8 +7124,23 @@ var Registry = class {
5741
7124
  }
5742
7125
  )
5743
7126
  ]);
5744
- this.#removeSignalHandlers();
5745
- process.kill(process.pid, signal);
7127
+ }
7128
+ async #actorStopThresholdMs(configuredRegistryPromise) {
7129
+ var _a;
7130
+ if (configuredRegistryPromise === void 0) return void 0;
7131
+ try {
7132
+ const { runtime, registry } = await configuredRegistryPromise;
7133
+ const thresholdMs = await ((_a = runtime.registryActorStopThresholdMs) == null ? void 0 : _a.call(runtime, registry));
7134
+ if (thresholdMs !== void 0 && Number.isFinite(thresholdMs) && thresholdMs > 0) {
7135
+ return thresholdMs;
7136
+ }
7137
+ } catch (err) {
7138
+ logger2().warn(
7139
+ { err },
7140
+ "failed to read actor stop threshold for shutdown grace"
7141
+ );
7142
+ }
7143
+ return void 0;
5746
7144
  }
5747
7145
  #removeSignalHandlers() {
5748
7146
  for (const [signal, handler] of Object.entries(
@@ -5755,9 +7153,86 @@ var Registry = class {
5755
7153
  startEnvoy() {
5756
7154
  this.#startEnvoy(this.parseConfig(), true);
5757
7155
  }
7156
+ /**
7157
+ * Starts the serverful registry if needed and waits until its envoy has
7158
+ * registered with the Engine. Repeated and concurrent calls share one
7159
+ * startup lifecycle and readiness promise.
7160
+ *
7161
+ * Unlike {@link start}, this reports startup failures and does not resolve
7162
+ * merely because an HTTP health endpoint is listening.
7163
+ */
7164
+ startAndWait() {
7165
+ if (this.#shutdownInFlight !== null) {
7166
+ return Promise.reject(
7167
+ new Error(
7168
+ "registry.startAndWait() cannot run after shutdown has begun"
7169
+ )
7170
+ );
7171
+ }
7172
+ if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
7173
+ if (getRivetkitRuntimeMode() === "serverless") {
7174
+ return Promise.reject(
7175
+ new Error(
7176
+ "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request"
7177
+ )
7178
+ );
7179
+ }
7180
+ const config = this.parseConfig();
7181
+ if (config.runtime === "wasm") {
7182
+ return Promise.reject(
7183
+ new Error(
7184
+ "registry.startAndWait() requires the native runtime; WebAssembly registries do not host an envoy"
7185
+ )
7186
+ );
7187
+ }
7188
+ this.#startEnvoy(config, true);
7189
+ const configuredRegistryPromise = this.#runtimeServeConfiguredPromise;
7190
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
7191
+ if (!configuredRegistryPromise || !serveLifecyclePromise) {
7192
+ throw new Error("registry envoy startup did not initialize");
7193
+ }
7194
+ let timeout;
7195
+ const timeoutPromise = new Promise((_resolve, reject) => {
7196
+ var _a;
7197
+ timeout = setTimeout(
7198
+ () => reject(
7199
+ new Error(
7200
+ `RivetKit registry did not register with the Engine within ${REGISTRY_READY_TIMEOUT_MS}ms`
7201
+ )
7202
+ ),
7203
+ REGISTRY_READY_TIMEOUT_MS
7204
+ );
7205
+ (_a = timeout.unref) == null ? void 0 : _a.call(timeout);
7206
+ });
7207
+ const readinessPromise = (async () => {
7208
+ const { runtime, registry } = await configuredRegistryPromise;
7209
+ const stoppedBeforeReady = serveLifecyclePromise.then(() => {
7210
+ throw new Error(
7211
+ "RivetKit registry stopped before becoming ready"
7212
+ );
7213
+ });
7214
+ await Promise.race([
7215
+ runtime.waitRegistryReady(registry),
7216
+ stoppedBeforeReady
7217
+ ]);
7218
+ })();
7219
+ this.#runtimeReadyPromise = Promise.race([
7220
+ readinessPromise,
7221
+ timeoutPromise
7222
+ ]).finally(() => {
7223
+ if (timeout !== void 0) clearTimeout(timeout);
7224
+ });
7225
+ this.#runtimeReadyPromise.catch(() => {
7226
+ });
7227
+ return this.#runtimeReadyPromise;
7228
+ }
5758
7229
  /**
5759
7230
  * Starts the actor envoy for standalone server deployments.
5760
7231
  *
7232
+ * Set `RIVETKIT_RUNTIME_MODE=serverless` to instead bind an HTTP listener
7233
+ * via `listen()` (Mode B). Mode A (envoy) and Mode B (listener) are
7234
+ * mutually exclusive per registry instance.
7235
+ *
5761
7236
  * @example
5762
7237
  * ```ts
5763
7238
  * const registry = setup({ use: { counter } });
@@ -5765,10 +7240,20 @@ var Registry = class {
5765
7240
  * ```
5766
7241
  */
5767
7242
  start() {
7243
+ if (getRivetkitRuntimeMode() === "serverless") {
7244
+ const publicDir = getRivetkitPublicDir() ?? "/public";
7245
+ this.listen({ publicDir }).catch((error) => {
7246
+ logger2().error({ error }, "auto-listen failed; exiting");
7247
+ if (typeof process !== "undefined" && typeof process.exit === "function") {
7248
+ process.exit(1);
7249
+ }
7250
+ });
7251
+ return;
7252
+ }
5768
7253
  const config = this.parseConfig();
5769
7254
  this.#startEnvoy(config, true);
5770
7255
  }
5771
- #printWelcome(config, kind) {
7256
+ #printWelcome(config, kind, listener) {
5772
7257
  if (config.noWelcome || this.#welcomePrinted) return;
5773
7258
  this.#welcomePrinted = true;
5774
7259
  const logLine = (label, value) => {
@@ -5783,13 +7268,20 @@ var Registry = class {
5783
7268
  logLine("Namespace", config.namespace);
5784
7269
  }
5785
7270
  if (config.endpoint) {
5786
- const endpointType = config.endpoint === ENGINE_ENDPOINT ? "local native" : "remote";
7271
+ const endpointType = config.startEngine || isLocalEngineEndpoint(config.endpoint) ? "local native" : "remote";
5787
7272
  logLine("Endpoint", `${config.endpoint} (${endpointType})`);
5788
7273
  }
5789
7274
  if (kind === "serverless" && config.publicEndpoint) {
5790
7275
  logLine("Client", config.publicEndpoint);
5791
7276
  }
5792
7277
  logLine("Actors", Object.keys(config.use).length.toString());
7278
+ if (listener) {
7279
+ const host = listener.host ?? "0.0.0.0";
7280
+ logLine("Listening", `http://${host}:${listener.port}`);
7281
+ if (listener.publicDir) {
7282
+ logLine("Public Dir", listener.publicDir);
7283
+ }
7284
+ }
5793
7285
  console.log();
5794
7286
  }
5795
7287
  };
@@ -5805,6 +7297,12 @@ function isServerlessMetadataRequest(request, basePath) {
5805
7297
  const normalizedBase = basePath === "/" ? "" : `/${basePath.replace(/^\/+|\/+$/g, "")}`;
5806
7298
  return parsed.pathname === `${normalizedBase}/metadata`;
5807
7299
  }
7300
+ function jsonRouteResponse(status, body) {
7301
+ return new Response(JSON.stringify(body), {
7302
+ status,
7303
+ headers: { "content-type": "application/json" }
7304
+ });
7305
+ }
5808
7306
  function setup(input) {
5809
7307
  return new Registry(input);
5810
7308
  }