@rivetkit/supabase 2.3.11-rc.9 → 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 (3) hide show
  1. package/dist/mod.js +1021 -212
  2. package/dist/mod.mjs +1018 -209
  3. package/package.json +3 -3
package/dist/mod.js CHANGED
@@ -321,6 +321,7 @@ __export(mod_exports, {
321
321
  actor: () => actor,
322
322
  buildActorNames: () => buildActorNames,
323
323
  createClientWithDriver: () => createClientWithDriver,
324
+ defineRunHandler: () => defineRunHandler,
324
325
  event: () => event,
325
326
  isStaticActorDefinition: () => isStaticActorDefinition,
326
327
  isStaticActorInstance: () => isStaticActorInstance,
@@ -508,7 +509,7 @@ function unsupportedFeature(feature) {
508
509
  );
509
510
  }
510
511
 
511
- // ../rivetkit/dist/tsup/chunk-LZ4TSBIP.js
512
+ // ../rivetkit/dist/tsup/chunk-OUENKQHB.js
512
513
  var import_pino = require("pino");
513
514
 
514
515
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/external.js
@@ -13181,7 +13182,7 @@ var classic_default = external_exports;
13181
13182
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13182
13183
  var v4_default = classic_default;
13183
13184
 
13184
- // ../rivetkit/dist/tsup/chunk-LZ4TSBIP.js
13185
+ // ../rivetkit/dist/tsup/chunk-OUENKQHB.js
13185
13186
  var cbor = __toESM(require("cbor-x"), 1);
13186
13187
  var import_invariant = __toESM(require_invariant(), 1);
13187
13188
  var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
@@ -13346,7 +13347,7 @@ function noopNext() {
13346
13347
  }
13347
13348
  var package_default = {
13348
13349
  name: "rivetkit",
13349
- version: "2.3.11-rc.9",
13350
+ version: "2.3.11",
13350
13351
  description: "Lightweight libraries for building stateful actors on edge platforms",
13351
13352
  license: "Apache-2.0",
13352
13353
  keywords: [
@@ -13482,6 +13483,16 @@ var package_default = {
13482
13483
  default: "./dist/tsup/inspector/mod.cjs"
13483
13484
  }
13484
13485
  },
13486
+ "./experimental/inspector/workflow": {
13487
+ import: {
13488
+ types: "./dist/tsup/inspector/workflow.d.ts",
13489
+ default: "./dist/tsup/inspector/workflow.js"
13490
+ },
13491
+ require: {
13492
+ types: "./dist/tsup/inspector/workflow.d.cts",
13493
+ default: "./dist/tsup/inspector/workflow.cjs"
13494
+ }
13495
+ },
13485
13496
  "./inspector-tab": {
13486
13497
  import: {
13487
13498
  types: "./dist/tsup/inspector-tab/mod.d.ts",
@@ -13527,7 +13538,7 @@ var package_default = {
13527
13538
  "./dist/tsup/chunk-*.cjs"
13528
13539
  ],
13529
13540
  scripts: {
13530
- build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/utils.ts src/workflow/mod.ts src/test/mod.ts src/inspector/mod.ts src/inspector-tab/mod.ts src/db/mod.ts src/db/drizzle.ts src/dynamic/mod.ts src/unstable/migrations.ts && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os",
13541
+ build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/utils.ts src/workflow/mod.ts src/test/mod.ts src/inspector/mod.ts src/inspector/workflow.ts src/inspector-tab/mod.ts src/db/mod.ts src/db/drizzle.ts src/dynamic/mod.ts src/unstable/migrations.ts && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os && node scripts/check-built-commonjs.mjs",
13531
13542
  "build:browser": "tsup --config tsup.browser.config.ts",
13532
13543
  "check-types": "tsc --noEmit",
13533
13544
  lint: "biome check . && pnpm run check:test-skips && pnpm run check:wait-for-comments",
@@ -14639,7 +14650,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
14639
14650
  };
14640
14651
  }
14641
14652
 
14642
- // ../rivetkit/dist/tsup/chunk-C5TORAVP.js
14653
+ // ../rivetkit/dist/tsup/chunk-QFJ24MBU.js
14643
14654
  var config2 = /* @__PURE__ */ Config({});
14644
14655
  function readWorkflowCbor(bc) {
14645
14656
  return readData(bc);
@@ -14937,7 +14948,7 @@ function decodeWorkflowHistoryTransport(data) {
14937
14948
  return decodeWorkflowHistory(toUint8Array(data));
14938
14949
  }
14939
14950
 
14940
- // ../rivetkit/dist/tsup/chunk-QWLJCP3X.js
14951
+ // ../rivetkit/dist/tsup/chunk-6W5VGLFT.js
14941
14952
  function flattenActionHandlers(actions) {
14942
14953
  const flattened = /* @__PURE__ */ Object.create(null);
14943
14954
  for (const { name, handler } of collectActionEntries(actions)) {
@@ -15043,6 +15054,7 @@ var zActionTree = external_exports.custom((value) => {
15043
15054
  });
15044
15055
  var WorkflowInspectorConfigSchema = external_exports.object({
15045
15056
  getHistory: zFunction(),
15057
+ getState: zFunction().optional(),
15046
15058
  onHistoryUpdated: zFunction().optional(),
15047
15059
  replayFromStep: zFunction().optional()
15048
15060
  });
@@ -15112,9 +15124,36 @@ var RunConfigSchema = external_exports.object({
15112
15124
  /** Inspector integration for long-running run handlers. */
15113
15125
  inspector: RunInspectorConfigSchema.optional()
15114
15126
  });
15115
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for(
15116
- "rivetkit.run_function_config"
15117
- );
15127
+ var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
15128
+ function defineRunHandler(run, options) {
15129
+ if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
15130
+ throw new TypeError(
15131
+ "defineRunHandler requires inspectorKind and createInspector together"
15132
+ );
15133
+ }
15134
+ Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
15135
+ configurable: false,
15136
+ enumerable: false,
15137
+ writable: false,
15138
+ value: {
15139
+ name: options.name,
15140
+ icon: options.icon,
15141
+ inspectorKind: options.inspectorKind,
15142
+ createInspector: options.createInspector
15143
+ }
15144
+ });
15145
+ return run;
15146
+ }
15147
+ function getRunInspectorKind(run) {
15148
+ var _a2;
15149
+ if (!run || typeof run !== "function") return void 0;
15150
+ return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
15151
+ }
15152
+ function createRunInspector(run, context) {
15153
+ var _a2, _b;
15154
+ if (!run || typeof run !== "function") return void 0;
15155
+ return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context);
15156
+ }
15118
15157
  var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
15119
15158
  function getRunFunction(run) {
15120
15159
  if (!run) return void 0;
@@ -15138,6 +15177,12 @@ function getRunInspectorConfig(run, actor2) {
15138
15177
  }
15139
15178
  return run.inspector;
15140
15179
  }
15180
+ function hasRunInspectorConfig(run) {
15181
+ if (!run) return false;
15182
+ if (typeof run !== "function") return run.inspector !== void 0;
15183
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15184
+ return (config3 == null ? void 0 : config3.inspectorKind) !== void 0 || (config3 == null ? void 0 : config3.createInspector) !== void 0 || (config3 == null ? void 0 : config3.inspector) !== void 0 || (config3 == null ? void 0 : config3.inspectorFactory) !== void 0;
15185
+ }
15141
15186
  function disposeRunInspector(run, actorId) {
15142
15187
  var _a2;
15143
15188
  if (!run || typeof run !== "function") {
@@ -15484,7 +15529,90 @@ function removePrefixFromKey(prefixedKey) {
15484
15529
  return prefixedKey.slice(KEYS.KV.length);
15485
15530
  }
15486
15531
 
15487
- // ../rivetkit/dist/tsup/chunk-XOOESJY7.js
15532
+ // ../rivetkit/dist/tsup/chunk-JTHHCZCZ.js
15533
+ var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15534
+ function isManualTransactionControl(query) {
15535
+ return /^\s*(?:BEGIN|SAVEPOINT|COMMIT|END|ROLLBACK)\b/i.test(query);
15536
+ }
15537
+ function validateTransactionTimeout(timeout) {
15538
+ if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout <= 0)) {
15539
+ throw new Error(
15540
+ "db.transaction() timeout must be a positive finite number of milliseconds"
15541
+ );
15542
+ }
15543
+ }
15544
+ function validateTransactionName(name) {
15545
+ if (name === void 0) {
15546
+ return;
15547
+ }
15548
+ if (name.length === 0) {
15549
+ throw new Error("db.transaction() name must not be empty");
15550
+ }
15551
+ }
15552
+ function isSqliteBindingValue(value) {
15553
+ if (value === null || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || value instanceof Uint8Array) {
15554
+ return true;
15555
+ }
15556
+ if (Array.isArray(value)) {
15557
+ return value.every((item) => typeof item === "number");
15558
+ }
15559
+ return false;
15560
+ }
15561
+ function isPlainObject3(value) {
15562
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
15563
+ return false;
15564
+ }
15565
+ return Object.getPrototypeOf(value) === Object.prototype;
15566
+ }
15567
+ function isSqliteBindingObject(value) {
15568
+ if (!isPlainObject3(value)) {
15569
+ return false;
15570
+ }
15571
+ return Object.values(value).every((entry) => isSqliteBindingValue(entry));
15572
+ }
15573
+ function toSqliteBindings(input) {
15574
+ if (Array.isArray(input)) {
15575
+ for (const value of input) {
15576
+ if (!isSqliteBindingValue(value)) {
15577
+ throw new Error(
15578
+ `unsupported sqlite binding type: ${typeof value}`
15579
+ );
15580
+ }
15581
+ }
15582
+ return input;
15583
+ }
15584
+ if (isSqliteBindingObject(input)) {
15585
+ return input;
15586
+ }
15587
+ throw new Error("unsupported sqlite binding collection");
15588
+ }
15589
+ var AsyncMutex = class {
15590
+ #locked = false;
15591
+ #waiting = [];
15592
+ async acquire() {
15593
+ while (this.#locked) {
15594
+ await new Promise((resolve) => this.#waiting.push(resolve));
15595
+ }
15596
+ this.#locked = true;
15597
+ }
15598
+ release() {
15599
+ this.#locked = false;
15600
+ const next = this.#waiting.shift();
15601
+ if (next) {
15602
+ next();
15603
+ }
15604
+ }
15605
+ async run(fn) {
15606
+ await this.acquire();
15607
+ try {
15608
+ return await fn();
15609
+ } finally {
15610
+ this.release();
15611
+ }
15612
+ }
15613
+ };
15614
+
15615
+ // ../rivetkit/dist/tsup/chunk-FWROC5LA.js
15488
15616
  function logger() {
15489
15617
  return getLogger("actor-client");
15490
15618
  }
@@ -15522,35 +15650,7 @@ async function importWebSocket() {
15522
15650
  return webSocketPromise;
15523
15651
  }
15524
15652
 
15525
- // ../rivetkit/dist/tsup/chunk-7AFZMFPQ.js
15526
- var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15527
- var AsyncMutex = class {
15528
- #locked = false;
15529
- #waiting = [];
15530
- async acquire() {
15531
- while (this.#locked) {
15532
- await new Promise((resolve) => this.#waiting.push(resolve));
15533
- }
15534
- this.#locked = true;
15535
- }
15536
- release() {
15537
- this.#locked = false;
15538
- const next = this.#waiting.shift();
15539
- if (next) {
15540
- next();
15541
- }
15542
- }
15543
- async run(fn) {
15544
- await this.acquire();
15545
- try {
15546
- return await fn();
15547
- } finally {
15548
- this.release();
15549
- }
15550
- }
15551
- };
15552
-
15553
- // ../rivetkit/dist/tsup/chunk-HOZ3ZLZ2.js
15653
+ // ../rivetkit/dist/tsup/chunk-3ZR542SK.js
15554
15654
  var import_invariant2 = __toESM(require_invariant(), 1);
15555
15655
 
15556
15656
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -15728,7 +15828,7 @@ function createVersionedDataHandler(config3) {
15728
15828
  return new VersionedDataHandler(config3);
15729
15829
  }
15730
15830
 
15731
- // ../rivetkit/dist/tsup/chunk-HOZ3ZLZ2.js
15831
+ // ../rivetkit/dist/tsup/chunk-3ZR542SK.js
15732
15832
  var import_invariant3 = __toESM(require_invariant(), 1);
15733
15833
  var import_invariant4 = __toESM(require_invariant(), 1);
15734
15834
  var PATH_CONNECT = "/connect";
@@ -21444,6 +21544,231 @@ function apiActorToOutput(actor2) {
21444
21544
  };
21445
21545
  }
21446
21546
 
21547
+ // ../rivetkit/dist/tsup/chunk-6WYATRS4.js
21548
+ var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
21549
+ var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
21550
+ function registerNativeStateTransactionOpener(provider, opener) {
21551
+ nativeStateTransactionOpeners.set(provider, opener);
21552
+ return provider;
21553
+ }
21554
+ function bindNativeStateTransactionContext(client, context) {
21555
+ if ((typeof client !== "object" || client === null) && typeof client !== "function") {
21556
+ return client;
21557
+ }
21558
+ const bind = nativeStateTransactionClientBinders.get(client);
21559
+ return (bind == null ? void 0 : bind(context)) ?? client;
21560
+ }
21561
+ function hasMultipleStatements(query) {
21562
+ const trimmed = query.trim().replace(/;+$/, "").trimEnd();
21563
+ return trimmed.includes(";");
21564
+ }
21565
+ function db({
21566
+ onMigrate,
21567
+ warnOnManualTransactions = true,
21568
+ profiling
21569
+ } = {}) {
21570
+ const provider = {
21571
+ sqliteProfiling: profiling,
21572
+ createClient: async (ctx) => {
21573
+ const nativeDatabaseProvider = ctx.nativeDatabaseProvider;
21574
+ if (!nativeDatabaseProvider) {
21575
+ throw new Error(
21576
+ "native SQLite is required, but the current runtime did not provide a native database provider"
21577
+ );
21578
+ }
21579
+ const db2 = await nativeDatabaseProvider.open(ctx.actorId);
21580
+ let closed = false;
21581
+ let manualTransactionWarned = false;
21582
+ const ensureOpen = () => {
21583
+ if (closed) {
21584
+ throw new Error(
21585
+ "Database is closed. This usually means a background timer (setInterval, setTimeout) or a stray promise is still running after the actor stopped. Use c.abortSignal to clean up timers before the actor shuts down."
21586
+ );
21587
+ }
21588
+ };
21589
+ const createClient = (target, transactionScoped = false, stateTransactionContext) => {
21590
+ const client2 = {
21591
+ execute: async (query, ...args) => {
21592
+ var _a2, _b, _c, _d;
21593
+ ensureOpen();
21594
+ if (!transactionScoped && warnOnManualTransactions && !manualTransactionWarned && !hasMultipleStatements(query) && isManualTransactionControl(query)) {
21595
+ manualTransactionWarned = true;
21596
+ getLogger("database").warn(
21597
+ { actorId: ctx.actorId },
21598
+ "Manual cross-call SQLite transactions can interleave with other actor work. Use db.transaction() for coordinated transactions. Set warnOnManualTransactions: false in your db(...) configuration to disable this warning."
21599
+ );
21600
+ }
21601
+ const kvReadsBefore = ((_a2 = ctx.metrics) == null ? void 0 : _a2.totalKvReads) ?? 0;
21602
+ const kvWritesBefore = ((_b = ctx.metrics) == null ? void 0 : _b.totalKvWrites) ?? 0;
21603
+ const start = performance.now();
21604
+ try {
21605
+ if (args.length > 0) {
21606
+ const bindings = args.length === 1 && isSqliteBindingObject(args[0]) ? toSqliteBindings(args[0]) : toSqliteBindings(args);
21607
+ const { rows, columns } = await target.execute(
21608
+ query,
21609
+ bindings
21610
+ );
21611
+ return rows.map(
21612
+ (row) => rowToObject(row, columns)
21613
+ );
21614
+ }
21615
+ if (!hasMultipleStatements(query)) {
21616
+ const { rows, columns } = await target.execute(
21617
+ query,
21618
+ void 0
21619
+ );
21620
+ return rows.map(
21621
+ (row) => rowToObject(row, columns)
21622
+ );
21623
+ }
21624
+ return await execMultiStatement(
21625
+ target,
21626
+ query
21627
+ );
21628
+ } finally {
21629
+ const durationMs = performance.now() - start;
21630
+ (_c = ctx.metrics) == null ? void 0 : _c.trackSql(query, durationMs);
21631
+ if (ctx.metrics) {
21632
+ const kvReads = ctx.metrics.totalKvReads - kvReadsBefore;
21633
+ const kvWrites = ctx.metrics.totalKvWrites - kvWritesBefore;
21634
+ (_d = ctx.log) == null ? void 0 : _d.debug({
21635
+ msg: "sql query",
21636
+ query: query.slice(0, 120),
21637
+ durationMs,
21638
+ kvReads,
21639
+ kvWrites
21640
+ });
21641
+ }
21642
+ }
21643
+ },
21644
+ transaction: async (callback, options) => {
21645
+ var _a2, _b;
21646
+ validateTransactionTimeout(options == null ? void 0 : options.timeout);
21647
+ validateTransactionName(options == null ? void 0 : options.name);
21648
+ if (transactionScoped && ((_a2 = options == null ? void 0 : options.experimental) == null ? void 0 : _a2.includeState)) {
21649
+ throw new Error(
21650
+ "experimental.includeState is not supported for nested transactions"
21651
+ );
21652
+ }
21653
+ const includeState = ((_b = options == null ? void 0 : options.experimental) == null ? void 0 : _b.includeState) === true;
21654
+ const stateScope = includeState && stateTransactionContext ? await stateTransactionContext.enter() : void 0;
21655
+ try {
21656
+ const transaction = includeState ? await (() => {
21657
+ const beginStateTransaction = ctx.nativeDatabaseProvider && nativeStateTransactionOpeners.get(
21658
+ ctx.nativeDatabaseProvider
21659
+ );
21660
+ if (!beginStateTransaction) {
21661
+ throw new Error(
21662
+ "experimental.includeState is only supported by RivetKit's embedded database provider"
21663
+ );
21664
+ }
21665
+ return beginStateTransaction(
21666
+ options == null ? void 0 : options.timeout,
21667
+ stateScope
21668
+ );
21669
+ })() : await db2.beginTransaction(
21670
+ options == null ? void 0 : options.timeout,
21671
+ options == null ? void 0 : options.name
21672
+ );
21673
+ const tx = createClient(transaction, true);
21674
+ try {
21675
+ const result = await callback(tx);
21676
+ await transaction.commit();
21677
+ return result;
21678
+ } catch (error46) {
21679
+ try {
21680
+ await transaction.rollback();
21681
+ } catch {
21682
+ }
21683
+ throw error46;
21684
+ }
21685
+ } finally {
21686
+ if (stateScope !== void 0) {
21687
+ stateTransactionContext == null ? void 0 : stateTransactionContext.exit(stateScope);
21688
+ }
21689
+ }
21690
+ },
21691
+ close: async () => {
21692
+ if (!closed) {
21693
+ closed = true;
21694
+ await db2.close();
21695
+ }
21696
+ },
21697
+ nativeMetrics: () => {
21698
+ var _a2;
21699
+ return ((_a2 = db2.nativeMetrics) == null ? void 0 : _a2.call(db2)) ?? null;
21700
+ }
21701
+ };
21702
+ if (!transactionScoped) {
21703
+ nativeStateTransactionClientBinders.set(
21704
+ client2,
21705
+ (context) => createClient(target, false, context)
21706
+ );
21707
+ }
21708
+ return client2;
21709
+ };
21710
+ const client = createClient(db2);
21711
+ return client;
21712
+ },
21713
+ onMigrate: async (client) => {
21714
+ if (onMigrate) {
21715
+ await withMigrationSavepoint(
21716
+ client,
21717
+ (leased) => onMigrate(leased)
21718
+ );
21719
+ }
21720
+ }
21721
+ };
21722
+ return provider;
21723
+ }
21724
+ function rowToObject(row, columns) {
21725
+ const rowObj = {};
21726
+ for (let i = 0; i < columns.length; i++) {
21727
+ rowObj[columns[i]] = row[i];
21728
+ }
21729
+ return rowObj;
21730
+ }
21731
+ async function execMultiStatement(db2, query) {
21732
+ const results = [];
21733
+ let columnNames = null;
21734
+ await db2.exec(query, (row, columns) => {
21735
+ if (!columnNames) {
21736
+ columnNames = columns;
21737
+ }
21738
+ results.push(rowToObject(row, columnNames));
21739
+ });
21740
+ return results;
21741
+ }
21742
+ async function withMigrationSavepoint(client, callback) {
21743
+ return await client.transaction(
21744
+ async (transaction) => {
21745
+ await transaction.execute("SAVEPOINT __rivet_on_migrate");
21746
+ try {
21747
+ const result = await callback(transaction);
21748
+ await transaction.execute(
21749
+ "RELEASE SAVEPOINT __rivet_on_migrate"
21750
+ );
21751
+ return result;
21752
+ } catch (error46) {
21753
+ try {
21754
+ await transaction.execute(
21755
+ "ROLLBACK TO SAVEPOINT __rivet_on_migrate"
21756
+ );
21757
+ } finally {
21758
+ await transaction.execute(
21759
+ "RELEASE SAVEPOINT __rivet_on_migrate"
21760
+ );
21761
+ }
21762
+ throw error46;
21763
+ }
21764
+ },
21765
+ {
21766
+ name: "rivetkit-migration",
21767
+ timeout: MIGRATION_TRANSACTION_TIMEOUT_MS
21768
+ }
21769
+ );
21770
+ }
21771
+
21447
21772
  // ../../../shared/typescript/virtual-websocket/dist/mod.js
21448
21773
  var VirtualWebSocket = class {
21449
21774
  static CONNECTING = 0;
@@ -22677,7 +23002,6 @@ onChange.unsubscribe = (proxy) => proxy?.[UNSUBSCRIBE] ?? proxy;
22677
23002
  var source_default = onChange;
22678
23003
 
22679
23004
  // ../rivetkit/dist/tsup/mod.js
22680
- var import_meta = {};
22681
23005
  function loggerWithoutContext() {
22682
23006
  return getLogger("actor-runtime");
22683
23007
  }
@@ -23764,11 +24088,33 @@ function wrapJsNativeDatabase(database) {
23764
24088
  release();
23765
24089
  }
23766
24090
  },
23767
- async beginTransaction(timeoutMs) {
24091
+ async beginTransaction(timeoutMs, name) {
23768
24092
  const release = gate.enter();
23769
24093
  let transaction;
23770
24094
  try {
23771
- transaction = await database.beginTransaction(timeoutMs);
24095
+ transaction = await database.beginTransaction(timeoutMs, name);
24096
+ } catch (error46) {
24097
+ enrichNativeDatabaseError(database, error46);
24098
+ } finally {
24099
+ release();
24100
+ }
24101
+ return wrapTransaction(database, transaction, gate, (result) => {
24102
+ if (result.lastInsertRowId !== void 0) {
24103
+ lastInsertRowId = result.lastInsertRowId;
24104
+ }
24105
+ });
24106
+ },
24107
+ async beginStateTransaction(timeoutMs, context) {
24108
+ if (!database.beginStateTransaction) {
24109
+ throw new Error("actor state transactions are not configured");
24110
+ }
24111
+ const release = gate.enter();
24112
+ let transaction;
24113
+ try {
24114
+ transaction = await database.beginStateTransaction(
24115
+ timeoutMs,
24116
+ context
24117
+ );
23772
24118
  } catch (error46) {
23773
24119
  enrichNativeDatabaseError(database, error46);
23774
24120
  } finally {
@@ -23875,45 +24221,37 @@ var nodeChildProcess;
23875
24221
  var nodeStream;
23876
24222
  var nodeUrl;
23877
24223
  var hasImportedDependencies = false;
23878
- function getRequireFn() {
23879
- return (0, import_module.createRequire)(import_meta.url);
24224
+ var fallbackRequire;
24225
+ function loadNodeBuiltin(id) {
24226
+ var _a2;
24227
+ const nodeProcess = globalThis.process;
24228
+ const builtin = (_a2 = nodeProcess == null ? void 0 : nodeProcess.getBuiltinModule) == null ? void 0 : _a2.call(nodeProcess, id);
24229
+ if (builtin !== void 0) {
24230
+ return builtin;
24231
+ }
24232
+ if (!(nodeProcess == null ? void 0 : nodeProcess.execPath)) {
24233
+ throw new Error("Node.js built-ins are not available");
24234
+ }
24235
+ fallbackRequire ??= (0, import_module.createRequire)(nodeProcess.execPath);
24236
+ return fallbackRequire(id);
23880
24237
  }
23881
24238
  function importNodeDependencies() {
23882
24239
  if (hasImportedDependencies) return;
23883
24240
  try {
23884
- const requireFn = getRequireFn();
23885
- nodeCrypto = requireFn(
23886
- /* webpackIgnore: true */
23887
- "node:crypto"
23888
- );
23889
- nodeFsSync = requireFn(
23890
- /* webpackIgnore: true */
23891
- "node:fs"
23892
- );
23893
- nodeFs = requireFn(
23894
- /* webpackIgnore: true */
24241
+ nodeCrypto = loadNodeBuiltin("node:crypto");
24242
+ nodeFsSync = loadNodeBuiltin("node:fs");
24243
+ nodeFs = loadNodeBuiltin(
23895
24244
  "node:fs/promises"
23896
24245
  );
23897
- nodePath = requireFn(
23898
- /* webpackIgnore: true */
23899
- "node:path"
23900
- );
23901
- nodeOs = requireFn(
23902
- /* webpackIgnore: true */
23903
- "node:os"
23904
- );
23905
- nodeChildProcess = requireFn(
23906
- /* webpackIgnore: true */
24246
+ nodePath = loadNodeBuiltin("node:path");
24247
+ nodeOs = loadNodeBuiltin("node:os");
24248
+ nodeChildProcess = loadNodeBuiltin(
23907
24249
  "node:child_process"
23908
24250
  );
23909
- nodeStream = requireFn(
23910
- /* webpackIgnore: true */
24251
+ nodeStream = loadNodeBuiltin(
23911
24252
  "node:stream/promises"
23912
24253
  );
23913
- nodeUrl = requireFn(
23914
- /* webpackIgnore: true */
23915
- "node:url"
23916
- );
24254
+ nodeUrl = loadNodeBuiltin("node:url");
23917
24255
  hasImportedDependencies = true;
23918
24256
  } catch (err) {
23919
24257
  console.warn(
@@ -23960,6 +24298,9 @@ function asNativeWebSocket(handle) {
23960
24298
  function asNativeSqlTransaction(handle) {
23961
24299
  return handle;
23962
24300
  }
24301
+ function asNativeActorStateTransaction(handle) {
24302
+ return handle;
24303
+ }
23963
24304
  function asNativeCancellationToken(handle) {
23964
24305
  return handle;
23965
24306
  }
@@ -24183,6 +24524,9 @@ var NapiCoreRuntime = class {
24183
24524
  actorSetAlarm(ctx, timestampMs) {
24184
24525
  asNativeActorContext(ctx).setAlarm(timestampMs);
24185
24526
  }
24527
+ async actorSetRunWakeAt(ctx, timestampMs) {
24528
+ await asNativeActorContext(ctx).setRunWakeAt(timestampMs);
24529
+ }
24186
24530
  actorRequestSave(ctx, opts) {
24187
24531
  asNativeActorContext(ctx).requestSave(opts);
24188
24532
  }
@@ -24343,9 +24687,10 @@ var NapiCoreRuntime = class {
24343
24687
  );
24344
24688
  return results.map(normalizeRuntimeSqlExecuteResult);
24345
24689
  }
24346
- async actorSqlBeginTransaction(ctx, timeoutMs) {
24690
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
24347
24691
  return await this.#actorSql(ctx).beginTransaction(
24348
- timeoutMs
24692
+ timeoutMs,
24693
+ name
24349
24694
  );
24350
24695
  }
24351
24696
  async actorSqlTransactionExec(transaction, sql) {
@@ -24364,6 +24709,26 @@ var NapiCoreRuntime = class {
24364
24709
  async actorSqlTransactionRollback(transaction) {
24365
24710
  await asNativeSqlTransaction(transaction).rollback();
24366
24711
  }
24712
+ async actorBeginStateTransaction(ctx, timeoutMs) {
24713
+ return await asNativeActorContext(ctx).beginStateTransaction(
24714
+ timeoutMs
24715
+ );
24716
+ }
24717
+ async actorStateTransactionExecute(transaction, sql, params) {
24718
+ const result = await asNativeActorStateTransaction(transaction).execute(
24719
+ sql,
24720
+ toNapiSqlBindParams(params)
24721
+ );
24722
+ return normalizeRuntimeSqlExecuteResult(result);
24723
+ }
24724
+ async actorStateTransactionCommit(transaction, payload) {
24725
+ await asNativeActorStateTransaction(transaction).commit(
24726
+ toNapiStateDeltaPayload(payload)
24727
+ );
24728
+ }
24729
+ async actorStateTransactionRollback(transaction) {
24730
+ await asNativeActorStateTransaction(transaction).rollback();
24731
+ }
24367
24732
  async actorSqlQuery(ctx, sql, params) {
24368
24733
  return await this.#actorSql(ctx).query(
24369
24734
  sql,
@@ -24421,6 +24786,13 @@ var NapiCoreRuntime = class {
24421
24786
  signal ? asNativeCancellationToken(signal) : signal
24422
24787
  );
24423
24788
  }
24789
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
24790
+ return await asNativeActorContext(ctx).queue().completePersisted(
24791
+ messageId,
24792
+ expectedName,
24793
+ response == null ? response : toNapiBuffer(response)
24794
+ );
24795
+ }
24424
24796
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
24425
24797
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
24426
24798
  name,
@@ -24607,6 +24979,164 @@ function validationError(target, issues) {
24607
24979
  metadata: { issues }
24608
24980
  });
24609
24981
  }
24982
+ function runUnavailable(actorId, reason) {
24983
+ return new RivetError(
24984
+ "actor",
24985
+ "run_handler_unavailable",
24986
+ `Run handler control is unavailable for actor ${actorId}: ${reason}.`,
24987
+ {
24988
+ public: true,
24989
+ statusCode: 409,
24990
+ metadata: { actorId, reason }
24991
+ }
24992
+ );
24993
+ }
24994
+ function notifyStateChanged(state) {
24995
+ const waiters = [...state.waiters];
24996
+ state.waiters.clear();
24997
+ for (const waiter of waiters) {
24998
+ waiter();
24999
+ }
25000
+ }
25001
+ function waitForStateChange(state) {
25002
+ return new Promise((resolve) => {
25003
+ state.waiters.add(resolve);
25004
+ });
25005
+ }
25006
+ var RunHandlerCoordinator = class {
25007
+ #run;
25008
+ #states = /* @__PURE__ */ new Map();
25009
+ constructor(run) {
25010
+ this.#run = run;
25011
+ }
25012
+ get inspectorKind() {
25013
+ return getRunInspectorKind(this.#run);
25014
+ }
25015
+ async run(actorId, restart, callback) {
25016
+ const state = this.#getOrCreate(actorId);
25017
+ state.restart = restart;
25018
+ this.#initializeInspector(actorId, state);
25019
+ state.queued += 1;
25020
+ const blockedGeneration = state.exclusive ? state.exclusiveGeneration : void 0;
25021
+ try {
25022
+ while (!state.closed && (state.exclusive || state.active)) {
25023
+ await waitForStateChange(state);
25024
+ }
25025
+ } finally {
25026
+ state.queued -= 1;
25027
+ }
25028
+ if (state.closed) {
25029
+ return "closed";
25030
+ }
25031
+ if (blockedGeneration !== void 0 && state.exclusiveGeneration === blockedGeneration && state.exclusiveOutcome === "failure") {
25032
+ return "suppressed";
25033
+ }
25034
+ state.active = true;
25035
+ try {
25036
+ await callback();
25037
+ return "ran";
25038
+ } finally {
25039
+ state.active = false;
25040
+ notifyStateChanged(state);
25041
+ }
25042
+ }
25043
+ getInspector(actorId, restart) {
25044
+ var _a2;
25045
+ const state = this.#getOrCreate(actorId);
25046
+ state.restart = restart;
25047
+ this.#initializeInspector(actorId, state);
25048
+ return (_a2 = state.inspector) == null ? void 0 : _a2.inspector;
25049
+ }
25050
+ destroy(actorId) {
25051
+ var _a2, _b;
25052
+ const state = this.#states.get(actorId);
25053
+ if (!state) return;
25054
+ state.closed = true;
25055
+ (_b = (_a2 = state.inspector) == null ? void 0 : _a2.dispose) == null ? void 0 : _b.call(_a2);
25056
+ state.inspector = void 0;
25057
+ notifyStateChanged(state);
25058
+ this.#states.delete(actorId);
25059
+ }
25060
+ #control(actorId, state) {
25061
+ return {
25062
+ run: {
25063
+ withInactive: async (options, callback) => {
25064
+ if (state.closed) {
25065
+ throw runUnavailable(actorId, "actor is destroyed");
25066
+ }
25067
+ if (state.active || state.queued > 0 || state.exclusive) {
25068
+ throw runUnavailable(
25069
+ actorId,
25070
+ "the run handler is active or waiting to start"
25071
+ );
25072
+ }
25073
+ state.exclusive = true;
25074
+ state.exclusiveGeneration += 1;
25075
+ state.exclusiveOutcome = void 0;
25076
+ try {
25077
+ const result = await callback();
25078
+ if (state.closed) {
25079
+ throw runUnavailable(actorId, "actor is destroyed");
25080
+ }
25081
+ state.exclusiveOutcome = "success";
25082
+ if (options.restartOnSuccess && state.queued === 0) {
25083
+ if (!state.restart) {
25084
+ throw runUnavailable(
25085
+ actorId,
25086
+ "the runtime restart callback is not available"
25087
+ );
25088
+ }
25089
+ await state.restart();
25090
+ }
25091
+ return result;
25092
+ } catch (error46) {
25093
+ state.exclusiveOutcome = "failure";
25094
+ throw error46;
25095
+ } finally {
25096
+ state.exclusive = false;
25097
+ notifyStateChanged(state);
25098
+ }
25099
+ }
25100
+ }
25101
+ };
25102
+ }
25103
+ #getOrCreate(actorId) {
25104
+ let state = this.#states.get(actorId);
25105
+ if (!state) {
25106
+ state = {
25107
+ active: false,
25108
+ closed: false,
25109
+ exclusive: false,
25110
+ exclusiveGeneration: 0,
25111
+ inspectorInitialized: false,
25112
+ queued: 0,
25113
+ waiters: /* @__PURE__ */ new Set()
25114
+ };
25115
+ this.#states.set(actorId, state);
25116
+ }
25117
+ return state;
25118
+ }
25119
+ #initializeInspector(actorId, state) {
25120
+ if (state.inspectorInitialized) return;
25121
+ const inspector = createRunInspector(this.#run, {
25122
+ actorId,
25123
+ control: this.#control(actorId, state)
25124
+ });
25125
+ if (this.inspectorKind === "workflow") {
25126
+ const workflow = inspector === void 0 ? void 0 : inspector.inspector.workflow;
25127
+ if (!workflow || typeof workflow.getHistory !== "function" || typeof workflow.getState !== "function" || typeof workflow.onHistoryUpdated !== "function" || typeof workflow.replayFromStep !== "function") {
25128
+ throw new TypeError(
25129
+ `defineRunHandler createInspector returned an invalid workflow adapter for actor ${actorId}`
25130
+ );
25131
+ }
25132
+ }
25133
+ state.inspector = inspector;
25134
+ state.inspectorInitialized = true;
25135
+ }
25136
+ };
25137
+ function asWasmConstructors(bindings) {
25138
+ return bindings;
25139
+ }
24610
25140
  function asWasmRegistry(handle) {
24611
25141
  return handle;
24612
25142
  }
@@ -24731,10 +25261,10 @@ function childHandle(handle, name) {
24731
25261
  }
24732
25262
  var WasmCoreRuntime = class {
24733
25263
  kind = "wasm";
24734
- #bindings;
25264
+ #constructors;
24735
25265
  #sql = /* @__PURE__ */ new WeakMap();
24736
25266
  constructor(bindings) {
24737
- this.#bindings = bindings;
25267
+ this.#constructors = asWasmConstructors(bindings);
24738
25268
  }
24739
25269
  #actorSql(ctx) {
24740
25270
  const wasmCtx = asWasmActorContext(ctx);
@@ -24747,7 +25277,7 @@ var WasmCoreRuntime = class {
24747
25277
  }
24748
25278
  createRegistry() {
24749
25279
  return callWasmSync(
24750
- () => asRegistryHandle2(new this.#bindings.CoreRegistry())
25280
+ () => asRegistryHandle2(new this.#constructors.CoreRegistry())
24751
25281
  );
24752
25282
  }
24753
25283
  registerActor(registry2, name, factory) {
@@ -24802,13 +25332,13 @@ var WasmCoreRuntime = class {
24802
25332
  createActorFactory(callbacks, config3) {
24803
25333
  return callWasmSync(
24804
25334
  () => asActorFactoryHandle2(
24805
- new this.#bindings.ActorFactory(callbacks, config3)
25335
+ new this.#constructors.ActorFactory(callbacks, config3)
24806
25336
  )
24807
25337
  );
24808
25338
  }
24809
25339
  createCancellationToken() {
24810
25340
  return callWasmSync(
24811
- () => new this.#bindings.CancellationToken()
25341
+ () => new this.#constructors.CancellationToken()
24812
25342
  );
24813
25343
  }
24814
25344
  cancellationTokenAborted(token) {
@@ -24843,6 +25373,13 @@ var WasmCoreRuntime = class {
24843
25373
  optionalWasmNumber(timestampMs)
24844
25374
  );
24845
25375
  }
25376
+ async actorSetRunWakeAt(ctx, timestampMs) {
25377
+ await callHandleAsync(
25378
+ asWasmActorContext(ctx),
25379
+ "setRunWakeAt",
25380
+ optionalWasmNumber(timestampMs)
25381
+ );
25382
+ }
24846
25383
  actorRequestSave(ctx, opts) {
24847
25384
  callHandle(asWasmActorContext(ctx), "requestSave", opts);
24848
25385
  }
@@ -25057,9 +25594,9 @@ var WasmCoreRuntime = class {
25057
25594
  );
25058
25595
  return results.map(normalizeRuntimeSqlExecuteResult);
25059
25596
  }
25060
- async actorSqlBeginTransaction(ctx, timeoutMs) {
25597
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
25061
25598
  return await callWasm(
25062
- () => this.#actorSql(ctx).beginTransaction(timeoutMs)
25599
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs, name)
25063
25600
  );
25064
25601
  }
25065
25602
  async actorSqlTransactionExec(transaction, sql) {
@@ -25083,6 +25620,27 @@ var WasmCoreRuntime = class {
25083
25620
  () => transaction.rollback()
25084
25621
  );
25085
25622
  }
25623
+ async actorBeginStateTransaction(ctx, timeoutMs) {
25624
+ return await callWasm(
25625
+ () => asWasmActorContext(ctx).beginStateTransaction(timeoutMs)
25626
+ );
25627
+ }
25628
+ async actorStateTransactionExecute(transaction, sql, params) {
25629
+ const result = await callWasm(
25630
+ () => transaction.execute(sql, params)
25631
+ );
25632
+ return normalizeRuntimeSqlExecuteResult(result);
25633
+ }
25634
+ async actorStateTransactionCommit(transaction, payload) {
25635
+ await callWasm(
25636
+ () => transaction.commit(payload)
25637
+ );
25638
+ }
25639
+ async actorStateTransactionRollback(transaction) {
25640
+ await callWasm(
25641
+ () => transaction.rollback()
25642
+ );
25643
+ }
25086
25644
  async actorSqlQuery(ctx, sql, params) {
25087
25645
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
25088
25646
  }
@@ -25155,6 +25713,16 @@ var WasmCoreRuntime = class {
25155
25713
  signal
25156
25714
  );
25157
25715
  }
25716
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
25717
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
25718
+ return await callHandleAsync(
25719
+ queue2,
25720
+ "completePersisted",
25721
+ messageId,
25722
+ expectedName,
25723
+ response
25724
+ );
25725
+ }
25158
25726
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
25159
25727
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
25160
25728
  return optionalBytes(
@@ -25363,7 +25931,7 @@ function unwrapProxy(value) {
25363
25931
  }
25364
25932
  return current;
25365
25933
  }
25366
- function isPlainObject3(value) {
25934
+ function isPlainObject4(value) {
25367
25935
  const proto = Object.getPrototypeOf(value);
25368
25936
  return proto === Object.prototype || proto === null;
25369
25937
  }
@@ -25416,7 +25984,7 @@ function unwrapDeep(value, seen) {
25416
25984
  }
25417
25985
  return unwrapped;
25418
25986
  }
25419
- if (isPlainObject3(unwrapped)) {
25987
+ if (isPlainObject4(unwrapped)) {
25420
25988
  for (const key of Object.keys(unwrapped)) {
25421
25989
  const child = unwrapDeep(unwrapped[key], seen);
25422
25990
  if (child !== unwrapped[key]) {
@@ -25573,6 +26141,14 @@ function stateMutationReentrantError() {
25573
26141
  "State mutations are not allowed inside onStateChange."
25574
26142
  );
25575
26143
  }
26144
+ function stateTransactionConflictError() {
26145
+ return new RivetError(
26146
+ "actor",
26147
+ "state_transaction_conflict",
26148
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
26149
+ { public: true, statusCode: 409 }
26150
+ );
26151
+ }
25576
26152
  function databaseNotConfiguredError() {
25577
26153
  return new RivetError(
25578
26154
  "actor",
@@ -25589,6 +26165,14 @@ function databaseClientNotReadyError() {
25589
26165
  { public: true }
25590
26166
  );
25591
26167
  }
26168
+ function runHandlerNotConfiguredError() {
26169
+ return new RivetError(
26170
+ "actor",
26171
+ "run_handler_unavailable",
26172
+ "Cannot schedule a run wake because this actor does not define a run handler.",
26173
+ { public: true, statusCode: 409 }
26174
+ );
26175
+ }
25592
26176
  function stateNotEnabledError() {
25593
26177
  return new RivetError(
25594
26178
  "actor",
@@ -25691,10 +26275,11 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
25691
26275
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
25692
26276
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
25693
26277
  executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
25694
- beginTransaction: async (timeoutMs) => {
26278
+ beginTransaction: async (timeoutMs, name) => {
25695
26279
  const transaction = await runtime.actorSqlBeginTransaction(
25696
26280
  ctx,
25697
- timeoutMs
26281
+ timeoutMs,
26282
+ name
25698
26283
  );
25699
26284
  return {
25700
26285
  exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
@@ -25707,6 +26292,38 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
25707
26292
  rollback: () => runtime.actorSqlTransactionRollback(transaction)
25708
26293
  };
25709
26294
  },
26295
+ beginStateTransaction: async (timeoutMs, context) => {
26296
+ const scope = context;
26297
+ if (!scope) {
26298
+ throw new Error(
26299
+ "actor state transaction context is not configured"
26300
+ );
26301
+ }
26302
+ const transaction = await runtime.actorBeginStateTransaction(
26303
+ ctx,
26304
+ timeoutMs
26305
+ );
26306
+ return {
26307
+ exec: async () => {
26308
+ throw new Error(
26309
+ "actor state transactions only support single-statement execute calls"
26310
+ );
26311
+ },
26312
+ execute: (sql, params) => runtime.actorStateTransactionExecute(
26313
+ transaction,
26314
+ sql,
26315
+ params
26316
+ ),
26317
+ commit: async () => {
26318
+ await runtime.actorStateTransactionCommit(
26319
+ transaction,
26320
+ scope.actorContext.serializeForTick("save")
26321
+ );
26322
+ scope.committed = true;
26323
+ },
26324
+ rollback: () => runtime.actorStateTransactionRollback(transaction)
26325
+ };
26326
+ },
25710
26327
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
25711
26328
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
25712
26329
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -26087,12 +26704,16 @@ var NativeConnAdapter = class {
26087
26704
  #schemas;
26088
26705
  #ctx;
26089
26706
  #queueHibernationRemoval;
26090
- constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval) {
26707
+ #assertCanMutateState;
26708
+ #stateProxy;
26709
+ #stateProxyTarget;
26710
+ constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval, assertCanMutateState) {
26091
26711
  this.#runtime = runtime;
26092
26712
  this.#conn = conn;
26093
26713
  this.#schemas = schemas;
26094
26714
  this.#ctx = ctx;
26095
26715
  this.#queueHibernationRemoval = queueHibernationRemoval;
26716
+ this.#assertCanMutateState = assertCanMutateState;
26096
26717
  this[CONN_STATE_MANAGER_SYMBOL] = {
26097
26718
  stateEnabled: true,
26098
26719
  get state() {
@@ -26118,29 +26739,35 @@ var NativeConnAdapter = class {
26118
26739
  if (!this.#ctx) {
26119
26740
  return this.#createStateProxy(nextState);
26120
26741
  }
26121
- const connState = getNativeConnPersistState(
26122
- this.#runtime,
26123
- this.#ctx,
26124
- this.#conn
26125
- );
26126
- if (connState.stateProxy === void 0 || connState.stateProxyTarget !== nextState) {
26127
- connState.stateProxyTarget = nextState;
26128
- connState.stateProxy = this.#createStateProxy(nextState);
26742
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
26743
+ this.#stateProxyTarget = nextState;
26744
+ this.#stateProxy = this.#createStateProxy(nextState);
26129
26745
  }
26130
- return connState.stateProxy;
26746
+ return this.#stateProxy;
26131
26747
  }
26132
26748
  #createStateProxy(state) {
26749
+ const assertCurrentState = () => {
26750
+ var _a2;
26751
+ (_a2 = this.#assertCanMutateState) == null ? void 0 : _a2.call(this);
26752
+ if (this.#ctx && this.#readState() !== state) {
26753
+ throw stateTransactionConflictError();
26754
+ }
26755
+ };
26133
26756
  return createWriteThroughProxy(
26134
26757
  state,
26135
26758
  (nextValue) => {
26759
+ assertCurrentState();
26136
26760
  this.#writeState(nextValue, { writeNative: true });
26137
26761
  },
26138
26762
  (newValue) => {
26763
+ assertCurrentState();
26139
26764
  assertJsonCompatValue(newValue);
26140
26765
  }
26141
26766
  );
26142
26767
  }
26143
26768
  set state(value) {
26769
+ var _a2;
26770
+ (_a2 = this.#assertCanMutateState) == null ? void 0 : _a2.call(this);
26144
26771
  const nextValue = unwrapWriteThroughProxy(value);
26145
26772
  assertJsonCompatValue(nextValue);
26146
26773
  this.#writeState(nextValue, { writeNative: true });
@@ -26466,8 +27093,9 @@ var NativeKvAdapter = class {
26466
27093
  };
26467
27094
  function wrapQueueMessage(message, schemas) {
26468
27095
  const name = callNativeSync(() => message.name());
27096
+ const id = callNativeSync(() => message.id());
26469
27097
  return {
26470
- id: Number(callNativeSync(() => message.id())),
27098
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
26471
27099
  name,
26472
27100
  body: validateQueueBody(
26473
27101
  schemas,
@@ -26605,6 +27233,25 @@ var NativeQueueAdapter = class {
26605
27233
  cleanup == null ? void 0 : cleanup();
26606
27234
  }
26607
27235
  }
27236
+ async waitForAvailable(names, options) {
27237
+ await this.waitForNamesAvailable(names ?? [], options);
27238
+ }
27239
+ async complete(message, response) {
27240
+ const validatedResponse = validateQueueComplete(
27241
+ this.#schemas,
27242
+ message.name,
27243
+ response
27244
+ );
27245
+ await callNative(
27246
+ () => this.#runtime.actorQueueCompletePersisted(
27247
+ this.#ctx,
27248
+ BigInt(message.id),
27249
+ message.name,
27250
+ encodeValue(validatedResponse)
27251
+ )
27252
+ );
27253
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
27254
+ }
26608
27255
  async enqueueAndWait(name, body, options) {
26609
27256
  const validatedBody = validateQueueBody(this.#schemas, name, body);
26610
27257
  const { token, cleanup } = await createCancellationTokenHandle(
@@ -27041,10 +27688,12 @@ var NativeConnectionMap = class {
27041
27688
  #runtime;
27042
27689
  #ctx;
27043
27690
  #schemas;
27044
- constructor(runtime, ctx, schemas) {
27691
+ #assertCanMutateState;
27692
+ constructor(runtime, ctx, schemas, assertCanMutateState) {
27045
27693
  this.#runtime = runtime;
27046
27694
  this.#ctx = ctx;
27047
27695
  this.#schemas = schemas;
27696
+ this.#assertCanMutateState = assertCanMutateState;
27048
27697
  }
27049
27698
  #connToAdapter(conn) {
27050
27699
  return new NativeConnAdapter(
@@ -27057,7 +27706,8 @@ var NativeConnectionMap = class {
27057
27706
  this.#ctx,
27058
27707
  connId
27059
27708
  )
27060
- )
27709
+ ),
27710
+ this.#assertCanMutateState
27061
27711
  );
27062
27712
  }
27063
27713
  get size() {
@@ -27116,17 +27766,20 @@ var ActorContextHandleAdapter = class {
27116
27766
  #queue;
27117
27767
  #request;
27118
27768
  #schedule;
27119
- #sql;
27120
- #runHandlerActiveProvider;
27769
+ #run;
27770
+ #runHandlerConfigured;
27121
27771
  #onStateChange;
27122
27772
  #stateEnabled;
27123
- constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, runHandlerActiveProvider, onStateChange, dispatchCancelToken) {
27773
+ #stateProxy;
27774
+ #stateProxyTarget;
27775
+ #stateTransactionOwner = /* @__PURE__ */ Symbol("actor-state-transaction-owner");
27776
+ constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
27124
27777
  this.#runtime = runtime;
27125
27778
  this.#ctx = ctx;
27126
27779
  this.#clientFactory = clientFactory;
27127
27780
  this.#schemas = schemas;
27128
27781
  this.#dispatchCancelToken = dispatchCancelToken;
27129
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
27782
+ this.#runHandlerConfigured = runHandlerConfigured;
27130
27783
  this.#onStateChange = onStateChange;
27131
27784
  this.#stateEnabled = stateEnabled;
27132
27785
  if (databaseProvider) {
@@ -27143,12 +27796,6 @@ var ActorContextHandleAdapter = class {
27143
27796
  }
27144
27797
  return this.#kv;
27145
27798
  }
27146
- get sql() {
27147
- if (!this.#sql) {
27148
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
27149
- }
27150
- return this.#sql;
27151
- }
27152
27799
  async actorRuntimeSocket() {
27153
27800
  return await callNative(
27154
27801
  () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
@@ -27164,7 +27811,7 @@ var ActorContextHandleAdapter = class {
27164
27811
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
27165
27812
  const cachedClient = runtimeState.databaseClient;
27166
27813
  if (cachedClient) {
27167
- this.#db = cachedClient.client;
27814
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
27168
27815
  return this.#db;
27169
27816
  }
27170
27817
  throw databaseClientNotReadyError();
@@ -27179,22 +27826,28 @@ var ActorContextHandleAdapter = class {
27179
27826
  if (!this.#stateEnabled) {
27180
27827
  throw stateNotEnabledError();
27181
27828
  }
27182
- const actorState = getNativePersistState(this.#runtime, this.#ctx);
27183
27829
  const nextState = this.#readState();
27184
- if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
27185
- actorState.stateProxyTarget = nextState;
27186
- actorState.stateProxy = createWriteThroughProxy(
27830
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
27831
+ const assertCurrentState = () => {
27832
+ this.#assertCanMutateState();
27833
+ if (this.#readState() !== nextState) {
27834
+ throw stateTransactionConflictError();
27835
+ }
27836
+ };
27837
+ this.#stateProxyTarget = nextState;
27838
+ this.#stateProxy = createWriteThroughProxy(
27187
27839
  nextState,
27188
27840
  (nextValue) => {
27841
+ assertCurrentState();
27189
27842
  this.#writeState(nextValue, { scheduleSave: true });
27190
27843
  },
27191
27844
  (newValue) => {
27192
- this.#assertCanMutateState();
27845
+ assertCurrentState();
27193
27846
  assertJsonCompatValue(newValue);
27194
27847
  }
27195
27848
  );
27196
27849
  }
27197
- return actorState.stateProxy;
27850
+ return this.#stateProxy;
27198
27851
  }
27199
27852
  set state(value) {
27200
27853
  if (!this.#stateEnabled) {
@@ -27237,6 +27890,26 @@ var ActorContextHandleAdapter = class {
27237
27890
  }
27238
27891
  return this.#queue;
27239
27892
  }
27893
+ get run() {
27894
+ if (!this.#run) {
27895
+ this.#run = {
27896
+ setWakeAt: async (timestamp) => {
27897
+ if (timestamp !== null && !this.#runHandlerConfigured) {
27898
+ throw runHandlerNotConfiguredError();
27899
+ }
27900
+ if (timestamp !== null && (!Number.isSafeInteger(timestamp) || timestamp < 0)) {
27901
+ throw new TypeError(
27902
+ "Run wake timestamp must be a non-negative safe integer or null"
27903
+ );
27904
+ }
27905
+ await callNative(
27906
+ () => this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp)
27907
+ );
27908
+ }
27909
+ };
27910
+ }
27911
+ return this.#run;
27912
+ }
27240
27913
  get schedule() {
27241
27914
  if (!this.#schedule) {
27242
27915
  this.#schedule = new NativeScheduleAdapter(
@@ -27271,7 +27944,8 @@ var ActorContextHandleAdapter = class {
27271
27944
  this.#connMap = new NativeConnectionMap(
27272
27945
  this.#runtime,
27273
27946
  this.#ctx,
27274
- this.#schemas
27947
+ this.#schemas,
27948
+ () => this.#assertCanMutateState()
27275
27949
  );
27276
27950
  }
27277
27951
  return this.#connMap;
@@ -27340,11 +28014,11 @@ var ActorContextHandleAdapter = class {
27340
28014
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
27341
28015
  const cachedClient = runtimeState.databaseClient;
27342
28016
  if (cachedClient) {
27343
- this.#db = cachedClient.client;
28017
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
27344
28018
  return this.#db;
27345
28019
  }
27346
28020
  const actorId = this.actorId;
27347
- const client = await this.#databaseProvider.createClient({
28021
+ const createdClient = await this.#databaseProvider.createClient({
27348
28022
  actorId,
27349
28023
  kv: {
27350
28024
  batchPut: async (entries) => {
@@ -27365,21 +28039,126 @@ var ActorContextHandleAdapter = class {
27365
28039
  log: {
27366
28040
  debug: (obj) => logger22().debug(obj)
27367
28041
  },
27368
- nativeDatabaseProvider: {
27369
- open: async (requestedActorId) => {
27370
- void requestedActorId;
27371
- return getOrCreateNativeSqlDatabase(
27372
- this.#runtime,
27373
- this.#ctx
27374
- );
27375
- }
27376
- }
28042
+ nativeDatabaseProvider: registerNativeStateTransactionOpener(
28043
+ {
28044
+ open: async (requestedActorId) => {
28045
+ void requestedActorId;
28046
+ return getOrCreateNativeSqlDatabase(
28047
+ this.#runtime,
28048
+ this.#ctx
28049
+ );
28050
+ }
28051
+ },
28052
+ async (timeoutMs, context) => await getOrCreateNativeSqlDatabase(
28053
+ this.#runtime,
28054
+ this.#ctx
28055
+ ).beginStateTransaction(timeoutMs, context)
28056
+ )
27377
28057
  });
27378
28058
  runtimeState.databaseClient = {
27379
- client
28059
+ client: createdClient
27380
28060
  };
27381
- this.#db = client;
27382
- return client;
28061
+ this.#db = this.#bindDatabaseClient(createdClient);
28062
+ return this.#db;
28063
+ }
28064
+ #bindDatabaseClient(client) {
28065
+ return bindNativeStateTransactionContext(client, {
28066
+ enter: async () => await this.#enterStateTransaction(),
28067
+ exit: (scope) => this.#exitStateTransaction(
28068
+ scope
28069
+ )
28070
+ });
28071
+ }
28072
+ async #enterStateTransaction() {
28073
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28074
+ let pendingOwners = actorState.pendingStateTransactionOwners;
28075
+ if (!pendingOwners) {
28076
+ pendingOwners = /* @__PURE__ */ new Set();
28077
+ actorState.pendingStateTransactionOwners = pendingOwners;
28078
+ }
28079
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner || pendingOwners.has(this.#stateTransactionOwner)) {
28080
+ throw stateTransactionConflictError();
28081
+ }
28082
+ pendingOwners.add(this.#stateTransactionOwner);
28083
+ const predecessor = actorState.stateTransactionTail ?? Promise.resolve();
28084
+ let release;
28085
+ const hold = new Promise((resolve) => {
28086
+ release = resolve;
28087
+ });
28088
+ actorState.stateTransactionTail = predecessor.then(
28089
+ async () => await hold
28090
+ );
28091
+ try {
28092
+ await predecessor;
28093
+ pendingOwners.delete(this.#stateTransactionOwner);
28094
+ actorState.activeStateTransactionOwner = this.#stateTransactionOwner;
28095
+ return {
28096
+ actorContext: this,
28097
+ actorStateBaseline: this.#stateEnabled ? structuredClone(this.#readState()) : void 0,
28098
+ connectionStateBaselines: new Map(
28099
+ callNativeSync(
28100
+ () => this.#runtime.actorConns(this.#ctx)
28101
+ ).map((conn) => [
28102
+ callNativeSync(() => this.#runtime.connId(conn)),
28103
+ new Uint8Array(
28104
+ callNativeSync(() => this.#runtime.connState(conn))
28105
+ )
28106
+ ])
28107
+ ),
28108
+ committed: false,
28109
+ release
28110
+ };
28111
+ } catch (error46) {
28112
+ pendingOwners.delete(this.#stateTransactionOwner);
28113
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28114
+ actorState.activeStateTransactionOwner = void 0;
28115
+ }
28116
+ release();
28117
+ throw error46;
28118
+ }
28119
+ }
28120
+ #exitStateTransaction(scope) {
28121
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28122
+ try {
28123
+ if (!scope.committed) {
28124
+ this.#restoreStateTransactionBaseline(scope);
28125
+ }
28126
+ } finally {
28127
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28128
+ actorState.activeStateTransactionOwner = void 0;
28129
+ }
28130
+ if (actorState.stateTransactionSaveDeferred) {
28131
+ actorState.stateTransactionSaveDeferred = false;
28132
+ this.#scheduleSave();
28133
+ }
28134
+ scope.release();
28135
+ }
28136
+ }
28137
+ #restoreStateTransactionBaseline(scope) {
28138
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28139
+ if (actorState.pendingSaveHandle !== void 0) {
28140
+ clearImmediate(actorState.pendingSaveHandle);
28141
+ }
28142
+ actorState.pendingSaveHandle = void 0;
28143
+ actorState.saveScheduled = false;
28144
+ if (this.#stateEnabled) {
28145
+ actorState.state = structuredClone(scope.actorStateBaseline);
28146
+ }
28147
+ for (const conn of callNativeSync(
28148
+ () => this.#runtime.actorConns(this.#ctx)
28149
+ )) {
28150
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
28151
+ const baseline = scope.connectionStateBaselines.get(connId);
28152
+ if (baseline === void 0) {
28153
+ continue;
28154
+ }
28155
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
28156
+ const cached2 = actorState.connStates.get(connId);
28157
+ if (cached2) {
28158
+ cached2.state = decodeValue(baseline);
28159
+ }
28160
+ }
28161
+ this.#scheduleSave();
27383
28162
  }
27384
28163
  async prepare() {
27385
28164
  if (!this.#databaseProvider) {
@@ -27397,7 +28176,6 @@ var ActorContextHandleAdapter = class {
27397
28176
  }
27398
28177
  async closeDatabase() {
27399
28178
  this.#db = void 0;
27400
- this.#sql = void 0;
27401
28179
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
27402
28180
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
27403
28181
  }
@@ -27417,6 +28195,7 @@ var ActorContextHandleAdapter = class {
27417
28195
  }
27418
28196
  async saveState(opts) {
27419
28197
  if (opts == null ? void 0 : opts.immediate) {
28198
+ this.#assertCanAwaitStateSave();
27420
28199
  await callNative(
27421
28200
  () => this.#runtime.actorRequestSaveAndWait(this.#ctx, {
27422
28201
  immediate: true
@@ -27437,10 +28216,17 @@ var ActorContextHandleAdapter = class {
27437
28216
  );
27438
28217
  }
27439
28218
  async saveStateAndWorkflowBatch(writes) {
28219
+ this.#assertCanAwaitStateSave();
27440
28220
  await callNative(
27441
28221
  () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
27442
28222
  );
27443
28223
  }
28224
+ #assertCanAwaitStateSave() {
28225
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28226
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28227
+ throw stateTransactionConflictError();
28228
+ }
28229
+ }
27444
28230
  serializeForTick(reason) {
27445
28231
  void reason;
27446
28232
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -27494,10 +28280,6 @@ var ActorContextHandleAdapter = class {
27494
28280
  }
27495
28281
  return promise2;
27496
28282
  }
27497
- runHandlerActive() {
27498
- var _a2;
27499
- return ((_a2 = this.#runHandlerActiveProvider) == null ? void 0 : _a2.call(this)) ?? false;
27500
- }
27501
28283
  internalKeepAwake(run) {
27502
28284
  const promise2 = typeof run === "function" ? run() : run;
27503
28285
  const trackedPromise = promise2.then(
@@ -27579,7 +28361,6 @@ var ActorContextHandleAdapter = class {
27579
28361
  var _a2;
27580
28362
  this.#flushStateChange();
27581
28363
  (_a2 = this.#abortSignalCleanup) == null ? void 0 : _a2.call(this);
27582
- this.#sql = void 0;
27583
28364
  }
27584
28365
  #createActorAbortSignal() {
27585
28366
  const nativeSignal = callNativeSync(
@@ -27613,10 +28394,18 @@ var ActorContextHandleAdapter = class {
27613
28394
  this.#scheduleSave();
27614
28395
  }
27615
28396
  #assertCanMutateState() {
28397
+ var _a2;
27616
28398
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
27617
28399
  if (actorState.isInOnStateChange) {
27618
28400
  throw stateMutationReentrantError();
27619
28401
  }
28402
+ if (actorState.activeStateTransactionOwner !== this.#stateTransactionOwner && (actorState.activeStateTransactionOwner !== void 0 || (((_a2 = actorState.pendingStateTransactionOwners) == null ? void 0 : _a2.size) ?? 0) > 0)) {
28403
+ throw stateTransactionConflictError();
28404
+ }
28405
+ }
28406
+ /** @internal */
28407
+ assertCanMutateState() {
28408
+ this.#assertCanMutateState();
27620
28409
  }
27621
28410
  // Coalesce the request-save and onStateChange work to once per event loop
27622
28411
  // tick. A synchronous burst of mutations (for example
@@ -27638,6 +28427,15 @@ var ActorContextHandleAdapter = class {
27638
28427
  if (!actorState.saveScheduled) {
27639
28428
  return;
27640
28429
  }
28430
+ if (actorState.activeStateTransactionOwner !== void 0) {
28431
+ actorState.saveScheduled = false;
28432
+ if (actorState.pendingSaveHandle !== void 0) {
28433
+ clearImmediate(actorState.pendingSaveHandle);
28434
+ actorState.pendingSaveHandle = void 0;
28435
+ }
28436
+ actorState.stateTransactionSaveDeferred = true;
28437
+ return;
28438
+ }
27641
28439
  actorState.saveScheduled = false;
27642
28440
  if (actorState.pendingSaveHandle !== void 0) {
27643
28441
  clearImmediate(actorState.pendingSaveHandle);
@@ -27761,9 +28559,6 @@ var NativeWorkflowRuntimeAdapter = class {
27761
28559
  }
27762
28560
  };
27763
28561
  }
27764
- isRunHandlerActive() {
27765
- return this.#ctx.runHandlerActive();
27766
- }
27767
28562
  async restartRunHandler() {
27768
28563
  await this.#ctx.restartRunHandler();
27769
28564
  }
@@ -27796,43 +28591,45 @@ var NativeWorkflowRuntimeAdapter = class {
27796
28591
  };
27797
28592
  }
27798
28593
  };
27799
- function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken) {
27800
- return Object.assign(
27801
- new ActorContextHandleAdapter(
28594
+ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
28595
+ const actorContext = new ActorContextHandleAdapter(
28596
+ runtime,
28597
+ ctx,
28598
+ clientFactory,
28599
+ schemas,
28600
+ databaseProvider,
28601
+ request,
28602
+ stateEnabled,
28603
+ onStateChange,
28604
+ dispatchCancelToken,
28605
+ runHandlerConfigured
28606
+ );
28607
+ return Object.assign(actorContext, {
28608
+ conn: new NativeConnAdapter(
27802
28609
  runtime,
27803
- ctx,
27804
- clientFactory,
28610
+ conn,
27805
28611
  schemas,
27806
- databaseProvider,
27807
- request,
27808
- stateEnabled,
27809
- void 0,
27810
- onStateChange,
27811
- dispatchCancelToken
27812
- ),
27813
- {
27814
- conn: new NativeConnAdapter(
27815
- runtime,
27816
- conn,
27817
- schemas,
27818
- ctx,
27819
- (connId) => callNativeSync(
27820
- () => runtime.actorQueueHibernationRemoval(ctx, connId)
27821
- )
27822
- )
27823
- }
27824
- );
28612
+ ctx,
28613
+ (connId) => callNativeSync(
28614
+ () => runtime.actorQueueHibernationRemoval(ctx, connId)
28615
+ ),
28616
+ () => actorContext.assertCanMutateState()
28617
+ )
28618
+ });
27825
28619
  }
27826
28620
  function buildActorConfig(definition, registryConfig, runtimeKind) {
28621
+ var _a2;
27827
28622
  const config3 = definition.config;
27828
28623
  const options = config3.options ?? {};
27829
28624
  const canHibernate = options.canHibernateWebSocket;
27830
28625
  const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
28626
+ const sqliteProfiling = (_a2 = config3.db) == null ? void 0 : _a2.sqliteProfiling;
27831
28627
  return {
27832
28628
  name: options.name,
27833
28629
  icon: options.icon,
27834
- hasDatabase: config3.db !== void 0 || usesRemoteSqlite,
28630
+ hasDatabase: true,
27835
28631
  remoteSqlite: usesRemoteSqlite,
28632
+ sqliteProfiling,
27836
28633
  enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
27837
28634
  hasState: config3.state !== void 0 || typeof config3.createState === "function",
27838
28635
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
@@ -27931,7 +28728,7 @@ function validateInspectorTabSource(tabId, resolved) {
27931
28728
  function buildNativeFactory(runtime, registryConfig, definition) {
27932
28729
  var _a2;
27933
28730
  const config3 = definition.config;
27934
- const databaseProvider = config3.db;
28731
+ const databaseProvider = config3.db ?? db();
27935
28732
  const actionHandlers = flattenActionHandlers(config3.actions);
27936
28733
  const schemaConfig = {
27937
28734
  actionInputSchemas: flattenActionInputSchemas(
@@ -27948,16 +28745,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27948
28745
  ),
27949
28746
  { encoding: "bare" }
27950
28747
  );
27951
- const nativeRunHandlerActiveByActorId = /* @__PURE__ */ new Map();
27952
- const isNativeRunHandlerActive = (ctx) => nativeRunHandlerActiveByActorId.get(
27953
- callNativeSync(() => runtime.actorId(ctx))
27954
- ) ?? false;
28748
+ const run = getRunFunction(config3.run);
28749
+ const runHandlerCoordinator = getRunInspectorKind(config3.run) === "workflow" ? new RunHandlerCoordinator(config3.run) : void 0;
27955
28750
  const getNativeWorkflowInspector = (ctx) => {
27956
- var _a22;
27957
- return (_a22 = getRunInspectorConfig(
27958
- config3.run,
27959
- callNativeSync(() => runtime.actorId(ctx))
27960
- )) == null ? void 0 : _a22.workflow;
28751
+ var _a22, _b;
28752
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
28753
+ const restart = () => callNativeSync(() => runtime.actorRestartRunHandler(ctx));
28754
+ return ((_a22 = runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.getInspector(actorId, restart)) == null ? void 0 : _a22.workflow) ?? ((_b = getRunInspectorConfig(config3.run, actorId)) == null ? void 0 : _b.workflow);
27961
28755
  };
27962
28756
  const onStateChange = typeof config3.onStateChange === "function" ? (actorCtx, nextState) => {
27963
28757
  config3.onStateChange(actorCtx, nextState);
@@ -27977,9 +28771,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27977
28771
  databaseProvider,
27978
28772
  request,
27979
28773
  stateEnabled,
27980
- () => isNativeRunHandlerActive(ctx),
27981
28774
  onStateChange,
27982
- cancelToken
28775
+ cancelToken,
28776
+ run !== void 0
27983
28777
  );
27984
28778
  const makeConnCtx = (ctx, conn, request, cancelToken) => withConnContext(
27985
28779
  runtime,
@@ -27991,7 +28785,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27991
28785
  request,
27992
28786
  stateEnabled,
27993
28787
  onStateChange,
27994
- cancelToken
28788
+ cancelToken,
28789
+ run !== void 0
27995
28790
  );
27996
28791
  const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
27997
28792
  var _a22, _b, _c, _d;
@@ -28042,6 +28837,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28042
28837
  return await ((_b2 = (_a3 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3)) ?? null;
28043
28838
  };
28044
28839
  const actorCtx = makeActorCtx(ctx, jsRequest);
28840
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
28045
28841
  try {
28046
28842
  if (url2.pathname === "/inspector/state" && jsRequest.method === "GET") {
28047
28843
  return jsonResponse({
@@ -28169,9 +28965,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28169
28965
  }
28170
28966
  }
28171
28967
  if (url2.pathname === "/inspector/database/schema" && jsRequest.method === "GET") {
28172
- const db = actorCtx.sql;
28968
+ const db2 = sql;
28173
28969
  const tables = queryRows(
28174
- await db.query(
28970
+ await db2.query(
28175
28971
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name"
28176
28972
  )
28177
28973
  );
@@ -28179,13 +28975,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28179
28975
  for (const table of tables) {
28180
28976
  const quoted = `"${table.name.replace(/"/g, '""')}"`;
28181
28977
  const columns = queryRows(
28182
- await db.query(`PRAGMA table_info(${quoted})`)
28978
+ await db2.query(`PRAGMA table_info(${quoted})`)
28183
28979
  );
28184
28980
  const foreignKeys = queryRows(
28185
- await db.query(`PRAGMA foreign_key_list(${quoted})`)
28981
+ await db2.query(`PRAGMA foreign_key_list(${quoted})`)
28186
28982
  );
28187
28983
  const countResult = queryRows(
28188
- await db.query(
28984
+ await db2.query(
28189
28985
  `SELECT COUNT(*) as count FROM ${quoted}`
28190
28986
  )
28191
28987
  );
@@ -28220,7 +29016,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28220
29016
  );
28221
29017
  const quoted = `"${table.replace(/"/g, '""')}"`;
28222
29018
  const rows = queryRows(
28223
- await actorCtx.sql.query(
29019
+ await sql.query(
28224
29020
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
28225
29021
  [
28226
29022
  Math.max(0, Math.min(limit, 500)),
@@ -28248,15 +29044,11 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28248
29044
  const bindings = normalizeSqlitePropertyBindings(
28249
29045
  body.properties
28250
29046
  );
28251
- const rows2 = queryRows(
28252
- await actorCtx.sql.query(body.sql, bindings)
28253
- );
29047
+ const rows2 = queryRows(await sql.query(body.sql, bindings));
28254
29048
  return jsonResponse({ rows: jsonSafe(rows2) });
28255
29049
  }
28256
29050
  const args = Array.isArray(body.args) ? body.args : [];
28257
- const rows = queryRows(
28258
- await actorCtx.sql.query(body.sql, args)
28259
- );
29051
+ const rows = queryRows(await sql.query(body.sql, args));
28260
29052
  return jsonResponse({ rows: jsonSafe(rows) });
28261
29053
  }
28262
29054
  if (url2.pathname === "/inspector/summary" && jsRequest.method === "GET") {
@@ -28282,7 +29074,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28282
29074
  rpcs: Object.keys(actionHandlers).sort(),
28283
29075
  queueSize: inspectorSnapshot.queueSize,
28284
29076
  isStateEnabled: stateEnabled,
28285
- isDatabaseEnabled: databaseProvider !== void 0,
29077
+ isDatabaseEnabled: true,
28286
29078
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0,
28287
29079
  workflowState: await workflowState(),
28288
29080
  workflowHistory: workflowHistory()
@@ -28472,6 +29264,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28472
29264
  async (error46, payload) => {
28473
29265
  const { ctx } = unwrapTsfnPayload(error46, payload);
28474
29266
  const actorCtx = makeActorCtx(ctx);
29267
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
28475
29268
  const saveActorState = async () => {
28476
29269
  if (runtime.kind === "wasm") {
28477
29270
  await runtime.actorSaveState(
@@ -28497,6 +29290,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28497
29290
  saveActorState
28498
29291
  );
28499
29292
  } finally {
29293
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
29294
+ disposeRunInspector(config3.run, actorId);
28500
29295
  await actorCtx.dispose();
28501
29296
  }
28502
29297
  }
@@ -28506,14 +29301,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28506
29301
  async (error46, payload) => {
28507
29302
  const { ctx } = unwrapTsfnPayload(error46, payload);
28508
29303
  const actorCtx = makeActorCtx(ctx);
29304
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
29305
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
29306
+ disposeRunInspector(config3.run, actorId);
28509
29307
  try {
28510
29308
  if (typeof config3.onDestroy === "function") {
28511
29309
  await config3.onDestroy(actorCtx);
28512
29310
  }
28513
29311
  } finally {
28514
- const actorId = callNativeSync(() => runtime.actorId(ctx));
28515
- nativeRunHandlerActiveByActorId.delete(actorId);
28516
- disposeRunInspector(config3.run, actorId);
28517
29312
  resolveNativeDestroy(runtime, ctx);
28518
29313
  await actorCtx.closeDatabase();
28519
29314
  clearNativeRuntimeState(runtime, ctx);
@@ -28561,7 +29356,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28561
29356
  ctx,
28562
29357
  connId
28563
29358
  )
28564
- )
29359
+ ),
29360
+ () => actorCtx.assertCanMutateState()
28565
29361
  );
28566
29362
  try {
28567
29363
  const nextConnState = hasStaticConnState ? structuredClone(config3.connState) : await config3.createConnState(
@@ -28598,7 +29394,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28598
29394
  ctx,
28599
29395
  connId
28600
29396
  )
28601
- )
29397
+ ),
29398
+ () => actorCtx.assertCanMutateState()
28602
29399
  );
28603
29400
  try {
28604
29401
  await config3.onConnect(
@@ -28630,7 +29427,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28630
29427
  ctx,
28631
29428
  connId
28632
29429
  )
28633
- )
29430
+ ),
29431
+ () => actorCtx.assertCanMutateState()
28634
29432
  )
28635
29433
  );
28636
29434
  }
@@ -28774,7 +29572,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28774
29572
  }
28775
29573
  ) : void 0,
28776
29574
  run: (() => {
28777
- const run = getRunFunction(config3.run);
28778
29575
  if (!run) {
28779
29576
  return void 0;
28780
29577
  }
@@ -28782,18 +29579,30 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28782
29579
  async (error46, payload) => {
28783
29580
  const { ctx } = unwrapTsfnPayload(error46, payload);
28784
29581
  const actorId = callNativeSync(() => runtime.actorId(ctx));
28785
- const actorCtx = makeActorCtx(ctx);
28786
- nativeRunHandlerActiveByActorId.set(actorId, true);
28787
- try {
28788
- await run(actorCtx);
28789
- } finally {
28790
- nativeRunHandlerActiveByActorId.delete(actorId);
28791
- await actorCtx.dispose();
29582
+ const executeRun = async () => {
29583
+ const actorCtx = makeActorCtx(ctx);
29584
+ try {
29585
+ await run(actorCtx);
29586
+ } finally {
29587
+ await actorCtx.dispose();
29588
+ }
29589
+ };
29590
+ if (runHandlerCoordinator) {
29591
+ const outcome = await runHandlerCoordinator.run(
29592
+ actorId,
29593
+ () => callNativeSync(
29594
+ () => runtime.actorRestartRunHandler(ctx)
29595
+ ),
29596
+ executeRun
29597
+ );
29598
+ return outcome !== "suppressed";
28792
29599
  }
29600
+ await executeRun();
29601
+ return true;
28793
29602
  }
28794
29603
  );
28795
29604
  })(),
28796
- getWorkflowHistory: getRunInspectorConfig(config3.run) !== void 0 ? wrapNativeCallback(
29605
+ getWorkflowHistory: hasRunInspectorConfig(config3.run) ? wrapNativeCallback(
28797
29606
  async (error46, payload) => {
28798
29607
  var _a22;
28799
29608
  const { ctx } = unwrapTsfnPayload(error46, payload);
@@ -28801,7 +29610,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28801
29610
  return history == null ? void 0 : toUint8Array(history);
28802
29611
  }
28803
29612
  ) : void 0,
28804
- replayWorkflow: getRunInspectorConfig(config3.run) !== void 0 ? wrapNativeCallback(
29613
+ replayWorkflow: hasRunInspectorConfig(config3.run) ? wrapNativeCallback(
28805
29614
  async (error46, payload) => {
28806
29615
  const { ctx, entryId } = unwrapTsfnPayload(
28807
29616
  error46,
@@ -28811,9 +29620,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28811
29620
  if (!(workflowInspector == null ? void 0 : workflowInspector.replayFromStep)) {
28812
29621
  return void 0;
28813
29622
  }
28814
- const history = await workflowInspector.replayFromStep(
28815
- entryId
28816
- ) ?? null;
29623
+ const history = await workflowInspector.replayFromStep(entryId) ?? null;
28817
29624
  return history == null ? void 0 : toUint8Array(history);
28818
29625
  }
28819
29626
  ) : void 0,
@@ -28866,7 +29673,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28866
29673
  jsRequest,
28867
29674
  stateEnabled,
28868
29675
  onStateChange,
28869
- cancelToken
29676
+ cancelToken,
29677
+ run !== void 0
28870
29678
  );
28871
29679
  try {
28872
29680
  if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
@@ -29749,7 +30557,7 @@ function setup(input) {
29749
30557
  }
29750
30558
 
29751
30559
  // src/mod.ts
29752
- var import_meta2 = {};
30560
+ var import_meta = {};
29753
30561
  var DEFAULT_MANAGER_PATH = "/api/rivet";
29754
30562
  function setup2(config3) {
29755
30563
  return setup({
@@ -29760,7 +30568,7 @@ function setup2(config3) {
29760
30568
  });
29761
30569
  }
29762
30570
  var resolveWasmUrl = () => new URL(
29763
- import_meta2.resolve("@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm")
30571
+ import_meta.resolve("@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm")
29764
30572
  );
29765
30573
  function applyEnv(config3, managerPath) {
29766
30574
  if (!config3.endpoint) {
@@ -29837,6 +30645,7 @@ async function serve(registryOrConfig, options = {}) {
29837
30645
  actor,
29838
30646
  buildActorNames,
29839
30647
  createClientWithDriver,
30648
+ defineRunHandler,
29840
30649
  event,
29841
30650
  isStaticActorDefinition,
29842
30651
  isStaticActorInstance,