rivetkit 2.3.11-rc.8 → 2.3.11

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 (153) hide show
  1. package/dist/browser/client.d.ts +96 -14
  2. package/dist/browser/client.js +12 -2
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.d.ts +139 -139
  5. package/dist/browser/inspector/client.js +12 -2
  6. package/dist/browser/inspector/client.js.map +1 -1
  7. package/dist/tsup/agent-os/index.cjs +146 -76
  8. package/dist/tsup/agent-os/index.cjs.map +1 -1
  9. package/dist/tsup/agent-os/index.d.cts +83 -9
  10. package/dist/tsup/agent-os/index.d.ts +83 -9
  11. package/dist/tsup/agent-os/index.js +146 -76
  12. package/dist/tsup/agent-os/index.js.map +1 -1
  13. package/dist/tsup/{chunk-JBQ63WSM.js → chunk-3ZR542SK.js} +4 -4
  14. package/dist/tsup/chunk-3ZR542SK.js.map +1 -0
  15. package/dist/tsup/{chunk-HNHLBM3Y.cjs → chunk-4KGXFC6M.cjs} +42 -5
  16. package/dist/tsup/chunk-4KGXFC6M.cjs.map +1 -0
  17. package/dist/tsup/chunk-5UYWLCRO.js +14 -0
  18. package/dist/tsup/chunk-5UYWLCRO.js.map +1 -0
  19. package/dist/tsup/{chunk-QWLJCP3X.js → chunk-6W5VGLFT.js} +42 -5
  20. package/dist/tsup/chunk-6W5VGLFT.js.map +1 -0
  21. package/dist/tsup/chunk-6WYATRS4.js +243 -0
  22. package/dist/tsup/chunk-6WYATRS4.js.map +1 -0
  23. package/dist/tsup/chunk-B3W74FBB.cjs +14 -0
  24. package/dist/tsup/chunk-B3W74FBB.cjs.map +1 -0
  25. package/dist/tsup/{chunk-V6ANE6JM.js → chunk-FWROC5LA.js} +2 -2
  26. package/dist/tsup/{chunk-ZVM35ICH.cjs → chunk-GLIPKKEC.cjs} +7 -7
  27. package/dist/tsup/{chunk-ZVM35ICH.cjs.map → chunk-GLIPKKEC.cjs.map} +1 -1
  28. package/dist/tsup/{chunk-CCUO5OKD.cjs → chunk-GN2EUMEW.cjs} +3 -3
  29. package/dist/tsup/{chunk-CCUO5OKD.cjs.map → chunk-GN2EUMEW.cjs.map} +1 -1
  30. package/dist/tsup/{chunk-2ROUKH7W.cjs → chunk-GU7ML3KE.cjs} +13 -3
  31. package/dist/tsup/chunk-GU7ML3KE.cjs.map +1 -0
  32. package/dist/tsup/{chunk-WRRB24UY.js → chunk-JQ2AZ5FN.js} +3 -3
  33. package/dist/tsup/{chunk-7AFZMFPQ.js → chunk-JTHHCZCZ.js} +10 -1
  34. package/dist/tsup/chunk-JTHHCZCZ.js.map +1 -0
  35. package/dist/tsup/{chunk-UEULFXUI.cjs → chunk-KVFIONKQ.cjs} +11 -2
  36. package/dist/tsup/chunk-KVFIONKQ.cjs.map +1 -0
  37. package/dist/tsup/chunk-LWQFXGKS.cjs +243 -0
  38. package/dist/tsup/chunk-LWQFXGKS.cjs.map +1 -0
  39. package/dist/tsup/{chunk-KVD6ZWNM.js → chunk-MO2SSUOR.js} +8 -7
  40. package/dist/tsup/chunk-MO2SSUOR.js.map +1 -0
  41. package/dist/tsup/{chunk-AGNBLCNJ.js → chunk-OUENKQHB.js} +13 -3
  42. package/dist/tsup/chunk-OUENKQHB.js.map +1 -0
  43. package/dist/tsup/{chunk-E6WB2BLO.cjs → chunk-PUZY2XCD.cjs} +10 -9
  44. package/dist/tsup/chunk-PUZY2XCD.cjs.map +1 -0
  45. package/dist/tsup/{chunk-4EDGOGCB.js → chunk-QFJ24MBU.js} +27 -2
  46. package/dist/tsup/{chunk-4EDGOGCB.js.map → chunk-QFJ24MBU.js.map} +1 -1
  47. package/dist/tsup/{chunk-A55CGZIV.cjs → chunk-RXXDNJXB.cjs} +140 -140
  48. package/dist/tsup/{chunk-A55CGZIV.cjs.map → chunk-RXXDNJXB.cjs.map} +1 -1
  49. package/dist/tsup/{chunk-N6MBTYGX.cjs → chunk-VBJQIBXI.cjs} +30 -5
  50. package/dist/tsup/chunk-VBJQIBXI.cjs.map +1 -0
  51. package/dist/tsup/client/mod.cjs +6 -6
  52. package/dist/tsup/client/mod.d.cts +4 -3
  53. package/dist/tsup/client/mod.d.ts +4 -3
  54. package/dist/tsup/client/mod.js +5 -5
  55. package/dist/tsup/common/log.cjs +2 -2
  56. package/dist/tsup/common/log.js +1 -1
  57. package/dist/tsup/common/websocket.cjs +3 -3
  58. package/dist/tsup/common/websocket.js +2 -2
  59. package/dist/tsup/{config-CZcjyT5B.d.ts → config-C4OSv0QP.d.ts} +92 -7
  60. package/dist/tsup/{config-rGWrumlO.d.cts → config-DTGoWdkG.d.cts} +92 -7
  61. package/dist/tsup/{config-BxOimoGX.d.cts → config-ey2I2zz5.d.cts} +46 -6
  62. package/dist/tsup/{config-BxOimoGX.d.ts → config-ey2I2zz5.d.ts} +46 -6
  63. package/dist/tsup/{context-B8W8E8nW.d.cts → context-C6cvDNyk.d.cts} +2 -2
  64. package/dist/tsup/{context-_UrDZhEh.d.ts → context-CMygeBxS.d.ts} +2 -2
  65. package/dist/tsup/db/drizzle.cjs +18 -10
  66. package/dist/tsup/db/drizzle.cjs.map +1 -1
  67. package/dist/tsup/db/drizzle.d.cts +5 -6
  68. package/dist/tsup/db/drizzle.d.ts +5 -6
  69. package/dist/tsup/db/drizzle.js +13 -5
  70. package/dist/tsup/db/drizzle.js.map +1 -1
  71. package/dist/tsup/db/mod.cjs +5 -175
  72. package/dist/tsup/db/mod.cjs.map +1 -1
  73. package/dist/tsup/db/mod.d.cts +11 -4
  74. package/dist/tsup/db/mod.d.ts +11 -4
  75. package/dist/tsup/db/mod.js +4 -174
  76. package/dist/tsup/db/mod.js.map +1 -1
  77. package/dist/tsup/dynamic/mod.cjs +2 -2
  78. package/dist/tsup/dynamic/mod.d.cts +3 -2
  79. package/dist/tsup/dynamic/mod.d.ts +3 -2
  80. package/dist/tsup/dynamic/mod.js +1 -1
  81. package/dist/tsup/inspector/mod.cjs +5 -4
  82. package/dist/tsup/inspector/mod.cjs.map +1 -1
  83. package/dist/tsup/inspector/mod.d.cts +12 -146
  84. package/dist/tsup/inspector/mod.d.ts +12 -146
  85. package/dist/tsup/inspector/mod.js +4 -3
  86. package/dist/tsup/inspector/mod.js.map +1 -1
  87. package/dist/tsup/inspector/workflow.cjs +21 -0
  88. package/dist/tsup/inspector/workflow.cjs.map +1 -0
  89. package/dist/tsup/inspector/workflow.d.cts +144 -0
  90. package/dist/tsup/inspector/workflow.d.ts +144 -0
  91. package/dist/tsup/inspector/workflow.js +21 -0
  92. package/dist/tsup/inspector/workflow.js.map +1 -0
  93. package/dist/tsup/inspector-tab/mod.cjs +2 -2
  94. package/dist/tsup/inspector-tab/mod.d.cts +4 -3
  95. package/dist/tsup/inspector-tab/mod.d.ts +4 -3
  96. package/dist/tsup/inspector-tab/mod.js +1 -1
  97. package/dist/tsup/mod.cjs +837 -243
  98. package/dist/tsup/mod.cjs.map +1 -1
  99. package/dist/tsup/mod.d.cts +6 -5
  100. package/dist/tsup/mod.d.ts +6 -5
  101. package/dist/tsup/mod.js +766 -172
  102. package/dist/tsup/mod.js.map +1 -1
  103. package/dist/tsup/test/mod.cjs +7 -7
  104. package/dist/tsup/test/mod.d.cts +3 -2
  105. package/dist/tsup/test/mod.d.ts +3 -2
  106. package/dist/tsup/test/mod.js +5 -5
  107. package/dist/tsup/unstable/migrations.d.cts +1 -1
  108. package/dist/tsup/unstable/migrations.d.ts +1 -1
  109. package/dist/tsup/utils.cjs +2 -2
  110. package/dist/tsup/utils.js +1 -1
  111. package/dist/tsup/workflow/mod.cjs +89 -95
  112. package/dist/tsup/workflow/mod.cjs.map +1 -1
  113. package/dist/tsup/workflow/mod.d.cts +5 -4
  114. package/dist/tsup/workflow/mod.d.ts +5 -4
  115. package/dist/tsup/workflow/mod.js +86 -92
  116. package/dist/tsup/workflow/mod.js.map +1 -1
  117. package/package.json +19 -9
  118. package/src/actor/config.test.ts +65 -1
  119. package/src/actor/config.ts +169 -5
  120. package/src/actor/mod.ts +10 -1
  121. package/src/client/actor-common.ts +5 -14
  122. package/src/common/database/config.ts +50 -3
  123. package/src/common/database/mod.test.ts +142 -4
  124. package/src/common/database/mod.ts +210 -98
  125. package/src/common/database/native-database.ts +42 -3
  126. package/src/common/database/shared.ts +9 -0
  127. package/src/db/drizzle.test.ts +8 -1
  128. package/src/db/drizzle.ts +15 -4
  129. package/src/db/mod.ts +3 -0
  130. package/src/inspector/workflow.ts +61 -0
  131. package/src/registry/napi-runtime.ts +69 -1
  132. package/src/registry/native.ts +505 -155
  133. package/src/registry/run-handler-coordinator.test.ts +252 -0
  134. package/src/registry/run-handler-coordinator.ts +219 -0
  135. package/src/registry/runtime.ts +34 -1
  136. package/src/registry/wasm-runtime.ts +122 -17
  137. package/src/registry/write-through-proxy.ts +101 -0
  138. package/src/utils/node.ts +44 -28
  139. package/src/workflow/driver.ts +56 -58
  140. package/src/workflow/inspector.ts +10 -15
  141. package/src/workflow/mod.ts +48 -70
  142. package/dist/tsup/chunk-2ROUKH7W.cjs.map +0 -1
  143. package/dist/tsup/chunk-7AFZMFPQ.js.map +0 -1
  144. package/dist/tsup/chunk-AGNBLCNJ.js.map +0 -1
  145. package/dist/tsup/chunk-E6WB2BLO.cjs.map +0 -1
  146. package/dist/tsup/chunk-HNHLBM3Y.cjs.map +0 -1
  147. package/dist/tsup/chunk-JBQ63WSM.js.map +0 -1
  148. package/dist/tsup/chunk-KVD6ZWNM.js.map +0 -1
  149. package/dist/tsup/chunk-N6MBTYGX.cjs.map +0 -1
  150. package/dist/tsup/chunk-QWLJCP3X.js.map +0 -1
  151. package/dist/tsup/chunk-UEULFXUI.cjs.map +0 -1
  152. /package/dist/tsup/{chunk-V6ANE6JM.js.map → chunk-FWROC5LA.js.map} +0 -0
  153. /package/dist/tsup/{chunk-WRRB24UY.js.map → chunk-JQ2AZ5FN.js.map} +0 -0
package/dist/tsup/mod.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } var _class; var _class2; var _class3;
2
2
 
3
- var _chunkN6MBTYGXcjs = require('./chunk-N6MBTYGX.cjs');
3
+ var _chunkVBJQIBXIcjs = require('./chunk-VBJQIBXI.cjs');
4
4
 
5
5
 
6
6
 
@@ -12,28 +12,34 @@ var _chunkN6MBTYGXcjs = require('./chunk-N6MBTYGX.cjs');
12
12
 
13
13
 
14
14
 
15
- var _chunkHNHLBM3Ycjs = require('./chunk-HNHLBM3Y.cjs');
16
15
 
17
16
 
18
17
 
19
18
 
19
+ var _chunk4KGXFC6Mcjs = require('./chunk-4KGXFC6M.cjs');
20
20
 
21
21
 
22
22
 
23
23
 
24
24
 
25
25
 
26
- var _chunkA55CGZIVcjs = require('./chunk-A55CGZIV.cjs');
26
+
27
+
28
+
29
+
30
+ var _chunkRXXDNJXBcjs = require('./chunk-RXXDNJXB.cjs');
27
31
 
28
32
 
29
33
 
30
34
  var _chunkMYWZCDMLcjs = require('./chunk-MYWZCDML.cjs');
31
- require('./chunk-UEULFXUI.cjs');
32
- require('./chunk-CCUO5OKD.cjs');
33
35
 
34
36
 
35
37
 
36
38
 
39
+ var _chunkLWQFXGKScjs = require('./chunk-LWQFXGKS.cjs');
40
+ require('./chunk-KVFIONKQ.cjs');
41
+ require('./chunk-GN2EUMEW.cjs');
42
+
37
43
 
38
44
 
39
45
 
@@ -62,7 +68,10 @@ require('./chunk-CCUO5OKD.cjs');
62
68
 
63
69
 
64
70
 
65
- var _chunk2ROUKH7Wcjs = require('./chunk-2ROUKH7W.cjs');
71
+
72
+
73
+
74
+ var _chunkGU7ML3KEcjs = require('./chunk-GU7ML3KE.cjs');
66
75
 
67
76
 
68
77
 
@@ -78,7 +87,7 @@ var _chunk4FC7TVS6cjs = require('./chunk-4FC7TVS6.cjs');
78
87
 
79
88
  // src/actor/log.ts
80
89
  function loggerWithoutContext() {
81
- return _chunk2ROUKH7Wcjs.getLogger.call(void 0, "actor-runtime");
90
+ return _chunkGU7ML3KEcjs.getLogger.call(void 0, "actor-runtime");
82
91
  }
83
92
 
84
93
  // src/actor/definition.ts
@@ -117,9 +126,9 @@ function actor(input) {
117
126
  warnDeprecatedOptionKeys(
118
127
  input == null ? void 0 : input.options
119
128
  );
120
- const config = _chunkHNHLBM3Ycjs.ActorConfigSchema.parse(input);
121
- _chunkHNHLBM3Ycjs.flattenActionHandlers.call(void 0, config.actions);
122
- _chunkHNHLBM3Ycjs.flattenActionInputSchemas.call(void 0, config.actions, config.actionInputSchemas);
129
+ const config = _chunk4KGXFC6Mcjs.ActorConfigSchema.parse(input);
130
+ _chunk4KGXFC6Mcjs.flattenActionHandlers.call(void 0, config.actions);
131
+ _chunk4KGXFC6Mcjs.flattenActionInputSchemas.call(void 0, config.actions, config.actionInputSchemas);
123
132
  return new ActorDefinition(config);
124
133
  }
125
134
  function isStaticActorDefinition(definition) {
@@ -218,7 +227,7 @@ function validateSchemaSync(schemas, key, data) {
218
227
  var _virtualwebsocket = require('@rivetkit/virtual-websocket');
219
228
  var _ws = require('hono/ws');
220
229
  function logger() {
221
- return _chunk2ROUKH7Wcjs.getLogger.call(void 0, "inline-websocket-adapter");
230
+ return _chunkGU7ML3KEcjs.getLogger.call(void 0, "inline-websocket-adapter");
222
231
  }
223
232
  var InlineWebSocketAdapter = class {
224
233
  #handler;
@@ -389,7 +398,7 @@ function isLocalEngineEndpoint(endpoint) {
389
398
 
390
399
  // src/registry/log.ts
391
400
  function logger2() {
392
- return _chunk2ROUKH7Wcjs.getLogger.call(void 0, "registry");
401
+ return _chunkGU7ML3KEcjs.getLogger.call(void 0, "registry");
393
402
  }
394
403
 
395
404
  // src/serverless/configure.ts
@@ -435,8 +444,8 @@ async function configureServerlessPool(config) {
435
444
  );
436
445
  }
437
446
  const customConfig = config.configurePool;
438
- const clientConfig = _chunkA55CGZIVcjs.convertRegistryConfigToClientConfig.call(void 0, config);
439
- const dcsRes = await _chunkA55CGZIVcjs.getDatacenters.call(void 0, clientConfig);
447
+ const clientConfig = _chunkRXXDNJXBcjs.convertRegistryConfigToClientConfig.call(void 0, config);
448
+ const dcsRes = await _chunkRXXDNJXBcjs.getDatacenters.call(void 0, clientConfig);
440
449
  const poolName = _nullishCoalesce(customConfig.name, () => ( "default"));
441
450
  const serverlessToken = _nullishCoalesce(config.token, () => ( config.publicToken));
442
451
  const headers = {
@@ -458,7 +467,7 @@ async function configureServerlessPool(config) {
458
467
  metadata: _nullishCoalesce(customConfig.metadata, () => ( {})),
459
468
  drain_on_version_upgrade: _nullishCoalesce(customConfig.drainOnVersionUpgrade, () => ( true))
460
469
  };
461
- await _chunkA55CGZIVcjs.updateRunnerConfig.call(void 0, clientConfig, poolName, {
470
+ await _chunkRXXDNJXBcjs.updateRunnerConfig.call(void 0, clientConfig, poolName, {
462
471
  datacenters: Object.fromEntries(
463
472
  dcsRes.datacenters.map((dc) => [dc.name, serverlessConfig])
464
473
  )
@@ -475,7 +484,7 @@ async function configureServerlessPool(config) {
475
484
  logger2().warn({
476
485
  msg: "serverless pool configuration attempt failed",
477
486
  attempts,
478
- error: _chunk2ROUKH7Wcjs.stringifyError.call(void 0, error)
487
+ error: _chunkGU7ML3KEcjs.stringifyError.call(void 0, error)
479
488
  });
480
489
  await sleep(CONFIGURE_RETRY_DELAY_MS);
481
490
  }
@@ -483,7 +492,7 @@ async function configureServerlessPool(config) {
483
492
  logger2().error({
484
493
  msg: "failed to configure serverless pool, validate endpoint is configured correctly then restart this process",
485
494
  attempts,
486
- error: _chunk2ROUKH7Wcjs.stringifyError.call(void 0, lastError)
495
+ error: _chunkGU7ML3KEcjs.stringifyError.call(void 0, lastError)
487
496
  });
488
497
  throw lastError;
489
498
  }
@@ -495,20 +504,20 @@ var _zod = require('zod');
495
504
  var _v4 = require('zod/v4');
496
505
  var warnedMissingVersion = false;
497
506
  var EnvoyConfigSchema = _v4.z.object({
498
- poolName: _v4.z.string().default(() => _nullishCoalesce(_chunk2ROUKH7Wcjs.getRivetPool.call(void 0, ), () => ( "default"))),
507
+ poolName: _v4.z.string().default(() => _nullishCoalesce(_chunkGU7ML3KEcjs.getRivetPool.call(void 0, ), () => ( "default"))),
499
508
  version: _v4.z.number().default(() => {
500
- const version = _chunk2ROUKH7Wcjs.getRivetEnvoyVersion.call(void 0, );
509
+ const version = _chunkGU7ML3KEcjs.getRivetEnvoyVersion.call(void 0, );
501
510
  if (version !== void 0) return version;
502
- if (_chunk2ROUKH7Wcjs.getNodeEnv.call(void 0, ) === "production" && !warnedMissingVersion) {
511
+ if (_chunkGU7ML3KEcjs.getNodeEnv.call(void 0, ) === "production" && !warnedMissingVersion) {
503
512
  warnedMissingVersion = true;
504
- _chunk2ROUKH7Wcjs.getLogger.call(void 0, "rivetkit").error(
513
+ _chunkGU7ML3KEcjs.getLogger.call(void 0, "rivetkit").error(
505
514
  "RIVET_ENVOY_VERSION is not set. Actors will not be versioned, which means they won't be drained on deploy. This is only needed when self-hosting or using a custom envoy (not needed for Rivet Compute). Set this as a build arg in your Dockerfile. See https://rivet.dev/docs/actors/versions"
506
515
  );
507
516
  }
508
517
  return 1;
509
518
  }),
510
519
  // Deprecated.
511
- totalSlots: _v4.z.number().default(() => _nullishCoalesce(_chunk2ROUKH7Wcjs.getRivetTotalSlots.call(void 0, ), () => ( 1e5))),
520
+ totalSlots: _v4.z.number().default(() => _nullishCoalesce(_chunkGU7ML3KEcjs.getRivetTotalSlots.call(void 0, ), () => ( 1e5))),
512
521
  envoyKey: _v4.z.string().optional()
513
522
  });
514
523
 
@@ -546,7 +555,7 @@ var ServerlessConfigSchema = _v4.z.object({
546
555
  *
547
556
  * Can also be set via RIVET_PUBLIC_ENDPOINT environment variable.
548
557
  */
549
- publicEndpoint: _v4.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunk2ROUKH7Wcjs.getRivetPublicEndpoint.call(void 0, )))),
558
+ publicEndpoint: _v4.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkGU7ML3KEcjs.getRivetPublicEndpoint.call(void 0, )))),
550
559
  /**
551
560
  * Token that clients should use when connecting via the public endpoint.
552
561
  *
@@ -554,7 +563,7 @@ var ServerlessConfigSchema = _v4.z.object({
554
563
  *
555
564
  * Can also be specified in the publicEndpoint URL as `https://namespace:token@host`.
556
565
  */
557
- publicToken: _v4.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunk2ROUKH7Wcjs.getRivetPublicToken.call(void 0, ))))
566
+ publicToken: _v4.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkGU7ML3KEcjs.getRivetPublicToken.call(void 0, ))))
558
567
  // There is no publicNamespace config option because the frontend and backend
559
568
  // cannot use different namespaces. The namespace is extracted from the
560
569
  // publicEndpoint URL auth syntax if provided.
@@ -608,7 +617,7 @@ var RegistryConfigSchema = _zod.z.object({
608
617
  * Runtime binding to use for RivetKit core.
609
618
  * */
610
619
  runtime: RuntimeKindSchema.optional().transform((val, ctx) => {
611
- const rawRuntime = _nullishCoalesce(val, () => ( _chunk2ROUKH7Wcjs.getRivetkitRuntime.call(void 0, )));
620
+ const rawRuntime = _nullishCoalesce(val, () => ( _chunkGU7ML3KEcjs.getRivetkitRuntime.call(void 0, )));
612
621
  if (rawRuntime === void 0) {
613
622
  return "auto";
614
623
  }
@@ -645,7 +654,7 @@ var RegistryConfigSchema = _zod.z.object({
645
654
  * */
646
655
  logging: _zod.z.object({
647
656
  baseLogger: _zod.z.custom().optional(),
648
- level: _chunk2ROUKH7Wcjs.LogLevelSchema.optional()
657
+ level: _chunkGU7ML3KEcjs.LogLevelSchema.optional()
649
658
  }).optional().default(() => ({})),
650
659
  // MARK: Routing
651
660
  // // This is a function to allow for lazy configuration of upgradeWebSocket on the
@@ -663,9 +672,9 @@ var RegistryConfigSchema = _zod.z.object({
663
672
  *
664
673
  * Can also be set via RIVET_ENDPOINT environment variables.
665
674
  */
666
- endpoint: _zod.z.string().optional().transform((val) => _nullishCoalesce(_nullishCoalesce(val, () => ( _chunk2ROUKH7Wcjs.getRivetEngine.call(void 0, ))), () => ( _chunk2ROUKH7Wcjs.getRivetEndpoint.call(void 0, )))),
667
- token: _zod.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunk2ROUKH7Wcjs.getRivetToken.call(void 0, )))),
668
- namespace: _zod.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunk2ROUKH7Wcjs.getRivetNamespace.call(void 0, )))),
675
+ endpoint: _zod.z.string().optional().transform((val) => _nullishCoalesce(_nullishCoalesce(val, () => ( _chunkGU7ML3KEcjs.getRivetEngine.call(void 0, ))), () => ( _chunkGU7ML3KEcjs.getRivetEndpoint.call(void 0, )))),
676
+ token: _zod.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkGU7ML3KEcjs.getRivetToken.call(void 0, )))),
677
+ namespace: _zod.z.string().optional().transform((val) => _nullishCoalesce(val, () => ( _chunkGU7ML3KEcjs.getRivetNamespace.call(void 0, )))),
669
678
  headers: _zod.z.record(_zod.z.string(), _zod.z.string()).optional().default({}),
670
679
  // MARK: Client
671
680
  // TODO:
@@ -705,21 +714,21 @@ var RegistryConfigSchema = _zod.z.object({
705
714
  *
706
715
  * Starts the full Rust engine process locally.
707
716
  */
708
- startEngine: _zod.z.boolean().default(() => _chunk2ROUKH7Wcjs.getRivetRunEngine.call(void 0, )),
717
+ startEngine: _zod.z.boolean().default(() => _chunkGU7ML3KEcjs.getRivetRunEngine.call(void 0, )),
709
718
  /**
710
719
  * @experimental
711
720
  *
712
721
  * Host to bind the spawned local engine process to.
713
722
  */
714
- engineHost: _zod.z.string().optional().default(() => _nullishCoalesce(_chunk2ROUKH7Wcjs.getRivetRunEngineHost.call(void 0, ), () => ( ENGINE_HOST))),
723
+ engineHost: _zod.z.string().optional().default(() => _nullishCoalesce(_chunkGU7ML3KEcjs.getRivetRunEngineHost.call(void 0, ), () => ( ENGINE_HOST))),
715
724
  /**
716
725
  * @experimental
717
726
  *
718
727
  * Port to bind the spawned local engine process to.
719
728
  */
720
- enginePort: _zod.z.number().int().min(1).max(65535).optional().default(() => _nullishCoalesce(_chunk2ROUKH7Wcjs.getRivetRunEnginePort.call(void 0, ), () => ( ENGINE_PORT))),
729
+ enginePort: _zod.z.number().int().min(1).max(65535).optional().default(() => _nullishCoalesce(_chunkGU7ML3KEcjs.getRivetRunEnginePort.call(void 0, ), () => ( ENGINE_PORT))),
721
730
  /** @experimental */
722
- engineVersion: _zod.z.string().optional().default(() => _nullishCoalesce(_chunk2ROUKH7Wcjs.getRivetRunEngineVersion.call(void 0, ), () => ( _chunk2ROUKH7Wcjs.VERSION))),
731
+ engineVersion: _zod.z.string().optional().default(() => _nullishCoalesce(_chunkGU7ML3KEcjs.getRivetRunEngineVersion.call(void 0, ), () => ( _chunkGU7ML3KEcjs.VERSION))),
723
732
  /**
724
733
  * @experimental
725
734
  *
@@ -767,7 +776,7 @@ var RegistryConfigSchema = _zod.z.object({
767
776
  }))
768
777
  }).transform((config, ctx) => {
769
778
  var _a, _b, _c;
770
- const isDevEnv = _chunk2ROUKH7Wcjs.isDev.call(void 0, );
779
+ const isDevEnv = _chunkGU7ML3KEcjs.isDev.call(void 0, );
771
780
  const sqliteBackend = _nullishCoalesce(((_a = config.sqlite) == null ? void 0 : _a.backend), () => ( ((_b = config.test) == null ? void 0 : _b.sqliteBackend)));
772
781
  if (config.runtime === "wasm" && sqliteBackend === "local") {
773
782
  ctx.addIssue({
@@ -777,7 +786,7 @@ var RegistryConfigSchema = _zod.z.object({
777
786
  });
778
787
  }
779
788
  const sqlite = config.runtime === "wasm" && config.sqlite === void 0 ? { backend: "remote" } : config.sqlite;
780
- const parsedEndpoint = config.endpoint ? _chunkA55CGZIVcjs.tryParseEndpoint.call(void 0, ctx, {
789
+ const parsedEndpoint = config.endpoint ? _chunkRXXDNJXBcjs.tryParseEndpoint.call(void 0, ctx, {
781
790
  endpoint: config.endpoint,
782
791
  path: ["endpoint"],
783
792
  namespace: config.namespace,
@@ -805,7 +814,7 @@ var RegistryConfigSchema = _zod.z.object({
805
814
  );
806
815
  const namespace = _nullishCoalesce(_nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.namespace), () => ( config.namespace)), () => ( "default"));
807
816
  const token = _nullishCoalesce((parsedEndpoint == null ? void 0 : parsedEndpoint.token), () => ( config.token));
808
- const parsedPublicEndpoint = config.serverless.publicEndpoint ? _chunkA55CGZIVcjs.tryParseEndpoint.call(void 0, ctx, {
817
+ const parsedPublicEndpoint = config.serverless.publicEndpoint ? _chunkRXXDNJXBcjs.tryParseEndpoint.call(void 0, ctx, {
809
818
  endpoint: config.serverless.publicEndpoint,
810
819
  path: ["serverless", "publicEndpoint"]
811
820
  }) : void 0;
@@ -840,7 +849,7 @@ function buildActorNames(config) {
840
849
  Object.keys(config.use).map((actorName) => {
841
850
  const definition = config.use[actorName];
842
851
  const options = _nullishCoalesce(definition.config.options, () => ( {}));
843
- const runMeta = _chunkHNHLBM3Ycjs.getRunMetadata.call(void 0, definition.config.run);
852
+ const runMeta = _chunk4KGXFC6Mcjs.getRunMetadata.call(void 0, definition.config.run);
844
853
  const metadata = {};
845
854
  metadata.icon = _nullishCoalesce(options.icon, () => ( runMeta.icon));
846
855
  metadata.name = _nullishCoalesce(options.name, () => ( runMeta.name));
@@ -908,7 +917,7 @@ var DocRegistryConfigSchema = _zod.z.object({
908
917
  noWelcome: _zod.z.boolean().optional().describe("Disable the welcome message on startup. Default: false"),
909
918
  sqlite: DocSqliteConfigSchema,
910
919
  logging: _zod.z.object({
911
- level: _chunk2ROUKH7Wcjs.LogLevelSchema.optional().describe(
920
+ level: _chunkGU7ML3KEcjs.LogLevelSchema.optional().describe(
912
921
  "Log level for RivetKit. Default: 'warn'"
913
922
  )
914
923
  }).optional().describe("Logging configuration."),
@@ -1193,11 +1202,33 @@ function wrapJsNativeDatabase(database) {
1193
1202
  release();
1194
1203
  }
1195
1204
  },
1196
- async beginTransaction(timeoutMs) {
1205
+ async beginTransaction(timeoutMs, name) {
1206
+ const release = gate.enter();
1207
+ let transaction;
1208
+ try {
1209
+ transaction = await database.beginTransaction(timeoutMs, name);
1210
+ } catch (error) {
1211
+ enrichNativeDatabaseError(database, error);
1212
+ } finally {
1213
+ release();
1214
+ }
1215
+ return wrapTransaction(database, transaction, gate, (result) => {
1216
+ if (result.lastInsertRowId !== void 0) {
1217
+ lastInsertRowId = result.lastInsertRowId;
1218
+ }
1219
+ });
1220
+ },
1221
+ async beginStateTransaction(timeoutMs, context) {
1222
+ if (!database.beginStateTransaction) {
1223
+ throw new Error("actor state transactions are not configured");
1224
+ }
1197
1225
  const release = gate.enter();
1198
1226
  let transaction;
1199
1227
  try {
1200
- transaction = await database.beginTransaction(timeoutMs);
1228
+ transaction = await database.beginStateTransaction(
1229
+ timeoutMs,
1230
+ context
1231
+ );
1201
1232
  } catch (error) {
1202
1233
  enrichNativeDatabaseError(database, error);
1203
1234
  } finally {
@@ -1307,45 +1338,37 @@ var nodeChildProcess;
1307
1338
  var nodeStream;
1308
1339
  var nodeUrl;
1309
1340
  var hasImportedDependencies = false;
1310
- function getRequireFn() {
1311
- return _module.createRequire.call(void 0, import.meta.url);
1341
+ var fallbackRequire;
1342
+ function loadNodeBuiltin(id) {
1343
+ var _a;
1344
+ const nodeProcess = globalThis.process;
1345
+ const builtin = (_a = nodeProcess == null ? void 0 : nodeProcess.getBuiltinModule) == null ? void 0 : _a.call(nodeProcess, id);
1346
+ if (builtin !== void 0) {
1347
+ return builtin;
1348
+ }
1349
+ if (!(nodeProcess == null ? void 0 : nodeProcess.execPath)) {
1350
+ throw new Error("Node.js built-ins are not available");
1351
+ }
1352
+ fallbackRequire ??= _module.createRequire.call(void 0, nodeProcess.execPath);
1353
+ return fallbackRequire(id);
1312
1354
  }
1313
1355
  function importNodeDependencies() {
1314
1356
  if (hasImportedDependencies) return;
1315
1357
  try {
1316
- const requireFn = getRequireFn();
1317
- nodeCrypto = requireFn(
1318
- /* webpackIgnore: true */
1319
- "node:crypto"
1320
- );
1321
- nodeFsSync = requireFn(
1322
- /* webpackIgnore: true */
1323
- "node:fs"
1324
- );
1325
- nodeFs = requireFn(
1326
- /* webpackIgnore: true */
1358
+ nodeCrypto = loadNodeBuiltin("node:crypto");
1359
+ nodeFsSync = loadNodeBuiltin("node:fs");
1360
+ nodeFs = loadNodeBuiltin(
1327
1361
  "node:fs/promises"
1328
1362
  );
1329
- nodePath = requireFn(
1330
- /* webpackIgnore: true */
1331
- "node:path"
1332
- );
1333
- nodeOs = requireFn(
1334
- /* webpackIgnore: true */
1335
- "node:os"
1336
- );
1337
- nodeChildProcess = requireFn(
1338
- /* webpackIgnore: true */
1363
+ nodePath = loadNodeBuiltin("node:path");
1364
+ nodeOs = loadNodeBuiltin("node:os");
1365
+ nodeChildProcess = loadNodeBuiltin(
1339
1366
  "node:child_process"
1340
1367
  );
1341
- nodeStream = requireFn(
1342
- /* webpackIgnore: true */
1368
+ nodeStream = loadNodeBuiltin(
1343
1369
  "node:stream/promises"
1344
1370
  );
1345
- nodeUrl = requireFn(
1346
- /* webpackIgnore: true */
1347
- "node:url"
1348
- );
1371
+ nodeUrl = loadNodeBuiltin("node:url");
1349
1372
  hasImportedDependencies = true;
1350
1373
  } catch (err) {
1351
1374
  console.warn(
@@ -1396,6 +1419,9 @@ function asNativeWebSocket(handle) {
1396
1419
  function asNativeSqlTransaction(handle) {
1397
1420
  return handle;
1398
1421
  }
1422
+ function asNativeActorStateTransaction(handle) {
1423
+ return handle;
1424
+ }
1399
1425
  function asNativeCancellationToken(handle) {
1400
1426
  return handle;
1401
1427
  }
@@ -1619,6 +1645,9 @@ var NapiCoreRuntime = (_class = class {
1619
1645
  actorSetAlarm(ctx, timestampMs) {
1620
1646
  asNativeActorContext(ctx).setAlarm(timestampMs);
1621
1647
  }
1648
+ async actorSetRunWakeAt(ctx, timestampMs) {
1649
+ await asNativeActorContext(ctx).setRunWakeAt(timestampMs);
1650
+ }
1622
1651
  actorRequestSave(ctx, opts) {
1623
1652
  asNativeActorContext(ctx).requestSave(opts);
1624
1653
  }
@@ -1779,9 +1808,10 @@ var NapiCoreRuntime = (_class = class {
1779
1808
  );
1780
1809
  return results.map(normalizeRuntimeSqlExecuteResult);
1781
1810
  }
1782
- async actorSqlBeginTransaction(ctx, timeoutMs) {
1811
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
1783
1812
  return await this.#actorSql(ctx).beginTransaction(
1784
- timeoutMs
1813
+ timeoutMs,
1814
+ name
1785
1815
  );
1786
1816
  }
1787
1817
  async actorSqlTransactionExec(transaction, sql) {
@@ -1800,6 +1830,26 @@ var NapiCoreRuntime = (_class = class {
1800
1830
  async actorSqlTransactionRollback(transaction) {
1801
1831
  await asNativeSqlTransaction(transaction).rollback();
1802
1832
  }
1833
+ async actorBeginStateTransaction(ctx, timeoutMs) {
1834
+ return await asNativeActorContext(ctx).beginStateTransaction(
1835
+ timeoutMs
1836
+ );
1837
+ }
1838
+ async actorStateTransactionExecute(transaction, sql, params) {
1839
+ const result = await asNativeActorStateTransaction(transaction).execute(
1840
+ sql,
1841
+ toNapiSqlBindParams(params)
1842
+ );
1843
+ return normalizeRuntimeSqlExecuteResult(result);
1844
+ }
1845
+ async actorStateTransactionCommit(transaction, payload) {
1846
+ await asNativeActorStateTransaction(transaction).commit(
1847
+ toNapiStateDeltaPayload(payload)
1848
+ );
1849
+ }
1850
+ async actorStateTransactionRollback(transaction) {
1851
+ await asNativeActorStateTransaction(transaction).rollback();
1852
+ }
1803
1853
  async actorSqlQuery(ctx, sql, params) {
1804
1854
  return await this.#actorSql(ctx).query(
1805
1855
  sql,
@@ -1857,6 +1907,13 @@ var NapiCoreRuntime = (_class = class {
1857
1907
  signal ? asNativeCancellationToken(signal) : signal
1858
1908
  );
1859
1909
  }
1910
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
1911
+ return await asNativeActorContext(ctx).queue().completePersisted(
1912
+ messageId,
1913
+ expectedName,
1914
+ response == null ? response : toNapiBuffer(response)
1915
+ );
1916
+ }
1860
1917
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1861
1918
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
1862
1919
  name,
@@ -2046,7 +2103,167 @@ function validationError(target, issues) {
2046
2103
  });
2047
2104
  }
2048
2105
 
2106
+ // src/registry/run-handler-coordinator.ts
2107
+ function runUnavailable(actorId, reason) {
2108
+ return new (0, _chunk4FC7TVS6cjs.RivetError)(
2109
+ "actor",
2110
+ "run_handler_unavailable",
2111
+ `Run handler control is unavailable for actor ${actorId}: ${reason}.`,
2112
+ {
2113
+ public: true,
2114
+ statusCode: 409,
2115
+ metadata: { actorId, reason }
2116
+ }
2117
+ );
2118
+ }
2119
+ function notifyStateChanged(state) {
2120
+ const waiters = [...state.waiters];
2121
+ state.waiters.clear();
2122
+ for (const waiter of waiters) {
2123
+ waiter();
2124
+ }
2125
+ }
2126
+ function waitForStateChange(state) {
2127
+ return new Promise((resolve) => {
2128
+ state.waiters.add(resolve);
2129
+ });
2130
+ }
2131
+ var RunHandlerCoordinator = class {
2132
+ #run;
2133
+ #states = /* @__PURE__ */ new Map();
2134
+ constructor(run) {
2135
+ this.#run = run;
2136
+ }
2137
+ get inspectorKind() {
2138
+ return _chunk4KGXFC6Mcjs.getRunInspectorKind.call(void 0, this.#run);
2139
+ }
2140
+ async run(actorId, restart, callback) {
2141
+ const state = this.#getOrCreate(actorId);
2142
+ state.restart = restart;
2143
+ this.#initializeInspector(actorId, state);
2144
+ state.queued += 1;
2145
+ const blockedGeneration = state.exclusive ? state.exclusiveGeneration : void 0;
2146
+ try {
2147
+ while (!state.closed && (state.exclusive || state.active)) {
2148
+ await waitForStateChange(state);
2149
+ }
2150
+ } finally {
2151
+ state.queued -= 1;
2152
+ }
2153
+ if (state.closed) {
2154
+ return "closed";
2155
+ }
2156
+ if (blockedGeneration !== void 0 && state.exclusiveGeneration === blockedGeneration && state.exclusiveOutcome === "failure") {
2157
+ return "suppressed";
2158
+ }
2159
+ state.active = true;
2160
+ try {
2161
+ await callback();
2162
+ return "ran";
2163
+ } finally {
2164
+ state.active = false;
2165
+ notifyStateChanged(state);
2166
+ }
2167
+ }
2168
+ getInspector(actorId, restart) {
2169
+ var _a;
2170
+ const state = this.#getOrCreate(actorId);
2171
+ state.restart = restart;
2172
+ this.#initializeInspector(actorId, state);
2173
+ return (_a = state.inspector) == null ? void 0 : _a.inspector;
2174
+ }
2175
+ destroy(actorId) {
2176
+ var _a, _b;
2177
+ const state = this.#states.get(actorId);
2178
+ if (!state) return;
2179
+ state.closed = true;
2180
+ (_b = (_a = state.inspector) == null ? void 0 : _a.dispose) == null ? void 0 : _b.call(_a);
2181
+ state.inspector = void 0;
2182
+ notifyStateChanged(state);
2183
+ this.#states.delete(actorId);
2184
+ }
2185
+ #control(actorId, state) {
2186
+ return {
2187
+ run: {
2188
+ withInactive: async (options, callback) => {
2189
+ if (state.closed) {
2190
+ throw runUnavailable(actorId, "actor is destroyed");
2191
+ }
2192
+ if (state.active || state.queued > 0 || state.exclusive) {
2193
+ throw runUnavailable(
2194
+ actorId,
2195
+ "the run handler is active or waiting to start"
2196
+ );
2197
+ }
2198
+ state.exclusive = true;
2199
+ state.exclusiveGeneration += 1;
2200
+ state.exclusiveOutcome = void 0;
2201
+ try {
2202
+ const result = await callback();
2203
+ if (state.closed) {
2204
+ throw runUnavailable(actorId, "actor is destroyed");
2205
+ }
2206
+ state.exclusiveOutcome = "success";
2207
+ if (options.restartOnSuccess && state.queued === 0) {
2208
+ if (!state.restart) {
2209
+ throw runUnavailable(
2210
+ actorId,
2211
+ "the runtime restart callback is not available"
2212
+ );
2213
+ }
2214
+ await state.restart();
2215
+ }
2216
+ return result;
2217
+ } catch (error) {
2218
+ state.exclusiveOutcome = "failure";
2219
+ throw error;
2220
+ } finally {
2221
+ state.exclusive = false;
2222
+ notifyStateChanged(state);
2223
+ }
2224
+ }
2225
+ }
2226
+ };
2227
+ }
2228
+ #getOrCreate(actorId) {
2229
+ let state = this.#states.get(actorId);
2230
+ if (!state) {
2231
+ state = {
2232
+ active: false,
2233
+ closed: false,
2234
+ exclusive: false,
2235
+ exclusiveGeneration: 0,
2236
+ inspectorInitialized: false,
2237
+ queued: 0,
2238
+ waiters: /* @__PURE__ */ new Set()
2239
+ };
2240
+ this.#states.set(actorId, state);
2241
+ }
2242
+ return state;
2243
+ }
2244
+ #initializeInspector(actorId, state) {
2245
+ if (state.inspectorInitialized) return;
2246
+ const inspector = _chunk4KGXFC6Mcjs.createRunInspector.call(void 0, this.#run, {
2247
+ actorId,
2248
+ control: this.#control(actorId, state)
2249
+ });
2250
+ if (this.inspectorKind === "workflow") {
2251
+ const workflow = inspector === void 0 ? void 0 : inspector.inspector.workflow;
2252
+ if (!workflow || typeof workflow.getHistory !== "function" || typeof workflow.getState !== "function" || typeof workflow.onHistoryUpdated !== "function" || typeof workflow.replayFromStep !== "function") {
2253
+ throw new TypeError(
2254
+ `defineRunHandler createInspector returned an invalid workflow adapter for actor ${actorId}`
2255
+ );
2256
+ }
2257
+ }
2258
+ state.inspector = inspector;
2259
+ state.inspectorInitialized = true;
2260
+ }
2261
+ };
2262
+
2049
2263
  // src/registry/wasm-runtime.ts
2264
+ function asWasmConstructors(bindings) {
2265
+ return bindings;
2266
+ }
2050
2267
  function asWasmRegistry(handle) {
2051
2268
  return handle;
2052
2269
  }
@@ -2171,10 +2388,10 @@ function childHandle(handle, name) {
2171
2388
  }
2172
2389
  var WasmCoreRuntime = (_class2 = class {
2173
2390
  __init2() {this.kind = "wasm"}
2174
- #bindings;
2391
+ #constructors;
2175
2392
  #sql = /* @__PURE__ */ new WeakMap();
2176
2393
  constructor(bindings) {;_class2.prototype.__init2.call(this);
2177
- this.#bindings = bindings;
2394
+ this.#constructors = asWasmConstructors(bindings);
2178
2395
  }
2179
2396
  #actorSql(ctx) {
2180
2397
  const wasmCtx = asWasmActorContext(ctx);
@@ -2187,7 +2404,7 @@ var WasmCoreRuntime = (_class2 = class {
2187
2404
  }
2188
2405
  createRegistry() {
2189
2406
  return callWasmSync(
2190
- () => asRegistryHandle2(new this.#bindings.CoreRegistry())
2407
+ () => asRegistryHandle2(new this.#constructors.CoreRegistry())
2191
2408
  );
2192
2409
  }
2193
2410
  registerActor(registry, name, factory) {
@@ -2242,13 +2459,13 @@ var WasmCoreRuntime = (_class2 = class {
2242
2459
  createActorFactory(callbacks, config) {
2243
2460
  return callWasmSync(
2244
2461
  () => asActorFactoryHandle2(
2245
- new this.#bindings.ActorFactory(callbacks, config)
2462
+ new this.#constructors.ActorFactory(callbacks, config)
2246
2463
  )
2247
2464
  );
2248
2465
  }
2249
2466
  createCancellationToken() {
2250
2467
  return callWasmSync(
2251
- () => new this.#bindings.CancellationToken()
2468
+ () => new this.#constructors.CancellationToken()
2252
2469
  );
2253
2470
  }
2254
2471
  cancellationTokenAborted(token) {
@@ -2283,6 +2500,13 @@ var WasmCoreRuntime = (_class2 = class {
2283
2500
  optionalWasmNumber(timestampMs)
2284
2501
  );
2285
2502
  }
2503
+ async actorSetRunWakeAt(ctx, timestampMs) {
2504
+ await callHandleAsync(
2505
+ asWasmActorContext(ctx),
2506
+ "setRunWakeAt",
2507
+ optionalWasmNumber(timestampMs)
2508
+ );
2509
+ }
2286
2510
  actorRequestSave(ctx, opts) {
2287
2511
  callHandle(asWasmActorContext(ctx), "requestSave", opts);
2288
2512
  }
@@ -2497,9 +2721,9 @@ var WasmCoreRuntime = (_class2 = class {
2497
2721
  );
2498
2722
  return results.map(normalizeRuntimeSqlExecuteResult);
2499
2723
  }
2500
- async actorSqlBeginTransaction(ctx, timeoutMs) {
2724
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
2501
2725
  return await callWasm(
2502
- () => this.#actorSql(ctx).beginTransaction(timeoutMs)
2726
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs, name)
2503
2727
  );
2504
2728
  }
2505
2729
  async actorSqlTransactionExec(transaction, sql) {
@@ -2523,6 +2747,27 @@ var WasmCoreRuntime = (_class2 = class {
2523
2747
  () => transaction.rollback()
2524
2748
  );
2525
2749
  }
2750
+ async actorBeginStateTransaction(ctx, timeoutMs) {
2751
+ return await callWasm(
2752
+ () => asWasmActorContext(ctx).beginStateTransaction(timeoutMs)
2753
+ );
2754
+ }
2755
+ async actorStateTransactionExecute(transaction, sql, params) {
2756
+ const result = await callWasm(
2757
+ () => transaction.execute(sql, params)
2758
+ );
2759
+ return normalizeRuntimeSqlExecuteResult(result);
2760
+ }
2761
+ async actorStateTransactionCommit(transaction, payload) {
2762
+ await callWasm(
2763
+ () => transaction.commit(payload)
2764
+ );
2765
+ }
2766
+ async actorStateTransactionRollback(transaction) {
2767
+ await callWasm(
2768
+ () => transaction.rollback()
2769
+ );
2770
+ }
2526
2771
  async actorSqlQuery(ctx, sql, params) {
2527
2772
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
2528
2773
  }
@@ -2595,6 +2840,16 @@ var WasmCoreRuntime = (_class2 = class {
2595
2840
  signal
2596
2841
  );
2597
2842
  }
2843
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
2844
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2845
+ return await callHandleAsync(
2846
+ queue2,
2847
+ "completePersisted",
2848
+ messageId,
2849
+ expectedName,
2850
+ response
2851
+ );
2852
+ }
2598
2853
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
2599
2854
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2600
2855
  return optionalBytes(
@@ -2795,6 +3050,83 @@ function createWriteThroughProxy(value, commit, beforeChange) {
2795
3050
  }
2796
3051
  );
2797
3052
  }
3053
+ function unwrapProxy(value) {
3054
+ let current = value;
3055
+ while (current !== null && typeof current === "object") {
3056
+ const target = _onchange2.default.target(current);
3057
+ if (target === current) {
3058
+ break;
3059
+ }
3060
+ current = target;
3061
+ }
3062
+ return current;
3063
+ }
3064
+ function isPlainObject(value) {
3065
+ const proto = Object.getPrototypeOf(value);
3066
+ return proto === Object.prototype || proto === null;
3067
+ }
3068
+ function unwrapDeep(value, seen) {
3069
+ const unwrapped = unwrapProxy(value);
3070
+ if (!unwrapped || typeof unwrapped !== "object") {
3071
+ return unwrapped;
3072
+ }
3073
+ if (seen.has(unwrapped)) {
3074
+ return unwrapped;
3075
+ }
3076
+ seen.add(unwrapped);
3077
+ if (Array.isArray(unwrapped)) {
3078
+ for (let i = 0; i < unwrapped.length; i++) {
3079
+ const child = unwrapDeep(unwrapped[i], seen);
3080
+ if (child !== unwrapped[i]) {
3081
+ unwrapped[i] = child;
3082
+ }
3083
+ }
3084
+ return unwrapped;
3085
+ }
3086
+ if (unwrapped instanceof Map) {
3087
+ const replacements = [];
3088
+ for (const [key, child] of unwrapped.entries()) {
3089
+ const nextKey = unwrapDeep(key, seen);
3090
+ const nextChild = unwrapDeep(child, seen);
3091
+ if (nextKey !== key || nextChild !== child) {
3092
+ replacements.push([key, nextKey, nextChild]);
3093
+ }
3094
+ }
3095
+ for (const [key, nextKey, nextChild] of replacements) {
3096
+ if (nextKey !== key) {
3097
+ unwrapped.delete(key);
3098
+ }
3099
+ unwrapped.set(nextKey, nextChild);
3100
+ }
3101
+ return unwrapped;
3102
+ }
3103
+ if (unwrapped instanceof Set) {
3104
+ const replacements = [];
3105
+ for (const child of unwrapped.values()) {
3106
+ const next = unwrapDeep(child, seen);
3107
+ if (next !== child) {
3108
+ replacements.push([child, next]);
3109
+ }
3110
+ }
3111
+ for (const [child, next] of replacements) {
3112
+ unwrapped.delete(child);
3113
+ unwrapped.add(next);
3114
+ }
3115
+ return unwrapped;
3116
+ }
3117
+ if (isPlainObject(unwrapped)) {
3118
+ for (const key of Object.keys(unwrapped)) {
3119
+ const child = unwrapDeep(unwrapped[key], seen);
3120
+ if (child !== unwrapped[key]) {
3121
+ unwrapped[key] = child;
3122
+ }
3123
+ }
3124
+ }
3125
+ return unwrapped;
3126
+ }
3127
+ function unwrapWriteThroughProxy(value) {
3128
+ return unwrapDeep(value, /* @__PURE__ */ new Set());
3129
+ }
2798
3130
 
2799
3131
  // src/registry/native.ts
2800
3132
  var textEncoder = new TextEncoder();
@@ -2941,6 +3273,14 @@ function stateMutationReentrantError() {
2941
3273
  "State mutations are not allowed inside onStateChange."
2942
3274
  );
2943
3275
  }
3276
+ function stateTransactionConflictError() {
3277
+ return new (0, _chunk4FC7TVS6cjs.RivetError)(
3278
+ "actor",
3279
+ "state_transaction_conflict",
3280
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
3281
+ { public: true, statusCode: 409 }
3282
+ );
3283
+ }
2944
3284
  function databaseNotConfiguredError() {
2945
3285
  return new (0, _chunk4FC7TVS6cjs.RivetError)(
2946
3286
  "actor",
@@ -2957,6 +3297,14 @@ function databaseClientNotReadyError() {
2957
3297
  { public: true }
2958
3298
  );
2959
3299
  }
3300
+ function runHandlerNotConfiguredError() {
3301
+ return new (0, _chunk4FC7TVS6cjs.RivetError)(
3302
+ "actor",
3303
+ "run_handler_unavailable",
3304
+ "Cannot schedule a run wake because this actor does not define a run handler.",
3305
+ { public: true, statusCode: 409 }
3306
+ );
3307
+ }
2960
3308
  function stateNotEnabledError() {
2961
3309
  return new (0, _chunk4FC7TVS6cjs.RivetError)(
2962
3310
  "actor",
@@ -3019,7 +3367,7 @@ async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrai
3019
3367
  }).catch((error) => {
3020
3368
  logger2().warn({
3021
3369
  msg: "deferred native sleep cleanup failed",
3022
- error: _chunk2ROUKH7Wcjs.stringifyError.call(void 0, error)
3370
+ error: _chunkGU7ML3KEcjs.stringifyError.call(void 0, error)
3023
3371
  });
3024
3372
  });
3025
3373
  return;
@@ -3059,10 +3407,11 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
3059
3407
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
3060
3408
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
3061
3409
  executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
3062
- beginTransaction: async (timeoutMs) => {
3410
+ beginTransaction: async (timeoutMs, name) => {
3063
3411
  const transaction = await runtime.actorSqlBeginTransaction(
3064
3412
  ctx,
3065
- timeoutMs
3413
+ timeoutMs,
3414
+ name
3066
3415
  );
3067
3416
  return {
3068
3417
  exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
@@ -3075,6 +3424,38 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
3075
3424
  rollback: () => runtime.actorSqlTransactionRollback(transaction)
3076
3425
  };
3077
3426
  },
3427
+ beginStateTransaction: async (timeoutMs, context) => {
3428
+ const scope = context;
3429
+ if (!scope) {
3430
+ throw new Error(
3431
+ "actor state transaction context is not configured"
3432
+ );
3433
+ }
3434
+ const transaction = await runtime.actorBeginStateTransaction(
3435
+ ctx,
3436
+ timeoutMs
3437
+ );
3438
+ return {
3439
+ exec: async () => {
3440
+ throw new Error(
3441
+ "actor state transactions only support single-statement execute calls"
3442
+ );
3443
+ },
3444
+ execute: (sql, params) => runtime.actorStateTransactionExecute(
3445
+ transaction,
3446
+ sql,
3447
+ params
3448
+ ),
3449
+ commit: async () => {
3450
+ await runtime.actorStateTransactionCommit(
3451
+ transaction,
3452
+ scope.actorContext.serializeForTick("save")
3453
+ );
3454
+ scope.committed = true;
3455
+ },
3456
+ rollback: () => runtime.actorStateTransactionRollback(transaction)
3457
+ };
3458
+ },
3078
3459
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
3079
3460
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
3080
3461
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -3146,10 +3527,10 @@ function decodeValue(value) {
3146
3527
  if (!value || value.length === 0) {
3147
3528
  return void 0;
3148
3529
  }
3149
- return _chunk2ROUKH7Wcjs.decodeCborCompat.call(void 0, value);
3530
+ return _chunkGU7ML3KEcjs.decodeCborCompat.call(void 0, value);
3150
3531
  }
3151
3532
  function encodeValue(value) {
3152
- return _chunk2ROUKH7Wcjs.encodeCborCompat.call(void 0, value);
3533
+ return _chunkGU7ML3KEcjs.encodeCborCompat.call(void 0, value);
3153
3534
  }
3154
3535
  function normalizeArgs(value) {
3155
3536
  return Array.isArray(value) ? value : value === void 0 || value === null ? [] : [value];
@@ -3185,7 +3566,7 @@ function isStructuredBridgeError(error) {
3185
3566
  return _chunk4FC7TVS6cjs.isRivetErrorLike.call(void 0, error) && "__type" in error && (error.__type === "RivetError" || error.__type === "ActorError");
3186
3567
  }
3187
3568
  function encodeNativeCallbackError(error) {
3188
- const structuredError = isStructuredBridgeError(error) ? error : _chunk2ROUKH7Wcjs.deconstructError.call(void 0, error, true);
3569
+ const structuredError = isStructuredBridgeError(error) ? error : _chunkGU7ML3KEcjs.deconstructError.call(void 0, error, true);
3189
3570
  const bridgeError = new Error(_chunk4FC7TVS6cjs.encodeBridgeRivetError.call(void 0, structuredError), {
3190
3571
  cause: error instanceof Error ? error : void 0
3191
3572
  });
@@ -3235,7 +3616,7 @@ function decodeWorkflowCbor(data) {
3235
3616
  return null;
3236
3617
  }
3237
3618
  try {
3238
- return _chunk2ROUKH7Wcjs.decodeCborCompat.call(void 0, new Uint8Array(data));
3619
+ return _chunkGU7ML3KEcjs.decodeCborCompat.call(void 0, new Uint8Array(data));
3239
3620
  } catch (e5) {
3240
3621
  return null;
3241
3622
  }
@@ -3348,7 +3729,7 @@ function serializeWorkflowHistoryForJson(data) {
3348
3729
  if (data === null) {
3349
3730
  return null;
3350
3731
  }
3351
- const history = _chunkN6MBTYGXcjs.decodeWorkflowHistoryTransport.call(void 0, data);
3732
+ const history = _chunkVBJQIBXIcjs.decodeWorkflowHistoryTransport.call(void 0, data);
3352
3733
  return jsonSafe({
3353
3734
  nameRegistry: [...history.nameRegistry],
3354
3735
  entries: history.entries.map((entry) => ({
@@ -3455,13 +3836,17 @@ var NativeConnAdapter = class {
3455
3836
  #schemas;
3456
3837
  #ctx;
3457
3838
  #queueHibernationRemoval;
3458
- constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval) {
3839
+ #assertCanMutateState;
3840
+ #stateProxy;
3841
+ #stateProxyTarget;
3842
+ constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval, assertCanMutateState) {
3459
3843
  this.#runtime = runtime;
3460
3844
  this.#conn = conn;
3461
3845
  this.#schemas = schemas;
3462
3846
  this.#ctx = ctx;
3463
3847
  this.#queueHibernationRemoval = queueHibernationRemoval;
3464
- this[_chunkHNHLBM3Ycjs.CONN_STATE_MANAGER_SYMBOL] = {
3848
+ this.#assertCanMutateState = assertCanMutateState;
3849
+ this[_chunk4KGXFC6Mcjs.CONN_STATE_MANAGER_SYMBOL] = {
3465
3850
  stateEnabled: true,
3466
3851
  get state() {
3467
3852
  return thisConn.state;
@@ -3478,27 +3863,51 @@ var NativeConnAdapter = class {
3478
3863
  decodeValue(this.#runtime.connParams(this.#conn))
3479
3864
  );
3480
3865
  }
3481
- [_chunkHNHLBM3Ycjs.RAW_STATE_SYMBOL]() {
3866
+ [_chunk4KGXFC6Mcjs.RAW_STATE_SYMBOL]() {
3482
3867
  return this.#readState();
3483
3868
  }
3484
3869
  get state() {
3485
3870
  const nextState = this.#readState();
3871
+ if (!this.#ctx) {
3872
+ return this.#createStateProxy(nextState);
3873
+ }
3874
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
3875
+ this.#stateProxyTarget = nextState;
3876
+ this.#stateProxy = this.#createStateProxy(nextState);
3877
+ }
3878
+ return this.#stateProxy;
3879
+ }
3880
+ #createStateProxy(state) {
3881
+ const assertCurrentState = () => {
3882
+ var _a;
3883
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
3884
+ if (this.#ctx && this.#readState() !== state) {
3885
+ throw stateTransactionConflictError();
3886
+ }
3887
+ };
3486
3888
  return createWriteThroughProxy(
3487
- nextState,
3889
+ state,
3488
3890
  (nextValue) => {
3891
+ assertCurrentState();
3489
3892
  this.#writeState(nextValue, { writeNative: true });
3490
3893
  },
3491
3894
  (newValue) => {
3492
- _chunk2ROUKH7Wcjs.assertJsonCompatValue.call(void 0, newValue);
3895
+ assertCurrentState();
3896
+ _chunkGU7ML3KEcjs.assertJsonCompatValue.call(void 0, newValue);
3493
3897
  }
3494
3898
  );
3495
3899
  }
3496
3900
  set state(value) {
3497
- _chunk2ROUKH7Wcjs.assertJsonCompatValue.call(void 0, value);
3498
- this.#writeState(value, { writeNative: true });
3901
+ var _a;
3902
+ (_a = this.#assertCanMutateState) == null ? void 0 : _a.call(this);
3903
+ const nextValue = unwrapWriteThroughProxy(value);
3904
+ _chunkGU7ML3KEcjs.assertJsonCompatValue.call(void 0, nextValue);
3905
+ this.#writeState(nextValue, { writeNative: true });
3499
3906
  }
3500
3907
  initializeState(value) {
3501
- this.#writeState(value, { writeNative: false });
3908
+ this.#writeState(unwrapWriteThroughProxy(value), {
3909
+ writeNative: false
3910
+ });
3502
3911
  }
3503
3912
  get isHibernatable() {
3504
3913
  return callNativeSync(
@@ -3816,8 +4225,9 @@ var NativeKvAdapter = class {
3816
4225
  };
3817
4226
  function wrapQueueMessage(message, schemas) {
3818
4227
  const name = callNativeSync(() => message.name());
4228
+ const id = callNativeSync(() => message.id());
3819
4229
  return {
3820
- id: Number(callNativeSync(() => message.id())),
4230
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
3821
4231
  name,
3822
4232
  body: validateQueueBody(
3823
4233
  schemas,
@@ -3955,6 +4365,25 @@ var NativeQueueAdapter = class {
3955
4365
  cleanup == null ? void 0 : cleanup();
3956
4366
  }
3957
4367
  }
4368
+ async waitForAvailable(names, options) {
4369
+ await this.waitForNamesAvailable(_nullishCoalesce(names, () => ( [])), options);
4370
+ }
4371
+ async complete(message, response) {
4372
+ const validatedResponse = validateQueueComplete(
4373
+ this.#schemas,
4374
+ message.name,
4375
+ response
4376
+ );
4377
+ await callNative(
4378
+ () => this.#runtime.actorQueueCompletePersisted(
4379
+ this.#ctx,
4380
+ BigInt(message.id),
4381
+ message.name,
4382
+ encodeValue(validatedResponse)
4383
+ )
4384
+ );
4385
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
4386
+ }
3958
4387
  async enqueueAndWait(name, body, options) {
3959
4388
  const validatedBody = validateQueueBody(this.#schemas, name, body);
3960
4389
  const { token, cleanup } = await createCancellationTokenHandle(
@@ -4391,10 +4820,12 @@ var NativeConnectionMap = (_class3 = class {
4391
4820
  #runtime;
4392
4821
  #ctx;
4393
4822
  #schemas;
4394
- constructor(runtime, ctx, schemas) {;_class3.prototype.__init3.call(this);
4823
+ #assertCanMutateState;
4824
+ constructor(runtime, ctx, schemas, assertCanMutateState) {;_class3.prototype.__init3.call(this);
4395
4825
  this.#runtime = runtime;
4396
4826
  this.#ctx = ctx;
4397
4827
  this.#schemas = schemas;
4828
+ this.#assertCanMutateState = assertCanMutateState;
4398
4829
  }
4399
4830
  #connToAdapter(conn) {
4400
4831
  return new NativeConnAdapter(
@@ -4407,7 +4838,8 @@ var NativeConnectionMap = (_class3 = class {
4407
4838
  this.#ctx,
4408
4839
  connId
4409
4840
  )
4410
- )
4841
+ ),
4842
+ this.#assertCanMutateState
4411
4843
  );
4412
4844
  }
4413
4845
  get size() {
@@ -4466,24 +4898,27 @@ var ActorContextHandleAdapter = class {
4466
4898
  #queue;
4467
4899
  #request;
4468
4900
  #schedule;
4469
- #sql;
4470
- #runHandlerActiveProvider;
4901
+ #run;
4902
+ #runHandlerConfigured;
4471
4903
  #onStateChange;
4472
4904
  #stateEnabled;
4473
- constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, runHandlerActiveProvider, onStateChange, dispatchCancelToken) {
4905
+ #stateProxy;
4906
+ #stateProxyTarget;
4907
+ #stateTransactionOwner = /* @__PURE__ */ Symbol("actor-state-transaction-owner");
4908
+ constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
4474
4909
  this.#runtime = runtime;
4475
4910
  this.#ctx = ctx;
4476
4911
  this.#clientFactory = clientFactory;
4477
4912
  this.#schemas = schemas;
4478
4913
  this.#dispatchCancelToken = dispatchCancelToken;
4479
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
4914
+ this.#runHandlerConfigured = runHandlerConfigured;
4480
4915
  this.#onStateChange = onStateChange;
4481
4916
  this.#stateEnabled = stateEnabled;
4482
4917
  if (databaseProvider) {
4483
4918
  this.#databaseProvider = databaseProvider;
4484
4919
  }
4485
4920
  this.#request = request;
4486
- this[_chunkHNHLBM3Ycjs.ACTOR_CONTEXT_INTERNAL_SYMBOL] = new NativeWorkflowRuntimeAdapter(
4921
+ this[_chunk4KGXFC6Mcjs.ACTOR_CONTEXT_INTERNAL_SYMBOL] = new NativeWorkflowRuntimeAdapter(
4487
4922
  this
4488
4923
  );
4489
4924
  }
@@ -4493,12 +4928,6 @@ var ActorContextHandleAdapter = class {
4493
4928
  }
4494
4929
  return this.#kv;
4495
4930
  }
4496
- get sql() {
4497
- if (!this.#sql) {
4498
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
4499
- }
4500
- return this.#sql;
4501
- }
4502
4931
  async actorRuntimeSocket() {
4503
4932
  return await callNative(
4504
4933
  () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
@@ -4514,12 +4943,12 @@ var ActorContextHandleAdapter = class {
4514
4943
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4515
4944
  const cachedClient = runtimeState.databaseClient;
4516
4945
  if (cachedClient) {
4517
- this.#db = cachedClient.client;
4946
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
4518
4947
  return this.#db;
4519
4948
  }
4520
4949
  throw databaseClientNotReadyError();
4521
4950
  }
4522
- [_chunkHNHLBM3Ycjs.RAW_STATE_SYMBOL]() {
4951
+ [_chunk4KGXFC6Mcjs.RAW_STATE_SYMBOL]() {
4523
4952
  if (!this.#stateEnabled) {
4524
4953
  throw stateNotEnabledError();
4525
4954
  }
@@ -4529,36 +4958,45 @@ var ActorContextHandleAdapter = class {
4529
4958
  if (!this.#stateEnabled) {
4530
4959
  throw stateNotEnabledError();
4531
4960
  }
4532
- const actorState = getNativePersistState(this.#runtime, this.#ctx);
4533
4961
  const nextState = this.#readState();
4534
- if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
4535
- actorState.stateProxyTarget = nextState;
4536
- actorState.stateProxy = createWriteThroughProxy(
4962
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
4963
+ const assertCurrentState = () => {
4964
+ this.#assertCanMutateState();
4965
+ if (this.#readState() !== nextState) {
4966
+ throw stateTransactionConflictError();
4967
+ }
4968
+ };
4969
+ this.#stateProxyTarget = nextState;
4970
+ this.#stateProxy = createWriteThroughProxy(
4537
4971
  nextState,
4538
4972
  (nextValue) => {
4973
+ assertCurrentState();
4539
4974
  this.#writeState(nextValue, { scheduleSave: true });
4540
4975
  },
4541
4976
  (newValue) => {
4542
- this.#assertCanMutateState();
4543
- _chunk2ROUKH7Wcjs.assertJsonCompatValue.call(void 0, newValue);
4977
+ assertCurrentState();
4978
+ _chunkGU7ML3KEcjs.assertJsonCompatValue.call(void 0, newValue);
4544
4979
  }
4545
4980
  );
4546
4981
  }
4547
- return actorState.stateProxy;
4982
+ return this.#stateProxy;
4548
4983
  }
4549
4984
  set state(value) {
4550
4985
  if (!this.#stateEnabled) {
4551
4986
  throw stateNotEnabledError();
4552
4987
  }
4553
4988
  this.#assertCanMutateState();
4554
- _chunk2ROUKH7Wcjs.assertJsonCompatValue.call(void 0, value);
4555
- this.#writeState(value, { scheduleSave: true });
4989
+ const nextValue = unwrapWriteThroughProxy(value);
4990
+ _chunkGU7ML3KEcjs.assertJsonCompatValue.call(void 0, nextValue);
4991
+ this.#writeState(nextValue, { scheduleSave: true });
4556
4992
  }
4557
4993
  initializeState(value) {
4558
4994
  if (!this.#stateEnabled) {
4559
4995
  return;
4560
4996
  }
4561
- this.#writeState(value, { scheduleSave: false });
4997
+ this.#writeState(unwrapWriteThroughProxy(value), {
4998
+ scheduleSave: false
4999
+ });
4562
5000
  }
4563
5001
  get vars() {
4564
5002
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
@@ -4584,6 +5022,26 @@ var ActorContextHandleAdapter = class {
4584
5022
  }
4585
5023
  return this.#queue;
4586
5024
  }
5025
+ get run() {
5026
+ if (!this.#run) {
5027
+ this.#run = {
5028
+ setWakeAt: async (timestamp) => {
5029
+ if (timestamp !== null && !this.#runHandlerConfigured) {
5030
+ throw runHandlerNotConfiguredError();
5031
+ }
5032
+ if (timestamp !== null && (!Number.isSafeInteger(timestamp) || timestamp < 0)) {
5033
+ throw new TypeError(
5034
+ "Run wake timestamp must be a non-negative safe integer or null"
5035
+ );
5036
+ }
5037
+ await callNative(
5038
+ () => this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp)
5039
+ );
5040
+ }
5041
+ };
5042
+ }
5043
+ return this.#run;
5044
+ }
4587
5045
  get schedule() {
4588
5046
  if (!this.#schedule) {
4589
5047
  this.#schedule = new NativeScheduleAdapter(
@@ -4618,7 +5076,8 @@ var ActorContextHandleAdapter = class {
4618
5076
  this.#connMap = new NativeConnectionMap(
4619
5077
  this.#runtime,
4620
5078
  this.#ctx,
4621
- this.#schemas
5079
+ this.#schemas,
5080
+ () => this.#assertCanMutateState()
4622
5081
  );
4623
5082
  }
4624
5083
  return this.#connMap;
@@ -4687,11 +5146,11 @@ var ActorContextHandleAdapter = class {
4687
5146
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4688
5147
  const cachedClient = runtimeState.databaseClient;
4689
5148
  if (cachedClient) {
4690
- this.#db = cachedClient.client;
5149
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
4691
5150
  return this.#db;
4692
5151
  }
4693
5152
  const actorId = this.actorId;
4694
- const client = await this.#databaseProvider.createClient({
5153
+ const createdClient = await this.#databaseProvider.createClient({
4695
5154
  actorId,
4696
5155
  kv: {
4697
5156
  batchPut: async (entries) => {
@@ -4712,21 +5171,126 @@ var ActorContextHandleAdapter = class {
4712
5171
  log: {
4713
5172
  debug: (obj) => logger2().debug(obj)
4714
5173
  },
4715
- nativeDatabaseProvider: {
4716
- open: async (requestedActorId) => {
4717
- void requestedActorId;
4718
- return getOrCreateNativeSqlDatabase(
4719
- this.#runtime,
4720
- this.#ctx
4721
- );
4722
- }
4723
- }
5174
+ nativeDatabaseProvider: _chunkLWQFXGKScjs.registerNativeStateTransactionOpener.call(void 0,
5175
+ {
5176
+ open: async (requestedActorId) => {
5177
+ void requestedActorId;
5178
+ return getOrCreateNativeSqlDatabase(
5179
+ this.#runtime,
5180
+ this.#ctx
5181
+ );
5182
+ }
5183
+ },
5184
+ async (timeoutMs, context) => await getOrCreateNativeSqlDatabase(
5185
+ this.#runtime,
5186
+ this.#ctx
5187
+ ).beginStateTransaction(timeoutMs, context)
5188
+ )
4724
5189
  });
4725
5190
  runtimeState.databaseClient = {
4726
- client
5191
+ client: createdClient
4727
5192
  };
4728
- this.#db = client;
4729
- return client;
5193
+ this.#db = this.#bindDatabaseClient(createdClient);
5194
+ return this.#db;
5195
+ }
5196
+ #bindDatabaseClient(client) {
5197
+ return _chunkLWQFXGKScjs.bindNativeStateTransactionContext.call(void 0, client, {
5198
+ enter: async () => await this.#enterStateTransaction(),
5199
+ exit: (scope) => this.#exitStateTransaction(
5200
+ scope
5201
+ )
5202
+ });
5203
+ }
5204
+ async #enterStateTransaction() {
5205
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5206
+ let pendingOwners = actorState.pendingStateTransactionOwners;
5207
+ if (!pendingOwners) {
5208
+ pendingOwners = /* @__PURE__ */ new Set();
5209
+ actorState.pendingStateTransactionOwners = pendingOwners;
5210
+ }
5211
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner || pendingOwners.has(this.#stateTransactionOwner)) {
5212
+ throw stateTransactionConflictError();
5213
+ }
5214
+ pendingOwners.add(this.#stateTransactionOwner);
5215
+ const predecessor = _nullishCoalesce(actorState.stateTransactionTail, () => ( Promise.resolve()));
5216
+ let release;
5217
+ const hold = new Promise((resolve) => {
5218
+ release = resolve;
5219
+ });
5220
+ actorState.stateTransactionTail = predecessor.then(
5221
+ async () => await hold
5222
+ );
5223
+ try {
5224
+ await predecessor;
5225
+ pendingOwners.delete(this.#stateTransactionOwner);
5226
+ actorState.activeStateTransactionOwner = this.#stateTransactionOwner;
5227
+ return {
5228
+ actorContext: this,
5229
+ actorStateBaseline: this.#stateEnabled ? structuredClone(this.#readState()) : void 0,
5230
+ connectionStateBaselines: new Map(
5231
+ callNativeSync(
5232
+ () => this.#runtime.actorConns(this.#ctx)
5233
+ ).map((conn) => [
5234
+ callNativeSync(() => this.#runtime.connId(conn)),
5235
+ new Uint8Array(
5236
+ callNativeSync(() => this.#runtime.connState(conn))
5237
+ )
5238
+ ])
5239
+ ),
5240
+ committed: false,
5241
+ release
5242
+ };
5243
+ } catch (error) {
5244
+ pendingOwners.delete(this.#stateTransactionOwner);
5245
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5246
+ actorState.activeStateTransactionOwner = void 0;
5247
+ }
5248
+ release();
5249
+ throw error;
5250
+ }
5251
+ }
5252
+ #exitStateTransaction(scope) {
5253
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5254
+ try {
5255
+ if (!scope.committed) {
5256
+ this.#restoreStateTransactionBaseline(scope);
5257
+ }
5258
+ } finally {
5259
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5260
+ actorState.activeStateTransactionOwner = void 0;
5261
+ }
5262
+ if (actorState.stateTransactionSaveDeferred) {
5263
+ actorState.stateTransactionSaveDeferred = false;
5264
+ this.#scheduleSave();
5265
+ }
5266
+ scope.release();
5267
+ }
5268
+ }
5269
+ #restoreStateTransactionBaseline(scope) {
5270
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5271
+ if (actorState.pendingSaveHandle !== void 0) {
5272
+ clearImmediate(actorState.pendingSaveHandle);
5273
+ }
5274
+ actorState.pendingSaveHandle = void 0;
5275
+ actorState.saveScheduled = false;
5276
+ if (this.#stateEnabled) {
5277
+ actorState.state = structuredClone(scope.actorStateBaseline);
5278
+ }
5279
+ for (const conn of callNativeSync(
5280
+ () => this.#runtime.actorConns(this.#ctx)
5281
+ )) {
5282
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
5283
+ const baseline = scope.connectionStateBaselines.get(connId);
5284
+ if (baseline === void 0) {
5285
+ continue;
5286
+ }
5287
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
5288
+ const cached = actorState.connStates.get(connId);
5289
+ if (cached) {
5290
+ cached.state = decodeValue(baseline);
5291
+ }
5292
+ }
5293
+ this.#scheduleSave();
4730
5294
  }
4731
5295
  async prepare() {
4732
5296
  if (!this.#databaseProvider) {
@@ -4744,7 +5308,6 @@ var ActorContextHandleAdapter = class {
4744
5308
  }
4745
5309
  async closeDatabase() {
4746
5310
  this.#db = void 0;
4747
- this.#sql = void 0;
4748
5311
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
4749
5312
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
4750
5313
  }
@@ -4764,6 +5327,7 @@ var ActorContextHandleAdapter = class {
4764
5327
  }
4765
5328
  async saveState(opts) {
4766
5329
  if (opts == null ? void 0 : opts.immediate) {
5330
+ this.#assertCanAwaitStateSave();
4767
5331
  await callNative(
4768
5332
  () => this.#runtime.actorRequestSaveAndWait(this.#ctx, {
4769
5333
  immediate: true
@@ -4784,10 +5348,17 @@ var ActorContextHandleAdapter = class {
4784
5348
  );
4785
5349
  }
4786
5350
  async saveStateAndWorkflowBatch(writes) {
5351
+ this.#assertCanAwaitStateSave();
4787
5352
  await callNative(
4788
5353
  () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
4789
5354
  );
4790
5355
  }
5356
+ #assertCanAwaitStateSave() {
5357
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
5358
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
5359
+ throw stateTransactionConflictError();
5360
+ }
5361
+ }
4791
5362
  serializeForTick(reason) {
4792
5363
  void reason;
4793
5364
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -4827,7 +5398,7 @@ var ActorContextHandleAdapter = class {
4827
5398
  const trackedPromise = Promise.resolve(promise).catch((error) => {
4828
5399
  logger2().warn({
4829
5400
  msg: "keepAwake promise rejected",
4830
- error: _chunk2ROUKH7Wcjs.stringifyError.call(void 0, error)
5401
+ error: _chunkGU7ML3KEcjs.stringifyError.call(void 0, error)
4831
5402
  });
4832
5403
  }).then(() => null);
4833
5404
  try {
@@ -4841,10 +5412,6 @@ var ActorContextHandleAdapter = class {
4841
5412
  }
4842
5413
  return promise;
4843
5414
  }
4844
- runHandlerActive() {
4845
- var _a;
4846
- return _nullishCoalesce(((_a = this.#runHandlerActiveProvider) == null ? void 0 : _a.call(this)), () => ( false));
4847
- }
4848
5415
  internalKeepAwake(run) {
4849
5416
  const promise = typeof run === "function" ? run() : run;
4850
5417
  const trackedPromise = promise.then(
@@ -4926,7 +5493,6 @@ var ActorContextHandleAdapter = class {
4926
5493
  var _a;
4927
5494
  this.#flushStateChange();
4928
5495
  (_a = this.#abortSignalCleanup) == null ? void 0 : _a.call(this);
4929
- this.#sql = void 0;
4930
5496
  }
4931
5497
  #createActorAbortSignal() {
4932
5498
  const nativeSignal = callNativeSync(
@@ -4960,10 +5526,18 @@ var ActorContextHandleAdapter = class {
4960
5526
  this.#scheduleSave();
4961
5527
  }
4962
5528
  #assertCanMutateState() {
5529
+ var _a;
4963
5530
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
4964
5531
  if (actorState.isInOnStateChange) {
4965
5532
  throw stateMutationReentrantError();
4966
5533
  }
5534
+ if (actorState.activeStateTransactionOwner !== this.#stateTransactionOwner && (actorState.activeStateTransactionOwner !== void 0 || (_nullishCoalesce(((_a = actorState.pendingStateTransactionOwners) == null ? void 0 : _a.size), () => ( 0))) > 0)) {
5535
+ throw stateTransactionConflictError();
5536
+ }
5537
+ }
5538
+ /** @internal */
5539
+ assertCanMutateState() {
5540
+ this.#assertCanMutateState();
4967
5541
  }
4968
5542
  // Coalesce the request-save and onStateChange work to once per event loop
4969
5543
  // tick. A synchronous burst of mutations (for example
@@ -4985,6 +5559,15 @@ var ActorContextHandleAdapter = class {
4985
5559
  if (!actorState.saveScheduled) {
4986
5560
  return;
4987
5561
  }
5562
+ if (actorState.activeStateTransactionOwner !== void 0) {
5563
+ actorState.saveScheduled = false;
5564
+ if (actorState.pendingSaveHandle !== void 0) {
5565
+ clearImmediate(actorState.pendingSaveHandle);
5566
+ actorState.pendingSaveHandle = void 0;
5567
+ }
5568
+ actorState.stateTransactionSaveDeferred = true;
5569
+ return;
5570
+ }
4988
5571
  actorState.saveScheduled = false;
4989
5572
  if (actorState.pendingSaveHandle !== void 0) {
4990
5573
  clearImmediate(actorState.pendingSaveHandle);
@@ -5108,9 +5691,6 @@ var NativeWorkflowRuntimeAdapter = class {
5108
5691
  }
5109
5692
  };
5110
5693
  }
5111
- isRunHandlerActive() {
5112
- return this.#ctx.runHandlerActive();
5113
- }
5114
5694
  async restartRunHandler() {
5115
5695
  await this.#ctx.restartRunHandler();
5116
5696
  }
@@ -5143,43 +5723,45 @@ var NativeWorkflowRuntimeAdapter = class {
5143
5723
  };
5144
5724
  }
5145
5725
  };
5146
- function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken) {
5147
- return Object.assign(
5148
- new ActorContextHandleAdapter(
5726
+ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
5727
+ const actorContext = new ActorContextHandleAdapter(
5728
+ runtime,
5729
+ ctx,
5730
+ clientFactory,
5731
+ schemas,
5732
+ databaseProvider,
5733
+ request,
5734
+ stateEnabled,
5735
+ onStateChange,
5736
+ dispatchCancelToken,
5737
+ runHandlerConfigured
5738
+ );
5739
+ return Object.assign(actorContext, {
5740
+ conn: new NativeConnAdapter(
5149
5741
  runtime,
5150
- ctx,
5151
- clientFactory,
5742
+ conn,
5152
5743
  schemas,
5153
- databaseProvider,
5154
- request,
5155
- stateEnabled,
5156
- void 0,
5157
- onStateChange,
5158
- dispatchCancelToken
5159
- ),
5160
- {
5161
- conn: new NativeConnAdapter(
5162
- runtime,
5163
- conn,
5164
- schemas,
5165
- ctx,
5166
- (connId) => callNativeSync(
5167
- () => runtime.actorQueueHibernationRemoval(ctx, connId)
5168
- )
5169
- )
5170
- }
5171
- );
5744
+ ctx,
5745
+ (connId) => callNativeSync(
5746
+ () => runtime.actorQueueHibernationRemoval(ctx, connId)
5747
+ ),
5748
+ () => actorContext.assertCanMutateState()
5749
+ )
5750
+ });
5172
5751
  }
5173
5752
  function buildActorConfig(definition, registryConfig, runtimeKind) {
5753
+ var _a;
5174
5754
  const config = definition.config;
5175
5755
  const options = _nullishCoalesce(config.options, () => ( {}));
5176
5756
  const canHibernate = options.canHibernateWebSocket;
5177
5757
  const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
5758
+ const sqliteProfiling = (_a = config.db) == null ? void 0 : _a.sqliteProfiling;
5178
5759
  return {
5179
5760
  name: options.name,
5180
5761
  icon: options.icon,
5181
- hasDatabase: config.db !== void 0 || usesRemoteSqlite,
5762
+ hasDatabase: true,
5182
5763
  remoteSqlite: usesRemoteSqlite,
5764
+ sqliteProfiling,
5183
5765
  enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
5184
5766
  hasState: config.state !== void 0 || typeof config.createState === "function",
5185
5767
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
@@ -5202,7 +5784,7 @@ function buildActorConfig(definition, registryConfig, runtimeKind) {
5202
5784
  maxOutgoingMessageSize: registryConfig.maxOutgoingMessageSize,
5203
5785
  preloadMaxWorkflowBytes: options.preloadMaxWorkflowBytes,
5204
5786
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes,
5205
- actions: Object.keys(_chunkHNHLBM3Ycjs.flattenActionHandlers.call(void 0, config.actions)).sort().map((name) => ({ name })),
5787
+ actions: Object.keys(_chunk4KGXFC6Mcjs.flattenActionHandlers.call(void 0, config.actions)).sort().map((name) => ({ name })),
5206
5788
  inspectorTabs: buildInspectorTabs(config.inspector, runtimeKind)
5207
5789
  };
5208
5790
  }
@@ -5278,10 +5860,10 @@ function validateInspectorTabSource(tabId, resolved) {
5278
5860
  function buildNativeFactory(runtime, registryConfig, definition) {
5279
5861
  var _a;
5280
5862
  const config = definition.config;
5281
- const databaseProvider = config.db;
5282
- const actionHandlers = _chunkHNHLBM3Ycjs.flattenActionHandlers.call(void 0, config.actions);
5863
+ const databaseProvider = _nullishCoalesce(config.db, () => ( _chunkLWQFXGKScjs.db.call(void 0, )));
5864
+ const actionHandlers = _chunk4KGXFC6Mcjs.flattenActionHandlers.call(void 0, config.actions);
5283
5865
  const schemaConfig = {
5284
- actionInputSchemas: _chunkHNHLBM3Ycjs.flattenActionInputSchemas.call(void 0,
5866
+ actionInputSchemas: _chunk4KGXFC6Mcjs.flattenActionInputSchemas.call(void 0,
5285
5867
  config.actions,
5286
5868
  config.actionInputSchemas
5287
5869
  ),
@@ -5289,22 +5871,19 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5289
5871
  events: config.events,
5290
5872
  queues: config.queues
5291
5873
  };
5292
- const createClient = () => _chunkA55CGZIVcjs.createClientWithDriver.call(void 0,
5293
- new (0, _chunkA55CGZIVcjs.RemoteEngineControlClient)(
5294
- _chunkA55CGZIVcjs.convertRegistryConfigToClientConfig.call(void 0, registryConfig)
5874
+ const createClient = () => _chunkRXXDNJXBcjs.createClientWithDriver.call(void 0,
5875
+ new (0, _chunkRXXDNJXBcjs.RemoteEngineControlClient)(
5876
+ _chunkRXXDNJXBcjs.convertRegistryConfigToClientConfig.call(void 0, registryConfig)
5295
5877
  ),
5296
5878
  { encoding: "bare" }
5297
5879
  );
5298
- const nativeRunHandlerActiveByActorId = /* @__PURE__ */ new Map();
5299
- const isNativeRunHandlerActive = (ctx) => _nullishCoalesce(nativeRunHandlerActiveByActorId.get(
5300
- callNativeSync(() => runtime.actorId(ctx))
5301
- ), () => ( false));
5880
+ const run = _chunk4KGXFC6Mcjs.getRunFunction.call(void 0, config.run);
5881
+ const runHandlerCoordinator = _chunk4KGXFC6Mcjs.getRunInspectorKind.call(void 0, config.run) === "workflow" ? new RunHandlerCoordinator(config.run) : void 0;
5302
5882
  const getNativeWorkflowInspector = (ctx) => {
5303
- var _a2;
5304
- return (_a2 = _chunkHNHLBM3Ycjs.getRunInspectorConfig.call(void 0,
5305
- config.run,
5306
- callNativeSync(() => runtime.actorId(ctx))
5307
- )) == null ? void 0 : _a2.workflow;
5883
+ var _a2, _b;
5884
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5885
+ const restart = () => callNativeSync(() => runtime.actorRestartRunHandler(ctx));
5886
+ return _nullishCoalesce(((_a2 = runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.getInspector(actorId, restart)) == null ? void 0 : _a2.workflow), () => ( ((_b = _chunk4KGXFC6Mcjs.getRunInspectorConfig.call(void 0, config.run, actorId)) == null ? void 0 : _b.workflow)));
5308
5887
  };
5309
5888
  const onStateChange = typeof config.onStateChange === "function" ? (actorCtx, nextState) => {
5310
5889
  config.onStateChange(actorCtx, nextState);
@@ -5324,9 +5903,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5324
5903
  databaseProvider,
5325
5904
  request,
5326
5905
  stateEnabled,
5327
- () => isNativeRunHandlerActive(ctx),
5328
5906
  onStateChange,
5329
- cancelToken
5907
+ cancelToken,
5908
+ run !== void 0
5330
5909
  );
5331
5910
  const makeConnCtx = (ctx, conn, request, cancelToken) => withConnContext(
5332
5911
  runtime,
@@ -5338,7 +5917,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5338
5917
  request,
5339
5918
  stateEnabled,
5340
5919
  onStateChange,
5341
- cancelToken
5920
+ cancelToken,
5921
+ run !== void 0
5342
5922
  );
5343
5923
  const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
5344
5924
  var _a2, _b, _c, _d;
@@ -5389,6 +5969,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5389
5969
  return await _asyncNullishCoalesce(await ((_b2 = (_a3 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3)), async () => ( null));
5390
5970
  };
5391
5971
  const actorCtx = makeActorCtx(ctx, jsRequest);
5972
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
5392
5973
  try {
5393
5974
  if (url.pathname === "/inspector/state" && jsRequest.method === "GET") {
5394
5975
  return jsonResponse({
@@ -5474,7 +6055,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5474
6055
  400
5475
6056
  );
5476
6057
  }
5477
- const cbor = _chunk2ROUKH7Wcjs.encodeCborCompat.call(void 0,
6058
+ const cbor = _chunkGU7ML3KEcjs.encodeCborCompat.call(void 0,
5478
6059
  _nullishCoalesce(body.body, () => ( null))
5479
6060
  );
5480
6061
  const message = await runtime.actorQueueSend(ctx, name, cbor);
@@ -5516,9 +6097,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5516
6097
  }
5517
6098
  }
5518
6099
  if (url.pathname === "/inspector/database/schema" && jsRequest.method === "GET") {
5519
- const db = actorCtx.sql;
6100
+ const db2 = sql;
5520
6101
  const tables = queryRows(
5521
- await db.query(
6102
+ await db2.query(
5522
6103
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name"
5523
6104
  )
5524
6105
  );
@@ -5526,13 +6107,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5526
6107
  for (const table of tables) {
5527
6108
  const quoted = `"${table.name.replace(/"/g, '""')}"`;
5528
6109
  const columns = queryRows(
5529
- await db.query(`PRAGMA table_info(${quoted})`)
6110
+ await db2.query(`PRAGMA table_info(${quoted})`)
5530
6111
  );
5531
6112
  const foreignKeys = queryRows(
5532
- await db.query(`PRAGMA foreign_key_list(${quoted})`)
6113
+ await db2.query(`PRAGMA foreign_key_list(${quoted})`)
5533
6114
  );
5534
6115
  const countResult = queryRows(
5535
- await db.query(
6116
+ await db2.query(
5536
6117
  `SELECT COUNT(*) as count FROM ${quoted}`
5537
6118
  )
5538
6119
  );
@@ -5567,7 +6148,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5567
6148
  );
5568
6149
  const quoted = `"${table.replace(/"/g, '""')}"`;
5569
6150
  const rows = queryRows(
5570
- await actorCtx.sql.query(
6151
+ await sql.query(
5571
6152
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
5572
6153
  [
5573
6154
  Math.max(0, Math.min(limit, 500)),
@@ -5595,15 +6176,11 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5595
6176
  const bindings = normalizeSqlitePropertyBindings(
5596
6177
  body.properties
5597
6178
  );
5598
- const rows2 = queryRows(
5599
- await actorCtx.sql.query(body.sql, bindings)
5600
- );
6179
+ const rows2 = queryRows(await sql.query(body.sql, bindings));
5601
6180
  return jsonResponse({ rows: jsonSafe(rows2) });
5602
6181
  }
5603
6182
  const args = Array.isArray(body.args) ? body.args : [];
5604
- const rows = queryRows(
5605
- await actorCtx.sql.query(body.sql, args)
5606
- );
6183
+ const rows = queryRows(await sql.query(body.sql, args));
5607
6184
  return jsonResponse({ rows: jsonSafe(rows) });
5608
6185
  }
5609
6186
  if (url.pathname === "/inspector/summary" && jsRequest.method === "GET") {
@@ -5629,7 +6206,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5629
6206
  rpcs: Object.keys(actionHandlers).sort(),
5630
6207
  queueSize: inspectorSnapshot.queueSize,
5631
6208
  isStateEnabled: stateEnabled,
5632
- isDatabaseEnabled: databaseProvider !== void 0,
6209
+ isDatabaseEnabled: true,
5633
6210
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0,
5634
6211
  workflowState: await workflowState(),
5635
6212
  workflowHistory: workflowHistory()
@@ -5819,6 +6396,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5819
6396
  async (error, payload) => {
5820
6397
  const { ctx } = unwrapTsfnPayload(error, payload);
5821
6398
  const actorCtx = makeActorCtx(ctx);
6399
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
5822
6400
  const saveActorState = async () => {
5823
6401
  if (runtime.kind === "wasm") {
5824
6402
  await runtime.actorSaveState(
@@ -5844,6 +6422,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5844
6422
  saveActorState
5845
6423
  );
5846
6424
  } finally {
6425
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
6426
+ _chunk4KGXFC6Mcjs.disposeRunInspector.call(void 0, config.run, actorId);
5847
6427
  await actorCtx.dispose();
5848
6428
  }
5849
6429
  }
@@ -5853,14 +6433,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5853
6433
  async (error, payload) => {
5854
6434
  const { ctx } = unwrapTsfnPayload(error, payload);
5855
6435
  const actorCtx = makeActorCtx(ctx);
6436
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
6437
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
6438
+ _chunk4KGXFC6Mcjs.disposeRunInspector.call(void 0, config.run, actorId);
5856
6439
  try {
5857
6440
  if (typeof config.onDestroy === "function") {
5858
6441
  await config.onDestroy(actorCtx);
5859
6442
  }
5860
6443
  } finally {
5861
- const actorId = callNativeSync(() => runtime.actorId(ctx));
5862
- nativeRunHandlerActiveByActorId.delete(actorId);
5863
- _chunkHNHLBM3Ycjs.disposeRunInspector.call(void 0, config.run, actorId);
5864
6444
  resolveNativeDestroy(runtime, ctx);
5865
6445
  await actorCtx.closeDatabase();
5866
6446
  clearNativeRuntimeState(runtime, ctx);
@@ -5908,7 +6488,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5908
6488
  ctx,
5909
6489
  connId
5910
6490
  )
5911
- )
6491
+ ),
6492
+ () => actorCtx.assertCanMutateState()
5912
6493
  );
5913
6494
  try {
5914
6495
  const nextConnState = hasStaticConnState ? structuredClone(config.connState) : await config.createConnState(
@@ -5945,7 +6526,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5945
6526
  ctx,
5946
6527
  connId
5947
6528
  )
5948
- )
6529
+ ),
6530
+ () => actorCtx.assertCanMutateState()
5949
6531
  );
5950
6532
  try {
5951
6533
  await config.onConnect(
@@ -5977,7 +6559,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5977
6559
  ctx,
5978
6560
  connId
5979
6561
  )
5980
- )
6562
+ ),
6563
+ () => actorCtx.assertCanMutateState()
5981
6564
  )
5982
6565
  );
5983
6566
  }
@@ -6056,7 +6639,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6056
6639
  new Response(null, { status: 404 })
6057
6640
  );
6058
6641
  }
6059
- const rawConnParams = jsRequest.headers.get(_chunkA55CGZIVcjs.HEADER_CONN_PARAMS);
6642
+ const rawConnParams = jsRequest.headers.get(_chunkRXXDNJXBcjs.HEADER_CONN_PARAMS);
6060
6643
  let requestCtx;
6061
6644
  let conn;
6062
6645
  try {
@@ -6081,7 +6664,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6081
6664
  requestCtx,
6082
6665
  jsRequest
6083
6666
  );
6084
- if (!_chunkA55CGZIVcjs.isResponseLike.call(void 0, response)) {
6667
+ if (!_chunkRXXDNJXBcjs.isResponseLike.call(void 0, response)) {
6085
6668
  throw new Error(
6086
6669
  "onRequest handler must return a Response"
6087
6670
  );
@@ -6121,7 +6704,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6121
6704
  }
6122
6705
  ) : void 0,
6123
6706
  run: (() => {
6124
- const run = _chunkHNHLBM3Ycjs.getRunFunction.call(void 0, config.run);
6125
6707
  if (!run) {
6126
6708
  return void 0;
6127
6709
  }
@@ -6129,26 +6711,38 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6129
6711
  async (error, payload) => {
6130
6712
  const { ctx } = unwrapTsfnPayload(error, payload);
6131
6713
  const actorId = callNativeSync(() => runtime.actorId(ctx));
6132
- const actorCtx = makeActorCtx(ctx);
6133
- nativeRunHandlerActiveByActorId.set(actorId, true);
6134
- try {
6135
- await run(actorCtx);
6136
- } finally {
6137
- nativeRunHandlerActiveByActorId.delete(actorId);
6138
- await actorCtx.dispose();
6714
+ const executeRun = async () => {
6715
+ const actorCtx = makeActorCtx(ctx);
6716
+ try {
6717
+ await run(actorCtx);
6718
+ } finally {
6719
+ await actorCtx.dispose();
6720
+ }
6721
+ };
6722
+ if (runHandlerCoordinator) {
6723
+ const outcome = await runHandlerCoordinator.run(
6724
+ actorId,
6725
+ () => callNativeSync(
6726
+ () => runtime.actorRestartRunHandler(ctx)
6727
+ ),
6728
+ executeRun
6729
+ );
6730
+ return outcome !== "suppressed";
6139
6731
  }
6732
+ await executeRun();
6733
+ return true;
6140
6734
  }
6141
6735
  );
6142
6736
  })(),
6143
- getWorkflowHistory: _chunkHNHLBM3Ycjs.getRunInspectorConfig.call(void 0, config.run) !== void 0 ? wrapNativeCallback(
6737
+ getWorkflowHistory: _chunk4KGXFC6Mcjs.hasRunInspectorConfig.call(void 0, config.run) ? wrapNativeCallback(
6144
6738
  async (error, payload) => {
6145
6739
  var _a2;
6146
6740
  const { ctx } = unwrapTsfnPayload(error, payload);
6147
6741
  const history = (_a2 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a2.getHistory();
6148
- return history == null ? void 0 : _chunk2ROUKH7Wcjs.toUint8Array.call(void 0, history);
6742
+ return history == null ? void 0 : _chunkGU7ML3KEcjs.toUint8Array.call(void 0, history);
6149
6743
  }
6150
6744
  ) : void 0,
6151
- replayWorkflow: _chunkHNHLBM3Ycjs.getRunInspectorConfig.call(void 0, config.run) !== void 0 ? wrapNativeCallback(
6745
+ replayWorkflow: _chunk4KGXFC6Mcjs.hasRunInspectorConfig.call(void 0, config.run) ? wrapNativeCallback(
6152
6746
  async (error, payload) => {
6153
6747
  const { ctx, entryId } = unwrapTsfnPayload(
6154
6748
  error,
@@ -6158,10 +6752,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6158
6752
  if (!(workflowInspector == null ? void 0 : workflowInspector.replayFromStep)) {
6159
6753
  return void 0;
6160
6754
  }
6161
- const history = await _asyncNullishCoalesce(await workflowInspector.replayFromStep(
6162
- entryId
6163
- ), async () => ( null));
6164
- return history == null ? void 0 : _chunk2ROUKH7Wcjs.toUint8Array.call(void 0, history);
6755
+ const history = await _asyncNullishCoalesce(await workflowInspector.replayFromStep(entryId), async () => ( null));
6756
+ return history == null ? void 0 : _chunkGU7ML3KEcjs.toUint8Array.call(void 0, history);
6165
6757
  }
6166
6758
  ) : void 0,
6167
6759
  actions: Object.fromEntries(
@@ -6213,7 +6805,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6213
6805
  jsRequest,
6214
6806
  stateEnabled,
6215
6807
  onStateChange,
6216
- cancelToken
6808
+ cancelToken,
6809
+ run !== void 0
6217
6810
  );
6218
6811
  try {
6219
6812
  if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
@@ -6284,7 +6877,7 @@ async function buildServeConfig(config) {
6284
6877
  poolName: config.envoy.poolName,
6285
6878
  handleInspectorHttpInRuntime: true,
6286
6879
  serverlessBasePath: config.serverless.basePath,
6287
- serverlessPackageVersion: _chunk2ROUKH7Wcjs.VERSION,
6880
+ serverlessPackageVersion: _chunkGU7ML3KEcjs.VERSION,
6288
6881
  serverlessClientEndpoint: config.publicEndpoint,
6289
6882
  serverlessClientNamespace: config.publicNamespace,
6290
6883
  serverlessClientToken: config.publicToken,
@@ -6297,19 +6890,19 @@ async function buildServeConfig(config) {
6297
6890
  } catch (error) {
6298
6891
  logger2().warn({
6299
6892
  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",
6300
- error: _chunk2ROUKH7Wcjs.stringifyError.call(void 0, error)
6893
+ error: _chunkGU7ML3KEcjs.stringifyError.call(void 0, error)
6301
6894
  });
6302
6895
  }
6303
6896
  serveConfig.engineHost = config.engineHost;
6304
6897
  serveConfig.enginePort = config.enginePort;
6305
6898
  if ((_a = config.test) == null ? void 0 : _a.enabled) {
6306
- serveConfig.inspectorTestToken = _nullishCoalesce(_chunk2ROUKH7Wcjs.getEnvUniversal.call(void 0, "_RIVET_TEST_INSPECTOR_TOKEN"), () => ( "token"));
6899
+ serveConfig.inspectorTestToken = _nullishCoalesce(_chunkGU7ML3KEcjs.getEnvUniversal.call(void 0, "_RIVET_TEST_INSPECTOR_TOKEN"), () => ( "token"));
6307
6900
  }
6308
6901
  return serveConfig;
6309
6902
  }
6310
6903
  async function buildRegistryWithRuntime(config, runtime) {
6311
6904
  var _a;
6312
- if (((_a = config.test) == null ? void 0 : _a.enabled) && _chunk2ROUKH7Wcjs.getEnvUniversal.call(void 0, "_RIVET_TEST_INSPECTOR_TOKEN") === void 0) {
6905
+ if (((_a = config.test) == null ? void 0 : _a.enabled) && _chunkGU7ML3KEcjs.getEnvUniversal.call(void 0, "_RIVET_TEST_INSPECTOR_TOKEN") === void 0) {
6313
6906
  trySetProcessEnv("_RIVET_TEST_INSPECTOR_TOKEN", "token");
6314
6907
  }
6315
6908
  if (runtime.kind === "napi") {
@@ -6364,7 +6957,7 @@ function createApplicationFetch(application) {
6364
6957
  body
6365
6958
  })
6366
6959
  );
6367
- if (!_chunkA55CGZIVcjs.isResponseLike.call(void 0, response)) {
6960
+ if (!_chunkRXXDNJXBcjs.isResponseLike.call(void 0, response)) {
6368
6961
  throw new TypeError(
6369
6962
  "registry.listen() application fetch must return a Response"
6370
6963
  );
@@ -6401,7 +6994,7 @@ var Registry = class {
6401
6994
  var _a;
6402
6995
  this.#config = config;
6403
6996
  if ((_a = config.logging) == null ? void 0 : _a.baseLogger) {
6404
- _chunk2ROUKH7Wcjs.configureBaseLogger.call(void 0, config.logging.baseLogger);
6997
+ _chunkGU7ML3KEcjs.configureBaseLogger.call(void 0, config.logging.baseLogger);
6405
6998
  }
6406
6999
  this.#buildConfiguredRegistry = _nullishCoalesce((deps == null ? void 0 : deps.buildConfiguredRegistry), () => ( buildConfiguredRegistry));
6407
7000
  this.routes = {
@@ -6627,11 +7220,11 @@ var Registry = class {
6627
7220
  * ```
6628
7221
  */
6629
7222
  async listen(opts = {}) {
6630
- const port = _nullishCoalesce(_nullishCoalesce(opts.port, () => ( _chunk2ROUKH7Wcjs.parsePortEnv.call(void 0, process.env.RIVET_PORT))), () => ( 3e3));
6631
- const publicDir = _nullishCoalesce(opts.publicDir, () => ( _chunk2ROUKH7Wcjs.getRivetkitPublicDir.call(void 0, )));
7223
+ const port = _nullishCoalesce(_nullishCoalesce(opts.port, () => ( _chunkGU7ML3KEcjs.parsePortEnv.call(void 0, process.env.RIVET_PORT))), () => ( 3e3));
7224
+ const publicDir = _nullishCoalesce(opts.publicDir, () => ( _chunkGU7ML3KEcjs.getRivetkitPublicDir.call(void 0, )));
6632
7225
  const config = this.parseConfig();
6633
7226
  const application = opts.application ? createApplicationFetch(opts.application) : void 0;
6634
- if (application && _chunk2ROUKH7Wcjs.getRivetkitRuntimeMode.call(void 0, ) !== "serverless") {
7227
+ if (application && _chunkGU7ML3KEcjs.getRivetkitRuntimeMode.call(void 0, ) !== "serverless") {
6635
7228
  if (config.runtime === "wasm") {
6636
7229
  throw new Error(
6637
7230
  "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
@@ -6705,7 +7298,7 @@ var Registry = class {
6705
7298
  return jsonRouteResponse(503, {
6706
7299
  status: "not_started",
6707
7300
  runtime: "rivetkit",
6708
- version: _chunk2ROUKH7Wcjs.VERSION
7301
+ version: _chunkGU7ML3KEcjs.VERSION
6709
7302
  });
6710
7303
  }
6711
7304
  const { runtime, registry } = configured;
@@ -6713,7 +7306,7 @@ var Registry = class {
6713
7306
  return jsonRouteResponse(501, {
6714
7307
  status: "unsupported",
6715
7308
  runtime: "rivetkit",
6716
- version: _chunk2ROUKH7Wcjs.VERSION
7309
+ version: _chunkGU7ML3KEcjs.VERSION
6717
7310
  });
6718
7311
  }
6719
7312
  const response = await runtime.registryHealth(registry);
@@ -6960,7 +7553,7 @@ var Registry = class {
6960
7553
  );
6961
7554
  }
6962
7555
  if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
6963
- if (_chunk2ROUKH7Wcjs.getRivetkitRuntimeMode.call(void 0, ) === "serverless") {
7556
+ if (_chunkGU7ML3KEcjs.getRivetkitRuntimeMode.call(void 0, ) === "serverless") {
6964
7557
  return Promise.reject(
6965
7558
  new Error(
6966
7559
  "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request"
@@ -7030,8 +7623,8 @@ var Registry = class {
7030
7623
  * ```
7031
7624
  */
7032
7625
  start() {
7033
- if (_chunk2ROUKH7Wcjs.getRivetkitRuntimeMode.call(void 0, ) === "serverless") {
7034
- const publicDir = _nullishCoalesce(_chunk2ROUKH7Wcjs.getRivetkitPublicDir.call(void 0, ), () => ( "/public"));
7626
+ if (_chunkGU7ML3KEcjs.getRivetkitRuntimeMode.call(void 0, ) === "serverless") {
7627
+ const publicDir = _nullishCoalesce(_chunkGU7ML3KEcjs.getRivetkitPublicDir.call(void 0, ), () => ( "/public"));
7035
7628
  this.listen({ publicDir }).catch((error) => {
7036
7629
  logger2().error({ error }, "auto-listen failed; exiting");
7037
7630
  if (typeof process !== "undefined" && typeof process.exit === "function") {
@@ -7052,7 +7645,7 @@ var Registry = class {
7052
7645
  };
7053
7646
  console.log();
7054
7647
  console.log(
7055
- ` RivetKit ${_chunk2ROUKH7Wcjs.VERSION} (Engine - ${kind === "serverless" ? "Serverless" : "Serverful"})`
7648
+ ` RivetKit ${_chunkGU7ML3KEcjs.VERSION} (Engine - ${kind === "serverless" ? "Serverless" : "Serverful"})`
7056
7649
  );
7057
7650
  if (config.namespace !== "default") {
7058
7651
  logLine("Namespace", config.namespace);
@@ -7127,5 +7720,6 @@ function setup(input) {
7127
7720
 
7128
7721
 
7129
7722
 
7130
- exports.ALLOWED_PUBLIC_HEADERS = _chunkA55CGZIVcjs.ALLOWED_PUBLIC_HEADERS; exports.ActorDefinition = ActorDefinition; exports.ActorError = _chunk4FC7TVS6cjs.RivetError; exports.ActorsSchema = ActorsSchema; exports.DocConfigurePoolSchema = DocConfigurePoolSchema; exports.DocEnvoyConfigSchema = DocEnvoyConfigSchema; exports.DocRegistryConfigSchema = DocRegistryConfigSchema; exports.DocServerlessConfigSchema = DocServerlessConfigSchema; exports.DocSqliteConfigSchema = DocSqliteConfigSchema; exports.InlineWebSocketAdapter = InlineWebSocketAdapter; exports.Registry = Registry; exports.RegistryConfigSchema = RegistryConfigSchema; exports.RivetError = _chunk4FC7TVS6cjs.RivetError; exports.RuntimeKindSchema = RuntimeKindSchema; exports.SqliteBackendSchema = SqliteBackendSchema; exports.SqliteConfigSchema = SqliteConfigSchema; exports.TestConfigSchema = TestConfigSchema; exports.UserError = _chunk4FC7TVS6cjs.UserError; exports.WasmRuntimeConfigSchema = WasmRuntimeConfigSchema; exports.actor = actor; exports.buildActorNames = buildActorNames; exports.createClientWithDriver = _chunkA55CGZIVcjs.createClientWithDriver; exports.event = event; exports.isStaticActorDefinition = isStaticActorDefinition; exports.isStaticActorInstance = isStaticActorInstance; exports.lookupInRegistry = lookupInRegistry; exports.noopNext = _chunk2ROUKH7Wcjs.noopNext; exports.queue = queue; exports.setup = setup; exports.toUint8Array = _chunk2ROUKH7Wcjs.toUint8Array;
7723
+
7724
+ exports.ALLOWED_PUBLIC_HEADERS = _chunkRXXDNJXBcjs.ALLOWED_PUBLIC_HEADERS; exports.ActorDefinition = ActorDefinition; exports.ActorError = _chunk4FC7TVS6cjs.RivetError; exports.ActorsSchema = ActorsSchema; exports.DocConfigurePoolSchema = DocConfigurePoolSchema; exports.DocEnvoyConfigSchema = DocEnvoyConfigSchema; exports.DocRegistryConfigSchema = DocRegistryConfigSchema; exports.DocServerlessConfigSchema = DocServerlessConfigSchema; exports.DocSqliteConfigSchema = DocSqliteConfigSchema; exports.InlineWebSocketAdapter = InlineWebSocketAdapter; exports.Registry = Registry; exports.RegistryConfigSchema = RegistryConfigSchema; exports.RivetError = _chunk4FC7TVS6cjs.RivetError; exports.RuntimeKindSchema = RuntimeKindSchema; exports.SqliteBackendSchema = SqliteBackendSchema; exports.SqliteConfigSchema = SqliteConfigSchema; exports.TestConfigSchema = TestConfigSchema; exports.UserError = _chunk4FC7TVS6cjs.UserError; exports.WasmRuntimeConfigSchema = WasmRuntimeConfigSchema; exports.actor = actor; exports.buildActorNames = buildActorNames; exports.createClientWithDriver = _chunkRXXDNJXBcjs.createClientWithDriver; exports.defineRunHandler = _chunk4KGXFC6Mcjs.defineRunHandler; exports.event = event; exports.isStaticActorDefinition = isStaticActorDefinition; exports.isStaticActorInstance = isStaticActorInstance; exports.lookupInRegistry = lookupInRegistry; exports.noopNext = _chunkGU7ML3KEcjs.noopNext; exports.queue = queue; exports.setup = setup; exports.toUint8Array = _chunkGU7ML3KEcjs.toUint8Array;
7131
7725
  //# sourceMappingURL=mod.cjs.map