@rivetkit/supabase 0.0.0-main.3118df2 → 0.0.0-main.79e97f1

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 +2494 -1715
  2. package/dist/mod.mjs +2494 -1715
  3. package/package.json +3 -3
package/dist/mod.mjs CHANGED
@@ -471,7 +471,7 @@ function unsupportedFeature(feature) {
471
471
  );
472
472
  }
473
473
 
474
- // ../rivetkit/dist/tsup/chunk-6HYOPKO3.js
474
+ // ../rivetkit/dist/tsup/chunk-Y5BCFECV.js
475
475
  import {
476
476
  pino,
477
477
  stdTimeFunctions
@@ -13147,7 +13147,9 @@ var classic_default = external_exports;
13147
13147
  // ../../../node_modules/.pnpm/zod@4.1.13/node_modules/zod/v4/index.js
13148
13148
  var v4_default = classic_default;
13149
13149
 
13150
- // ../rivetkit/dist/tsup/chunk-6HYOPKO3.js
13150
+ // ../rivetkit/dist/tsup/chunk-Y5BCFECV.js
13151
+ var import_invariant = __toESM(require_invariant(), 1);
13152
+ import * as cbor from "cbor-x";
13151
13153
  var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
13152
13154
  var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
13153
13155
  var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
@@ -13310,7 +13312,7 @@ function noopNext() {
13310
13312
  }
13311
13313
  var package_default = {
13312
13314
  name: "rivetkit",
13313
- version: "0.0.0-main.3118df2",
13315
+ version: "0.0.0-main.79e97f1",
13314
13316
  description: "Lightweight libraries for building stateful actors on edge platforms",
13315
13317
  license: "Apache-2.0",
13316
13318
  keywords: [
@@ -13382,6 +13384,16 @@ var package_default = {
13382
13384
  default: "./dist/tsup/db/drizzle.cjs"
13383
13385
  }
13384
13386
  },
13387
+ "./unstable/migrations": {
13388
+ import: {
13389
+ types: "./dist/tsup/unstable/migrations.d.ts",
13390
+ default: "./dist/tsup/unstable/migrations.js"
13391
+ },
13392
+ require: {
13393
+ types: "./dist/tsup/unstable/migrations.d.cts",
13394
+ default: "./dist/tsup/unstable/migrations.cjs"
13395
+ }
13396
+ },
13385
13397
  "./dynamic": {
13386
13398
  import: {
13387
13399
  types: "./dist/tsup/dynamic/mod.d.ts",
@@ -13481,7 +13493,7 @@ var package_default = {
13481
13493
  "./dist/tsup/chunk-*.cjs"
13482
13494
  ],
13483
13495
  scripts: {
13484
- 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 && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os",
13496
+ build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/utils.ts src/workflow/mod.ts src/test/mod.ts src/inspector/mod.ts src/inspector-tab/mod.ts src/db/mod.ts src/db/drizzle.ts src/dynamic/mod.ts src/unstable/migrations.ts && tsup src/agent-os/index.ts --no-clean --out-dir dist/tsup/agent-os",
13485
13497
  "build:browser": "tsup --config tsup.browser.config.ts",
13486
13498
  "check-types": "tsc --noEmit",
13487
13499
  lint: "biome check . && pnpm run check:test-skips && pnpm run check:wait-for-comments",
@@ -13707,1633 +13719,1766 @@ function quoteLogfmtString(value) {
13707
13719
  }
13708
13720
  return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n")}"`;
13709
13721
  }
13710
- var VERSION = package_default.version;
13711
- var _userAgent;
13712
- function httpUserAgent() {
13713
- if (_userAgent !== void 0) {
13714
- return _userAgent;
13722
+ function uint8ArrayToBase642(uint8Array) {
13723
+ if (typeof Buffer !== "undefined") {
13724
+ return Buffer.from(uint8Array).toString("base64");
13715
13725
  }
13716
- let userAgent = `RivetKit/${VERSION}`;
13717
- const navigatorObj = typeof navigator !== "undefined" ? navigator : void 0;
13718
- if (navigatorObj == null ? void 0 : navigatorObj.userAgent) userAgent += ` ${navigatorObj.userAgent}`;
13719
- _userAgent = userAgent;
13720
- return userAgent;
13721
- }
13722
- function getEnvUniversal(key) {
13723
- if (typeof Deno !== "undefined") {
13724
- return Deno.env.get(key);
13725
- } else if (typeof process !== "undefined") {
13726
- return process.env[key];
13726
+ let binary = "";
13727
+ const len = uint8Array.byteLength;
13728
+ for (let i = 0; i < len; i++) {
13729
+ binary += String.fromCharCode(uint8Array[i]);
13727
13730
  }
13731
+ return btoa(binary);
13728
13732
  }
13729
- function toUint8Array(data) {
13730
- if (data instanceof Uint8Array) {
13731
- return data;
13732
- } else if (data instanceof ArrayBuffer) {
13733
- return new Uint8Array(data);
13734
- } else if (ArrayBuffer.isView(data)) {
13735
- return new Uint8Array(
13736
- data.buffer.slice(
13737
- data.byteOffset,
13738
- data.byteOffset + data.byteLength
13739
- )
13740
- );
13733
+ function contentTypeForEncoding(encoding) {
13734
+ if (encoding === "json") {
13735
+ return "application/json";
13736
+ } else if (encoding === "cbor" || encoding === "bare") {
13737
+ return "application/octet-stream";
13741
13738
  } else {
13742
- throw new TypeError("Input must be ArrayBuffer or ArrayBufferView");
13739
+ assertUnreachable(encoding);
13743
13740
  }
13744
13741
  }
13745
- function promiseWithResolvers(onReject) {
13746
- let resolve;
13747
- let reject;
13748
- const promise2 = new Promise((res, rej) => {
13749
- resolve = res;
13750
- reject = rej;
13751
- });
13752
- promise2.catch(onReject);
13753
- return { promise: promise2, resolve, reject };
13742
+ function encodeCborCompat(value) {
13743
+ return cbor.encode(encodeJsonCompatValue(value));
13754
13744
  }
13755
- function bufferToArrayBuffer(buf) {
13756
- return buf.buffer.slice(
13757
- buf.byteOffset,
13758
- buf.byteOffset + buf.byteLength
13759
- );
13745
+ function decodeCborCompat(buffer) {
13746
+ return reviveJsonCompatValue(cbor.decode(buffer));
13760
13747
  }
13761
- function combineUrlPath(endpoint, path2, queryParams) {
13762
- const baseUrl = new URL(endpoint);
13763
- const pathParts = path2.split("?");
13764
- const pathOnly = pathParts[0];
13765
- const existingQuery = pathParts[1] || "";
13766
- const basePath = baseUrl.pathname.replace(/\/$/, "");
13767
- const cleanPath = pathOnly.startsWith("/") ? pathOnly : `/${pathOnly}`;
13768
- const fullPath = (basePath + cleanPath).replace(/\/\//g, "/");
13769
- const queryParts = [];
13770
- if (existingQuery) {
13771
- queryParts.push(existingQuery);
13772
- }
13773
- if (queryParams) {
13774
- for (const [key, value] of Object.entries(queryParams)) {
13775
- if (value !== void 0) {
13776
- queryParts.push(
13777
- `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
13778
- );
13779
- }
13748
+ function serializeWithEncoding(encoding, value, versionedDataHandler, version2, zodSchema, toJson, toBare) {
13749
+ if (encoding === "json") {
13750
+ const jsonValue = toJson(value);
13751
+ const validated = zodSchema.parse(jsonValue);
13752
+ return jsonStringifyCompat(validated);
13753
+ } else if (encoding === "cbor") {
13754
+ const jsonValue = toJson(value);
13755
+ const validated = zodSchema.parse(jsonValue);
13756
+ return cbor.encode(validated);
13757
+ } else if (encoding === "bare") {
13758
+ if (!versionedDataHandler) {
13759
+ throw new Error(
13760
+ "VersionedDataHandler is required for 'bare' encoding"
13761
+ );
13780
13762
  }
13781
- }
13782
- const fullQuery = queryParts.length > 0 ? `?${queryParts.join("&")}` : "";
13783
- return `${baseUrl.protocol}//${baseUrl.host}${fullPath}${fullQuery}`;
13784
- }
13785
-
13786
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/imports/dev.node.js
13787
- var DEV = process.env.NODE_ENV === "development";
13788
-
13789
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/assert.js
13790
- var V8Error = Error;
13791
- function assert2(test, message = "") {
13792
- if (!test) {
13793
- const e = new AssertionError(message);
13794
- V8Error.captureStackTrace?.(e, assert2);
13795
- throw e;
13763
+ if (version2 === void 0) {
13764
+ throw new Error("version is required for 'bare' encoding");
13765
+ }
13766
+ const bareValue = toBare(value);
13767
+ return versionedDataHandler.serializeWithEmbeddedVersion(
13768
+ bareValue,
13769
+ version2
13770
+ );
13771
+ } else {
13772
+ assertUnreachable(encoding);
13796
13773
  }
13797
13774
  }
13798
- var AssertionError = class extends Error {
13799
- constructor() {
13800
- super(...arguments);
13801
- this.name = "AssertionError";
13775
+ function deserializeWithEncoding(encoding, buffer, versionedDataHandler, zodSchema, fromJson, fromBare) {
13776
+ if (encoding === "json") {
13777
+ let parsed;
13778
+ if (typeof buffer === "string") {
13779
+ parsed = jsonParseCompat(buffer);
13780
+ } else {
13781
+ const decoder = new TextDecoder("utf-8");
13782
+ const jsonString = decoder.decode(buffer);
13783
+ parsed = jsonParseCompat(jsonString);
13784
+ }
13785
+ const validated = zodSchema.parse(parsed);
13786
+ return fromJson(validated);
13787
+ } else if (encoding === "cbor") {
13788
+ (0, import_invariant.default)(
13789
+ typeof buffer !== "string",
13790
+ "buffer cannot be string for cbor encoding"
13791
+ );
13792
+ const decoded = decodeCborCompat(buffer);
13793
+ const validated = zodSchema.parse(decoded);
13794
+ return fromJson(validated);
13795
+ } else if (encoding === "bare") {
13796
+ (0, import_invariant.default)(
13797
+ typeof buffer !== "string",
13798
+ "buffer cannot be string for bare encoding"
13799
+ );
13800
+ if (!versionedDataHandler) {
13801
+ throw new Error(
13802
+ "VersionedDataHandler is required for 'bare' encoding"
13803
+ );
13804
+ }
13805
+ const bareValue = versionedDataHandler.deserializeWithEmbeddedVersion(buffer);
13806
+ return fromBare(bareValue);
13807
+ } else {
13808
+ assertUnreachable(encoding);
13802
13809
  }
13803
- };
13804
-
13805
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/validator.js
13806
- function isU8(val) {
13807
- return val === (val & 255);
13808
- }
13809
- function isU32(val) {
13810
- return val === val >>> 0;
13811
13810
  }
13812
- function isU64(val) {
13813
- return val === BigInt.asUintN(64, val);
13811
+ var JSON_COMPAT_BIGINT = "$BigInt";
13812
+ var JSON_COMPAT_ARRAY_BUFFER = "$ArrayBuffer";
13813
+ var JSON_COMPAT_UINT8_ARRAY = "$Uint8Array";
13814
+ var JSON_COMPAT_UNDEFINED = "$Undefined";
13815
+ var JSON_COMPAT_SET = "$Set";
13816
+ function isTypedArray(value) {
13817
+ return value instanceof Uint8ClampedArray || value instanceof Uint16Array || value instanceof Uint32Array || value instanceof BigUint64Array || value instanceof Int8Array || value instanceof Int16Array || value instanceof Int32Array || value instanceof BigInt64Array || value instanceof Float32Array || value instanceof Float64Array;
13814
13818
  }
13815
-
13816
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/constants.js
13817
- var TEXT_DECODER_THRESHOLD = 256;
13818
- var TEXT_ENCODER_THRESHOLD = 256;
13819
- var INT_SAFE_MAX_BYTE_COUNT = 8;
13820
- var UINT_MAX_BYTE_COUNT = 10;
13821
- var UINT_SAFE32_MAX_BYTE_COUNT = 5;
13822
- var INVALID_UTF8_STRING = "invalid UTF-8 string";
13823
- var NON_CANONICAL_REPRESENTATION = "must be canonical";
13824
- var TOO_LARGE_BUFFER = "too large buffer";
13825
- var TOO_LARGE_NUMBER = "too large number";
13826
-
13827
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/bare-error.js
13828
- var BareError = class extends Error {
13829
- constructor(offset, issue2, opts) {
13830
- super(`(byte:${offset}) ${issue2}`);
13831
- this.name = "BareError";
13832
- this.issue = issue2;
13833
- this.offset = offset;
13834
- this.cause = opts?.cause;
13835
- }
13836
- };
13837
-
13838
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/byte-cursor.js
13839
- var ByteCursor = class {
13840
- /**
13841
- * @throws {BareError} Buffer exceeds `config.maxBufferLength`
13842
- */
13843
- constructor(bytes, config3) {
13844
- this.offset = 0;
13845
- if (bytes.length > config3.maxBufferLength) {
13846
- throw new BareError(0, TOO_LARGE_BUFFER);
13847
- }
13848
- this.bytes = bytes;
13849
- this.config = config3;
13850
- this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
13819
+ function assertJsonCompatValue(value, path2 = "") {
13820
+ var _a2;
13821
+ if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
13822
+ return;
13851
13823
  }
13852
- };
13853
- function check2(bc, min) {
13854
- if (DEV) {
13855
- assert2(isU32(min));
13824
+ if (typeof value === "function") {
13825
+ throw new TypeError(
13826
+ `Value at ${path2 || "root"} is a function and is not CBOR serializable`
13827
+ );
13856
13828
  }
13857
- if (bc.offset + min > bc.bytes.length) {
13858
- throw new BareError(bc.offset, "missing bytes");
13829
+ if (typeof value === "symbol") {
13830
+ throw new TypeError(
13831
+ `Value at ${path2 || "root"} is a symbol and is not CBOR serializable`
13832
+ );
13859
13833
  }
13860
- }
13861
- function reserve(bc, min) {
13862
- if (DEV) {
13863
- assert2(isU32(min));
13834
+ if (value instanceof Date || value instanceof RegExp || value instanceof Error || value instanceof ArrayBuffer || value instanceof Uint8Array || isTypedArray(value)) {
13835
+ return;
13864
13836
  }
13865
- const minLen = bc.offset + min | 0;
13866
- if (minLen > bc.bytes.length) {
13867
- grow(bc, minLen);
13837
+ if (value instanceof WeakMap) {
13838
+ throw new TypeError(
13839
+ `Value at ${path2 || "root"} is a WeakMap and is not CBOR serializable`
13840
+ );
13868
13841
  }
13869
- }
13870
- function grow(bc, minLen) {
13871
- if (minLen > bc.config.maxBufferLength) {
13872
- throw new BareError(0, TOO_LARGE_BUFFER);
13842
+ if (value instanceof WeakSet) {
13843
+ throw new TypeError(
13844
+ `Value at ${path2 || "root"} is a WeakSet and is not CBOR serializable`
13845
+ );
13873
13846
  }
13874
- const buffer = bc.bytes.buffer;
13875
- let newBytes;
13876
- if (isEs2024ArrayBufferLike(buffer) && // Make sure that the view covers the end of the buffer.
13877
- // If it is not the case, this indicates that the user don't want
13878
- // to override the trailing bytes.
13879
- bc.bytes.byteOffset + bc.bytes.byteLength === buffer.byteLength && bc.bytes.byteLength + minLen <= buffer.maxByteLength) {
13880
- const newLen = Math.min(minLen << 1, bc.config.maxBufferLength, buffer.maxByteLength);
13881
- if (buffer instanceof ArrayBuffer) {
13882
- buffer.resize(newLen);
13883
- } else {
13884
- buffer.grow(newLen);
13885
- }
13886
- newBytes = new Uint8Array(buffer, bc.bytes.byteOffset, newLen);
13887
- } else {
13888
- const newLen = Math.min(minLen << 1, bc.config.maxBufferLength);
13889
- newBytes = new Uint8Array(newLen);
13890
- newBytes.set(bc.bytes);
13891
- }
13892
- bc.bytes = newBytes;
13893
- bc.view = new DataView(newBytes.buffer);
13894
- }
13895
- function isEs2024ArrayBufferLike(buffer) {
13896
- return "maxByteLength" in buffer;
13897
- }
13898
-
13899
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/fixed-primitive.js
13900
- function readBool(bc) {
13901
- const val = readU8(bc);
13902
- if (val > 1) {
13903
- bc.offset--;
13904
- throw new BareError(bc.offset, "a bool must be equal to 0 or 1");
13905
- }
13906
- return val > 0;
13907
- }
13908
- function writeBool(bc, x) {
13909
- writeU8(bc, x ? 1 : 0);
13910
- }
13911
- function readU8(bc) {
13912
- check2(bc, 1);
13913
- return bc.bytes[bc.offset++];
13914
- }
13915
- function writeU8(bc, x) {
13916
- if (DEV) {
13917
- assert2(isU8(x), TOO_LARGE_NUMBER);
13847
+ if (value instanceof WeakRef) {
13848
+ throw new TypeError(
13849
+ `Value at ${path2 || "root"} is a WeakRef and is not CBOR serializable`
13850
+ );
13918
13851
  }
13919
- reserve(bc, 1);
13920
- bc.bytes[bc.offset++] = x;
13921
- }
13922
- function readU32(bc) {
13923
- check2(bc, 4);
13924
- const result = bc.view.getUint32(bc.offset, true);
13925
- bc.offset += 4;
13926
- return result;
13927
- }
13928
- function readU64(bc) {
13929
- check2(bc, 8);
13930
- const result = bc.view.getBigUint64(bc.offset, true);
13931
- bc.offset += 8;
13932
- return result;
13933
- }
13934
- function writeU64(bc, x) {
13935
- if (DEV) {
13936
- assert2(isU64(x), TOO_LARGE_NUMBER);
13852
+ if (value instanceof Promise) {
13853
+ throw new TypeError(
13854
+ `Value at ${path2 || "root"} is a Promise and is not CBOR serializable`
13855
+ );
13937
13856
  }
13938
- reserve(bc, 8);
13939
- bc.view.setBigUint64(bc.offset, x, true);
13940
- bc.offset += 8;
13941
- }
13942
-
13943
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/uint.js
13944
- function readUint(bc) {
13945
- let low = readU8(bc);
13946
- if (low >= 128) {
13947
- low &= 127;
13948
- let shiftMul = 128;
13949
- let byteCount = 1;
13950
- let byte;
13951
- do {
13952
- byte = readU8(bc);
13953
- low += (byte & 127) * shiftMul;
13954
- shiftMul *= /* 2**7 */
13955
- 128;
13956
- byteCount++;
13957
- } while (byte >= 128 && byteCount < 7);
13958
- let height = 0;
13959
- shiftMul = 1;
13960
- while (byte >= 128 && byteCount < UINT_MAX_BYTE_COUNT) {
13961
- byte = readU8(bc);
13962
- height += (byte & 127) * shiftMul;
13963
- shiftMul *= /* 2**7 */
13964
- 128;
13965
- byteCount++;
13966
- }
13967
- if (byte === 0 || byteCount === UINT_MAX_BYTE_COUNT && byte > 1) {
13968
- bc.offset -= byteCount;
13969
- throw new BareError(bc.offset, NON_CANONICAL_REPRESENTATION);
13857
+ if (value instanceof Map) {
13858
+ for (const [k, v] of value.entries()) {
13859
+ assertJsonCompatValue(k, `${path2 || "root"}.key(${String(k)})`);
13860
+ assertJsonCompatValue(v, `${path2 || "root"}.value(${String(k)})`);
13970
13861
  }
13971
- return BigInt(low) + (BigInt(height) << BigInt(7 * 7));
13972
- }
13973
- return BigInt(low);
13974
- }
13975
- function writeUint(bc, x) {
13976
- const truncated = BigInt.asUintN(64, x);
13977
- if (DEV) {
13978
- assert2(truncated === x, TOO_LARGE_NUMBER);
13862
+ return;
13979
13863
  }
13980
- writeUintTruncated(bc, truncated);
13981
- }
13982
- function writeUintTruncated(bc, x) {
13983
- let tmp = Number(BigInt.asUintN(7 * 7, x));
13984
- let rest = Number(x >> BigInt(7 * 7));
13985
- let byteCount = 0;
13986
- while (tmp >= 128 || rest > 0) {
13987
- writeU8(bc, 128 | tmp & 127);
13988
- tmp = Math.floor(tmp / /* 2**7 */
13989
- 128);
13990
- byteCount++;
13991
- if (byteCount === 7) {
13992
- tmp = rest;
13993
- rest = 0;
13864
+ if (value instanceof Set) {
13865
+ let index = 0;
13866
+ for (const item of value.values()) {
13867
+ assertJsonCompatValue(item, `${path2 || "root"}.set[${index}]`);
13868
+ index++;
13994
13869
  }
13870
+ return;
13995
13871
  }
13996
- writeU8(bc, tmp);
13997
- }
13998
- function readUintSafe32(bc) {
13999
- let result = readU8(bc);
14000
- if (result >= 128) {
14001
- result &= 127;
14002
- let shift = 7;
14003
- let byteCount = 1;
14004
- let byte;
14005
- do {
14006
- byte = readU8(bc);
14007
- result += (byte & 127) << shift >>> 0;
14008
- shift += 7;
14009
- byteCount++;
14010
- } while (byte >= 128 && byteCount < UINT_SAFE32_MAX_BYTE_COUNT);
14011
- if (byte === 0) {
14012
- bc.offset -= byteCount - 1;
14013
- throw new BareError(bc.offset - byteCount + 1, NON_CANONICAL_REPRESENTATION);
13872
+ if (Array.isArray(value)) {
13873
+ for (let i = 0; i < value.length; i++) {
13874
+ assertJsonCompatValue(value[i], `${path2 || "root"}[${i}]`);
14014
13875
  }
14015
- if (byteCount === UINT_SAFE32_MAX_BYTE_COUNT && byte > 15) {
14016
- bc.offset -= byteCount - 1;
14017
- throw new BareError(bc.offset, TOO_LARGE_NUMBER);
13876
+ return;
13877
+ }
13878
+ if (isPlainObject2(value)) {
13879
+ for (const key in value) {
13880
+ assertJsonCompatValue(
13881
+ value[key],
13882
+ path2 ? `${path2}.${key}` : key
13883
+ );
14018
13884
  }
13885
+ return;
14019
13886
  }
14020
- return result;
13887
+ const typeName = typeof value === "object" && value !== null ? ((_a2 = value.constructor) == null ? void 0 : _a2.name) ?? typeof value : typeof value;
13888
+ throw new TypeError(
13889
+ `Value at ${path2 || "root"} of type "${typeName}" is not CBOR serializable`
13890
+ );
14021
13891
  }
14022
- function writeUintSafe32(bc, x) {
14023
- if (DEV) {
14024
- assert2(isU32(x), TOO_LARGE_NUMBER);
13892
+ var EncodingSchema = external_exports.enum(["json", "cbor", "bare"]);
13893
+ async function inputDataToBuffer(data) {
13894
+ if (typeof data === "string") {
13895
+ return data;
14025
13896
  }
14026
- let zigZag = x >>> 0;
14027
- while (zigZag >= 128) {
14028
- writeU8(bc, 128 | zigZag & 127);
14029
- zigZag >>>= 7;
13897
+ if (data instanceof Blob) {
13898
+ return new Uint8Array(await data.arrayBuffer());
14030
13899
  }
14031
- writeU8(bc, zigZag);
14032
- }
14033
- function readUintSafe(bc) {
14034
- let result = readU8(bc);
14035
- if (result >= 128) {
14036
- result &= 127;
14037
- let shiftMul = (
14038
- /* 2**7 */
14039
- 128
14040
- );
14041
- let byteCount = 1;
14042
- let byte;
14043
- do {
14044
- byte = readU8(bc);
14045
- result += (byte & 127) * shiftMul;
14046
- shiftMul *= /* 2**7 */
14047
- 128;
14048
- byteCount++;
14049
- } while (byte >= 128 && byteCount < INT_SAFE_MAX_BYTE_COUNT);
14050
- if (byte === 0) {
14051
- bc.offset -= byteCount - 1;
14052
- throw new BareError(bc.offset - byteCount + 1, NON_CANONICAL_REPRESENTATION);
14053
- }
14054
- if (byteCount === INT_SAFE_MAX_BYTE_COUNT && byte > 15) {
14055
- bc.offset -= byteCount - 1;
14056
- throw new BareError(bc.offset, TOO_LARGE_NUMBER);
14057
- }
13900
+ if (data instanceof Uint8Array) {
13901
+ return data;
14058
13902
  }
14059
- return result;
14060
- }
14061
-
14062
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/u8-array.js
14063
- function readU8Array(bc) {
14064
- return readU8FixedArray(bc, readUintSafe32(bc));
13903
+ if (data instanceof ArrayBuffer || data instanceof SharedArrayBuffer) {
13904
+ return new Uint8Array(data);
13905
+ }
13906
+ throw new Error("Malformed message");
14065
13907
  }
14066
- function writeU8Array(bc, x) {
14067
- writeUintSafe32(bc, x.length);
14068
- writeU8FixedArray(bc, x);
13908
+ function base64EncodeUint8Array(uint8Array) {
13909
+ let binary = "";
13910
+ for (const value of uint8Array) {
13911
+ binary += String.fromCharCode(value);
13912
+ }
13913
+ return btoa(binary);
14069
13914
  }
14070
- function readU8FixedArray(bc, len) {
14071
- return readUnsafeU8FixedArray(bc, len).slice();
13915
+ function base64EncodeArrayBuffer(arrayBuffer) {
13916
+ return base64EncodeUint8Array(new Uint8Array(arrayBuffer));
14072
13917
  }
14073
- function writeU8FixedArray(bc, x) {
14074
- const len = x.length;
14075
- if (len > 0) {
14076
- reserve(bc, len);
14077
- bc.bytes.set(x, bc.offset);
14078
- bc.offset += len;
13918
+ function isPlainObject2(value) {
13919
+ if (value === null || typeof value !== "object") {
13920
+ return false;
14079
13921
  }
13922
+ const proto = Object.getPrototypeOf(value);
13923
+ return proto === Object.prototype || proto === null;
14080
13924
  }
14081
- function readUnsafeU8FixedArray(bc, len) {
14082
- if (DEV) {
14083
- assert2(isU32(len));
13925
+ function encodeJsonCompatValue(input) {
13926
+ var _a2;
13927
+ if (input === null) {
13928
+ return input;
14084
13929
  }
14085
- check2(bc, len);
14086
- const offset = bc.offset;
14087
- bc.offset += len;
14088
- return bc.bytes.subarray(offset, offset + len);
14089
- }
14090
-
14091
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/data.js
14092
- function readData(bc) {
14093
- return readU8Array(bc).buffer;
14094
- }
14095
- function writeData(bc, x) {
14096
- writeU8Array(bc, new Uint8Array(x));
14097
- }
14098
-
14099
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/string.js
14100
- function readString(bc) {
14101
- return readFixedString(bc, readUintSafe32(bc));
14102
- }
14103
- function writeString(bc, x) {
14104
- if (x.length < TEXT_ENCODER_THRESHOLD) {
14105
- const byteLen = utf8ByteLength(x);
14106
- writeUintSafe32(bc, byteLen);
14107
- reserve(bc, byteLen);
14108
- writeUtf8Js(bc, x);
14109
- } else {
14110
- const strBytes = UTF8_ENCODER.encode(x);
14111
- writeUintSafe32(bc, strBytes.length);
14112
- writeU8FixedArray(bc, strBytes);
13930
+ if (input === void 0) {
13931
+ return [JSON_COMPAT_UNDEFINED, 0];
14113
13932
  }
14114
- }
14115
- function readFixedString(bc, byteLen) {
14116
- if (DEV) {
14117
- assert2(isU32(byteLen));
13933
+ if (typeof input === "string" || typeof input === "number" || typeof input === "boolean") {
13934
+ return input;
14118
13935
  }
14119
- if (byteLen < TEXT_DECODER_THRESHOLD) {
14120
- return readUtf8Js(bc, byteLen);
13936
+ if (typeof input === "bigint") {
13937
+ return [JSON_COMPAT_BIGINT, input.toString()];
14121
13938
  }
14122
- try {
14123
- return UTF8_DECODER.decode(readUnsafeU8FixedArray(bc, byteLen));
14124
- } catch (_cause) {
14125
- throw new BareError(bc.offset, INVALID_UTF8_STRING);
13939
+ if (input instanceof ArrayBuffer) {
13940
+ return [JSON_COMPAT_ARRAY_BUFFER, base64EncodeArrayBuffer(input)];
14126
13941
  }
14127
- }
14128
- function readUtf8Js(bc, byteLen) {
14129
- check2(bc, byteLen);
14130
- let result = "";
14131
- const bytes = bc.bytes;
14132
- let offset = bc.offset;
14133
- const upperOffset = offset + byteLen;
14134
- while (offset < upperOffset) {
14135
- let codePoint = bytes[offset++];
14136
- if (codePoint > 127) {
14137
- let malformed = true;
14138
- const byte1 = codePoint;
14139
- if (offset < upperOffset && codePoint < 224) {
14140
- const byte2 = bytes[offset++];
14141
- codePoint = (byte1 & 31) << 6 | byte2 & 63;
14142
- malformed = codePoint >> 7 === 0 || // non-canonical char
14143
- byte1 >> 5 !== 6 || // invalid tag
14144
- byte2 >> 6 !== 2;
14145
- } else if (offset + 1 < upperOffset && codePoint < 240) {
14146
- const byte2 = bytes[offset++];
14147
- const byte3 = bytes[offset++];
14148
- codePoint = (byte1 & 15) << 12 | (byte2 & 63) << 6 | byte3 & 63;
14149
- malformed = codePoint >> 11 === 0 || // non-canonical char or missing data
14150
- codePoint >> 11 === 27 || // surrogate char (0xD800 <= codePoint <= 0xDFFF)
14151
- byte1 >> 4 !== 14 || // invalid tag
14152
- byte2 >> 6 !== 2 || // invalid tag
14153
- byte3 >> 6 !== 2;
14154
- } else if (offset + 2 < upperOffset) {
14155
- const byte2 = bytes[offset++];
14156
- const byte3 = bytes[offset++];
14157
- const byte4 = bytes[offset++];
14158
- codePoint = (byte1 & 7) << 18 | (byte2 & 63) << 12 | (byte3 & 63) << 6 | byte4 & 63;
14159
- malformed = codePoint >> 16 === 0 || // non-canonical char or missing data
14160
- codePoint > 1114111 || // too large code point
14161
- byte1 >> 3 !== 30 || // invalid tag
14162
- byte2 >> 6 !== 2 || // invalid tag
14163
- byte3 >> 6 !== 2 || // invalid tag
14164
- byte4 >> 6 !== 2;
14165
- }
14166
- if (malformed) {
14167
- throw new BareError(bc.offset, INVALID_UTF8_STRING);
14168
- }
14169
- }
14170
- result += String.fromCodePoint(codePoint);
13942
+ if (input instanceof Uint8Array) {
13943
+ return [JSON_COMPAT_UINT8_ARRAY, base64EncodeUint8Array(input)];
14171
13944
  }
14172
- bc.offset = offset;
14173
- return result;
14174
- }
14175
- function writeUtf8Js(bc, s) {
14176
- const bytes = bc.bytes;
14177
- let offset = bc.offset;
14178
- let i = 0;
14179
- while (i < s.length) {
14180
- const codePoint = s.codePointAt(i++);
14181
- if (codePoint < 128) {
14182
- bytes[offset++] = codePoint;
14183
- } else {
14184
- if (codePoint < 2048) {
14185
- bytes[offset++] = 192 | codePoint >> 6;
14186
- } else {
14187
- if (codePoint < 65536) {
14188
- bytes[offset++] = 224 | codePoint >> 12;
14189
- } else {
14190
- bytes[offset++] = 240 | codePoint >> 18;
14191
- bytes[offset++] = 128 | codePoint >> 12 & 63;
14192
- i++;
14193
- }
14194
- bytes[offset++] = 128 | codePoint >> 6 & 63;
14195
- }
14196
- bytes[offset++] = 128 | codePoint & 63;
14197
- }
13945
+ if (isTypedArray(input)) {
13946
+ return input;
14198
13947
  }
14199
- bc.offset = offset;
14200
- }
14201
- function utf8ByteLength(s) {
14202
- let result = s.length;
14203
- for (let i = 0; i < s.length; i++) {
14204
- const codePoint = s.codePointAt(i);
14205
- if (codePoint > 127) {
14206
- result++;
14207
- if (codePoint > 2047) {
14208
- result++;
14209
- if (codePoint > 65535) {
14210
- i++;
14211
- }
14212
- }
14213
- }
13948
+ if (input instanceof Date || input instanceof RegExp || input instanceof Error) {
13949
+ return input;
14214
13950
  }
14215
- return result;
14216
- }
14217
- var UTF8_DECODER = /* @__PURE__ */ new TextDecoder("utf-8", { fatal: true });
14218
- var UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();
14219
-
14220
- // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/config.js
14221
- function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32 }) {
14222
- if (DEV) {
14223
- assert2(isU32(initialBufferLength), TOO_LARGE_NUMBER);
14224
- assert2(isU32(maxBufferLength), TOO_LARGE_NUMBER);
14225
- assert2(initialBufferLength <= maxBufferLength, "initialBufferLength must be lower than or equal to maxBufferLength");
13951
+ if (input instanceof Set) {
13952
+ const encoded = [...input.values()].map(
13953
+ (v) => encodeJsonCompatValue(v)
13954
+ );
13955
+ return [JSON_COMPAT_SET, encoded];
14226
13956
  }
14227
- return {
14228
- initialBufferLength,
14229
- maxBufferLength
14230
- };
14231
- }
14232
-
14233
- // ../rivetkit/dist/tsup/chunk-QTINS2PE.js
14234
- var config2 = /* @__PURE__ */ Config({});
14235
- function readWorkflowCbor(bc) {
14236
- return readData(bc);
14237
- }
14238
- function readWorkflowNameIndex(bc) {
14239
- return readU32(bc);
14240
- }
14241
- function readWorkflowLoopIterationMarker(bc) {
14242
- return {
14243
- loop: readWorkflowNameIndex(bc),
14244
- iteration: readU32(bc)
14245
- };
14246
- }
14247
- function readWorkflowPathSegment(bc) {
14248
- const offset = bc.offset;
14249
- const tag = readU8(bc);
14250
- switch (tag) {
14251
- case 0:
14252
- return { tag: "WorkflowNameIndex", val: readWorkflowNameIndex(bc) };
14253
- case 1:
14254
- return {
14255
- tag: "WorkflowLoopIterationMarker",
14256
- val: readWorkflowLoopIterationMarker(bc)
14257
- };
14258
- default: {
14259
- bc.offset = offset;
14260
- throw new BareError(offset, "invalid tag");
13957
+ if (input instanceof Map) {
13958
+ const encoded = /* @__PURE__ */ new Map();
13959
+ for (const [k, v] of input.entries()) {
13960
+ encoded.set(
13961
+ encodeJsonCompatValue(k),
13962
+ encodeJsonCompatValue(v)
13963
+ );
14261
13964
  }
13965
+ return encoded;
14262
13966
  }
14263
- }
14264
- function readWorkflowLocation(bc) {
14265
- const len = readUintSafe(bc);
14266
- if (len === 0) {
14267
- return [];
14268
- }
14269
- const result = [readWorkflowPathSegment(bc)];
14270
- for (let i = 1; i < len; i++) {
14271
- result[i] = readWorkflowPathSegment(bc);
13967
+ if (Array.isArray(input)) {
13968
+ const encoded = input.map(
13969
+ (value) => encodeJsonCompatValue(value)
13970
+ );
13971
+ if (encoded.length === 2 && typeof encoded[0] === "string" && encoded[0].startsWith("$")) {
13972
+ return [`$${encoded[0]}`, encoded[1]];
13973
+ }
13974
+ return encoded;
14272
13975
  }
14273
- return result;
14274
- }
14275
- function readWorkflowEntryStatus(bc) {
14276
- const offset = bc.offset;
14277
- const tag = readU8(bc);
14278
- switch (tag) {
14279
- case 0:
14280
- return "PENDING";
14281
- case 1:
14282
- return "RUNNING";
14283
- case 2:
14284
- return "COMPLETED";
14285
- case 3:
14286
- return "FAILED";
14287
- case 4:
14288
- return "EXHAUSTED";
14289
- default: {
14290
- bc.offset = offset;
14291
- throw new BareError(offset, "invalid tag");
13976
+ if (isPlainObject2(input)) {
13977
+ const encoded = {};
13978
+ for (const [key, value] of Object.entries(input)) {
13979
+ encoded[key] = encodeJsonCompatValue(value);
14292
13980
  }
13981
+ return encoded;
14293
13982
  }
13983
+ const typeName = typeof input === "object" && input !== null ? ((_a2 = input.constructor) == null ? void 0 : _a2.name) ?? typeof input : typeof input;
13984
+ throw new TypeError(`Value of type "${typeName}" is not CBOR serializable`);
14294
13985
  }
14295
- function readWorkflowSleepState(bc) {
14296
- const offset = bc.offset;
14297
- const tag = readU8(bc);
14298
- switch (tag) {
14299
- case 0:
14300
- return "PENDING";
14301
- case 1:
14302
- return "COMPLETED";
14303
- case 2:
14304
- return "INTERRUPTED";
14305
- default: {
14306
- bc.offset = offset;
14307
- throw new BareError(offset, "invalid tag");
13986
+ function reviveJsonCompatValue(input, options = {}) {
13987
+ if (typeof input === "bigint") {
13988
+ if (options.coerceSafeIntegerBigInts && input >= BigInt(Number.MIN_SAFE_INTEGER) && input <= BigInt(Number.MAX_SAFE_INTEGER)) {
13989
+ return Number(input);
14308
13990
  }
13991
+ return input;
14309
13992
  }
14310
- }
14311
- function readWorkflowBranchStatusType(bc) {
14312
- const offset = bc.offset;
14313
- const tag = readU8(bc);
14314
- switch (tag) {
14315
- case 0:
14316
- return "PENDING";
14317
- case 1:
14318
- return "RUNNING";
14319
- case 2:
14320
- return "COMPLETED";
14321
- case 3:
14322
- return "FAILED";
14323
- case 4:
14324
- return "CANCELLED";
14325
- default: {
14326
- bc.offset = offset;
14327
- throw new BareError(offset, "invalid tag");
13993
+ if (input instanceof Map) {
13994
+ const revived = /* @__PURE__ */ new Map();
13995
+ for (const [k, v] of input.entries()) {
13996
+ revived.set(
13997
+ reviveJsonCompatValue(k, options),
13998
+ reviveJsonCompatValue(v, options)
13999
+ );
14000
+ }
14001
+ return revived;
14002
+ }
14003
+ if (Array.isArray(input)) {
14004
+ if (input.length === 2 && typeof input[0] === "string" && input[0].startsWith("$")) {
14005
+ if (input[0] === JSON_COMPAT_BIGINT) {
14006
+ return BigInt(input[1]);
14007
+ }
14008
+ if (input[0] === JSON_COMPAT_ARRAY_BUFFER) {
14009
+ return base64DecodeToArrayBuffer(input[1]);
14010
+ }
14011
+ if (input[0] === JSON_COMPAT_UINT8_ARRAY) {
14012
+ return base64DecodeToUint8Array(input[1]);
14013
+ }
14014
+ if (input[0] === JSON_COMPAT_UNDEFINED) {
14015
+ return void 0;
14016
+ }
14017
+ if (input[0] === JSON_COMPAT_SET) {
14018
+ const items = input[1].map(
14019
+ (v) => reviveJsonCompatValue(v, options)
14020
+ );
14021
+ return new Set(items);
14022
+ }
14023
+ if (input[0].startsWith("$$")) {
14024
+ return [
14025
+ input[0].substring(1),
14026
+ reviveJsonCompatValue(input[1], options)
14027
+ ];
14028
+ }
14029
+ throw new Error(
14030
+ `Unknown JSON encoding type: ${input[0]}. This may indicate corrupted data or a version mismatch.`
14031
+ );
14328
14032
  }
14033
+ return input.map((value) => reviveJsonCompatValue(value, options));
14034
+ }
14035
+ if (isPlainObject2(input)) {
14036
+ const decoded = {};
14037
+ for (const [key, value] of Object.entries(input)) {
14038
+ decoded[key] = reviveJsonCompatValue(value, options);
14039
+ }
14040
+ return decoded;
14329
14041
  }
14042
+ return input;
14330
14043
  }
14331
- function read0(bc) {
14332
- return readBool(bc) ? readWorkflowCbor(bc) : null;
14044
+ function base64DecodeToUint8Array(base643) {
14045
+ if (typeof Buffer !== "undefined") {
14046
+ return new Uint8Array(Buffer.from(base643, "base64"));
14047
+ }
14048
+ const binary = atob(base643);
14049
+ const bytes = new Uint8Array(binary.length);
14050
+ for (let i = 0; i < binary.length; i++) {
14051
+ bytes[i] = binary.charCodeAt(i);
14052
+ }
14053
+ return bytes;
14333
14054
  }
14334
- function read1(bc) {
14335
- return readBool(bc) ? readString(bc) : null;
14055
+ function base64DecodeToArrayBuffer(base643) {
14056
+ return base64DecodeToUint8Array(base643).buffer;
14336
14057
  }
14337
- function readWorkflowStepEntry(bc) {
14338
- return {
14339
- output: read0(bc),
14340
- error: read1(bc)
14341
- };
14058
+ function jsonStringifyCompat(input, space) {
14059
+ return JSON.stringify(
14060
+ input,
14061
+ (_key, value) => {
14062
+ if (typeof value === "bigint") {
14063
+ return [JSON_COMPAT_BIGINT, value.toString()];
14064
+ }
14065
+ if (value instanceof ArrayBuffer) {
14066
+ return [
14067
+ JSON_COMPAT_ARRAY_BUFFER,
14068
+ base64EncodeArrayBuffer(value)
14069
+ ];
14070
+ }
14071
+ if (value instanceof Uint8Array) {
14072
+ return [JSON_COMPAT_UINT8_ARRAY, base64EncodeUint8Array(value)];
14073
+ }
14074
+ if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && value[0].startsWith("$")) {
14075
+ return [`$${value[0]}`, value[1]];
14076
+ }
14077
+ return value;
14078
+ },
14079
+ space
14080
+ );
14342
14081
  }
14343
- function readWorkflowLoopEntry(bc) {
14344
- return {
14345
- state: readWorkflowCbor(bc),
14346
- iteration: readU32(bc),
14347
- output: read0(bc)
14348
- };
14082
+ function jsonParseCompat(input) {
14083
+ return reviveJsonCompatValue(JSON.parse(input));
14349
14084
  }
14350
- function readWorkflowSleepEntry(bc) {
14351
- return {
14352
- deadline: readU64(bc),
14353
- state: readWorkflowSleepState(bc)
14354
- };
14085
+ var VERSION = package_default.version;
14086
+ var _userAgent;
14087
+ function httpUserAgent() {
14088
+ if (_userAgent !== void 0) {
14089
+ return _userAgent;
14090
+ }
14091
+ let userAgent = `RivetKit/${VERSION}`;
14092
+ const navigatorObj = typeof navigator !== "undefined" ? navigator : void 0;
14093
+ if (navigatorObj == null ? void 0 : navigatorObj.userAgent) userAgent += ` ${navigatorObj.userAgent}`;
14094
+ _userAgent = userAgent;
14095
+ return userAgent;
14355
14096
  }
14356
- function readWorkflowMessageEntry(bc) {
14357
- return {
14358
- name: readString(bc),
14359
- messageData: readWorkflowCbor(bc)
14360
- };
14097
+ function getEnvUniversal(key) {
14098
+ if (typeof Deno !== "undefined") {
14099
+ return Deno.env.get(key);
14100
+ } else if (typeof process !== "undefined") {
14101
+ return process.env[key];
14102
+ }
14361
14103
  }
14362
- function readWorkflowRollbackCheckpointEntry(bc) {
14363
- return {
14364
- name: readString(bc)
14365
- };
14104
+ function toUint8Array(data) {
14105
+ if (data instanceof Uint8Array) {
14106
+ return data;
14107
+ } else if (data instanceof ArrayBuffer) {
14108
+ return new Uint8Array(data);
14109
+ } else if (ArrayBuffer.isView(data)) {
14110
+ return new Uint8Array(
14111
+ data.buffer.slice(
14112
+ data.byteOffset,
14113
+ data.byteOffset + data.byteLength
14114
+ )
14115
+ );
14116
+ } else {
14117
+ throw new TypeError("Input must be ArrayBuffer or ArrayBufferView");
14118
+ }
14366
14119
  }
14367
- function readWorkflowBranchStatus(bc) {
14368
- return {
14369
- status: readWorkflowBranchStatusType(bc),
14370
- output: read0(bc),
14371
- error: read1(bc)
14372
- };
14120
+ function promiseWithResolvers(onReject) {
14121
+ let resolve;
14122
+ let reject;
14123
+ const promise2 = new Promise((res, rej) => {
14124
+ resolve = res;
14125
+ reject = rej;
14126
+ });
14127
+ promise2.catch(onReject);
14128
+ return { promise: promise2, resolve, reject };
14373
14129
  }
14374
- function read2(bc) {
14375
- const len = readUintSafe(bc);
14376
- const result = /* @__PURE__ */ new Map();
14377
- for (let i = 0; i < len; i++) {
14378
- const offset = bc.offset;
14379
- const key = readString(bc);
14380
- if (result.has(key)) {
14381
- bc.offset = offset;
14382
- throw new BareError(offset, "duplicated key");
14130
+ function bufferToArrayBuffer(buf) {
14131
+ return buf.buffer.slice(
14132
+ buf.byteOffset,
14133
+ buf.byteOffset + buf.byteLength
14134
+ );
14135
+ }
14136
+ function combineUrlPath(endpoint, path2, queryParams) {
14137
+ const baseUrl = new URL(endpoint);
14138
+ const pathParts = path2.split("?");
14139
+ const pathOnly = pathParts[0];
14140
+ const existingQuery = pathParts[1] || "";
14141
+ const basePath = baseUrl.pathname.replace(/\/$/, "");
14142
+ const cleanPath = pathOnly.startsWith("/") ? pathOnly : `/${pathOnly}`;
14143
+ const fullPath = (basePath + cleanPath).replace(/\/\//g, "/");
14144
+ const queryParts = [];
14145
+ if (existingQuery) {
14146
+ queryParts.push(existingQuery);
14147
+ }
14148
+ if (queryParams) {
14149
+ for (const [key, value] of Object.entries(queryParams)) {
14150
+ if (value !== void 0) {
14151
+ queryParts.push(
14152
+ `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
14153
+ );
14154
+ }
14383
14155
  }
14384
- result.set(key, readWorkflowBranchStatus(bc));
14385
14156
  }
14386
- return result;
14157
+ const fullQuery = queryParts.length > 0 ? `?${queryParts.join("&")}` : "";
14158
+ return `${baseUrl.protocol}//${baseUrl.host}${fullPath}${fullQuery}`;
14387
14159
  }
14388
- function readWorkflowJoinEntry(bc) {
14389
- return {
14390
- branches: read2(bc)
14391
- };
14160
+
14161
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/imports/dev.node.js
14162
+ var DEV = process.env.NODE_ENV === "development";
14163
+
14164
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/assert.js
14165
+ var V8Error = Error;
14166
+ function assert2(test, message = "") {
14167
+ if (!test) {
14168
+ const e = new AssertionError(message);
14169
+ V8Error.captureStackTrace?.(e, assert2);
14170
+ throw e;
14171
+ }
14392
14172
  }
14393
- function readWorkflowRaceEntry(bc) {
14394
- return {
14395
- winner: read1(bc),
14396
- branches: read2(bc)
14397
- };
14173
+ var AssertionError = class extends Error {
14174
+ constructor() {
14175
+ super(...arguments);
14176
+ this.name = "AssertionError";
14177
+ }
14178
+ };
14179
+
14180
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/validator.js
14181
+ function isU8(val) {
14182
+ return val === (val & 255);
14398
14183
  }
14399
- function readWorkflowRemovedEntry(bc) {
14400
- return {
14401
- originalType: readString(bc),
14402
- originalName: read1(bc)
14403
- };
14184
+ function isU32(val) {
14185
+ return val === val >>> 0;
14404
14186
  }
14405
- function readWorkflowVersionCheckEntry(bc) {
14406
- return {
14407
- resolved: readU32(bc),
14408
- latest: readU32(bc)
14409
- };
14187
+ function isU64(val) {
14188
+ return val === BigInt.asUintN(64, val);
14410
14189
  }
14411
- function readWorkflowEntryKind(bc) {
14412
- const offset = bc.offset;
14413
- const tag = readU8(bc);
14414
- switch (tag) {
14415
- case 0:
14416
- return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
14417
- case 1:
14418
- return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
14419
- case 2:
14420
- return {
14421
- tag: "WorkflowSleepEntry",
14422
- val: readWorkflowSleepEntry(bc)
14423
- };
14424
- case 3:
14425
- return {
14426
- tag: "WorkflowMessageEntry",
14427
- val: readWorkflowMessageEntry(bc)
14428
- };
14429
- case 4:
14430
- return {
14431
- tag: "WorkflowRollbackCheckpointEntry",
14432
- val: readWorkflowRollbackCheckpointEntry(bc)
14433
- };
14434
- case 5:
14435
- return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
14436
- case 6:
14437
- return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
14438
- case 7:
14439
- return {
14440
- tag: "WorkflowRemovedEntry",
14441
- val: readWorkflowRemovedEntry(bc)
14442
- };
14443
- case 8:
14444
- return {
14445
- tag: "WorkflowVersionCheckEntry",
14446
- val: readWorkflowVersionCheckEntry(bc)
14447
- };
14448
- default: {
14449
- bc.offset = offset;
14450
- throw new BareError(offset, "invalid tag");
14190
+
14191
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/util/constants.js
14192
+ var TEXT_DECODER_THRESHOLD = 256;
14193
+ var TEXT_ENCODER_THRESHOLD = 256;
14194
+ var INT_SAFE_MAX_BYTE_COUNT = 8;
14195
+ var UINT_MAX_BYTE_COUNT = 10;
14196
+ var UINT_SAFE32_MAX_BYTE_COUNT = 5;
14197
+ var INVALID_UTF8_STRING = "invalid UTF-8 string";
14198
+ var NON_CANONICAL_REPRESENTATION = "must be canonical";
14199
+ var TOO_LARGE_BUFFER = "too large buffer";
14200
+ var TOO_LARGE_NUMBER = "too large number";
14201
+
14202
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/bare-error.js
14203
+ var BareError = class extends Error {
14204
+ constructor(offset, issue2, opts) {
14205
+ super(`(byte:${offset}) ${issue2}`);
14206
+ this.name = "BareError";
14207
+ this.issue = issue2;
14208
+ this.offset = offset;
14209
+ this.cause = opts?.cause;
14210
+ }
14211
+ };
14212
+
14213
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/byte-cursor.js
14214
+ var ByteCursor = class {
14215
+ /**
14216
+ * @throws {BareError} Buffer exceeds `config.maxBufferLength`
14217
+ */
14218
+ constructor(bytes, config3) {
14219
+ this.offset = 0;
14220
+ if (bytes.length > config3.maxBufferLength) {
14221
+ throw new BareError(0, TOO_LARGE_BUFFER);
14451
14222
  }
14223
+ this.bytes = bytes;
14224
+ this.config = config3;
14225
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
14226
+ }
14227
+ };
14228
+ function check2(bc, min) {
14229
+ if (DEV) {
14230
+ assert2(isU32(min));
14231
+ }
14232
+ if (bc.offset + min > bc.bytes.length) {
14233
+ throw new BareError(bc.offset, "missing bytes");
14452
14234
  }
14453
14235
  }
14454
- function readWorkflowEntry(bc) {
14455
- return {
14456
- id: readString(bc),
14457
- location: readWorkflowLocation(bc),
14458
- kind: readWorkflowEntryKind(bc)
14459
- };
14236
+ function reserve(bc, min) {
14237
+ if (DEV) {
14238
+ assert2(isU32(min));
14239
+ }
14240
+ const minLen = bc.offset + min | 0;
14241
+ if (minLen > bc.bytes.length) {
14242
+ grow(bc, minLen);
14243
+ }
14460
14244
  }
14461
- function read3(bc) {
14462
- return readBool(bc) ? readU64(bc) : null;
14245
+ function grow(bc, minLen) {
14246
+ if (minLen > bc.config.maxBufferLength) {
14247
+ throw new BareError(0, TOO_LARGE_BUFFER);
14248
+ }
14249
+ const buffer = bc.bytes.buffer;
14250
+ let newBytes;
14251
+ if (isEs2024ArrayBufferLike(buffer) && // Make sure that the view covers the end of the buffer.
14252
+ // If it is not the case, this indicates that the user don't want
14253
+ // to override the trailing bytes.
14254
+ bc.bytes.byteOffset + bc.bytes.byteLength === buffer.byteLength && bc.bytes.byteLength + minLen <= buffer.maxByteLength) {
14255
+ const newLen = Math.min(minLen << 1, bc.config.maxBufferLength, buffer.maxByteLength);
14256
+ if (buffer instanceof ArrayBuffer) {
14257
+ buffer.resize(newLen);
14258
+ } else {
14259
+ buffer.grow(newLen);
14260
+ }
14261
+ newBytes = new Uint8Array(buffer, bc.bytes.byteOffset, newLen);
14262
+ } else {
14263
+ const newLen = Math.min(minLen << 1, bc.config.maxBufferLength);
14264
+ newBytes = new Uint8Array(newLen);
14265
+ newBytes.set(bc.bytes);
14266
+ }
14267
+ bc.bytes = newBytes;
14268
+ bc.view = new DataView(newBytes.buffer);
14463
14269
  }
14464
- function readWorkflowEntryMetadata(bc) {
14465
- return {
14466
- status: readWorkflowEntryStatus(bc),
14467
- error: read1(bc),
14468
- attempts: readU32(bc),
14469
- lastAttemptAt: readU64(bc),
14470
- createdAt: readU64(bc),
14471
- completedAt: read3(bc),
14472
- rollbackCompletedAt: read3(bc),
14473
- rollbackError: read1(bc)
14474
- };
14270
+ function isEs2024ArrayBufferLike(buffer) {
14271
+ return "maxByteLength" in buffer;
14475
14272
  }
14476
- function read4(bc) {
14477
- const len = readUintSafe(bc);
14478
- if (len === 0) {
14479
- return [];
14273
+
14274
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/fixed-primitive.js
14275
+ function readBool(bc) {
14276
+ const val = readU8(bc);
14277
+ if (val > 1) {
14278
+ bc.offset--;
14279
+ throw new BareError(bc.offset, "a bool must be equal to 0 or 1");
14480
14280
  }
14481
- const result = [readString(bc)];
14482
- for (let i = 1; i < len; i++) {
14483
- result[i] = readString(bc);
14281
+ return val > 0;
14282
+ }
14283
+ function writeBool(bc, x) {
14284
+ writeU8(bc, x ? 1 : 0);
14285
+ }
14286
+ function readU8(bc) {
14287
+ check2(bc, 1);
14288
+ return bc.bytes[bc.offset++];
14289
+ }
14290
+ function writeU8(bc, x) {
14291
+ if (DEV) {
14292
+ assert2(isU8(x), TOO_LARGE_NUMBER);
14484
14293
  }
14294
+ reserve(bc, 1);
14295
+ bc.bytes[bc.offset++] = x;
14296
+ }
14297
+ function readU32(bc) {
14298
+ check2(bc, 4);
14299
+ const result = bc.view.getUint32(bc.offset, true);
14300
+ bc.offset += 4;
14485
14301
  return result;
14486
14302
  }
14487
- function read5(bc) {
14488
- const len = readUintSafe(bc);
14489
- if (len === 0) {
14490
- return [];
14491
- }
14492
- const result = [readWorkflowEntry(bc)];
14493
- for (let i = 1; i < len; i++) {
14494
- result[i] = readWorkflowEntry(bc);
14495
- }
14303
+ function readU64(bc) {
14304
+ check2(bc, 8);
14305
+ const result = bc.view.getBigUint64(bc.offset, true);
14306
+ bc.offset += 8;
14496
14307
  return result;
14497
14308
  }
14498
- function read6(bc) {
14499
- const len = readUintSafe(bc);
14500
- const result = /* @__PURE__ */ new Map();
14501
- for (let i = 0; i < len; i++) {
14502
- const offset = bc.offset;
14503
- const key = readString(bc);
14504
- if (result.has(key)) {
14505
- bc.offset = offset;
14506
- throw new BareError(offset, "duplicated key");
14309
+ function writeU64(bc, x) {
14310
+ if (DEV) {
14311
+ assert2(isU64(x), TOO_LARGE_NUMBER);
14312
+ }
14313
+ reserve(bc, 8);
14314
+ bc.view.setBigUint64(bc.offset, x, true);
14315
+ bc.offset += 8;
14316
+ }
14317
+
14318
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/uint.js
14319
+ function readUint(bc) {
14320
+ let low = readU8(bc);
14321
+ if (low >= 128) {
14322
+ low &= 127;
14323
+ let shiftMul = 128;
14324
+ let byteCount = 1;
14325
+ let byte;
14326
+ do {
14327
+ byte = readU8(bc);
14328
+ low += (byte & 127) * shiftMul;
14329
+ shiftMul *= /* 2**7 */
14330
+ 128;
14331
+ byteCount++;
14332
+ } while (byte >= 128 && byteCount < 7);
14333
+ let height = 0;
14334
+ shiftMul = 1;
14335
+ while (byte >= 128 && byteCount < UINT_MAX_BYTE_COUNT) {
14336
+ byte = readU8(bc);
14337
+ height += (byte & 127) * shiftMul;
14338
+ shiftMul *= /* 2**7 */
14339
+ 128;
14340
+ byteCount++;
14507
14341
  }
14508
- result.set(key, readWorkflowEntryMetadata(bc));
14342
+ if (byte === 0 || byteCount === UINT_MAX_BYTE_COUNT && byte > 1) {
14343
+ bc.offset -= byteCount;
14344
+ throw new BareError(bc.offset, NON_CANONICAL_REPRESENTATION);
14345
+ }
14346
+ return BigInt(low) + (BigInt(height) << BigInt(7 * 7));
14509
14347
  }
14510
- return result;
14348
+ return BigInt(low);
14511
14349
  }
14512
- function readWorkflowHistory(bc) {
14513
- return {
14514
- nameRegistry: read4(bc),
14515
- entries: read5(bc),
14516
- entryMetadata: read6(bc)
14517
- };
14350
+ function writeUint(bc, x) {
14351
+ const truncated = BigInt.asUintN(64, x);
14352
+ if (DEV) {
14353
+ assert2(truncated === x, TOO_LARGE_NUMBER);
14354
+ }
14355
+ writeUintTruncated(bc, truncated);
14518
14356
  }
14519
- function decodeWorkflowHistory(bytes) {
14520
- const bc = new ByteCursor(bytes, config2);
14521
- const result = readWorkflowHistory(bc);
14522
- if (bc.offset < bc.view.byteLength) {
14523
- throw new BareError(bc.offset, "remaining bytes");
14357
+ function writeUintTruncated(bc, x) {
14358
+ let tmp = Number(BigInt.asUintN(7 * 7, x));
14359
+ let rest = Number(x >> BigInt(7 * 7));
14360
+ let byteCount = 0;
14361
+ while (tmp >= 128 || rest > 0) {
14362
+ writeU8(bc, 128 | tmp & 127);
14363
+ tmp = Math.floor(tmp / /* 2**7 */
14364
+ 128);
14365
+ byteCount++;
14366
+ if (byteCount === 7) {
14367
+ tmp = rest;
14368
+ rest = 0;
14369
+ }
14524
14370
  }
14525
- return result;
14371
+ writeU8(bc, tmp);
14526
14372
  }
14527
- function decodeWorkflowHistoryTransport(data) {
14528
- return decodeWorkflowHistory(toUint8Array(data));
14373
+ function readUintSafe32(bc) {
14374
+ let result = readU8(bc);
14375
+ if (result >= 128) {
14376
+ result &= 127;
14377
+ let shift = 7;
14378
+ let byteCount = 1;
14379
+ let byte;
14380
+ do {
14381
+ byte = readU8(bc);
14382
+ result += (byte & 127) << shift >>> 0;
14383
+ shift += 7;
14384
+ byteCount++;
14385
+ } while (byte >= 128 && byteCount < UINT_SAFE32_MAX_BYTE_COUNT);
14386
+ if (byte === 0) {
14387
+ bc.offset -= byteCount - 1;
14388
+ throw new BareError(bc.offset - byteCount + 1, NON_CANONICAL_REPRESENTATION);
14389
+ }
14390
+ if (byteCount === UINT_SAFE32_MAX_BYTE_COUNT && byte > 15) {
14391
+ bc.offset -= byteCount - 1;
14392
+ throw new BareError(bc.offset, TOO_LARGE_NUMBER);
14393
+ }
14394
+ }
14395
+ return result;
14529
14396
  }
14530
-
14531
- // ../rivetkit/dist/tsup/chunk-X3LBDNEH.js
14532
- var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
14533
- var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
14534
- "rivetkit.actor_context_internal"
14535
- );
14536
- var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
14537
- var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
14538
- var zFunction = () => external_exports.custom((val) => typeof val === "function");
14539
- var WorkflowInspectorConfigSchema = external_exports.object({
14540
- getHistory: zFunction(),
14541
- onHistoryUpdated: zFunction().optional(),
14542
- replayFromStep: zFunction().optional()
14543
- });
14544
- var RunInspectorConfigSchema = external_exports.object({
14545
- workflow: WorkflowInspectorConfigSchema.optional()
14546
- }).optional();
14547
- var BUILTIN_INSPECTOR_TAB_IDS = [
14548
- "workflow",
14549
- "database",
14550
- "state",
14551
- "queue",
14552
- "connections",
14553
- "console"
14554
- ];
14555
- var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
14556
- var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
14557
- var CustomInspectorTabEntrySchema = external_exports.object({
14558
- id: external_exports.string().regex(
14559
- CUSTOM_INSPECTOR_TAB_ID_RE,
14560
- "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
14561
- ),
14562
- label: external_exports.string().min(1),
14563
- source: external_exports.string().min(1),
14564
- /**
14565
- * Optional icon id. The dashboard maps strings to glyphs (see its
14566
- * icon registry); unknown ids fall back to a generic icon.
14567
- */
14568
- icon: external_exports.string().min(1).optional(),
14569
- hidden: external_exports.literal(false).optional()
14570
- }).strict();
14571
- var HideInspectorTabEntrySchema = external_exports.object({
14572
- id: BuiltinInspectorTabIdSchema,
14573
- hidden: external_exports.literal(true)
14574
- }).strict();
14575
- var InspectorTabEntrySchema = external_exports.union([
14576
- CustomInspectorTabEntrySchema,
14577
- HideInspectorTabEntrySchema
14578
- ]);
14579
- var ActorInspectorConfigSchema = external_exports.object({
14580
- tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
14581
- }).strict().refine(
14582
- (data) => {
14583
- const ids = data.tabs.map((t) => t.id);
14584
- return new Set(ids).size === ids.length;
14585
- },
14586
- { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
14587
- ).refine(
14588
- (data) => {
14589
- const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
14590
- return data.tabs.every(
14591
- (t) => t.hidden === true || !builtinSet.has(t.id)
14397
+ function writeUintSafe32(bc, x) {
14398
+ if (DEV) {
14399
+ assert2(isU32(x), TOO_LARGE_NUMBER);
14400
+ }
14401
+ let zigZag = x >>> 0;
14402
+ while (zigZag >= 128) {
14403
+ writeU8(bc, 128 | zigZag & 127);
14404
+ zigZag >>>= 7;
14405
+ }
14406
+ writeU8(bc, zigZag);
14407
+ }
14408
+ function readUintSafe(bc) {
14409
+ let result = readU8(bc);
14410
+ if (result >= 128) {
14411
+ result &= 127;
14412
+ let shiftMul = (
14413
+ /* 2**7 */
14414
+ 128
14592
14415
  );
14593
- },
14594
- {
14595
- message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
14596
- path: ["tabs"]
14416
+ let byteCount = 1;
14417
+ let byte;
14418
+ do {
14419
+ byte = readU8(bc);
14420
+ result += (byte & 127) * shiftMul;
14421
+ shiftMul *= /* 2**7 */
14422
+ 128;
14423
+ byteCount++;
14424
+ } while (byte >= 128 && byteCount < INT_SAFE_MAX_BYTE_COUNT);
14425
+ if (byte === 0) {
14426
+ bc.offset -= byteCount - 1;
14427
+ throw new BareError(bc.offset - byteCount + 1, NON_CANONICAL_REPRESENTATION);
14428
+ }
14429
+ if (byteCount === INT_SAFE_MAX_BYTE_COUNT && byte > 15) {
14430
+ bc.offset -= byteCount - 1;
14431
+ throw new BareError(bc.offset, TOO_LARGE_NUMBER);
14432
+ }
14597
14433
  }
14598
- );
14599
- var RunConfigSchema = external_exports.object({
14600
- /** Display name for the actor in the Inspector UI. */
14601
- name: external_exports.string().optional(),
14602
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
14603
- icon: external_exports.string().optional(),
14604
- /** The run handler function. */
14605
- run: zFunction(),
14606
- /** Inspector integration for long-running run handlers. */
14607
- inspector: RunInspectorConfigSchema.optional()
14608
- });
14609
- var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for(
14610
- "rivetkit.run_function_config"
14611
- );
14612
- var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
14613
- function getRunFunction(run) {
14614
- if (!run) return void 0;
14615
- if (typeof run === "function") return run;
14616
- return run.run;
14434
+ return result;
14617
14435
  }
14618
- function getRunMetadata(run) {
14619
- if (!run) return {};
14620
- if (typeof run === "function") {
14621
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
14622
- if (!config3) return {};
14623
- return { name: config3.name, icon: config3.icon };
14436
+
14437
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/u8-array.js
14438
+ function readU8Array(bc) {
14439
+ return readU8FixedArray(bc, readUintSafe32(bc));
14440
+ }
14441
+ function writeU8Array(bc, x) {
14442
+ writeUintSafe32(bc, x.length);
14443
+ writeU8FixedArray(bc, x);
14444
+ }
14445
+ function readU8FixedArray(bc, len) {
14446
+ return readUnsafeU8FixedArray(bc, len).slice();
14447
+ }
14448
+ function writeU8FixedArray(bc, x) {
14449
+ const len = x.length;
14450
+ if (len > 0) {
14451
+ reserve(bc, len);
14452
+ bc.bytes.set(x, bc.offset);
14453
+ bc.offset += len;
14624
14454
  }
14625
- return { name: run.name, icon: run.icon };
14626
14455
  }
14627
- function getRunInspectorConfig(run, actor2) {
14628
- if (!run) return void 0;
14629
- if (typeof run === "function") {
14630
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
14631
- return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
14456
+ function readUnsafeU8FixedArray(bc, len) {
14457
+ if (DEV) {
14458
+ assert2(isU32(len));
14632
14459
  }
14633
- return run.inspector;
14460
+ check2(bc, len);
14461
+ const offset = bc.offset;
14462
+ bc.offset += len;
14463
+ return bc.bytes.subarray(offset, offset + len);
14634
14464
  }
14635
- function disposeRunInspector(run, actorId) {
14636
- var _a2;
14637
- if (!run || typeof run !== "function") {
14638
- return;
14465
+
14466
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/data.js
14467
+ function readData(bc) {
14468
+ return readU8Array(bc).buffer;
14469
+ }
14470
+ function writeData(bc, x) {
14471
+ writeU8Array(bc, new Uint8Array(x));
14472
+ }
14473
+
14474
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/codec/string.js
14475
+ function readString(bc) {
14476
+ return readFixedString(bc, readUintSafe32(bc));
14477
+ }
14478
+ function writeString(bc, x) {
14479
+ if (x.length < TEXT_ENCODER_THRESHOLD) {
14480
+ const byteLen = utf8ByteLength(x);
14481
+ writeUintSafe32(bc, byteLen);
14482
+ reserve(bc, byteLen);
14483
+ writeUtf8Js(bc, x);
14484
+ } else {
14485
+ const strBytes = UTF8_ENCODER.encode(x);
14486
+ writeUintSafe32(bc, strBytes.length);
14487
+ writeU8FixedArray(bc, strBytes);
14639
14488
  }
14640
- const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
14641
- (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
14642
14489
  }
14643
- var GlobalActorOptionsBaseSchema = external_exports.object({
14644
- /** Display name for the actor in the Inspector UI. */
14645
- name: external_exports.string().optional(),
14646
- /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
14647
- icon: external_exports.string().optional(),
14648
- /** Enables the experimental Actor Runtime Socket for this actor. */
14649
- enableActorRuntimeSocket: external_exports.boolean().default(false),
14650
- /**
14651
- * Can hibernate WebSockets for onWebSocket.
14652
- *
14653
- * WebSockets using actions/events are hibernatable by default.
14654
- *
14655
- * @experimental
14656
- **/
14657
- canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
14658
- }).strict();
14659
- var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
14660
- () => ({})
14661
- );
14662
- var InstanceActorOptionsBaseSchema = external_exports.object({
14663
- createVarsTimeout: external_exports.number().positive().default(5e3),
14664
- createConnStateTimeout: external_exports.number().positive().default(5e3),
14665
- onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
14666
- onConnectTimeout: external_exports.number().positive().default(5e3),
14667
- onMigrateTimeout: external_exports.number().positive().default(3e4),
14668
- sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
14669
- /** @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. */
14670
- onDestroyTimeout: external_exports.number().positive().optional(),
14671
- /** @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. */
14672
- waitUntilTimeout: external_exports.number().positive().optional(),
14673
- stateSaveInterval: external_exports.number().positive().default(1e3),
14674
- actionTimeout: external_exports.number().positive().default(6e4),
14675
- connectionLivenessTimeout: external_exports.number().positive().default(2500),
14676
- connectionLivenessInterval: external_exports.number().positive().default(5e3),
14677
- /** @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. */
14678
- noSleep: external_exports.boolean().default(false),
14679
- sleepTimeout: external_exports.number().positive().default(3e4),
14680
- maxQueueSize: external_exports.number().positive().default(1e3),
14681
- maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
14682
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
14683
- preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
14684
- /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
14685
- preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
14686
- }).strict();
14687
- var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
14688
- var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
14689
- InstanceActorOptionsBaseSchema.shape
14690
- ).strict().prefault(() => ({}));
14691
- var ActorConfigSchema = external_exports.object({
14692
- onCreate: zFunction().optional(),
14693
- onDestroy: zFunction().optional(),
14694
- onMigrate: zFunction().optional(),
14695
- onWake: zFunction().optional(),
14696
- onSleep: zFunction().optional(),
14697
- run: zRunHandler,
14698
- onStateChange: zFunction().optional(),
14699
- onBeforeConnect: zFunction().optional(),
14700
- onConnect: zFunction().optional(),
14701
- onDisconnect: zFunction().optional(),
14702
- onBeforeActionResponse: zFunction().optional(),
14703
- onRequest: zFunction().optional(),
14704
- onWebSocket: zFunction().optional(),
14705
- actions: external_exports.record(external_exports.string(), zFunction()).default(() => ({})),
14706
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
14707
- connParamsSchema: external_exports.any().optional(),
14708
- events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
14709
- queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
14710
- state: external_exports.any().optional(),
14711
- createState: zFunction().optional(),
14712
- connState: external_exports.any().optional(),
14713
- createConnState: zFunction().optional(),
14714
- vars: external_exports.any().optional(),
14715
- db: external_exports.any().optional(),
14716
- createVars: zFunction().optional(),
14717
- options: ActorOptionsSchema,
14718
- inspector: ActorInspectorConfigSchema.optional()
14719
- }).strict().refine(
14720
- (data) => !(data.state !== void 0 && data.createState !== void 0),
14721
- {
14722
- message: "Cannot define both 'state' and 'createState'",
14723
- path: ["state"]
14724
- }
14725
- ).refine(
14726
- (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
14727
- {
14728
- message: "Cannot define both 'connState' and 'createConnState'",
14729
- path: ["connState"]
14490
+ function readFixedString(bc, byteLen) {
14491
+ if (DEV) {
14492
+ assert2(isU32(byteLen));
14730
14493
  }
14731
- ).refine(
14732
- (data) => !(data.vars !== void 0 && data.createVars !== void 0),
14733
- {
14734
- message: "Cannot define both 'vars' and 'createVars'",
14735
- path: ["vars"]
14494
+ if (byteLen < TEXT_DECODER_THRESHOLD) {
14495
+ return readUtf8Js(bc, byteLen);
14736
14496
  }
14737
- );
14738
- var DocActorOptionsSchema = external_exports.object({
14739
- name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
14740
- icon: external_exports.string().optional().describe(
14741
- "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
14742
- ),
14743
- enableActorRuntimeSocket: external_exports.boolean().optional().describe(
14744
- "Enables the experimental Actor Runtime Socket for this actor. Default: false"
14745
- ),
14746
- createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
14747
- createConnStateTimeout: external_exports.number().optional().describe(
14748
- "Timeout in ms for createConnState handler. Default: 5000"
14749
- ),
14750
- onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
14751
- onBeforeConnectTimeout: external_exports.number().optional().describe(
14752
- "Timeout in ms for onBeforeConnect handler. Default: 5000"
14753
- ),
14754
- onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
14755
- sleepGracePeriod: external_exports.number().optional().describe(
14756
- `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}.`
14757
- ),
14758
- onDestroyTimeout: external_exports.number().optional().describe(
14759
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
14760
- ),
14761
- waitUntilTimeout: external_exports.number().optional().describe(
14762
- "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
14763
- ),
14764
- stateSaveInterval: external_exports.number().optional().describe(
14765
- "Interval in ms between automatic state saves. Default: 1000"
14766
- ),
14767
- actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
14768
- connectionLivenessTimeout: external_exports.number().optional().describe(
14769
- "Timeout in ms for connection liveness checks. Default: 2500"
14770
- ),
14771
- connectionLivenessInterval: external_exports.number().optional().describe(
14772
- "Interval in ms between connection liveness checks. Default: 5000"
14773
- ),
14774
- noSleep: external_exports.boolean().optional().describe(
14775
- "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
14776
- ),
14777
- sleepTimeout: external_exports.number().optional().describe(
14778
- "Time in ms of inactivity before the actor sleeps. Default: 30000"
14779
- ),
14780
- maxQueueSize: external_exports.number().optional().describe(
14781
- "Maximum number of queue messages before rejecting new messages. Default: 1000"
14782
- ),
14783
- maxQueueMessageSize: external_exports.number().optional().describe(
14784
- "Maximum size of each queue message in bytes. Default: 65536"
14785
- ),
14786
- canHibernateWebSocket: external_exports.boolean().optional().describe(
14787
- "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
14788
- )
14789
- }).describe("Actor options for timeouts and behavior configuration.");
14790
- var DocActorConfigSchema = external_exports.object({
14791
- state: external_exports.unknown().optional().describe(
14792
- "Initial state value for the actor. Cannot be used with createState."
14793
- ),
14794
- createState: external_exports.unknown().optional().describe(
14795
- "Function to create initial state. Receives context and input. Cannot be used with state."
14796
- ),
14797
- connState: external_exports.unknown().optional().describe(
14798
- "Initial connection state value. Cannot be used with createConnState."
14799
- ),
14800
- createConnState: external_exports.unknown().optional().describe(
14801
- "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."
14802
- ),
14803
- vars: external_exports.unknown().optional().describe(
14804
- "Initial ephemeral variables value. Cannot be used with createVars."
14805
- ),
14806
- createVars: external_exports.unknown().optional().describe(
14807
- "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
14808
- ),
14809
- db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
14810
- onCreate: external_exports.unknown().optional().describe(
14811
- "Called when the actor is first initialized. Use to initialize state."
14812
- ),
14813
- onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
14814
- onMigrate: external_exports.unknown().optional().describe(
14815
- "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
14816
- ),
14817
- onWake: external_exports.unknown().optional().describe(
14818
- "Called when the actor wakes up and is ready to receive connections and actions."
14819
- ),
14820
- onSleep: external_exports.unknown().optional().describe(
14821
- "Called when the actor is stopping or sleeping. Use to clean up resources."
14822
- ),
14823
- run: external_exports.unknown().optional().describe(
14824
- "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."
14825
- ),
14826
- onStateChange: external_exports.unknown().optional().describe(
14827
- "Called when the actor's state changes. State changes within this hook won't trigger recursion."
14828
- ),
14829
- onBeforeConnect: external_exports.unknown().optional().describe(
14830
- "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
14831
- ),
14832
- onConnect: external_exports.unknown().optional().describe(
14833
- "Called when a client successfully connects. The connection is visible in c.conns before this runs."
14834
- ),
14835
- onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
14836
- onBeforeActionResponse: external_exports.unknown().optional().describe(
14837
- "Called before sending an action response. Use to transform output."
14838
- ),
14839
- onRequest: external_exports.unknown().optional().describe(
14840
- "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
14841
- ),
14842
- onWebSocket: external_exports.unknown().optional().describe(
14843
- "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
14844
- ),
14845
- actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
14846
- "Map of action name to handler function. Defaults to an empty object."
14847
- ),
14848
- actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
14849
- "Optional schema map for validating action argument tuples in native runtimes."
14850
- ),
14851
- connParamsSchema: external_exports.unknown().optional().describe(
14852
- "Optional schema for validating connection params in native runtimes."
14853
- ),
14854
- events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
14855
- queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
14856
- options: DocActorOptionsSchema.optional()
14857
- }).describe("Actor configuration passed to the actor() function.");
14858
-
14859
- // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
14860
- var EMPTY_KEY = "/";
14861
- var KEY_SEPARATOR = "/";
14862
- var KEYS = {
14863
- PERSIST_DATA: Uint8Array.from([1]),
14864
- CONN_PREFIX: Uint8Array.from([2]),
14865
- INSPECTOR_TOKEN: Uint8Array.from([3]),
14866
- KV: Uint8Array.from([4]),
14867
- QUEUE_PREFIX: Uint8Array.from([5]),
14868
- LAST_PUSHED_ALARM: Uint8Array.from([6]),
14869
- WORKFLOW_PREFIX: Uint8Array.from([6]),
14870
- TRACES_PREFIX: Uint8Array.from([7])
14871
- };
14872
- var STORAGE_VERSION = {
14873
- QUEUE: 1,
14874
- WORKFLOW: 1,
14875
- TRACES: 1
14876
- };
14877
- var STORAGE_VERSION_BYTES = {
14878
- QUEUE: Uint8Array.from([STORAGE_VERSION.QUEUE]),
14879
- WORKFLOW: Uint8Array.from([STORAGE_VERSION.WORKFLOW]),
14880
- TRACES: Uint8Array.from([STORAGE_VERSION.TRACES])
14881
- };
14882
- var QUEUE_NAMESPACE = {
14883
- METADATA: Uint8Array.from([1]),
14884
- MESSAGES: Uint8Array.from([2])
14885
- };
14886
- function concatPrefix(prefix, suffix) {
14887
- const merged = new Uint8Array(prefix.length + suffix.length);
14888
- merged.set(prefix, 0);
14889
- merged.set(suffix, prefix.length);
14890
- return merged;
14891
- }
14892
- var QUEUE_STORAGE_PREFIX = concatPrefix(
14893
- KEYS.QUEUE_PREFIX,
14894
- STORAGE_VERSION_BYTES.QUEUE
14895
- );
14896
- var QUEUE_METADATA_KEY = concatPrefix(
14897
- QUEUE_STORAGE_PREFIX,
14898
- QUEUE_NAMESPACE.METADATA
14899
- );
14900
- var QUEUE_MESSAGES_PREFIX = concatPrefix(
14901
- QUEUE_STORAGE_PREFIX,
14902
- QUEUE_NAMESPACE.MESSAGES
14903
- );
14904
- var WORKFLOW_STORAGE_PREFIX = concatPrefix(
14905
- KEYS.WORKFLOW_PREFIX,
14906
- STORAGE_VERSION_BYTES.WORKFLOW
14907
- );
14908
- var TRACES_STORAGE_PREFIX = concatPrefix(
14909
- KEYS.TRACES_PREFIX,
14910
- STORAGE_VERSION_BYTES.TRACES
14911
- );
14912
- function serializeActorKey(key) {
14913
- if (key.length === 0) {
14914
- return EMPTY_KEY;
14497
+ try {
14498
+ return UTF8_DECODER.decode(readUnsafeU8FixedArray(bc, byteLen));
14499
+ } catch (_cause) {
14500
+ throw new BareError(bc.offset, INVALID_UTF8_STRING);
14915
14501
  }
14916
- const escapedParts = key.map((part) => {
14917
- if (part === "") {
14918
- return "\\0";
14919
- }
14920
- let escaped = part.replace(/\\/g, "\\\\");
14921
- escaped = escaped.replace(/\//g, `\\${KEY_SEPARATOR}`);
14922
- return escaped;
14923
- });
14924
- return escapedParts.join(KEY_SEPARATOR);
14925
14502
  }
14926
- function deserializeActorKey(keyString) {
14927
- if (keyString === void 0 || keyString === null || keyString === EMPTY_KEY) {
14928
- return [];
14929
- }
14930
- const parts = [];
14931
- let currentPart = "";
14932
- let escaping = false;
14933
- let isEmptyStringMarker = false;
14934
- for (let i = 0; i < keyString.length; i++) {
14935
- const char = keyString[i];
14936
- if (escaping) {
14937
- if (char === "0") {
14938
- isEmptyStringMarker = true;
14939
- } else {
14940
- currentPart += char;
14941
- }
14942
- escaping = false;
14943
- } else if (char === "\\") {
14944
- escaping = true;
14945
- } else if (char === KEY_SEPARATOR) {
14946
- if (isEmptyStringMarker) {
14947
- parts.push("");
14948
- isEmptyStringMarker = false;
14949
- } else {
14950
- parts.push(currentPart);
14503
+ function readUtf8Js(bc, byteLen) {
14504
+ check2(bc, byteLen);
14505
+ let result = "";
14506
+ const bytes = bc.bytes;
14507
+ let offset = bc.offset;
14508
+ const upperOffset = offset + byteLen;
14509
+ while (offset < upperOffset) {
14510
+ let codePoint = bytes[offset++];
14511
+ if (codePoint > 127) {
14512
+ let malformed = true;
14513
+ const byte1 = codePoint;
14514
+ if (offset < upperOffset && codePoint < 224) {
14515
+ const byte2 = bytes[offset++];
14516
+ codePoint = (byte1 & 31) << 6 | byte2 & 63;
14517
+ malformed = codePoint >> 7 === 0 || // non-canonical char
14518
+ byte1 >> 5 !== 6 || // invalid tag
14519
+ byte2 >> 6 !== 2;
14520
+ } else if (offset + 1 < upperOffset && codePoint < 240) {
14521
+ const byte2 = bytes[offset++];
14522
+ const byte3 = bytes[offset++];
14523
+ codePoint = (byte1 & 15) << 12 | (byte2 & 63) << 6 | byte3 & 63;
14524
+ malformed = codePoint >> 11 === 0 || // non-canonical char or missing data
14525
+ codePoint >> 11 === 27 || // surrogate char (0xD800 <= codePoint <= 0xDFFF)
14526
+ byte1 >> 4 !== 14 || // invalid tag
14527
+ byte2 >> 6 !== 2 || // invalid tag
14528
+ byte3 >> 6 !== 2;
14529
+ } else if (offset + 2 < upperOffset) {
14530
+ const byte2 = bytes[offset++];
14531
+ const byte3 = bytes[offset++];
14532
+ const byte4 = bytes[offset++];
14533
+ codePoint = (byte1 & 7) << 18 | (byte2 & 63) << 12 | (byte3 & 63) << 6 | byte4 & 63;
14534
+ malformed = codePoint >> 16 === 0 || // non-canonical char or missing data
14535
+ codePoint > 1114111 || // too large code point
14536
+ byte1 >> 3 !== 30 || // invalid tag
14537
+ byte2 >> 6 !== 2 || // invalid tag
14538
+ byte3 >> 6 !== 2 || // invalid tag
14539
+ byte4 >> 6 !== 2;
14540
+ }
14541
+ if (malformed) {
14542
+ throw new BareError(bc.offset, INVALID_UTF8_STRING);
14951
14543
  }
14952
- currentPart = "";
14953
- } else {
14954
- currentPart += char;
14955
14544
  }
14545
+ result += String.fromCodePoint(codePoint);
14956
14546
  }
14957
- if (escaping) {
14958
- parts.push(`${currentPart}\\`);
14959
- } else if (isEmptyStringMarker) {
14960
- parts.push("");
14961
- } else if (currentPart !== "" || parts.length > 0) {
14962
- parts.push(currentPart);
14547
+ bc.offset = offset;
14548
+ return result;
14549
+ }
14550
+ function writeUtf8Js(bc, s) {
14551
+ const bytes = bc.bytes;
14552
+ let offset = bc.offset;
14553
+ let i = 0;
14554
+ while (i < s.length) {
14555
+ const codePoint = s.codePointAt(i++);
14556
+ if (codePoint < 128) {
14557
+ bytes[offset++] = codePoint;
14558
+ } else {
14559
+ if (codePoint < 2048) {
14560
+ bytes[offset++] = 192 | codePoint >> 6;
14561
+ } else {
14562
+ if (codePoint < 65536) {
14563
+ bytes[offset++] = 224 | codePoint >> 12;
14564
+ } else {
14565
+ bytes[offset++] = 240 | codePoint >> 18;
14566
+ bytes[offset++] = 128 | codePoint >> 12 & 63;
14567
+ i++;
14568
+ }
14569
+ bytes[offset++] = 128 | codePoint >> 6 & 63;
14570
+ }
14571
+ bytes[offset++] = 128 | codePoint & 63;
14572
+ }
14963
14573
  }
14964
- return parts;
14574
+ bc.offset = offset;
14965
14575
  }
14966
- function makePrefixedKey(key) {
14967
- const prefixed = new Uint8Array(KEYS.KV.length + key.length);
14968
- prefixed.set(KEYS.KV, 0);
14969
- prefixed.set(key, KEYS.KV.length);
14970
- return prefixed;
14576
+ function utf8ByteLength(s) {
14577
+ let result = s.length;
14578
+ for (let i = 0; i < s.length; i++) {
14579
+ const codePoint = s.codePointAt(i);
14580
+ if (codePoint > 127) {
14581
+ result++;
14582
+ if (codePoint > 2047) {
14583
+ result++;
14584
+ if (codePoint > 65535) {
14585
+ i++;
14586
+ }
14587
+ }
14588
+ }
14589
+ }
14590
+ return result;
14971
14591
  }
14972
- function removePrefixFromKey(prefixedKey) {
14973
- return prefixedKey.slice(KEYS.KV.length);
14592
+ var UTF8_DECODER = /* @__PURE__ */ new TextDecoder("utf-8", { fatal: true });
14593
+ var UTF8_ENCODER = /* @__PURE__ */ new TextEncoder();
14594
+
14595
+ // ../../../node_modules/.pnpm/@rivetkit+bare-ts@0.6.2/node_modules/@rivetkit/bare-ts/dist/core/config.js
14596
+ function Config({ initialBufferLength = 1024, maxBufferLength = 1024 * 1024 * 32 }) {
14597
+ if (DEV) {
14598
+ assert2(isU32(initialBufferLength), TOO_LARGE_NUMBER);
14599
+ assert2(isU32(maxBufferLength), TOO_LARGE_NUMBER);
14600
+ assert2(initialBufferLength <= maxBufferLength, "initialBufferLength must be lower than or equal to maxBufferLength");
14601
+ }
14602
+ return {
14603
+ initialBufferLength,
14604
+ maxBufferLength
14605
+ };
14974
14606
  }
14975
14607
 
14976
- // ../rivetkit/dist/tsup/chunk-PM4ACAVN.js
14977
- var import_invariant = __toESM(require_invariant(), 1);
14978
- import * as cbor from "cbor-x";
14979
- var JSON_COMPAT_BIGINT = "$BigInt";
14980
- var JSON_COMPAT_ARRAY_BUFFER = "$ArrayBuffer";
14981
- var JSON_COMPAT_UINT8_ARRAY = "$Uint8Array";
14982
- var JSON_COMPAT_UNDEFINED = "$Undefined";
14983
- var JSON_COMPAT_SET = "$Set";
14984
- function isTypedArray(value) {
14985
- return value instanceof Uint8ClampedArray || value instanceof Uint16Array || value instanceof Uint32Array || value instanceof BigUint64Array || value instanceof Int8Array || value instanceof Int16Array || value instanceof Int32Array || value instanceof BigInt64Array || value instanceof Float32Array || value instanceof Float64Array;
14608
+ // ../rivetkit/dist/tsup/chunk-ULYPJPHB.js
14609
+ var config2 = /* @__PURE__ */ Config({});
14610
+ function readWorkflowCbor(bc) {
14611
+ return readData(bc);
14986
14612
  }
14987
- function assertJsonCompatValue(value, path2 = "") {
14988
- var _a2;
14989
- if (value === null || value === void 0 || typeof value === "string" || typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
14990
- return;
14991
- }
14992
- if (typeof value === "function") {
14993
- throw new TypeError(
14994
- `Value at ${path2 || "root"} is a function and is not CBOR serializable`
14995
- );
14996
- }
14997
- if (typeof value === "symbol") {
14998
- throw new TypeError(
14999
- `Value at ${path2 || "root"} is a symbol and is not CBOR serializable`
15000
- );
15001
- }
15002
- if (value instanceof Date || value instanceof RegExp || value instanceof Error || value instanceof ArrayBuffer || value instanceof Uint8Array || isTypedArray(value)) {
15003
- return;
15004
- }
15005
- if (value instanceof WeakMap) {
15006
- throw new TypeError(
15007
- `Value at ${path2 || "root"} is a WeakMap and is not CBOR serializable`
15008
- );
15009
- }
15010
- if (value instanceof WeakSet) {
15011
- throw new TypeError(
15012
- `Value at ${path2 || "root"} is a WeakSet and is not CBOR serializable`
15013
- );
15014
- }
15015
- if (value instanceof WeakRef) {
15016
- throw new TypeError(
15017
- `Value at ${path2 || "root"} is a WeakRef and is not CBOR serializable`
15018
- );
15019
- }
15020
- if (value instanceof Promise) {
15021
- throw new TypeError(
15022
- `Value at ${path2 || "root"} is a Promise and is not CBOR serializable`
15023
- );
15024
- }
15025
- if (value instanceof Map) {
15026
- for (const [k, v] of value.entries()) {
15027
- assertJsonCompatValue(k, `${path2 || "root"}.key(${String(k)})`);
15028
- assertJsonCompatValue(v, `${path2 || "root"}.value(${String(k)})`);
14613
+ function readWorkflowNameIndex(bc) {
14614
+ return readU32(bc);
14615
+ }
14616
+ function readWorkflowLoopIterationMarker(bc) {
14617
+ return {
14618
+ loop: readWorkflowNameIndex(bc),
14619
+ iteration: readU32(bc)
14620
+ };
14621
+ }
14622
+ function readWorkflowPathSegment(bc) {
14623
+ const offset = bc.offset;
14624
+ const tag = readU8(bc);
14625
+ switch (tag) {
14626
+ case 0:
14627
+ return { tag: "WorkflowNameIndex", val: readWorkflowNameIndex(bc) };
14628
+ case 1:
14629
+ return {
14630
+ tag: "WorkflowLoopIterationMarker",
14631
+ val: readWorkflowLoopIterationMarker(bc)
14632
+ };
14633
+ default: {
14634
+ bc.offset = offset;
14635
+ throw new BareError(offset, "invalid tag");
15029
14636
  }
15030
- return;
15031
14637
  }
15032
- if (value instanceof Set) {
15033
- let index = 0;
15034
- for (const item of value.values()) {
15035
- assertJsonCompatValue(item, `${path2 || "root"}.set[${index}]`);
15036
- index++;
15037
- }
15038
- return;
14638
+ }
14639
+ function readWorkflowLocation(bc) {
14640
+ const len = readUintSafe(bc);
14641
+ if (len === 0) {
14642
+ return [];
15039
14643
  }
15040
- if (Array.isArray(value)) {
15041
- for (let i = 0; i < value.length; i++) {
15042
- assertJsonCompatValue(value[i], `${path2 || "root"}[${i}]`);
15043
- }
15044
- return;
14644
+ const result = [readWorkflowPathSegment(bc)];
14645
+ for (let i = 1; i < len; i++) {
14646
+ result[i] = readWorkflowPathSegment(bc);
15045
14647
  }
15046
- if (isPlainObject2(value)) {
15047
- for (const key in value) {
15048
- assertJsonCompatValue(
15049
- value[key],
15050
- path2 ? `${path2}.${key}` : key
15051
- );
14648
+ return result;
14649
+ }
14650
+ function readWorkflowEntryStatus(bc) {
14651
+ const offset = bc.offset;
14652
+ const tag = readU8(bc);
14653
+ switch (tag) {
14654
+ case 0:
14655
+ return "PENDING";
14656
+ case 1:
14657
+ return "RUNNING";
14658
+ case 2:
14659
+ return "COMPLETED";
14660
+ case 3:
14661
+ return "FAILED";
14662
+ case 4:
14663
+ return "EXHAUSTED";
14664
+ default: {
14665
+ bc.offset = offset;
14666
+ throw new BareError(offset, "invalid tag");
15052
14667
  }
15053
- return;
15054
14668
  }
15055
- const typeName = typeof value === "object" && value !== null ? ((_a2 = value.constructor) == null ? void 0 : _a2.name) ?? typeof value : typeof value;
15056
- throw new TypeError(
15057
- `Value at ${path2 || "root"} of type "${typeName}" is not CBOR serializable`
15058
- );
15059
14669
  }
15060
- var EncodingSchema = external_exports.enum(["json", "cbor", "bare"]);
15061
- async function inputDataToBuffer(data) {
15062
- if (typeof data === "string") {
15063
- return data;
15064
- }
15065
- if (data instanceof Blob) {
15066
- return new Uint8Array(await data.arrayBuffer());
15067
- }
15068
- if (data instanceof Uint8Array) {
15069
- return data;
15070
- }
15071
- if (data instanceof ArrayBuffer || data instanceof SharedArrayBuffer) {
15072
- return new Uint8Array(data);
14670
+ function readWorkflowSleepState(bc) {
14671
+ const offset = bc.offset;
14672
+ const tag = readU8(bc);
14673
+ switch (tag) {
14674
+ case 0:
14675
+ return "PENDING";
14676
+ case 1:
14677
+ return "COMPLETED";
14678
+ case 2:
14679
+ return "INTERRUPTED";
14680
+ default: {
14681
+ bc.offset = offset;
14682
+ throw new BareError(offset, "invalid tag");
14683
+ }
15073
14684
  }
15074
- throw new Error("Malformed message");
15075
14685
  }
15076
- function base64EncodeUint8Array(uint8Array) {
15077
- let binary = "";
15078
- for (const value of uint8Array) {
15079
- binary += String.fromCharCode(value);
14686
+ function readWorkflowBranchStatusType(bc) {
14687
+ const offset = bc.offset;
14688
+ const tag = readU8(bc);
14689
+ switch (tag) {
14690
+ case 0:
14691
+ return "PENDING";
14692
+ case 1:
14693
+ return "RUNNING";
14694
+ case 2:
14695
+ return "COMPLETED";
14696
+ case 3:
14697
+ return "FAILED";
14698
+ case 4:
14699
+ return "CANCELLED";
14700
+ default: {
14701
+ bc.offset = offset;
14702
+ throw new BareError(offset, "invalid tag");
14703
+ }
15080
14704
  }
15081
- return btoa(binary);
15082
14705
  }
15083
- function base64EncodeArrayBuffer(arrayBuffer) {
15084
- return base64EncodeUint8Array(new Uint8Array(arrayBuffer));
14706
+ function read0(bc) {
14707
+ return readBool(bc) ? readWorkflowCbor(bc) : null;
15085
14708
  }
15086
- function isPlainObject2(value) {
15087
- if (value === null || typeof value !== "object") {
15088
- return false;
15089
- }
15090
- const proto = Object.getPrototypeOf(value);
15091
- return proto === Object.prototype || proto === null;
14709
+ function read1(bc) {
14710
+ return readBool(bc) ? readString(bc) : null;
15092
14711
  }
15093
- function encodeJsonCompatValue(input) {
15094
- var _a2;
15095
- if (input === null) {
15096
- return input;
14712
+ function readWorkflowStepEntry(bc) {
14713
+ return {
14714
+ output: read0(bc),
14715
+ error: read1(bc)
14716
+ };
14717
+ }
14718
+ function readWorkflowLoopEntry(bc) {
14719
+ return {
14720
+ state: readWorkflowCbor(bc),
14721
+ iteration: readU32(bc),
14722
+ output: read0(bc)
14723
+ };
14724
+ }
14725
+ function readWorkflowSleepEntry(bc) {
14726
+ return {
14727
+ deadline: readU64(bc),
14728
+ state: readWorkflowSleepState(bc)
14729
+ };
14730
+ }
14731
+ function readWorkflowMessageEntry(bc) {
14732
+ return {
14733
+ name: readString(bc),
14734
+ messageData: readWorkflowCbor(bc)
14735
+ };
14736
+ }
14737
+ function readWorkflowRollbackCheckpointEntry(bc) {
14738
+ return {
14739
+ name: readString(bc)
14740
+ };
14741
+ }
14742
+ function readWorkflowBranchStatus(bc) {
14743
+ return {
14744
+ status: readWorkflowBranchStatusType(bc),
14745
+ output: read0(bc),
14746
+ error: read1(bc)
14747
+ };
14748
+ }
14749
+ function read2(bc) {
14750
+ const len = readUintSafe(bc);
14751
+ const result = /* @__PURE__ */ new Map();
14752
+ for (let i = 0; i < len; i++) {
14753
+ const offset = bc.offset;
14754
+ const key = readString(bc);
14755
+ if (result.has(key)) {
14756
+ bc.offset = offset;
14757
+ throw new BareError(offset, "duplicated key");
14758
+ }
14759
+ result.set(key, readWorkflowBranchStatus(bc));
15097
14760
  }
15098
- if (input === void 0) {
15099
- return [JSON_COMPAT_UNDEFINED, 0];
14761
+ return result;
14762
+ }
14763
+ function readWorkflowJoinEntry(bc) {
14764
+ return {
14765
+ branches: read2(bc)
14766
+ };
14767
+ }
14768
+ function readWorkflowRaceEntry(bc) {
14769
+ return {
14770
+ winner: read1(bc),
14771
+ branches: read2(bc)
14772
+ };
14773
+ }
14774
+ function readWorkflowRemovedEntry(bc) {
14775
+ return {
14776
+ originalType: readString(bc),
14777
+ originalName: read1(bc)
14778
+ };
14779
+ }
14780
+ function readWorkflowVersionCheckEntry(bc) {
14781
+ return {
14782
+ resolved: readU32(bc),
14783
+ latest: readU32(bc)
14784
+ };
14785
+ }
14786
+ function readWorkflowEntryKind(bc) {
14787
+ const offset = bc.offset;
14788
+ const tag = readU8(bc);
14789
+ switch (tag) {
14790
+ case 0:
14791
+ return { tag: "WorkflowStepEntry", val: readWorkflowStepEntry(bc) };
14792
+ case 1:
14793
+ return { tag: "WorkflowLoopEntry", val: readWorkflowLoopEntry(bc) };
14794
+ case 2:
14795
+ return {
14796
+ tag: "WorkflowSleepEntry",
14797
+ val: readWorkflowSleepEntry(bc)
14798
+ };
14799
+ case 3:
14800
+ return {
14801
+ tag: "WorkflowMessageEntry",
14802
+ val: readWorkflowMessageEntry(bc)
14803
+ };
14804
+ case 4:
14805
+ return {
14806
+ tag: "WorkflowRollbackCheckpointEntry",
14807
+ val: readWorkflowRollbackCheckpointEntry(bc)
14808
+ };
14809
+ case 5:
14810
+ return { tag: "WorkflowJoinEntry", val: readWorkflowJoinEntry(bc) };
14811
+ case 6:
14812
+ return { tag: "WorkflowRaceEntry", val: readWorkflowRaceEntry(bc) };
14813
+ case 7:
14814
+ return {
14815
+ tag: "WorkflowRemovedEntry",
14816
+ val: readWorkflowRemovedEntry(bc)
14817
+ };
14818
+ case 8:
14819
+ return {
14820
+ tag: "WorkflowVersionCheckEntry",
14821
+ val: readWorkflowVersionCheckEntry(bc)
14822
+ };
14823
+ default: {
14824
+ bc.offset = offset;
14825
+ throw new BareError(offset, "invalid tag");
14826
+ }
15100
14827
  }
15101
- if (typeof input === "string" || typeof input === "number" || typeof input === "boolean") {
15102
- return input;
14828
+ }
14829
+ function readWorkflowEntry(bc) {
14830
+ return {
14831
+ id: readString(bc),
14832
+ location: readWorkflowLocation(bc),
14833
+ kind: readWorkflowEntryKind(bc)
14834
+ };
14835
+ }
14836
+ function read3(bc) {
14837
+ return readBool(bc) ? readU64(bc) : null;
14838
+ }
14839
+ function readWorkflowEntryMetadata(bc) {
14840
+ return {
14841
+ status: readWorkflowEntryStatus(bc),
14842
+ error: read1(bc),
14843
+ attempts: readU32(bc),
14844
+ lastAttemptAt: readU64(bc),
14845
+ createdAt: readU64(bc),
14846
+ completedAt: read3(bc),
14847
+ rollbackCompletedAt: read3(bc),
14848
+ rollbackError: read1(bc)
14849
+ };
14850
+ }
14851
+ function read4(bc) {
14852
+ const len = readUintSafe(bc);
14853
+ if (len === 0) {
14854
+ return [];
15103
14855
  }
15104
- if (typeof input === "bigint") {
15105
- return [JSON_COMPAT_BIGINT, input.toString()];
14856
+ const result = [readString(bc)];
14857
+ for (let i = 1; i < len; i++) {
14858
+ result[i] = readString(bc);
15106
14859
  }
15107
- if (input instanceof ArrayBuffer) {
15108
- return [JSON_COMPAT_ARRAY_BUFFER, base64EncodeArrayBuffer(input)];
14860
+ return result;
14861
+ }
14862
+ function read5(bc) {
14863
+ const len = readUintSafe(bc);
14864
+ if (len === 0) {
14865
+ return [];
15109
14866
  }
15110
- if (input instanceof Uint8Array) {
15111
- return [JSON_COMPAT_UINT8_ARRAY, base64EncodeUint8Array(input)];
14867
+ const result = [readWorkflowEntry(bc)];
14868
+ for (let i = 1; i < len; i++) {
14869
+ result[i] = readWorkflowEntry(bc);
15112
14870
  }
15113
- if (isTypedArray(input)) {
15114
- return input;
14871
+ return result;
14872
+ }
14873
+ function read6(bc) {
14874
+ const len = readUintSafe(bc);
14875
+ const result = /* @__PURE__ */ new Map();
14876
+ for (let i = 0; i < len; i++) {
14877
+ const offset = bc.offset;
14878
+ const key = readString(bc);
14879
+ if (result.has(key)) {
14880
+ bc.offset = offset;
14881
+ throw new BareError(offset, "duplicated key");
14882
+ }
14883
+ result.set(key, readWorkflowEntryMetadata(bc));
15115
14884
  }
15116
- if (input instanceof Date || input instanceof RegExp || input instanceof Error) {
15117
- return input;
14885
+ return result;
14886
+ }
14887
+ function readWorkflowHistory(bc) {
14888
+ return {
14889
+ nameRegistry: read4(bc),
14890
+ entries: read5(bc),
14891
+ entryMetadata: read6(bc)
14892
+ };
14893
+ }
14894
+ function decodeWorkflowHistory(bytes) {
14895
+ const bc = new ByteCursor(bytes, config2);
14896
+ const result = readWorkflowHistory(bc);
14897
+ if (bc.offset < bc.view.byteLength) {
14898
+ throw new BareError(bc.offset, "remaining bytes");
15118
14899
  }
15119
- if (input instanceof Set) {
15120
- const encoded = [...input.values()].map(
15121
- (v) => encodeJsonCompatValue(v)
15122
- );
15123
- return [JSON_COMPAT_SET, encoded];
15124
- }
15125
- if (input instanceof Map) {
15126
- const encoded = /* @__PURE__ */ new Map();
15127
- for (const [k, v] of input.entries()) {
15128
- encoded.set(
15129
- encodeJsonCompatValue(k),
15130
- encodeJsonCompatValue(v)
14900
+ return result;
14901
+ }
14902
+ function decodeWorkflowHistoryTransport(data) {
14903
+ return decodeWorkflowHistory(toUint8Array(data));
14904
+ }
14905
+
14906
+ // ../rivetkit/dist/tsup/chunk-QWLJCP3X.js
14907
+ function flattenActionHandlers(actions) {
14908
+ const flattened = /* @__PURE__ */ Object.create(null);
14909
+ for (const { name, handler } of collectActionEntries(actions)) {
14910
+ flattened[name] = handler;
14911
+ }
14912
+ return flattened;
14913
+ }
14914
+ function flattenActionInputSchemas(actions, schemas) {
14915
+ if (schemas === void 0) return void 0;
14916
+ if (!isRecord(schemas)) {
14917
+ throw new TypeError("actionInputSchemas must be an object");
14918
+ }
14919
+ const flattened = /* @__PURE__ */ Object.create(null);
14920
+ for (const { name, path: path2 } of collectActionEntries(actions)) {
14921
+ const nestedSchema = lookupNestedSchema(schemas, path2);
14922
+ const flatSchema = schemas[name];
14923
+ if (nestedSchema !== void 0 && flatSchema !== void 0 && nestedSchema !== flatSchema) {
14924
+ throw new TypeError(
14925
+ `Action input schema \`${name}\` is defined by both a nested path and a dotted key`
15131
14926
  );
15132
14927
  }
15133
- return encoded;
14928
+ const schema = nestedSchema ?? flatSchema;
14929
+ if (schema !== void 0) {
14930
+ flattened[name] = schema;
14931
+ }
15134
14932
  }
15135
- if (Array.isArray(input)) {
15136
- const encoded = input.map(
15137
- (value) => encodeJsonCompatValue(value)
14933
+ return flattened;
14934
+ }
14935
+ function collectActionEntries(actions) {
14936
+ const entries = [];
14937
+ const names = /* @__PURE__ */ new Set();
14938
+ visitActionGroup(actions ?? {}, [], entries, names);
14939
+ return entries;
14940
+ }
14941
+ function visitActionGroup(value, path2, entries, names) {
14942
+ if (!isRecord(value)) {
14943
+ throw new TypeError(
14944
+ `${formatActionPath(path2)} must be an action handler or group`
15138
14945
  );
15139
- if (encoded.length === 2 && typeof encoded[0] === "string" && encoded[0].startsWith("$")) {
15140
- return [`$${encoded[0]}`, encoded[1]];
15141
- }
15142
- return encoded;
15143
14946
  }
15144
- if (isPlainObject2(input)) {
15145
- const encoded = {};
15146
- for (const [key, value] of Object.entries(input)) {
15147
- encoded[key] = encodeJsonCompatValue(value);
14947
+ for (const [segment, child] of Object.entries(value)) {
14948
+ const childPath = [...path2, segment];
14949
+ if (typeof child === "function") {
14950
+ const name = childPath.join(".");
14951
+ if (names.has(name)) {
14952
+ throw new TypeError(
14953
+ `Multiple action definitions flatten to \`${name}\``
14954
+ );
14955
+ }
14956
+ names.add(name);
14957
+ entries.push({
14958
+ name,
14959
+ path: childPath,
14960
+ handler: child
14961
+ });
14962
+ } else {
14963
+ visitActionGroup(child, childPath, entries, names);
15148
14964
  }
15149
- return encoded;
15150
14965
  }
15151
- const typeName = typeof input === "object" && input !== null ? ((_a2 = input.constructor) == null ? void 0 : _a2.name) ?? typeof input : typeof input;
15152
- throw new TypeError(`Value of type "${typeName}" is not CBOR serializable`);
15153
14966
  }
15154
- function reviveJsonCompatValue(input, options = {}) {
15155
- if (typeof input === "bigint") {
15156
- if (options.coerceSafeIntegerBigInts && input >= BigInt(Number.MIN_SAFE_INTEGER) && input <= BigInt(Number.MAX_SAFE_INTEGER)) {
15157
- return Number(input);
14967
+ function lookupNestedSchema(schemas, path2) {
14968
+ let value = schemas;
14969
+ for (const segment of path2) {
14970
+ if (!isRecord(value) || !Object.hasOwn(value, segment)) {
14971
+ return void 0;
15158
14972
  }
15159
- return input;
14973
+ value = value[segment];
15160
14974
  }
15161
- if (input instanceof Map) {
15162
- const revived = /* @__PURE__ */ new Map();
15163
- for (const [k, v] of input.entries()) {
15164
- revived.set(
15165
- reviveJsonCompatValue(k, options),
15166
- reviveJsonCompatValue(v, options)
15167
- );
15168
- }
15169
- return revived;
14975
+ return value;
14976
+ }
14977
+ function isRecord(value) {
14978
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
14979
+ return false;
15170
14980
  }
15171
- if (Array.isArray(input)) {
15172
- if (input.length === 2 && typeof input[0] === "string" && input[0].startsWith("$")) {
15173
- if (input[0] === JSON_COMPAT_BIGINT) {
15174
- return BigInt(input[1]);
15175
- }
15176
- if (input[0] === JSON_COMPAT_ARRAY_BUFFER) {
15177
- return base64DecodeToArrayBuffer(input[1]);
15178
- }
15179
- if (input[0] === JSON_COMPAT_UINT8_ARRAY) {
15180
- return base64DecodeToUint8Array(input[1]);
15181
- }
15182
- if (input[0] === JSON_COMPAT_UNDEFINED) {
15183
- return void 0;
15184
- }
15185
- if (input[0] === JSON_COMPAT_SET) {
15186
- const items = input[1].map(
15187
- (v) => reviveJsonCompatValue(v, options)
15188
- );
15189
- return new Set(items);
15190
- }
15191
- if (input[0].startsWith("$$")) {
15192
- return [
15193
- input[0].substring(1),
15194
- reviveJsonCompatValue(input[1], options)
15195
- ];
15196
- }
15197
- throw new Error(
15198
- `Unknown JSON encoding type: ${input[0]}. This may indicate corrupted data or a version mismatch.`
15199
- );
15200
- }
15201
- return input.map((value) => reviveJsonCompatValue(value, options));
14981
+ const prototype = Object.getPrototypeOf(value);
14982
+ return prototype === Object.prototype || prototype === null;
14983
+ }
14984
+ function formatActionPath(path2) {
14985
+ return path2.length === 0 ? "actions" : `Action \`${path2.join(".")}\``;
14986
+ }
14987
+ var DEFAULT_SLEEP_GRACE_PERIOD = 15e3;
14988
+ var ACTOR_CONTEXT_INTERNAL_SYMBOL = /* @__PURE__ */ Symbol(
14989
+ "rivetkit.actor_context_internal"
14990
+ );
14991
+ var RAW_STATE_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.raw_state");
14992
+ var CONN_STATE_MANAGER_SYMBOL = /* @__PURE__ */ Symbol("rivetkit.conn_state_manager");
14993
+ var zFunction = () => external_exports.custom((val) => typeof val === "function");
14994
+ var zActionTree = external_exports.custom((value) => {
14995
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
14996
+ return false;
15202
14997
  }
15203
- if (isPlainObject2(input)) {
15204
- const decoded = {};
15205
- for (const [key, value] of Object.entries(input)) {
15206
- decoded[key] = reviveJsonCompatValue(value, options);
15207
- }
15208
- return decoded;
14998
+ const prototype = Object.getPrototypeOf(value);
14999
+ return prototype === Object.prototype || prototype === null;
15000
+ }).superRefine((actions, ctx) => {
15001
+ try {
15002
+ flattenActionHandlers(actions);
15003
+ } catch (error46) {
15004
+ ctx.addIssue({
15005
+ code: "custom",
15006
+ message: error46 instanceof Error ? error46.message : "Invalid action definition"
15007
+ });
15209
15008
  }
15210
- return input;
15009
+ });
15010
+ var WorkflowInspectorConfigSchema = external_exports.object({
15011
+ getHistory: zFunction(),
15012
+ onHistoryUpdated: zFunction().optional(),
15013
+ replayFromStep: zFunction().optional()
15014
+ });
15015
+ var RunInspectorConfigSchema = external_exports.object({
15016
+ workflow: WorkflowInspectorConfigSchema.optional()
15017
+ }).optional();
15018
+ var BUILTIN_INSPECTOR_TAB_IDS = [
15019
+ "workflow",
15020
+ "database",
15021
+ "state",
15022
+ "queue",
15023
+ "schedules",
15024
+ "connections",
15025
+ "console"
15026
+ ];
15027
+ var BuiltinInspectorTabIdSchema = external_exports.enum(BUILTIN_INSPECTOR_TAB_IDS);
15028
+ var CUSTOM_INSPECTOR_TAB_ID_RE = /^[A-Za-z0-9_-]+$/;
15029
+ var CustomInspectorTabEntrySchema = external_exports.object({
15030
+ id: external_exports.string().regex(
15031
+ CUSTOM_INSPECTOR_TAB_ID_RE,
15032
+ "inspector.tabs[].id must contain only letters, digits, underscore, or dash"
15033
+ ),
15034
+ label: external_exports.string().min(1),
15035
+ source: external_exports.string().min(1),
15036
+ /**
15037
+ * Optional icon id. The dashboard maps strings to glyphs (see its
15038
+ * icon registry); unknown ids fall back to a generic icon.
15039
+ */
15040
+ icon: external_exports.string().min(1).optional(),
15041
+ hidden: external_exports.literal(false).optional()
15042
+ }).strict();
15043
+ var HideInspectorTabEntrySchema = external_exports.object({
15044
+ id: BuiltinInspectorTabIdSchema,
15045
+ hidden: external_exports.literal(true)
15046
+ }).strict();
15047
+ var InspectorTabEntrySchema = external_exports.union([
15048
+ CustomInspectorTabEntrySchema,
15049
+ HideInspectorTabEntrySchema
15050
+ ]);
15051
+ var ActorInspectorConfigSchema = external_exports.object({
15052
+ tabs: external_exports.array(InspectorTabEntrySchema).default(() => [])
15053
+ }).strict().refine(
15054
+ (data) => {
15055
+ const ids = data.tabs.map((t) => t.id);
15056
+ return new Set(ids).size === ids.length;
15057
+ },
15058
+ { message: "Duplicate id in inspector.tabs", path: ["tabs"] }
15059
+ ).refine(
15060
+ (data) => {
15061
+ const builtinSet = new Set(BUILTIN_INSPECTOR_TAB_IDS);
15062
+ return data.tabs.every(
15063
+ (t) => t.hidden === true || !builtinSet.has(t.id)
15064
+ );
15065
+ },
15066
+ {
15067
+ message: "Custom inspector tab id collides with a built-in (use hidden: true to hide a built-in)",
15068
+ path: ["tabs"]
15069
+ }
15070
+ );
15071
+ var RunConfigSchema = external_exports.object({
15072
+ /** Display name for the actor in the Inspector UI. */
15073
+ name: external_exports.string().optional(),
15074
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15075
+ icon: external_exports.string().optional(),
15076
+ /** The run handler function. */
15077
+ run: zFunction(),
15078
+ /** Inspector integration for long-running run handlers. */
15079
+ inspector: RunInspectorConfigSchema.optional()
15080
+ });
15081
+ var RUN_FUNCTION_CONFIG_SYMBOL = /* @__PURE__ */ Symbol.for(
15082
+ "rivetkit.run_function_config"
15083
+ );
15084
+ var zRunHandler = external_exports.union([zFunction(), RunConfigSchema]).optional();
15085
+ function getRunFunction(run) {
15086
+ if (!run) return void 0;
15087
+ if (typeof run === "function") return run;
15088
+ return run.run;
15089
+ }
15090
+ function getRunMetadata(run) {
15091
+ if (!run) return {};
15092
+ if (typeof run === "function") {
15093
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15094
+ if (!config3) return {};
15095
+ return { name: config3.name, icon: config3.icon };
15096
+ }
15097
+ return { name: run.name, icon: run.icon };
15098
+ }
15099
+ function getRunInspectorConfig(run, actor2) {
15100
+ if (!run) return void 0;
15101
+ if (typeof run === "function") {
15102
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15103
+ return (config3 == null ? void 0 : config3.inspectorFactory) ? config3.inspectorFactory(actor2) : config3 == null ? void 0 : config3.inspector;
15104
+ }
15105
+ return run.inspector;
15106
+ }
15107
+ function disposeRunInspector(run, actorId) {
15108
+ var _a2;
15109
+ if (!run || typeof run !== "function") {
15110
+ return;
15111
+ }
15112
+ const config3 = run[RUN_FUNCTION_CONFIG_SYMBOL];
15113
+ (_a2 = config3 == null ? void 0 : config3.disposeInspector) == null ? void 0 : _a2.call(config3, actorId);
15114
+ }
15115
+ var GlobalActorOptionsBaseSchema = external_exports.object({
15116
+ /** Display name for the actor in the Inspector UI. */
15117
+ name: external_exports.string().optional(),
15118
+ /** Icon for the actor in the Inspector UI. Can be an emoji or FontAwesome icon name. */
15119
+ icon: external_exports.string().optional(),
15120
+ /** Enables the experimental Actor Runtime Socket for this actor. */
15121
+ enableActorRuntimeSocket: external_exports.boolean().default(false),
15122
+ /**
15123
+ * Can hibernate WebSockets for onWebSocket.
15124
+ *
15125
+ * WebSockets using actions/events are hibernatable by default.
15126
+ *
15127
+ * @experimental
15128
+ **/
15129
+ canHibernateWebSocket: external_exports.union([external_exports.boolean(), zFunction()]).default(false)
15130
+ }).strict();
15131
+ var GlobalActorOptionsSchema = GlobalActorOptionsBaseSchema.prefault(
15132
+ () => ({})
15133
+ );
15134
+ var InstanceActorOptionsBaseSchema = external_exports.object({
15135
+ createVarsTimeout: external_exports.number().positive().default(5e3),
15136
+ createConnStateTimeout: external_exports.number().positive().default(5e3),
15137
+ onBeforeConnectTimeout: external_exports.number().positive().default(5e3),
15138
+ onConnectTimeout: external_exports.number().positive().default(5e3),
15139
+ onMigrateTimeout: external_exports.number().positive().default(3e4),
15140
+ sleepGracePeriod: external_exports.number().positive().default(DEFAULT_SLEEP_GRACE_PERIOD),
15141
+ /** @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. */
15142
+ onDestroyTimeout: external_exports.number().positive().optional(),
15143
+ /** @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. */
15144
+ waitUntilTimeout: external_exports.number().positive().optional(),
15145
+ stateSaveInterval: external_exports.number().positive().default(1e3),
15146
+ actionTimeout: external_exports.number().positive().default(6e4),
15147
+ connectionLivenessTimeout: external_exports.number().positive().default(2500),
15148
+ connectionLivenessInterval: external_exports.number().positive().default(5e3),
15149
+ /** @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. */
15150
+ noSleep: external_exports.boolean().default(false),
15151
+ sleepTimeout: external_exports.number().positive().default(3e4),
15152
+ maxQueueSize: external_exports.number().positive().default(1e3),
15153
+ /** Maximum pending one-shot and recurring schedules. */
15154
+ maxSchedules: external_exports.number().int().nonnegative().default(1e3),
15155
+ maxQueueMessageSize: external_exports.number().positive().default(64 * 1024),
15156
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15157
+ preloadMaxWorkflowBytes: external_exports.number().nonnegative().optional(),
15158
+ /** @deprecated Internal storage moved to SQLite and no longer uses KV preloading, so this option is ignored. Will be removed in 2.2.0. */
15159
+ preloadMaxConnectionsBytes: external_exports.number().nonnegative().optional()
15160
+ }).strict();
15161
+ var InstanceActorOptionsSchema = InstanceActorOptionsBaseSchema.prefault(() => ({}));
15162
+ var ActorOptionsSchema = GlobalActorOptionsBaseSchema.extend(
15163
+ InstanceActorOptionsBaseSchema.shape
15164
+ ).strict().prefault(() => ({}));
15165
+ var ActorConfigSchema = external_exports.object({
15166
+ onCreate: zFunction().optional(),
15167
+ onDestroy: zFunction().optional(),
15168
+ onMigrate: zFunction().optional(),
15169
+ onWake: zFunction().optional(),
15170
+ onSleep: zFunction().optional(),
15171
+ run: zRunHandler,
15172
+ onStateChange: zFunction().optional(),
15173
+ onBeforeConnect: zFunction().optional(),
15174
+ onConnect: zFunction().optional(),
15175
+ onDisconnect: zFunction().optional(),
15176
+ onBeforeActionResponse: zFunction().optional(),
15177
+ onRequest: zFunction().optional(),
15178
+ onWebSocket: zFunction().optional(),
15179
+ actions: zActionTree.default(() => ({})),
15180
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15181
+ connParamsSchema: external_exports.any().optional(),
15182
+ events: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15183
+ queues: external_exports.record(external_exports.string(), external_exports.any()).optional(),
15184
+ state: external_exports.any().optional(),
15185
+ createState: zFunction().optional(),
15186
+ connState: external_exports.any().optional(),
15187
+ createConnState: zFunction().optional(),
15188
+ vars: external_exports.any().optional(),
15189
+ db: external_exports.any().optional(),
15190
+ createVars: zFunction().optional(),
15191
+ options: ActorOptionsSchema,
15192
+ inspector: ActorInspectorConfigSchema.optional()
15193
+ }).strict().refine(
15194
+ (data) => !(data.state !== void 0 && data.createState !== void 0),
15195
+ {
15196
+ message: "Cannot define both 'state' and 'createState'",
15197
+ path: ["state"]
15198
+ }
15199
+ ).refine(
15200
+ (data) => !(data.connState !== void 0 && data.createConnState !== void 0),
15201
+ {
15202
+ message: "Cannot define both 'connState' and 'createConnState'",
15203
+ path: ["connState"]
15204
+ }
15205
+ ).refine(
15206
+ (data) => !(data.vars !== void 0 && data.createVars !== void 0),
15207
+ {
15208
+ message: "Cannot define both 'vars' and 'createVars'",
15209
+ path: ["vars"]
15210
+ }
15211
+ );
15212
+ var DocActorOptionsSchema = external_exports.object({
15213
+ name: external_exports.string().optional().describe("Display name for the actor in the Inspector UI."),
15214
+ icon: external_exports.string().optional().describe(
15215
+ "Icon for the actor in the Inspector UI. Can be an emoji (e.g., '\u{1F680}') or FontAwesome icon name (e.g., 'rocket')."
15216
+ ),
15217
+ enableActorRuntimeSocket: external_exports.boolean().optional().describe(
15218
+ "Enables the experimental Actor Runtime Socket for this actor. Default: false"
15219
+ ),
15220
+ createVarsTimeout: external_exports.number().optional().describe("Timeout in ms for createVars handler. Default: 5000"),
15221
+ createConnStateTimeout: external_exports.number().optional().describe(
15222
+ "Timeout in ms for createConnState handler. Default: 5000"
15223
+ ),
15224
+ onMigrateTimeout: external_exports.number().optional().describe("Timeout in ms for onMigrate handler. Default: 30000"),
15225
+ onBeforeConnectTimeout: external_exports.number().optional().describe(
15226
+ "Timeout in ms for onBeforeConnect handler. Default: 5000"
15227
+ ),
15228
+ onConnectTimeout: external_exports.number().optional().describe("Timeout in ms for onConnect handler. Default: 5000"),
15229
+ sleepGracePeriod: external_exports.number().optional().describe(
15230
+ `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}.`
15231
+ ),
15232
+ onDestroyTimeout: external_exports.number().optional().describe(
15233
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15234
+ ),
15235
+ waitUntilTimeout: external_exports.number().optional().describe(
15236
+ "Deprecated. Folded into sleepGracePeriod, which now bounds the entire graceful shutdown window for both sleep and destroy. Will be removed in 2.2.0."
15237
+ ),
15238
+ stateSaveInterval: external_exports.number().optional().describe(
15239
+ "Interval in ms between automatic state saves. Default: 1000"
15240
+ ),
15241
+ actionTimeout: external_exports.number().optional().describe("Timeout in ms for action handlers. Default: 60000"),
15242
+ connectionLivenessTimeout: external_exports.number().optional().describe(
15243
+ "Timeout in ms for connection liveness checks. Default: 2500"
15244
+ ),
15245
+ connectionLivenessInterval: external_exports.number().optional().describe(
15246
+ "Interval in ms between connection liveness checks. Default: 5000"
15247
+ ),
15248
+ noSleep: external_exports.boolean().optional().describe(
15249
+ "Deprecated. If true, the actor will never sleep. Use c.keepAwake(promise) to scope keep-awake to a specific operation instead. Default: false"
15250
+ ),
15251
+ sleepTimeout: external_exports.number().optional().describe(
15252
+ "Time in ms of inactivity before the actor sleeps. Default: 30000"
15253
+ ),
15254
+ maxQueueSize: external_exports.number().optional().describe(
15255
+ "Maximum number of queue messages before rejecting new messages. Default: 1000"
15256
+ ),
15257
+ maxSchedules: external_exports.number().int().nonnegative().optional().describe(
15258
+ "Maximum pending one-shot and recurring schedules before rejecting new schedules. Default: 1000"
15259
+ ),
15260
+ maxQueueMessageSize: external_exports.number().optional().describe(
15261
+ "Maximum size of each queue message in bytes. Default: 65536"
15262
+ ),
15263
+ canHibernateWebSocket: external_exports.boolean().optional().describe(
15264
+ "Whether WebSockets using onWebSocket can be hibernated. WebSockets using actions/events are hibernatable by default. Default: false"
15265
+ )
15266
+ }).describe("Actor options for timeouts and behavior configuration.");
15267
+ var DocActorConfigSchema = external_exports.object({
15268
+ state: external_exports.unknown().optional().describe(
15269
+ "Initial state value for the actor. Cannot be used with createState."
15270
+ ),
15271
+ createState: external_exports.unknown().optional().describe(
15272
+ "Function to create initial state. Receives context and input. Cannot be used with state."
15273
+ ),
15274
+ connState: external_exports.unknown().optional().describe(
15275
+ "Initial connection state value. Cannot be used with createConnState."
15276
+ ),
15277
+ createConnState: external_exports.unknown().optional().describe(
15278
+ "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."
15279
+ ),
15280
+ vars: external_exports.unknown().optional().describe(
15281
+ "Initial ephemeral variables value. Cannot be used with createVars."
15282
+ ),
15283
+ createVars: external_exports.unknown().optional().describe(
15284
+ "Function to create ephemeral variables. Receives context and driver context. Cannot be used with vars."
15285
+ ),
15286
+ db: external_exports.unknown().optional().describe("Database provider instance for the actor."),
15287
+ onCreate: external_exports.unknown().optional().describe(
15288
+ "Called when the actor is first initialized. Use to initialize state."
15289
+ ),
15290
+ onDestroy: external_exports.unknown().optional().describe("Called when the actor is destroyed."),
15291
+ onMigrate: external_exports.unknown().optional().describe(
15292
+ "Called on every actor start after persisted state loads and before onWake. Use for repeatable schema migrations."
15293
+ ),
15294
+ onWake: external_exports.unknown().optional().describe(
15295
+ "Called when the actor wakes up and is ready to receive connections and actions."
15296
+ ),
15297
+ onSleep: external_exports.unknown().optional().describe(
15298
+ "Called when the actor is stopping or sleeping. Use to clean up resources."
15299
+ ),
15300
+ run: external_exports.unknown().optional().describe(
15301
+ "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."
15302
+ ),
15303
+ onStateChange: external_exports.unknown().optional().describe(
15304
+ "Called when the actor's state changes. State changes within this hook won't trigger recursion."
15305
+ ),
15306
+ onBeforeConnect: external_exports.unknown().optional().describe(
15307
+ "Called before a client connects. Throw an error to reject the connection. The pending connection is not visible in c.conns while this runs."
15308
+ ),
15309
+ onConnect: external_exports.unknown().optional().describe(
15310
+ "Called when a client successfully connects. The connection is visible in c.conns before this runs."
15311
+ ),
15312
+ onDisconnect: external_exports.unknown().optional().describe("Called when a client disconnects."),
15313
+ onBeforeActionResponse: external_exports.unknown().optional().describe(
15314
+ "Called before sending an action response. Use to transform output."
15315
+ ),
15316
+ onRequest: external_exports.unknown().optional().describe(
15317
+ "Called for raw HTTP requests to /actors/{name}/http/* endpoints."
15318
+ ),
15319
+ onWebSocket: external_exports.unknown().optional().describe(
15320
+ "Called for raw WebSocket connections to /actors/{name}/websocket/* endpoints."
15321
+ ),
15322
+ actions: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15323
+ "Tree of action names or nested groups to handler functions. Nested paths use dot-separated low-level action names. Defaults to an empty object."
15324
+ ),
15325
+ actionInputSchemas: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe(
15326
+ "Optional schemas for validating action argument tuples in native runtimes. May mirror nested action groups or use dot-separated low-level action names."
15327
+ ),
15328
+ connParamsSchema: external_exports.unknown().optional().describe(
15329
+ "Optional schema for validating connection params in native runtimes."
15330
+ ),
15331
+ events: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of event names to schemas."),
15332
+ queues: external_exports.record(external_exports.string(), external_exports.unknown()).optional().describe("Map of queue names to schemas."),
15333
+ options: DocActorOptionsSchema.optional()
15334
+ }).describe("Actor configuration passed to the actor() function.");
15335
+
15336
+ // ../rivetkit/dist/tsup/chunk-JI6GZ2C2.js
15337
+ var EMPTY_KEY = "/";
15338
+ var KEY_SEPARATOR = "/";
15339
+ var KEYS = {
15340
+ PERSIST_DATA: Uint8Array.from([1]),
15341
+ CONN_PREFIX: Uint8Array.from([2]),
15342
+ INSPECTOR_TOKEN: Uint8Array.from([3]),
15343
+ KV: Uint8Array.from([4]),
15344
+ QUEUE_PREFIX: Uint8Array.from([5]),
15345
+ LAST_PUSHED_ALARM: Uint8Array.from([6]),
15346
+ WORKFLOW_PREFIX: Uint8Array.from([6]),
15347
+ TRACES_PREFIX: Uint8Array.from([7])
15348
+ };
15349
+ var STORAGE_VERSION = {
15350
+ QUEUE: 1,
15351
+ WORKFLOW: 1,
15352
+ TRACES: 1
15353
+ };
15354
+ var STORAGE_VERSION_BYTES = {
15355
+ QUEUE: Uint8Array.from([STORAGE_VERSION.QUEUE]),
15356
+ WORKFLOW: Uint8Array.from([STORAGE_VERSION.WORKFLOW]),
15357
+ TRACES: Uint8Array.from([STORAGE_VERSION.TRACES])
15358
+ };
15359
+ var QUEUE_NAMESPACE = {
15360
+ METADATA: Uint8Array.from([1]),
15361
+ MESSAGES: Uint8Array.from([2])
15362
+ };
15363
+ function concatPrefix(prefix, suffix) {
15364
+ const merged = new Uint8Array(prefix.length + suffix.length);
15365
+ merged.set(prefix, 0);
15366
+ merged.set(suffix, prefix.length);
15367
+ return merged;
15211
15368
  }
15212
- function base64DecodeToUint8Array(base643) {
15213
- if (typeof Buffer !== "undefined") {
15214
- return new Uint8Array(Buffer.from(base643, "base64"));
15215
- }
15216
- const binary = atob(base643);
15217
- const bytes = new Uint8Array(binary.length);
15218
- for (let i = 0; i < binary.length; i++) {
15219
- bytes[i] = binary.charCodeAt(i);
15369
+ var QUEUE_STORAGE_PREFIX = concatPrefix(
15370
+ KEYS.QUEUE_PREFIX,
15371
+ STORAGE_VERSION_BYTES.QUEUE
15372
+ );
15373
+ var QUEUE_METADATA_KEY = concatPrefix(
15374
+ QUEUE_STORAGE_PREFIX,
15375
+ QUEUE_NAMESPACE.METADATA
15376
+ );
15377
+ var QUEUE_MESSAGES_PREFIX = concatPrefix(
15378
+ QUEUE_STORAGE_PREFIX,
15379
+ QUEUE_NAMESPACE.MESSAGES
15380
+ );
15381
+ var WORKFLOW_STORAGE_PREFIX = concatPrefix(
15382
+ KEYS.WORKFLOW_PREFIX,
15383
+ STORAGE_VERSION_BYTES.WORKFLOW
15384
+ );
15385
+ var TRACES_STORAGE_PREFIX = concatPrefix(
15386
+ KEYS.TRACES_PREFIX,
15387
+ STORAGE_VERSION_BYTES.TRACES
15388
+ );
15389
+ function serializeActorKey(key) {
15390
+ if (key.length === 0) {
15391
+ return EMPTY_KEY;
15220
15392
  }
15221
- return bytes;
15222
- }
15223
- function base64DecodeToArrayBuffer(base643) {
15224
- return base64DecodeToUint8Array(base643).buffer;
15225
- }
15226
- function jsonStringifyCompat(input) {
15227
- return JSON.stringify(input, (_key, value) => {
15228
- if (typeof value === "bigint") {
15229
- return [JSON_COMPAT_BIGINT, value.toString()];
15230
- }
15231
- if (value instanceof ArrayBuffer) {
15232
- return [JSON_COMPAT_ARRAY_BUFFER, base64EncodeArrayBuffer(value)];
15233
- }
15234
- if (value instanceof Uint8Array) {
15235
- return [JSON_COMPAT_UINT8_ARRAY, base64EncodeUint8Array(value)];
15236
- }
15237
- if (Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && value[0].startsWith("$")) {
15238
- return [`$${value[0]}`, value[1]];
15393
+ const escapedParts = key.map((part) => {
15394
+ if (part === "") {
15395
+ return "\\0";
15239
15396
  }
15240
- return value;
15397
+ let escaped = part.replace(/\\/g, "\\\\");
15398
+ escaped = escaped.replace(/\//g, `\\${KEY_SEPARATOR}`);
15399
+ return escaped;
15241
15400
  });
15401
+ return escapedParts.join(KEY_SEPARATOR);
15242
15402
  }
15243
- function jsonParseCompat(input) {
15244
- return reviveJsonCompatValue(JSON.parse(input));
15245
- }
15246
- function uint8ArrayToBase642(uint8Array) {
15247
- if (typeof Buffer !== "undefined") {
15248
- return Buffer.from(uint8Array).toString("base64");
15403
+ function deserializeActorKey(keyString) {
15404
+ if (keyString === void 0 || keyString === null || keyString === EMPTY_KEY) {
15405
+ return [];
15249
15406
  }
15250
- let binary = "";
15251
- const len = uint8Array.byteLength;
15252
- for (let i = 0; i < len; i++) {
15253
- binary += String.fromCharCode(uint8Array[i]);
15407
+ const parts = [];
15408
+ let currentPart = "";
15409
+ let escaping = false;
15410
+ let isEmptyStringMarker = false;
15411
+ for (let i = 0; i < keyString.length; i++) {
15412
+ const char = keyString[i];
15413
+ if (escaping) {
15414
+ if (char === "0") {
15415
+ isEmptyStringMarker = true;
15416
+ } else {
15417
+ currentPart += char;
15418
+ }
15419
+ escaping = false;
15420
+ } else if (char === "\\") {
15421
+ escaping = true;
15422
+ } else if (char === KEY_SEPARATOR) {
15423
+ if (isEmptyStringMarker) {
15424
+ parts.push("");
15425
+ isEmptyStringMarker = false;
15426
+ } else {
15427
+ parts.push(currentPart);
15428
+ }
15429
+ currentPart = "";
15430
+ } else {
15431
+ currentPart += char;
15432
+ }
15254
15433
  }
15255
- return btoa(binary);
15256
- }
15257
- function contentTypeForEncoding(encoding) {
15258
- if (encoding === "json") {
15259
- return "application/json";
15260
- } else if (encoding === "cbor" || encoding === "bare") {
15261
- return "application/octet-stream";
15262
- } else {
15263
- assertUnreachable(encoding);
15434
+ if (escaping) {
15435
+ parts.push(`${currentPart}\\`);
15436
+ } else if (isEmptyStringMarker) {
15437
+ parts.push("");
15438
+ } else if (currentPart !== "" || parts.length > 0) {
15439
+ parts.push(currentPart);
15264
15440
  }
15441
+ return parts;
15265
15442
  }
15266
- function encodeCborCompat(value) {
15267
- return cbor.encode(encodeJsonCompatValue(value));
15443
+ function makePrefixedKey(key) {
15444
+ const prefixed = new Uint8Array(KEYS.KV.length + key.length);
15445
+ prefixed.set(KEYS.KV, 0);
15446
+ prefixed.set(key, KEYS.KV.length);
15447
+ return prefixed;
15268
15448
  }
15269
- function decodeCborCompat(buffer) {
15270
- return reviveJsonCompatValue(cbor.decode(buffer));
15449
+ function removePrefixFromKey(prefixedKey) {
15450
+ return prefixedKey.slice(KEYS.KV.length);
15271
15451
  }
15272
- function serializeWithEncoding(encoding, value, versionedDataHandler, version2, zodSchema, toJson, toBare) {
15273
- if (encoding === "json") {
15274
- const jsonValue = toJson(value);
15275
- const validated = zodSchema.parse(jsonValue);
15276
- return jsonStringifyCompat(validated);
15277
- } else if (encoding === "cbor") {
15278
- const jsonValue = toJson(value);
15279
- const validated = zodSchema.parse(jsonValue);
15280
- return cbor.encode(validated);
15281
- } else if (encoding === "bare") {
15282
- if (!versionedDataHandler) {
15283
- throw new Error(
15284
- "VersionedDataHandler is required for 'bare' encoding"
15285
- );
15286
- }
15287
- if (version2 === void 0) {
15288
- throw new Error("version is required for 'bare' encoding");
15452
+
15453
+ // ../rivetkit/dist/tsup/chunk-7AFZMFPQ.js
15454
+ var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15455
+ var AsyncMutex = class {
15456
+ #locked = false;
15457
+ #waiting = [];
15458
+ async acquire() {
15459
+ while (this.#locked) {
15460
+ await new Promise((resolve) => this.#waiting.push(resolve));
15289
15461
  }
15290
- const bareValue = toBare(value);
15291
- return versionedDataHandler.serializeWithEmbeddedVersion(
15292
- bareValue,
15293
- version2
15294
- );
15295
- } else {
15296
- assertUnreachable(encoding);
15462
+ this.#locked = true;
15297
15463
  }
15298
- }
15299
- function deserializeWithEncoding(encoding, buffer, versionedDataHandler, zodSchema, fromJson, fromBare) {
15300
- if (encoding === "json") {
15301
- let parsed;
15302
- if (typeof buffer === "string") {
15303
- parsed = jsonParseCompat(buffer);
15304
- } else {
15305
- const decoder = new TextDecoder("utf-8");
15306
- const jsonString = decoder.decode(buffer);
15307
- parsed = jsonParseCompat(jsonString);
15464
+ release() {
15465
+ this.#locked = false;
15466
+ const next = this.#waiting.shift();
15467
+ if (next) {
15468
+ next();
15308
15469
  }
15309
- const validated = zodSchema.parse(parsed);
15310
- return fromJson(validated);
15311
- } else if (encoding === "cbor") {
15312
- (0, import_invariant.default)(
15313
- typeof buffer !== "string",
15314
- "buffer cannot be string for cbor encoding"
15315
- );
15316
- const decoded = decodeCborCompat(buffer);
15317
- const validated = zodSchema.parse(decoded);
15318
- return fromJson(validated);
15319
- } else if (encoding === "bare") {
15320
- (0, import_invariant.default)(
15321
- typeof buffer !== "string",
15322
- "buffer cannot be string for bare encoding"
15323
- );
15324
- if (!versionedDataHandler) {
15325
- throw new Error(
15326
- "VersionedDataHandler is required for 'bare' encoding"
15327
- );
15470
+ }
15471
+ async run(fn) {
15472
+ await this.acquire();
15473
+ try {
15474
+ return await fn();
15475
+ } finally {
15476
+ this.release();
15328
15477
  }
15329
- const bareValue = versionedDataHandler.deserializeWithEmbeddedVersion(buffer);
15330
- return fromBare(bareValue);
15331
- } else {
15332
- assertUnreachable(encoding);
15333
15478
  }
15334
- }
15479
+ };
15335
15480
 
15336
- // ../rivetkit/dist/tsup/chunk-HTXJT6DN.js
15481
+ // ../rivetkit/dist/tsup/chunk-KUWK4UNH.js
15337
15482
  function logger() {
15338
15483
  return getLogger("actor-client");
15339
15484
  }
@@ -15356,50 +15501,22 @@ async function importWebSocket() {
15356
15501
  _WebSocket = ws.default;
15357
15502
  logger().debug("using websocket from npm");
15358
15503
  } catch {
15359
- _WebSocket = class MockWebSocket {
15360
- constructor() {
15361
- throw new Error(
15362
- 'WebSocket support requires installing the "ws" peer dependency.'
15363
- );
15364
- }
15365
- };
15366
- logger().debug("using mock websocket");
15367
- }
15368
- }
15369
- return _WebSocket;
15370
- })();
15371
- return webSocketPromise;
15372
- }
15373
-
15374
- // ../rivetkit/dist/tsup/chunk-7AFZMFPQ.js
15375
- var MIGRATION_TRANSACTION_TIMEOUT_MS = 5 * 6e4;
15376
- var AsyncMutex = class {
15377
- #locked = false;
15378
- #waiting = [];
15379
- async acquire() {
15380
- while (this.#locked) {
15381
- await new Promise((resolve) => this.#waiting.push(resolve));
15382
- }
15383
- this.#locked = true;
15384
- }
15385
- release() {
15386
- this.#locked = false;
15387
- const next = this.#waiting.shift();
15388
- if (next) {
15389
- next();
15390
- }
15391
- }
15392
- async run(fn) {
15393
- await this.acquire();
15394
- try {
15395
- return await fn();
15396
- } finally {
15397
- this.release();
15504
+ _WebSocket = class MockWebSocket {
15505
+ constructor() {
15506
+ throw new Error(
15507
+ 'WebSocket support requires installing the "ws" peer dependency.'
15508
+ );
15509
+ }
15510
+ };
15511
+ logger().debug("using mock websocket");
15512
+ }
15398
15513
  }
15399
- }
15400
- };
15514
+ return _WebSocket;
15515
+ })();
15516
+ return webSocketPromise;
15517
+ }
15401
15518
 
15402
- // ../rivetkit/dist/tsup/chunk-2Y5LK2Q3.js
15519
+ // ../rivetkit/dist/tsup/chunk-J2TA4HLA.js
15403
15520
  var import_invariant2 = __toESM(require_invariant(), 1);
15404
15521
 
15405
15522
  // ../../../node_modules/.pnpm/p-retry@6.2.1/node_modules/p-retry/index.js
@@ -15577,7 +15694,7 @@ function createVersionedDataHandler(config3) {
15577
15694
  return new VersionedDataHandler(config3);
15578
15695
  }
15579
15696
 
15580
- // ../rivetkit/dist/tsup/chunk-2Y5LK2Q3.js
15697
+ // ../rivetkit/dist/tsup/chunk-J2TA4HLA.js
15581
15698
  var import_invariant3 = __toESM(require_invariant(), 1);
15582
15699
  var import_invariant4 = __toESM(require_invariant(), 1);
15583
15700
  var PATH_CONNECT = "/connect";
@@ -15586,6 +15703,7 @@ var PATH_WEBSOCKET_PREFIX = "/websocket/";
15586
15703
  var HEADER_ACTOR_QUERY = "x-rivet-query";
15587
15704
  var HEADER_ENCODING = "x-rivet-encoding";
15588
15705
  var HEADER_CONN_PARAMS = "x-rivet-conn-params";
15706
+ var HEADER_ORIGINAL_REQUEST_URL = "x-rivet-internal-original-request-url";
15589
15707
  var HEADER_ACTOR_ID = "x-rivet-actor";
15590
15708
  var HEADER_ACTOR_GENERATION = "x-rivet-actor-generation";
15591
15709
  var HEADER_ACTOR_KEY = "x-rivet-actor-key";
@@ -17638,6 +17756,18 @@ async function checkForSchedulingError(group, code, actorId, query, driver) {
17638
17756
  }
17639
17757
  return null;
17640
17758
  }
17759
+ function isUrlLike(value) {
17760
+ return typeof value === "object" && value !== null && typeof value.href === "string" && typeof value.pathname === "string" && typeof value.search === "string";
17761
+ }
17762
+ function isRequestLike(value) {
17763
+ return typeof value === "object" && value !== null && typeof value.url === "string" && typeof value.method === "string" && isHeadersLike(value.headers);
17764
+ }
17765
+ function isResponseLike(value) {
17766
+ return typeof value === "object" && value !== null && typeof value.status === "number" && isHeadersLike(value.headers) && typeof value.arrayBuffer === "function";
17767
+ }
17768
+ function isHeadersLike(value) {
17769
+ return typeof value === "object" && value !== null && typeof value.entries === "function";
17770
+ }
17641
17771
  function* walkErrorChain(error46, maxDepth = 8) {
17642
17772
  let current = error46;
17643
17773
  let depth = 0;
@@ -18063,14 +18193,17 @@ function createQueueSender(senderOptions) {
18063
18193
  }
18064
18194
  async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18065
18195
  let path2;
18196
+ let originalUrl;
18066
18197
  let mergedInit = init || {};
18067
18198
  if (typeof input === "string") {
18068
18199
  path2 = input;
18069
- } else if (input instanceof URL) {
18200
+ } else if (isUrlLike(input)) {
18070
18201
  path2 = input.pathname + input.search;
18071
- } else if (input instanceof Request) {
18202
+ originalUrl = input.toString();
18203
+ } else if (isRequestLike(input)) {
18072
18204
  const url2 = new URL(input.url);
18073
18205
  path2 = url2.pathname + url2.search;
18206
+ originalUrl = url2.toString();
18074
18207
  const requestHeaders = new Headers(input.headers);
18075
18208
  const initHeaders = new Headers((init == null ? void 0 : init.headers) || {});
18076
18209
  const mergedHeaders = new Headers(requestHeaders);
@@ -18112,6 +18245,10 @@ async function rawHttpFetch(driver, target, params, input, init, options = {}) {
18112
18245
  const normalizedPath = path2.startsWith("/") ? path2.slice(1) : path2;
18113
18246
  const url2 = new URL(`http://actor/request/${normalizedPath}`);
18114
18247
  const proxyRequestHeaders = new Headers(mergedInit.headers);
18248
+ proxyRequestHeaders.delete(HEADER_ORIGINAL_REQUEST_URL);
18249
+ if (originalUrl) {
18250
+ proxyRequestHeaders.set(HEADER_ORIGINAL_REQUEST_URL, originalUrl);
18251
+ }
18115
18252
  if (params) {
18116
18253
  proxyRequestHeaders.set(HEADER_CONN_PARAMS, JSON.stringify(params));
18117
18254
  }
@@ -18580,6 +18717,7 @@ var ActorHandleRaw = class {
18580
18717
  async #fetchWithResolvedActor(input, init) {
18581
18718
  const maxAttempts = this.#getDynamicQueryMaxAttempts();
18582
18719
  let useQueryTarget = false;
18720
+ const retryableRequest = isRequestLike(input) ? input.clone() : void 0;
18583
18721
  const { skipReadyWait, ...requestInit } = init ?? {};
18584
18722
  const gatewayOptions = resolveActorGatewayOptions(
18585
18723
  this.#gatewayOptions,
@@ -18599,7 +18737,7 @@ var ActorHandleRaw = class {
18599
18737
  this.#driver,
18600
18738
  target,
18601
18739
  this.#params,
18602
- input,
18740
+ retryableRequest ? retryableRequest.clone() : input,
18603
18741
  requestInit,
18604
18742
  gatewayOptions
18605
18743
  );
@@ -19024,6 +19162,23 @@ function createClientWithDriver(driver, config3 = {}) {
19024
19162
  }
19025
19163
  function createActorProxy(handle) {
19026
19164
  const methodCache = /* @__PURE__ */ new Map();
19165
+ const actionPath = (name) => {
19166
+ let method2 = methodCache.get(name);
19167
+ if (method2) return method2;
19168
+ method2 = new Proxy(
19169
+ (...args) => handle.action({ name, args }),
19170
+ {
19171
+ get(target, prop) {
19172
+ if (typeof prop === "symbol")
19173
+ return Reflect.get(target, prop);
19174
+ if (prop === "then") return void 0;
19175
+ return actionPath(`${name}.${prop}`);
19176
+ }
19177
+ }
19178
+ );
19179
+ methodCache.set(name, method2);
19180
+ return method2;
19181
+ };
19027
19182
  return new Proxy(handle, {
19028
19183
  get(target, prop, receiver) {
19029
19184
  if (typeof prop === "symbol") {
@@ -19038,12 +19193,7 @@ function createActorProxy(handle) {
19038
19193
  }
19039
19194
  if (typeof prop === "string") {
19040
19195
  if (prop === "then") return void 0;
19041
- let method2 = methodCache.get(prop);
19042
- if (!method2) {
19043
- method2 = (...args) => target.action({ name: prop, args });
19044
- methodCache.set(prop, method2);
19045
- }
19046
- return method2;
19196
+ return actionPath(prop);
19047
19197
  }
19048
19198
  },
19049
19199
  // Support for 'in' operator
@@ -19061,6 +19211,7 @@ function createActorProxy(handle) {
19061
19211
  },
19062
19212
  // Support proper property descriptors
19063
19213
  getOwnPropertyDescriptor(target, prop) {
19214
+ if (prop === "then") return void 0;
19064
19215
  const targetDescriptor = Reflect.getOwnPropertyDescriptor(
19065
19216
  target,
19066
19217
  prop
@@ -19073,7 +19224,7 @@ function createActorProxy(handle) {
19073
19224
  configurable: true,
19074
19225
  enumerable: false,
19075
19226
  writable: false,
19076
- value: (...args) => target.action({ name: prop, args })
19227
+ value: actionPath(prop)
19077
19228
  };
19078
19229
  }
19079
19230
  return void 0;
@@ -20309,103 +20460,6 @@ function convertRegistryConfigToClientConfig(config3) {
20309
20460
  devtools: typeof window !== "undefined" && (((_a2 = window == null ? void 0 : window.location) == null ? void 0 : _a2.hostname) === "127.0.0.1" || ((_b = window == null ? void 0 : window.location) == null ? void 0 : _b.hostname) === "localhost")
20310
20461
  };
20311
20462
  }
20312
- function logger2() {
20313
- return getLogger("engine-client");
20314
- }
20315
- function getEndpoint(config3) {
20316
- return config3.endpoint ?? "http://127.0.0.1:6420";
20317
- }
20318
- async function apiCall(config3, method2, path2, body) {
20319
- const endpoint = getEndpoint(config3);
20320
- const url2 = combineUrlPath(endpoint, path2, {
20321
- namespace: config3.namespace
20322
- });
20323
- logger2().debug({ msg: "making api call", method: method2, url: url2 });
20324
- const headers = {
20325
- ...config3.headers
20326
- };
20327
- if (config3.token) {
20328
- headers.Authorization = `Bearer ${config3.token}`;
20329
- }
20330
- return await sendHttpRequest({
20331
- method: method2,
20332
- url: url2,
20333
- headers,
20334
- body,
20335
- encoding: "json",
20336
- skipParseResponse: false,
20337
- requestVersionedDataHandler: void 0,
20338
- requestVersion: void 0,
20339
- responseVersionedDataHandler: void 0,
20340
- responseVersion: void 0,
20341
- requestZodSchema: external_exports.any(),
20342
- responseZodSchema: external_exports.any(),
20343
- // Identity conversions (passthrough for generic API calls)
20344
- requestToJson: (value) => value,
20345
- requestToBare: (value) => value,
20346
- responseFromJson: (value) => value,
20347
- responseFromBare: (value) => value
20348
- });
20349
- }
20350
- async function getActor(config3, _, actorId) {
20351
- return apiCall(
20352
- config3,
20353
- "GET",
20354
- `/actors?actor_ids=${encodeURIComponent(actorId)}`
20355
- );
20356
- }
20357
- async function getActorByKey(config3, name, key) {
20358
- const serializedKey = serializeActorKey(key);
20359
- return apiCall(
20360
- config3,
20361
- "GET",
20362
- `/actors?name=${encodeURIComponent(name)}&key=${encodeURIComponent(serializedKey)}`
20363
- );
20364
- }
20365
- async function listActorsByName(config3, name) {
20366
- return apiCall(
20367
- config3,
20368
- "GET",
20369
- `/actors?name=${encodeURIComponent(name)}`
20370
- );
20371
- }
20372
- async function getOrCreateActor(config3, request) {
20373
- return apiCall(
20374
- config3,
20375
- "PUT",
20376
- `/actors`,
20377
- request
20378
- );
20379
- }
20380
- async function createActor(config3, request) {
20381
- return apiCall(
20382
- config3,
20383
- "POST",
20384
- `/actors`,
20385
- request
20386
- );
20387
- }
20388
- async function destroyActor(config3, actorId) {
20389
- return apiCall(
20390
- config3,
20391
- "DELETE",
20392
- `/actors/${encodeURIComponent(actorId)}`
20393
- );
20394
- }
20395
- async function getMetadata(config3) {
20396
- return apiCall(config3, "GET", `/metadata`);
20397
- }
20398
- async function getDatacenters(config3) {
20399
- return apiCall(config3, "GET", `/datacenters`);
20400
- }
20401
- async function updateRunnerConfig(config3, runnerName, request) {
20402
- return apiCall(
20403
- config3,
20404
- "PUT",
20405
- `/runner-configs/${runnerName}`,
20406
- request
20407
- );
20408
- }
20409
20463
  function shouldSkipReadyWait(options = {}) {
20410
20464
  return options.skipReadyWait === true;
20411
20465
  }
@@ -20416,23 +20470,19 @@ async function sendHttpRequestToGateway(runConfig, gatewayUrl, actorRequest, opt
20416
20470
  if (actorRequest.bodyUsed) {
20417
20471
  throw new Error("Request body has already been consumed");
20418
20472
  }
20419
- const reqBody = await actorRequest.arrayBuffer();
20420
- if (reqBody.byteLength !== 0) {
20421
- bodyToSend = reqBody;
20473
+ if (actorRequest.body) {
20474
+ bodyToSend = actorRequest.body;
20422
20475
  guardHeaders.delete("transfer-encoding");
20423
20476
  guardHeaders.delete("content-length");
20424
20477
  }
20425
20478
  }
20426
- const guardRequest = new Request(gatewayUrl, {
20479
+ return fetch(gatewayUrl, {
20427
20480
  method: actorRequest.method,
20428
20481
  headers: guardHeaders,
20429
20482
  body: bodyToSend,
20430
- signal: actorRequest.signal
20483
+ signal: actorRequest.signal,
20484
+ ...bodyToSend ? { duplex: "half" } : {}
20431
20485
  });
20432
- return mutableResponse(await fetch(guardRequest));
20433
- }
20434
- function mutableResponse(fetchRes) {
20435
- return new Response(fetchRes.body, fetchRes);
20436
20486
  }
20437
20487
  function buildGuardHeaders(runConfig, actorRequest, options) {
20438
20488
  const headers = new Headers();
@@ -20493,6 +20543,9 @@ function setRemoteHibernatableWebSocketAckTestHooks(websocket, token, enabled) {
20493
20543
  enabled
20494
20544
  );
20495
20545
  }
20546
+ function logger2() {
20547
+ return getLogger("engine-client");
20548
+ }
20496
20549
  var BufferedRemoteWebSocket = class {
20497
20550
  CONNECTING = 0;
20498
20551
  OPEN = 1;
@@ -20770,6 +20823,100 @@ function buildWebSocketProtocols(runConfig, encoding, params, ackHookToken, targ
20770
20823
  }
20771
20824
  return protocols;
20772
20825
  }
20826
+ function getEndpoint(config3) {
20827
+ return config3.endpoint ?? "http://127.0.0.1:6420";
20828
+ }
20829
+ async function apiCall(config3, method2, path2, body) {
20830
+ const endpoint = getEndpoint(config3);
20831
+ const url2 = combineUrlPath(endpoint, path2, {
20832
+ namespace: config3.namespace
20833
+ });
20834
+ logger2().debug({ msg: "making api call", method: method2, url: url2 });
20835
+ const headers = {
20836
+ ...config3.headers
20837
+ };
20838
+ if (config3.token) {
20839
+ headers.Authorization = `Bearer ${config3.token}`;
20840
+ }
20841
+ return await sendHttpRequest({
20842
+ method: method2,
20843
+ url: url2,
20844
+ headers,
20845
+ body,
20846
+ encoding: "json",
20847
+ skipParseResponse: false,
20848
+ requestVersionedDataHandler: void 0,
20849
+ requestVersion: void 0,
20850
+ responseVersionedDataHandler: void 0,
20851
+ responseVersion: void 0,
20852
+ requestZodSchema: external_exports.any(),
20853
+ responseZodSchema: external_exports.any(),
20854
+ // Identity conversions (passthrough for generic API calls)
20855
+ requestToJson: (value) => value,
20856
+ requestToBare: (value) => value,
20857
+ responseFromJson: (value) => value,
20858
+ responseFromBare: (value) => value
20859
+ });
20860
+ }
20861
+ async function getActor(config3, _, actorId) {
20862
+ return apiCall(
20863
+ config3,
20864
+ "GET",
20865
+ `/actors?actor_ids=${encodeURIComponent(actorId)}`
20866
+ );
20867
+ }
20868
+ async function getActorByKey(config3, name, key) {
20869
+ const serializedKey = serializeActorKey(key);
20870
+ return apiCall(
20871
+ config3,
20872
+ "GET",
20873
+ `/actors?name=${encodeURIComponent(name)}&key=${encodeURIComponent(serializedKey)}`
20874
+ );
20875
+ }
20876
+ async function listActorsByName(config3, name) {
20877
+ return apiCall(
20878
+ config3,
20879
+ "GET",
20880
+ `/actors?name=${encodeURIComponent(name)}`
20881
+ );
20882
+ }
20883
+ async function getOrCreateActor(config3, request) {
20884
+ return apiCall(
20885
+ config3,
20886
+ "PUT",
20887
+ `/actors`,
20888
+ request
20889
+ );
20890
+ }
20891
+ async function createActor(config3, request) {
20892
+ return apiCall(
20893
+ config3,
20894
+ "POST",
20895
+ `/actors`,
20896
+ request
20897
+ );
20898
+ }
20899
+ async function destroyActor(config3, actorId) {
20900
+ return apiCall(
20901
+ config3,
20902
+ "DELETE",
20903
+ `/actors/${encodeURIComponent(actorId)}`
20904
+ );
20905
+ }
20906
+ async function getMetadata(config3) {
20907
+ return apiCall(config3, "GET", `/metadata`);
20908
+ }
20909
+ async function getDatacenters(config3) {
20910
+ return apiCall(config3, "GET", `/datacenters`);
20911
+ }
20912
+ async function updateRunnerConfig(config3, runnerName, request) {
20913
+ return apiCall(
20914
+ config3,
20915
+ "PUT",
20916
+ `/runner-configs/${runnerName}`,
20917
+ request
20918
+ );
20919
+ }
20773
20920
  var metadataLookupCache = /* @__PURE__ */ new Map();
20774
20921
  async function lookupMetadataCached(config3) {
20775
20922
  const endpoint = getEndpoint(config3);
@@ -22528,6 +22675,8 @@ function actor(input) {
22528
22675
  input == null ? void 0 : input.options
22529
22676
  );
22530
22677
  const config3 = ActorConfigSchema.parse(input);
22678
+ flattenActionHandlers(config3.actions);
22679
+ flattenActionInputSchemas(config3.actions, config3.actionInputSchemas);
22531
22680
  return new ActorDefinition(config3);
22532
22681
  }
22533
22682
  function isStaticActorDefinition(definition) {
@@ -23184,7 +23333,7 @@ var RegistryConfigSchema = external_exports.object({
23184
23333
  config3.engineHost,
23185
23334
  config3.enginePort
23186
23335
  );
23187
- const endpoint = config3.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? buildEngineEndpoint(ENGINE_HOST, ENGINE_PORT) : void 0);
23336
+ const endpoint = config3.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? localEngineEndpoint : void 0);
23188
23337
  const validateServerlessEndpoint = Boolean(
23189
23338
  config3.startEngine || parsedEndpoint
23190
23339
  );
@@ -23201,7 +23350,7 @@ var RegistryConfigSchema = external_exports.object({
23201
23350
  path: ["serverless", "publicEndpoint"]
23202
23351
  });
23203
23352
  }
23204
- const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && config3.startEngine ? endpoint : void 0);
23353
+ const publicEndpoint = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.endpoint) ?? (isDevEnv && !parsedEndpoint ? endpoint : void 0);
23205
23354
  const publicNamespace = parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.namespace;
23206
23355
  const publicToken = (parsedPublicEndpoint == null ? void 0 : parsedPublicEndpoint.token) ?? config3.serverless.publicToken;
23207
23356
  return {
@@ -23807,6 +23956,36 @@ function toNapiSqlBatchStatement(statement) {
23807
23956
  function toNapiBuffer(value) {
23808
23957
  return Buffer.from(value);
23809
23958
  }
23959
+ function toNapiApplication(application) {
23960
+ return async (error46, request) => {
23961
+ if (error46) throw error46;
23962
+ if (!request) {
23963
+ throw new Error("application fetch callback received no request");
23964
+ }
23965
+ const response = await application(
23966
+ {
23967
+ ...request,
23968
+ body: new Uint8Array(request.body),
23969
+ cancelToken: request.cancelToken
23970
+ },
23971
+ request.responseBodyStream ? fromNapiHttpResponseBodyStream(
23972
+ request.responseBodyStream
23973
+ ) : void 0
23974
+ );
23975
+ return {
23976
+ ...response,
23977
+ body: response.body === void 0 ? void 0 : toNapiBuffer(response.body)
23978
+ };
23979
+ };
23980
+ }
23981
+ function fromNapiHttpResponseBodyStream(stream) {
23982
+ return {
23983
+ cancelled: () => stream.cancelled(),
23984
+ write: (chunk) => stream.write(Buffer.from(chunk)),
23985
+ end: () => stream.end(),
23986
+ error: (message) => stream.error(message)
23987
+ };
23988
+ }
23810
23989
  function toNapiHttpRequest(request) {
23811
23990
  if (!request) {
23812
23991
  return request;
@@ -23871,6 +24050,9 @@ var NapiCoreRuntime = class {
23871
24050
  async serveRegistry(registry2, config3) {
23872
24051
  await asNativeRegistry(registry2).serve(config3);
23873
24052
  }
24053
+ async waitRegistryReady(registry2) {
24054
+ await asNativeRegistry(registry2).waitReady();
24055
+ }
23874
24056
  async shutdownRegistry(registry2) {
23875
24057
  await asNativeRegistry(registry2).shutdown();
23876
24058
  }
@@ -23910,12 +24092,25 @@ var NapiCoreRuntime = class {
23910
24092
  );
23911
24093
  }
23912
24094
  async serveListener(registry2, listener, config3) {
24095
+ const application = listener.application ? toNapiApplication(listener.application) : void 0;
23913
24096
  await asNativeRegistry(registry2).serveListener(
23914
24097
  {
23915
24098
  port: listener.port,
23916
24099
  host: listener.host,
23917
24100
  publicDir: listener.publicDir
23918
24101
  },
24102
+ config3,
24103
+ application
24104
+ );
24105
+ }
24106
+ async serveApplicationListener(registry2, listener, config3) {
24107
+ await asNativeRegistry(registry2).serveApplicationListener(
24108
+ {
24109
+ port: listener.port,
24110
+ host: listener.host,
24111
+ publicDir: listener.publicDir
24112
+ },
24113
+ toNapiApplication(listener.application),
23919
24114
  config3
23920
24115
  );
23921
24116
  }
@@ -24212,17 +24407,57 @@ var NapiCoreRuntime = class {
24212
24407
  actorQueueMaxSize(ctx) {
24213
24408
  return asNativeActorContext(ctx).queue().maxSize();
24214
24409
  }
24215
- async actorQueueInspectMessages(ctx) {
24216
- return await asNativeActorContext(ctx).queue().inspectMessages();
24410
+ async actorQueueInspectMessages(ctx) {
24411
+ return await asNativeActorContext(ctx).queue().inspectMessages();
24412
+ }
24413
+ async actorQueueReset(ctx) {
24414
+ await asNativeActorContext(ctx).queue().reset();
24415
+ }
24416
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
24417
+ return await asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
24418
+ }
24419
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
24420
+ return await asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
24421
+ }
24422
+ async actorScheduleCancel(ctx, id) {
24423
+ return await asNativeActorContext(ctx).schedule().cancel(id);
24424
+ }
24425
+ async actorScheduleGet(ctx, id) {
24426
+ return await asNativeActorContext(ctx).schedule().get(id) ?? void 0;
24427
+ }
24428
+ async actorScheduleList(ctx) {
24429
+ return await asNativeActorContext(ctx).schedule().list();
24430
+ }
24431
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
24432
+ await asNativeActorContext(ctx).schedule().cronSet(
24433
+ name,
24434
+ expression,
24435
+ timezone,
24436
+ actionName,
24437
+ toNapiBuffer(args),
24438
+ maxHistory
24439
+ );
24440
+ }
24441
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
24442
+ await asNativeActorContext(ctx).schedule().cronEvery(
24443
+ name,
24444
+ intervalMs,
24445
+ actionName,
24446
+ toNapiBuffer(args),
24447
+ maxHistory
24448
+ );
24449
+ }
24450
+ async actorCronGet(ctx, name) {
24451
+ return await asNativeActorContext(ctx).schedule().cronGet(name) ?? void 0;
24217
24452
  }
24218
- async actorQueueReset(ctx) {
24219
- await asNativeActorContext(ctx).queue().reset();
24453
+ async actorCronList(ctx) {
24454
+ return await asNativeActorContext(ctx).schedule().cronList();
24220
24455
  }
24221
- actorScheduleAfter(ctx, durationMs, actionName, args) {
24222
- asNativeActorContext(ctx).schedule().after(durationMs, actionName, toNapiBuffer(args));
24456
+ async actorCronDelete(ctx, name) {
24457
+ return await asNativeActorContext(ctx).schedule().cronDelete(name);
24223
24458
  }
24224
- actorScheduleAt(ctx, timestampMs, actionName, args) {
24225
- asNativeActorContext(ctx).schedule().at(timestampMs, actionName, toNapiBuffer(args));
24459
+ async actorCronHistory(ctx, name, limit) {
24460
+ return await asNativeActorContext(ctx).schedule().cronHistory(name, limit);
24226
24461
  }
24227
24462
  connId(conn) {
24228
24463
  return asNativeConn(conn).id();
@@ -24262,6 +24497,135 @@ async function loadNapiRuntime() {
24262
24497
  runtime: new NapiCoreRuntime(bindings)
24263
24498
  };
24264
24499
  }
24500
+ var HTTP_BODY_CHUNK_SIZE = 64 * 1024;
24501
+ function runtimeBytesToArrayBuffer(value) {
24502
+ return value.buffer.slice(
24503
+ value.byteOffset,
24504
+ value.byteOffset + value.byteLength
24505
+ );
24506
+ }
24507
+ function buildNativeHttpRequest(init) {
24508
+ var _a2;
24509
+ const headers = new Headers(init.headers);
24510
+ const originalUrl = headers.get(HEADER_ORIGINAL_REQUEST_URL);
24511
+ headers.delete(HEADER_ORIGINAL_REQUEST_URL);
24512
+ const url2 = originalUrl ?? (init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString());
24513
+ const method2 = init.method.toUpperCase();
24514
+ const bodyForbidden = method2 === "GET" || method2 === "HEAD";
24515
+ const body = bodyForbidden ? void 0 : init.bodyStream ? new ReadableStream({
24516
+ async pull(controller) {
24517
+ var _a22, _b;
24518
+ try {
24519
+ if (init.body && init.body.length > 0) {
24520
+ controller.enqueue(new Uint8Array(init.body));
24521
+ init.body = void 0;
24522
+ return;
24523
+ }
24524
+ const chunk = await ((_a22 = init.bodyStream) == null ? void 0 : _a22.read());
24525
+ if (!chunk) {
24526
+ controller.close();
24527
+ } else {
24528
+ controller.enqueue(new Uint8Array(chunk));
24529
+ }
24530
+ } catch (error46) {
24531
+ (_b = init.abortController) == null ? void 0 : _b.abort(error46);
24532
+ controller.error(error46);
24533
+ }
24534
+ },
24535
+ async cancel() {
24536
+ var _a22;
24537
+ await ((_a22 = init.bodyStream) == null ? void 0 : _a22.cancel());
24538
+ }
24539
+ }) : init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
24540
+ const streamInit = init.bodyStream && !bodyForbidden ? { duplex: "half" } : {};
24541
+ return new Request(url2, {
24542
+ method: method2,
24543
+ headers,
24544
+ body,
24545
+ signal: ((_a2 = init.abortController) == null ? void 0 : _a2.signal) ?? init.signal,
24546
+ ...streamInit
24547
+ });
24548
+ }
24549
+ async function cancelNativeHttpRequestBody(bodyStream) {
24550
+ await (bodyStream == null ? void 0 : bodyStream.cancel());
24551
+ }
24552
+ async function writeResponseChunk(stream, chunk) {
24553
+ for (let offset = 0; offset < chunk.byteLength; offset += HTTP_BODY_CHUNK_SIZE) {
24554
+ await stream.write(
24555
+ chunk.subarray(offset, offset + HTTP_BODY_CHUNK_SIZE)
24556
+ );
24557
+ }
24558
+ }
24559
+ async function pumpResponseBody(reader, stream) {
24560
+ var _a2;
24561
+ const cancelled = stream.cancelled().then(() => ({ cancelled: true }));
24562
+ try {
24563
+ for (; ; ) {
24564
+ const read = reader.read().then((next2) => ({ cancelled: false, next: next2 }));
24565
+ const result = await Promise.race([read, cancelled]);
24566
+ if (result.cancelled) {
24567
+ await reader.cancel(
24568
+ new Error("native http response stream receiver dropped")
24569
+ );
24570
+ return;
24571
+ }
24572
+ const { next } = result;
24573
+ if (next.done) {
24574
+ await stream.end();
24575
+ return;
24576
+ }
24577
+ if ((_a2 = next.value) == null ? void 0 : _a2.byteLength) {
24578
+ await writeResponseChunk(stream, next.value);
24579
+ }
24580
+ }
24581
+ } catch (error46) {
24582
+ try {
24583
+ await stream.error(stringifyError(error46));
24584
+ } catch (streamError) {
24585
+ logger22().debug({
24586
+ msg: "failed to report native http response stream error",
24587
+ error: streamError
24588
+ });
24589
+ }
24590
+ try {
24591
+ await reader.cancel(error46);
24592
+ } catch {
24593
+ }
24594
+ } finally {
24595
+ reader.releaseLock();
24596
+ }
24597
+ }
24598
+ async function convertNativeHttpResponse(response, responseBodyStream) {
24599
+ const headers = Object.fromEntries(response.headers.entries());
24600
+ if (!response.body) {
24601
+ return {
24602
+ response: {
24603
+ status: response.status,
24604
+ headers,
24605
+ body: new Uint8Array()
24606
+ }
24607
+ };
24608
+ }
24609
+ if (responseBodyStream) {
24610
+ const reader = response.body.getReader();
24611
+ const bodyCompletion = pumpResponseBody(reader, responseBodyStream);
24612
+ return {
24613
+ response: {
24614
+ status: response.status,
24615
+ headers,
24616
+ stream: true
24617
+ },
24618
+ bodyCompletion
24619
+ };
24620
+ }
24621
+ return {
24622
+ response: {
24623
+ status: response.status,
24624
+ headers,
24625
+ body: new Uint8Array(await response.arrayBuffer())
24626
+ }
24627
+ };
24628
+ }
24265
24629
  var CONN_PARAMS_KEY = "__conn_params__";
24266
24630
  function validateActionArgs(schemas, name, args) {
24267
24631
  if (!(schemas == null ? void 0 : schemas[name])) {
@@ -24495,6 +24859,11 @@ var WasmCoreRuntime = class {
24495
24859
  async serveRegistry(registry2, config3) {
24496
24860
  await callWasm(() => asWasmRegistry(registry2).serve(config3));
24497
24861
  }
24862
+ async waitRegistryReady() {
24863
+ throw new Error(
24864
+ "registry.startAndWait() is not supported by the WASM runtime"
24865
+ );
24866
+ }
24498
24867
  async shutdownRegistry(registry2) {
24499
24868
  await callWasm(() => asWasmRegistry(registry2).shutdown());
24500
24869
  }
@@ -24526,6 +24895,11 @@ var WasmCoreRuntime = class {
24526
24895
  "registry.listen() is not supported on the wasm runtime; use registry.serve() and mount the handler in your platform's HTTP server instead"
24527
24896
  );
24528
24897
  }
24898
+ async serveApplicationListener(_registry, _listener, _config) {
24899
+ throw new Error(
24900
+ "registry.listen() is not supported on the wasm runtime; use an application-owned HTTP server instead"
24901
+ );
24902
+ }
24529
24903
  createActorFactory(callbacks, config3) {
24530
24904
  return callWasmSync(
24531
24905
  () => asActorFactoryHandle2(
@@ -24915,13 +25289,97 @@ var WasmCoreRuntime = class {
24915
25289
  const queue2 = childHandle(asWasmActorContext(ctx), "queue");
24916
25290
  await callHandleAsync(queue2, "reset");
24917
25291
  }
24918
- actorScheduleAfter(ctx, durationMs, actionName, args) {
25292
+ async actorScheduleAfter(ctx, durationMs, actionName, args) {
25293
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25294
+ return await callHandleAsync(
25295
+ schedule,
25296
+ "after",
25297
+ wasmNumber(durationMs),
25298
+ actionName,
25299
+ args
25300
+ );
25301
+ }
25302
+ async actorScheduleAt(ctx, timestampMs, actionName, args) {
25303
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25304
+ return await callHandleAsync(
25305
+ schedule,
25306
+ "at",
25307
+ wasmNumber(timestampMs),
25308
+ actionName,
25309
+ args
25310
+ );
25311
+ }
25312
+ async actorScheduleCancel(ctx, id) {
25313
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25314
+ return await callHandleAsync(schedule, "cancel", id);
25315
+ }
25316
+ async actorScheduleGet(ctx, id) {
25317
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25318
+ return await callHandleAsync(
25319
+ schedule,
25320
+ "get",
25321
+ id
25322
+ );
25323
+ }
25324
+ async actorScheduleList(ctx) {
25325
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25326
+ return await callHandleAsync(
25327
+ schedule,
25328
+ "list"
25329
+ );
25330
+ }
25331
+ async actorCronSet(ctx, name, expression, timezone, actionName, args, maxHistory) {
25332
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25333
+ await callHandleAsync(
25334
+ schedule,
25335
+ "cronSet",
25336
+ name,
25337
+ expression,
25338
+ timezone,
25339
+ actionName,
25340
+ args,
25341
+ maxHistory
25342
+ );
25343
+ }
25344
+ async actorCronEvery(ctx, name, intervalMs, actionName, args, maxHistory) {
25345
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25346
+ await callHandleAsync(
25347
+ schedule,
25348
+ "cronEvery",
25349
+ name,
25350
+ intervalMs,
25351
+ actionName,
25352
+ args,
25353
+ maxHistory
25354
+ );
25355
+ }
25356
+ async actorCronGet(ctx, name) {
25357
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25358
+ return await callHandleAsync(
25359
+ schedule,
25360
+ "cronGet",
25361
+ name
25362
+ );
25363
+ }
25364
+ async actorCronList(ctx) {
25365
+ const schedule = childHandle(asWasmActorContext(ctx), "schedule");
25366
+ return await callHandleAsync(
25367
+ schedule,
25368
+ "cronList"
25369
+ );
25370
+ }
25371
+ async actorCronDelete(ctx, name) {
24919
25372
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
24920
- callHandle(schedule, "after", wasmNumber(durationMs), actionName, args);
25373
+ return await callHandleAsync(schedule, "cronDelete", name);
24921
25374
  }
24922
- actorScheduleAt(ctx, timestampMs, actionName, args) {
25375
+ async actorCronHistory(ctx, name, limit) {
24923
25376
  const schedule = childHandle(asWasmActorContext(ctx), "schedule");
24924
- callHandle(schedule, "at", wasmNumber(timestampMs), actionName, args);
25377
+ return await callHandleAsync(
25378
+ schedule,
25379
+ "cronHistory",
25380
+ name,
25381
+ limit
25382
+ );
24925
25383
  }
24926
25384
  connId(conn) {
24927
25385
  return callHandle(asWasmConn(conn), "id");
@@ -25294,7 +25752,7 @@ function toRuntimeBytes(value) {
25294
25752
  function arrayBufferViewToRuntimeBytes(value) {
25295
25753
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
25296
25754
  }
25297
- function runtimeBytesToArrayBuffer(value) {
25755
+ function runtimeBytesToArrayBuffer2(value) {
25298
25756
  return value.buffer.slice(
25299
25757
  value.byteOffset,
25300
25758
  value.byteOffset + value.byteLength
@@ -25624,24 +26082,6 @@ function decodeArgs(value) {
25624
26082
  const decoded = decodeValue(value);
25625
26083
  return normalizeArgs(decoded);
25626
26084
  }
25627
- function buildRequest(init) {
25628
- const url2 = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
25629
- const body = init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
25630
- return new Request(url2, {
25631
- method: init.method,
25632
- headers: init.headers,
25633
- body
25634
- });
25635
- }
25636
- async function toRuntimeHttpResponse(response) {
25637
- const headers = Object.fromEntries(response.headers.entries());
25638
- const body = new Uint8Array(await response.arrayBuffer());
25639
- return {
25640
- status: response.status,
25641
- headers,
25642
- body
25643
- };
25644
- }
25645
26085
  function toActorKey(segments) {
25646
26086
  return segments.map(
25647
26087
  (segment) => segment.kind === "number" ? String(segment.numberValue ?? 0) : segment.stringValue ?? ""
@@ -25766,26 +26206,116 @@ var NativeScheduleAdapter = class {
25766
26206
  this.#ctx = ctx;
25767
26207
  }
25768
26208
  async after(duration3, action, ...args) {
25769
- callNativeSync(
25770
- () => this.#runtime.actorScheduleAfter(
25771
- this.#ctx,
25772
- duration3,
25773
- action,
25774
- encodeValue(args)
25775
- )
26209
+ return await this.#runtime.actorScheduleAfter(
26210
+ this.#ctx,
26211
+ duration3,
26212
+ action,
26213
+ encodeValue(args)
25776
26214
  );
25777
26215
  }
25778
26216
  async at(timestamp, action, ...args) {
25779
- callNativeSync(
25780
- () => this.#runtime.actorScheduleAt(
25781
- this.#ctx,
25782
- timestamp,
25783
- action,
25784
- encodeValue(args)
25785
- )
26217
+ return await this.#runtime.actorScheduleAt(
26218
+ this.#ctx,
26219
+ timestamp,
26220
+ action,
26221
+ encodeValue(args)
26222
+ );
26223
+ }
26224
+ async cancel(id) {
26225
+ return await this.#runtime.actorScheduleCancel(this.#ctx, id);
26226
+ }
26227
+ async get(id) {
26228
+ const event2 = await this.#runtime.actorScheduleGet(this.#ctx, id);
26229
+ return event2 ? decodeScheduledEventInfo(event2) : void 0;
26230
+ }
26231
+ async list() {
26232
+ return (await this.#runtime.actorScheduleList(this.#ctx)).map(
26233
+ decodeScheduledEventInfo
26234
+ );
26235
+ }
26236
+ };
26237
+ var NativeCronAdapter = class {
26238
+ #runtime;
26239
+ #ctx;
26240
+ constructor(runtime, ctx) {
26241
+ this.#runtime = runtime;
26242
+ this.#ctx = ctx;
26243
+ }
26244
+ async set(options) {
26245
+ await this.#runtime.actorCronSet(
26246
+ this.#ctx,
26247
+ options.name,
26248
+ options.expression,
26249
+ options.timezone,
26250
+ options.action,
26251
+ encodeValue(options.args ?? []),
26252
+ options.maxHistory
25786
26253
  );
25787
26254
  }
26255
+ async every(options) {
26256
+ await this.#runtime.actorCronEvery(
26257
+ this.#ctx,
26258
+ options.name,
26259
+ options.interval,
26260
+ options.action,
26261
+ encodeValue(options.args ?? []),
26262
+ options.maxHistory
26263
+ );
26264
+ }
26265
+ async get(name) {
26266
+ const job = await this.#runtime.actorCronGet(this.#ctx, name);
26267
+ return job ? decodeCronJobInfo(job) : void 0;
26268
+ }
26269
+ async list() {
26270
+ return (await this.#runtime.actorCronList(this.#ctx)).map(
26271
+ decodeCronJobInfo
26272
+ );
26273
+ }
26274
+ async delete(name) {
26275
+ return await this.#runtime.actorCronDelete(this.#ctx, name);
26276
+ }
26277
+ async history(name, options) {
26278
+ return (await this.#runtime.actorCronHistory(
26279
+ this.#ctx,
26280
+ name,
26281
+ options == null ? void 0 : options.limit
26282
+ )).map(decodeCronFire);
26283
+ }
25788
26284
  };
26285
+ function decodeScheduledEventInfo(event2) {
26286
+ return {
26287
+ id: event2.id,
26288
+ action: event2.action,
26289
+ args: decodeArgs(event2.args),
26290
+ runAt: event2.runAt
26291
+ };
26292
+ }
26293
+ function decodeCronJobInfo(job) {
26294
+ const base = {
26295
+ name: job.name,
26296
+ action: job.action,
26297
+ args: decodeArgs(job.args),
26298
+ nextRunAt: job.nextRunAt,
26299
+ lastRunAt: job.lastRunAt,
26300
+ maxHistory: job.maxHistory
26301
+ };
26302
+ if (job.kind === "cron") {
26303
+ return {
26304
+ ...base,
26305
+ kind: "cron",
26306
+ expression: job.expression,
26307
+ timezone: job.timezone
26308
+ };
26309
+ }
26310
+ return {
26311
+ ...base,
26312
+ kind: "every",
26313
+ interval: job.intervalMs
26314
+ };
26315
+ }
26316
+ function decodeCronFire(fire) {
26317
+ return { ...fire };
26318
+ }
25789
26319
  var NativeKvAdapter = class {
25790
26320
  #runtime;
25791
26321
  #ctx;
@@ -26216,7 +26746,7 @@ var NativeWebSocketAdapter = class {
26216
26746
  this.#runtime.webSocketSetEventCallback(this.#ws, (event2) => {
26217
26747
  if (event2.kind === "message") {
26218
26748
  this.#virtual.triggerMessage(
26219
- event2.binary ? runtimeBytesToArrayBuffer(event2.data) : event2.data,
26749
+ event2.binary ? runtimeBytesToArrayBuffer2(event2.data) : event2.data,
26220
26750
  event2.messageIndex
26221
26751
  );
26222
26752
  return;
@@ -26566,6 +27096,7 @@ var ActorContextHandleAdapter = class {
26566
27096
  #client;
26567
27097
  #clientFactory;
26568
27098
  #connMap;
27099
+ #cron;
26569
27100
  #databaseProvider;
26570
27101
  #db;
26571
27102
  #dispatchCancelToken;
@@ -26700,6 +27231,12 @@ var ActorContextHandleAdapter = class {
26700
27231
  }
26701
27232
  return this.#schedule;
26702
27233
  }
27234
+ get cron() {
27235
+ if (!this.#cron) {
27236
+ this.#cron = new NativeCronAdapter(this.#runtime, this.#ctx);
27237
+ }
27238
+ return this.#cron;
27239
+ }
26703
27240
  get actorId() {
26704
27241
  return callNativeSync(() => this.#runtime.actorId(this.#ctx));
26705
27242
  }
@@ -27297,12 +27834,13 @@ function buildActorConfig(definition, registryConfig, runtimeKind) {
27297
27834
  connectionLivenessTimeoutMs: options.connectionLivenessTimeout,
27298
27835
  connectionLivenessIntervalMs: options.connectionLivenessInterval,
27299
27836
  maxQueueSize: options.maxQueueSize,
27837
+ maxSchedules: options.maxSchedules,
27300
27838
  maxQueueMessageSize: options.maxQueueMessageSize,
27301
27839
  maxIncomingMessageSize: registryConfig.maxIncomingMessageSize,
27302
27840
  maxOutgoingMessageSize: registryConfig.maxOutgoingMessageSize,
27303
27841
  preloadMaxWorkflowBytes: options.preloadMaxWorkflowBytes,
27304
27842
  preloadMaxConnectionsBytes: options.preloadMaxConnectionsBytes,
27305
- actions: Object.keys(config3.actions ?? {}).sort().map((name) => ({ name })),
27843
+ actions: Object.keys(flattenActionHandlers(config3.actions)).sort().map((name) => ({ name })),
27306
27844
  inspectorTabs: buildInspectorTabs(config3.inspector, runtimeKind)
27307
27845
  };
27308
27846
  }
@@ -27379,15 +27917,16 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27379
27917
  var _a2;
27380
27918
  const config3 = definition.config;
27381
27919
  const databaseProvider = config3.db;
27920
+ const actionHandlers = flattenActionHandlers(config3.actions);
27382
27921
  const schemaConfig = {
27383
- actionInputSchemas: config3.actionInputSchemas,
27922
+ actionInputSchemas: flattenActionInputSchemas(
27923
+ config3.actions,
27924
+ config3.actionInputSchemas
27925
+ ),
27384
27926
  connParamsSchema: config3.connParamsSchema,
27385
27927
  events: config3.events,
27386
27928
  queues: config3.queues
27387
27929
  };
27388
- const actionHandlers = Object.fromEntries(
27389
- Object.entries(config3.actions ?? {}).map(([name, handler]) => [name, handler])
27390
- );
27391
27930
  const createClient = () => createClientWithDriver(
27392
27931
  new RemoteEngineControlClient(
27393
27932
  convertRegistryConfigToClientConfig(registryConfig)
@@ -27439,12 +27978,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27439
27978
  onStateChange,
27440
27979
  cancelToken
27441
27980
  );
27442
- const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
27981
+ const maybeHandleNativeInspectorRequest = async (ctx, rawRequest) => {
27443
27982
  var _a22, _b, _c, _d;
27444
- const url2 = new URL(jsRequest.url);
27983
+ const rawUrl = rawRequest.uri.startsWith("http") ? rawRequest.uri : new URL(rawRequest.uri, "http://127.0.0.1").toString();
27984
+ const url2 = new URL(rawUrl);
27445
27985
  if (!url2.pathname.startsWith("/inspector/")) {
27446
27986
  return void 0;
27447
27987
  }
27988
+ const jsRequest = buildNativeHttpRequest(rawRequest);
27448
27989
  const jsonResponse = (body, init) => new Response(JSON.stringify(body), {
27449
27990
  status: (init == null ? void 0 : init.status) ?? 200,
27450
27991
  headers: {
@@ -27975,7 +28516,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27975
28516
  );
27976
28517
  const actorCtx = makeActorCtx(
27977
28518
  ctx,
27978
- request ? buildRequest(request) : void 0
28519
+ request ? buildNativeHttpRequest(request) : void 0
27979
28520
  );
27980
28521
  try {
27981
28522
  await config3.onBeforeConnect(
@@ -27995,7 +28536,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
27995
28536
  const { ctx, conn, params, request } = unwrapTsfnPayload(error46, payload);
27996
28537
  const actorCtx = makeActorCtx(
27997
28538
  ctx,
27998
- request ? buildRequest(request) : void 0
28539
+ request ? buildNativeHttpRequest(request) : void 0
27999
28540
  );
28000
28541
  const connAdapter = new NativeConnAdapter(
28001
28542
  runtime,
@@ -28032,7 +28573,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28032
28573
  );
28033
28574
  const actorCtx = makeActorCtx(
28034
28575
  ctx,
28035
- request ? buildRequest(request) : void 0
28576
+ request ? buildNativeHttpRequest(request) : void 0
28036
28577
  );
28037
28578
  const connAdapter = new NativeConnAdapter(
28038
28579
  runtime,
@@ -28137,27 +28678,45 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28137
28678
  onRequest: wrapNativeCallback(
28138
28679
  async (error46, payload) => {
28139
28680
  try {
28140
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
28141
- error46,
28142
- payload
28143
- );
28144
- const jsRequest = buildRequest(request);
28145
- const inspectorResponse = await maybeHandleNativeInspectorRequest(
28146
- ctx,
28147
- request,
28148
- jsRequest
28149
- );
28681
+ const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error46, payload);
28682
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(ctx, request);
28150
28683
  if (inspectorResponse) {
28151
- return await toRuntimeHttpResponse(inspectorResponse);
28684
+ await cancelNativeHttpRequestBody(request.bodyStream);
28685
+ return (await convertNativeHttpResponse(
28686
+ inspectorResponse,
28687
+ responseBodyStream
28688
+ )).response;
28152
28689
  }
28153
28690
  if (typeof config3.onRequest !== "function") {
28154
- return await toRuntimeHttpResponse(
28155
- new Response(null, { status: 404 })
28156
- );
28691
+ await cancelNativeHttpRequestBody(request.bodyStream);
28692
+ return (await convertNativeHttpResponse(
28693
+ new Response(null, { status: 404 }),
28694
+ responseBodyStream
28695
+ )).response;
28157
28696
  }
28158
- const rawConnParams = jsRequest.headers.get(HEADER_CONN_PARAMS);
28697
+ const requestAbortController = new AbortController();
28698
+ const handlerRequest = buildNativeHttpRequest({
28699
+ ...request,
28700
+ abortController: requestAbortController
28701
+ });
28702
+ const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
28159
28703
  let requestCtx;
28160
28704
  let conn;
28705
+ let removeRequestAbortListener;
28706
+ let cleanupDeferredToBody = false;
28707
+ let cleanedUp = false;
28708
+ const cleanupRequest = async () => {
28709
+ if (cleanedUp) return;
28710
+ cleanedUp = true;
28711
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
28712
+ try {
28713
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
28714
+ } finally {
28715
+ if (conn) {
28716
+ await runtime.connDisconnect(conn);
28717
+ }
28718
+ }
28719
+ };
28161
28720
  try {
28162
28721
  const connParams = validateConnParams(
28163
28722
  schemaConfig.connParamsSchema,
@@ -28173,23 +28732,56 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28173
28732
  requestCtx = makeConnCtx(
28174
28733
  ctx,
28175
28734
  conn,
28176
- jsRequest,
28735
+ handlerRequest,
28177
28736
  cancelToken
28178
28737
  );
28738
+ const ctxAbortSignal = requestCtx.abortSignal;
28739
+ const abortRequest = () => requestAbortController.abort(ctxAbortSignal.reason);
28740
+ if (ctxAbortSignal.aborted) {
28741
+ abortRequest();
28742
+ } else {
28743
+ ctxAbortSignal.addEventListener(
28744
+ "abort",
28745
+ abortRequest,
28746
+ { once: true }
28747
+ );
28748
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
28749
+ "abort",
28750
+ abortRequest
28751
+ );
28752
+ }
28179
28753
  const response = await config3.onRequest(
28180
28754
  requestCtx,
28181
- jsRequest
28755
+ handlerRequest
28182
28756
  );
28183
- if (!(response instanceof Response)) {
28757
+ if (!isResponseLike(response)) {
28184
28758
  throw new Error(
28185
28759
  "onRequest handler must return a Response"
28186
28760
  );
28187
28761
  }
28188
- return await toRuntimeHttpResponse(response);
28762
+ const conversion = await convertNativeHttpResponse(
28763
+ response,
28764
+ responseBodyStream
28765
+ );
28766
+ if (conversion.bodyCompletion) {
28767
+ cleanupDeferredToBody = true;
28768
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
28769
+ logger22().error({
28770
+ msg: "failed to clean up native streaming http request",
28771
+ error: cleanupError
28772
+ });
28773
+ });
28774
+ }
28775
+ return conversion.response;
28189
28776
  } finally {
28190
- await (requestCtx == null ? void 0 : requestCtx.dispose());
28191
- if (conn) {
28192
- await runtime.connDisconnect(conn);
28777
+ try {
28778
+ await cancelNativeHttpRequestBody(
28779
+ request.bodyStream
28780
+ );
28781
+ } finally {
28782
+ if (!cleanupDeferredToBody) {
28783
+ await cleanupRequest();
28784
+ }
28193
28785
  }
28194
28786
  }
28195
28787
  } catch (error210) {
@@ -28204,7 +28796,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28204
28796
  onWebSocket: typeof config3.onWebSocket === "function" ? wrapNativeCallback(
28205
28797
  async (error46, payload) => {
28206
28798
  const { ctx, conn, ws, request } = unwrapTsfnPayload(error46, payload);
28207
- const jsRequest = request ? buildRequest(request) : void 0;
28799
+ const jsRequest = request ? buildNativeHttpRequest(request) : void 0;
28208
28800
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
28209
28801
  try {
28210
28802
  await config3.onWebSocket(
@@ -28268,7 +28860,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28268
28860
  name,
28269
28861
  wrapNativeCallback(
28270
28862
  async (error46, payload) => {
28271
- const { ctx, conn, args, cancelToken } = unwrapTsfnPayload(error46, payload);
28863
+ const { ctx, conn, args, scheduledFire, cancelToken } = unwrapTsfnPayload(error46, payload);
28272
28864
  const actorCtx = conn != null ? makeConnCtx(ctx, conn, void 0, cancelToken) : makeActorCtx(ctx, void 0, cancelToken);
28273
28865
  try {
28274
28866
  return encodeValue(
@@ -28278,7 +28870,8 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28278
28870
  schemaConfig.actionInputSchemas,
28279
28871
  name,
28280
28872
  decodeArgs(args)
28281
- )
28873
+ ),
28874
+ ...scheduledFire ? [scheduledFire] : []
28282
28875
  )
28283
28876
  );
28284
28877
  } finally {
@@ -28300,7 +28893,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
28300
28893
  timeoutMs,
28301
28894
  cancelToken
28302
28895
  } = unwrapTsfnPayload(error46, payload);
28303
- const jsRequest = buildRequest(request);
28896
+ const jsRequest = buildNativeHttpRequest(request);
28304
28897
  const actorCtx = withConnContext(
28305
28898
  runtime,
28306
28899
  ctx,
@@ -28434,6 +29027,7 @@ async function buildConfiguredRegistry(config3) {
28434
29027
  runtime
28435
29028
  );
28436
29029
  }
29030
+ var REGISTRY_READY_TIMEOUT_MS = 3e4;
28437
29031
  function signalExitCode(signal) {
28438
29032
  switch (signal) {
28439
29033
  case "SIGINT":
@@ -28448,6 +29042,54 @@ function finishShutdownSignal(signal) {
28448
29042
  }
28449
29043
  process.kill(process.pid, signal);
28450
29044
  }
29045
+ function createApplicationFetch(application, runtime) {
29046
+ return async (request, responseBodyStream) => {
29047
+ const method2 = request.method.toUpperCase();
29048
+ const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
29049
+ const abortController = new AbortController();
29050
+ if (request.cancelToken) {
29051
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
29052
+ abortController.abort();
29053
+ } else {
29054
+ runtime.onCancellationTokenCancelled(
29055
+ request.cancelToken,
29056
+ () => abortController.abort()
29057
+ );
29058
+ }
29059
+ }
29060
+ const response = await application.fetch(
29061
+ new Request(request.url, {
29062
+ method: method2,
29063
+ headers: request.headers,
29064
+ body,
29065
+ signal: abortController.signal
29066
+ })
29067
+ );
29068
+ if (!isResponseLike(response)) {
29069
+ throw new TypeError(
29070
+ "registry.listen() application fetch must return a Response"
29071
+ );
29072
+ }
29073
+ const conversion = await convertNativeHttpResponse(
29074
+ response,
29075
+ responseBodyStream
29076
+ );
29077
+ if (conversion.bodyCompletion) {
29078
+ void conversion.bodyCompletion.catch((error46) => {
29079
+ logger22().error({
29080
+ msg: "application response stream failed",
29081
+ error: error46
29082
+ });
29083
+ });
29084
+ }
29085
+ return {
29086
+ status: conversion.response.status ?? response.status,
29087
+ headers: conversion.response.headers ?? Object.fromEntries(response.headers.entries()),
29088
+ body: conversion.response.body,
29089
+ stream: conversion.response.stream
29090
+ };
29091
+ };
29092
+ }
28451
29093
  var Registry = class {
28452
29094
  #config;
28453
29095
  #buildConfiguredRegistry;
@@ -28459,8 +29101,11 @@ var Registry = class {
28459
29101
  return RegistryConfigSchema.parse(this.#config);
28460
29102
  }
28461
29103
  #runtimeServePromise;
29104
+ #runtimeServeLifecyclePromise;
29105
+ #runtimeReadyPromise;
28462
29106
  #runtimeServeConfiguredPromise;
28463
29107
  #runtimeServerlessPromise;
29108
+ #applicationListenerPromise;
28464
29109
  #configureServerlessPoolPromise;
28465
29110
  #welcomePrinted = false;
28466
29111
  #shutdownInstalled = false;
@@ -28686,18 +29331,67 @@ var Registry = class {
28686
29331
  * @param opts.host Address to bind. Defaults to `0.0.0.0`.
28687
29332
  * @param opts.publicDir If set, serves static files from this directory
28688
29333
  * as a fallback below the framework routes.
29334
+ * @param opts.application If set, handles requests that do not match a
29335
+ * framework route.
28689
29336
  *
28690
29337
  * @example
28691
29338
  * ```ts
28692
29339
  * await registry.listen();
28693
- * await registry.listen({ port: 8080, publicDir: "./public" });
29340
+ * await registry.listen({ application: app });
28694
29341
  * ```
28695
29342
  */
28696
29343
  async listen(opts = {}) {
28697
29344
  const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
28698
29345
  const publicDir = opts.publicDir ?? getRivetkitPublicDir();
28699
29346
  const config3 = this.parseConfig();
28700
- const configuredRegistryPromise = buildConfiguredRegistry(config3);
29347
+ if (opts.application && getRivetkitRuntimeMode() !== "serverless") {
29348
+ if (config3.runtime === "wasm") {
29349
+ throw new Error(
29350
+ "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
29351
+ );
29352
+ }
29353
+ this.#installSignalHandlers(config3);
29354
+ this.#printWelcome(config3, "serverful", {
29355
+ port,
29356
+ host: opts.host,
29357
+ publicDir
29358
+ });
29359
+ this.#startEnvoy(config3, true);
29360
+ const readyPromise = this.startAndWait();
29361
+ const configuredRegistryPromise2 = this.#runtimeServeConfiguredPromise;
29362
+ if (!configuredRegistryPromise2) {
29363
+ throw new Error("registry envoy startup did not initialize");
29364
+ }
29365
+ const { runtime: runtime2, registry: registry22, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
29366
+ const application2 = createApplicationFetch(
29367
+ opts.application,
29368
+ runtime2
29369
+ );
29370
+ await readyPromise;
29371
+ const listenerPromise = runtime2.serveApplicationListener(
29372
+ registry22,
29373
+ {
29374
+ port,
29375
+ host: opts.host,
29376
+ publicDir,
29377
+ application: application2
29378
+ },
29379
+ serveConfig2
29380
+ );
29381
+ this.#applicationListenerPromise = listenerPromise;
29382
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
29383
+ if (!serveLifecyclePromise) {
29384
+ throw new Error(
29385
+ "registry envoy serve lifecycle did not initialize"
29386
+ );
29387
+ }
29388
+ await Promise.all([
29389
+ listenerPromise,
29390
+ serveLifecyclePromise
29391
+ ]);
29392
+ return;
29393
+ }
29394
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
28701
29395
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
28702
29396
  this.#runtimeServerlessPromise = configuredRegistryPromise;
28703
29397
  this.#installSignalHandlers(config3);
@@ -28708,9 +29402,15 @@ var Registry = class {
28708
29402
  });
28709
29403
  this.#ensureServerlessPoolConfigured(config3);
28710
29404
  const { runtime, registry: registry2, serveConfig } = await configuredRegistryPromise;
29405
+ const application = opts.application ? createApplicationFetch(opts.application, runtime) : void 0;
28711
29406
  await runtime.serveListener(
28712
29407
  registry2,
28713
- { port, host: opts.host, publicDir },
29408
+ {
29409
+ port,
29410
+ host: opts.host,
29411
+ publicDir,
29412
+ application
29413
+ },
28714
29414
  serveConfig
28715
29415
  );
28716
29416
  }
@@ -28805,9 +29505,12 @@ var Registry = class {
28805
29505
  if (!this.#runtimeServePromise) {
28806
29506
  const configuredRegistryPromise = this.#buildConfiguredRegistry(config3);
28807
29507
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
28808
- this.#runtimeServePromise = configuredRegistryPromise.then(async ({ runtime, registry: registry2, serveConfig }) => {
28809
- await runtime.serveRegistry(registry2, serveConfig);
28810
- }).catch((error46) => {
29508
+ this.#runtimeServeLifecyclePromise = configuredRegistryPromise.then(
29509
+ async ({ runtime, registry: registry2, serveConfig }) => {
29510
+ await runtime.serveRegistry(registry2, serveConfig);
29511
+ }
29512
+ );
29513
+ this.#runtimeServePromise = this.#runtimeServeLifecyclePromise.catch((error46) => {
28811
29514
  logger22().warn({ error: error46 }, "runtime registry serve errored");
28812
29515
  });
28813
29516
  this.#installSignalHandlers(config3);
@@ -28916,6 +29619,9 @@ var Registry = class {
28916
29619
  if (runtimeServePromise !== void 0) {
28917
29620
  await runtimeServePromise.catch(() => void 0);
28918
29621
  }
29622
+ if (this.#applicationListenerPromise !== void 0) {
29623
+ await this.#applicationListenerPromise.catch(() => void 0);
29624
+ }
28919
29625
  };
28920
29626
  await Promise.race([
28921
29627
  drain(),
@@ -28955,6 +29661,79 @@ var Registry = class {
28955
29661
  startEnvoy() {
28956
29662
  this.#startEnvoy(this.parseConfig(), true);
28957
29663
  }
29664
+ /**
29665
+ * Starts the serverful registry if needed and waits until its envoy has
29666
+ * registered with the Engine. Repeated and concurrent calls share one
29667
+ * startup lifecycle and readiness promise.
29668
+ *
29669
+ * Unlike {@link start}, this reports startup failures and does not resolve
29670
+ * merely because an HTTP health endpoint is listening.
29671
+ */
29672
+ startAndWait() {
29673
+ if (this.#shutdownInFlight !== null) {
29674
+ return Promise.reject(
29675
+ new Error(
29676
+ "registry.startAndWait() cannot run after shutdown has begun"
29677
+ )
29678
+ );
29679
+ }
29680
+ if (this.#runtimeReadyPromise) return this.#runtimeReadyPromise;
29681
+ if (getRivetkitRuntimeMode() === "serverless") {
29682
+ return Promise.reject(
29683
+ new Error(
29684
+ "registry.startAndWait() requires envoy runtime mode; serverless registries become ready per request"
29685
+ )
29686
+ );
29687
+ }
29688
+ const config3 = this.parseConfig();
29689
+ if (config3.runtime === "wasm") {
29690
+ return Promise.reject(
29691
+ new Error(
29692
+ "registry.startAndWait() requires the native runtime; WebAssembly registries do not host an envoy"
29693
+ )
29694
+ );
29695
+ }
29696
+ this.#startEnvoy(config3, true);
29697
+ const configuredRegistryPromise = this.#runtimeServeConfiguredPromise;
29698
+ const serveLifecyclePromise = this.#runtimeServeLifecyclePromise;
29699
+ if (!configuredRegistryPromise || !serveLifecyclePromise) {
29700
+ throw new Error("registry envoy startup did not initialize");
29701
+ }
29702
+ let timeout;
29703
+ const timeoutPromise = new Promise((_resolve, reject) => {
29704
+ var _a2;
29705
+ timeout = setTimeout(
29706
+ () => reject(
29707
+ new Error(
29708
+ `RivetKit registry did not register with the Engine within ${REGISTRY_READY_TIMEOUT_MS}ms`
29709
+ )
29710
+ ),
29711
+ REGISTRY_READY_TIMEOUT_MS
29712
+ );
29713
+ (_a2 = timeout.unref) == null ? void 0 : _a2.call(timeout);
29714
+ });
29715
+ const readinessPromise = (async () => {
29716
+ const { runtime, registry: registry2 } = await configuredRegistryPromise;
29717
+ const stoppedBeforeReady = serveLifecyclePromise.then(() => {
29718
+ throw new Error(
29719
+ "RivetKit registry stopped before becoming ready"
29720
+ );
29721
+ });
29722
+ await Promise.race([
29723
+ runtime.waitRegistryReady(registry2),
29724
+ stoppedBeforeReady
29725
+ ]);
29726
+ })();
29727
+ this.#runtimeReadyPromise = Promise.race([
29728
+ readinessPromise,
29729
+ timeoutPromise
29730
+ ]).finally(() => {
29731
+ if (timeout !== void 0) clearTimeout(timeout);
29732
+ });
29733
+ this.#runtimeReadyPromise.catch(() => {
29734
+ });
29735
+ return this.#runtimeReadyPromise;
29736
+ }
28958
29737
  /**
28959
29738
  * Starts the actor envoy for standalone server deployments.
28960
29739
  *