@rivetkit/supabase 2.3.12-rc.2 → 2.3.12-rc.3

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 +946 -921
  2. package/dist/mod.mjs +949 -924
  3. package/package.json +3 -3
package/dist/mod.js CHANGED
@@ -335,6 +335,193 @@ __export(mod_exports, {
335
335
  module.exports = __toCommonJS(mod_exports);
336
336
  var wasmBindings = __toESM(require("@rivetkit/rivetkit-wasm"));
337
337
 
338
+ // ../rivetkit/dist/tsup/chunk-IXBD7BXC.js
339
+ var INTERNAL_ERROR_CODE = "internal_error";
340
+ var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
341
+ var USER_ERROR_CODE = "user_error";
342
+ var BRIDGE_RIVET_ERROR_PREFIX = "__RIVET_ERROR_JSON__:";
343
+ function looksLikeRivetErrorOptions(value) {
344
+ return typeof value === "object" && value !== null && ("public" in value || "metadata" in value || "rayId" in value || "statusCode" in value || "actor" in value || "cause" in value);
345
+ }
346
+ function isTypedErrorTag(value) {
347
+ return value === "ActorError" || value === "RivetError";
348
+ }
349
+ function errorMessage(error46, fallback = String(error46)) {
350
+ if (error46 && typeof error46 === "object" && "message" in error46 && typeof error46.message === "string") {
351
+ return error46.message;
352
+ }
353
+ return fallback;
354
+ }
355
+ function isRivetErrorLike(error46) {
356
+ return typeof error46 === "object" && error46 !== null && "group" in error46 && typeof error46.group === "string" && "code" in error46 && typeof error46.code === "string" && "message" in error46 && typeof error46.message === "string" && (!("rayId" in error46) || error46.rayId === void 0 || typeof error46.rayId === "string") && (!("__type" in error46) || isTypedErrorTag(error46.__type));
357
+ }
358
+ function isActorAbortedError(error46) {
359
+ return isRivetErrorLike(error46) && error46.group === "actor" && error46.code === "aborted";
360
+ }
361
+ function isActorSpecifier(value) {
362
+ return typeof value === "object" && value !== null && "actorId" in value && typeof value.actorId === "string" && "generation" in value && typeof value.generation === "number" && (!("key" in value) || value.key === void 0 || typeof value.key === "string");
363
+ }
364
+ var RivetError = class extends Error {
365
+ __type = "RivetError";
366
+ public;
367
+ metadata;
368
+ rayId;
369
+ statusCode;
370
+ actor;
371
+ group;
372
+ code;
373
+ static isRivetError(error46) {
374
+ return isRivetErrorLike(error46);
375
+ }
376
+ static isActorError(error46) {
377
+ return isRivetErrorLike(error46);
378
+ }
379
+ constructor(group, code, message, options) {
380
+ const normalized = looksLikeRivetErrorOptions(options) ? options : { metadata: options };
381
+ super(message, { cause: normalized.cause });
382
+ this.name = "RivetError";
383
+ this.group = group;
384
+ this.code = code;
385
+ this.public = normalized.public ?? false;
386
+ this.metadata = normalized.metadata;
387
+ this.rayId = normalized.rayId ?? void 0;
388
+ this.statusCode = normalized.statusCode ?? (this.public ? 400 : 500);
389
+ this.actor = normalized.actor;
390
+ }
391
+ toString() {
392
+ return this.message;
393
+ }
394
+ };
395
+ var UserError = class extends RivetError {
396
+ constructor(message, options) {
397
+ super("user", (options == null ? void 0 : options.code) ?? USER_ERROR_CODE, message, {
398
+ public: true,
399
+ metadata: options == null ? void 0 : options.metadata,
400
+ cause: options == null ? void 0 : options.cause
401
+ });
402
+ }
403
+ };
404
+ function toRivetError(error46, fallback) {
405
+ if (typeof error46 === "string") {
406
+ const bridged = decodeBridgeRivetError(error46);
407
+ if (bridged) {
408
+ return bridged;
409
+ }
410
+ }
411
+ if (error46 instanceof Error) {
412
+ const bridged = decodeBridgeRivetError(error46.message);
413
+ if (bridged) {
414
+ return bridged;
415
+ }
416
+ }
417
+ if (isRivetErrorLike(error46)) {
418
+ return new RivetError(error46.group, error46.code, error46.message, {
419
+ public: error46.public,
420
+ statusCode: error46.statusCode,
421
+ metadata: error46.metadata,
422
+ rayId: error46.rayId,
423
+ actor: error46.actor,
424
+ cause: error46 instanceof Error ? error46.cause : void 0
425
+ });
426
+ }
427
+ return new RivetError(
428
+ (fallback == null ? void 0 : fallback.group) ?? "actor",
429
+ (fallback == null ? void 0 : fallback.code) ?? INTERNAL_ERROR_CODE,
430
+ errorMessage(error46, (fallback == null ? void 0 : fallback.message) ?? "Unknown error"),
431
+ {
432
+ public: fallback == null ? void 0 : fallback.public,
433
+ statusCode: fallback == null ? void 0 : fallback.statusCode,
434
+ metadata: fallback == null ? void 0 : fallback.metadata,
435
+ rayId: fallback == null ? void 0 : fallback.rayId,
436
+ actor: fallback == null ? void 0 : fallback.actor,
437
+ cause: error46 instanceof Error ? error46 : void 0
438
+ }
439
+ );
440
+ }
441
+ function encodeBridgeRivetError(error46) {
442
+ return `${BRIDGE_RIVET_ERROR_PREFIX}${JSON.stringify({
443
+ group: error46.group,
444
+ code: error46.code,
445
+ message: error46.message,
446
+ metadata: error46.metadata,
447
+ rayId: error46.rayId,
448
+ public: error46.public,
449
+ statusCode: error46.statusCode,
450
+ actor: error46.actor
451
+ })}`;
452
+ }
453
+ function decodeBridgeRivetErrorPayload(value) {
454
+ if (!value.startsWith(BRIDGE_RIVET_ERROR_PREFIX)) {
455
+ return void 0;
456
+ }
457
+ try {
458
+ const raw = JSON.parse(
459
+ value.slice(BRIDGE_RIVET_ERROR_PREFIX.length)
460
+ );
461
+ const payload = {
462
+ ...raw,
463
+ rayId: raw.rayId ?? void 0
464
+ };
465
+ if (!isRivetErrorLike(payload)) {
466
+ return void 0;
467
+ }
468
+ if (payload.actor !== void 0 && payload.actor !== null && !isActorSpecifier(payload.actor)) {
469
+ return void 0;
470
+ }
471
+ return payload;
472
+ } catch {
473
+ return void 0;
474
+ }
475
+ }
476
+ function decodeBridgeRivetError(value) {
477
+ const payload = decodeBridgeRivetErrorPayload(value);
478
+ if (!payload) {
479
+ return void 0;
480
+ }
481
+ return new RivetError(payload.group, payload.code, payload.message, {
482
+ metadata: payload.metadata,
483
+ rayId: payload.rayId,
484
+ public: payload.public,
485
+ statusCode: payload.statusCode,
486
+ actor: payload.actor ?? void 0
487
+ });
488
+ }
489
+ function invalidRequest(error46) {
490
+ return new RivetError(
491
+ "request",
492
+ "invalid",
493
+ `Invalid request: ${errorMessage(error46, String(error46))}`,
494
+ {
495
+ public: true,
496
+ cause: error46 instanceof Error ? error46 : void 0
497
+ }
498
+ );
499
+ }
500
+ function actorNotFound(identifier) {
501
+ return new RivetError(
502
+ "actor",
503
+ "not_found",
504
+ identifier ? `Actor not found: ${identifier} (https://www.rivet.dev/docs/clients/javascript)` : "Actor not found (https://www.rivet.dev/docs/clients/javascript)",
505
+ { public: true }
506
+ );
507
+ }
508
+ function forbiddenError() {
509
+ return new RivetError("auth", "forbidden", "Forbidden", {
510
+ public: true,
511
+ statusCode: 403
512
+ });
513
+ }
514
+ function unsupportedFeature(feature) {
515
+ return new RivetError(
516
+ "feature",
517
+ "unsupported",
518
+ `Unsupported feature: ${feature}`
519
+ );
520
+ }
521
+
522
+ // ../rivetkit/dist/tsup/chunk-OLGQYFUW.js
523
+ var import_pino = require("pino");
524
+
338
525
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/classic/external.js
339
526
  var external_exports = {};
340
527
  __export(external_exports, {
@@ -13005,702 +13192,53 @@ var classic_default = external_exports;
13005
13192
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13006
13193
  var v4_default = classic_default;
13007
13194
 
13008
- // ../rivetkit/dist/tsup/chunk-6W5VGLFT.js
13009
- function flattenActionHandlers(actions) {
13010
- const flattened = /* @__PURE__ */ Object.create(null);
13011
- for (const { name, handler } of collectActionEntries(actions)) {
13012
- flattened[name] = handler;
13195
+ // ../rivetkit/dist/tsup/chunk-OLGQYFUW.js
13196
+ var cbor = __toESM(require("cbor-x"), 1);
13197
+ var import_invariant = __toESM(require_invariant(), 1);
13198
+ var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13199
+ var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13200
+ var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
13201
+ var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
13202
+ var getRivetPool = () => getEnvUniversal("RIVET_POOL");
13203
+ var getRivetTotalSlots = () => {
13204
+ const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
13205
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13206
+ };
13207
+ var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
13208
+ var getRivetRunEngineHost = () => getEnvUniversal("RIVET_RUN_ENGINE_HOST");
13209
+ var getRivetRunEnginePort = () => {
13210
+ const value = getEnvUniversal("RIVET_RUN_ENGINE_PORT");
13211
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13212
+ };
13213
+ var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13214
+ var getRivetEnvoyVersion = () => {
13215
+ const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13216
+ return value !== void 0 ? parseInt(value, 10) : void 0;
13217
+ };
13218
+ var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
13219
+ var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
13220
+ var getRivetkitRuntime = () => getEnvUniversal("RIVETKIT_RUNTIME");
13221
+ var getRivetkitRuntimeMode = () => {
13222
+ const value = getEnvUniversal("RIVETKIT_RUNTIME_MODE");
13223
+ if (value === void 0) return "envoy";
13224
+ if (value === "envoy" || value === "serverless") return value;
13225
+ throw new Error(
13226
+ `RIVETKIT_RUNTIME_MODE env var must be "envoy" or "serverless"; got "${value}"`
13227
+ );
13228
+ };
13229
+ var getRivetkitPublicDir = () => {
13230
+ const value = getEnvUniversal("RIVETKIT_PUBLIC_DIR");
13231
+ return value === void 0 || value === "" ? void 0 : value;
13232
+ };
13233
+ function parsePortEnv(raw) {
13234
+ if (raw === void 0 || raw === "") return void 0;
13235
+ const parsed = Number.parseInt(raw, 10);
13236
+ if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535 || String(parsed) !== raw.trim()) {
13237
+ throw new Error(
13238
+ `RIVET_PORT env var must be an integer between 1 and 65535; got "${raw}"`
13239
+ );
13013
13240
  }
13014
- return flattened;
13015
- }
13016
- function flattenActionInputSchemas(actions, schemas) {
13017
- if (schemas === void 0) return void 0;
13018
- if (!isRecord(schemas)) {
13019
- throw new TypeError("actionInputSchemas must be an object");
13020
- }
13021
- const flattened = /* @__PURE__ */ Object.create(null);
13022
- for (const { name, path: path2 } of collectActionEntries(actions)) {
13023
- const nestedSchema = lookupNestedSchema(schemas, path2);
13024
- const flatSchema = schemas[name];
13025
- if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
13026
- throw new TypeError(
13027
- `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
13028
- );
13029
- }
13030
- const schema = nestedSchema ?? flatSchema;
13031
- if (schema !== void 0) {
13032
- flattened[name] = schema;
13033
- }
13034
- }
13035
- return flattened;
13036
- }
13037
- function collectActionEntries(actions) {
13038
- const entries = [];
13039
- const names = /* @__PURE__ */ new Set();
13040
- visitActionGroup(actions ?? {}, [], entries, names);
13041
- return entries;
13042
- }
13043
- function visitActionGroup(value, path2, entries, names) {
13044
- if (!isRecord(value)) {
13045
- throw new TypeError(
13046
- `${formatActionPath(path2)} must be an action handler or group`
13047
- );
13048
- }
13049
- for (const [segment, child] of Object.entries(value)) {
13050
- const childPath = [...path2, segment];
13051
- if (typeof child === "function") {
13052
- const name = childPath.join(".");
13053
- if (names.has(name)) {
13054
- throw new TypeError(
13055
- `Multiple action definitions flatten to \`${name}\``
13056
- );
13057
- }
13058
- names.add(name);
13059
- entries.push({
13060
- name,
13061
- path: childPath,
13062
- handler: child
13063
- });
13064
- } else {
13065
- visitActionGroup(child, childPath, entries, names);
13066
- }
13067
- }
13068
- }
13069
- function lookupNestedSchema(schemas, path2) {
13070
- let value = schemas;
13071
- for (const segment of path2) {
13072
- if (!isRecord(value) || !Object.hasOwn(value, segment)) {
13073
- return void 0;
13074
- }
13075
- value = value[segment];
13076
- }
13077
- return value;
13078
- }
13079
- function isRecord(value) {
13080
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
13081
- return false;
13082
- }
13083
- const prototype = Object.getPrototypeOf(value);
13084
- return prototype === Object.prototype || prototype === null;
13085
- }
13086
- function formatActionPath(path2) {
13087
- return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
13088
- }
13089
- var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
13090
- var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
13091
- "rivetkit.actor_context_internal"
13092
- );
13093
- var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
13094
- var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
13095
- var zFunction = () => external_exports.custom((val) => typeof val === "function");
13096
- var zActionTree = external_exports.custom((value) => {
13097
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
13098
- return false;
13099
- }
13100
- const prototype = Object.getPrototypeOf(value);
13101
- return prototype === Object.prototype || prototype === null;
13102
- }).superRefine((actions, ctx) => {
13103
- try {
13104
- flattenActionHandlers(actions);
13105
- } catch (error46) {
13106
- ctx.addIssue({
13107
- code: "custom",
13108
- message: error46 instanceof Error ? error46.message : "Invalid action definition"
13109
- });
13110
- }
13111
- });
13112
- var WorkflowInspectorConfigSchema = external_exports.object({
13113
- getHistory: zFunction(),
13114
- getState: zFunction().optional(),
13115
- onHistoryUpdated: zFunction().optional(),
13116
- replayFromStep: zFunction().optional()
13117
- });
13118
- var RunInspectorConfigSchema = external_exports.object({
13119
- workflow: WorkflowInspectorConfigSchema.optional()
13120
- }).optional();
13121
- var BUILTIN_INSPECTOR_TAB_IDS = [
13122
- "workflow",
13123
- "database",
13124
- "state",
13125
- "queue",
13126
- "schedules",
13127
- "connections",
13128
- "console"
13129
- ];
13130
- var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
13131
- var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
13132
- var CustomInspectorTabEntrySchema = external_exports.object({
13133
- id: external_exports.string().regex(
13134
- CUSTOM_INSPECTOR_TAB_ID_RE,
13135
- "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
13136
- ),
13137
- label: external_exports.string().min(1),
13138
- source: external_exports.string().min(1),
13139
- /**
13140
- * Optional icon id. The dashboard maps strings to glyphs (see its
13141
- * icon registry); unknown ids fall back to a generic icon.
13142
- */
13143
- icon: external_exports.string().min(1).optional(),
13144
- hidden: external_exports.literal(false).optional()
13145
- }).strict();
13146
- var HideInspectorTabEntrySchema = external_exports.object({
13147
- id: BuiltinInspectorTabIdSchema,
13148
- hidden: external_exports.literal(true)
13149
- }).strict();
13150
- var InspectorTabEntrySchema = external_exports.union([
13151
- CustomInspectorTabEntrySchema,
13152
- HideInspectorTabEntrySchema
13153
- ]);
13154
- var ActorInspectorConfigSchema = external_exports.object({
13155
- tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
13156
- }).strict().refine(
13157
- (data) => {
13158
- const ids = data.tabs.map((t) => t.id);
13159
- return new Set(ids).size === ids.length;
13160
- },
13161
- { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
13162
- ).refine(
13163
- (data) => {
13164
- const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
13165
- return data.tabs.every(
13166
- (t) => t.hidden === true || !builtinSet.has(t.id)
13167
- );
13168
- },
13169
- {
13170
- message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
13171
- path: ["tabs"]
13172
- }
13173
- );
13174
- var RunConfigSchema = external_exports.object({
13175
- /** Display name for the actor in the Inspector UI. */
13176
- name: external_exports.string().optional(),
13177
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13178
- icon: external_exports.string().optional(),
13179
- /** The run handler function. */
13180
- run: zFunction(),
13181
- /** Inspector integration for long-running run handlers. */
13182
- inspector: RunInspectorConfigSchema.optional()
13183
- });
13184
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
13185
- function defineRunHandler(run, options) {
13186
- if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
13187
- throw new TypeError(
13188
- "defineRunHandler requires inspectorKind and createInspector together"
13189
- );
13190
- }
13191
- Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
13192
- configurable: false,
13193
- enumerable: false,
13194
- writable: false,
13195
- value: {
13196
- name: options.name,
13197
- icon: options.icon,
13198
- inspectorKind: options.inspectorKind,
13199
- createInspector: options.createInspector
13200
- }
13201
- });
13202
- return run;
13203
- }
13204
- function getRunInspectorKind(run) {
13205
- var _a2;
13206
- if (!run || typeof run !== "function") return void 0;
13207
- return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
13208
- }
13209
- function createRunInspector(run, context) {
13210
- var _a2, _b;
13211
- if (!run || typeof run !== "function") return void 0;
13212
- return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context);
13213
- }
13214
- var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
13215
- function getRunFunction(run) {
13216
- if (!run) return void 0;
13217
- if (typeof run === "function") return run;
13218
- return run.run;
13219
- }
13220
- function getRunMetadata(run) {
13221
- if (!run) return {};
13222
- if (typeof run === "function") {
13223
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13224
- if (!config3) return {};
13225
- return { name: config3.name, icon: config3.icon };
13226
- }
13227
- return { name: run.name, icon: run.icon };
13228
- }
13229
- function getRunInspectorConfig(run, actor2) {
13230
- if (!run) return void 0;
13231
- if (typeof run === "function") {
13232
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13233
- return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
13234
- }
13235
- return run.inspector;
13236
- }
13237
- function hasRunInspectorConfig(run) {
13238
- if (!run) return false;
13239
- if (typeof run !== "function") return run.inspector !== void 0;
13240
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13241
- 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;
13242
- }
13243
- function disposeRunInspector(run, actorId) {
13244
- var _a2;
13245
- if (!run || typeof run !== "function") {
13246
- return;
13247
- }
13248
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
13249
- (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
13250
- }
13251
- var GlobalActorOptionsBaseSchema = external_exports.object({
13252
- /** Display name for the actor in the Inspector UI. */
13253
- name: external_exports.string().optional(),
13254
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
13255
- icon: external_exports.string().optional(),
13256
- /** Enables the experimental Actor Runtime Socket for this actor. */
13257
- enableActorRuntimeSocket: external_exports.boolean().default(false),
13258
- /**
13259
- * Can hibernate WebSockets for onWebSocket.
13260
- *
13261
- * WebSockets using actions/events are hibernatable by default.
13262
- *
13263
- * @experimental
13264
- **/
13265
- canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
13266
- }).strict();
13267
- var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
13268
- () => ({})
13269
- );
13270
- var InstanceActorOptionsBaseSchema = external_exports.object({
13271
- createVarsTimeout: external_exports.number().positive().default(5e3),
13272
- createConnStateTimeout: external_exports.number().positive().default(5e3),
13273
- onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
13274
- onConnectTimeout: external_exports.number().positive().default(5e3),
13275
- onMigrateTimeout: external_exports.number().positive().default(3e4),
13276
- sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
13277
- /** @deprecated `onDestroyTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
13278
- onDestroyTimeout: external_exports.number().positive().optional(),
13279
- /** @deprecated `waitUntilTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
13280
- waitUntilTimeout: external_exports.number().positive().optional(),
13281
- stateSaveInterval: external_exports.number().positive().default(1e3),
13282
- actionTimeout: external_exports.number().positive().default(6e4),
13283
- connectionLivenessTimeout: external_exports.number().positive().default(2500),
13284
- connectionLivenessInterval: external_exports.number().positive().default(5e3),
13285
- /** @deprecated Use `c.keepAwake(promise)` to scope keep-awake to a specific operation, or keep `noSleep` for actors that must stay awake indefinitely. Will be removed in 2.2.0. */
13286
- noSleep: external_exports.boolean().default(false),
13287
- sleepTimeout: external_exports.number().positive().default(3e4),
13288
- maxQueueSize: external_exports.number().positive().default(1e3),
13289
- /** Maximum pending one-shot and recurring schedules. */
13290
- maxSchedules: external_exports.number().int().nonnegative().default(1e3),
13291
- maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
13292
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13293
- preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
13294
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
13295
- preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
13296
- }).strict();
13297
- var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
13298
- var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
13299
- InstanceActorOptionsBaseSchema.shape
13300
- ).strict().prefault(() => ({}));
13301
- var ActorConfigSchema = external_exports.object({
13302
- onCreate: zFunction().optional(),
13303
- onDestroy: zFunction().optional(),
13304
- onMigrate: zFunction().optional(),
13305
- onWake: zFunction().optional(),
13306
- onSleep: zFunction().optional(),
13307
- run: zRunHandler,
13308
- onStateChange: zFunction().optional(),
13309
- onBeforeConnect: zFunction().optional(),
13310
- onConnect: zFunction().optional(),
13311
- onDisconnect: zFunction().optional(),
13312
- onBeforeActionResponse: zFunction().optional(),
13313
- onRequest: zFunction().optional(),
13314
- onWebSocket: zFunction().optional(),
13315
- actions: zActionTree.default(() => ({})),
13316
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13317
- connParamsSchema: external_exports.any().optional(),
13318
- events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13319
- queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
13320
- state: external_exports.any().optional(),
13321
- createState: zFunction().optional(),
13322
- connState: external_exports.any().optional(),
13323
- createConnState: zFunction().optional(),
13324
- vars: external_exports.any().optional(),
13325
- db: external_exports.any().optional(),
13326
- createVars: zFunction().optional(),
13327
- options: ActorOptionsSchema,
13328
- inspector: ActorInspectorConfigSchema.optional()
13329
- }).strict().refine(
13330
- (data) => !(data.state !== void 0 && data.createState !== void 0),
13331
- {
13332
- message: "Cannot define both 'state' and 'createState'",
13333
- path: ["state"]
13334
- }
13335
- ).refine(
13336
- (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
13337
- {
13338
- message: "Cannot define both 'connState' and 'createConnState'",
13339
- path: ["connState"]
13340
- }
13341
- ).refine(
13342
- (data) => !(data.vars !== void 0 && data.createVars !== void 0),
13343
- {
13344
- message: "Cannot define both 'vars' and 'createVars'",
13345
- path: ["vars"]
13346
- }
13347
- );
13348
- var DocActorOptionsSchema = external_exports.object({
13349
- name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
13350
- icon: external_exports.string().optional().describe(
13351
- "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
13352
- ),
13353
- enableActorRuntimeSocket: external_exports.boolean().optional().describe(
13354
- "Enables the experimental Actor Runtime Socket for this actor. Default: false"
13355
- ),
13356
- createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
13357
- createConnStateTimeout: external_exports.number().optional().describe(
13358
- "Timeout in ms for createConnState handler. Default: 5000"
13359
- ),
13360
- onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
13361
- onBeforeConnectTimeout: external_exports.number().optional().describe(
13362
- "Timeout in ms for onBeforeConnect handler. Default: 5000"
13363
- ),
13364
- onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
13365
- sleepGracePeriod: external_exports.number().optional().describe(
13366
- `Max time in ms for the graceful shutdown window. Covers lifecycle hooks (onSleep, onDestroy), the run handler wait, async raw WebSocket handlers, disconnect callbacks, and final state serialization. Default: ${DEFAULT_SLEEP_GRACE_PERIOD}.`
13367
- ),
13368
- onDestroyTimeout: external_exports.number().optional().describe(
13369
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13370
- ),
13371
- waitUntilTimeout: external_exports.number().optional().describe(
13372
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
13373
- ),
13374
- stateSaveInterval: external_exports.number().optional().describe(
13375
- "Interval in ms between automatic state saves. Default: 1000"
13376
- ),
13377
- actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
13378
- connectionLivenessTimeout: external_exports.number().optional().describe(
13379
- "Timeout in ms for connection liveness checks. Default: 2500"
13380
- ),
13381
- connectionLivenessInterval: external_exports.number().optional().describe(
13382
- "Interval in ms between connection liveness checks. Default: 5000"
13383
- ),
13384
- noSleep: external_exports.boolean().optional().describe(
13385
- "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
13386
- ),
13387
- sleepTimeout: external_exports.number().optional().describe(
13388
- "Time in ms of inactivity before the actor sleeps. Default: 30000"
13389
- ),
13390
- maxQueueSize: external_exports.number().optional().describe(
13391
- "Maximum number of queue messages before rejecting new messages. Default: 1000"
13392
- ),
13393
- maxSchedules: external_exports.number().int().nonnegative().optional().describe(
13394
- "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
13395
- ),
13396
- maxQueueMessageSize: external_exports.number().optional().describe(
13397
- "Maximum size of each queue message in bytes. Default: 65536"
13398
- ),
13399
- canHibernateWebSocket: external_exports.boolean().optional().describe(
13400
- "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
13401
- )
13402
- }).describe("Actor options for timeouts and behavior configuration.");
13403
- var DocActorConfigSchema = external_exports.object({
13404
- state: external_exports.unknown().optional().describe(
13405
- "Initial state value for the actor. Cannot be used with createState."
13406
- ),
13407
- createState: external_exports.unknown().optional().describe(
13408
- "Function to create initial state. Receives context and input. Cannot be used with state."
13409
- ),
13410
- connState: external_exports.unknown().optional().describe(
13411
- "Initial connection state value. Cannot be used with createConnState."
13412
- ),
13413
- createConnState: external_exports.unknown().optional().describe(
13414
- "Function to create connection state. Receives context and connection params. The pending connection is not visible in c.conns until this succeeds. Cannot be used with connState."
13415
- ),
13416
- vars: external_exports.unknown().optional().describe(
13417
- "Initial ephemeral variables value. Cannot be used with createVars."
13418
- ),
13419
- createVars: external_exports.unknown().optional().describe(
13420
- "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
13421
- ),
13422
- db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
13423
- onCreate: external_exports.unknown().optional().describe(
13424
- "Called when the actor is first initialized. Use to initialize state."
13425
- ),
13426
- onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
13427
- onMigrate: external_exports.unknown().optional().describe(
13428
- "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
13429
- ),
13430
- onWake: external_exports.unknown().optional().describe(
13431
- "Called when the actor wakes up and is ready to receive connections and actions."
13432
- ),
13433
- onSleep: external_exports.unknown().optional().describe(
13434
- "Called when the actor is stopping or sleeping. Use to clean up resources."
13435
- ),
13436
- run: external_exports.unknown().optional().describe(
13437
- "Called after actor starts. Does not block startup. Use for background tasks like queue processing or tick loops. If it exits, the actor follows the normal idle sleep timeout once idle. If it throws, the actor logs the error and then follows the normal idle sleep timeout once idle."
13438
- ),
13439
- onStateChange: external_exports.unknown().optional().describe(
13440
- "Called when the actor's state changes. State changes within this hook won't trigger recursion."
13441
- ),
13442
- onBeforeConnect: external_exports.unknown().optional().describe(
13443
- "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
13444
- ),
13445
- onConnect: external_exports.unknown().optional().describe(
13446
- "Called when a client successfully connects. The connection is visible in c.conns before this runs."
13447
- ),
13448
- onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
13449
- onBeforeActionResponse: external_exports.unknown().optional().describe(
13450
- "Called before sending an action response. Use to transform output."
13451
- ),
13452
- onRequest: external_exports.unknown().optional().describe(
13453
- "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
13454
- ),
13455
- onWebSocket: external_exports.unknown().optional().describe(
13456
- "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
13457
- ),
13458
- actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13459
- "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
13460
- ),
13461
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
13462
- "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
13463
- ),
13464
- connParamsSchema: external_exports.unknown().optional().describe(
13465
- "Optional schema for validating connection params in native runtimes."
13466
- ),
13467
- events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
13468
- queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
13469
- options: DocActorOptionsSchema.optional()
13470
- }).describe("Actor configuration passed to the actor() function.");
13471
-
13472
- // ../rivetkit/dist/tsup/chunk-IXBD7BXC.js
13473
- var INTERNAL_ERROR_CODE = "internal_error";
13474
- var INTERNAL_ERROR_DESCRIPTION = "An internal error occurred";
13475
- var USER_ERROR_CODE = "user_error";
13476
- var BRIDGE_RIVET_ERROR_PREFIX = "__RIVET_ERROR_JSON__:";
13477
- function looksLikeRivetErrorOptions(value) {
13478
- return typeof value === "object" && value !== null && ("public" in value || "metadata" in value || "rayId" in value || "statusCode" in value || "actor" in value || "cause" in value);
13479
- }
13480
- function isTypedErrorTag(value) {
13481
- return value === "ActorError" || value === "RivetError";
13482
- }
13483
- function errorMessage(error46, fallback = String(error46)) {
13484
- if (error46 && typeof error46 === "object" && "message" in error46 && typeof error46.message === "string") {
13485
- return error46.message;
13486
- }
13487
- return fallback;
13488
- }
13489
- function isRivetErrorLike(error46) {
13490
- return typeof error46 === "object" && error46 !== null && "group" in error46 && typeof error46.group === "string" && "code" in error46 && typeof error46.code === "string" && "message" in error46 && typeof error46.message === "string" && (!("rayId" in error46) || error46.rayId === void 0 || typeof error46.rayId === "string") && (!("__type" in error46) || isTypedErrorTag(error46.__type));
13491
- }
13492
- function isActorAbortedError(error46) {
13493
- return isRivetErrorLike(error46) && error46.group === "actor" && error46.code === "aborted";
13494
- }
13495
- function isActorSpecifier(value) {
13496
- return typeof value === "object" && value !== null && "actorId" in value && typeof value.actorId === "string" && "generation" in value && typeof value.generation === "number" && (!("key" in value) || value.key === void 0 || typeof value.key === "string");
13497
- }
13498
- var RivetError = class extends Error {
13499
- __type = "RivetError";
13500
- public;
13501
- metadata;
13502
- rayId;
13503
- statusCode;
13504
- actor;
13505
- group;
13506
- code;
13507
- static isRivetError(error46) {
13508
- return isRivetErrorLike(error46);
13509
- }
13510
- static isActorError(error46) {
13511
- return isRivetErrorLike(error46);
13512
- }
13513
- constructor(group, code, message, options) {
13514
- const normalized = looksLikeRivetErrorOptions(options) ? options : { metadata: options };
13515
- super(message, { cause: normalized.cause });
13516
- this.name = "RivetError";
13517
- this.group = group;
13518
- this.code = code;
13519
- this.public = normalized.public ?? false;
13520
- this.metadata = normalized.metadata;
13521
- this.rayId = normalized.rayId ?? void 0;
13522
- this.statusCode = normalized.statusCode ?? (this.public ? 400 : 500);
13523
- this.actor = normalized.actor;
13524
- }
13525
- toString() {
13526
- return this.message;
13527
- }
13528
- };
13529
- var UserError = class extends RivetError {
13530
- constructor(message, options) {
13531
- super("user", (options == null ? void 0 : options.code) ?? USER_ERROR_CODE, message, {
13532
- public: true,
13533
- metadata: options == null ? void 0 : options.metadata,
13534
- cause: options == null ? void 0 : options.cause
13535
- });
13536
- }
13537
- };
13538
- function toRivetError(error46, fallback) {
13539
- if (typeof error46 === "string") {
13540
- const bridged = decodeBridgeRivetError(error46);
13541
- if (bridged) {
13542
- return bridged;
13543
- }
13544
- }
13545
- if (error46 instanceof Error) {
13546
- const bridged = decodeBridgeRivetError(error46.message);
13547
- if (bridged) {
13548
- return bridged;
13549
- }
13550
- }
13551
- if (isRivetErrorLike(error46)) {
13552
- return new RivetError(error46.group, error46.code, error46.message, {
13553
- public: error46.public,
13554
- statusCode: error46.statusCode,
13555
- metadata: error46.metadata,
13556
- rayId: error46.rayId,
13557
- actor: error46.actor,
13558
- cause: error46 instanceof Error ? error46.cause : void 0
13559
- });
13560
- }
13561
- return new RivetError(
13562
- (fallback == null ? void 0 : fallback.group) ?? "actor",
13563
- (fallback == null ? void 0 : fallback.code) ?? INTERNAL_ERROR_CODE,
13564
- errorMessage(error46, (fallback == null ? void 0 : fallback.message) ?? "Unknown error"),
13565
- {
13566
- public: fallback == null ? void 0 : fallback.public,
13567
- statusCode: fallback == null ? void 0 : fallback.statusCode,
13568
- metadata: fallback == null ? void 0 : fallback.metadata,
13569
- rayId: fallback == null ? void 0 : fallback.rayId,
13570
- actor: fallback == null ? void 0 : fallback.actor,
13571
- cause: error46 instanceof Error ? error46 : void 0
13572
- }
13573
- );
13574
- }
13575
- function encodeBridgeRivetError(error46) {
13576
- return `${BRIDGE_RIVET_ERROR_PREFIX}${JSON.stringify({
13577
- group: error46.group,
13578
- code: error46.code,
13579
- message: error46.message,
13580
- metadata: error46.metadata,
13581
- rayId: error46.rayId,
13582
- public: error46.public,
13583
- statusCode: error46.statusCode,
13584
- actor: error46.actor
13585
- })}`;
13586
- }
13587
- function decodeBridgeRivetErrorPayload(value) {
13588
- if (!value.startsWith(BRIDGE_RIVET_ERROR_PREFIX)) {
13589
- return void 0;
13590
- }
13591
- try {
13592
- const raw = JSON.parse(
13593
- value.slice(BRIDGE_RIVET_ERROR_PREFIX.length)
13594
- );
13595
- const payload = {
13596
- ...raw,
13597
- rayId: raw.rayId ?? void 0
13598
- };
13599
- if (!isRivetErrorLike(payload)) {
13600
- return void 0;
13601
- }
13602
- if (payload.actor !== void 0 && payload.actor !== null && !isActorSpecifier(payload.actor)) {
13603
- return void 0;
13604
- }
13605
- return payload;
13606
- } catch {
13607
- return void 0;
13608
- }
13609
- }
13610
- function decodeBridgeRivetError(value) {
13611
- const payload = decodeBridgeRivetErrorPayload(value);
13612
- if (!payload) {
13613
- return void 0;
13614
- }
13615
- return new RivetError(payload.group, payload.code, payload.message, {
13616
- metadata: payload.metadata,
13617
- rayId: payload.rayId,
13618
- public: payload.public,
13619
- statusCode: payload.statusCode,
13620
- actor: payload.actor ?? void 0
13621
- });
13622
- }
13623
- function invalidRequest(error46) {
13624
- return new RivetError(
13625
- "request",
13626
- "invalid",
13627
- `Invalid request: ${errorMessage(error46, String(error46))}`,
13628
- {
13629
- public: true,
13630
- cause: error46 instanceof Error ? error46 : void 0
13631
- }
13632
- );
13633
- }
13634
- function actorNotFound(identifier) {
13635
- return new RivetError(
13636
- "actor",
13637
- "not_found",
13638
- identifier ? `Actor not found: ${identifier} (https://www.rivet.dev/docs/clients/javascript)` : "Actor not found (https://www.rivet.dev/docs/clients/javascript)",
13639
- { public: true }
13640
- );
13641
- }
13642
- function forbiddenError() {
13643
- return new RivetError("auth", "forbidden", "Forbidden", {
13644
- public: true,
13645
- statusCode: 403
13646
- });
13647
- }
13648
- function unsupportedFeature(feature) {
13649
- return new RivetError(
13650
- "feature",
13651
- "unsupported",
13652
- `Unsupported feature: ${feature}`
13653
- );
13654
- }
13655
-
13656
- // ../rivetkit/dist/tsup/chunk-YW75TS76.js
13657
- var import_pino = require("pino");
13658
- var cbor = __toESM(require("cbor-x"), 1);
13659
- var import_invariant = __toESM(require_invariant(), 1);
13660
- var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13661
- var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13662
- var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
13663
- var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
13664
- var getRivetPool = () => getEnvUniversal("RIVET_POOL");
13665
- var getRivetTotalSlots = () => {
13666
- const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
13667
- return value !== void 0 ? parseInt(value, 10) : void 0;
13668
- };
13669
- var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
13670
- var getRivetRunEngineHost = () => getEnvUniversal("RIVET_RUN_ENGINE_HOST");
13671
- var getRivetRunEnginePort = () => {
13672
- const value = getEnvUniversal("RIVET_RUN_ENGINE_PORT");
13673
- return value !== void 0 ? parseInt(value, 10) : void 0;
13674
- };
13675
- var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
13676
- var getRivetEnvoyVersion = () => {
13677
- const value = getEnvUniversal("RIVET_ENVOY_VERSION");
13678
- return value !== void 0 ? parseInt(value, 10) : void 0;
13679
- };
13680
- var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
13681
- var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
13682
- var getRivetkitRuntime = () => getEnvUniversal("RIVETKIT_RUNTIME");
13683
- var getRivetkitRuntimeMode = () => {
13684
- const value = getEnvUniversal("RIVETKIT_RUNTIME_MODE");
13685
- if (value === void 0) return "envoy";
13686
- if (value === "envoy" || value === "serverless") return value;
13687
- throw new Error(
13688
- `RIVETKIT_RUNTIME_MODE env var must be "envoy" or "serverless"; got "${value}"`
13689
- );
13690
- };
13691
- var getRivetkitPublicDir = () => {
13692
- const value = getEnvUniversal("RIVETKIT_PUBLIC_DIR");
13693
- return value === void 0 || value === "" ? void 0 : value;
13694
- };
13695
- function parsePortEnv(raw) {
13696
- if (raw === void 0 || raw === "") return void 0;
13697
- const parsed = Number.parseInt(raw, 10);
13698
- if (!Number.isFinite(parsed) || parsed < 1 || parsed > 65535 || String(parsed) !== raw.trim()) {
13699
- throw new Error(
13700
- `RIVET_PORT env var must be an integer between 1 and 65535; got "${raw}"`
13701
- );
13702
- }
13703
- return parsed;
13241
+ return parsed;
13704
13242
  }
13705
13243
  var getLogLevel = () => getEnvUniversal("RIVET_LOG_LEVEL") ?? getEnvUniversal("LOG_LEVEL");
13706
13244
  var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
@@ -13824,7 +13362,7 @@ function noopNext() {
13824
13362
  }
13825
13363
  var package_default = {
13826
13364
  name: "rivetkit",
13827
- version: "2.3.12-rc.2",
13365
+ version: "2.3.12-rc.3",
13828
13366
  description: "Lightweight libraries for building stateful actors on edge platforms",
13829
13367
  license: "Apache-2.0",
13830
13368
  keywords: [
@@ -15127,7 +14665,7 @@ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32
15127
14665
  };
15128
14666
  }
15129
14667
 
15130
- // ../rivetkit/dist/tsup/chunk-KPZQI3TG.js
14668
+ // ../rivetkit/dist/tsup/chunk-WVFTFWJL.js
15131
14669
  var config2 = /* @__PURE__ */ Config({});
15132
14670
  function readWorkflowCbor(bc) {
15133
14671
  return readData(bc);
@@ -15237,38 +14775,162 @@ function readWorkflowStepEntry(bc) {
15237
14775
  error: read1(bc)
15238
14776
  };
15239
14777
  }
15240
- function readWorkflowLoopEntry(bc) {
14778
+ function readWorkflowLoopEntry(bc) {
14779
+ return {
14780
+ state: readWorkflowCbor(bc),
14781
+ iteration: readU32(bc),
14782
+ output: read0(bc)
14783
+ };
14784
+ }
14785
+ function readWorkflowSleepEntry(bc) {
14786
+ return {
14787
+ deadline: readU64(bc),
14788
+ state: readWorkflowSleepState(bc)
14789
+ };
14790
+ }
14791
+ function readWorkflowMessageEntry(bc) {
14792
+ return {
14793
+ name: readString(bc),
14794
+ messageData: readWorkflowCbor(bc)
14795
+ };
14796
+ }
14797
+ function readWorkflowRollbackCheckpointEntry(bc) {
14798
+ return {
14799
+ name: readString(bc)
14800
+ };
14801
+ }
14802
+ function readWorkflowBranchStatus(bc) {
14803
+ return {
14804
+ status: readWorkflowBranchStatusType(bc),
14805
+ output: read0(bc),
14806
+ error: read1(bc)
14807
+ };
14808
+ }
14809
+ function read2(bc) {
14810
+ const len = readUintSafe(bc);
14811
+ const result = /* @__PURE__ */ new Map();
14812
+ for (let i = 0; i < len; i++) {
14813
+ const offset = bc.offset;
14814
+ const key = readString(bc);
14815
+ if (result.has(key)) {
14816
+ bc.offset = offset;
14817
+ throw new BareError(offset, "duplicated key");
14818
+ }
14819
+ result.set(key, readWorkflowBranchStatus(bc));
14820
+ }
14821
+ return result;
14822
+ }
14823
+ function readWorkflowJoinEntry(bc) {
14824
+ return {
14825
+ branches: read2(bc)
14826
+ };
14827
+ }
14828
+ function readWorkflowRaceEntry(bc) {
14829
+ return {
14830
+ winner: read1(bc),
14831
+ branches: read2(bc)
14832
+ };
14833
+ }
14834
+ function readWorkflowRemovedEntry(bc) {
14835
+ return {
14836
+ originalType: readString(bc),
14837
+ originalName: read1(bc)
14838
+ };
14839
+ }
14840
+ function readWorkflowVersionCheckEntry(bc) {
14841
+ return {
14842
+ resolved: readU32(bc),
14843
+ latest: readU32(bc)
14844
+ };
14845
+ }
14846
+ function readWorkflowEntryKind(bc) {
14847
+ const offset = bc.offset;
14848
+ const tag = readU8(bc);
14849
+ switch (tag) {
14850
+ case 0:
14851
+ return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
14852
+ case 1:
14853
+ return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
14854
+ case 2:
14855
+ return {
14856
+ tag: "WorkflowSleepEntry",
14857
+ val: readWorkflowSleepEntry(bc)
14858
+ };
14859
+ case 3:
14860
+ return {
14861
+ tag: "WorkflowMessageEntry",
14862
+ val: readWorkflowMessageEntry(bc)
14863
+ };
14864
+ case 4:
14865
+ return {
14866
+ tag: "WorkflowRollbackCheckpointEntry",
14867
+ val: readWorkflowRollbackCheckpointEntry(bc)
14868
+ };
14869
+ case 5:
14870
+ return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
14871
+ case 6:
14872
+ return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
14873
+ case 7:
14874
+ return {
14875
+ tag: "WorkflowRemovedEntry",
14876
+ val: readWorkflowRemovedEntry(bc)
14877
+ };
14878
+ case 8:
14879
+ return {
14880
+ tag: "WorkflowVersionCheckEntry",
14881
+ val: readWorkflowVersionCheckEntry(bc)
14882
+ };
14883
+ default: {
14884
+ bc.offset = offset;
14885
+ throw new BareError(offset, "invalid tag");
14886
+ }
14887
+ }
14888
+ }
14889
+ function readWorkflowEntry(bc) {
15241
14890
  return {
15242
- state: readWorkflowCbor(bc),
15243
- iteration: readU32(bc),
15244
- output: read0(bc)
14891
+ id: readString(bc),
14892
+ location: readWorkflowLocation(bc),
14893
+ kind: readWorkflowEntryKind(bc)
15245
14894
  };
15246
14895
  }
15247
- function readWorkflowSleepEntry(bc) {
15248
- return {
15249
- deadline: readU64(bc),
15250
- state: readWorkflowSleepState(bc)
15251
- };
14896
+ function read3(bc) {
14897
+ return readBool(bc) ? readU64(bc) : null;
15252
14898
  }
15253
- function readWorkflowMessageEntry(bc) {
14899
+ function readWorkflowEntryMetadata(bc) {
15254
14900
  return {
15255
- name: readString(bc),
15256
- messageData: readWorkflowCbor(bc)
14901
+ status: readWorkflowEntryStatus(bc),
14902
+ error: read1(bc),
14903
+ attempts: readU32(bc),
14904
+ lastAttemptAt: readU64(bc),
14905
+ createdAt: readU64(bc),
14906
+ completedAt: read3(bc),
14907
+ rollbackCompletedAt: read3(bc),
14908
+ rollbackError: read1(bc)
15257
14909
  };
15258
14910
  }
15259
- function readWorkflowRollbackCheckpointEntry(bc) {
15260
- return {
15261
- name: readString(bc)
15262
- };
14911
+ function read4(bc) {
14912
+ const len = readUintSafe(bc);
14913
+ if (len === 0) {
14914
+ return [];
14915
+ }
14916
+ const result = [readString(bc)];
14917
+ for (let i = 1; i < len; i++) {
14918
+ result[i] = readString(bc);
14919
+ }
14920
+ return result;
15263
14921
  }
15264
- function readWorkflowBranchStatus(bc) {
15265
- return {
15266
- status: readWorkflowBranchStatusType(bc),
15267
- output: read0(bc),
15268
- error: read1(bc)
15269
- };
14922
+ function read5(bc) {
14923
+ const len = readUintSafe(bc);
14924
+ if (len === 0) {
14925
+ return [];
14926
+ }
14927
+ const result = [readWorkflowEntry(bc)];
14928
+ for (let i = 1; i < len; i++) {
14929
+ result[i] = readWorkflowEntry(bc);
14930
+ }
14931
+ return result;
15270
14932
  }
15271
- function read2(bc) {
14933
+ function read6(bc) {
15272
14934
  const len = readUintSafe(bc);
15273
14935
  const result = /* @__PURE__ */ new Map();
15274
14936
  for (let i = 0; i < len; i++) {
@@ -15278,152 +14940,492 @@ function read2(bc) {
15278
14940
  bc.offset = offset;
15279
14941
  throw new BareError(offset, "duplicated key");
15280
14942
  }
15281
- result.set(key, readWorkflowBranchStatus(bc));
14943
+ result.set(key, readWorkflowEntryMetadata(bc));
14944
+ }
14945
+ return result;
14946
+ }
14947
+ function readWorkflowHistory(bc) {
14948
+ return {
14949
+ nameRegistry: read4(bc),
14950
+ entries: read5(bc),
14951
+ entryMetadata: read6(bc)
14952
+ };
14953
+ }
14954
+ function decodeWorkflowHistory(bytes) {
14955
+ const bc = new ByteCursor(bytes, config2);
14956
+ const result = readWorkflowHistory(bc);
14957
+ if (bc.offset < bc.view.byteLength) {
14958
+ throw new BareError(bc.offset, "remaining bytes");
14959
+ }
14960
+ return result;
14961
+ }
14962
+ function decodeWorkflowHistoryTransport(data) {
14963
+ return decodeWorkflowHistory(toUint8Array(data));
14964
+ }
14965
+
14966
+ // ../rivetkit/dist/tsup/chunk-6W5VGLFT.js
14967
+ function flattenActionHandlers(actions) {
14968
+ const flattened = /* @__PURE__ */ Object.create(null);
14969
+ for (const { name, handler } of collectActionEntries(actions)) {
14970
+ flattened[name] = handler;
14971
+ }
14972
+ return flattened;
14973
+ }
14974
+ function flattenActionInputSchemas(actions, schemas) {
14975
+ if (schemas === void 0) return void 0;
14976
+ if (!isRecord(schemas)) {
14977
+ throw new TypeError("actionInputSchemas must be an object");
14978
+ }
14979
+ const flattened = /* @__PURE__ */ Object.create(null);
14980
+ for (const { name, path: path2 } of collectActionEntries(actions)) {
14981
+ const nestedSchema = lookupNestedSchema(schemas, path2);
14982
+ const flatSchema = schemas[name];
14983
+ if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
14984
+ throw new TypeError(
14985
+ `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
14986
+ );
14987
+ }
14988
+ const schema = nestedSchema ?? flatSchema;
14989
+ if (schema !== void 0) {
14990
+ flattened[name] = schema;
14991
+ }
14992
+ }
14993
+ return flattened;
14994
+ }
14995
+ function collectActionEntries(actions) {
14996
+ const entries = [];
14997
+ const names = /* @__PURE__ */ new Set();
14998
+ visitActionGroup(actions ?? {}, [], entries, names);
14999
+ return entries;
15000
+ }
15001
+ function visitActionGroup(value, path2, entries, names) {
15002
+ if (!isRecord(value)) {
15003
+ throw new TypeError(
15004
+ `${formatActionPath(path2)} must be an action handler or group`
15005
+ );
15006
+ }
15007
+ for (const [segment, child] of Object.entries(value)) {
15008
+ const childPath = [...path2, segment];
15009
+ if (typeof child === "function") {
15010
+ const name = childPath.join(".");
15011
+ if (names.has(name)) {
15012
+ throw new TypeError(
15013
+ `Multiple action definitions flatten to \`${name}\``
15014
+ );
15015
+ }
15016
+ names.add(name);
15017
+ entries.push({
15018
+ name,
15019
+ path: childPath,
15020
+ handler: child
15021
+ });
15022
+ } else {
15023
+ visitActionGroup(child, childPath, entries, names);
15024
+ }
15025
+ }
15026
+ }
15027
+ function lookupNestedSchema(schemas, path2) {
15028
+ let value = schemas;
15029
+ for (const segment of path2) {
15030
+ if (!isRecord(value) || !Object.hasOwn(value, segment)) {
15031
+ return void 0;
15032
+ }
15033
+ value = value[segment];
15034
+ }
15035
+ return value;
15036
+ }
15037
+ function isRecord(value) {
15038
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
15039
+ return false;
15040
+ }
15041
+ const prototype = Object.getPrototypeOf(value);
15042
+ return prototype === Object.prototype || prototype === null;
15043
+ }
15044
+ function formatActionPath(path2) {
15045
+ return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
15046
+ }
15047
+ var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
15048
+ var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
15049
+ "rivetkit.actor_context_internal"
15050
+ );
15051
+ var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
15052
+ var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
15053
+ var zFunction = () => external_exports.custom((val) => typeof val === "function");
15054
+ var zActionTree = external_exports.custom((value) => {
15055
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
15056
+ return false;
15057
+ }
15058
+ const prototype = Object.getPrototypeOf(value);
15059
+ return prototype === Object.prototype || prototype === null;
15060
+ }).superRefine((actions, ctx) => {
15061
+ try {
15062
+ flattenActionHandlers(actions);
15063
+ } catch (error46) {
15064
+ ctx.addIssue({
15065
+ code: "custom",
15066
+ message: error46 instanceof Error ? error46.message : "Invalid action definition"
15067
+ });
15068
+ }
15069
+ });
15070
+ var WorkflowInspectorConfigSchema = external_exports.object({
15071
+ getHistory: zFunction(),
15072
+ getState: zFunction().optional(),
15073
+ onHistoryUpdated: zFunction().optional(),
15074
+ replayFromStep: zFunction().optional()
15075
+ });
15076
+ var RunInspectorConfigSchema = external_exports.object({
15077
+ workflow: WorkflowInspectorConfigSchema.optional()
15078
+ }).optional();
15079
+ var BUILTIN_INSPECTOR_TAB_IDS = [
15080
+ "workflow",
15081
+ "database",
15082
+ "state",
15083
+ "queue",
15084
+ "schedules",
15085
+ "connections",
15086
+ "console"
15087
+ ];
15088
+ var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
15089
+ var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
15090
+ var CustomInspectorTabEntrySchema = external_exports.object({
15091
+ id: external_exports.string().regex(
15092
+ CUSTOM_INSPECTOR_TAB_ID_RE,
15093
+ "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
15094
+ ),
15095
+ label: external_exports.string().min(1),
15096
+ source: external_exports.string().min(1),
15097
+ /**
15098
+ * Optional icon id. The dashboard maps strings to glyphs (see its
15099
+ * icon registry); unknown ids fall back to a generic icon.
15100
+ */
15101
+ icon: external_exports.string().min(1).optional(),
15102
+ hidden: external_exports.literal(false).optional()
15103
+ }).strict();
15104
+ var HideInspectorTabEntrySchema = external_exports.object({
15105
+ id: BuiltinInspectorTabIdSchema,
15106
+ hidden: external_exports.literal(true)
15107
+ }).strict();
15108
+ var InspectorTabEntrySchema = external_exports.union([
15109
+ CustomInspectorTabEntrySchema,
15110
+ HideInspectorTabEntrySchema
15111
+ ]);
15112
+ var ActorInspectorConfigSchema = external_exports.object({
15113
+ tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
15114
+ }).strict().refine(
15115
+ (data) => {
15116
+ const ids = data.tabs.map((t) => t.id);
15117
+ return new Set(ids).size === ids.length;
15118
+ },
15119
+ { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
15120
+ ).refine(
15121
+ (data) => {
15122
+ const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
15123
+ return data.tabs.every(
15124
+ (t) => t.hidden === true || !builtinSet.has(t.id)
15125
+ );
15126
+ },
15127
+ {
15128
+ message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
15129
+ path: ["tabs"]
15130
+ }
15131
+ );
15132
+ var RunConfigSchema = external_exports.object({
15133
+ /** Display name for the actor in the Inspector UI. */
15134
+ name: external_exports.string().optional(),
15135
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15136
+ icon: external_exports.string().optional(),
15137
+ /** The run handler function. */
15138
+ run: zFunction(),
15139
+ /** Inspector integration for long-running run handlers. */
15140
+ inspector: RunInspectorConfigSchema.optional()
15141
+ });
15142
+ var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for("rivetkit.run_function_config");
15143
+ function defineRunHandler(run, options) {
15144
+ if (options.inspectorKind === void 0 !== (options.createInspector === void 0)) {
15145
+ throw new TypeError(
15146
+ "defineRunHandler requires inspectorKind and createInspector together"
15147
+ );
15282
15148
  }
15283
- return result;
15284
- }
15285
- function readWorkflowJoinEntry(bc) {
15286
- return {
15287
- branches: read2(bc)
15288
- };
15149
+ Object.defineProperty(run, RUN_FUNCTION_CONFIG_SYMBOL, {
15150
+ configurable: false,
15151
+ enumerable: false,
15152
+ writable: false,
15153
+ value: {
15154
+ name: options.name,
15155
+ icon: options.icon,
15156
+ inspectorKind: options.inspectorKind,
15157
+ createInspector: options.createInspector
15158
+ }
15159
+ });
15160
+ return run;
15289
15161
  }
15290
- function readWorkflowRaceEntry(bc) {
15291
- return {
15292
- winner: read1(bc),
15293
- branches: read2(bc)
15294
- };
15162
+ function getRunInspectorKind(run) {
15163
+ var _a2;
15164
+ if (!run || typeof run !== "function") return void 0;
15165
+ return (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.inspectorKind;
15295
15166
  }
15296
- function readWorkflowRemovedEntry(bc) {
15297
- return {
15298
- originalType: readString(bc),
15299
- originalName: read1(bc)
15300
- };
15167
+ function createRunInspector(run, context) {
15168
+ var _a2, _b;
15169
+ if (!run || typeof run !== "function") return void 0;
15170
+ return (_b = (_a2 = run[RUN_FUNCTION_CONFIG_SYMBOL]) == null ? void 0 : _a2.createInspector) == null ? void 0 : _b.call(_a2, context);
15301
15171
  }
15302
- function readWorkflowVersionCheckEntry(bc) {
15303
- return {
15304
- resolved: readU32(bc),
15305
- latest: readU32(bc)
15306
- };
15172
+ var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
15173
+ function getRunFunction(run) {
15174
+ if (!run) return void 0;
15175
+ if (typeof run === "function") return run;
15176
+ return run.run;
15307
15177
  }
15308
- function readWorkflowEntryKind(bc) {
15309
- const offset = bc.offset;
15310
- const tag = readU8(bc);
15311
- switch (tag) {
15312
- case 0:
15313
- return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
15314
- case 1:
15315
- return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
15316
- case 2:
15317
- return {
15318
- tag: "WorkflowSleepEntry",
15319
- val: readWorkflowSleepEntry(bc)
15320
- };
15321
- case 3:
15322
- return {
15323
- tag: "WorkflowMessageEntry",
15324
- val: readWorkflowMessageEntry(bc)
15325
- };
15326
- case 4:
15327
- return {
15328
- tag: "WorkflowRollbackCheckpointEntry",
15329
- val: readWorkflowRollbackCheckpointEntry(bc)
15330
- };
15331
- case 5:
15332
- return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
15333
- case 6:
15334
- return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
15335
- case 7:
15336
- return {
15337
- tag: "WorkflowRemovedEntry",
15338
- val: readWorkflowRemovedEntry(bc)
15339
- };
15340
- case 8:
15341
- return {
15342
- tag: "WorkflowVersionCheckEntry",
15343
- val: readWorkflowVersionCheckEntry(bc)
15344
- };
15345
- default: {
15346
- bc.offset = offset;
15347
- throw new BareError(offset, "invalid tag");
15348
- }
15178
+ function getRunMetadata(run) {
15179
+ if (!run) return {};
15180
+ if (typeof run === "function") {
15181
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15182
+ if (!config3) return {};
15183
+ return { name: config3.name, icon: config3.icon };
15349
15184
  }
15185
+ return { name: run.name, icon: run.icon };
15350
15186
  }
15351
- function readWorkflowEntry(bc) {
15352
- return {
15353
- id: readString(bc),
15354
- location: readWorkflowLocation(bc),
15355
- kind: readWorkflowEntryKind(bc)
15356
- };
15357
- }
15358
- function read3(bc) {
15359
- return readBool(bc) ? readU64(bc) : null;
15187
+ function getRunInspectorConfig(run, actor2) {
15188
+ if (!run) return void 0;
15189
+ if (typeof run === "function") {
15190
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15191
+ return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
15192
+ }
15193
+ return run.inspector;
15360
15194
  }
15361
- function readWorkflowEntryMetadata(bc) {
15362
- return {
15363
- status: readWorkflowEntryStatus(bc),
15364
- error: read1(bc),
15365
- attempts: readU32(bc),
15366
- lastAttemptAt: readU64(bc),
15367
- createdAt: readU64(bc),
15368
- completedAt: read3(bc),
15369
- rollbackCompletedAt: read3(bc),
15370
- rollbackError: read1(bc)
15371
- };
15195
+ function hasRunInspectorConfig(run) {
15196
+ if (!run) return false;
15197
+ if (typeof run !== "function") return run.inspector !== void 0;
15198
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15199
+ 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;
15372
15200
  }
15373
- function read4(bc) {
15374
- const len = readUintSafe(bc);
15375
- if (len === 0) {
15376
- return [];
15377
- }
15378
- const result = [readString(bc)];
15379
- for (let i = 1; i < len; i++) {
15380
- result[i] = readString(bc);
15201
+ function disposeRunInspector(run, actorId) {
15202
+ var _a2;
15203
+ if (!run || typeof run !== "function") {
15204
+ return;
15381
15205
  }
15382
- return result;
15206
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15207
+ (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
15383
15208
  }
15384
- function read5(bc) {
15385
- const len = readUintSafe(bc);
15386
- if (len === 0) {
15387
- return [];
15388
- }
15389
- const result = [readWorkflowEntry(bc)];
15390
- for (let i = 1; i < len; i++) {
15391
- result[i] = readWorkflowEntry(bc);
15209
+ var GlobalActorOptionsBaseSchema = external_exports.object({
15210
+ /** Display name for the actor in the Inspector UI. */
15211
+ name: external_exports.string().optional(),
15212
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15213
+ icon: external_exports.string().optional(),
15214
+ /** Enables the experimental Actor Runtime Socket for this actor. */
15215
+ enableActorRuntimeSocket: external_exports.boolean().default(false),
15216
+ /**
15217
+ * Can hibernate WebSockets for onWebSocket.
15218
+ *
15219
+ * WebSockets using actions/events are hibernatable by default.
15220
+ *
15221
+ * @experimental
15222
+ **/
15223
+ canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
15224
+ }).strict();
15225
+ var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
15226
+ () => ({})
15227
+ );
15228
+ var InstanceActorOptionsBaseSchema = external_exports.object({
15229
+ createVarsTimeout: external_exports.number().positive().default(5e3),
15230
+ createConnStateTimeout: external_exports.number().positive().default(5e3),
15231
+ onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
15232
+ onConnectTimeout: external_exports.number().positive().default(5e3),
15233
+ onMigrateTimeout: external_exports.number().positive().default(3e4),
15234
+ sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
15235
+ /** @deprecated `onDestroyTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
15236
+ onDestroyTimeout: external_exports.number().positive().optional(),
15237
+ /** @deprecated `waitUntilTimeout` is folded into `sleepGracePeriod`, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0. */
15238
+ waitUntilTimeout: external_exports.number().positive().optional(),
15239
+ stateSaveInterval: external_exports.number().positive().default(1e3),
15240
+ actionTimeout: external_exports.number().positive().default(6e4),
15241
+ connectionLivenessTimeout: external_exports.number().positive().default(2500),
15242
+ connectionLivenessInterval: external_exports.number().positive().default(5e3),
15243
+ /** @deprecated Use `c.keepAwake(promise)` to scope keep-awake to a specific operation, or keep `noSleep` for actors that must stay awake indefinitely. Will be removed in 2.2.0. */
15244
+ noSleep: external_exports.boolean().default(false),
15245
+ sleepTimeout: external_exports.number().positive().default(3e4),
15246
+ maxQueueSize: external_exports.number().positive().default(1e3),
15247
+ /** Maximum pending one-shot and recurring schedules. */
15248
+ maxSchedules: external_exports.number().int().nonnegative().default(1e3),
15249
+ maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
15250
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15251
+ preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
15252
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15253
+ preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
15254
+ }).strict();
15255
+ var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
15256
+ var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
15257
+ InstanceActorOptionsBaseSchema.shape
15258
+ ).strict().prefault(() => ({}));
15259
+ var ActorConfigSchema = external_exports.object({
15260
+ onCreate: zFunction().optional(),
15261
+ onDestroy: zFunction().optional(),
15262
+ onMigrate: zFunction().optional(),
15263
+ onWake: zFunction().optional(),
15264
+ onSleep: zFunction().optional(),
15265
+ run: zRunHandler,
15266
+ onStateChange: zFunction().optional(),
15267
+ onBeforeConnect: zFunction().optional(),
15268
+ onConnect: zFunction().optional(),
15269
+ onDisconnect: zFunction().optional(),
15270
+ onBeforeActionResponse: zFunction().optional(),
15271
+ onRequest: zFunction().optional(),
15272
+ onWebSocket: zFunction().optional(),
15273
+ actions: zActionTree.default(() => ({})),
15274
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15275
+ connParamsSchema: external_exports.any().optional(),
15276
+ events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15277
+ queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15278
+ state: external_exports.any().optional(),
15279
+ createState: zFunction().optional(),
15280
+ connState: external_exports.any().optional(),
15281
+ createConnState: zFunction().optional(),
15282
+ vars: external_exports.any().optional(),
15283
+ db: external_exports.any().optional(),
15284
+ createVars: zFunction().optional(),
15285
+ options: ActorOptionsSchema,
15286
+ inspector: ActorInspectorConfigSchema.optional()
15287
+ }).strict().refine(
15288
+ (data) => !(data.state !== void 0 && data.createState !== void 0),
15289
+ {
15290
+ message: "Cannot define both 'state' and 'createState'",
15291
+ path: ["state"]
15392
15292
  }
15393
- return result;
15394
- }
15395
- function read6(bc) {
15396
- const len = readUintSafe(bc);
15397
- const result = /* @__PURE__ */ new Map();
15398
- for (let i = 0; i < len; i++) {
15399
- const offset = bc.offset;
15400
- const key = readString(bc);
15401
- if (result.has(key)) {
15402
- bc.offset = offset;
15403
- throw new BareError(offset, "duplicated key");
15404
- }
15405
- result.set(key, readWorkflowEntryMetadata(bc));
15293
+ ).refine(
15294
+ (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
15295
+ {
15296
+ message: "Cannot define both 'connState' and 'createConnState'",
15297
+ path: ["connState"]
15406
15298
  }
15407
- return result;
15408
- }
15409
- function readWorkflowHistory(bc) {
15410
- return {
15411
- nameRegistry: read4(bc),
15412
- entries: read5(bc),
15413
- entryMetadata: read6(bc)
15414
- };
15415
- }
15416
- function decodeWorkflowHistory(bytes) {
15417
- const bc = new ByteCursor(bytes, config2);
15418
- const result = readWorkflowHistory(bc);
15419
- if (bc.offset < bc.view.byteLength) {
15420
- throw new BareError(bc.offset, "remaining bytes");
15299
+ ).refine(
15300
+ (data) => !(data.vars !== void 0 && data.createVars !== void 0),
15301
+ {
15302
+ message: "Cannot define both 'vars' and 'createVars'",
15303
+ path: ["vars"]
15421
15304
  }
15422
- return result;
15423
- }
15424
- function decodeWorkflowHistoryTransport(data) {
15425
- return decodeWorkflowHistory(toUint8Array(data));
15426
- }
15305
+ );
15306
+ var DocActorOptionsSchema = external_exports.object({
15307
+ name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
15308
+ icon: external_exports.string().optional().describe(
15309
+ "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
15310
+ ),
15311
+ enableActorRuntimeSocket: external_exports.boolean().optional().describe(
15312
+ "Enables the experimental Actor Runtime Socket for this actor. Default: false"
15313
+ ),
15314
+ createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
15315
+ createConnStateTimeout: external_exports.number().optional().describe(
15316
+ "Timeout in ms for createConnState handler. Default: 5000"
15317
+ ),
15318
+ onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
15319
+ onBeforeConnectTimeout: external_exports.number().optional().describe(
15320
+ "Timeout in ms for onBeforeConnect handler. Default: 5000"
15321
+ ),
15322
+ onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
15323
+ sleepGracePeriod: external_exports.number().optional().describe(
15324
+ `Max time in ms for the graceful shutdown window. Covers lifecycle hooks (onSleep, onDestroy), the run handler wait, async raw WebSocket handlers, disconnect callbacks, and final state serialization. Default: ${DEFAULT_SLEEP_GRACE_PERIOD}.`
15325
+ ),
15326
+ onDestroyTimeout: external_exports.number().optional().describe(
15327
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15328
+ ),
15329
+ waitUntilTimeout: external_exports.number().optional().describe(
15330
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15331
+ ),
15332
+ stateSaveInterval: external_exports.number().optional().describe(
15333
+ "Interval in ms between automatic state saves. Default: 1000"
15334
+ ),
15335
+ actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
15336
+ connectionLivenessTimeout: external_exports.number().optional().describe(
15337
+ "Timeout in ms for connection liveness checks. Default: 2500"
15338
+ ),
15339
+ connectionLivenessInterval: external_exports.number().optional().describe(
15340
+ "Interval in ms between connection liveness checks. Default: 5000"
15341
+ ),
15342
+ noSleep: external_exports.boolean().optional().describe(
15343
+ "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
15344
+ ),
15345
+ sleepTimeout: external_exports.number().optional().describe(
15346
+ "Time in ms of inactivity before the actor sleeps. Default: 30000"
15347
+ ),
15348
+ maxQueueSize: external_exports.number().optional().describe(
15349
+ "Maximum number of queue messages before rejecting new messages. Default: 1000"
15350
+ ),
15351
+ maxSchedules: external_exports.number().int().nonnegative().optional().describe(
15352
+ "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
15353
+ ),
15354
+ maxQueueMessageSize: external_exports.number().optional().describe(
15355
+ "Maximum size of each queue message in bytes. Default: 65536"
15356
+ ),
15357
+ canHibernateWebSocket: external_exports.boolean().optional().describe(
15358
+ "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
15359
+ )
15360
+ }).describe("Actor options for timeouts and behavior configuration.");
15361
+ var DocActorConfigSchema = external_exports.object({
15362
+ state: external_exports.unknown().optional().describe(
15363
+ "Initial state value for the actor. Cannot be used with createState."
15364
+ ),
15365
+ createState: external_exports.unknown().optional().describe(
15366
+ "Function to create initial state. Receives context and input. Cannot be used with state."
15367
+ ),
15368
+ connState: external_exports.unknown().optional().describe(
15369
+ "Initial connection state value. Cannot be used with createConnState."
15370
+ ),
15371
+ createConnState: external_exports.unknown().optional().describe(
15372
+ "Function to create connection state. Receives context and connection params. The pending connection is not visible in c.conns until this succeeds. Cannot be used with connState."
15373
+ ),
15374
+ vars: external_exports.unknown().optional().describe(
15375
+ "Initial ephemeral variables value. Cannot be used with createVars."
15376
+ ),
15377
+ createVars: external_exports.unknown().optional().describe(
15378
+ "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
15379
+ ),
15380
+ db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
15381
+ onCreate: external_exports.unknown().optional().describe(
15382
+ "Called when the actor is first initialized. Use to initialize state."
15383
+ ),
15384
+ onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
15385
+ onMigrate: external_exports.unknown().optional().describe(
15386
+ "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
15387
+ ),
15388
+ onWake: external_exports.unknown().optional().describe(
15389
+ "Called when the actor wakes up and is ready to receive connections and actions."
15390
+ ),
15391
+ onSleep: external_exports.unknown().optional().describe(
15392
+ "Called when the actor is stopping or sleeping. Use to clean up resources."
15393
+ ),
15394
+ run: external_exports.unknown().optional().describe(
15395
+ "Called after actor starts. Does not block startup. Use for background tasks like queue processing or tick loops. If it exits, the actor follows the normal idle sleep timeout once idle. If it throws, the actor logs the error and then follows the normal idle sleep timeout once idle."
15396
+ ),
15397
+ onStateChange: external_exports.unknown().optional().describe(
15398
+ "Called when the actor's state changes. State changes within this hook won't trigger recursion."
15399
+ ),
15400
+ onBeforeConnect: external_exports.unknown().optional().describe(
15401
+ "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
15402
+ ),
15403
+ onConnect: external_exports.unknown().optional().describe(
15404
+ "Called when a client successfully connects. The connection is visible in c.conns before this runs."
15405
+ ),
15406
+ onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
15407
+ onBeforeActionResponse: external_exports.unknown().optional().describe(
15408
+ "Called before sending an action response. Use to transform output."
15409
+ ),
15410
+ onRequest: external_exports.unknown().optional().describe(
15411
+ "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
15412
+ ),
15413
+ onWebSocket: external_exports.unknown().optional().describe(
15414
+ "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
15415
+ ),
15416
+ actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15417
+ "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
15418
+ ),
15419
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15420
+ "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
15421
+ ),
15422
+ connParamsSchema: external_exports.unknown().optional().describe(
15423
+ "Optional schema for validating connection params in native runtimes."
15424
+ ),
15425
+ events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
15426
+ queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
15427
+ options: DocActorOptionsSchema.optional()
15428
+ }).describe("Actor configuration passed to the actor() function.");
15427
15429
 
15428
15430
  // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
15429
15431
  var EMPTY_KEY = "/";
@@ -15542,44 +15544,6 @@ function removePrefixFromKey(prefixedKey) {
15542
15544
  return prefixedKey.slice(KEYS.KV.length);
15543
15545
  }
15544
15546
 
15545
- // ../rivetkit/dist/tsup/chunk-ZEIH7S4M.js
15546
- function logger() {
15547
- return getLogger("actor-client");
15548
- }
15549
- var webSocketPromise = null;
15550
- async function importWebSocket() {
15551
- if (webSocketPromise !== null) {
15552
- return webSocketPromise;
15553
- }
15554
- webSocketPromise = (async () => {
15555
- let _WebSocket;
15556
- if (typeof WebSocket !== "undefined") {
15557
- _WebSocket = WebSocket;
15558
- } else {
15559
- try {
15560
- const moduleName = "ws";
15561
- const ws = await import(
15562
- /* webpackIgnore: true */
15563
- moduleName
15564
- );
15565
- _WebSocket = ws.default;
15566
- logger().debug("using websocket from npm");
15567
- } catch {
15568
- _WebSocket = class MockWebSocket {
15569
- constructor() {
15570
- throw new Error(
15571
- 'WebSocket support requires installing the "ws" peer dependency.'
15572
- );
15573
- }
15574
- };
15575
- logger().debug("using mock websocket");
15576
- }
15577
- }
15578
- return _WebSocket;
15579
- })();
15580
- return webSocketPromise;
15581
- }
15582
-
15583
15547
  // ../rivetkit/dist/tsup/chunk-JTHHCZCZ.js
15584
15548
  var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15585
15549
  function isManualTransactionControl(query) {
@@ -15663,7 +15627,45 @@ var AsyncMutex = class {
15663
15627
  }
15664
15628
  };
15665
15629
 
15666
- // ../rivetkit/dist/tsup/chunk-BK2JOGQQ.js
15630
+ // ../rivetkit/dist/tsup/chunk-XI4MEUUI.js
15631
+ function logger() {
15632
+ return getLogger("actor-client");
15633
+ }
15634
+ var webSocketPromise = null;
15635
+ async function importWebSocket() {
15636
+ if (webSocketPromise !== null) {
15637
+ return webSocketPromise;
15638
+ }
15639
+ webSocketPromise = (async () => {
15640
+ let _WebSocket;
15641
+ if (typeof WebSocket !== "undefined") {
15642
+ _WebSocket = WebSocket;
15643
+ } else {
15644
+ try {
15645
+ const moduleName = "ws";
15646
+ const ws = await import(
15647
+ /* webpackIgnore: true */
15648
+ moduleName
15649
+ );
15650
+ _WebSocket = ws.default;
15651
+ logger().debug("using websocket from npm");
15652
+ } catch {
15653
+ _WebSocket = class MockWebSocket {
15654
+ constructor() {
15655
+ throw new Error(
15656
+ 'WebSocket support requires installing the "ws" peer dependency.'
15657
+ );
15658
+ }
15659
+ };
15660
+ logger().debug("using mock websocket");
15661
+ }
15662
+ }
15663
+ return _WebSocket;
15664
+ })();
15665
+ return webSocketPromise;
15666
+ }
15667
+
15668
+ // ../rivetkit/dist/tsup/chunk-YYIDQBBM.js
15667
15669
  var import_invariant2 = __toESM(require_invariant(), 1);
15668
15670
 
15669
15671
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -15841,7 +15843,7 @@ function createVersionedDataHandler(config3) {
15841
15843
  return new VersionedDataHandler(config3);
15842
15844
  }
15843
15845
 
15844
- // ../rivetkit/dist/tsup/chunk-BK2JOGQQ.js
15846
+ // ../rivetkit/dist/tsup/chunk-YYIDQBBM.js
15845
15847
  var import_invariant3 = __toESM(require_invariant(), 1);
15846
15848
  var import_invariant4 = __toESM(require_invariant(), 1);
15847
15849
  var PATH_CONNECT = "/connect";
@@ -18521,7 +18523,7 @@ var ActorHandleRaw = class {
18521
18523
  async #sendQueueMessage(name, body, options) {
18522
18524
  return await this.#queueSendMutex.run(async () => {
18523
18525
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18524
- let useQueryTarget = false;
18526
+ let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18525
18527
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
18526
18528
  let actorId;
18527
18529
  try {
@@ -18584,8 +18586,9 @@ var ActorHandleRaw = class {
18584
18586
  code
18585
18587
  );
18586
18588
  if (invalidated && attempt < maxAttempts - 1) {
18587
- useQueryTarget = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18588
- if (useQueryTarget) {
18589
+ const waitForReady = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18590
+ useQueryTarget = useQueryTarget || waitForReady;
18591
+ if (waitForReady) {
18589
18592
  await this.#waitForRetryWindow();
18590
18593
  }
18591
18594
  continue;
@@ -18621,7 +18624,7 @@ var ActorHandleRaw = class {
18621
18624
  }
18622
18625
  async #sendActionNow(opts) {
18623
18626
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18624
- let useQueryTarget = false;
18627
+ let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18625
18628
  const gatewayOptions = resolveActorGatewayOptions(
18626
18629
  this.#gatewayOptions,
18627
18630
  opts
@@ -18870,7 +18873,7 @@ var ActorHandleRaw = class {
18870
18873
  }
18871
18874
  async #fetchWithResolvedActor(input, init) {
18872
18875
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18873
- let useQueryTarget = false;
18876
+ let useQueryTarget = isDynamicActorQuery(this.#actorResolutionState);
18874
18877
  const { skipReadyWait, ...requestInit } = init ?? {};
18875
18878
  const gatewayOptions = resolveActorGatewayOptions(
18876
18879
  this.#gatewayOptions,
@@ -18938,8 +18941,9 @@ var ActorHandleRaw = class {
18938
18941
  code
18939
18942
  );
18940
18943
  if (invalidated && attempt < maxAttempts - 1) {
18941
- useQueryTarget = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18942
- if (useQueryTarget) {
18944
+ const waitForReady = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18945
+ useQueryTarget = useQueryTarget || waitForReady;
18946
+ if (waitForReady) {
18943
18947
  await this.#waitForRetryWindow();
18944
18948
  }
18945
18949
  continue;
@@ -18989,10 +18993,10 @@ var ActorHandleRaw = class {
18989
18993
  }
18990
18994
  const invalidated = this.#invalidateResolvedActorId(group, code);
18991
18995
  if (invalidated && attempt < maxAttempts - 1) {
18992
- const useQueryTarget = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18996
+ const waitForReady = code === "starting" || code === "stopping" || code.startsWith("destroyed_");
18993
18997
  return {
18994
- useQueryTarget,
18995
- waitForRetryWindow: useQueryTarget
18998
+ useQueryTarget: true,
18999
+ waitForRetryWindow: waitForReady
18996
19000
  };
18997
19001
  }
18998
19002
  return null;
@@ -21365,24 +21369,45 @@ var RemoteEngineControlClient = class {
21365
21369
  name,
21366
21370
  key
21367
21371
  });
21368
- const { actor: actor2, created } = await getOrCreateActor(this.#config, {
21369
- datacenter: region,
21370
- name,
21371
- key: serializeActorKey(key),
21372
- runner_name_selector: poolName ?? this.#config.poolName,
21373
- input: actorInput ? uint8ArrayToBase642(
21374
- encodeCborCompat(actorInput)
21375
- ) : void 0,
21376
- crash_policy: crashPolicy ?? "sleep"
21377
- });
21378
- logger2().info({
21379
- msg: "getOrCreateWithKey: actor ready",
21380
- actorId: actor2.actor_id,
21381
- name,
21382
- key,
21383
- created
21384
- });
21385
- return apiActorToOutput(actor2);
21372
+ try {
21373
+ const { actor: actor2, created } = await getOrCreateActor(this.#config, {
21374
+ datacenter: region,
21375
+ name,
21376
+ key: serializeActorKey(key),
21377
+ runner_name_selector: poolName ?? this.#config.poolName,
21378
+ input: actorInput ? uint8ArrayToBase642(
21379
+ encodeCborCompat(actorInput)
21380
+ ) : void 0,
21381
+ crash_policy: crashPolicy ?? "sleep"
21382
+ });
21383
+ logger2().info({
21384
+ msg: "getOrCreateWithKey: actor ready",
21385
+ actorId: actor2.actor_id,
21386
+ name,
21387
+ key,
21388
+ created
21389
+ });
21390
+ return apiActorToOutput(actor2);
21391
+ } catch (error46) {
21392
+ if (error46 instanceof RivetError && error46.group === "actor" && error46.code === "key_reserved_in_different_datacenter") {
21393
+ logger2().warn({
21394
+ msg: "getOrCreateWithKey: key reserved in different datacenter, retrying as get",
21395
+ name,
21396
+ key
21397
+ });
21398
+ const response = await getActorByKey(this.#config, name, key);
21399
+ const existing = response.actors[0];
21400
+ if (!existing) throw error46;
21401
+ logger2().info({
21402
+ msg: "getOrCreateWithKey: resolved existing actor via get",
21403
+ actorId: existing.actor_id,
21404
+ name,
21405
+ key
21406
+ });
21407
+ return apiActorToOutput(existing);
21408
+ }
21409
+ throw error46;
21410
+ }
21386
21411
  }
21387
21412
  async createActor({
21388
21413
  name,
@@ -21583,7 +21608,7 @@ function apiActorToOutput(actor2) {
21583
21608
  };
21584
21609
  }
21585
21610
 
21586
- // ../rivetkit/dist/tsup/chunk-KRQI5GXM.js
21611
+ // ../rivetkit/dist/tsup/chunk-PSXMESQJ.js
21587
21612
  var nativeStateTransactionOpeners = /* @__PURE__ */ new WeakMap();
21588
21613
  var nativeStateTransactionClientBinders = /* @__PURE__ */ new WeakMap();
21589
21614
  function registerNativeStateTransactionOpener(provider, opener) {