@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.mjs CHANGED
@@ -471,7 +471,7 @@ function unsupportedFeature(feature) {
471
471
  );
472
472
  }
473
473
 
474
- // ../rivetkit/dist/tsup/chunk-LZ4TSBIP.js
474
+ // ../rivetkit/dist/tsup/chunk-OUENKQHB.js
475
475
  import {
476
476
  pino,
477
477
  stdTimeFunctions
@@ -13147,7 +13147,7 @@ var classic_default = external_exports;
13147
13147
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13148
13148
  var v4_default = classic_default;
13149
13149
 
13150
- // ../rivetkit/dist/tsup/chunk-LZ4TSBIP.js
13150
+ // ../rivetkit/dist/tsup/chunk-OUENKQHB.js
13151
13151
  var import_invariant = __toESM(require_invariant(), 1);
13152
13152
  import * as cbor from "cbor-x";
13153
13153
  var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
@@ -13312,7 +13312,7 @@ function noopNext() {
13312
13312
  }
13313
13313
  var package_default = {
13314
13314
  name: "rivetkit",
13315
- version: "2.3.11-rc.9",
13315
+ version: "2.3.11",
13316
13316
  description: "Lightweight libraries for building stateful actors on edge platforms",
13317
13317
  license: "Apache-2.0",
13318
13318
  keywords: [
@@ -13448,6 +13448,16 @@ var package_default = {
13448
13448
  default: "./dist/tsup/inspector/mod.cjs"
13449
13449
  }
13450
13450
  },
13451
+ "./experimental/inspector/workflow": {
13452
+ import: {
13453
+ types: "./dist/tsup/inspector/workflow.d.ts",
13454
+ default: "./dist/tsup/inspector/workflow.js"
13455
+ },
13456
+ require: {
13457
+ types: "./dist/tsup/inspector/workflow.d.cts",
13458
+ default: "./dist/tsup/inspector/workflow.cjs"
13459
+ }
13460
+ },
13451
13461
  "./inspector-tab": {
13452
13462
  import: {
13453
13463
  types: "./dist/tsup/inspector-tab/mod.d.ts",
@@ -13493,7 +13503,7 @@ var package_default = {
13493
13503
  "./dist/tsup/chunk-*.cjs"
13494
13504
  ],
13495
13505
  scripts: {
13496
- 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",
13506
+ 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",
13497
13507
  "build:browser": "tsup --config tsup.browser.config.ts",
13498
13508
  "check-types": "tsc --noEmit",
13499
13509
  lint: "biome check . && pnpm run check:test-skips && pnpm run check:wait-for-comments",
@@ -14605,7 +14615,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
14605
14615
  };
14606
14616
  }
14607
14617
 
14608
- // ../rivetkit/dist/tsup/chunk-C5TORAVP.js
14618
+ // ../rivetkit/dist/tsup/chunk-QFJ24MBU.js
14609
14619
  var config2 = /* @__PURE__ */ Config({});
14610
14620
  function readWorkflowCbor(bc) {
14611
14621
  return readData(bc);
@@ -14903,7 +14913,7 @@ function decodeWorkflowHistoryTransport(data) {
14903
14913
  return decodeWorkflowHistory(toUint8Array(data));
14904
14914
  }
14905
14915
 
14906
- // ../rivetkit/dist/tsup/chunk-QWLJCP3X.js
14916
+ // ../rivetkit/dist/tsup/chunk-6W5VGLFT.js
14907
14917
  function flattenActionHandlers(actions) {
14908
14918
  const flattened = /* @__PURE__ */ Object.create(null);
14909
14919
  for (const { name, handler } of collectActionEntries(actions)) {
@@ -15009,6 +15019,7 @@ var zActionTree = external_exports.custom((value) => {
15009
15019
  });
15010
15020
  var WorkflowInspectorConfigSchema = external_exports.object({
15011
15021
  getHistory: zFunction(),
15022
+ getState: zFunction().optional(),
15012
15023
  onHistoryUpdated: zFunction().optional(),
15013
15024
  replayFromStep: zFunction().optional()
15014
15025
  });
@@ -15078,9 +15089,36 @@ var RunConfigSchema = external_exports.object({
15078
15089
  /** Inspector integration for long-running run handlers. */
15079
15090
  inspector: RunInspectorConfigSchema.optional()
15080
15091
  });
15081
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for(
15082
- "rivetkit.run_function_config"
15083
- );
15092
+ var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
15093
+ function defineRunHandler(run, options) {
15094
+ if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
15095
+ throw new TypeError(
15096
+ "defineRunHandler requires inspectorKind and createInspector together"
15097
+ );
15098
+ }
15099
+ Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
15100
+ configurable: false,
15101
+ enumerable: false,
15102
+ writable: false,
15103
+ value: {
15104
+ name: options.name,
15105
+ icon: options.icon,
15106
+ inspectorKind: options.inspectorKind,
15107
+ createInspector: options.createInspector
15108
+ }
15109
+ });
15110
+ return run;
15111
+ }
15112
+ function getRunInspectorKind(run) {
15113
+ var _a2;
15114
+ if (!run || typeof run !== "function") return void 0;
15115
+ return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
15116
+ }
15117
+ function createRunInspector(run, context) {
15118
+ var _a2, _b;
15119
+ if (!run || typeof run !== "function") return void 0;
15120
+ return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context);
15121
+ }
15084
15122
  var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
15085
15123
  function getRunFunction(run) {
15086
15124
  if (!run) return void 0;
@@ -15104,6 +15142,12 @@ function getRunInspectorConfig(run, actor2) {
15104
15142
  }
15105
15143
  return run.inspector;
15106
15144
  }
15145
+ function hasRunInspectorConfig(run) {
15146
+ if (!run) return false;
15147
+ if (typeof run !== "function") return run.inspector !== void 0;
15148
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15149
+ 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;
15150
+ }
15107
15151
  function disposeRunInspector(run, actorId) {
15108
15152
  var _a2;
15109
15153
  if (!run || typeof run !== "function") {
@@ -15450,7 +15494,90 @@ function removePrefixFromKey(prefixedKey) {
15450
15494
  return prefixedKey.slice(KEYS.KV.length);
15451
15495
  }
15452
15496
 
15453
- // ../rivetkit/dist/tsup/chunk-XOOESJY7.js
15497
+ // ../rivetkit/dist/tsup/chunk-JTHHCZCZ.js
15498
+ var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15499
+ function isManualTransactionControl(query) {
15500
+ return /^\s*(?:BEGIN|SAVEPOINT|COMMIT|END|ROLLBACK)\b/i.test(query);
15501
+ }
15502
+ function validateTransactionTimeout(timeout) {
15503
+ if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout <= 0)) {
15504
+ throw new Error(
15505
+ "db.transaction() timeout must be a positive finite number of milliseconds"
15506
+ );
15507
+ }
15508
+ }
15509
+ function validateTransactionName(name) {
15510
+ if (name === void 0) {
15511
+ return;
15512
+ }
15513
+ if (name.length === 0) {
15514
+ throw new Error("db.transaction() name must not be empty");
15515
+ }
15516
+ }
15517
+ function isSqliteBindingValue(value) {
15518
+ if (value === null || typeof value === "number" || typeof value === "string" || typeof value === "bigint" || value instanceof Uint8Array) {
15519
+ return true;
15520
+ }
15521
+ if (Array.isArray(value)) {
15522
+ return value.every((item) => typeof item === "number");
15523
+ }
15524
+ return false;
15525
+ }
15526
+ function isPlainObject3(value) {
15527
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
15528
+ return false;
15529
+ }
15530
+ return Object.getPrototypeOf(value) === Object.prototype;
15531
+ }
15532
+ function isSqliteBindingObject(value) {
15533
+ if (!isPlainObject3(value)) {
15534
+ return false;
15535
+ }
15536
+ return Object.values(value).every((entry) => isSqliteBindingValue(entry));
15537
+ }
15538
+ function toSqliteBindings(input) {
15539
+ if (Array.isArray(input)) {
15540
+ for (const value of input) {
15541
+ if (!isSqliteBindingValue(value)) {
15542
+ throw new Error(
15543
+ `unsupported sqlite binding type: ${typeof value}`
15544
+ );
15545
+ }
15546
+ }
15547
+ return input;
15548
+ }
15549
+ if (isSqliteBindingObject(input)) {
15550
+ return input;
15551
+ }
15552
+ throw new Error("unsupported sqlite binding collection");
15553
+ }
15554
+ var AsyncMutex = class {
15555
+ #locked = false;
15556
+ #waiting = [];
15557
+ async acquire() {
15558
+ while (this.#locked) {
15559
+ await new Promise((resolve) => this.#waiting.push(resolve));
15560
+ }
15561
+ this.#locked = true;
15562
+ }
15563
+ release() {
15564
+ this.#locked = false;
15565
+ const next = this.#waiting.shift();
15566
+ if (next) {
15567
+ next();
15568
+ }
15569
+ }
15570
+ async run(fn) {
15571
+ await this.acquire();
15572
+ try {
15573
+ return await fn();
15574
+ } finally {
15575
+ this.release();
15576
+ }
15577
+ }
15578
+ };
15579
+
15580
+ // ../rivetkit/dist/tsup/chunk-FWROC5LA.js
15454
15581
  function logger() {
15455
15582
  return getLogger("actor-client");
15456
15583
  }
@@ -15488,35 +15615,7 @@ async function importWebSocket() {
15488
15615
  return webSocketPromise;
15489
15616
  }
15490
15617
 
15491
- // ../rivetkit/dist/tsup/chunk-7AFZMFPQ.js
15492
- var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15493
- var AsyncMutex = class {
15494
- #locked = false;
15495
- #waiting = [];
15496
- async acquire() {
15497
- while (this.#locked) {
15498
- await new Promise((resolve) => this.#waiting.push(resolve));
15499
- }
15500
- this.#locked = true;
15501
- }
15502
- release() {
15503
- this.#locked = false;
15504
- const next = this.#waiting.shift();
15505
- if (next) {
15506
- next();
15507
- }
15508
- }
15509
- async run(fn) {
15510
- await this.acquire();
15511
- try {
15512
- return await fn();
15513
- } finally {
15514
- this.release();
15515
- }
15516
- }
15517
- };
15518
-
15519
- // ../rivetkit/dist/tsup/chunk-HOZ3ZLZ2.js
15618
+ // ../rivetkit/dist/tsup/chunk-3ZR542SK.js
15520
15619
  var import_invariant2 = __toESM(require_invariant(), 1);
15521
15620
 
15522
15621
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -15694,7 +15793,7 @@ function createVersionedDataHandler(config3) {
15694
15793
  return new VersionedDataHandler(config3);
15695
15794
  }
15696
15795
 
15697
- // ../rivetkit/dist/tsup/chunk-HOZ3ZLZ2.js
15796
+ // ../rivetkit/dist/tsup/chunk-3ZR542SK.js
15698
15797
  var import_invariant3 = __toESM(require_invariant(), 1);
15699
15798
  var import_invariant4 = __toESM(require_invariant(), 1);
15700
15799
  var PATH_CONNECT = "/connect";
@@ -21410,6 +21509,231 @@ function apiActorToOutput(actor2) {
21410
21509
  };
21411
21510
  }
21412
21511
 
21512
+ // ../rivetkit/dist/tsup/chunk-6WYATRS4.js
21513
+ var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
21514
+ var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
21515
+ function registerNativeStateTransactionOpener(provider, opener) {
21516
+ nativeStateTransactionOpeners.set(provider, opener);
21517
+ return provider;
21518
+ }
21519
+ function bindNativeStateTransactionContext(client, context) {
21520
+ if ((typeof client !== "object" || client === null) && typeof client !== "function") {
21521
+ return client;
21522
+ }
21523
+ const bind = nativeStateTransactionClientBinders.get(client);
21524
+ return (bind == null ? void 0 : bind(context)) ?? client;
21525
+ }
21526
+ function hasMultipleStatements(query) {
21527
+ const trimmed = query.trim().replace(/;+$/, "").trimEnd();
21528
+ return trimmed.includes(";");
21529
+ }
21530
+ function db({
21531
+ onMigrate,
21532
+ warnOnManualTransactions = true,
21533
+ profiling
21534
+ } = {}) {
21535
+ const provider = {
21536
+ sqliteProfiling: profiling,
21537
+ createClient: async (ctx) => {
21538
+ const nativeDatabaseProvider = ctx.nativeDatabaseProvider;
21539
+ if (!nativeDatabaseProvider) {
21540
+ throw new Error(
21541
+ "native SQLite is required, but the current runtime did not provide a native database provider"
21542
+ );
21543
+ }
21544
+ const db2 = await nativeDatabaseProvider.open(ctx.actorId);
21545
+ let closed = false;
21546
+ let manualTransactionWarned = false;
21547
+ const ensureOpen = () => {
21548
+ if (closed) {
21549
+ throw new Error(
21550
+ "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."
21551
+ );
21552
+ }
21553
+ };
21554
+ const createClient = (target, transactionScoped = false, stateTransactionContext) => {
21555
+ const client2 = {
21556
+ execute: async (query, ...args) => {
21557
+ var _a2, _b, _c, _d;
21558
+ ensureOpen();
21559
+ if (!transactionScoped && warnOnManualTransactions && !manualTransactionWarned && !hasMultipleStatements(query) && isManualTransactionControl(query)) {
21560
+ manualTransactionWarned = true;
21561
+ getLogger("database").warn(
21562
+ { actorId: ctx.actorId },
21563
+ "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."
21564
+ );
21565
+ }
21566
+ const kvReadsBefore = ((_a2 = ctx.metrics) == null ? void 0 : _a2.totalKvReads) ?? 0;
21567
+ const kvWritesBefore = ((_b = ctx.metrics) == null ? void 0 : _b.totalKvWrites) ?? 0;
21568
+ const start = performance.now();
21569
+ try {
21570
+ if (args.length > 0) {
21571
+ const bindings = args.length === 1 && isSqliteBindingObject(args[0]) ? toSqliteBindings(args[0]) : toSqliteBindings(args);
21572
+ const { rows, columns } = await target.execute(
21573
+ query,
21574
+ bindings
21575
+ );
21576
+ return rows.map(
21577
+ (row) => rowToObject(row, columns)
21578
+ );
21579
+ }
21580
+ if (!hasMultipleStatements(query)) {
21581
+ const { rows, columns } = await target.execute(
21582
+ query,
21583
+ void 0
21584
+ );
21585
+ return rows.map(
21586
+ (row) => rowToObject(row, columns)
21587
+ );
21588
+ }
21589
+ return await execMultiStatement(
21590
+ target,
21591
+ query
21592
+ );
21593
+ } finally {
21594
+ const durationMs = performance.now() - start;
21595
+ (_c = ctx.metrics) == null ? void 0 : _c.trackSql(query, durationMs);
21596
+ if (ctx.metrics) {
21597
+ const kvReads = ctx.metrics.totalKvReads - kvReadsBefore;
21598
+ const kvWrites = ctx.metrics.totalKvWrites - kvWritesBefore;
21599
+ (_d = ctx.log) == null ? void 0 : _d.debug({
21600
+ msg: "sql query",
21601
+ query: query.slice(0, 120),
21602
+ durationMs,
21603
+ kvReads,
21604
+ kvWrites
21605
+ });
21606
+ }
21607
+ }
21608
+ },
21609
+ transaction: async (callback, options) => {
21610
+ var _a2, _b;
21611
+ validateTransactionTimeout(options == null ? void 0 : options.timeout);
21612
+ validateTransactionName(options == null ? void 0 : options.name);
21613
+ if (transactionScoped && ((_a2 = options == null ? void 0 : options.experimental) == null ? void 0 : _a2.includeState)) {
21614
+ throw new Error(
21615
+ "experimental.includeState is not supported for nested transactions"
21616
+ );
21617
+ }
21618
+ const includeState = ((_b = options == null ? void 0 : options.experimental) == null ? void 0 : _b.includeState) === true;
21619
+ const stateScope = includeState && stateTransactionContext ? await stateTransactionContext.enter() : void 0;
21620
+ try {
21621
+ const transaction = includeState ? await (() => {
21622
+ const beginStateTransaction = ctx.nativeDatabaseProvider && nativeStateTransactionOpeners.get(
21623
+ ctx.nativeDatabaseProvider
21624
+ );
21625
+ if (!beginStateTransaction) {
21626
+ throw new Error(
21627
+ "experimental.includeState is only supported by RivetKit's embedded database provider"
21628
+ );
21629
+ }
21630
+ return beginStateTransaction(
21631
+ options == null ? void 0 : options.timeout,
21632
+ stateScope
21633
+ );
21634
+ })() : await db2.beginTransaction(
21635
+ options == null ? void 0 : options.timeout,
21636
+ options == null ? void 0 : options.name
21637
+ );
21638
+ const tx = createClient(transaction, true);
21639
+ try {
21640
+ const result = await callback(tx);
21641
+ await transaction.commit();
21642
+ return result;
21643
+ } catch (error46) {
21644
+ try {
21645
+ await transaction.rollback();
21646
+ } catch {
21647
+ }
21648
+ throw error46;
21649
+ }
21650
+ } finally {
21651
+ if (stateScope !== void 0) {
21652
+ stateTransactionContext == null ? void 0 : stateTransactionContext.exit(stateScope);
21653
+ }
21654
+ }
21655
+ },
21656
+ close: async () => {
21657
+ if (!closed) {
21658
+ closed = true;
21659
+ await db2.close();
21660
+ }
21661
+ },
21662
+ nativeMetrics: () => {
21663
+ var _a2;
21664
+ return ((_a2 = db2.nativeMetrics) == null ? void 0 : _a2.call(db2)) ?? null;
21665
+ }
21666
+ };
21667
+ if (!transactionScoped) {
21668
+ nativeStateTransactionClientBinders.set(
21669
+ client2,
21670
+ (context) => createClient(target, false, context)
21671
+ );
21672
+ }
21673
+ return client2;
21674
+ };
21675
+ const client = createClient(db2);
21676
+ return client;
21677
+ },
21678
+ onMigrate: async (client) => {
21679
+ if (onMigrate) {
21680
+ await withMigrationSavepoint(
21681
+ client,
21682
+ (leased) => onMigrate(leased)
21683
+ );
21684
+ }
21685
+ }
21686
+ };
21687
+ return provider;
21688
+ }
21689
+ function rowToObject(row, columns) {
21690
+ const rowObj = {};
21691
+ for (let i = 0; i < columns.length; i++) {
21692
+ rowObj[columns[i]] = row[i];
21693
+ }
21694
+ return rowObj;
21695
+ }
21696
+ async function execMultiStatement(db2, query) {
21697
+ const results = [];
21698
+ let columnNames = null;
21699
+ await db2.exec(query, (row, columns) => {
21700
+ if (!columnNames) {
21701
+ columnNames = columns;
21702
+ }
21703
+ results.push(rowToObject(row, columnNames));
21704
+ });
21705
+ return results;
21706
+ }
21707
+ async function withMigrationSavepoint(client, callback) {
21708
+ return await client.transaction(
21709
+ async (transaction) => {
21710
+ await transaction.execute("SAVEPOINT __rivet_on_migrate");
21711
+ try {
21712
+ const result = await callback(transaction);
21713
+ await transaction.execute(
21714
+ "RELEASE SAVEPOINT __rivet_on_migrate"
21715
+ );
21716
+ return result;
21717
+ } catch (error46) {
21718
+ try {
21719
+ await transaction.execute(
21720
+ "ROLLBACK TO SAVEPOINT __rivet_on_migrate"
21721
+ );
21722
+ } finally {
21723
+ await transaction.execute(
21724
+ "RELEASE SAVEPOINT __rivet_on_migrate"
21725
+ );
21726
+ }
21727
+ throw error46;
21728
+ }
21729
+ },
21730
+ {
21731
+ name: "rivetkit-migration",
21732
+ timeout: MIGRATION_TRANSACTION_TIMEOUT_MS
21733
+ }
21734
+ );
21735
+ }
21736
+
21413
21737
  // ../../../shared/typescript/virtual-websocket/dist/mod.js
21414
21738
  var VirtualWebSocket = class {
21415
21739
  static CONNECTING = 0;
@@ -23729,11 +24053,33 @@ function wrapJsNativeDatabase(database) {
23729
24053
  release();
23730
24054
  }
23731
24055
  },
23732
- async beginTransaction(timeoutMs) {
24056
+ async beginTransaction(timeoutMs, name) {
23733
24057
  const release = gate.enter();
23734
24058
  let transaction;
23735
24059
  try {
23736
- transaction = await database.beginTransaction(timeoutMs);
24060
+ transaction = await database.beginTransaction(timeoutMs, name);
24061
+ } catch (error46) {
24062
+ enrichNativeDatabaseError(database, error46);
24063
+ } finally {
24064
+ release();
24065
+ }
24066
+ return wrapTransaction(database, transaction, gate, (result) => {
24067
+ if (result.lastInsertRowId !== void 0) {
24068
+ lastInsertRowId = result.lastInsertRowId;
24069
+ }
24070
+ });
24071
+ },
24072
+ async beginStateTransaction(timeoutMs, context) {
24073
+ if (!database.beginStateTransaction) {
24074
+ throw new Error("actor state transactions are not configured");
24075
+ }
24076
+ const release = gate.enter();
24077
+ let transaction;
24078
+ try {
24079
+ transaction = await database.beginStateTransaction(
24080
+ timeoutMs,
24081
+ context
24082
+ );
23737
24083
  } catch (error46) {
23738
24084
  enrichNativeDatabaseError(database, error46);
23739
24085
  } finally {
@@ -23840,45 +24186,37 @@ var nodeChildProcess;
23840
24186
  var nodeStream;
23841
24187
  var nodeUrl;
23842
24188
  var hasImportedDependencies = false;
23843
- function getRequireFn() {
23844
- return createRequire(import.meta.url);
24189
+ var fallbackRequire;
24190
+ function loadNodeBuiltin(id) {
24191
+ var _a2;
24192
+ const nodeProcess = globalThis.process;
24193
+ const builtin = (_a2 = nodeProcess == null ? void 0 : nodeProcess.getBuiltinModule) == null ? void 0 : _a2.call(nodeProcess, id);
24194
+ if (builtin !== void 0) {
24195
+ return builtin;
24196
+ }
24197
+ if (!(nodeProcess == null ? void 0 : nodeProcess.execPath)) {
24198
+ throw new Error("Node.js built-ins are not available");
24199
+ }
24200
+ fallbackRequire ??= createRequire(nodeProcess.execPath);
24201
+ return fallbackRequire(id);
23845
24202
  }
23846
24203
  function importNodeDependencies() {
23847
24204
  if (hasImportedDependencies) return;
23848
24205
  try {
23849
- const requireFn = getRequireFn();
23850
- nodeCrypto = requireFn(
23851
- /* webpackIgnore: true */
23852
- "node:crypto"
23853
- );
23854
- nodeFsSync = requireFn(
23855
- /* webpackIgnore: true */
23856
- "node:fs"
23857
- );
23858
- nodeFs = requireFn(
23859
- /* webpackIgnore: true */
24206
+ nodeCrypto = loadNodeBuiltin("node:crypto");
24207
+ nodeFsSync = loadNodeBuiltin("node:fs");
24208
+ nodeFs = loadNodeBuiltin(
23860
24209
  "node:fs/promises"
23861
24210
  );
23862
- nodePath = requireFn(
23863
- /* webpackIgnore: true */
23864
- "node:path"
23865
- );
23866
- nodeOs = requireFn(
23867
- /* webpackIgnore: true */
23868
- "node:os"
23869
- );
23870
- nodeChildProcess = requireFn(
23871
- /* webpackIgnore: true */
24211
+ nodePath = loadNodeBuiltin("node:path");
24212
+ nodeOs = loadNodeBuiltin("node:os");
24213
+ nodeChildProcess = loadNodeBuiltin(
23872
24214
  "node:child_process"
23873
24215
  );
23874
- nodeStream = requireFn(
23875
- /* webpackIgnore: true */
24216
+ nodeStream = loadNodeBuiltin(
23876
24217
  "node:stream/promises"
23877
24218
  );
23878
- nodeUrl = requireFn(
23879
- /* webpackIgnore: true */
23880
- "node:url"
23881
- );
24219
+ nodeUrl = loadNodeBuiltin("node:url");
23882
24220
  hasImportedDependencies = true;
23883
24221
  } catch (err) {
23884
24222
  console.warn(
@@ -23925,6 +24263,9 @@ function asNativeWebSocket(handle) {
23925
24263
  function asNativeSqlTransaction(handle) {
23926
24264
  return handle;
23927
24265
  }
24266
+ function asNativeActorStateTransaction(handle) {
24267
+ return handle;
24268
+ }
23928
24269
  function asNativeCancellationToken(handle) {
23929
24270
  return handle;
23930
24271
  }
@@ -24148,6 +24489,9 @@ var NapiCoreRuntime = class {
24148
24489
  actorSetAlarm(ctx, timestampMs) {
24149
24490
  asNativeActorContext(ctx).setAlarm(timestampMs);
24150
24491
  }
24492
+ async actorSetRunWakeAt(ctx, timestampMs) {
24493
+ await asNativeActorContext(ctx).setRunWakeAt(timestampMs);
24494
+ }
24151
24495
  actorRequestSave(ctx, opts) {
24152
24496
  asNativeActorContext(ctx).requestSave(opts);
24153
24497
  }
@@ -24308,9 +24652,10 @@ var NapiCoreRuntime = class {
24308
24652
  );
24309
24653
  return results.map(normalizeRuntimeSqlExecuteResult);
24310
24654
  }
24311
- async actorSqlBeginTransaction(ctx, timeoutMs) {
24655
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
24312
24656
  return await this.#actorSql(ctx).beginTransaction(
24313
- timeoutMs
24657
+ timeoutMs,
24658
+ name
24314
24659
  );
24315
24660
  }
24316
24661
  async actorSqlTransactionExec(transaction, sql) {
@@ -24329,6 +24674,26 @@ var NapiCoreRuntime = class {
24329
24674
  async actorSqlTransactionRollback(transaction) {
24330
24675
  await asNativeSqlTransaction(transaction).rollback();
24331
24676
  }
24677
+ async actorBeginStateTransaction(ctx, timeoutMs) {
24678
+ return await asNativeActorContext(ctx).beginStateTransaction(
24679
+ timeoutMs
24680
+ );
24681
+ }
24682
+ async actorStateTransactionExecute(transaction, sql, params) {
24683
+ const result = await asNativeActorStateTransaction(transaction).execute(
24684
+ sql,
24685
+ toNapiSqlBindParams(params)
24686
+ );
24687
+ return normalizeRuntimeSqlExecuteResult(result);
24688
+ }
24689
+ async actorStateTransactionCommit(transaction, payload) {
24690
+ await asNativeActorStateTransaction(transaction).commit(
24691
+ toNapiStateDeltaPayload(payload)
24692
+ );
24693
+ }
24694
+ async actorStateTransactionRollback(transaction) {
24695
+ await asNativeActorStateTransaction(transaction).rollback();
24696
+ }
24332
24697
  async actorSqlQuery(ctx, sql, params) {
24333
24698
  return await this.#actorSql(ctx).query(
24334
24699
  sql,
@@ -24386,6 +24751,13 @@ var NapiCoreRuntime = class {
24386
24751
  signal ? asNativeCancellationToken(signal) : signal
24387
24752
  );
24388
24753
  }
24754
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
24755
+ return await asNativeActorContext(ctx).queue().completePersisted(
24756
+ messageId,
24757
+ expectedName,
24758
+ response == null ? response : toNapiBuffer(response)
24759
+ );
24760
+ }
24389
24761
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
24390
24762
  return await asNativeActorContext(ctx).queue().enqueueAndWait(
24391
24763
  name,
@@ -24572,6 +24944,164 @@ function validationError(target, issues) {
24572
24944
  metadata: { issues }
24573
24945
  });
24574
24946
  }
24947
+ function runUnavailable(actorId, reason) {
24948
+ return new RivetError(
24949
+ "actor",
24950
+ "run_handler_unavailable",
24951
+ `Run handler control is unavailable for actor ${actorId}: ${reason}.`,
24952
+ {
24953
+ public: true,
24954
+ statusCode: 409,
24955
+ metadata: { actorId, reason }
24956
+ }
24957
+ );
24958
+ }
24959
+ function notifyStateChanged(state) {
24960
+ const waiters = [...state.waiters];
24961
+ state.waiters.clear();
24962
+ for (const waiter of waiters) {
24963
+ waiter();
24964
+ }
24965
+ }
24966
+ function waitForStateChange(state) {
24967
+ return new Promise((resolve) => {
24968
+ state.waiters.add(resolve);
24969
+ });
24970
+ }
24971
+ var RunHandlerCoordinator = class {
24972
+ #run;
24973
+ #states = /* @__PURE__ */ new Map();
24974
+ constructor(run) {
24975
+ this.#run = run;
24976
+ }
24977
+ get inspectorKind() {
24978
+ return getRunInspectorKind(this.#run);
24979
+ }
24980
+ async run(actorId, restart, callback) {
24981
+ const state = this.#getOrCreate(actorId);
24982
+ state.restart = restart;
24983
+ this.#initializeInspector(actorId, state);
24984
+ state.queued += 1;
24985
+ const blockedGeneration = state.exclusive ? state.exclusiveGeneration : void 0;
24986
+ try {
24987
+ while (!state.closed && (state.exclusive || state.active)) {
24988
+ await waitForStateChange(state);
24989
+ }
24990
+ } finally {
24991
+ state.queued -= 1;
24992
+ }
24993
+ if (state.closed) {
24994
+ return "closed";
24995
+ }
24996
+ if (blockedGeneration !== void 0 && state.exclusiveGeneration === blockedGeneration && state.exclusiveOutcome === "failure") {
24997
+ return "suppressed";
24998
+ }
24999
+ state.active = true;
25000
+ try {
25001
+ await callback();
25002
+ return "ran";
25003
+ } finally {
25004
+ state.active = false;
25005
+ notifyStateChanged(state);
25006
+ }
25007
+ }
25008
+ getInspector(actorId, restart) {
25009
+ var _a2;
25010
+ const state = this.#getOrCreate(actorId);
25011
+ state.restart = restart;
25012
+ this.#initializeInspector(actorId, state);
25013
+ return (_a2 = state.inspector) == null ? void 0 : _a2.inspector;
25014
+ }
25015
+ destroy(actorId) {
25016
+ var _a2, _b;
25017
+ const state = this.#states.get(actorId);
25018
+ if (!state) return;
25019
+ state.closed = true;
25020
+ (_b = (_a2 = state.inspector) == null ? void 0 : _a2.dispose) == null ? void 0 : _b.call(_a2);
25021
+ state.inspector = void 0;
25022
+ notifyStateChanged(state);
25023
+ this.#states.delete(actorId);
25024
+ }
25025
+ #control(actorId, state) {
25026
+ return {
25027
+ run: {
25028
+ withInactive: async (options, callback) => {
25029
+ if (state.closed) {
25030
+ throw runUnavailable(actorId, "actor is destroyed");
25031
+ }
25032
+ if (state.active || state.queued > 0 || state.exclusive) {
25033
+ throw runUnavailable(
25034
+ actorId,
25035
+ "the run handler is active or waiting to start"
25036
+ );
25037
+ }
25038
+ state.exclusive = true;
25039
+ state.exclusiveGeneration += 1;
25040
+ state.exclusiveOutcome = void 0;
25041
+ try {
25042
+ const result = await callback();
25043
+ if (state.closed) {
25044
+ throw runUnavailable(actorId, "actor is destroyed");
25045
+ }
25046
+ state.exclusiveOutcome = "success";
25047
+ if (options.restartOnSuccess && state.queued === 0) {
25048
+ if (!state.restart) {
25049
+ throw runUnavailable(
25050
+ actorId,
25051
+ "the runtime restart callback is not available"
25052
+ );
25053
+ }
25054
+ await state.restart();
25055
+ }
25056
+ return result;
25057
+ } catch (error46) {
25058
+ state.exclusiveOutcome = "failure";
25059
+ throw error46;
25060
+ } finally {
25061
+ state.exclusive = false;
25062
+ notifyStateChanged(state);
25063
+ }
25064
+ }
25065
+ }
25066
+ };
25067
+ }
25068
+ #getOrCreate(actorId) {
25069
+ let state = this.#states.get(actorId);
25070
+ if (!state) {
25071
+ state = {
25072
+ active: false,
25073
+ closed: false,
25074
+ exclusive: false,
25075
+ exclusiveGeneration: 0,
25076
+ inspectorInitialized: false,
25077
+ queued: 0,
25078
+ waiters: /* @__PURE__ */ new Set()
25079
+ };
25080
+ this.#states.set(actorId, state);
25081
+ }
25082
+ return state;
25083
+ }
25084
+ #initializeInspector(actorId, state) {
25085
+ if (state.inspectorInitialized) return;
25086
+ const inspector = createRunInspector(this.#run, {
25087
+ actorId,
25088
+ control: this.#control(actorId, state)
25089
+ });
25090
+ if (this.inspectorKind === "workflow") {
25091
+ const workflow = inspector === void 0 ? void 0 : inspector.inspector.workflow;
25092
+ if (!workflow || typeof workflow.getHistory !== "function" || typeof workflow.getState !== "function" || typeof workflow.onHistoryUpdated !== "function" || typeof workflow.replayFromStep !== "function") {
25093
+ throw new TypeError(
25094
+ `defineRunHandler createInspector returned an invalid workflow adapter for actor ${actorId}`
25095
+ );
25096
+ }
25097
+ }
25098
+ state.inspector = inspector;
25099
+ state.inspectorInitialized = true;
25100
+ }
25101
+ };
25102
+ function asWasmConstructors(bindings) {
25103
+ return bindings;
25104
+ }
24575
25105
  function asWasmRegistry(handle) {
24576
25106
  return handle;
24577
25107
  }
@@ -24696,10 +25226,10 @@ function childHandle(handle, name) {
24696
25226
  }
24697
25227
  var WasmCoreRuntime = class {
24698
25228
  kind = "wasm";
24699
- #bindings;
25229
+ #constructors;
24700
25230
  #sql = /* @__PURE__ */ new WeakMap();
24701
25231
  constructor(bindings) {
24702
- this.#bindings = bindings;
25232
+ this.#constructors = asWasmConstructors(bindings);
24703
25233
  }
24704
25234
  #actorSql(ctx) {
24705
25235
  const wasmCtx = asWasmActorContext(ctx);
@@ -24712,7 +25242,7 @@ var WasmCoreRuntime = class {
24712
25242
  }
24713
25243
  createRegistry() {
24714
25244
  return callWasmSync(
24715
- () => asRegistryHandle2(new this.#bindings.CoreRegistry())
25245
+ () => asRegistryHandle2(new this.#constructors.CoreRegistry())
24716
25246
  );
24717
25247
  }
24718
25248
  registerActor(registry2, name, factory) {
@@ -24767,13 +25297,13 @@ var WasmCoreRuntime = class {
24767
25297
  createActorFactory(callbacks, config3) {
24768
25298
  return callWasmSync(
24769
25299
  () => asActorFactoryHandle2(
24770
- new this.#bindings.ActorFactory(callbacks, config3)
25300
+ new this.#constructors.ActorFactory(callbacks, config3)
24771
25301
  )
24772
25302
  );
24773
25303
  }
24774
25304
  createCancellationToken() {
24775
25305
  return callWasmSync(
24776
- () => new this.#bindings.CancellationToken()
25306
+ () => new this.#constructors.CancellationToken()
24777
25307
  );
24778
25308
  }
24779
25309
  cancellationTokenAborted(token) {
@@ -24808,6 +25338,13 @@ var WasmCoreRuntime = class {
24808
25338
  optionalWasmNumber(timestampMs)
24809
25339
  );
24810
25340
  }
25341
+ async actorSetRunWakeAt(ctx, timestampMs) {
25342
+ await callHandleAsync(
25343
+ asWasmActorContext(ctx),
25344
+ "setRunWakeAt",
25345
+ optionalWasmNumber(timestampMs)
25346
+ );
25347
+ }
24811
25348
  actorRequestSave(ctx, opts) {
24812
25349
  callHandle(asWasmActorContext(ctx), "requestSave", opts);
24813
25350
  }
@@ -25022,9 +25559,9 @@ var WasmCoreRuntime = class {
25022
25559
  );
25023
25560
  return results.map(normalizeRuntimeSqlExecuteResult);
25024
25561
  }
25025
- async actorSqlBeginTransaction(ctx, timeoutMs) {
25562
+ async actorSqlBeginTransaction(ctx, timeoutMs, name) {
25026
25563
  return await callWasm(
25027
- () => this.#actorSql(ctx).beginTransaction(timeoutMs)
25564
+ () => this.#actorSql(ctx).beginTransaction(timeoutMs, name)
25028
25565
  );
25029
25566
  }
25030
25567
  async actorSqlTransactionExec(transaction, sql) {
@@ -25048,6 +25585,27 @@ var WasmCoreRuntime = class {
25048
25585
  () => transaction.rollback()
25049
25586
  );
25050
25587
  }
25588
+ async actorBeginStateTransaction(ctx, timeoutMs) {
25589
+ return await callWasm(
25590
+ () => asWasmActorContext(ctx).beginStateTransaction(timeoutMs)
25591
+ );
25592
+ }
25593
+ async actorStateTransactionExecute(transaction, sql, params) {
25594
+ const result = await callWasm(
25595
+ () => transaction.execute(sql, params)
25596
+ );
25597
+ return normalizeRuntimeSqlExecuteResult(result);
25598
+ }
25599
+ async actorStateTransactionCommit(transaction, payload) {
25600
+ await callWasm(
25601
+ () => transaction.commit(payload)
25602
+ );
25603
+ }
25604
+ async actorStateTransactionRollback(transaction) {
25605
+ await callWasm(
25606
+ () => transaction.rollback()
25607
+ );
25608
+ }
25051
25609
  async actorSqlQuery(ctx, sql, params) {
25052
25610
  return await callWasm(() => this.#actorSql(ctx).query(sql, params));
25053
25611
  }
@@ -25120,6 +25678,16 @@ var WasmCoreRuntime = class {
25120
25678
  signal
25121
25679
  );
25122
25680
  }
25681
+ async actorQueueCompletePersisted(ctx, messageId, expectedName, response) {
25682
+ const queue2 = childHandle(asWasmActorContext(ctx), "queue");
25683
+ return await callHandleAsync(
25684
+ queue2,
25685
+ "completePersisted",
25686
+ messageId,
25687
+ expectedName,
25688
+ response
25689
+ );
25690
+ }
25123
25691
  async actorQueueEnqueueAndWait(ctx, name, body, options, signal) {
25124
25692
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
25125
25693
  return optionalBytes(
@@ -25328,7 +25896,7 @@ function unwrapProxy(value) {
25328
25896
  }
25329
25897
  return current;
25330
25898
  }
25331
- function isPlainObject3(value) {
25899
+ function isPlainObject4(value) {
25332
25900
  const proto = Object.getPrototypeOf(value);
25333
25901
  return proto === Object.prototype || proto === null;
25334
25902
  }
@@ -25381,7 +25949,7 @@ function unwrapDeep(value, seen) {
25381
25949
  }
25382
25950
  return unwrapped;
25383
25951
  }
25384
- if (isPlainObject3(unwrapped)) {
25952
+ if (isPlainObject4(unwrapped)) {
25385
25953
  for (const key of Object.keys(unwrapped)) {
25386
25954
  const child = unwrapDeep(unwrapped[key], seen);
25387
25955
  if (child !== unwrapped[key]) {
@@ -25538,6 +26106,14 @@ function stateMutationReentrantError() {
25538
26106
  "State mutations are not allowed inside onStateChange."
25539
26107
  );
25540
26108
  }
26109
+ function stateTransactionConflictError() {
26110
+ return new RivetError(
26111
+ "actor",
26112
+ "state_transaction_conflict",
26113
+ "State cannot be mutated by another action while an experimental state-aware database transaction is active.",
26114
+ { public: true, statusCode: 409 }
26115
+ );
26116
+ }
25541
26117
  function databaseNotConfiguredError() {
25542
26118
  return new RivetError(
25543
26119
  "actor",
@@ -25554,6 +26130,14 @@ function databaseClientNotReadyError() {
25554
26130
  { public: true }
25555
26131
  );
25556
26132
  }
26133
+ function runHandlerNotConfiguredError() {
26134
+ return new RivetError(
26135
+ "actor",
26136
+ "run_handler_unavailable",
26137
+ "Cannot schedule a run wake because this actor does not define a run handler.",
26138
+ { public: true, statusCode: 409 }
26139
+ );
26140
+ }
25557
26141
  function stateNotEnabledError() {
25558
26142
  return new RivetError(
25559
26143
  "actor",
@@ -25656,10 +26240,11 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
25656
26240
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
25657
26241
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
25658
26242
  executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
25659
- beginTransaction: async (timeoutMs) => {
26243
+ beginTransaction: async (timeoutMs, name) => {
25660
26244
  const transaction = await runtime.actorSqlBeginTransaction(
25661
26245
  ctx,
25662
- timeoutMs
26246
+ timeoutMs,
26247
+ name
25663
26248
  );
25664
26249
  return {
25665
26250
  exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
@@ -25672,6 +26257,38 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
25672
26257
  rollback: () => runtime.actorSqlTransactionRollback(transaction)
25673
26258
  };
25674
26259
  },
26260
+ beginStateTransaction: async (timeoutMs, context) => {
26261
+ const scope = context;
26262
+ if (!scope) {
26263
+ throw new Error(
26264
+ "actor state transaction context is not configured"
26265
+ );
26266
+ }
26267
+ const transaction = await runtime.actorBeginStateTransaction(
26268
+ ctx,
26269
+ timeoutMs
26270
+ );
26271
+ return {
26272
+ exec: async () => {
26273
+ throw new Error(
26274
+ "actor state transactions only support single-statement execute calls"
26275
+ );
26276
+ },
26277
+ execute: (sql, params) => runtime.actorStateTransactionExecute(
26278
+ transaction,
26279
+ sql,
26280
+ params
26281
+ ),
26282
+ commit: async () => {
26283
+ await runtime.actorStateTransactionCommit(
26284
+ transaction,
26285
+ scope.actorContext.serializeForTick("save")
26286
+ );
26287
+ scope.committed = true;
26288
+ },
26289
+ rollback: () => runtime.actorStateTransactionRollback(transaction)
26290
+ };
26291
+ },
25675
26292
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
25676
26293
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
25677
26294
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -26052,12 +26669,16 @@ var NativeConnAdapter = class {
26052
26669
  #schemas;
26053
26670
  #ctx;
26054
26671
  #queueHibernationRemoval;
26055
- constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval) {
26672
+ #assertCanMutateState;
26673
+ #stateProxy;
26674
+ #stateProxyTarget;
26675
+ constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval, assertCanMutateState) {
26056
26676
  this.#runtime = runtime;
26057
26677
  this.#conn = conn;
26058
26678
  this.#schemas = schemas;
26059
26679
  this.#ctx = ctx;
26060
26680
  this.#queueHibernationRemoval = queueHibernationRemoval;
26681
+ this.#assertCanMutateState = assertCanMutateState;
26061
26682
  this[CONN_STATE_MANAGER_SYMBOL] = {
26062
26683
  stateEnabled: true,
26063
26684
  get state() {
@@ -26083,29 +26704,35 @@ var NativeConnAdapter = class {
26083
26704
  if (!this.#ctx) {
26084
26705
  return this.#createStateProxy(nextState);
26085
26706
  }
26086
- const connState = getNativeConnPersistState(
26087
- this.#runtime,
26088
- this.#ctx,
26089
- this.#conn
26090
- );
26091
- if (connState.stateProxy === void 0 || connState.stateProxyTarget !== nextState) {
26092
- connState.stateProxyTarget = nextState;
26093
- connState.stateProxy = this.#createStateProxy(nextState);
26707
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
26708
+ this.#stateProxyTarget = nextState;
26709
+ this.#stateProxy = this.#createStateProxy(nextState);
26094
26710
  }
26095
- return connState.stateProxy;
26711
+ return this.#stateProxy;
26096
26712
  }
26097
26713
  #createStateProxy(state) {
26714
+ const assertCurrentState = () => {
26715
+ var _a2;
26716
+ (_a2 = this.#assertCanMutateState) == null ? void 0 : _a2.call(this);
26717
+ if (this.#ctx && this.#readState() !== state) {
26718
+ throw stateTransactionConflictError();
26719
+ }
26720
+ };
26098
26721
  return createWriteThroughProxy(
26099
26722
  state,
26100
26723
  (nextValue) => {
26724
+ assertCurrentState();
26101
26725
  this.#writeState(nextValue, { writeNative: true });
26102
26726
  },
26103
26727
  (newValue) => {
26728
+ assertCurrentState();
26104
26729
  assertJsonCompatValue(newValue);
26105
26730
  }
26106
26731
  );
26107
26732
  }
26108
26733
  set state(value) {
26734
+ var _a2;
26735
+ (_a2 = this.#assertCanMutateState) == null ? void 0 : _a2.call(this);
26109
26736
  const nextValue = unwrapWriteThroughProxy(value);
26110
26737
  assertJsonCompatValue(nextValue);
26111
26738
  this.#writeState(nextValue, { writeNative: true });
@@ -26431,8 +27058,9 @@ var NativeKvAdapter = class {
26431
27058
  };
26432
27059
  function wrapQueueMessage(message, schemas) {
26433
27060
  const name = callNativeSync(() => message.name());
27061
+ const id = callNativeSync(() => message.id());
26434
27062
  return {
26435
- id: Number(callNativeSync(() => message.id())),
27063
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
26436
27064
  name,
26437
27065
  body: validateQueueBody(
26438
27066
  schemas,
@@ -26570,6 +27198,25 @@ var NativeQueueAdapter = class {
26570
27198
  cleanup == null ? void 0 : cleanup();
26571
27199
  }
26572
27200
  }
27201
+ async waitForAvailable(names, options) {
27202
+ await this.waitForNamesAvailable(names ?? [], options);
27203
+ }
27204
+ async complete(message, response) {
27205
+ const validatedResponse = validateQueueComplete(
27206
+ this.#schemas,
27207
+ message.name,
27208
+ response
27209
+ );
27210
+ await callNative(
27211
+ () => this.#runtime.actorQueueCompletePersisted(
27212
+ this.#ctx,
27213
+ BigInt(message.id),
27214
+ message.name,
27215
+ encodeValue(validatedResponse)
27216
+ )
27217
+ );
27218
+ this.#pendingCompletableMessageIds.delete(message.id.toString());
27219
+ }
26573
27220
  async enqueueAndWait(name, body, options) {
26574
27221
  const validatedBody = validateQueueBody(this.#schemas, name, body);
26575
27222
  const { token, cleanup } = await createCancellationTokenHandle(
@@ -27006,10 +27653,12 @@ var NativeConnectionMap = class {
27006
27653
  #runtime;
27007
27654
  #ctx;
27008
27655
  #schemas;
27009
- constructor(runtime, ctx, schemas) {
27656
+ #assertCanMutateState;
27657
+ constructor(runtime, ctx, schemas, assertCanMutateState) {
27010
27658
  this.#runtime = runtime;
27011
27659
  this.#ctx = ctx;
27012
27660
  this.#schemas = schemas;
27661
+ this.#assertCanMutateState = assertCanMutateState;
27013
27662
  }
27014
27663
  #connToAdapter(conn) {
27015
27664
  return new NativeConnAdapter(
@@ -27022,7 +27671,8 @@ var NativeConnectionMap = class {
27022
27671
  this.#ctx,
27023
27672
  connId
27024
27673
  )
27025
- )
27674
+ ),
27675
+ this.#assertCanMutateState
27026
27676
  );
27027
27677
  }
27028
27678
  get size() {
@@ -27081,17 +27731,20 @@ var ActorContextHandleAdapter = class {
27081
27731
  #queue;
27082
27732
  #request;
27083
27733
  #schedule;
27084
- #sql;
27085
- #runHandlerActiveProvider;
27734
+ #run;
27735
+ #runHandlerConfigured;
27086
27736
  #onStateChange;
27087
27737
  #stateEnabled;
27088
- constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, runHandlerActiveProvider, onStateChange, dispatchCancelToken) {
27738
+ #stateProxy;
27739
+ #stateProxyTarget;
27740
+ #stateTransactionOwner = /* @__PURE__ */ Symbol("actor-state-transaction-owner");
27741
+ constructor(runtime, ctx, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
27089
27742
  this.#runtime = runtime;
27090
27743
  this.#ctx = ctx;
27091
27744
  this.#clientFactory = clientFactory;
27092
27745
  this.#schemas = schemas;
27093
27746
  this.#dispatchCancelToken = dispatchCancelToken;
27094
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
27747
+ this.#runHandlerConfigured = runHandlerConfigured;
27095
27748
  this.#onStateChange = onStateChange;
27096
27749
  this.#stateEnabled = stateEnabled;
27097
27750
  if (databaseProvider) {
@@ -27108,12 +27761,6 @@ var ActorContextHandleAdapter = class {
27108
27761
  }
27109
27762
  return this.#kv;
27110
27763
  }
27111
- get sql() {
27112
- if (!this.#sql) {
27113
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
27114
- }
27115
- return this.#sql;
27116
- }
27117
27764
  async actorRuntimeSocket() {
27118
27765
  return await callNative(
27119
27766
  () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
@@ -27129,7 +27776,7 @@ var ActorContextHandleAdapter = class {
27129
27776
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
27130
27777
  const cachedClient = runtimeState.databaseClient;
27131
27778
  if (cachedClient) {
27132
- this.#db = cachedClient.client;
27779
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
27133
27780
  return this.#db;
27134
27781
  }
27135
27782
  throw databaseClientNotReadyError();
@@ -27144,22 +27791,28 @@ var ActorContextHandleAdapter = class {
27144
27791
  if (!this.#stateEnabled) {
27145
27792
  throw stateNotEnabledError();
27146
27793
  }
27147
- const actorState = getNativePersistState(this.#runtime, this.#ctx);
27148
27794
  const nextState = this.#readState();
27149
- if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
27150
- actorState.stateProxyTarget = nextState;
27151
- actorState.stateProxy = createWriteThroughProxy(
27795
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
27796
+ const assertCurrentState = () => {
27797
+ this.#assertCanMutateState();
27798
+ if (this.#readState() !== nextState) {
27799
+ throw stateTransactionConflictError();
27800
+ }
27801
+ };
27802
+ this.#stateProxyTarget = nextState;
27803
+ this.#stateProxy = createWriteThroughProxy(
27152
27804
  nextState,
27153
27805
  (nextValue) => {
27806
+ assertCurrentState();
27154
27807
  this.#writeState(nextValue, { scheduleSave: true });
27155
27808
  },
27156
27809
  (newValue) => {
27157
- this.#assertCanMutateState();
27810
+ assertCurrentState();
27158
27811
  assertJsonCompatValue(newValue);
27159
27812
  }
27160
27813
  );
27161
27814
  }
27162
- return actorState.stateProxy;
27815
+ return this.#stateProxy;
27163
27816
  }
27164
27817
  set state(value) {
27165
27818
  if (!this.#stateEnabled) {
@@ -27202,6 +27855,26 @@ var ActorContextHandleAdapter = class {
27202
27855
  }
27203
27856
  return this.#queue;
27204
27857
  }
27858
+ get run() {
27859
+ if (!this.#run) {
27860
+ this.#run = {
27861
+ setWakeAt: async (timestamp) => {
27862
+ if (timestamp !== null && !this.#runHandlerConfigured) {
27863
+ throw runHandlerNotConfiguredError();
27864
+ }
27865
+ if (timestamp !== null && (!Number.isSafeInteger(timestamp) || timestamp < 0)) {
27866
+ throw new TypeError(
27867
+ "Run wake timestamp must be a non-negative safe integer or null"
27868
+ );
27869
+ }
27870
+ await callNative(
27871
+ () => this.#runtime.actorSetRunWakeAt(this.#ctx, timestamp)
27872
+ );
27873
+ }
27874
+ };
27875
+ }
27876
+ return this.#run;
27877
+ }
27205
27878
  get schedule() {
27206
27879
  if (!this.#schedule) {
27207
27880
  this.#schedule = new NativeScheduleAdapter(
@@ -27236,7 +27909,8 @@ var ActorContextHandleAdapter = class {
27236
27909
  this.#connMap = new NativeConnectionMap(
27237
27910
  this.#runtime,
27238
27911
  this.#ctx,
27239
- this.#schemas
27912
+ this.#schemas,
27913
+ () => this.#assertCanMutateState()
27240
27914
  );
27241
27915
  }
27242
27916
  return this.#connMap;
@@ -27305,11 +27979,11 @@ var ActorContextHandleAdapter = class {
27305
27979
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
27306
27980
  const cachedClient = runtimeState.databaseClient;
27307
27981
  if (cachedClient) {
27308
- this.#db = cachedClient.client;
27982
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
27309
27983
  return this.#db;
27310
27984
  }
27311
27985
  const actorId = this.actorId;
27312
- const client = await this.#databaseProvider.createClient({
27986
+ const createdClient = await this.#databaseProvider.createClient({
27313
27987
  actorId,
27314
27988
  kv: {
27315
27989
  batchPut: async (entries) => {
@@ -27330,21 +28004,126 @@ var ActorContextHandleAdapter = class {
27330
28004
  log: {
27331
28005
  debug: (obj) => logger22().debug(obj)
27332
28006
  },
27333
- nativeDatabaseProvider: {
27334
- open: async (requestedActorId) => {
27335
- void requestedActorId;
27336
- return getOrCreateNativeSqlDatabase(
27337
- this.#runtime,
27338
- this.#ctx
27339
- );
27340
- }
27341
- }
28007
+ nativeDatabaseProvider: registerNativeStateTransactionOpener(
28008
+ {
28009
+ open: async (requestedActorId) => {
28010
+ void requestedActorId;
28011
+ return getOrCreateNativeSqlDatabase(
28012
+ this.#runtime,
28013
+ this.#ctx
28014
+ );
28015
+ }
28016
+ },
28017
+ async (timeoutMs, context) => await getOrCreateNativeSqlDatabase(
28018
+ this.#runtime,
28019
+ this.#ctx
28020
+ ).beginStateTransaction(timeoutMs, context)
28021
+ )
27342
28022
  });
27343
28023
  runtimeState.databaseClient = {
27344
- client
28024
+ client: createdClient
27345
28025
  };
27346
- this.#db = client;
27347
- return client;
28026
+ this.#db = this.#bindDatabaseClient(createdClient);
28027
+ return this.#db;
28028
+ }
28029
+ #bindDatabaseClient(client) {
28030
+ return bindNativeStateTransactionContext(client, {
28031
+ enter: async () => await this.#enterStateTransaction(),
28032
+ exit: (scope) => this.#exitStateTransaction(
28033
+ scope
28034
+ )
28035
+ });
28036
+ }
28037
+ async #enterStateTransaction() {
28038
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28039
+ let pendingOwners = actorState.pendingStateTransactionOwners;
28040
+ if (!pendingOwners) {
28041
+ pendingOwners = /* @__PURE__ */ new Set();
28042
+ actorState.pendingStateTransactionOwners = pendingOwners;
28043
+ }
28044
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner || pendingOwners.has(this.#stateTransactionOwner)) {
28045
+ throw stateTransactionConflictError();
28046
+ }
28047
+ pendingOwners.add(this.#stateTransactionOwner);
28048
+ const predecessor = actorState.stateTransactionTail ?? Promise.resolve();
28049
+ let release;
28050
+ const hold = new Promise((resolve) => {
28051
+ release = resolve;
28052
+ });
28053
+ actorState.stateTransactionTail = predecessor.then(
28054
+ async () => await hold
28055
+ );
28056
+ try {
28057
+ await predecessor;
28058
+ pendingOwners.delete(this.#stateTransactionOwner);
28059
+ actorState.activeStateTransactionOwner = this.#stateTransactionOwner;
28060
+ return {
28061
+ actorContext: this,
28062
+ actorStateBaseline: this.#stateEnabled ? structuredClone(this.#readState()) : void 0,
28063
+ connectionStateBaselines: new Map(
28064
+ callNativeSync(
28065
+ () => this.#runtime.actorConns(this.#ctx)
28066
+ ).map((conn) => [
28067
+ callNativeSync(() => this.#runtime.connId(conn)),
28068
+ new Uint8Array(
28069
+ callNativeSync(() => this.#runtime.connState(conn))
28070
+ )
28071
+ ])
28072
+ ),
28073
+ committed: false,
28074
+ release
28075
+ };
28076
+ } catch (error46) {
28077
+ pendingOwners.delete(this.#stateTransactionOwner);
28078
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28079
+ actorState.activeStateTransactionOwner = void 0;
28080
+ }
28081
+ release();
28082
+ throw error46;
28083
+ }
28084
+ }
28085
+ #exitStateTransaction(scope) {
28086
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28087
+ try {
28088
+ if (!scope.committed) {
28089
+ this.#restoreStateTransactionBaseline(scope);
28090
+ }
28091
+ } finally {
28092
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28093
+ actorState.activeStateTransactionOwner = void 0;
28094
+ }
28095
+ if (actorState.stateTransactionSaveDeferred) {
28096
+ actorState.stateTransactionSaveDeferred = false;
28097
+ this.#scheduleSave();
28098
+ }
28099
+ scope.release();
28100
+ }
28101
+ }
28102
+ #restoreStateTransactionBaseline(scope) {
28103
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28104
+ if (actorState.pendingSaveHandle !== void 0) {
28105
+ clearImmediate(actorState.pendingSaveHandle);
28106
+ }
28107
+ actorState.pendingSaveHandle = void 0;
28108
+ actorState.saveScheduled = false;
28109
+ if (this.#stateEnabled) {
28110
+ actorState.state = structuredClone(scope.actorStateBaseline);
28111
+ }
28112
+ for (const conn of callNativeSync(
28113
+ () => this.#runtime.actorConns(this.#ctx)
28114
+ )) {
28115
+ const connId = callNativeSync(() => this.#runtime.connId(conn));
28116
+ const baseline = scope.connectionStateBaselines.get(connId);
28117
+ if (baseline === void 0) {
28118
+ continue;
28119
+ }
28120
+ callNativeSync(() => this.#runtime.connSetState(conn, baseline));
28121
+ const cached2 = actorState.connStates.get(connId);
28122
+ if (cached2) {
28123
+ cached2.state = decodeValue(baseline);
28124
+ }
28125
+ }
28126
+ this.#scheduleSave();
27348
28127
  }
27349
28128
  async prepare() {
27350
28129
  if (!this.#databaseProvider) {
@@ -27362,7 +28141,6 @@ var ActorContextHandleAdapter = class {
27362
28141
  }
27363
28142
  async closeDatabase() {
27364
28143
  this.#db = void 0;
27365
- this.#sql = void 0;
27366
28144
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
27367
28145
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
27368
28146
  }
@@ -27382,6 +28160,7 @@ var ActorContextHandleAdapter = class {
27382
28160
  }
27383
28161
  async saveState(opts) {
27384
28162
  if (opts == null ? void 0 : opts.immediate) {
28163
+ this.#assertCanAwaitStateSave();
27385
28164
  await callNative(
27386
28165
  () => this.#runtime.actorRequestSaveAndWait(this.#ctx, {
27387
28166
  immediate: true
@@ -27402,10 +28181,17 @@ var ActorContextHandleAdapter = class {
27402
28181
  );
27403
28182
  }
27404
28183
  async saveStateAndWorkflowBatch(writes) {
28184
+ this.#assertCanAwaitStateSave();
27405
28185
  await callNative(
27406
28186
  () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
27407
28187
  );
27408
28188
  }
28189
+ #assertCanAwaitStateSave() {
28190
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28191
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28192
+ throw stateTransactionConflictError();
28193
+ }
28194
+ }
27409
28195
  serializeForTick(reason) {
27410
28196
  void reason;
27411
28197
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -27459,10 +28245,6 @@ var ActorContextHandleAdapter = class {
27459
28245
  }
27460
28246
  return promise2;
27461
28247
  }
27462
- runHandlerActive() {
27463
- var _a2;
27464
- return ((_a2 = this.#runHandlerActiveProvider) == null ? void 0 : _a2.call(this)) ?? false;
27465
- }
27466
28248
  internalKeepAwake(run) {
27467
28249
  const promise2 = typeof run === "function" ? run() : run;
27468
28250
  const trackedPromise = promise2.then(
@@ -27544,7 +28326,6 @@ var ActorContextHandleAdapter = class {
27544
28326
  var _a2;
27545
28327
  this.#flushStateChange();
27546
28328
  (_a2 = this.#abortSignalCleanup) == null ? void 0 : _a2.call(this);
27547
- this.#sql = void 0;
27548
28329
  }
27549
28330
  #createActorAbortSignal() {
27550
28331
  const nativeSignal = callNativeSync(
@@ -27578,10 +28359,18 @@ var ActorContextHandleAdapter = class {
27578
28359
  this.#scheduleSave();
27579
28360
  }
27580
28361
  #assertCanMutateState() {
28362
+ var _a2;
27581
28363
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
27582
28364
  if (actorState.isInOnStateChange) {
27583
28365
  throw stateMutationReentrantError();
27584
28366
  }
28367
+ if (actorState.activeStateTransactionOwner !== this.#stateTransactionOwner && (actorState.activeStateTransactionOwner !== void 0 || (((_a2 = actorState.pendingStateTransactionOwners) == null ? void 0 : _a2.size) ?? 0) > 0)) {
28368
+ throw stateTransactionConflictError();
28369
+ }
28370
+ }
28371
+ /** @internal */
28372
+ assertCanMutateState() {
28373
+ this.#assertCanMutateState();
27585
28374
  }
27586
28375
  // Coalesce the request-save and onStateChange work to once per event loop
27587
28376
  // tick. A synchronous burst of mutations (for example
@@ -27603,6 +28392,15 @@ var ActorContextHandleAdapter = class {
27603
28392
  if (!actorState.saveScheduled) {
27604
28393
  return;
27605
28394
  }
28395
+ if (actorState.activeStateTransactionOwner !== void 0) {
28396
+ actorState.saveScheduled = false;
28397
+ if (actorState.pendingSaveHandle !== void 0) {
28398
+ clearImmediate(actorState.pendingSaveHandle);
28399
+ actorState.pendingSaveHandle = void 0;
28400
+ }
28401
+ actorState.stateTransactionSaveDeferred = true;
28402
+ return;
28403
+ }
27606
28404
  actorState.saveScheduled = false;
27607
28405
  if (actorState.pendingSaveHandle !== void 0) {
27608
28406
  clearImmediate(actorState.pendingSaveHandle);
@@ -27726,9 +28524,6 @@ var NativeWorkflowRuntimeAdapter = class {
27726
28524
  }
27727
28525
  };
27728
28526
  }
27729
- isRunHandlerActive() {
27730
- return this.#ctx.runHandlerActive();
27731
- }
27732
28527
  async restartRunHandler() {
27733
28528
  await this.#ctx.restartRunHandler();
27734
28529
  }
@@ -27761,43 +28556,45 @@ var NativeWorkflowRuntimeAdapter = class {
27761
28556
  };
27762
28557
  }
27763
28558
  };
27764
- function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken) {
27765
- return Object.assign(
27766
- new ActorContextHandleAdapter(
28559
+ function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken, runHandlerConfigured = false) {
28560
+ const actorContext = new ActorContextHandleAdapter(
28561
+ runtime,
28562
+ ctx,
28563
+ clientFactory,
28564
+ schemas,
28565
+ databaseProvider,
28566
+ request,
28567
+ stateEnabled,
28568
+ onStateChange,
28569
+ dispatchCancelToken,
28570
+ runHandlerConfigured
28571
+ );
28572
+ return Object.assign(actorContext, {
28573
+ conn: new NativeConnAdapter(
27767
28574
  runtime,
27768
- ctx,
27769
- clientFactory,
28575
+ conn,
27770
28576
  schemas,
27771
- databaseProvider,
27772
- request,
27773
- stateEnabled,
27774
- void 0,
27775
- onStateChange,
27776
- dispatchCancelToken
27777
- ),
27778
- {
27779
- conn: new NativeConnAdapter(
27780
- runtime,
27781
- conn,
27782
- schemas,
27783
- ctx,
27784
- (connId) => callNativeSync(
27785
- () => runtime.actorQueueHibernationRemoval(ctx, connId)
27786
- )
27787
- )
27788
- }
27789
- );
28577
+ ctx,
28578
+ (connId) => callNativeSync(
28579
+ () => runtime.actorQueueHibernationRemoval(ctx, connId)
28580
+ ),
28581
+ () => actorContext.assertCanMutateState()
28582
+ )
28583
+ });
27790
28584
  }
27791
28585
  function buildActorConfig(definition, registryConfig, runtimeKind) {
28586
+ var _a2;
27792
28587
  const config3 = definition.config;
27793
28588
  const options = config3.options ?? {};
27794
28589
  const canHibernate = options.canHibernateWebSocket;
27795
28590
  const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
28591
+ const sqliteProfiling = (_a2 = config3.db) == null ? void 0 : _a2.sqliteProfiling;
27796
28592
  return {
27797
28593
  name: options.name,
27798
28594
  icon: options.icon,
27799
- hasDatabase: config3.db !== void 0 || usesRemoteSqlite,
28595
+ hasDatabase: true,
27800
28596
  remoteSqlite: usesRemoteSqlite,
28597
+ sqliteProfiling,
27801
28598
  enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
27802
28599
  hasState: config3.state !== void 0 || typeof config3.createState === "function",
27803
28600
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
@@ -27896,7 +28693,7 @@ function validateInspectorTabSource(tabId, resolved) {
27896
28693
  function buildNativeFactory(runtime, registryConfig, definition) {
27897
28694
  var _a2;
27898
28695
  const config3 = definition.config;
27899
- const databaseProvider = config3.db;
28696
+ const databaseProvider = config3.db ?? db();
27900
28697
  const actionHandlers = flattenActionHandlers(config3.actions);
27901
28698
  const schemaConfig = {
27902
28699
  actionInputSchemas: flattenActionInputSchemas(
@@ -27913,16 +28710,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27913
28710
  ),
27914
28711
  { encoding: "bare" }
27915
28712
  );
27916
- const nativeRunHandlerActiveByActorId = /* @__PURE__ */ new Map();
27917
- const isNativeRunHandlerActive = (ctx) => nativeRunHandlerActiveByActorId.get(
27918
- callNativeSync(() => runtime.actorId(ctx))
27919
- ) ?? false;
28713
+ const run = getRunFunction(config3.run);
28714
+ const runHandlerCoordinator = getRunInspectorKind(config3.run) === "workflow" ? new RunHandlerCoordinator(config3.run) : void 0;
27920
28715
  const getNativeWorkflowInspector = (ctx) => {
27921
- var _a22;
27922
- return (_a22 = getRunInspectorConfig(
27923
- config3.run,
27924
- callNativeSync(() => runtime.actorId(ctx))
27925
- )) == null ? void 0 : _a22.workflow;
28716
+ var _a22, _b;
28717
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
28718
+ const restart = () => callNativeSync(() => runtime.actorRestartRunHandler(ctx));
28719
+ 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);
27926
28720
  };
27927
28721
  const onStateChange = typeof config3.onStateChange === "function" ? (actorCtx, nextState) => {
27928
28722
  config3.onStateChange(actorCtx, nextState);
@@ -27942,9 +28736,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27942
28736
  databaseProvider,
27943
28737
  request,
27944
28738
  stateEnabled,
27945
- () => isNativeRunHandlerActive(ctx),
27946
28739
  onStateChange,
27947
- cancelToken
28740
+ cancelToken,
28741
+ run !== void 0
27948
28742
  );
27949
28743
  const makeConnCtx = (ctx, conn, request, cancelToken) => withConnContext(
27950
28744
  runtime,
@@ -27956,7 +28750,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27956
28750
  request,
27957
28751
  stateEnabled,
27958
28752
  onStateChange,
27959
- cancelToken
28753
+ cancelToken,
28754
+ run !== void 0
27960
28755
  );
27961
28756
  const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
27962
28757
  var _a22, _b, _c, _d;
@@ -28007,6 +28802,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28007
28802
  return await ((_b2 = (_a3 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3)) ?? null;
28008
28803
  };
28009
28804
  const actorCtx = makeActorCtx(ctx, jsRequest);
28805
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
28010
28806
  try {
28011
28807
  if (url2.pathname === "/inspector/state" && jsRequest.method === "GET") {
28012
28808
  return jsonResponse({
@@ -28134,9 +28930,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28134
28930
  }
28135
28931
  }
28136
28932
  if (url2.pathname === "/inspector/database/schema" && jsRequest.method === "GET") {
28137
- const db = actorCtx.sql;
28933
+ const db2 = sql;
28138
28934
  const tables = queryRows(
28139
- await db.query(
28935
+ await db2.query(
28140
28936
  "SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '__drizzle_%' ORDER BY name"
28141
28937
  )
28142
28938
  );
@@ -28144,13 +28940,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28144
28940
  for (const table of tables) {
28145
28941
  const quoted = `"${table.name.replace(/"/g, '""')}"`;
28146
28942
  const columns = queryRows(
28147
- await db.query(`PRAGMA table_info(${quoted})`)
28943
+ await db2.query(`PRAGMA table_info(${quoted})`)
28148
28944
  );
28149
28945
  const foreignKeys = queryRows(
28150
- await db.query(`PRAGMA foreign_key_list(${quoted})`)
28946
+ await db2.query(`PRAGMA foreign_key_list(${quoted})`)
28151
28947
  );
28152
28948
  const countResult = queryRows(
28153
- await db.query(
28949
+ await db2.query(
28154
28950
  `SELECT COUNT(*) as count FROM ${quoted}`
28155
28951
  )
28156
28952
  );
@@ -28185,7 +28981,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28185
28981
  );
28186
28982
  const quoted = `"${table.replace(/"/g, '""')}"`;
28187
28983
  const rows = queryRows(
28188
- await actorCtx.sql.query(
28984
+ await sql.query(
28189
28985
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
28190
28986
  [
28191
28987
  Math.max(0, Math.min(limit, 500)),
@@ -28213,15 +29009,11 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28213
29009
  const bindings = normalizeSqlitePropertyBindings(
28214
29010
  body.properties
28215
29011
  );
28216
- const rows2 = queryRows(
28217
- await actorCtx.sql.query(body.sql, bindings)
28218
- );
29012
+ const rows2 = queryRows(await sql.query(body.sql, bindings));
28219
29013
  return jsonResponse({ rows: jsonSafe(rows2) });
28220
29014
  }
28221
29015
  const args = Array.isArray(body.args) ? body.args : [];
28222
- const rows = queryRows(
28223
- await actorCtx.sql.query(body.sql, args)
28224
- );
29016
+ const rows = queryRows(await sql.query(body.sql, args));
28225
29017
  return jsonResponse({ rows: jsonSafe(rows) });
28226
29018
  }
28227
29019
  if (url2.pathname === "/inspector/summary" && jsRequest.method === "GET") {
@@ -28247,7 +29039,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28247
29039
  rpcs: Object.keys(actionHandlers).sort(),
28248
29040
  queueSize: inspectorSnapshot.queueSize,
28249
29041
  isStateEnabled: stateEnabled,
28250
- isDatabaseEnabled: databaseProvider !== void 0,
29042
+ isDatabaseEnabled: true,
28251
29043
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0,
28252
29044
  workflowState: await workflowState(),
28253
29045
  workflowHistory: workflowHistory()
@@ -28437,6 +29229,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28437
29229
  async (error46, payload) => {
28438
29230
  const { ctx } = unwrapTsfnPayload(error46, payload);
28439
29231
  const actorCtx = makeActorCtx(ctx);
29232
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
28440
29233
  const saveActorState = async () => {
28441
29234
  if (runtime.kind === "wasm") {
28442
29235
  await runtime.actorSaveState(
@@ -28462,6 +29255,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28462
29255
  saveActorState
28463
29256
  );
28464
29257
  } finally {
29258
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
29259
+ disposeRunInspector(config3.run, actorId);
28465
29260
  await actorCtx.dispose();
28466
29261
  }
28467
29262
  }
@@ -28471,14 +29266,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28471
29266
  async (error46, payload) => {
28472
29267
  const { ctx } = unwrapTsfnPayload(error46, payload);
28473
29268
  const actorCtx = makeActorCtx(ctx);
29269
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
29270
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
29271
+ disposeRunInspector(config3.run, actorId);
28474
29272
  try {
28475
29273
  if (typeof config3.onDestroy === "function") {
28476
29274
  await config3.onDestroy(actorCtx);
28477
29275
  }
28478
29276
  } finally {
28479
- const actorId = callNativeSync(() => runtime.actorId(ctx));
28480
- nativeRunHandlerActiveByActorId.delete(actorId);
28481
- disposeRunInspector(config3.run, actorId);
28482
29277
  resolveNativeDestroy(runtime, ctx);
28483
29278
  await actorCtx.closeDatabase();
28484
29279
  clearNativeRuntimeState(runtime, ctx);
@@ -28526,7 +29321,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28526
29321
  ctx,
28527
29322
  connId
28528
29323
  )
28529
- )
29324
+ ),
29325
+ () => actorCtx.assertCanMutateState()
28530
29326
  );
28531
29327
  try {
28532
29328
  const nextConnState = hasStaticConnState ? structuredClone(config3.connState) : await config3.createConnState(
@@ -28563,7 +29359,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28563
29359
  ctx,
28564
29360
  connId
28565
29361
  )
28566
- )
29362
+ ),
29363
+ () => actorCtx.assertCanMutateState()
28567
29364
  );
28568
29365
  try {
28569
29366
  await config3.onConnect(
@@ -28595,7 +29392,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28595
29392
  ctx,
28596
29393
  connId
28597
29394
  )
28598
- )
29395
+ ),
29396
+ () => actorCtx.assertCanMutateState()
28599
29397
  )
28600
29398
  );
28601
29399
  }
@@ -28739,7 +29537,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28739
29537
  }
28740
29538
  ) : void 0,
28741
29539
  run: (() => {
28742
- const run = getRunFunction(config3.run);
28743
29540
  if (!run) {
28744
29541
  return void 0;
28745
29542
  }
@@ -28747,18 +29544,30 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28747
29544
  async (error46, payload) => {
28748
29545
  const { ctx } = unwrapTsfnPayload(error46, payload);
28749
29546
  const actorId = callNativeSync(() => runtime.actorId(ctx));
28750
- const actorCtx = makeActorCtx(ctx);
28751
- nativeRunHandlerActiveByActorId.set(actorId, true);
28752
- try {
28753
- await run(actorCtx);
28754
- } finally {
28755
- nativeRunHandlerActiveByActorId.delete(actorId);
28756
- await actorCtx.dispose();
29547
+ const executeRun = async () => {
29548
+ const actorCtx = makeActorCtx(ctx);
29549
+ try {
29550
+ await run(actorCtx);
29551
+ } finally {
29552
+ await actorCtx.dispose();
29553
+ }
29554
+ };
29555
+ if (runHandlerCoordinator) {
29556
+ const outcome = await runHandlerCoordinator.run(
29557
+ actorId,
29558
+ () => callNativeSync(
29559
+ () => runtime.actorRestartRunHandler(ctx)
29560
+ ),
29561
+ executeRun
29562
+ );
29563
+ return outcome !== "suppressed";
28757
29564
  }
29565
+ await executeRun();
29566
+ return true;
28758
29567
  }
28759
29568
  );
28760
29569
  })(),
28761
- getWorkflowHistory: getRunInspectorConfig(config3.run) !== void 0 ? wrapNativeCallback(
29570
+ getWorkflowHistory: hasRunInspectorConfig(config3.run) ? wrapNativeCallback(
28762
29571
  async (error46, payload) => {
28763
29572
  var _a22;
28764
29573
  const { ctx } = unwrapTsfnPayload(error46, payload);
@@ -28766,7 +29575,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28766
29575
  return history == null ? void 0 : toUint8Array(history);
28767
29576
  }
28768
29577
  ) : void 0,
28769
- replayWorkflow: getRunInspectorConfig(config3.run) !== void 0 ? wrapNativeCallback(
29578
+ replayWorkflow: hasRunInspectorConfig(config3.run) ? wrapNativeCallback(
28770
29579
  async (error46, payload) => {
28771
29580
  const { ctx, entryId } = unwrapTsfnPayload(
28772
29581
  error46,
@@ -28776,9 +29585,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28776
29585
  if (!(workflowInspector == null ? void 0 : workflowInspector.replayFromStep)) {
28777
29586
  return void 0;
28778
29587
  }
28779
- const history = await workflowInspector.replayFromStep(
28780
- entryId
28781
- ) ?? null;
29588
+ const history = await workflowInspector.replayFromStep(entryId) ?? null;
28782
29589
  return history == null ? void 0 : toUint8Array(history);
28783
29590
  }
28784
29591
  ) : void 0,
@@ -28831,7 +29638,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28831
29638
  jsRequest,
28832
29639
  stateEnabled,
28833
29640
  onStateChange,
28834
- cancelToken
29641
+ cancelToken,
29642
+ run !== void 0
28835
29643
  );
28836
29644
  try {
28837
29645
  if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
@@ -29800,6 +30608,7 @@ export {
29800
30608
  actor,
29801
30609
  buildActorNames,
29802
30610
  createClientWithDriver,
30611
+ defineRunHandler,
29803
30612
  event,
29804
30613
  isStaticActorDefinition,
29805
30614
  isStaticActorInstance,