@rivetkit/supabase 2.3.11-rc.8 → 2.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/mod.js +1088 -181
  2. package/dist/mod.mjs +1085 -178
  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-AGNBLCNJ.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-AGNBLCNJ.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.8",
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-4EDGOGCB.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,8 +15529,63 @@ function removePrefixFromKey(prefixedKey) {
15484
15529
  return prefixedKey.slice(KEYS.KV.length);
15485
15530
  }
15486
15531
 
15487
- // ../rivetkit/dist/tsup/chunk-7AFZMFPQ.js
15532
+ // ../rivetkit/dist/tsup/chunk-JTHHCZCZ.js
15488
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
+ }
15489
15589
  var AsyncMutex = class {
15490
15590
  #locked = false;
15491
15591
  #waiting = [];
@@ -15512,7 +15612,7 @@ var AsyncMutex = class {
15512
15612
  }
15513
15613
  };
15514
15614
 
15515
- // ../rivetkit/dist/tsup/chunk-V6ANE6JM.js
15615
+ // ../rivetkit/dist/tsup/chunk-FWROC5LA.js
15516
15616
  function logger() {
15517
15617
  return getLogger("actor-client");
15518
15618
  }
@@ -15550,7 +15650,7 @@ async function importWebSocket() {
15550
15650
  return webSocketPromise;
15551
15651
  }
15552
15652
 
15553
- // ../rivetkit/dist/tsup/chunk-JBQ63WSM.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-JBQ63WSM.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) {
24092
+ const release = gate.enter();
24093
+ let transaction;
24094
+ try {
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
+ }
23768
24111
  const release = gate.enter();
23769
24112
  let transaction;
23770
24113
  try {
23771
- transaction = await database.beginTransaction(timeoutMs);
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(
@@ -25352,6 +25920,83 @@ function createWriteThroughProxy(value, commit, beforeChange) {
25352
25920
  }
25353
25921
  );
25354
25922
  }
25923
+ function unwrapProxy(value) {
25924
+ let current = value;
25925
+ while (current !== null && typeof current === "object") {
25926
+ const target = source_default.target(current);
25927
+ if (target === current) {
25928
+ break;
25929
+ }
25930
+ current = target;
25931
+ }
25932
+ return current;
25933
+ }
25934
+ function isPlainObject4(value) {
25935
+ const proto = Object.getPrototypeOf(value);
25936
+ return proto === Object.prototype || proto === null;
25937
+ }
25938
+ function unwrapDeep(value, seen) {
25939
+ const unwrapped = unwrapProxy(value);
25940
+ if (!unwrapped || typeof unwrapped !== "object") {
25941
+ return unwrapped;
25942
+ }
25943
+ if (seen.has(unwrapped)) {
25944
+ return unwrapped;
25945
+ }
25946
+ seen.add(unwrapped);
25947
+ if (Array.isArray(unwrapped)) {
25948
+ for (let i = 0; i < unwrapped.length; i++) {
25949
+ const child = unwrapDeep(unwrapped[i], seen);
25950
+ if (child !== unwrapped[i]) {
25951
+ unwrapped[i] = child;
25952
+ }
25953
+ }
25954
+ return unwrapped;
25955
+ }
25956
+ if (unwrapped instanceof Map) {
25957
+ const replacements = [];
25958
+ for (const [key, child] of unwrapped.entries()) {
25959
+ const nextKey = unwrapDeep(key, seen);
25960
+ const nextChild = unwrapDeep(child, seen);
25961
+ if (nextKey !== key || nextChild !== child) {
25962
+ replacements.push([key, nextKey, nextChild]);
25963
+ }
25964
+ }
25965
+ for (const [key, nextKey, nextChild] of replacements) {
25966
+ if (nextKey !== key) {
25967
+ unwrapped.delete(key);
25968
+ }
25969
+ unwrapped.set(nextKey, nextChild);
25970
+ }
25971
+ return unwrapped;
25972
+ }
25973
+ if (unwrapped instanceof Set) {
25974
+ const replacements = [];
25975
+ for (const child of unwrapped.values()) {
25976
+ const next = unwrapDeep(child, seen);
25977
+ if (next !== child) {
25978
+ replacements.push([child, next]);
25979
+ }
25980
+ }
25981
+ for (const [child, next] of replacements) {
25982
+ unwrapped.delete(child);
25983
+ unwrapped.add(next);
25984
+ }
25985
+ return unwrapped;
25986
+ }
25987
+ if (isPlainObject4(unwrapped)) {
25988
+ for (const key of Object.keys(unwrapped)) {
25989
+ const child = unwrapDeep(unwrapped[key], seen);
25990
+ if (child !== unwrapped[key]) {
25991
+ unwrapped[key] = child;
25992
+ }
25993
+ }
25994
+ }
25995
+ return unwrapped;
25996
+ }
25997
+ function unwrapWriteThroughProxy(value) {
25998
+ return unwrapDeep(value, /* @__PURE__ */ new Set());
25999
+ }
25355
26000
  var textEncoder = new TextEncoder();
25356
26001
  var textDecoder = new TextDecoder();
25357
26002
  var defaultRuntimeLoaders = {
@@ -25496,6 +26141,14 @@ function stateMutationReentrantError() {
25496
26141
  "State mutations are not allowed inside onStateChange."
25497
26142
  );
25498
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
+ }
25499
26152
  function databaseNotConfiguredError() {
25500
26153
  return new RivetError(
25501
26154
  "actor",
@@ -25512,6 +26165,14 @@ function databaseClientNotReadyError() {
25512
26165
  { public: true }
25513
26166
  );
25514
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
+ }
25515
26176
  function stateNotEnabledError() {
25516
26177
  return new RivetError(
25517
26178
  "actor",
@@ -25614,10 +26275,11 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
25614
26275
  exec: (sql) => runtime.actorSqlExec(ctx, sql),
25615
26276
  execute: (sql, params) => runtime.actorSqlExecute(ctx, sql, params),
25616
26277
  executeBatch: (statements) => runtime.actorSqlExecuteBatch(ctx, statements),
25617
- beginTransaction: async (timeoutMs) => {
26278
+ beginTransaction: async (timeoutMs, name) => {
25618
26279
  const transaction = await runtime.actorSqlBeginTransaction(
25619
26280
  ctx,
25620
- timeoutMs
26281
+ timeoutMs,
26282
+ name
25621
26283
  );
25622
26284
  return {
25623
26285
  exec: (sql) => runtime.actorSqlTransactionExec(transaction, sql),
@@ -25630,6 +26292,38 @@ function getOrCreateNativeSqlDatabase(runtime, ctx) {
25630
26292
  rollback: () => runtime.actorSqlTransactionRollback(transaction)
25631
26293
  };
25632
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
+ },
25633
26327
  query: (sql, params) => runtime.actorSqlQuery(ctx, sql, params),
25634
26328
  run: (sql, params) => runtime.actorSqlRun(ctx, sql, params),
25635
26329
  metrics: () => runtime.actorSqlMetrics(ctx),
@@ -26010,12 +26704,16 @@ var NativeConnAdapter = class {
26010
26704
  #schemas;
26011
26705
  #ctx;
26012
26706
  #queueHibernationRemoval;
26013
- constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval) {
26707
+ #assertCanMutateState;
26708
+ #stateProxy;
26709
+ #stateProxyTarget;
26710
+ constructor(runtime, conn, schemas = {}, ctx, queueHibernationRemoval, assertCanMutateState) {
26014
26711
  this.#runtime = runtime;
26015
26712
  this.#conn = conn;
26016
26713
  this.#schemas = schemas;
26017
26714
  this.#ctx = ctx;
26018
26715
  this.#queueHibernationRemoval = queueHibernationRemoval;
26716
+ this.#assertCanMutateState = assertCanMutateState;
26019
26717
  this[CONN_STATE_MANAGER_SYMBOL] = {
26020
26718
  stateEnabled: true,
26021
26719
  get state() {
@@ -26038,22 +26736,46 @@ var NativeConnAdapter = class {
26038
26736
  }
26039
26737
  get state() {
26040
26738
  const nextState = this.#readState();
26739
+ if (!this.#ctx) {
26740
+ return this.#createStateProxy(nextState);
26741
+ }
26742
+ if (this.#stateProxy === void 0 || this.#stateProxyTarget !== nextState) {
26743
+ this.#stateProxyTarget = nextState;
26744
+ this.#stateProxy = this.#createStateProxy(nextState);
26745
+ }
26746
+ return this.#stateProxy;
26747
+ }
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
+ };
26041
26756
  return createWriteThroughProxy(
26042
- nextState,
26757
+ state,
26043
26758
  (nextValue) => {
26759
+ assertCurrentState();
26044
26760
  this.#writeState(nextValue, { writeNative: true });
26045
26761
  },
26046
26762
  (newValue) => {
26763
+ assertCurrentState();
26047
26764
  assertJsonCompatValue(newValue);
26048
26765
  }
26049
26766
  );
26050
26767
  }
26051
26768
  set state(value) {
26052
- assertJsonCompatValue(value);
26053
- this.#writeState(value, { writeNative: true });
26769
+ var _a2;
26770
+ (_a2 = this.#assertCanMutateState) == null ? void 0 : _a2.call(this);
26771
+ const nextValue = unwrapWriteThroughProxy(value);
26772
+ assertJsonCompatValue(nextValue);
26773
+ this.#writeState(nextValue, { writeNative: true });
26054
26774
  }
26055
26775
  initializeState(value) {
26056
- this.#writeState(value, { writeNative: false });
26776
+ this.#writeState(unwrapWriteThroughProxy(value), {
26777
+ writeNative: false
26778
+ });
26057
26779
  }
26058
26780
  get isHibernatable() {
26059
26781
  return callNativeSync(
@@ -26371,8 +27093,9 @@ var NativeKvAdapter = class {
26371
27093
  };
26372
27094
  function wrapQueueMessage(message, schemas) {
26373
27095
  const name = callNativeSync(() => message.name());
27096
+ const id = callNativeSync(() => message.id());
26374
27097
  return {
26375
- id: Number(callNativeSync(() => message.id())),
27098
+ id: id <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(id) : id,
26376
27099
  name,
26377
27100
  body: validateQueueBody(
26378
27101
  schemas,
@@ -26510,6 +27233,25 @@ var NativeQueueAdapter = class {
26510
27233
  cleanup == null ? void 0 : cleanup();
26511
27234
  }
26512
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
+ }
26513
27255
  async enqueueAndWait(name, body, options) {
26514
27256
  const validatedBody = validateQueueBody(this.#schemas, name, body);
26515
27257
  const { token, cleanup } = await createCancellationTokenHandle(
@@ -26946,10 +27688,12 @@ var NativeConnectionMap = class {
26946
27688
  #runtime;
26947
27689
  #ctx;
26948
27690
  #schemas;
26949
- constructor(runtime, ctx, schemas) {
27691
+ #assertCanMutateState;
27692
+ constructor(runtime, ctx, schemas, assertCanMutateState) {
26950
27693
  this.#runtime = runtime;
26951
27694
  this.#ctx = ctx;
26952
27695
  this.#schemas = schemas;
27696
+ this.#assertCanMutateState = assertCanMutateState;
26953
27697
  }
26954
27698
  #connToAdapter(conn) {
26955
27699
  return new NativeConnAdapter(
@@ -26962,7 +27706,8 @@ var NativeConnectionMap = class {
26962
27706
  this.#ctx,
26963
27707
  connId
26964
27708
  )
26965
- )
27709
+ ),
27710
+ this.#assertCanMutateState
26966
27711
  );
26967
27712
  }
26968
27713
  get size() {
@@ -27021,17 +27766,20 @@ var ActorContextHandleAdapter = class {
27021
27766
  #queue;
27022
27767
  #request;
27023
27768
  #schedule;
27024
- #sql;
27025
- #runHandlerActiveProvider;
27769
+ #run;
27770
+ #runHandlerConfigured;
27026
27771
  #onStateChange;
27027
27772
  #stateEnabled;
27028
- 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) {
27029
27777
  this.#runtime = runtime;
27030
27778
  this.#ctx = ctx;
27031
27779
  this.#clientFactory = clientFactory;
27032
27780
  this.#schemas = schemas;
27033
27781
  this.#dispatchCancelToken = dispatchCancelToken;
27034
- this.#runHandlerActiveProvider = runHandlerActiveProvider;
27782
+ this.#runHandlerConfigured = runHandlerConfigured;
27035
27783
  this.#onStateChange = onStateChange;
27036
27784
  this.#stateEnabled = stateEnabled;
27037
27785
  if (databaseProvider) {
@@ -27048,12 +27796,6 @@ var ActorContextHandleAdapter = class {
27048
27796
  }
27049
27797
  return this.#kv;
27050
27798
  }
27051
- get sql() {
27052
- if (!this.#sql) {
27053
- this.#sql = getOrCreateNativeSqlDatabase(this.#runtime, this.#ctx);
27054
- }
27055
- return this.#sql;
27056
- }
27057
27799
  async actorRuntimeSocket() {
27058
27800
  return await callNative(
27059
27801
  () => this.#runtime.actorRuntimeSocketProvision(this.#ctx)
@@ -27069,7 +27811,7 @@ var ActorContextHandleAdapter = class {
27069
27811
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
27070
27812
  const cachedClient = runtimeState.databaseClient;
27071
27813
  if (cachedClient) {
27072
- this.#db = cachedClient.client;
27814
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
27073
27815
  return this.#db;
27074
27816
  }
27075
27817
  throw databaseClientNotReadyError();
@@ -27084,36 +27826,45 @@ var ActorContextHandleAdapter = class {
27084
27826
  if (!this.#stateEnabled) {
27085
27827
  throw stateNotEnabledError();
27086
27828
  }
27087
- const actorState = getNativePersistState(this.#runtime, this.#ctx);
27088
27829
  const nextState = this.#readState();
27089
- if (actorState.stateProxy === void 0 || actorState.stateProxyTarget !== nextState) {
27090
- actorState.stateProxyTarget = nextState;
27091
- 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(
27092
27839
  nextState,
27093
27840
  (nextValue) => {
27841
+ assertCurrentState();
27094
27842
  this.#writeState(nextValue, { scheduleSave: true });
27095
27843
  },
27096
27844
  (newValue) => {
27097
- this.#assertCanMutateState();
27845
+ assertCurrentState();
27098
27846
  assertJsonCompatValue(newValue);
27099
27847
  }
27100
27848
  );
27101
27849
  }
27102
- return actorState.stateProxy;
27850
+ return this.#stateProxy;
27103
27851
  }
27104
27852
  set state(value) {
27105
27853
  if (!this.#stateEnabled) {
27106
27854
  throw stateNotEnabledError();
27107
27855
  }
27108
27856
  this.#assertCanMutateState();
27109
- assertJsonCompatValue(value);
27110
- this.#writeState(value, { scheduleSave: true });
27857
+ const nextValue = unwrapWriteThroughProxy(value);
27858
+ assertJsonCompatValue(nextValue);
27859
+ this.#writeState(nextValue, { scheduleSave: true });
27111
27860
  }
27112
27861
  initializeState(value) {
27113
27862
  if (!this.#stateEnabled) {
27114
27863
  return;
27115
27864
  }
27116
- this.#writeState(value, { scheduleSave: false });
27865
+ this.#writeState(unwrapWriteThroughProxy(value), {
27866
+ scheduleSave: false
27867
+ });
27117
27868
  }
27118
27869
  get vars() {
27119
27870
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
@@ -27139,6 +27890,26 @@ var ActorContextHandleAdapter = class {
27139
27890
  }
27140
27891
  return this.#queue;
27141
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
+ }
27142
27913
  get schedule() {
27143
27914
  if (!this.#schedule) {
27144
27915
  this.#schedule = new NativeScheduleAdapter(
@@ -27173,7 +27944,8 @@ var ActorContextHandleAdapter = class {
27173
27944
  this.#connMap = new NativeConnectionMap(
27174
27945
  this.#runtime,
27175
27946
  this.#ctx,
27176
- this.#schemas
27947
+ this.#schemas,
27948
+ () => this.#assertCanMutateState()
27177
27949
  );
27178
27950
  }
27179
27951
  return this.#connMap;
@@ -27242,11 +28014,11 @@ var ActorContextHandleAdapter = class {
27242
28014
  const runtimeState = getNativeRuntimeState(this.#runtime, this.#ctx);
27243
28015
  const cachedClient = runtimeState.databaseClient;
27244
28016
  if (cachedClient) {
27245
- this.#db = cachedClient.client;
28017
+ this.#db = this.#bindDatabaseClient(cachedClient.client);
27246
28018
  return this.#db;
27247
28019
  }
27248
28020
  const actorId = this.actorId;
27249
- const client = await this.#databaseProvider.createClient({
28021
+ const createdClient = await this.#databaseProvider.createClient({
27250
28022
  actorId,
27251
28023
  kv: {
27252
28024
  batchPut: async (entries) => {
@@ -27267,21 +28039,126 @@ var ActorContextHandleAdapter = class {
27267
28039
  log: {
27268
28040
  debug: (obj) => logger22().debug(obj)
27269
28041
  },
27270
- nativeDatabaseProvider: {
27271
- open: async (requestedActorId) => {
27272
- void requestedActorId;
27273
- return getOrCreateNativeSqlDatabase(
27274
- this.#runtime,
27275
- this.#ctx
27276
- );
27277
- }
27278
- }
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
+ )
27279
28057
  });
27280
28058
  runtimeState.databaseClient = {
27281
- client
28059
+ client: createdClient
27282
28060
  };
27283
- this.#db = client;
27284
- 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();
27285
28162
  }
27286
28163
  async prepare() {
27287
28164
  if (!this.#databaseProvider) {
@@ -27299,7 +28176,6 @@ var ActorContextHandleAdapter = class {
27299
28176
  }
27300
28177
  async closeDatabase() {
27301
28178
  this.#db = void 0;
27302
- this.#sql = void 0;
27303
28179
  await closeNativeDatabaseClient(this.#runtime, this.#ctx);
27304
28180
  await closeNativeSqlDatabase(this.#runtime, this.#ctx);
27305
28181
  }
@@ -27319,6 +28195,7 @@ var ActorContextHandleAdapter = class {
27319
28195
  }
27320
28196
  async saveState(opts) {
27321
28197
  if (opts == null ? void 0 : opts.immediate) {
28198
+ this.#assertCanAwaitStateSave();
27322
28199
  await callNative(
27323
28200
  () => this.#runtime.actorRequestSaveAndWait(this.#ctx, {
27324
28201
  immediate: true
@@ -27339,10 +28216,17 @@ var ActorContextHandleAdapter = class {
27339
28216
  );
27340
28217
  }
27341
28218
  async saveStateAndWorkflowBatch(writes) {
28219
+ this.#assertCanAwaitStateSave();
27342
28220
  await callNative(
27343
28221
  () => this.#runtime.actorSaveStateAndWorkflowBatch(this.#ctx, writes)
27344
28222
  );
27345
28223
  }
28224
+ #assertCanAwaitStateSave() {
28225
+ const actorState = getNativePersistState(this.#runtime, this.#ctx);
28226
+ if (actorState.activeStateTransactionOwner === this.#stateTransactionOwner) {
28227
+ throw stateTransactionConflictError();
28228
+ }
28229
+ }
27346
28230
  serializeForTick(reason) {
27347
28231
  void reason;
27348
28232
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
@@ -27396,10 +28280,6 @@ var ActorContextHandleAdapter = class {
27396
28280
  }
27397
28281
  return promise2;
27398
28282
  }
27399
- runHandlerActive() {
27400
- var _a2;
27401
- return ((_a2 = this.#runHandlerActiveProvider) == null ? void 0 : _a2.call(this)) ?? false;
27402
- }
27403
28283
  internalKeepAwake(run) {
27404
28284
  const promise2 = typeof run === "function" ? run() : run;
27405
28285
  const trackedPromise = promise2.then(
@@ -27481,7 +28361,6 @@ var ActorContextHandleAdapter = class {
27481
28361
  var _a2;
27482
28362
  this.#flushStateChange();
27483
28363
  (_a2 = this.#abortSignalCleanup) == null ? void 0 : _a2.call(this);
27484
- this.#sql = void 0;
27485
28364
  }
27486
28365
  #createActorAbortSignal() {
27487
28366
  const nativeSignal = callNativeSync(
@@ -27515,10 +28394,18 @@ var ActorContextHandleAdapter = class {
27515
28394
  this.#scheduleSave();
27516
28395
  }
27517
28396
  #assertCanMutateState() {
28397
+ var _a2;
27518
28398
  const actorState = getNativePersistState(this.#runtime, this.#ctx);
27519
28399
  if (actorState.isInOnStateChange) {
27520
28400
  throw stateMutationReentrantError();
27521
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();
27522
28409
  }
27523
28410
  // Coalesce the request-save and onStateChange work to once per event loop
27524
28411
  // tick. A synchronous burst of mutations (for example
@@ -27540,6 +28427,15 @@ var ActorContextHandleAdapter = class {
27540
28427
  if (!actorState.saveScheduled) {
27541
28428
  return;
27542
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
+ }
27543
28439
  actorState.saveScheduled = false;
27544
28440
  if (actorState.pendingSaveHandle !== void 0) {
27545
28441
  clearImmediate(actorState.pendingSaveHandle);
@@ -27663,9 +28559,6 @@ var NativeWorkflowRuntimeAdapter = class {
27663
28559
  }
27664
28560
  };
27665
28561
  }
27666
- isRunHandlerActive() {
27667
- return this.#ctx.runHandlerActive();
27668
- }
27669
28562
  async restartRunHandler() {
27670
28563
  await this.#ctx.restartRunHandler();
27671
28564
  }
@@ -27698,43 +28591,45 @@ var NativeWorkflowRuntimeAdapter = class {
27698
28591
  };
27699
28592
  }
27700
28593
  };
27701
- function withConnContext(runtime, ctx, conn, clientFactory, schemas = {}, databaseProvider, request, stateEnabled = true, onStateChange, dispatchCancelToken) {
27702
- return Object.assign(
27703
- 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(
27704
28609
  runtime,
27705
- ctx,
27706
- clientFactory,
28610
+ conn,
27707
28611
  schemas,
27708
- databaseProvider,
27709
- request,
27710
- stateEnabled,
27711
- void 0,
27712
- onStateChange,
27713
- dispatchCancelToken
27714
- ),
27715
- {
27716
- conn: new NativeConnAdapter(
27717
- runtime,
27718
- conn,
27719
- schemas,
27720
- ctx,
27721
- (connId) => callNativeSync(
27722
- () => runtime.actorQueueHibernationRemoval(ctx, connId)
27723
- )
27724
- )
27725
- }
27726
- );
28612
+ ctx,
28613
+ (connId) => callNativeSync(
28614
+ () => runtime.actorQueueHibernationRemoval(ctx, connId)
28615
+ ),
28616
+ () => actorContext.assertCanMutateState()
28617
+ )
28618
+ });
27727
28619
  }
27728
28620
  function buildActorConfig(definition, registryConfig, runtimeKind) {
28621
+ var _a2;
27729
28622
  const config3 = definition.config;
27730
28623
  const options = config3.options ?? {};
27731
28624
  const canHibernate = options.canHibernateWebSocket;
27732
28625
  const usesRemoteSqlite = sqliteBackendForConfig(registryConfig) === "remote";
28626
+ const sqliteProfiling = (_a2 = config3.db) == null ? void 0 : _a2.sqliteProfiling;
27733
28627
  return {
27734
28628
  name: options.name,
27735
28629
  icon: options.icon,
27736
- hasDatabase: config3.db !== void 0 || usesRemoteSqlite,
28630
+ hasDatabase: true,
27737
28631
  remoteSqlite: usesRemoteSqlite,
28632
+ sqliteProfiling,
27738
28633
  enableActorRuntimeSocket: options.enableActorRuntimeSocket === true,
27739
28634
  hasState: config3.state !== void 0 || typeof config3.createState === "function",
27740
28635
  canHibernateWebsocket: typeof canHibernate === "boolean" ? canHibernate : void 0,
@@ -27833,7 +28728,7 @@ function validateInspectorTabSource(tabId, resolved) {
27833
28728
  function buildNativeFactory(runtime, registryConfig, definition) {
27834
28729
  var _a2;
27835
28730
  const config3 = definition.config;
27836
- const databaseProvider = config3.db;
28731
+ const databaseProvider = config3.db ?? db();
27837
28732
  const actionHandlers = flattenActionHandlers(config3.actions);
27838
28733
  const schemaConfig = {
27839
28734
  actionInputSchemas: flattenActionInputSchemas(
@@ -27850,16 +28745,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27850
28745
  ),
27851
28746
  { encoding: "bare" }
27852
28747
  );
27853
- const nativeRunHandlerActiveByActorId = /* @__PURE__ */ new Map();
27854
- const isNativeRunHandlerActive = (ctx) => nativeRunHandlerActiveByActorId.get(
27855
- callNativeSync(() => runtime.actorId(ctx))
27856
- ) ?? false;
28748
+ const run = getRunFunction(config3.run);
28749
+ const runHandlerCoordinator = getRunInspectorKind(config3.run) === "workflow" ? new RunHandlerCoordinator(config3.run) : void 0;
27857
28750
  const getNativeWorkflowInspector = (ctx) => {
27858
- var _a22;
27859
- return (_a22 = getRunInspectorConfig(
27860
- config3.run,
27861
- callNativeSync(() => runtime.actorId(ctx))
27862
- )) == 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);
27863
28755
  };
27864
28756
  const onStateChange = typeof config3.onStateChange === "function" ? (actorCtx, nextState) => {
27865
28757
  config3.onStateChange(actorCtx, nextState);
@@ -27879,9 +28771,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27879
28771
  databaseProvider,
27880
28772
  request,
27881
28773
  stateEnabled,
27882
- () => isNativeRunHandlerActive(ctx),
27883
28774
  onStateChange,
27884
- cancelToken
28775
+ cancelToken,
28776
+ run !== void 0
27885
28777
  );
27886
28778
  const makeConnCtx = (ctx, conn, request, cancelToken) => withConnContext(
27887
28779
  runtime,
@@ -27893,7 +28785,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27893
28785
  request,
27894
28786
  stateEnabled,
27895
28787
  onStateChange,
27896
- cancelToken
28788
+ cancelToken,
28789
+ run !== void 0
27897
28790
  );
27898
28791
  const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
27899
28792
  var _a22, _b, _c, _d;
@@ -27944,6 +28837,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27944
28837
  return await ((_b2 = (_a3 = getNativeWorkflowInspector(ctx)) == null ? void 0 : _a3.getState) == null ? void 0 : _b2.call(_a3)) ?? null;
27945
28838
  };
27946
28839
  const actorCtx = makeActorCtx(ctx, jsRequest);
28840
+ const sql = getOrCreateNativeSqlDatabase(runtime, ctx);
27947
28841
  try {
27948
28842
  if (url2.pathname === "/inspector/state" && jsRequest.method === "GET") {
27949
28843
  return jsonResponse({
@@ -28071,9 +28965,9 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28071
28965
  }
28072
28966
  }
28073
28967
  if (url2.pathname === "/inspector/database/schema" && jsRequest.method === "GET") {
28074
- const db = actorCtx.sql;
28968
+ const db2 = sql;
28075
28969
  const tables = queryRows(
28076
- await db.query(
28970
+ await db2.query(
28077
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"
28078
28972
  )
28079
28973
  );
@@ -28081,13 +28975,13 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28081
28975
  for (const table of tables) {
28082
28976
  const quoted = `"${table.name.replace(/"/g, '""')}"`;
28083
28977
  const columns = queryRows(
28084
- await db.query(`PRAGMA table_info(${quoted})`)
28978
+ await db2.query(`PRAGMA table_info(${quoted})`)
28085
28979
  );
28086
28980
  const foreignKeys = queryRows(
28087
- await db.query(`PRAGMA foreign_key_list(${quoted})`)
28981
+ await db2.query(`PRAGMA foreign_key_list(${quoted})`)
28088
28982
  );
28089
28983
  const countResult = queryRows(
28090
- await db.query(
28984
+ await db2.query(
28091
28985
  `SELECT COUNT(*) as count FROM ${quoted}`
28092
28986
  )
28093
28987
  );
@@ -28122,7 +29016,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28122
29016
  );
28123
29017
  const quoted = `"${table.replace(/"/g, '""')}"`;
28124
29018
  const rows = queryRows(
28125
- await actorCtx.sql.query(
29019
+ await sql.query(
28126
29020
  `SELECT * FROM ${quoted} LIMIT ? OFFSET ?`,
28127
29021
  [
28128
29022
  Math.max(0, Math.min(limit, 500)),
@@ -28150,15 +29044,11 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28150
29044
  const bindings = normalizeSqlitePropertyBindings(
28151
29045
  body.properties
28152
29046
  );
28153
- const rows2 = queryRows(
28154
- await actorCtx.sql.query(body.sql, bindings)
28155
- );
29047
+ const rows2 = queryRows(await sql.query(body.sql, bindings));
28156
29048
  return jsonResponse({ rows: jsonSafe(rows2) });
28157
29049
  }
28158
29050
  const args = Array.isArray(body.args) ? body.args : [];
28159
- const rows = queryRows(
28160
- await actorCtx.sql.query(body.sql, args)
28161
- );
29051
+ const rows = queryRows(await sql.query(body.sql, args));
28162
29052
  return jsonResponse({ rows: jsonSafe(rows) });
28163
29053
  }
28164
29054
  if (url2.pathname === "/inspector/summary" && jsRequest.method === "GET") {
@@ -28184,7 +29074,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28184
29074
  rpcs: Object.keys(actionHandlers).sort(),
28185
29075
  queueSize: inspectorSnapshot.queueSize,
28186
29076
  isStateEnabled: stateEnabled,
28187
- isDatabaseEnabled: databaseProvider !== void 0,
29077
+ isDatabaseEnabled: true,
28188
29078
  isWorkflowEnabled: getNativeWorkflowInspector(ctx) !== void 0,
28189
29079
  workflowState: await workflowState(),
28190
29080
  workflowHistory: workflowHistory()
@@ -28374,6 +29264,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28374
29264
  async (error46, payload) => {
28375
29265
  const { ctx } = unwrapTsfnPayload(error46, payload);
28376
29266
  const actorCtx = makeActorCtx(ctx);
29267
+ const actorId = callNativeSync(() => runtime.actorId(ctx));
28377
29268
  const saveActorState = async () => {
28378
29269
  if (runtime.kind === "wasm") {
28379
29270
  await runtime.actorSaveState(
@@ -28399,6 +29290,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28399
29290
  saveActorState
28400
29291
  );
28401
29292
  } finally {
29293
+ runHandlerCoordinator == null ? void 0 : runHandlerCoordinator.destroy(actorId);
29294
+ disposeRunInspector(config3.run, actorId);
28402
29295
  await actorCtx.dispose();
28403
29296
  }
28404
29297
  }
@@ -28408,14 +29301,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28408
29301
  async (error46, payload) => {
28409
29302
  const { ctx } = unwrapTsfnPayload(error46, payload);
28410
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);
28411
29307
  try {
28412
29308
  if (typeof config3.onDestroy === "function") {
28413
29309
  await config3.onDestroy(actorCtx);
28414
29310
  }
28415
29311
  } finally {
28416
- const actorId = callNativeSync(() => runtime.actorId(ctx));
28417
- nativeRunHandlerActiveByActorId.delete(actorId);
28418
- disposeRunInspector(config3.run, actorId);
28419
29312
  resolveNativeDestroy(runtime, ctx);
28420
29313
  await actorCtx.closeDatabase();
28421
29314
  clearNativeRuntimeState(runtime, ctx);
@@ -28463,7 +29356,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28463
29356
  ctx,
28464
29357
  connId
28465
29358
  )
28466
- )
29359
+ ),
29360
+ () => actorCtx.assertCanMutateState()
28467
29361
  );
28468
29362
  try {
28469
29363
  const nextConnState = hasStaticConnState ? structuredClone(config3.connState) : await config3.createConnState(
@@ -28500,7 +29394,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28500
29394
  ctx,
28501
29395
  connId
28502
29396
  )
28503
- )
29397
+ ),
29398
+ () => actorCtx.assertCanMutateState()
28504
29399
  );
28505
29400
  try {
28506
29401
  await config3.onConnect(
@@ -28532,7 +29427,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28532
29427
  ctx,
28533
29428
  connId
28534
29429
  )
28535
- )
29430
+ ),
29431
+ () => actorCtx.assertCanMutateState()
28536
29432
  )
28537
29433
  );
28538
29434
  }
@@ -28676,7 +29572,6 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28676
29572
  }
28677
29573
  ) : void 0,
28678
29574
  run: (() => {
28679
- const run = getRunFunction(config3.run);
28680
29575
  if (!run) {
28681
29576
  return void 0;
28682
29577
  }
@@ -28684,18 +29579,30 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28684
29579
  async (error46, payload) => {
28685
29580
  const { ctx } = unwrapTsfnPayload(error46, payload);
28686
29581
  const actorId = callNativeSync(() => runtime.actorId(ctx));
28687
- const actorCtx = makeActorCtx(ctx);
28688
- nativeRunHandlerActiveByActorId.set(actorId, true);
28689
- try {
28690
- await run(actorCtx);
28691
- } finally {
28692
- nativeRunHandlerActiveByActorId.delete(actorId);
28693
- 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";
28694
29599
  }
29600
+ await executeRun();
29601
+ return true;
28695
29602
  }
28696
29603
  );
28697
29604
  })(),
28698
- getWorkflowHistory: getRunInspectorConfig(config3.run) !== void 0 ? wrapNativeCallback(
29605
+ getWorkflowHistory: hasRunInspectorConfig(config3.run) ? wrapNativeCallback(
28699
29606
  async (error46, payload) => {
28700
29607
  var _a22;
28701
29608
  const { ctx } = unwrapTsfnPayload(error46, payload);
@@ -28703,7 +29610,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28703
29610
  return history == null ? void 0 : toUint8Array(history);
28704
29611
  }
28705
29612
  ) : void 0,
28706
- replayWorkflow: getRunInspectorConfig(config3.run) !== void 0 ? wrapNativeCallback(
29613
+ replayWorkflow: hasRunInspectorConfig(config3.run) ? wrapNativeCallback(
28707
29614
  async (error46, payload) => {
28708
29615
  const { ctx, entryId } = unwrapTsfnPayload(
28709
29616
  error46,
@@ -28713,9 +29620,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28713
29620
  if (!(workflowInspector == null ? void 0 : workflowInspector.replayFromStep)) {
28714
29621
  return void 0;
28715
29622
  }
28716
- const history = await workflowInspector.replayFromStep(
28717
- entryId
28718
- ) ?? null;
29623
+ const history = await workflowInspector.replayFromStep(entryId) ?? null;
28719
29624
  return history == null ? void 0 : toUint8Array(history);
28720
29625
  }
28721
29626
  ) : void 0,
@@ -28768,7 +29673,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28768
29673
  jsRequest,
28769
29674
  stateEnabled,
28770
29675
  onStateChange,
28771
- cancelToken
29676
+ cancelToken,
29677
+ run !== void 0
28772
29678
  );
28773
29679
  try {
28774
29680
  if (!schemaConfig.queues || !hasSchemaConfigKey(schemaConfig.queues, name)) {
@@ -29651,7 +30557,7 @@ function setup(input) {
29651
30557
  }
29652
30558
 
29653
30559
  // src/mod.ts
29654
- var import_meta2 = {};
30560
+ var import_meta = {};
29655
30561
  var DEFAULT_MANAGER_PATH = "/api/rivet";
29656
30562
  function setup2(config3) {
29657
30563
  return setup({
@@ -29662,7 +30568,7 @@ function setup2(config3) {
29662
30568
  });
29663
30569
  }
29664
30570
  var resolveWasmUrl = () => new URL(
29665
- import_meta2.resolve("@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm")
30571
+ import_meta.resolve("@rivetkit/rivetkit-wasm/rivetkit_wasm_bg.wasm")
29666
30572
  );
29667
30573
  function applyEnv(config3, managerPath) {
29668
30574
  if (!config3.endpoint) {
@@ -29739,6 +30645,7 @@ async function serve(registryOrConfig, options = {}) {
29739
30645
  actor,
29740
30646
  buildActorNames,
29741
30647
  createClientWithDriver,
30648
+ defineRunHandler,
29742
30649
  event,
29743
30650
  isStaticActorDefinition,
29744
30651
  isStaticActorInstance,