"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }



var _chunkL47L3ZWJcjs = require('./chunk-L47L3ZWJ.cjs');

// src/utils/env-vars.ts
var getRivetEngine = () => getEnvUniversal("RIVET_ENGINE");
var getRivetEndpoint = () => getEnvUniversal("RIVET_ENDPOINT");
var getRivetToken = () => getEnvUniversal("RIVET_TOKEN");
var getRivetNamespace = () => getEnvUniversal("RIVET_NAMESPACE");
var getRivetRunner = () => getEnvUniversal("RIVET_RUNNER");
var getRivetTotalSlots = () => {
  const value = getEnvUniversal("RIVET_TOTAL_SLOTS");
  return value !== void 0 ? parseInt(value, 10) : void 0;
};
var getRivetRunnerKey = () => getEnvUniversal("RIVET_RUNNER_KEY");
var getRivetRunEngine = () => getEnvUniversal("RIVET_RUN_ENGINE") === "1";
var getRivetRunEngineVersion = () => getEnvUniversal("RIVET_RUN_ENGINE_VERSION");
var getRivetRunnerKind = () => getEnvUniversal("RIVET_RUNNER_KIND");
var getRivetRunnerVersion = () => {
  const value = getEnvUniversal("RIVET_RUNNER_VERSION");
  return value !== void 0 ? parseInt(value, 10) : void 0;
};
var getRivetPublicEndpoint = () => getEnvUniversal("RIVET_PUBLIC_ENDPOINT");
var getRivetPublicToken = () => getEnvUniversal("RIVET_PUBLIC_TOKEN");
var getRivetkitInspectorToken = () => getEnvUniversal("RIVET_INSPECTOR_TOKEN");
var getRivetkitInspectorDisable = () => getEnvUniversal("RIVET_INSPECTOR_DISABLE") === "1";
var getRivetkitStoragePath = () => getEnvUniversal("RIVETKIT_STORAGE_PATH");
var getLogLevel = () => _nullishCoalesce(getEnvUniversal("RIVET_LOG_LEVEL"), () => ( getEnvUniversal("LOG_LEVEL")));
var getLogTarget = () => getEnvUniversal("RIVET_LOG_TARGET") === "1";
var getLogTimestamp = () => getEnvUniversal("RIVET_LOG_TIMESTAMP") === "1";
var getLogMessage = () => getEnvUniversal("RIVET_LOG_MESSAGE") === "1";
var getLogErrorStack = () => getEnvUniversal("RIVET_LOG_ERROR_STACK") === "1";
var getLogHeaders = () => getEnvUniversal("RIVET_LOG_HEADERS") === "1";
var getNodeEnv = () => getEnvUniversal("NODE_ENV");
var getNextPhase = () => getEnvUniversal("NEXT_PHASE");
var isDev = () => getNodeEnv() !== "production";
var getRivetExperimentalOtel = () => getEnvUniversal("RIVET_EXPERIMENTAL_OTEL") === "1";

// src/common/utils.ts
function assertUnreachable(x) {
  throw new Error(`Unreachable case: ${x}`);
}
function isCborSerializable(value, onInvalid, currentPath = "") {
  if (value === null || value === void 0) {
    return true;
  }
  if (typeof value === "number") {
    if (!Number.isFinite(value)) {
      onInvalid == null ? void 0 : onInvalid(currentPath);
      return false;
    }
    return true;
  }
  if (typeof value === "boolean" || typeof value === "string") {
    return true;
  }
  if (typeof value === "bigint") {
    return true;
  }
  if (value instanceof Date) {
    return true;
  }
  if (value instanceof Uint8Array || 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) {
    return true;
  }
  if (value instanceof Map) {
    for (const [key, val] of value.entries()) {
      const keyPath = currentPath ? `${currentPath}.key(${String(key)})` : `key(${String(key)})`;
      const valPath = currentPath ? `${currentPath}.value(${String(key)})` : `value(${String(key)})`;
      if (!isCborSerializable(key, onInvalid, keyPath) || !isCborSerializable(val, onInvalid, valPath)) {
        return false;
      }
    }
    return true;
  }
  if (value instanceof Set) {
    let index = 0;
    for (const item of value.values()) {
      const itemPath = currentPath ? `${currentPath}.set[${index}]` : `set[${index}]`;
      if (!isCborSerializable(item, onInvalid, itemPath)) {
        return false;
      }
      index++;
    }
    return true;
  }
  if (value instanceof RegExp) {
    return true;
  }
  if (value instanceof Error) {
    return true;
  }
  if (Array.isArray(value)) {
    for (let i = 0; i < value.length; i++) {
      const itemPath = currentPath ? `${currentPath}[${i}]` : `[${i}]`;
      if (!isCborSerializable(value[i], onInvalid, itemPath)) {
        return false;
      }
    }
    return true;
  }
  if (typeof value === "object") {
    const proto = Object.getPrototypeOf(value);
    if (proto !== null && proto !== Object.prototype) {
      const protoConstructor = value.constructor;
      if (protoConstructor && typeof protoConstructor.name === "string") {
      }
    }
    for (const key in value) {
      const propPath = currentPath ? `${currentPath}.${key}` : key;
      if (!isCborSerializable(
        value[key],
        onInvalid,
        propPath
      )) {
        return false;
      }
    }
    return true;
  }
  onInvalid == null ? void 0 : onInvalid(currentPath);
  return false;
}
function deconstructError(error, logger2, extraLog, exposeInternalError = false) {
  let statusCode;
  let public_;
  let group;
  let code;
  let message;
  let metadata;
  if (_chunkL47L3ZWJcjs.ActorError.isActorError(error) && error.public) {
    statusCode = "statusCode" in error && error.statusCode ? error.statusCode : 400;
    public_ = true;
    group = error.group;
    code = error.code;
    message = getErrorMessage(error);
    metadata = error.metadata;
    logger2.info({
      msg: "public error",
      group,
      code,
      message,
      ...EXTRA_ERROR_LOG,
      ...extraLog
    });
  } else if (exposeInternalError) {
    if (_chunkL47L3ZWJcjs.ActorError.isActorError(error)) {
      statusCode = 500;
      public_ = false;
      group = error.group;
      code = error.code;
      message = getErrorMessage(error);
      metadata = error.metadata;
      logger2.info({
        msg: "internal error",
        group,
        code,
        message,
        stack: error == null ? void 0 : error.stack,
        ...EXTRA_ERROR_LOG,
        ...extraLog
      });
    } else {
      statusCode = 500;
      public_ = false;
      group = "rivetkit";
      code = _chunkL47L3ZWJcjs.INTERNAL_ERROR_CODE;
      message = getErrorMessage(error);
      logger2.info({
        msg: "internal error",
        group,
        code,
        message,
        stack: error == null ? void 0 : error.stack,
        ...EXTRA_ERROR_LOG,
        ...extraLog
      });
    }
  } else {
    statusCode = 500;
    public_ = false;
    group = "rivetkit";
    code = _chunkL47L3ZWJcjs.INTERNAL_ERROR_CODE;
    message = _chunkL47L3ZWJcjs.INTERNAL_ERROR_DESCRIPTION;
    metadata = {
      //url: `https://hub.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,
    };
    logger2.warn({
      msg: "internal error",
      error: getErrorMessage(error),
      stack: error == null ? void 0 : error.stack,
      ...EXTRA_ERROR_LOG,
      ...extraLog
    });
  }
  return {
    __type: "ActorError",
    statusCode,
    public: public_,
    group,
    code,
    message,
    metadata
  };
}
function stringifyError(error) {
  if (error instanceof Error) {
    if (typeof process !== "undefined" && getLogErrorStack()) {
      return `${error.name}: ${error.message}${error.stack ? `
${error.stack}` : ""}`;
    } else {
      return `${error.name}: ${error.message}`;
    }
  } else if (typeof error === "string") {
    return error;
  } else if (typeof error === "object" && error !== null) {
    try {
      return `${JSON.stringify(error)}`;
    } catch (e) {
      return "[cannot stringify error]";
    }
  } else {
    return `Unknown error: ${getErrorMessage(error)}`;
  }
}
function getErrorMessage(err) {
  if (err && typeof err === "object" && "message" in err && typeof err.message === "string") {
    return err.message;
  } else {
    return String(err);
  }
}
function noopNext() {
  return async () => {
  };
}

// package.json
var package_default = {
  name: "rivetkit",
  version: "2.1.1",
  description: "Lightweight libraries for building stateful actors on edge platforms",
  license: "Apache-2.0",
  keywords: [
    "rivetkit",
    "stateful",
    "serverless",
    "actors",
    "agents",
    "realtime",
    "websocket",
    "actors",
    "framework"
  ],
  files: [
    "dist",
    "src",
    "deno.json",
    "bun.json",
    "package.json"
  ],
  type: "module",
  exports: {
    ".": {
      import: {
        types: "./dist/tsup/mod.d.ts",
        default: "./dist/tsup/mod.js"
      },
      require: {
        types: "./dist/tsup/mod.d.cts",
        default: "./dist/tsup/mod.cjs"
      }
    },
    "./workflow": {
      import: {
        types: "./dist/tsup/workflow/mod.d.ts",
        default: "./dist/tsup/workflow/mod.js"
      },
      require: {
        types: "./dist/tsup/workflow/mod.d.cts",
        default: "./dist/tsup/workflow/mod.cjs"
      }
    },
    "./client": {
      import: {
        browser: {
          types: "./dist/browser/client.d.ts",
          default: "./dist/browser/client.js"
        },
        types: "./dist/tsup/client/mod.d.ts",
        default: "./dist/tsup/client/mod.js"
      },
      require: {
        types: "./dist/tsup/client/mod.d.cts",
        default: "./dist/tsup/client/mod.cjs"
      }
    },
    "./log": {
      import: {
        types: "./dist/tsup/common/log.d.ts",
        default: "./dist/tsup/common/log.js"
      },
      require: {
        types: "./dist/tsup/common/log.d.cts",
        default: "./dist/tsup/common/log.cjs"
      }
    },
    "./errors": {
      import: {
        types: "./dist/tsup/actor/errors.d.ts",
        default: "./dist/tsup/actor/errors.js"
      },
      require: {
        types: "./dist/tsup/actor/errors.d.cts",
        default: "./dist/tsup/actor/errors.cjs"
      }
    },
    "./utils": {
      import: {
        types: "./dist/tsup/utils.d.ts",
        default: "./dist/tsup/utils.js"
      },
      require: {
        types: "./dist/tsup/utils.d.cts",
        default: "./dist/tsup/utils.cjs"
      }
    },
    "./driver-helpers": {
      import: {
        types: "./dist/tsup/driver-helpers/mod.d.ts",
        default: "./dist/tsup/driver-helpers/mod.js"
      },
      require: {
        types: "./dist/tsup/driver-helpers/mod.d.cts",
        default: "./dist/tsup/driver-helpers/mod.cjs"
      }
    },
    "./driver-helpers/websocket": {
      import: {
        types: "./dist/tsup/common/websocket.d.ts",
        default: "./dist/tsup/common/websocket.js"
      },
      require: {
        types: "./dist/tsup/common/websocket.d.cts",
        default: "./dist/tsup/common/websocket.cjs"
      }
    },
    "./driver-test-suite": {
      import: {
        types: "./dist/tsup/driver-test-suite/mod.d.ts",
        default: "./dist/tsup/driver-test-suite/mod.js"
      },
      require: {
        types: "./dist/tsup/driver-test-suite/mod.d.cts",
        default: "./dist/tsup/driver-test-suite/mod.cjs"
      }
    },
    "./serve-test-suite": {
      import: {
        types: "./dist/tsup/serve-test-suite/mod.d.ts",
        default: "./dist/tsup/serve-test-suite/mod.js"
      },
      require: {
        types: "./dist/tsup/serve-test-suite/mod.d.cts",
        default: "./dist/tsup/serve-test-suite/mod.cjs"
      }
    },
    "./topologies/coordinate": {
      import: {
        types: "./dist/tsup/topologies/coordinate/mod.d.ts",
        default: "./dist/tsup/topologies/coordinate/mod.js"
      },
      require: {
        types: "./dist/tsup/topologies/coordinate/mod.d.cts",
        default: "./dist/tsup/topologies/coordinate/mod.cjs"
      }
    },
    "./topologies/partition": {
      import: {
        types: "./dist/tsup/topologies/partition/mod.d.ts",
        default: "./dist/tsup/topologies/partition/mod.js"
      },
      require: {
        types: "./dist/tsup/topologies/partition/mod.d.cts",
        default: "./dist/tsup/topologies/partition/mod.cjs"
      }
    },
    "./test": {
      import: {
        types: "./dist/tsup/test/mod.d.ts",
        default: "./dist/tsup/test/mod.js"
      },
      require: {
        types: "./dist/tsup/test/mod.d.cts",
        default: "./dist/tsup/test/mod.cjs"
      }
    },
    "./inspector": {
      import: {
        types: "./dist/tsup/inspector/mod.d.ts",
        default: "./dist/tsup/inspector/mod.js"
      },
      require: {
        types: "./dist/tsup/inspector/mod.d.cts",
        default: "./dist/tsup/inspector/mod.cjs"
      }
    },
    "./inspector/client": {
      import: {
        types: "./dist/browser/inspector/client.d.ts",
        default: "./dist/browser/inspector/client.js"
      }
    },
    "./db": {
      import: {
        types: "./dist/tsup/db/mod.d.ts",
        default: "./dist/tsup/db/mod.js"
      },
      require: {
        types: "./dist/tsup/db/mod.d.cts",
        default: "./dist/tsup/db/mod.cjs"
      }
    },
    "./db/drizzle": {
      import: {
        types: "./dist/tsup/db/drizzle/mod.d.ts",
        default: "./dist/tsup/db/drizzle/mod.js"
      },
      require: {
        types: "./dist/tsup/db/drizzle/mod.d.cts",
        default: "./dist/tsup/db/drizzle/mod.cjs"
      }
    }
  },
  engines: {
    node: ">=22.0.0"
  },
  sideEffects: [
    "./dist/tsup/chunk-*.js",
    "./dist/tsup/chunk-*.cjs"
  ],
  scripts: {
    build: "tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/topologies/coordinate/mod.ts src/topologies/partition/mod.ts src/utils.ts src/driver-helpers/mod.ts src/driver-test-suite/mod.ts src/serve-test-suite/mod.ts src/test/mod.ts src/inspector/mod.ts src/workflow/mod.ts src/db/mod.ts src/db/drizzle/mod.ts",
    "build:browser": "tsup --config tsup.browser.config.ts",
    "build:schema": "./scripts/compile-bare.ts compile schemas/client-protocol/v1.bare -o dist/schemas/client-protocol/v1.ts && ./scripts/compile-bare.ts compile schemas/client-protocol/v2.bare -o dist/schemas/client-protocol/v2.ts && ./scripts/compile-bare.ts compile schemas/client-protocol/v3.bare -o dist/schemas/client-protocol/v3.ts && ./scripts/compile-bare.ts compile schemas/file-system-driver/v1.bare -o dist/schemas/file-system-driver/v1.ts && ./scripts/compile-bare.ts compile schemas/file-system-driver/v2.bare -o dist/schemas/file-system-driver/v2.ts && ./scripts/compile-bare.ts compile schemas/file-system-driver/v3.bare -o dist/schemas/file-system-driver/v3.ts && ./scripts/compile-bare.ts compile schemas/actor-persist/v1.bare -o dist/schemas/actor-persist/v1.ts && ./scripts/compile-bare.ts compile schemas/actor-persist/v2.bare -o dist/schemas/actor-persist/v2.ts && ./scripts/compile-bare.ts compile schemas/actor-persist/v3.bare -o dist/schemas/actor-persist/v3.ts && ./scripts/compile-bare.ts compile schemas/actor-persist/v4.bare -o dist/schemas/actor-persist/v4.ts && ./scripts/compile-bare.ts compile schemas/persist/v1.bare -o dist/schemas/persist/v1.ts && ./scripts/compile-bare.ts compile schemas/transport/v1.bare -o dist/schemas/transport/v1.ts && ./scripts/compile-bare.ts compile schemas/actor-inspector/v1.bare -o dist/schemas/actor-inspector/v1.ts && ./scripts/compile-bare.ts compile schemas/actor-inspector/v2.bare -o dist/schemas/actor-inspector/v2.ts && ./scripts/compile-bare.ts compile schemas/actor-inspector/v3.bare -o dist/schemas/actor-inspector/v3.ts",
    "check-types": "tsc --noEmit",
    lint: "biome check .",
    "lint:fix": "biome check --write .",
    format: "biome format .",
    "format:write": "biome format --write .",
    test: "vitest run",
    "test:watch": "vitest",
    "manager-openapi-gen": "tsx scripts/manager-openapi-gen.ts",
    "dump-asyncapi": "tsx scripts/dump-asyncapi.ts",
    "registry-config-schema-gen": "tsx scripts/registry-config-schema-gen.ts",
    "actor-config-schema-gen": "tsx scripts/actor-config-schema-gen.ts",
    "build:pack-inspector": "tsx scripts/pack-inspector.ts"
  },
  dependencies: {
    "@hono/standard-validator": "^0.1.3",
    "@hono/zod-openapi": "^1.1.5",
    "@rivetkit/bare-ts": "^0.6.2",
    "@rivetkit/engine-runner": "workspace:*",
    "@rivetkit/fast-json-patch": "^3.1.2",
    "@rivetkit/on-change": "^6.0.2-rc.1",
    "@rivetkit/sqlite-vfs": "workspace:*",
    "@rivetkit/traces": "workspace:*",
    "@rivetkit/virtual-websocket": "workspace:*",
    "@rivetkit/workflow-engine": "workspace:*",
    "cbor-x": "^1.6.0",
    "get-port": "^7.1.0",
    hono: "^4.7.0",
    invariant: "^2.2.4",
    nanoevents: "^9.1.0",
    "p-retry": "^6.2.1",
    pino: "^9.5.0",
    tar: "^7.5.0",
    uuid: "^12.0.0",
    vbare: "^0.0.4",
    "@rivetkit/sqlite": "^0.1.1",
    zod: "^4.1.0"
  },
  devDependencies: {
    "@bare-ts/tools": "^0.13.0",
    "@biomejs/biome": "^2.3",
    "@hono/node-server": "^1.18.2",
    "@hono/node-ws": "^1.1.1",
    "@standard-schema/spec": "^1.0.0",
    "@types/invariant": "^2",
    "@types/node": "^22.13.1",
    "@types/ws": "^8",
    "@vitest/ui": "3.1.1",
    "cli-table3": "^0.6.5",
    commander: "^12.1.0",
    eventsource: "^4.0.0",
    "local-pkg": "^0.5.1",
    tsup: "^8.4.0",
    tsx: "^4.19.4",
    typescript: "^5.7.3",
    "vite-tsconfig-paths": "^5.1.4",
    vitest: "^3.1.1",
    ws: "^8.18.1",
    "zod-to-json-schema": "^3.25.0"
  },
  peerDependencies: {
    "@hono/node-server": "^1.14.0",
    "@hono/node-ws": "^1.1.1",
    "drizzle-kit": "^0.31.2",
    "drizzle-orm": "^0.44.2",
    eventsource: "^4.0.0",
    ws: "^8.0.0"
  },
  peerDependenciesMeta: {
    "@hono/node-server": {
      optional: true
    },
    "@hono/node-ws": {
      optional: true
    },
    "drizzle-kit": {
      optional: true
    },
    "drizzle-orm": {
      optional: true
    },
    eventsource: {
      optional: true
    },
    ws: {
      optional: true
    }
  },
  stableVersion: "0.8.0"
};

// src/common/log.ts



var _pino = require('pino');
var _v4 = require('zod/v4');

// src/common/log-levels.ts
var LogLevels = {
  TRACE: 0,
  DEBUG: 1,
  INFO: 2,
  WARN: 3,
  ERROR: 4,
  CRITICAL: 5
};

// src/common/logfmt.ts
var LOG_LEVEL_COLORS = {
  [LogLevels.CRITICAL]: "\x1B[31m",
  // Red
  [LogLevels.ERROR]: "\x1B[31m",
  // Red
  [LogLevels.WARN]: "\x1B[33m",
  // Yellow
  [LogLevels.INFO]: "\x1B[32m",
  // Green
  [LogLevels.DEBUG]: "\x1B[36m",
  // Cyan
  [LogLevels.TRACE]: "\x1B[36m"
  // Cyan
};
var RESET_COLOR = "\x1B[0m";
function stringify(data) {
  let line = "";
  const entries = Object.entries(data);
  for (let i = 0; i < entries.length; i++) {
    const [key, valueRaw] = entries[i];
    let isNull = false;
    let valueString;
    if (valueRaw == null) {
      isNull = true;
      valueString = "";
    } else {
      valueString = valueRaw.toString();
    }
    if (valueString.length > 512 && key !== "msg" && key !== "error")
      valueString = `${valueString.slice(0, 512)}...`;
    const needsQuoting = valueString.indexOf(" ") > -1 || valueString.indexOf("=") > -1;
    const needsEscaping = valueString.indexOf('"') > -1 || valueString.indexOf("\\") > -1;
    valueString = valueString.replace(/\n/g, "\\n");
    if (needsEscaping) valueString = valueString.replace(/["\\]/g, "\\$&");
    if (needsQuoting || needsEscaping) valueString = `"${valueString}"`;
    if (valueString === "" && !isNull) valueString = '""';
    if (LOGGER_CONFIG.enableColor) {
      let color = "\x1B[2m";
      if (key === "level") {
        const level = LogLevels[valueString];
        const levelColor = LOG_LEVEL_COLORS[level];
        if (levelColor) {
          color = levelColor;
        }
      } else if (key === "msg") {
        color = "\x1B[32m";
      } else if (key === "trace") {
        color = "\x1B[34m";
      }
      line += `\x1B[0m\x1B[1m${key}\x1B[0m\x1B[2m=\x1B[0m${color}${valueString}${RESET_COLOR}`;
    } else {
      line += `${key}=${valueString}`;
    }
    if (i !== entries.length - 1) {
      line += " ";
    }
  }
  return line;
}
function formatTimestamp(date) {
  const year = date.getUTCFullYear();
  const month = String(date.getUTCMonth() + 1).padStart(2, "0");
  const day = String(date.getUTCDate()).padStart(2, "0");
  const hours = String(date.getUTCHours()).padStart(2, "0");
  const minutes = String(date.getUTCMinutes()).padStart(2, "0");
  const seconds = String(date.getUTCSeconds()).padStart(2, "0");
  const milliseconds = String(date.getUTCMilliseconds()).padStart(3, "0");
  return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}Z`;
}
function castToLogValue(v) {
  if (typeof v === "string" || typeof v === "number" || typeof v === "bigint" || typeof v === "boolean" || v === null || v === void 0) {
    return v;
  }
  if (v instanceof Error) {
    return String(v);
  }
  try {
    return JSON.stringify(v);
  } catch (e2) {
    return "[cannot stringify]";
  }
}
var LOGGER_CONFIG = {
  enableColor: false,
  enableSpreadObject: false,
  enableErrorStack: false
};

// src/common/log.ts
var baseLogger;
var configuredLogLevel;
var loggerCache = /* @__PURE__ */ new Map();
var LogLevelSchema = _v4.z.enum([
  "trace",
  "debug",
  "info",
  "warn",
  "error",
  "fatal",
  "silent"
]);
function getPinoLevel(logLevel) {
  if (logLevel) {
    return logLevel;
  }
  if (configuredLogLevel) {
    return configuredLogLevel;
  }
  const raw = (getLogLevel() || "warn").toString().toLowerCase();
  const parsed = LogLevelSchema.safeParse(raw);
  if (parsed.success) {
    return parsed.data;
  }
  return "info";
}
function getIncludeTarget() {
  return getLogTarget();
}
function configureBaseLogger(logger2) {
  baseLogger = logger2;
  loggerCache.clear();
}
function customWrite(level, o) {
  const entries = {};
  if (getLogTimestamp() && o.time) {
    const date = typeof o.time === "number" ? new Date(o.time) : /* @__PURE__ */ new Date();
    entries.ts = formatTimestamp(date);
  }
  entries.level = level.toUpperCase();
  if (o.target) {
    entries.target = o.target;
  }
  if (o.msg) {
    entries.msg = o.msg;
  }
  for (const [key, value] of Object.entries(o)) {
    if (key !== "time" && key !== "level" && key !== "target" && key !== "msg" && key !== "pid" && key !== "hostname") {
      entries[key] = castToLogValue(value);
    }
  }
  const output = stringify(entries);
  console.log(output);
}
function configureDefaultLogger(logLevel) {
  if (logLevel) {
    configuredLogLevel = logLevel;
  }
  baseLogger = _pino.pino.call(void 0, {
    level: getPinoLevel(logLevel),
    messageKey: "msg",
    // Do not include pid/hostname in output
    base: {},
    // Keep a string level in the output
    formatters: {
      level(_label, number) {
        return { level: number };
      }
    },
    timestamp: getLogTimestamp() ? _pino.stdTimeFunctions.epochTime : false,
    browser: {
      write: {
        fatal: customWrite.bind(null, "fatal"),
        error: customWrite.bind(null, "error"),
        warn: customWrite.bind(null, "warn"),
        info: customWrite.bind(null, "info"),
        debug: customWrite.bind(null, "debug"),
        trace: customWrite.bind(null, "trace")
      }
    },
    hooks: {
      logMethod(inputArgs, method, level) {
        var _a;
        const levelMap = {
          10: "trace",
          20: "debug",
          30: "info",
          40: "warn",
          50: "error",
          60: "fatal"
        };
        const levelName = levelMap[level] || "info";
        const time = getLogTimestamp() ? Date.now() : void 0;
        const bindings = ((_a = this.bindings) == null ? void 0 : _a.call(this)) || {};
        if (inputArgs.length >= 2) {
          const [objOrMsg, msg] = inputArgs;
          if (typeof objOrMsg === "object" && objOrMsg !== null) {
            customWrite(levelName, {
              ...bindings,
              ...objOrMsg,
              msg,
              time
            });
          } else {
            customWrite(levelName, {
              ...bindings,
              msg: String(objOrMsg),
              time
            });
          }
        } else if (inputArgs.length === 1) {
          const [objOrMsg] = inputArgs;
          if (typeof objOrMsg === "object" && objOrMsg !== null) {
            customWrite(levelName, {
              ...bindings,
              ...objOrMsg,
              time
            });
          } else {
            customWrite(levelName, {
              ...bindings,
              msg: String(objOrMsg),
              time
            });
          }
        }
      }
    }
  });
  loggerCache.clear();
}
function getBaseLogger() {
  if (!baseLogger) {
    configureDefaultLogger();
  }
  return baseLogger;
}
function getLogger(name = "default") {
  const cached = loggerCache.get(name);
  if (cached) {
    return cached;
  }
  const base = getBaseLogger();
  const child = getIncludeTarget() ? base.child({ target: name }) : base;
  loggerCache.set(name, child);
  return child;
}

// src/utils.ts
function joinSignals(...signals) {
  const validSignals = signals.filter(
    (signal) => signal != null
  );
  if (validSignals.length === 0) {
    return new AbortController().signal;
  }
  if (validSignals.length === 1) {
    return validSignals[0];
  }
  const signalAny = AbortSignal.any;
  if (typeof signalAny === "function") {
    return signalAny(validSignals);
  }
  const controller = new AbortController();
  const cleanups = [];
  const abortWithSignal = (signal) => {
    if (controller.signal.aborted) {
      return;
    }
    for (const cleanup of cleanups) {
      cleanup();
    }
    const reason = signal.reason;
    controller.abort(reason);
  };
  for (const signal of validSignals) {
    if (signal.aborted) {
      abortWithSignal(signal);
      break;
    }
    const onAbort = () => abortWithSignal(signal);
    signal.addEventListener("abort", onAbort, { once: true });
    cleanups.push(() => signal.removeEventListener("abort", onAbort));
  }
  return controller.signal;
}
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
function interval(ms) {
  return () => sleep(ms);
}
var VERSION2 = package_default.version;
var _userAgent;
function logger() {
  return getLogger("utils");
}
function httpUserAgent() {
  if (_userAgent !== void 0) {
    return _userAgent;
  }
  let userAgent = `RivetKit/${VERSION2}`;
  const navigatorObj = typeof navigator !== "undefined" ? navigator : void 0;
  if (navigatorObj == null ? void 0 : navigatorObj.userAgent) userAgent += ` ${navigatorObj.userAgent}`;
  _userAgent = userAgent;
  return userAgent;
}
function getEnvUniversal(key) {
  if (typeof Deno !== "undefined") {
    return Deno.env.get(key);
  } else if (typeof process !== "undefined") {
    return process.env[key];
  }
}
function dbg(x) {
  console.trace(`=== DEBUG ===
${x}`);
  return x;
}
function toUint8Array(data) {
  if (data instanceof Uint8Array) {
    return data;
  } else if (data instanceof ArrayBuffer) {
    return new Uint8Array(data);
  } else if (ArrayBuffer.isView(data)) {
    return new Uint8Array(
      data.buffer.slice(
        data.byteOffset,
        data.byteOffset + data.byteLength
      )
    );
  } else {
    throw new TypeError("Input must be ArrayBuffer or ArrayBufferView");
  }
}
var TIMEOUT_MAX = 2147483647;
function promiseWithResolvers(onReject) {
  let resolve;
  let reject;
  const promise = new Promise((res, rej) => {
    resolve = res;
    reject = rej;
  });
  promise.catch(onReject);
  return { promise, resolve, reject };
}
function setLongTimeout(listener, after) {
  let timeout;
  function start(remaining) {
    if (remaining <= TIMEOUT_MAX) {
      timeout = setTimeout(listener, remaining);
    } else {
      timeout = setTimeout(() => {
        start(remaining - TIMEOUT_MAX);
      }, TIMEOUT_MAX);
    }
  }
  start(after);
  return {
    abort: () => {
      if (timeout !== void 0) clearTimeout(timeout);
    }
  };
}
var SinglePromiseQueue = class {
  /** Next operation to execute in the queue. If attempting to enqueue another op, it will override the existing op. */
  #queuedOp;
  /** The currently running promise of #drainLoop. Do not await this, instead await `pending` to await the current cycle. */
  
  /** Pending resolver fro the currently queued entry. */
  #pending;
  /** Queue the next operation and return a promise that resolves when it flushes. */
  enqueue(op) {
    this.#queuedOp = op;
    if (!this.#pending) {
      this.#pending = promiseWithResolvers((reason) => logger().warn({ msg: "unhandled single promise queue rejection", reason }));
    }
    const waitForThisCycle = this.#pending.promise;
    if (!this.runningDrainLoop) {
      this.runningDrainLoop = this.#drainLoop();
    }
    return waitForThisCycle;
  }
  /** Drain queued operations sequentially until there is nothing left. */
  async #drainLoop() {
    try {
      while (this.#queuedOp) {
        const resolver = this.#pending;
        this.#pending = void 0;
        const op = this.#queuedOp;
        this.#queuedOp = void 0;
        try {
          await op();
          resolver == null ? void 0 : resolver.resolve();
        } catch (err) {
          logger().error({
            msg: "error in SinglePromiseQueue drain loop",
            error: stringifyError(err)
          });
          resolver == null ? void 0 : resolver.reject(err);
        }
      }
    } finally {
      this.runningDrainLoop = void 0;
    }
  }
};
function bufferToArrayBuffer(buf) {
  return buf.buffer.slice(
    buf.byteOffset,
    buf.byteOffset + buf.byteLength
  );
}
function combineUrlPath(endpoint, path, queryParams) {
  const baseUrl = new URL(endpoint);
  const pathParts = path.split("?");
  const pathOnly = pathParts[0];
  const existingQuery = pathParts[1] || "";
  const basePath = baseUrl.pathname.replace(/\/$/, "");
  const cleanPath = pathOnly.startsWith("/") ? pathOnly : `/${pathOnly}`;
  const fullPath = (basePath + cleanPath).replace(/\/\//g, "/");
  const queryParts = [];
  if (existingQuery) {
    queryParts.push(existingQuery);
  }
  if (queryParams) {
    for (const [key, value] of Object.entries(queryParams)) {
      if (value !== void 0) {
        queryParts.push(
          `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
        );
      }
    }
  }
  const fullQuery = queryParts.length > 0 ? `?${queryParts.join("&")}` : "";
  return `${baseUrl.protocol}//${baseUrl.host}${fullPath}${fullQuery}`;
}
function arrayBuffersEqual(buf1, buf2) {
  if (buf1.byteLength !== buf2.byteLength) return false;
  const view1 = new Uint8Array(buf1);
  const view2 = new Uint8Array(buf2);
  for (let i = 0; i < view1.length; i++) {
    if (view1[i] !== view2[i]) return false;
  }
  return true;
}
var EXTRA_ERROR_LOG = {
  issues: "https://github.com/rivet-dev/rivetkit/issues",
  support: "https://rivet.dev/discord",
  version: VERSION2
};
function detectRuntime() {
  const userAgent = typeof navigator !== "undefined" ? navigator.userAgent : "";
  if (userAgent.includes("Deno")) {
    return "deno";
  }
  if (userAgent.includes("Bun")) {
    return "bun";
  }
  return "node";
}





















































exports.assertUnreachable = assertUnreachable; exports.isCborSerializable = isCborSerializable; exports.deconstructError = deconstructError; exports.stringifyError = stringifyError; exports.noopNext = noopNext; exports.package_default = package_default; exports.joinSignals = joinSignals; exports.sleep = sleep; exports.interval = interval; exports.VERSION = VERSION2; exports.httpUserAgent = httpUserAgent; exports.getEnvUniversal = getEnvUniversal; exports.dbg = dbg; exports.toUint8Array = toUint8Array; exports.promiseWithResolvers = promiseWithResolvers; exports.setLongTimeout = setLongTimeout; exports.SinglePromiseQueue = SinglePromiseQueue; exports.bufferToArrayBuffer = bufferToArrayBuffer; exports.combineUrlPath = combineUrlPath; exports.arrayBuffersEqual = arrayBuffersEqual; exports.EXTRA_ERROR_LOG = EXTRA_ERROR_LOG; exports.detectRuntime = detectRuntime; exports.getRivetEngine = getRivetEngine; exports.getRivetEndpoint = getRivetEndpoint; exports.getRivetToken = getRivetToken; exports.getRivetNamespace = getRivetNamespace; exports.getRivetRunner = getRivetRunner; exports.getRivetTotalSlots = getRivetTotalSlots; exports.getRivetRunnerKey = getRivetRunnerKey; exports.getRivetRunEngine = getRivetRunEngine; exports.getRivetRunEngineVersion = getRivetRunEngineVersion; exports.getRivetRunnerKind = getRivetRunnerKind; exports.getRivetRunnerVersion = getRivetRunnerVersion; exports.getRivetPublicEndpoint = getRivetPublicEndpoint; exports.getRivetPublicToken = getRivetPublicToken; exports.getRivetkitInspectorToken = getRivetkitInspectorToken; exports.getRivetkitInspectorDisable = getRivetkitInspectorDisable; exports.getRivetkitStoragePath = getRivetkitStoragePath; exports.getLogMessage = getLogMessage; exports.getLogHeaders = getLogHeaders; exports.getNodeEnv = getNodeEnv; exports.getNextPhase = getNextPhase; exports.isDev = isDev; exports.getRivetExperimentalOtel = getRivetExperimentalOtel; exports.LogLevelSchema = LogLevelSchema; exports.getPinoLevel = getPinoLevel; exports.getIncludeTarget = getIncludeTarget; exports.configureBaseLogger = configureBaseLogger; exports.configureDefaultLogger = configureDefaultLogger; exports.getBaseLogger = getBaseLogger; exports.getLogger = getLogger;
//# sourceMappingURL=chunk-MMUXNMJF.cjs.map