rivetkit 2.3.0-rc.10 → 2.3.0-rc.12

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 (205) hide show
  1. package/dist/browser/client.d.ts +448 -62
  2. package/dist/browser/client.js +131 -89
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +40 -20
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/actor/errors.cjs +2 -2
  7. package/dist/tsup/actor/errors.js +1 -1
  8. package/dist/tsup/agent-os/index.cjs +2103 -2090
  9. package/dist/tsup/agent-os/index.cjs.map +1 -1
  10. package/dist/tsup/agent-os/index.d.cts +446 -69
  11. package/dist/tsup/agent-os/index.d.ts +446 -69
  12. package/dist/tsup/agent-os/index.js +2102 -2089
  13. package/dist/tsup/agent-os/index.js.map +1 -1
  14. package/dist/tsup/{chunk-TE4VCDNY.cjs → chunk-2U6RLFKX.cjs} +219 -234
  15. package/dist/tsup/chunk-2U6RLFKX.cjs.map +1 -0
  16. package/dist/tsup/{chunk-4K3MV2MW.cjs → chunk-2ZTBRZRS.cjs} +10 -10
  17. package/dist/tsup/chunk-2ZTBRZRS.cjs.map +1 -0
  18. package/dist/tsup/{chunk-KU6VKVEK.js → chunk-3EVVOYFD.js} +19 -7
  19. package/dist/tsup/chunk-3EVVOYFD.js.map +1 -0
  20. package/dist/tsup/{chunk-3LGP4JSO.cjs → chunk-6KTMKPNU.cjs} +8 -8
  21. package/dist/tsup/{chunk-3LGP4JSO.cjs.map → chunk-6KTMKPNU.cjs.map} +1 -1
  22. package/dist/tsup/{chunk-WU2O2KIE.js → chunk-7UZF56RS.js} +63 -78
  23. package/dist/tsup/chunk-7UZF56RS.js.map +1 -0
  24. package/dist/tsup/{chunk-KIWH5H3K.js → chunk-BRP62GZC.js} +3 -3
  25. package/dist/tsup/chunk-BRP62GZC.js.map +1 -0
  26. package/dist/tsup/{chunk-G5RULGYQ.cjs → chunk-C7AAIILH.cjs} +24 -9
  27. package/dist/tsup/chunk-C7AAIILH.cjs.map +1 -0
  28. package/dist/tsup/{chunk-XV52XUWU.js → chunk-EWVOWEMD.js} +4 -4
  29. package/dist/tsup/chunk-EWVOWEMD.js.map +1 -0
  30. package/dist/tsup/{chunk-3YY5S6TV.js → chunk-HXUEHHJF.js} +2 -2
  31. package/dist/tsup/chunk-HXUEHHJF.js.map +1 -0
  32. package/dist/tsup/{chunk-PCBNKI2J.js → chunk-JZ7TWV65.js} +1 -1
  33. package/dist/tsup/chunk-JZ7TWV65.js.map +1 -0
  34. package/dist/tsup/{chunk-QAZLM4WT.cjs → chunk-KORQB2IR.cjs} +3 -3
  35. package/dist/tsup/{chunk-QAZLM4WT.cjs.map → chunk-KORQB2IR.cjs.map} +1 -1
  36. package/dist/tsup/{chunk-CMYS77J6.js → chunk-OLIJHKLL.js} +3 -3
  37. package/dist/tsup/{chunk-BM3EOY7M.js → chunk-OOB32JVG.js} +134 -20
  38. package/dist/tsup/chunk-OOB32JVG.js.map +1 -0
  39. package/dist/tsup/{chunk-G34LIR7S.js → chunk-QKSGGKGQ.js} +22 -7
  40. package/dist/tsup/chunk-QKSGGKGQ.js.map +1 -0
  41. package/dist/tsup/{chunk-PWFGP2US.cjs → chunk-SS56HFM2.cjs} +138 -24
  42. package/dist/tsup/chunk-SS56HFM2.cjs.map +1 -0
  43. package/dist/tsup/{chunk-Z4C3W2CQ.cjs → chunk-UETC5RF7.cjs} +3 -3
  44. package/dist/tsup/{chunk-Z4C3W2CQ.cjs.map → chunk-UETC5RF7.cjs.map} +1 -1
  45. package/dist/tsup/{chunk-LD5YASJU.cjs → chunk-VE2X4KMG.cjs} +2 -2
  46. package/dist/tsup/{chunk-LD5YASJU.cjs.map → chunk-VE2X4KMG.cjs.map} +1 -1
  47. package/dist/tsup/{chunk-6BI2MS3S.js → chunk-VLXRFJ7P.js} +2 -2
  48. package/dist/tsup/{chunk-J5P6S2LC.cjs → chunk-VNMIAPPF.cjs} +26 -14
  49. package/dist/tsup/chunk-VNMIAPPF.cjs.map +1 -0
  50. package/dist/tsup/{chunk-WQ4HNA4W.cjs → chunk-WHYBAEWG.cjs} +4 -2
  51. package/dist/tsup/chunk-WHYBAEWG.cjs.map +1 -0
  52. package/dist/tsup/{chunk-T6YVRM4K.js → chunk-WIMUFZVJ.js} +3 -1
  53. package/dist/tsup/chunk-WIMUFZVJ.js.map +1 -0
  54. package/dist/tsup/{chunk-2NDZ7JCR.cjs → chunk-ZA7FLHKH.cjs} +1 -1
  55. package/dist/tsup/chunk-ZA7FLHKH.cjs.map +1 -0
  56. package/dist/tsup/client/mod.cjs +9 -9
  57. package/dist/tsup/client/mod.d.cts +4 -4
  58. package/dist/tsup/client/mod.d.ts +4 -4
  59. package/dist/tsup/client/mod.js +8 -8
  60. package/dist/tsup/common/log.cjs +3 -3
  61. package/dist/tsup/common/log.js +2 -2
  62. package/dist/tsup/common/websocket.cjs +4 -4
  63. package/dist/tsup/common/websocket.js +3 -3
  64. package/dist/tsup/{config-Ca8dN4cS.d.cts → config-BtAh7oBu.d.cts} +409 -22
  65. package/dist/tsup/{config-CxjGYf4K.d.cts → config-D49x8NpL.d.cts} +1 -2
  66. package/dist/tsup/{config-CxjGYf4K.d.ts → config-D49x8NpL.d.ts} +1 -2
  67. package/dist/tsup/{config-0Ta55UV0.d.ts → config-DKgPGC0f.d.ts} +409 -22
  68. package/dist/tsup/{context-B_IWbWne.d.ts → context-C-6dGebY.d.ts} +8 -8
  69. package/dist/tsup/{context-CUrQ9MHc.d.cts → context-Cfjl5pgz.d.cts} +8 -8
  70. package/dist/tsup/db/drizzle.cjs +3 -3
  71. package/dist/tsup/db/drizzle.d.cts +1 -1
  72. package/dist/tsup/db/drizzle.d.ts +1 -1
  73. package/dist/tsup/db/drizzle.js +1 -1
  74. package/dist/tsup/db/mod.cjs +2 -2
  75. package/dist/tsup/db/mod.d.cts +2 -2
  76. package/dist/tsup/db/mod.d.ts +2 -2
  77. package/dist/tsup/db/mod.js +1 -1
  78. package/dist/tsup/dynamic/mod.cjs +24 -0
  79. package/dist/tsup/dynamic/mod.cjs.map +1 -0
  80. package/dist/tsup/dynamic/mod.d.cts +37 -0
  81. package/dist/tsup/dynamic/mod.d.ts +37 -0
  82. package/dist/tsup/dynamic/mod.js +24 -0
  83. package/dist/tsup/dynamic/mod.js.map +1 -0
  84. package/dist/tsup/inspector/mod.cjs +6 -6
  85. package/dist/tsup/inspector/mod.js +5 -5
  86. package/dist/tsup/mod.cjs +606 -325
  87. package/dist/tsup/mod.cjs.map +1 -1
  88. package/dist/tsup/mod.d.cts +4 -4
  89. package/dist/tsup/mod.d.ts +4 -4
  90. package/dist/tsup/mod.js +510 -229
  91. package/dist/tsup/mod.js.map +1 -1
  92. package/dist/tsup/test/mod.cjs +21 -18
  93. package/dist/tsup/test/mod.cjs.map +1 -1
  94. package/dist/tsup/test/mod.d.cts +3 -3
  95. package/dist/tsup/test/mod.d.ts +3 -3
  96. package/dist/tsup/test/mod.js +18 -15
  97. package/dist/tsup/test/mod.js.map +1 -1
  98. package/dist/tsup/utils.cjs +3 -3
  99. package/dist/tsup/utils.d.cts +1 -1
  100. package/dist/tsup/utils.d.ts +1 -1
  101. package/dist/tsup/utils.js +2 -2
  102. package/dist/tsup/workflow/mod.cjs +307 -282
  103. package/dist/tsup/workflow/mod.cjs.map +1 -1
  104. package/dist/tsup/workflow/mod.d.cts +5 -5
  105. package/dist/tsup/workflow/mod.d.ts +5 -5
  106. package/dist/tsup/workflow/mod.js +501 -476
  107. package/dist/tsup/workflow/mod.js.map +1 -1
  108. package/package.json +22 -11
  109. package/src/actor/config.ts +68 -51
  110. package/src/actor/contexts/index.ts +7 -2
  111. package/src/actor/definition.ts +17 -19
  112. package/src/actor/driver.ts +3 -3
  113. package/src/actor/errors.ts +9 -3
  114. package/src/actor/instance/mod.ts +22 -30
  115. package/src/actor/keys.ts +1 -1
  116. package/src/actor/mod.ts +20 -20
  117. package/src/actor/schema.ts +2 -2
  118. package/src/agent-os/actor/index.ts +38 -18
  119. package/src/agent-os/actor/preview.ts +1 -2
  120. package/src/agent-os/actor/session.ts +2 -2
  121. package/src/agent-os/config.ts +1 -1
  122. package/src/agent-os/fs/database-vfs.ts +1 -1
  123. package/src/agent-os/index.ts +16 -15
  124. package/src/client/actor-common.ts +87 -54
  125. package/src/client/actor-conn.ts +8 -36
  126. package/src/client/actor-handle.ts +69 -51
  127. package/src/client/actor-query.ts +5 -5
  128. package/src/client/errors.ts +1 -1
  129. package/src/client/lifecycle-errors.ts +2 -4
  130. package/src/client/query.ts +1 -1
  131. package/src/client/queue.ts +8 -3
  132. package/src/client/raw-utils.ts +8 -6
  133. package/src/client/resolve-gateway-target.ts +1 -1
  134. package/src/client/utils.ts +2 -7
  135. package/src/common/actor-websocket.ts +3 -1
  136. package/src/common/bare/actor-persist/v1.ts +205 -163
  137. package/src/common/bare/actor-persist/v2.ts +265 -213
  138. package/src/common/bare/actor-persist/v3.ts +176 -172
  139. package/src/common/bare/actor-persist/v4.ts +254 -253
  140. package/src/common/bare/transport/v1.ts +659 -543
  141. package/src/common/client-protocol-versioned.ts +66 -64
  142. package/src/common/database/config.ts +2 -8
  143. package/src/common/database/native-database.ts +1 -1
  144. package/src/common/database/shared.ts +1 -0
  145. package/src/common/encoding.ts +250 -16
  146. package/src/common/eventsource.ts +1 -1
  147. package/src/common/inline-websocket-adapter.ts +14 -13
  148. package/src/common/log.ts +1 -0
  149. package/src/common/router.ts +13 -17
  150. package/src/common/utils.ts +1 -150
  151. package/src/common/websocket-interface.ts +1 -1
  152. package/src/db/mod.ts +1 -1
  153. package/src/drivers/engine/actor-driver.ts +58 -56
  154. package/src/dynamic/instance.ts +32 -0
  155. package/src/dynamic/internal.ts +50 -0
  156. package/src/dynamic/isolate-runtime.ts +66 -0
  157. package/src/dynamic/mod.ts +32 -0
  158. package/src/engine-client/actor-http-client.ts +1 -1
  159. package/src/engine-client/actor-websocket-client.ts +6 -5
  160. package/src/engine-client/api-endpoints.ts +51 -2
  161. package/src/engine-client/api-utils.ts +2 -2
  162. package/src/engine-client/driver.ts +1 -1
  163. package/src/engine-client/mod.ts +6 -3
  164. package/src/engine-client/ws-proxy.ts +4 -4
  165. package/src/inspector/client.browser.ts +5 -11
  166. package/src/inspector/mod.ts +1 -3
  167. package/src/registry/config/envoy.ts +1 -2
  168. package/src/registry/config/index.ts +3 -9
  169. package/src/registry/index.ts +150 -72
  170. package/src/registry/napi-runtime.ts +13 -2
  171. package/src/registry/native-validation.ts +10 -12
  172. package/src/registry/native.ts +231 -173
  173. package/src/registry/process-metrics.ts +250 -0
  174. package/src/registry/runtime.ts +4 -0
  175. package/src/registry/wasm-runtime.ts +18 -2
  176. package/src/registry/write-through-proxy.ts +40 -0
  177. package/src/serde.ts +2 -2
  178. package/src/serverless/configure.ts +18 -7
  179. package/src/test/mod.ts +11 -8
  180. package/src/utils/endpoint-parser.ts +1 -1
  181. package/src/utils/router.ts +1 -1
  182. package/src/utils/serve.ts +4 -5
  183. package/src/utils.ts +1 -2
  184. package/src/workflow/context.ts +61 -33
  185. package/src/workflow/driver.ts +4 -6
  186. package/src/workflow/inspector.ts +4 -3
  187. package/src/workflow/mod.ts +15 -17
  188. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +0 -1
  189. package/dist/tsup/chunk-3YY5S6TV.js.map +0 -1
  190. package/dist/tsup/chunk-4K3MV2MW.cjs.map +0 -1
  191. package/dist/tsup/chunk-BM3EOY7M.js.map +0 -1
  192. package/dist/tsup/chunk-G34LIR7S.js.map +0 -1
  193. package/dist/tsup/chunk-G5RULGYQ.cjs.map +0 -1
  194. package/dist/tsup/chunk-J5P6S2LC.cjs.map +0 -1
  195. package/dist/tsup/chunk-KIWH5H3K.js.map +0 -1
  196. package/dist/tsup/chunk-KU6VKVEK.js.map +0 -1
  197. package/dist/tsup/chunk-PCBNKI2J.js.map +0 -1
  198. package/dist/tsup/chunk-PWFGP2US.cjs.map +0 -1
  199. package/dist/tsup/chunk-T6YVRM4K.js.map +0 -1
  200. package/dist/tsup/chunk-TE4VCDNY.cjs.map +0 -1
  201. package/dist/tsup/chunk-WQ4HNA4W.cjs.map +0 -1
  202. package/dist/tsup/chunk-WU2O2KIE.js.map +0 -1
  203. package/dist/tsup/chunk-XV52XUWU.js.map +0 -1
  204. /package/dist/tsup/{chunk-CMYS77J6.js.map → chunk-OLIJHKLL.js.map} +0 -0
  205. /package/dist/tsup/{chunk-6BI2MS3S.js.map → chunk-VLXRFJ7P.js.map} +0 -0
package/dist/tsup/mod.js CHANGED
@@ -2,13 +2,14 @@ import {
2
2
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
3
3
  ActorConfigSchema,
4
4
  CONN_STATE_MANAGER_SYMBOL,
5
+ RAW_STATE_SYMBOL,
5
6
  getRunFunction,
6
7
  getRunInspectorConfig,
7
8
  getRunMetadata
8
- } from "./chunk-T6YVRM4K.js";
9
+ } from "./chunk-WIMUFZVJ.js";
9
10
  import {
10
11
  decodeWorkflowHistoryTransport
11
- } from "./chunk-G34LIR7S.js";
12
+ } from "./chunk-QKSGGKGQ.js";
12
13
  import {
13
14
  ALLOWED_PUBLIC_HEADERS,
14
15
  HEADER_CONN_PARAMS,
@@ -18,7 +19,7 @@ import {
18
19
  getDatacenters,
19
20
  tryParseEndpoint,
20
21
  updateRunnerConfig
21
- } from "./chunk-WU2O2KIE.js";
22
+ } from "./chunk-7UZF56RS.js";
22
23
  import {
23
24
  KEYS,
24
25
  makePrefixedKey,
@@ -26,18 +27,19 @@ import {
26
27
  queueMetadataKey,
27
28
  removePrefixFromKey,
28
29
  workflowStoragePrefix
29
- } from "./chunk-3YY5S6TV.js";
30
+ } from "./chunk-HXUEHHJF.js";
30
31
  import {
32
+ assertJsonCompatValue,
31
33
  decodeCborCompat,
32
- decodeCborJsonCompat,
33
34
  encodeCborCompat
34
- } from "./chunk-BM3EOY7M.js";
35
- import "./chunk-PCBNKI2J.js";
36
- import "./chunk-6BI2MS3S.js";
35
+ } from "./chunk-OOB32JVG.js";
36
+ import "./chunk-JZ7TWV65.js";
37
+ import "./chunk-VLXRFJ7P.js";
37
38
  import {
38
39
  LogLevelSchema,
39
40
  VERSION,
40
41
  deconstructError,
42
+ detectRuntime,
41
43
  getEnvUniversal,
42
44
  getLogger,
43
45
  getNodeEnv,
@@ -57,7 +59,7 @@ import {
57
59
  noopNext,
58
60
  stringifyError,
59
61
  toUint8Array
60
- } from "./chunk-KU6VKVEK.js";
62
+ } from "./chunk-3EVVOYFD.js";
61
63
  import {
62
64
  INTERNAL_ERROR_CODE,
63
65
  RivetError,
@@ -68,7 +70,7 @@ import {
68
70
  isRivetErrorLike,
69
71
  toRivetError,
70
72
  unsupportedFeature
71
- } from "./chunk-KIWH5H3K.js";
73
+ } from "./chunk-BRP62GZC.js";
72
74
 
73
75
  // src/actor/log.ts
74
76
  function loggerWithoutContext() {
@@ -140,7 +142,7 @@ function hasSchemaConfigKey(schemas, key) {
140
142
  if (!schemas) {
141
143
  return false;
142
144
  }
143
- return Object.prototype.hasOwnProperty.call(schemas, key);
145
+ return Object.hasOwn(schemas, key);
144
146
  }
145
147
  function getEventCanSubscribe(schemas, key) {
146
148
  const schema = schemas == null ? void 0 : schemas[key];
@@ -201,8 +203,8 @@ function validateSchemaSync(schemas, key, data) {
201
203
  }
202
204
 
203
205
  // src/common/inline-websocket-adapter.ts
204
- import { WSContext } from "hono/ws";
205
206
  import { VirtualWebSocket } from "@rivetkit/virtual-websocket";
207
+ import { WSContext } from "hono/ws";
206
208
  function logger() {
207
209
  return getLogger("inline-websocket-adapter");
208
210
  }
@@ -314,24 +316,24 @@ var InlineWebSocketAdapter = class {
314
316
  this.#close(1011, "Internal error during initialization");
315
317
  }
316
318
  }
317
- #handleError(err) {
318
- console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", err);
319
+ #handleError(error) {
320
+ console.error("INLINE_WEBSOCKET_ADAPTER_ERROR", error);
319
321
  logger().error({
320
322
  msg: "error in websocket",
321
- error: err,
322
- errorMessage: err instanceof Error ? err.message : String(err),
323
- stack: err instanceof Error ? err.stack : void 0
323
+ error,
324
+ errorMessage: error instanceof Error ? error.message : String(error),
325
+ stack: error instanceof Error ? error.stack : void 0
324
326
  });
325
327
  try {
326
- this.#handler.onError(err, this.#wsContext);
327
- } catch (handlerErr) {
328
+ this.#handler.onError(error, this.#wsContext);
329
+ } catch (error2) {
328
330
  logger().error({
329
331
  msg: "error in onError handler",
330
- error: handlerErr
332
+ error: error2
331
333
  });
332
334
  }
333
- this.#clientWs.triggerError(err);
334
- this.#actorWs.triggerError(err);
335
+ this.#clientWs.triggerError(error);
336
+ this.#actorWs.triggerError(error);
335
337
  }
336
338
  #close(code, reason) {
337
339
  if (this.#readyState === 3 || this.#readyState === 2) {
@@ -344,8 +346,8 @@ var InlineWebSocketAdapter = class {
344
346
  { code, reason, wasClean: true },
345
347
  this.#wsContext
346
348
  );
347
- } catch (err) {
348
- logger().error({ msg: "error closing websocket", error: err });
349
+ } catch (error) {
350
+ logger().error({ msg: "error closing websocket", error });
349
351
  } finally {
350
352
  this.#readyState = 3;
351
353
  this.#clientWs.triggerClose(code, reason);
@@ -354,6 +356,9 @@ var InlineWebSocketAdapter = class {
354
356
  }
355
357
  };
356
358
 
359
+ // src/registry/index.ts
360
+ import { Hono } from "hono";
361
+
357
362
  // src/common/engine.ts
358
363
  var ENGINE_PORT = 6420;
359
364
  var ENGINE_ENDPOINT = `http://127.0.0.1:${ENGINE_PORT}`;
@@ -371,10 +376,13 @@ function sleep(ms) {
371
376
  }
372
377
  function configureTimeoutMs() {
373
378
  const value = process.env.RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS;
374
- if (value === void 0 || value === "") return DEFAULT_CONFIGURE_TIMEOUT_MS;
379
+ if (value === void 0 || value === "")
380
+ return DEFAULT_CONFIGURE_TIMEOUT_MS;
375
381
  const parsed = Number(value);
376
382
  if (!Number.isFinite(parsed) || parsed < 0) {
377
- throw new Error("RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number");
383
+ throw new Error(
384
+ "RIVET_SERVERLESS_CONFIGURE_TIMEOUT_MS must be a finite non-negative number"
385
+ );
378
386
  }
379
387
  return parsed;
380
388
  }
@@ -388,13 +396,19 @@ async function configureServerlessPool(config) {
388
396
  attempts += 1;
389
397
  try {
390
398
  if (!config.namespace) {
391
- throw new Error("namespace is required for serverless configuration");
399
+ throw new Error(
400
+ "namespace is required for serverless configuration"
401
+ );
392
402
  }
393
403
  if (!config.endpoint) {
394
- throw new Error("endpoint is required for serverless configuration");
404
+ throw new Error(
405
+ "endpoint is required for serverless configuration"
406
+ );
395
407
  }
396
408
  if (!config.configurePool) {
397
- throw new Error("configurePool is required for serverless configuration");
409
+ throw new Error(
410
+ "configurePool is required for serverless configuration"
411
+ );
398
412
  }
399
413
  const customConfig = config.configurePool;
400
414
  const clientConfig = convertRegistryConfigToClientConfig(config);
@@ -450,6 +464,145 @@ async function configureServerlessPool(config) {
450
464
  throw lastError;
451
465
  }
452
466
 
467
+ // src/utils/serve.ts
468
+ import getPort from "get-port";
469
+ var serveStaticLoaderPromises = {};
470
+ async function crossPlatformServe(config, httpPort, app, runtime = detectRuntime()) {
471
+ logger2().debug({ msg: "detected runtime for serve", runtime });
472
+ switch (runtime) {
473
+ case "deno":
474
+ return serveDeno(config, httpPort, app);
475
+ case "bun":
476
+ return serveBun(config, httpPort, app);
477
+ case "node":
478
+ return serveNode(config, httpPort, app);
479
+ default:
480
+ return serveNode(config, httpPort, app);
481
+ }
482
+ }
483
+ async function loadRuntimeServeStatic(runtime) {
484
+ if (!serveStaticLoaderPromises[runtime]) {
485
+ if (runtime === "node") {
486
+ const nodeServeStaticModule = "@hono/node-server/serve-static";
487
+ serveStaticLoaderPromises[runtime] = import(
488
+ /* webpackIgnore: true */
489
+ nodeServeStaticModule
490
+ ).then((x) => x.serveStatic);
491
+ } else if (runtime === "bun") {
492
+ const bunModule = "hono/bun";
493
+ serveStaticLoaderPromises[runtime] = import(
494
+ /* webpackIgnore: true */
495
+ bunModule
496
+ ).then((x) => x.serveStatic);
497
+ } else if (runtime === "deno") {
498
+ const denoModule = "hono/deno";
499
+ serveStaticLoaderPromises[runtime] = import(
500
+ /* webpackIgnore: true */
501
+ denoModule
502
+ ).then((x) => x.serveStatic);
503
+ } else {
504
+ throw new Error(`unsupported runtime: ${runtime}`);
505
+ }
506
+ }
507
+ return await serveStaticLoaderPromises[runtime];
508
+ }
509
+ async function serveNode(config, httpPort, app) {
510
+ const nodeServerModule = "@hono/node-server";
511
+ let serve;
512
+ try {
513
+ const dep = await import(
514
+ /* webpackIgnore: true */
515
+ nodeServerModule
516
+ );
517
+ serve = dep.serve;
518
+ } catch (err) {
519
+ logger2().error({
520
+ msg: "failed to import @hono/node-server. please run 'npm install @hono/node-server @hono/node-ws'",
521
+ error: stringifyError(err)
522
+ });
523
+ process.exit(1);
524
+ }
525
+ const nodeWsModule = "@hono/node-ws";
526
+ let createNodeWebSocket;
527
+ try {
528
+ const dep = await import(
529
+ /* webpackIgnore: true */
530
+ nodeWsModule
531
+ );
532
+ createNodeWebSocket = dep.createNodeWebSocket;
533
+ } catch (err) {
534
+ logger2().error({
535
+ msg: "failed to import @hono/node-ws. please run 'npm install @hono/node-server @hono/node-ws'",
536
+ error: stringifyError(err)
537
+ });
538
+ process.exit(1);
539
+ }
540
+ const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({
541
+ app
542
+ });
543
+ const port = httpPort;
544
+ const hostname = config.httpHost;
545
+ const server = serve(
546
+ { fetch: app.fetch, port, hostname },
547
+ () => logger2().info({ msg: "server listening", port, hostname })
548
+ );
549
+ injectWebSocket(server);
550
+ const closeServer = () => {
551
+ server.close();
552
+ };
553
+ return { upgradeWebSocket, closeServer };
554
+ }
555
+ async function serveDeno(config, httpPort, app) {
556
+ const honoDenoModule = "hono/deno";
557
+ let upgradeWebSocket;
558
+ try {
559
+ const dep = await import(
560
+ /* webpackIgnore: true */
561
+ honoDenoModule
562
+ );
563
+ upgradeWebSocket = dep.upgradeWebSocket;
564
+ } catch (err) {
565
+ logger2().error({
566
+ msg: "failed to import hono/deno",
567
+ error: stringifyError(err)
568
+ });
569
+ process.exit(1);
570
+ }
571
+ const port = httpPort;
572
+ const hostname = config.httpHost;
573
+ Deno.serve({ port, hostname }, app.fetch);
574
+ logger2().info({ msg: "server listening", port, hostname });
575
+ return { upgradeWebSocket };
576
+ }
577
+ async function serveBun(config, httpPort, app) {
578
+ const honoBunModule = "hono/bun";
579
+ let createBunWebSocket;
580
+ try {
581
+ const dep = await import(
582
+ /* webpackIgnore: true */
583
+ honoBunModule
584
+ );
585
+ createBunWebSocket = dep.createBunWebSocket;
586
+ } catch (err) {
587
+ logger2().error({
588
+ msg: "failed to import hono/bun",
589
+ error: stringifyError(err)
590
+ });
591
+ process.exit(1);
592
+ }
593
+ const { websocket, upgradeWebSocket } = createBunWebSocket();
594
+ const port = httpPort;
595
+ const hostname = config.httpHost;
596
+ Bun.serve({
597
+ fetch: app.fetch,
598
+ port,
599
+ hostname,
600
+ websocket
601
+ });
602
+ logger2().info({ msg: "server listening", port, hostname });
603
+ return { upgradeWebSocket };
604
+ }
605
+
453
606
  // src/registry/config/index.ts
454
607
  import { z as z3 } from "zod";
455
608
 
@@ -703,7 +856,7 @@ var RegistryConfigSchema = z3.object({
703
856
  * after calling `CoreRegistry::shutdown()`. Defaults to the
704
857
  * engine-provided actor stop threshold once the envoy connects.
705
858
  *
706
- * Must be >= rivetkit-core's drain timeout (20s) + margin.
859
+ * Must be long enough for rivetkit-core to drain the envoy.
707
860
  */
708
861
  gracePeriodMs: z3.number().int().min(1e3).optional(),
709
862
  /**
@@ -1424,6 +1577,9 @@ var NapiCoreRuntime = class {
1424
1577
  async actorWaitForTrackedShutdownWork(ctx) {
1425
1578
  return await asNativeActorContext(ctx).waitForTrackedShutdownWork();
1426
1579
  }
1580
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
1581
+ await asNativeActorContext(ctx).waitForTrackedShutdownWorkUnbounded();
1582
+ }
1427
1583
  actorKeepAwake(ctx, promise) {
1428
1584
  asNativeActorContext(ctx).keepAwake(promise);
1429
1585
  }
@@ -1535,8 +1691,12 @@ var NapiCoreRuntime = class {
1535
1691
  )
1536
1692
  );
1537
1693
  }
1538
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
1539
- await asNativeActorContext(ctx).queue().waitForNamesAvailable(names, options);
1694
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
1695
+ await asNativeActorContext(ctx).queue().waitForNamesAvailable(
1696
+ names,
1697
+ options,
1698
+ signal ? asNativeCancellationToken(signal) : signal
1699
+ );
1540
1700
  }
1541
1701
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
1542
1702
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
@@ -1670,20 +1830,18 @@ function validateQueueComplete(schemas, name, response) {
1670
1830
  response
1671
1831
  );
1672
1832
  if (!result.success) {
1673
- throw validationError(`queue \`${name}\` completion response`, result.issues);
1833
+ throw validationError(
1834
+ `queue \`${name}\` completion response`,
1835
+ result.issues
1836
+ );
1674
1837
  }
1675
1838
  return result.data;
1676
1839
  }
1677
1840
  function validationError(target, issues) {
1678
- return new RivetError(
1679
- "actor",
1680
- "validation_error",
1681
- `Invalid ${target}`,
1682
- {
1683
- public: true,
1684
- metadata: { issues }
1685
- }
1686
- );
1841
+ return new RivetError("actor", "validation_error", `Invalid ${target}`, {
1842
+ public: true,
1843
+ metadata: { issues }
1844
+ });
1687
1845
  }
1688
1846
 
1689
1847
  // src/registry/wasm-runtime.ts
@@ -2007,6 +2165,12 @@ var WasmCoreRuntime = class {
2007
2165
  "waitForTrackedShutdownWork"
2008
2166
  );
2009
2167
  }
2168
+ async actorWaitForTrackedShutdownWorkUnbounded(ctx) {
2169
+ await callHandle(
2170
+ asWasmActorContext(ctx),
2171
+ "waitForTrackedShutdownWorkUnbounded"
2172
+ );
2173
+ }
2010
2174
  actorKeepAwake(ctx, promise) {
2011
2175
  const wasmCtx = asWasmActorContext(ctx);
2012
2176
  const regionId = callHandle(wasmCtx, "beginKeepAwake");
@@ -2154,9 +2318,15 @@ var WasmCoreRuntime = class {
2154
2318
  )
2155
2319
  );
2156
2320
  }
2157
- async actorQueueWaitForNamesAvailable(ctx, names, options) {
2321
+ async actorQueueWaitForNamesAvailable(ctx, names, options, signal) {
2158
2322
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
2159
- await callHandleAsync(queue2, "waitForNamesAvailable", names, options);
2323
+ await callHandleAsync(
2324
+ queue2,
2325
+ "waitForNamesAvailable",
2326
+ names,
2327
+ options,
2328
+ signal
2329
+ );
2160
2330
  }
2161
2331
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
2162
2332
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
@@ -2248,6 +2418,29 @@ async function loadWasmRuntime(config) {
2248
2418
  };
2249
2419
  }
2250
2420
 
2421
+ // src/registry/write-through-proxy.ts
2422
+ import onChange from "@rivetkit/on-change";
2423
+ function createWriteThroughProxy(value, commit, beforeChange) {
2424
+ if (!value || typeof value !== "object") {
2425
+ return value;
2426
+ }
2427
+ return onChange(
2428
+ value,
2429
+ () => {
2430
+ commit(value);
2431
+ },
2432
+ {
2433
+ // Rejection is throw-based: beforeChange throws to prevent the
2434
+ // mutation. We always return true so on-change applies the change
2435
+ // if beforeChange did not throw.
2436
+ onValidate(_path, newValue) {
2437
+ beforeChange == null ? void 0 : beforeChange(newValue);
2438
+ return true;
2439
+ }
2440
+ }
2441
+ );
2442
+ }
2443
+
2251
2444
  // src/registry/native.ts
2252
2445
  var textEncoder = new TextEncoder();
2253
2446
  var textDecoder = new TextDecoder();
@@ -2401,6 +2594,14 @@ function databaseNotConfiguredError() {
2401
2594
  { public: true }
2402
2595
  );
2403
2596
  }
2597
+ function databaseClientNotReadyError() {
2598
+ return new RivetError(
2599
+ "actor",
2600
+ "database_client_not_ready",
2601
+ "actor database client was not initialized before user code ran. this is an internal lifecycle error; the migration callback should have pre-warmed the client. file an issue if you can reproduce.",
2602
+ { public: true }
2603
+ );
2604
+ }
2404
2605
  function stateNotEnabledError() {
2405
2606
  return new RivetError(
2406
2607
  "actor",
@@ -2452,8 +2653,23 @@ function resolveNativeDestroy(runtime, ctx) {
2452
2653
  function clearNativeRuntimeState(runtime, ctx) {
2453
2654
  callNativeSync(() => runtime.actorClearRuntimeState(ctx));
2454
2655
  }
2455
- async function cleanupNativeSleepRuntimeState(runtime, ctx) {
2456
- await runtime.actorWaitForTrackedShutdownWork(ctx);
2656
+ async function cleanupNativeSleepRuntimeState(runtime, ctx, afterTrackedWorkDrained) {
2657
+ const drained = await runtime.actorWaitForTrackedShutdownWork(ctx);
2658
+ if (!drained) {
2659
+ await closeNativeDatabaseClient(runtime, ctx);
2660
+ await closeNativeSqlDatabase(runtime, ctx);
2661
+ void runtime.actorWaitForTrackedShutdownWorkUnbounded(ctx).then(async () => {
2662
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
2663
+ clearNativeRuntimeState(runtime, ctx);
2664
+ }).catch((error) => {
2665
+ logger2().warn({
2666
+ msg: "deferred native sleep cleanup failed",
2667
+ error: stringifyError(error)
2668
+ });
2669
+ });
2670
+ return;
2671
+ }
2672
+ await (afterTrackedWorkDrained == null ? void 0 : afterTrackedWorkDrained());
2457
2673
  await closeNativeDatabaseClient(runtime, ctx);
2458
2674
  await closeNativeSqlDatabase(runtime, ctx);
2459
2675
  clearNativeRuntimeState(runtime, ctx);
@@ -2558,7 +2774,7 @@ function decodeValue(value) {
2558
2774
  if (!value || value.length === 0) {
2559
2775
  return void 0;
2560
2776
  }
2561
- return decodeCborJsonCompat(value);
2777
+ return decodeCborCompat(value);
2562
2778
  }
2563
2779
  function encodeValue(value) {
2564
2780
  return encodeCborCompat(value);
@@ -2618,12 +2834,6 @@ function callNativeSync(invoke) {
2618
2834
  throw normalizeNativeBridgeError(error);
2619
2835
  }
2620
2836
  }
2621
- function actorAbortedError() {
2622
- return Object.assign(new Error("Actor aborted"), {
2623
- group: "actor",
2624
- code: "aborted"
2625
- });
2626
- }
2627
2837
  function isClosedTaskRegistrationError(error) {
2628
2838
  const metadata = error instanceof RivetError ? error.metadata : void 0;
2629
2839
  const metadataError = metadata && typeof metadata === "object" && "error" in metadata ? metadata.error : void 0;
@@ -2756,7 +2966,7 @@ function serializeWorkflowHistoryForJson(data) {
2756
2966
  return null;
2757
2967
  }
2758
2968
  const history = decodeWorkflowHistoryTransport(data);
2759
- return {
2969
+ return jsonSafe({
2760
2970
  nameRegistry: [...history.nameRegistry],
2761
2971
  entries: history.entries.map((entry) => ({
2762
2972
  id: entry.id,
@@ -2780,7 +2990,7 @@ function serializeWorkflowHistoryForJson(data) {
2780
2990
  ]
2781
2991
  )
2782
2992
  )
2783
- };
2993
+ });
2784
2994
  }
2785
2995
  function toHttpJsonCompatible(value) {
2786
2996
  return JSON.parse(
@@ -2833,44 +3043,6 @@ function decodeArgs(value) {
2833
3043
  const decoded = decodeValue(value);
2834
3044
  return Array.isArray(decoded) ? decoded : decoded === void 0 ? [] : [decoded];
2835
3045
  }
2836
- function createWriteThroughProxy(value, commit, beforeChange) {
2837
- if (!value || typeof value !== "object") {
2838
- return value;
2839
- }
2840
- const proxies = /* @__PURE__ */ new WeakMap();
2841
- const wrap = (target) => {
2842
- const cached = proxies.get(target);
2843
- if (cached) {
2844
- return cached;
2845
- }
2846
- const proxy = new Proxy(target, {
2847
- get(innerTarget, property, receiver) {
2848
- const result = Reflect.get(innerTarget, property, receiver);
2849
- return result && typeof result === "object" ? wrap(result) : result;
2850
- },
2851
- set(innerTarget, property, nextValue, receiver) {
2852
- beforeChange == null ? void 0 : beforeChange();
2853
- const updated = Reflect.set(
2854
- innerTarget,
2855
- property,
2856
- nextValue,
2857
- receiver
2858
- );
2859
- commit(value);
2860
- return updated;
2861
- },
2862
- deleteProperty(innerTarget, property) {
2863
- beforeChange == null ? void 0 : beforeChange();
2864
- const updated = Reflect.deleteProperty(innerTarget, property);
2865
- commit(value);
2866
- return updated;
2867
- }
2868
- });
2869
- proxies.set(target, proxy);
2870
- return proxy;
2871
- };
2872
- return wrap(value);
2873
- }
2874
3046
  function buildRequest(init) {
2875
3047
  const url = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
2876
3048
  const body = init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
@@ -2923,13 +3095,23 @@ var NativeConnAdapter = class {
2923
3095
  decodeValue(this.#runtime.connParams(this.#conn))
2924
3096
  );
2925
3097
  }
3098
+ [RAW_STATE_SYMBOL]() {
3099
+ return this.#readState();
3100
+ }
2926
3101
  get state() {
2927
3102
  const nextState = this.#readState();
2928
- return createWriteThroughProxy(nextState, (nextValue) => {
2929
- this.#writeState(nextValue, { writeNative: true });
2930
- });
3103
+ return createWriteThroughProxy(
3104
+ nextState,
3105
+ (nextValue) => {
3106
+ this.#writeState(nextValue, { writeNative: true });
3107
+ },
3108
+ (newValue) => {
3109
+ assertJsonCompatValue(newValue);
3110
+ }
3111
+ );
2931
3112
  }
2932
3113
  set state(value) {
3114
+ assertJsonCompatValue(value);
2933
3115
  this.#writeState(value, { writeNative: true });
2934
3116
  }
2935
3117
  initializeState(value) {
@@ -3281,44 +3463,23 @@ var NativeQueueAdapter = class {
3281
3463
  }
3282
3464
  }
3283
3465
  async waitForNamesAvailable(names, options) {
3284
- if (!(options == null ? void 0 : options.signal)) {
3466
+ const { token, cleanup } = await createCancellationTokenHandle(
3467
+ this.#runtime,
3468
+ options == null ? void 0 : options.signal
3469
+ );
3470
+ try {
3285
3471
  await callNative(
3286
3472
  () => this.#runtime.actorQueueWaitForNamesAvailable(
3287
3473
  this.#ctx,
3288
3474
  [...names],
3289
3475
  {
3290
3476
  timeoutMs: options == null ? void 0 : options.timeout
3291
- }
3477
+ },
3478
+ token
3292
3479
  )
3293
3480
  );
3294
- return;
3295
- }
3296
- const deadline = options.timeout === void 0 ? void 0 : Date.now() + options.timeout;
3297
- for (; ; ) {
3298
- if (options.signal.aborted) {
3299
- throw actorAbortedError();
3300
- }
3301
- const remainingTimeout = deadline === void 0 ? void 0 : Math.max(0, deadline - Date.now());
3302
- const sliceTimeout = remainingTimeout === void 0 ? 100 : Math.min(remainingTimeout, 100);
3303
- try {
3304
- await callNative(
3305
- () => this.#runtime.actorQueueWaitForNamesAvailable(
3306
- this.#ctx,
3307
- [...names],
3308
- {
3309
- timeoutMs: sliceTimeout
3310
- }
3311
- )
3312
- );
3313
- return;
3314
- } catch (error) {
3315
- if (error.group === "queue" && error.code === "timed_out") {
3316
- if (remainingTimeout === void 0 || remainingTimeout > 100) {
3317
- continue;
3318
- }
3319
- }
3320
- throw error;
3321
- }
3481
+ } finally {
3482
+ cleanup == null ? void 0 : cleanup();
3322
3483
  }
3323
3484
  }
3324
3485
  async enqueueAndWait(name, body, options) {
@@ -3753,6 +3914,68 @@ var TrackedWebSocketHandleAdapter = class {
3753
3914
  return typeof value === "object" && value !== null && "then" in value && typeof value.then === "function";
3754
3915
  }
3755
3916
  };
3917
+ var NativeConnectionMap = class {
3918
+ #runtime;
3919
+ #ctx;
3920
+ #schemas;
3921
+ constructor(runtime, ctx, schemas) {
3922
+ this.#runtime = runtime;
3923
+ this.#ctx = ctx;
3924
+ this.#schemas = schemas;
3925
+ }
3926
+ #connToAdapter(conn) {
3927
+ return new NativeConnAdapter(
3928
+ this.#runtime,
3929
+ conn,
3930
+ this.#schemas,
3931
+ this.#ctx,
3932
+ (connId) => callNativeSync(
3933
+ () => this.#runtime.actorQueueHibernationRemoval(
3934
+ this.#ctx,
3935
+ connId
3936
+ )
3937
+ )
3938
+ );
3939
+ }
3940
+ get size() {
3941
+ return callNativeSync(() => this.#runtime.actorConns(this.#ctx)).length;
3942
+ }
3943
+ get(key) {
3944
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
3945
+ const conn = conns.find((c) => this.#runtime.connId(c) === key);
3946
+ if (!conn) return void 0;
3947
+ return this.#connToAdapter(conn);
3948
+ }
3949
+ has(key) {
3950
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
3951
+ return conns.some((c) => this.#runtime.connId(c) === key);
3952
+ }
3953
+ keys() {
3954
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
3955
+ return conns.map((c) => this.#runtime.connId(c))[Symbol.iterator]();
3956
+ }
3957
+ values() {
3958
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
3959
+ return conns.map((c) => this.#connToAdapter(c))[Symbol.iterator]();
3960
+ }
3961
+ entries() {
3962
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
3963
+ return conns.map(
3964
+ (c) => [this.#runtime.connId(c), this.#connToAdapter(c)]
3965
+ )[Symbol.iterator]();
3966
+ }
3967
+ forEach(callback, thisArg) {
3968
+ const conns = callNativeSync(() => this.#runtime.actorConns(this.#ctx));
3969
+ for (const conn of conns) {
3970
+ const id = this.#runtime.connId(conn);
3971
+ callback.call(thisArg, this.#connToAdapter(conn), id, this);
3972
+ }
3973
+ }
3974
+ [Symbol.iterator]() {
3975
+ return this.entries();
3976
+ }
3977
+ [Symbol.toStringTag] = "NativeConnectionMap";
3978
+ };
3756
3979
  var ActorContextHandleAdapter = class {
3757
3980
  #runtime;
3758
3981
  #ctx;
@@ -3761,9 +3984,9 @@ var ActorContextHandleAdapter = class {
3761
3984
  #abortSignalCleanup;
3762
3985
  #client;
3763
3986
  #clientFactory;
3987
+ #connMap;
3764
3988
  #databaseProvider;
3765
3989
  #db;
3766
- #dbProxy;
3767
3990
  #dispatchCancelToken;
3768
3991
  #kv;
3769
3992
  #queue;
@@ -3806,30 +4029,22 @@ var ActorContextHandleAdapter = class {
3806
4029
  if (!this.#databaseProvider) {
3807
4030
  throw databaseNotConfiguredError();
3808
4031
  }
3809
- if (!this.#dbProxy) {
3810
- this.#dbProxy = new Proxy(
3811
- {},
3812
- {
3813
- get: (_target, property) => {
3814
- if (property === "then") {
3815
- return void 0;
3816
- }
3817
- return async (...args) => {
3818
- const client = await this.ensureDatabaseClient();
3819
- const value = Reflect.get(
3820
- client,
3821
- property
3822
- );
3823
- if (typeof value !== "function") {
3824
- return value;
3825
- }
3826
- return await value.apply(client, args);
3827
- };
3828
- }
3829
- }
3830
- );
4032
+ if (this.#db) {
4033
+ return this.#db;
4034
+ }
4035
+ const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
4036
+ const cachedClient = runtimeState.databaseClient;
4037
+ if (cachedClient) {
4038
+ this.#db = cachedClient.client;
4039
+ return this.#db;
3831
4040
  }
3832
- return this.#dbProxy;
4041
+ throw databaseClientNotReadyError();
4042
+ }
4043
+ [RAW_STATE_SYMBOL]() {
4044
+ if (!this.#stateEnabled) {
4045
+ throw stateNotEnabledError();
4046
+ }
4047
+ return this.#readState();
3833
4048
  }
3834
4049
  get state() {
3835
4050
  if (!this.#stateEnabled) {
@@ -3844,8 +4059,9 @@ var ActorContextHandleAdapter = class {
3844
4059
  (nextValue) => {
3845
4060
  this.#writeState(nextValue, { scheduleSave: true });
3846
4061
  },
3847
- () => {
4062
+ (newValue) => {
3848
4063
  this.#assertCanMutateState();
4064
+ assertJsonCompatValue(newValue);
3849
4065
  }
3850
4066
  );
3851
4067
  }
@@ -3856,6 +4072,7 @@ var ActorContextHandleAdapter = class {
3856
4072
  throw stateNotEnabledError();
3857
4073
  }
3858
4074
  this.#assertCanMutateState();
4075
+ assertJsonCompatValue(value);
3859
4076
  this.#writeState(value, { scheduleSave: true });
3860
4077
  }
3861
4078
  initializeState(value) {
@@ -3912,25 +4129,14 @@ var ActorContextHandleAdapter = class {
3912
4129
  return callNativeSync(() => this.#runtime.actorRegion(this.#ctx));
3913
4130
  }
3914
4131
  get conns() {
3915
- return new Map(
3916
- callNativeSync(() => this.#runtime.actorConns(this.#ctx)).map(
3917
- (conn) => [
3918
- this.#runtime.connId(conn),
3919
- new NativeConnAdapter(
3920
- this.#runtime,
3921
- conn,
3922
- this.#schemas,
3923
- this.#ctx,
3924
- (connId) => callNativeSync(
3925
- () => this.#runtime.actorQueueHibernationRemoval(
3926
- this.#ctx,
3927
- connId
3928
- )
3929
- )
3930
- )
3931
- ]
3932
- )
3933
- );
4132
+ if (!this.#connMap) {
4133
+ this.#connMap = new NativeConnectionMap(
4134
+ this.#runtime,
4135
+ this.#ctx,
4136
+ this.#schemas
4137
+ );
4138
+ }
4139
+ return this.#connMap;
3934
4140
  }
3935
4141
  get log() {
3936
4142
  return logger2();
@@ -4207,6 +4413,7 @@ var ActorContextHandleAdapter = class {
4207
4413
  return false;
4208
4414
  }
4209
4415
  sleep() {
4416
+ this.#flushStateChange();
4210
4417
  callNativeSync(() => this.#runtime.actorSleep(this.#ctx));
4211
4418
  }
4212
4419
  destroy() {
@@ -4687,6 +4894,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4687
4894
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0
4688
4895
  });
4689
4896
  } catch (error) {
4897
+ logger2().error({
4898
+ msg: "error replaying workflow history",
4899
+ error
4900
+ });
4690
4901
  return errorResponse(error);
4691
4902
  }
4692
4903
  }
@@ -4838,6 +5049,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4838
5049
  );
4839
5050
  return jsonResponse({ output });
4840
5051
  } catch (error) {
5052
+ logger2().error({
5053
+ msg: "Error handling inspector action request",
5054
+ error
5055
+ });
4841
5056
  return errorResponse(error);
4842
5057
  }
4843
5058
  }
@@ -4851,6 +5066,10 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4851
5066
  { status: 404 }
4852
5067
  );
4853
5068
  } catch (error) {
5069
+ logger2().error({
5070
+ msg: "Error handling inspector request",
5071
+ error
5072
+ });
4854
5073
  return errorResponse(error);
4855
5074
  } finally {
4856
5075
  await actorCtx.dispose();
@@ -4973,24 +5192,30 @@ function buildNativeFactory(runtime, registryConfig, definition) {
4973
5192
  async (error, payload) => {
4974
5193
  const { ctx } = unwrapTsfnPayload(error, payload);
4975
5194
  const actorCtx = makeActorCtx(ctx);
5195
+ const saveActorState = async () => {
5196
+ if (runtime.kind === "wasm") {
5197
+ await runtime.actorSaveState(
5198
+ ctx,
5199
+ actorCtx.serializeForTick("save")
5200
+ );
5201
+ } else {
5202
+ await actorCtx.saveState({
5203
+ immediate: true
5204
+ });
5205
+ }
5206
+ };
4976
5207
  try {
4977
5208
  if (onSleep) {
4978
- try {
4979
- await onSleep(actorCtx);
4980
- } finally {
4981
- if (runtime.kind === "wasm") {
4982
- await runtime.actorSaveState(
4983
- ctx,
4984
- actorCtx.serializeForTick("save")
4985
- );
4986
- } else {
4987
- await actorCtx.saveState({ immediate: true });
4988
- }
4989
- }
5209
+ await onSleep(actorCtx);
4990
5210
  }
5211
+ await saveActorState();
4991
5212
  } finally {
4992
5213
  try {
4993
- await cleanupNativeSleepRuntimeState(runtime, ctx);
5214
+ await cleanupNativeSleepRuntimeState(
5215
+ runtime,
5216
+ ctx,
5217
+ saveActorState
5218
+ );
4994
5219
  } finally {
4995
5220
  await actorCtx.dispose();
4996
5221
  }
@@ -5488,6 +5713,7 @@ function finishShutdownSignal(signal) {
5488
5713
  }
5489
5714
  var Registry = class {
5490
5715
  #config;
5716
+ #buildConfiguredRegistry;
5491
5717
  routes;
5492
5718
  get config() {
5493
5719
  return this.#config;
@@ -5503,8 +5729,9 @@ var Registry = class {
5503
5729
  #shutdownInstalled = false;
5504
5730
  #shutdownInFlight = null;
5505
5731
  #signalHandlers = {};
5506
- constructor(config) {
5732
+ constructor(config, deps) {
5507
5733
  this.#config = config;
5734
+ this.#buildConfiguredRegistry = (deps == null ? void 0 : deps.buildConfiguredRegistry) ?? buildConfiguredRegistry;
5508
5735
  this.routes = {
5509
5736
  health: () => this.#healthRoute(),
5510
5737
  metadata: () => this.#metadataRoute(),
@@ -5514,12 +5741,12 @@ var Registry = class {
5514
5741
  #ensureServerlessPoolConfigured(config) {
5515
5742
  if (!config.configurePool) return void 0;
5516
5743
  if (!this.#configureServerlessPoolPromise) {
5517
- this.#configureServerlessPoolPromise = configureServerlessPool(config).catch(
5518
- (error) => {
5519
- this.#configureServerlessPoolPromise = void 0;
5520
- throw error;
5521
- }
5522
- );
5744
+ this.#configureServerlessPoolPromise = configureServerlessPool(
5745
+ config
5746
+ ).catch((error) => {
5747
+ this.#configureServerlessPoolPromise = void 0;
5748
+ throw error;
5749
+ });
5523
5750
  this.#configureServerlessPoolPromise.catch(() => {
5524
5751
  });
5525
5752
  }
@@ -5540,7 +5767,7 @@ var Registry = class {
5540
5767
  const config = this.parseConfig();
5541
5768
  this.#printWelcome(config, "serverless");
5542
5769
  if (!this.#runtimeServerlessPromise) {
5543
- this.#runtimeServerlessPromise = buildConfiguredRegistry(config);
5770
+ this.#runtimeServerlessPromise = this.#buildConfiguredRegistry(config);
5544
5771
  }
5545
5772
  const { runtime, registry, serveConfig } = await this.#runtimeServerlessPromise;
5546
5773
  const isStartRequest = isServerlessStartRequest(
@@ -5555,7 +5782,7 @@ var Registry = class {
5555
5782
  if (isStartRequest) {
5556
5783
  try {
5557
5784
  await this.#ensureServerlessPoolConfigured(config);
5558
- } catch (error) {
5785
+ } catch (_error) {
5559
5786
  return new Response(
5560
5787
  JSON.stringify({
5561
5788
  group: "guard",
@@ -5669,7 +5896,7 @@ var Registry = class {
5669
5896
  if (isMetadataRequest && !isEngineMetadataRequest) {
5670
5897
  try {
5671
5898
  await this.#ensureServerlessPoolConfigured(config);
5672
- } catch (error) {
5899
+ } catch (_error) {
5673
5900
  return new Response(
5674
5901
  JSON.stringify({
5675
5902
  group: "guard",
@@ -5702,6 +5929,33 @@ var Registry = class {
5702
5929
  fetch: (request) => this.handler(request)
5703
5930
  };
5704
5931
  }
5932
+ /**
5933
+ * Starts an HTTP server that dispatches every request through the
5934
+ * serverless handler. Uses `crossPlatformServe` to pick the right
5935
+ * runtime (Node, Bun, Deno).
5936
+ *
5937
+ * @param opts.port Port to listen on. Defaults to 3000.
5938
+ * @param opts.publicDir If set, serves static files from this directory
5939
+ * before falling through to the registry handler.
5940
+ *
5941
+ * @example
5942
+ * ```ts
5943
+ * await registry.listen();
5944
+ * await registry.listen({ port: 8080, publicDir: "./public" });
5945
+ * ```
5946
+ */
5947
+ async listen(opts = {}) {
5948
+ const port = opts.port ?? 3e3;
5949
+ const config = this.parseConfig();
5950
+ const runtime = detectRuntime();
5951
+ const app = new Hono();
5952
+ if (opts.publicDir) {
5953
+ const serveStatic = await loadRuntimeServeStatic(runtime);
5954
+ app.use("*", serveStatic({ root: opts.publicDir }));
5955
+ }
5956
+ app.all("*", (c) => this.handler(c.req.raw));
5957
+ await crossPlatformServe(config, port, app, runtime);
5958
+ }
5705
5959
  /**
5706
5960
  * Returns a health response suitable for mounting in a user-owned router.
5707
5961
  */
@@ -5791,20 +6045,20 @@ var Registry = class {
5791
6045
  */
5792
6046
  #startEnvoy(config, printWelcome) {
5793
6047
  if (!this.#runtimeServePromise) {
5794
- const configuredRegistryPromise = buildConfiguredRegistry(config);
6048
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
5795
6049
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
5796
6050
  this.#runtimeServePromise = configuredRegistryPromise.then(async ({ runtime, registry, serveConfig }) => {
5797
6051
  await runtime.serveRegistry(registry, serveConfig);
5798
- }).catch((err) => {
5799
- logger2().warn({ err }, "runtime registry serve errored");
6052
+ }).catch((error) => {
6053
+ logger2().warn({ error }, "runtime registry serve errored");
5800
6054
  });
5801
- this.#installSignalHandlers(config, configuredRegistryPromise);
6055
+ this.#installSignalHandlers(config);
5802
6056
  }
5803
6057
  if (printWelcome) {
5804
6058
  this.#printWelcome(config, "serverful");
5805
6059
  }
5806
6060
  }
5807
- #installSignalHandlers(config, configuredRegistryPromise) {
6061
+ #installSignalHandlers(config) {
5808
6062
  var _a;
5809
6063
  if (this.#shutdownInstalled) return;
5810
6064
  if ((_a = config.shutdown) == null ? void 0 : _a.disableSignalHandlers) return;
@@ -5813,58 +6067,86 @@ var Registry = class {
5813
6067
  }
5814
6068
  this.#shutdownInstalled = true;
5815
6069
  const install = (signal) => {
5816
- const handler = () => this.#onShutdownSignal(
5817
- signal,
5818
- config,
5819
- configuredRegistryPromise
5820
- );
6070
+ const handler = () => this.#onShutdownSignal(signal, config);
5821
6071
  this.#signalHandlers[signal] = handler;
5822
6072
  process.on(signal, handler);
5823
6073
  };
5824
6074
  install("SIGINT");
5825
6075
  install("SIGTERM");
5826
6076
  }
5827
- #onShutdownSignal(signal, config, configuredRegistryPromise) {
6077
+ #onShutdownSignal(signal, config) {
5828
6078
  if (this.#shutdownInFlight !== null) {
5829
6079
  this.#removeSignalHandlers();
5830
6080
  finishShutdownSignal(signal);
5831
6081
  return;
5832
6082
  }
5833
- this.#shutdownInFlight = this.#runShutdown(
5834
- signal,
5835
- config,
5836
- configuredRegistryPromise
5837
- ).catch((err) => {
6083
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
6084
+ logger2().warn({ err }, "shutdown error");
6085
+ }).then(() => {
6086
+ this.#removeSignalHandlers();
6087
+ finishShutdownSignal(signal);
6088
+ });
6089
+ }
6090
+ /**
6091
+ * Gracefully drains all live registries.
6092
+ *
6093
+ * Programmatic counterpart to the SIGINT/SIGTERM handlers: tears down
6094
+ * every live `CoreRegistry` (both `start()` and `handler()` modes) and
6095
+ * waits for the serve promise to resolve, all bounded by the shutdown
6096
+ * grace period. Unlike a signal-driven shutdown, this does not re-raise a
6097
+ * signal or exit the process. The caller owns process lifetime.
6098
+ *
6099
+ * Idempotent: concurrent or repeated calls share a single drain. Safe to
6100
+ * call even if nothing has been started.
6101
+ *
6102
+ * @example
6103
+ * ```ts
6104
+ * const registry = setup({ use: { counter } });
6105
+ * registry.start();
6106
+ * // ...later, on your own shutdown trigger:
6107
+ * await registry.shutdown();
6108
+ * ```
6109
+ */
6110
+ async shutdown() {
6111
+ if (this.#shutdownInFlight !== null) return this.#shutdownInFlight;
6112
+ const config = this.parseConfig();
6113
+ this.#removeSignalHandlers();
6114
+ this.#shutdownInFlight = this.#drain(config).catch((err) => {
5838
6115
  logger2().warn({ err }, "shutdown error");
5839
6116
  });
6117
+ return this.#shutdownInFlight;
5840
6118
  }
5841
- async #runShutdown(signal, config, configuredRegistryPromise) {
6119
+ async #drain(config) {
5842
6120
  var _a;
5843
- const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? await this.#actorStopThresholdMs(configuredRegistryPromise) ?? 30 * 60 * 1e3;
6121
+ const modeAPromise = this.#runtimeServeConfiguredPromise;
6122
+ const modeBPromise = this.#runtimeServerlessPromise;
6123
+ const gracePeriodMs = ((_a = config.shutdown) == null ? void 0 : _a.gracePeriodMs) ?? await this.#actorStopThresholdMs(modeAPromise ?? modeBPromise) ?? 30 * 60 * 1e3;
5844
6124
  const drain = async () => {
5845
- const registries = [
5846
- (async () => {
5847
- try {
5848
- const { runtime, registry } = await configuredRegistryPromise;
5849
- await runtime.shutdownRegistry(registry);
5850
- } catch (err) {
5851
- logger2().warn(
5852
- { err },
5853
- "runtime registry shutdown errored (mode A)"
5854
- );
5855
- }
5856
- })()
5857
- ];
5858
- const runtimeServerlessPromise = this.#runtimeServerlessPromise;
5859
- if (runtimeServerlessPromise !== void 0) {
6125
+ const registries = [];
6126
+ if (modeAPromise !== void 0) {
5860
6127
  registries.push(
5861
6128
  (async () => {
5862
6129
  try {
5863
- const { runtime, registry } = await runtimeServerlessPromise;
6130
+ const { runtime, registry } = await modeAPromise;
5864
6131
  await runtime.shutdownRegistry(registry);
5865
6132
  } catch (err) {
5866
6133
  logger2().warn(
5867
6134
  { err },
6135
+ "runtime registry shutdown errored (mode A)"
6136
+ );
6137
+ }
6138
+ })()
6139
+ );
6140
+ }
6141
+ if (modeBPromise !== void 0) {
6142
+ registries.push(
6143
+ (async () => {
6144
+ try {
6145
+ const { runtime, registry } = await modeBPromise;
6146
+ await runtime.shutdownRegistry(registry);
6147
+ } catch (err) {
6148
+ logger2().warn(
6149
+ { error: err },
5868
6150
  "runtime registry shutdown errored (mode B)"
5869
6151
  );
5870
6152
  }
@@ -5886,11 +6168,10 @@ var Registry = class {
5886
6168
  }
5887
6169
  )
5888
6170
  ]);
5889
- this.#removeSignalHandlers();
5890
- finishShutdownSignal(signal);
5891
6171
  }
5892
6172
  async #actorStopThresholdMs(configuredRegistryPromise) {
5893
6173
  var _a;
6174
+ if (configuredRegistryPromise === void 0) return void 0;
5894
6175
  try {
5895
6176
  const { runtime, registry } = await configuredRegistryPromise;
5896
6177
  const thresholdMs = await ((_a = runtime.registryActorStopThresholdMs) == null ? void 0 : _a.call(runtime, registry));