openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
42,388 lines • 1.61 MB
JavaScript
import { createRequire } from "node:module";
import { once } from "node:events";
import fs, { chmodSync, closeSync, createWriteStream, existsSync, readFileSync, readdirSync, realpathSync, statSync, unlinkSync, writeFileSync, default as openClawRootFsSync } from "node:fs";
import { Socket } from "node:net";
import { pipeline } from "node:stream";
import childProcess, { spawn, spawnSync } from "node:child_process";
import path, { basename, posix } from "node:path";
import os, { availableParallelism, endianness } from "node:os";
import { toUSVString } from "node:util";
import { AsyncLocalStorage, AsyncResource } from "node:async_hooks";
import { MessageChannel, MessagePort, Worker, getEnvironmentData, isMainThread, receiveMessageOnPort, setEnvironmentData, threadId, workerData } from "node:worker_threads";
import { hasNodeErrorCode as hasErrnoCode, isPathInside, isPathInside as isPathInside$1, normalizeWindowsPathForComparison } from "@openclaw/fs-safe/path";
import { performance as performance$1 } from "node:perf_hooks";
import { fileURLToPath, pathToFileURL } from "node:url";
import { appendRegularFile, appendRegularFileSync, canUseRootFileOpen, openRootFileSync, readFileWindowFullySync, sameFileIdentity } from "@openclaw/fs-safe/advanced";
import { createHash, hash, randomUUID } from "node:crypto";
import "@openclaw/fs-safe/errors";
import { channel } from "node:diagnostics_channel";
import { parse } from "semver";
import fsPromises, { realpath, stat } from "node:fs/promises";
import { sha256FileSync, syncDirectorySync } from "@openclaw/fs-safe/durability";
import { acquireFileLockSync } from "@openclaw/fs-safe/file-lock";
import { deserialize, serialize } from "node:v8";
import { isPromise } from "node:util/types";
import { Chalk } from "chalk";
import { Logger } from "tslog";
import "@openclaw/fs-safe/copy";
import { readRootJsonObjectSync } from "@openclaw/fs-safe/json";
import "@openclaw/fs-safe/output";
import "@openclaw/fs-safe/root";
import "@openclaw/fs-safe/secure-file";
import "@openclaw/fs-safe/walk";
import "json5";
import zlib from "node:zlib";
//#region \0rolldown/runtime.js
var __defProp = Object.defineProperty;
var __esmMin = (fn, res, err) => () => {
if (err) throw err[0];
try {
return fn && (res = fn(fn = 0)), res;
} catch (e) {
throw err = [e], e;
}
};
var __exportAll = (all, no_symbols) => {
let target = {};
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
return target;
};
//#endregion
//#region packages/normalization-core/src/record-coerce.ts
/** Type guard for non-array object records at browser-safe boundaries. */
function isRecord(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
/** Returns a non-array record or null. */
function asNullableRecord(value) {
return isRecord(value) ? value : null;
}
/** Returns any object-backed record, including arrays, or undefined. */
function asOptionalObjectRecord(value) {
return value && typeof value === "object" ? value : void 0;
}
var init_record_coerce = __esmMin((() => {}));
//#endregion
//#region src/shared/deferred.ts
function createDeferredCore() {
return promiseWithResolvers.withResolvers();
}
var promiseWithResolvers;
var init_deferred$1 = __esmMin((() => {
promiseWithResolvers = Promise;
}));
//#endregion
//#region src/process/linux-oom-score.ts
init_deferred$1();
const OOM_SCORE_WRAP_SHELL = "/bin/sh";
const OOM_SCORE_WRAP_SCRIPT = "echo 1000 > /proc/self/oom_score_adj 2>/dev/null; exec \"$0\" \"$@\"";
[
"echo 1000 > /proc/self/oom_score_adj 2>/dev/null; if [ \"${OC_INTERNAL_OOM_EXEC_BASH_ENV+x}\" = x ]; then BASH_ENV=\"$OC_INTERNAL_OOM_EXEC_BASH_ENV\"; export BASH_ENV; fi; unset OC_INTERNAL_OOM_EXEC_BASH_ENV",
"if [ \"${OC_INTERNAL_OOM_EXEC_ENV+x}\" = x ]; then ENV=\"$OC_INTERNAL_OOM_EXEC_ENV\"; export ENV; fi; unset OC_INTERNAL_OOM_EXEC_ENV",
"if [ \"${OC_INTERNAL_OOM_EXEC_CDPATH+x}\" = x ]; then CDPATH=\"$OC_INTERNAL_OOM_EXEC_CDPATH\"; export CDPATH; fi; unset OC_INTERNAL_OOM_EXEC_CDPATH",
"if [ \"${OC_INTERNAL_OOM_EXEC_PS4+x}\" = x ]; then PS4=\"$OC_INTERNAL_OOM_EXEC_PS4\"; export PS4; fi; unset OC_INTERNAL_OOM_EXEC_PS4; exec \"$0\" \"$@\""
].join("; ");
function isWrapped(command, args) {
return command === OOM_SCORE_WRAP_SHELL && args[0] === "-c" && args[1] === OOM_SCORE_WRAP_SCRIPT;
}
/** Only small spawn owners may temporarily raise their score; never call from the Gateway. */
function spawnWithInheritedOomScore(command, args, options) {
if (process.platform !== "linux" || !isWrapped(command, args) || !args[2] || options.shell || options.argv0 !== void 0) return spawn(command, args, options);
let scoreFd;
let original;
try {
scoreFd = fs.openSync("/proc/self/oom_score_adj", "r+");
original = fs.readFileSync(scoreFd, "utf8").trim();
fs.writeSync(scoreFd, "1000", 0, "utf8");
} catch {
if (scoreFd !== void 0) fs.closeSync(scoreFd);
return spawn(command, args, options);
}
try {
return spawn(args[2], args.slice(3), options);
} finally {
try {
fs.writeSync(scoreFd, original, 0, "utf8");
} catch {
process.emitWarning("Could not restore spawn owner's Linux OOM score");
} finally {
fs.closeSync(scoreFd);
}
}
}
//#endregion
//#region src/process/supervisor/cancellation-policy.ts
var GRACEFUL_CANCEL_TIMEOUT_MS;
var init_cancellation_policy = __esmMin((() => {
GRACEFUL_CANCEL_TIMEOUT_MS = 5e3;
}));
//#endregion
//#region packages/normalization-core/src/error-coercion.ts
function isErrorObject(value) {
try {
if (value instanceof Error) return true;
return Object.prototype.toString.call(value) === "[object Error]";
} catch {
return false;
}
}
function isAggregateErrorObject(error) {
try {
if (error instanceof AggregateError) return true;
for (let proto = Object.getPrototypeOf(error); proto; proto = Object.getPrototypeOf(proto)) {
const constructor = Object.getOwnPropertyDescriptor(proto, "constructor")?.value;
if (typeof constructor === "function" && constructor.name === "AggregateError") return true;
}
} catch {}
return false;
}
function readProperty(value, key) {
try {
return value[key];
} catch {
return;
}
}
function readErrorText(value, key) {
const field = readProperty(value, key);
return typeof field === "string" ? field : void 0;
}
function formatStatusAndCode(value) {
if ((typeof value !== "object" || value === null) && typeof value !== "function") return;
try {
if (Object.keys(value).some((key) => key !== "status" && key !== "code")) return;
} catch {}
const statusValue = readProperty(value, "status");
const codeValue = readProperty(value, "code");
if (statusValue === void 0 && codeValue === void 0) return;
return `status=${typeof statusValue === "string" || typeof statusValue === "number" ? String(statusValue) : "unknown"} code=${typeof codeValue === "string" || typeof codeValue === "number" ? String(codeValue) : "unknown"}`;
}
function stringifyUnknown(value) {
if (value === null || typeof value !== "object" && typeof value !== "function") return String(value);
try {
const json = JSON.stringify(value);
if (json !== void 0) return json;
} catch {}
try {
return Object.prototype.toString.call(value);
} catch {
return "Unknown error";
}
}
function readErrorCauses(current) {
if (!isErrorObject(current)) return [];
const cause = readProperty(current, "cause");
const errors = isAggregateErrorObject(current) ? readProperty(current, "errors") : void 0;
const suppressed = readErrorText(current, "name") === "SuppressedError" ? [readProperty(current, "error"), readProperty(current, "suppressed")].map((failure) => failure == null ? String(failure) : failure) : [];
return [
cause || void 0,
...Array.isArray(errors) ? errors : [],
...suppressed
];
}
/** Formats unknown errors with cause/aggregate details, structured codes, and secret redaction. */
function formatErrorMessage$1(value, options) {
let formatted;
if (isErrorObject(value)) {
formatted = readErrorText(value, "message") || readErrorText(value, "name") || "Error";
const seenMessages = /* @__PURE__ */ new Set([formatted]);
const appendCauseMessage = (message) => {
if (!message || seenMessages.has(message)) return;
formatted += ` | ${message}`;
seenMessages.add(message);
};
const appendCauseErrorMessage = (message) => {
if (message && formatted.includes(message)) {
seenMessages.add(message);
return;
}
appendCauseMessage(message);
};
if (options.includeCode) {
const code = readProperty(value, "code");
if (typeof code === "string" || typeof code === "number") appendCauseMessage(String(code));
}
const causes = collectErrorGraphCandidates(value, readErrorCauses);
for (const cause of causes.slice(1)) if (isErrorObject(cause)) {
appendCauseErrorMessage(readErrorText(cause, "message"));
const code = readProperty(cause, "code");
if (typeof code === "string" || typeof code === "number") appendCauseMessage(String(code));
} else if (typeof cause === "string") appendCauseMessage(cause);
else appendCauseMessage(formatStatusAndCode(cause) ?? stringifyUnknown(cause));
} else formatted = formatStatusAndCode(value) ?? stringifyUnknown(value);
return options.redact(formatted);
}
/**
* Normalizes an unknown thrown value into an Error. Non-Error objects become
* the `cause` and have their enumerable fields copied so structured details
* (codes, statuses) survive the coercion.
*/
function toErrorObject(value, fallbackMessage) {
if (value instanceof Error) return value;
if (typeof value === "string") return new Error(value);
const error = new Error(fallbackMessage, { cause: value });
if (typeof value === "object" && value !== null || typeof value === "function") Object.assign(error, value);
return error;
}
/** Reads Error messages unchanged and stringifies every other value. */
function coerceErrorMessage(value) {
return value instanceof Error ? value.message : String(value);
}
function extractErrorCode(err) {
if (!err || typeof err !== "object") return;
const code = readProperty(err, "code");
if (typeof code === "string") return code;
if (typeof code === "number") return String(code);
}
function collectErrorGraphCandidates(err, resolveNested) {
if (err == null) return [];
const candidates = [err];
const seen = (/* @__PURE__ */ new Set()).add(err);
for (const current of candidates) {
if (!current || typeof current !== "object" || !resolveNested) continue;
for (const nested of resolveNested(current)) if (nested != null && !seen.has(nested)) {
seen.add(nested);
candidates.push(nested);
}
}
return candidates;
}
var init_error_coercion = __esmMin((() => {}));
//#endregion
//#region src/infra/process-env.ts
/** Read one environment value using the same Windows key precedence as child_process. */
function resolveEnvironmentValue(env, name, platform = process.platform) {
if (!env) return;
if (platform !== "win32") return env[name] ?? (name === "PATH" ? env.Path : void 0);
const normalizedName = name.toUpperCase();
const key = Object.keys(env).toSorted().find((candidate) => candidate.toUpperCase() === normalizedName);
return key === void 0 ? void 0 : env[key];
}
/** Merge child environments while preserving Node's platform-specific key semantics. */
function mergeProcessEnv(sources, platform = process.platform) {
const merged = {};
for (const source of sources) {
if (!source) continue;
const keys = Object.keys(source);
const sourceKeys = /* @__PURE__ */ new Set();
for (const key of platform === "win32" ? keys.toSorted() : keys) {
if (platform === "win32") {
const normalizedKey = key.toUpperCase();
if (sourceKeys.has(normalizedKey)) continue;
sourceKeys.add(normalizedKey);
for (const previousKey of Object.keys(merged)) if (previousKey.toUpperCase() === normalizedKey) delete merged[previousKey];
}
const value = source[key];
if (value === void 0) delete merged[key];
else merged[key] = value;
}
}
return merged;
}
/** Project only native port/process diagnostic context; never mutate the parent environment. */
function resolveDiagnosticProcessEnv(env = process.env, platform = process.platform) {
return Object.fromEntries(Object.entries(mergeProcessEnv([env], platform)).filter(([key]) => DIAGNOSTIC_PROCESS_ENV_KEYS.has(platform === "win32" ? key.toUpperCase() : key)));
}
var DIAGNOSTIC_PROCESS_ENV_KEYS;
var init_process_env = __esmMin((() => {
DIAGNOSTIC_PROCESS_ENV_KEYS = /* @__PURE__ */ new Set([
"PATH",
"Path",
"HOME",
"USER",
"LOGNAME",
"TMPDIR",
"TMP",
"TEMP",
"LANG",
"LANGUAGE",
"TZ",
"LC_ALL",
"LC_COLLATE",
"LC_CTYPE",
"LC_MESSAGES",
"LC_MONETARY",
"LC_NUMERIC",
"LC_TIME",
"LC_ADDRESS",
"LC_IDENTIFICATION",
"LC_MEASUREMENT",
"LC_NAME",
"LC_PAPER",
"LC_TELEPHONE",
"SYSTEMROOT",
"WINDIR",
"COMSPEC",
"PATHEXT",
"SYSTEMDRIVE",
"USERPROFILE",
"HOMEDRIVE",
"HOMEPATH",
"USERNAME",
"USERDOMAIN",
"APPDATA",
"LOCALAPPDATA",
"PROGRAMDATA",
"ALLUSERSPROFILE",
"PROGRAMFILES",
"PROGRAMFILES(X86)",
"PROGRAMW6432",
"COMMONPROGRAMFILES",
"COMMONPROGRAMFILES(X86)",
"COMMONPROGRAMW6432",
"PSMODULEANALYSISCACHEPATH"
]);
}));
//#endregion
//#region src/infra/windows-process-start.ts
function loadNativeProcessStartTime() {
const kernel32 = createRequire(import.meta.url)("koffi").load("kernel32.dll");
const openProcess = kernel32.func("void * __stdcall OpenProcess(uint32_t access, int32_t inheritHandle, uint32_t processId)");
const getProcessTimes = kernel32.func("int32_t __stdcall GetProcessTimes(void *process, void *creation, void *exit, void *kernel, void *user)");
const closeHandle = kernel32.func("int32_t __stdcall CloseHandle(void *handle)");
return (pid) => {
const handle = openProcess(4096, 0, pid);
if (handle === null) return null;
try {
const creation = Buffer.alloc(8);
if (!getProcessTimes(handle, creation, Buffer.alloc(8), Buffer.alloc(8), Buffer.alloc(8))) return null;
const ticks = creation.readBigUInt64LE();
if (ticks === 0n) return null;
return Number(ticks / 10000n - 11644473600000n);
} finally {
closeHandle(handle);
}
};
}
function readNativeProcessStartTime(pid) {
if (process.platform !== "win32" || typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) return null;
try {
nativeProcessStartTime ??= loadNativeProcessStartTime();
return nativeProcessStartTime(pid);
} catch {
return null;
}
}
function windowsSystemRoot(env) {
const configured = resolveEnvironmentValue(env, "SystemRoot", "win32") ?? resolveEnvironmentValue(env, "WINDIR", "win32");
if (!configured) return DEFAULT_WINDOWS_SYSTEM_ROOT;
const normalized = path.win32.normalize(configured);
return /^[A-Za-z]:\\/.test(normalized) && !normalized.startsWith("\\\\") ? normalized : DEFAULT_WINDOWS_SYSTEM_ROOT;
}
function windowsPowerShellPath(env) {
return path.win32.join(windowsSystemRoot(env), "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
}
function windowsWmicPath(env) {
return path.win32.join(windowsSystemRoot(env), "System32", "wbem", "wmic.exe");
}
function decodeWindowsProcessOutput(output) {
if (!Buffer.isBuffer(output)) return output;
return output.length >= 2 && output[0] === 255 && output[1] === 254 ? output.toString("utf16le") : output.toString("utf8");
}
function parseWindowsProcessStartTime(raw) {
const lines = decodeWindowsProcessOutput(raw).split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
const value = lines.find((line) => line.toLowerCase().startsWith("creationdate="))?.slice(13).trim() ?? lines.find((line) => line.toLowerCase() !== "creationdate") ?? "";
const parsedIso = Date.parse(value);
if (Number.isFinite(parsedIso)) return parsedIso;
const dmtf = value.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);
if (!dmtf) return null;
const [, year, month, day, hour, minute, second, microseconds, offsetSign, offset] = dmtf;
return Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute), Number(second), Math.floor(Number(microseconds) / 1e3)) - Number(offset) * 6e4 * (offsetSign === "+" ? 1 : -1);
}
/** Read a stable Windows process creation time for lock-owner identity checks. */
function readWindowsProcessStartTimeSync(pid, timeoutMs = DEFAULT_PROCESS_START_TIMEOUT_MS, env = process.env) {
if (!Number.isInteger(pid) || pid <= 0 || pid > 4294967295) return null;
const deadline = Date.now() + timeoutMs;
const nativeStartTime = readNativeProcessStartTime(pid);
if (nativeStartTime !== null) return nativeStartTime;
const powershellBudgetMs = deadline - Date.now();
if (powershellBudgetMs <= 0) return null;
const powershell = spawnSync(windowsPowerShellPath(env), [
"-NoProfile",
"-NonInteractive",
"-Command",
`$process = [System.Diagnostics.Process]::GetProcessById(${pid}); try { [Console]::Out.Write($process.StartTime.ToUniversalTime().ToString("o")) } finally { $process.Dispose() }`
], {
encoding: "utf8",
env: resolveDiagnosticProcessEnv(env, "win32"),
timeout: Math.min(powershellBudgetMs, DEFAULT_TIMEOUT_MS),
windowsHide: true
});
if (!powershell.error && powershell.status === 0) {
const startTime = parseWindowsProcessStartTime(powershell.stdout);
if (startTime !== null) return startTime;
}
const remainingMs = deadline - Date.now();
if (remainingMs <= 0) return null;
const wmic = spawnSync(windowsWmicPath(env), [
"process",
"where",
`ProcessId=${pid}`,
"get",
"CreationDate",
"/value"
], {
env: resolveDiagnosticProcessEnv(env, "win32"),
timeout: remainingMs,
windowsHide: true,
stdio: [
"ignore",
"pipe",
"ignore"
]
});
return !wmic.error && wmic.status === 0 ? parseWindowsProcessStartTime(wmic.stdout) : null;
}
var DEFAULT_TIMEOUT_MS, DEFAULT_PROCESS_START_TIMEOUT_MS, DEFAULT_WINDOWS_SYSTEM_ROOT, nativeProcessStartTime;
var init_windows_process_start = __esmMin((() => {
init_process_env();
DEFAULT_TIMEOUT_MS = 5e3;
DEFAULT_PROCESS_START_TIMEOUT_MS = 1e4;
DEFAULT_WINDOWS_SYSTEM_ROOT = "C:\\Windows";
}));
//#endregion
//#region src/shared/freebsd-process-identity-native.ts
/** Normal installations use the dependency's public loader. */
function loadFreeBsdProcessIdentityNative() {
if (typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) throw new Error("FreeBSD process identity is unavailable in this sealed runtime");
return createRequire(import.meta.url)("koffi/indirect");
}
var init_freebsd_process_identity_native = __esmMin((() => {}));
//#endregion
//#region src/shared/freebsd-process-identity.ts
function getSysctl() {
if (!native) {
const library = loadFreeBsdProcessIdentityNative().load(null);
native = {
library,
sysctl: library.func("int sysctl(const int *name, unsigned int namelen, _Out_ void *oldp, _Inout_ size_t *oldlenp, const void *newp, size_t newlen)")
};
}
return native.sysctl;
}
function readTimeval(bytes, offset) {
const seconds = bytes.readBigInt64LE(offset);
const microseconds = bytes.readBigInt64LE(offset + 8);
if (seconds < 0n || microseconds < 0n || microseconds >= 1000000n) throw new Error("Invalid FreeBSD process identity timeval");
return seconds * 1000000n + microseconds;
}
/** Read the kernel's monotonic process start time in microseconds. */
function readFreeBsdProcessStartTime(pid) {
if (process.platform !== "freebsd" || process.arch !== "x64" && process.arch !== "arm64" || endianness() !== "LE" || !Number.isInteger(pid) || pid <= 0 || pid > 2147483647) return null;
try {
const sysctl = getSysctl();
const bytes = Buffer.alloc(1120);
for (const [mib, offset, length] of [
[
[1, 21],
0,
16
],
[
[
1,
14,
1,
pid
],
16,
1088
],
[
[1, 21],
1104,
16
]
]) {
const actual = [length];
if (sysctl(mib, mib.length, bytes.subarray(offset, offset + length), actual, null, 0) !== 0 || actual[0] !== length) return null;
}
if (bytes.readInt32LE(16) !== 1088 || bytes.readInt32LE(20) !== 0 || bytes.readInt32LE(88) !== pid || !bytes.subarray(0, 16).equals(bytes.subarray(1104))) return null;
const start = readTimeval(bytes, 352) - readTimeval(bytes, 0);
return start >= 0n && start <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(start) : null;
} catch {
return null;
}
}
var native;
var init_freebsd_process_identity = __esmMin((() => {
init_freebsd_process_identity_native();
}));
//#endregion
//#region src/shared/pid-alive.ts
function readDarwinNativeIdentity(pid) {
if (process.platform !== "darwin" || process.arch !== "arm64" || pid > 2147483647 || typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) return null;
try {
if (!darwinNative) {
const library = createRequire(import.meta.url)("koffi").load("/usr/lib/libproc.dylib");
darwinNative = {
library,
query: library.func("int proc_pidinfo(int pid, int flavor, uint64_t arg, _Out_ void *buffer, int buffersize)")
};
}
const bytes = Buffer.alloc(136);
if (darwinNative.query(pid, 3, 0, bytes, bytes.length) !== bytes.length) return null;
const parentPid = bytes.readUInt32LE(16);
const seconds = bytes.readBigUInt64LE(120);
const microseconds = bytes.readBigUInt64LE(128);
if (bytes.readUInt32LE(12) !== pid || parentPid > 2147483647 || seconds === 0n || seconds > BigInt(Number.MAX_SAFE_INTEGER) || microseconds >= 1000000n) return null;
return {
parentPid,
startedAt: Number(seconds),
microseconds: Number(microseconds)
};
} catch {
return null;
}
}
function isValidPid(pid) {
return Number.isInteger(pid) && pid > 0;
}
/**
* Check if every thread has exited by reading Linux /proc/<pid>/status.
* Returns false on non-Linux platforms or if the proc file can't be read.
*/
function isZombieProcess(pid) {
if (process.platform !== "linux") return false;
try {
const status = fs.readFileSync(`/proc/${pid}/status`, "utf8");
return status.match(/^State:\s+(\S)/m)?.[1] === "Z" && /^Threads:[ \t]+1[ \t]*$/m.test(status);
} catch {
return false;
}
}
/** Returns true only when a positive PID exists and is not a Linux zombie process. */
function isPidAlive(pid) {
if (!isValidPid(pid)) return false;
try {
process.kill(pid, 0);
} catch (err) {
if (err.code !== "EPERM") return false;
}
return !isZombieProcess(pid);
}
/** Returns true only when the PID is invalid, missing, or known to be a Linux zombie. */
function isPidDefinitelyDead(pid) {
if (!isValidPid(pid)) return true;
try {
process.kill(pid, 0);
} catch (err) {
return err.code === "ESRCH";
}
return isZombieProcess(pid);
}
function getDarwinProcessStartTime(pid, env, timeoutMs) {
const started = performance.now();
const native = readDarwinNativeIdentity(pid);
if (native) return native.startedAt;
const remainingMs = timeoutMs === void 0 ? PROCESS_START_TIMEOUT_MS : Math.ceil(timeoutMs - (performance.now() - started));
if (remainingMs <= 0) return null;
try {
const startedAt = childProcess.execFileSync("/bin/ps", [
"-o",
"lstart=",
"-p",
String(pid)
], {
encoding: "utf8",
env: {
...resolveDiagnosticProcessEnv(env),
LC_ALL: "C",
TZ: "UTC"
},
stdio: [
"ignore",
"pipe",
"ignore"
],
timeout: remainingMs,
killSignal: "SIGKILL"
}).trim();
const startedAtMs = Date.parse(`${startedAt} UTC`);
return Number.isFinite(startedAtMs) ? Math.floor(startedAtMs / 1e3) : null;
} catch {
return null;
}
}
/** Read the Linux procfs start identity used by Linux-owned runtime state. */
function getProcessStartTime(pid) {
if (!isValidPid(pid) || process.platform !== "linux") return null;
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
const commEndIndex = stat.lastIndexOf(")");
if (commEndIndex < 0) return null;
const fields = stat.slice(commEndIndex + 1).trimStart().split(/\s+/);
const starttime = Number(fields[19]);
return Number.isInteger(starttime) && starttime >= 0 ? starttime : null;
} catch {
return null;
}
}
/** Read a cross-platform process identity for filesystem lock ownership. */
function getFileLockProcessStartTime(pid, env = process.env, timeoutMs) {
if (!isValidPid(pid)) return null;
const isSelf = pid === process.pid;
if (isSelf && selfStartTime !== null) return selfStartTime;
const startTime = process.platform === "darwin" ? getDarwinProcessStartTime(pid, env, timeoutMs) : process.platform === "win32" ? readWindowsProcessStartTimeSync(pid, timeoutMs, env) : process.platform === "freebsd" ? readFreeBsdProcessStartTime(pid) : getProcessStartTime(pid);
if (isSelf && startTime !== null) selfStartTime = startTime;
return startTime;
}
var PROCESS_START_TIMEOUT_MS, darwinNative, selfStartTime;
var init_pid_alive = __esmMin((() => {
init_process_env();
init_windows_process_start();
init_freebsd_process_identity();
PROCESS_START_TIMEOUT_MS = 1e3;
selfStartTime = null;
}));
//#endregion
//#region src/process/supervisor/service-child-group-ownership.ts
/** The caller supplies native command inspection; the standalone group worker stays dependency-free. */
function* readProcessGroupMembers(timeoutMs, commandInspection) {
const includeCommand = commandInspection !== void 0;
if (process.platform === "linux") {
const deadline = Date.now() + timeoutMs;
for (const name of readdirSync("/proc")) {
if (Date.now() >= deadline) throw new Error("Process group census exceeded its deadline");
if (!/^\d+$/.test(name)) continue;
const pid = Number(name);
let stat;
let argv;
try {
stat = readFileSync(`/proc/${name}/stat`, "utf8");
if (includeCommand) argv = readFileSync(`/proc/${name}/cmdline`, "utf8").split("\0").filter(Boolean);
} catch (error) {
if (pid !== process.pid && ["ENOENT", "ESRCH"].includes(extractErrorCode(error) ?? "")) continue;
throw new Error(`Could not classify PID ${pid}: process command inspection failed (${extractErrorCode(error) ?? "unavailable"}).`, { cause: error });
}
const match = /^(\d+) \([\s\S]*\) (\S) (\d+) (\d+)(?:\s|$)/.exec(stat);
if (!match || Number(match[1]) !== pid || Date.now() >= deadline) throw new Error("Process group census is unavailable");
if (argv?.length === 0) {
const flags = Number(stat.slice(stat.lastIndexOf(")") + 2).split(/\s+/)[6]);
if (!(Number.isInteger(flags) && (flags & 2097152) !== 0) && !isPidDefinitelyDead(pid)) throw new Error(`Could not classify PID ${pid}: live userspace process has no readable arguments.`);
}
yield {
pid,
pgid: Number(match[4]),
state: match[2],
...argv ? { command: {
ppid: Number(match[3]),
argv
} } : {}
};
}
if (Date.now() >= deadline) throw new Error("Process group census exceeded its deadline");
return;
}
if (includeCommand && process.platform !== "darwin") throw new Error(`Exact process command census is unavailable on ${process.platform}.`);
const deadline = Date.now() + timeoutMs;
const census = spawnSync("/bin/ps", [
"-A",
"-o",
includeCommand ? "pid=,pgid=,stat=,ppid=,uid=" : "pid=,pgid=,stat="
], {
encoding: "utf8",
timeout: timeoutMs,
maxBuffer: 4194304
});
if (census.error || census.status !== 0) throw new Error("Process group census is unavailable");
for (const line of census.stdout.split("\n")) {
if (!line.trim()) continue;
const match = includeCommand ? /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(-?\d+)\s*$/.exec(line) : /^\s*(\d+)\s+(\d+)\s+(\S+)\s*$/.exec(line);
if (!match) throw new Error("Process group census is unavailable");
const pid = Number(match[1]);
if (pid !== census.pid) {
if (includeCommand && Date.now() >= deadline) throw new Error("Process group census exceeded its deadline");
const command = includeCommand ? match[3].startsWith("Z") || pid === 0 ? { argv: [] } : commandInspection?.readDarwinCommand(pid, Number(match[5]) >>> 0) : void 0;
if (includeCommand && !command) continue;
yield {
pid,
pgid: Number(match[2]),
state: match[3],
...command ? { command: {
ppid: Number(match[4]),
...command
} } : {}
};
}
}
if (includeCommand && Date.now() >= deadline) throw new Error("Process group census exceeded its deadline");
}
/** Advisory retirement timing only; the host owns kernel group-disappearance proof. */
function hasLiveOwnedProcessGroupMembers(timeoutMs = 1e3) {
let observedOwner = false;
try {
for (const { pid, pgid, state } of readProcessGroupMembers(Math.max(1, Math.min(1e3, timeoutMs)))) if (pid === process.pid) {
if (pgid !== process.pid) return;
observedOwner = true;
} else if (pgid === process.pid && (!state.startsWith("Z") || process.platform === "linux" && !isPidDefinitelyDead(pid))) return true;
} catch {
return;
}
return observedOwner ? false : void 0;
}
var init_service_child_group_ownership = __esmMin((() => {
init_error_coercion();
init_pid_alive();
}));
//#endregion
//#region src/process/supervisor/service-child-protocol.ts
init_cancellation_policy();
init_service_child_group_ownership();
function encodeServiceChildMessage(message) {
return `${JSON.stringify(message)}\n`;
}
//#endregion
//#region src/process/supervisor/service-child-stdio.ts
function setStdioEntry(stdio, fd, value) {
while (stdio.length <= fd) stdio.push("ignore");
stdio[fd] = value;
}
function reserveStdioEntry(stdio, value) {
let fd = 3;
while (stdio[fd] !== void 0 && stdio[fd] !== "ignore") fd += 1;
setStdioEntry(stdio, fd, value);
return fd;
}
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/object-utils.js
function isUndefined(obj) {
return typeof obj === "undefined" || obj === void 0;
}
function isString(obj) {
return typeof obj === "string";
}
function isNumber(obj) {
return typeof obj === "number";
}
function isBoolean(obj) {
return typeof obj === "boolean";
}
function isNull(obj) {
return obj === null;
}
function isDate(obj) {
return obj instanceof Date;
}
function isBigInt(obj) {
return typeof obj === "bigint";
}
function isFunction(obj) {
return typeof obj === "function";
}
function isObject$1(obj) {
return typeof obj === "object" && obj !== null;
}
function freeze(obj) {
return Object.freeze(obj);
}
function asArray(arg) {
if (isReadonlyArray(arg)) return arg;
else return [arg];
}
function isReadonlyArray(arg) {
return Array.isArray(arg);
}
function noop(obj) {
return obj;
}
function getMessage(error) {
return error instanceof Error ? error.message : String(error);
}
var init_object_utils = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/alter-table-node.js
var AlterTableNode;
var init_alter_table_node = __esmMin((() => {
init_object_utils();
AlterTableNode = freeze({
is(node) {
return node.kind === "AlterTableNode";
},
create(table) {
return freeze({
kind: "AlterTableNode",
table
});
},
cloneWithTableProps(node, props) {
return freeze({
...node,
...props
});
},
cloneWithColumnAlteration(node, columnAlteration) {
return freeze({
...node,
columnAlterations: node.columnAlterations ? [...node.columnAlterations, columnAlteration] : [columnAlteration]
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/identifier-node.js
var IdentifierNode;
var init_identifier_node = __esmMin((() => {
init_object_utils();
IdentifierNode = freeze({
is(node) {
return node.kind === "IdentifierNode";
},
create(name) {
return freeze({
kind: "IdentifierNode",
name
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/create-index-node.js
var CreateIndexNode;
var init_create_index_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
CreateIndexNode = freeze({
is(node) {
return node.kind === "CreateIndexNode";
},
create(name) {
return freeze({
kind: "CreateIndexNode",
name: IdentifierNode.create(name)
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
},
cloneWithColumns(node, columns) {
return freeze({
...node,
columns: [...node.columns || [], ...columns]
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/create-schema-node.js
var CreateSchemaNode;
var init_create_schema_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
CreateSchemaNode = freeze({
is(node) {
return node.kind === "CreateSchemaNode";
},
create(schema, params) {
return freeze({
kind: "CreateSchemaNode",
schema: IdentifierNode.create(schema),
...params
});
},
cloneWith(createSchema, params) {
return freeze({
...createSchema,
...params
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/create-table-node.js
var ON_COMMIT_ACTIONS, CreateTableNode;
var init_create_table_node = __esmMin((() => {
init_object_utils();
ON_COMMIT_ACTIONS = [
"preserve rows",
"delete rows",
"drop"
];
CreateTableNode = freeze({
is(node) {
return node.kind === "CreateTableNode";
},
create(table) {
return freeze({
kind: "CreateTableNode",
table,
columns: freeze([])
});
},
cloneWithColumn(node, column) {
return freeze({
...node,
columns: freeze([...node.columns, column])
});
},
cloneWithConstraint(node, constraint) {
return freeze({
...node,
constraints: node.constraints ? freeze([...node.constraints, constraint]) : freeze([constraint])
});
},
cloneWithIndex(node, index) {
return freeze({
...node,
indexes: node.indexes ? freeze([...node.indexes, index]) : freeze([index])
});
},
cloneWithFrontModifier(node, modifier) {
return freeze({
...node,
frontModifiers: node.frontModifiers ? freeze([...node.frontModifiers, modifier]) : freeze([modifier])
});
},
cloneWithEndModifier(node, modifier) {
return freeze({
...node,
endModifiers: node.endModifiers ? freeze([...node.endModifiers, modifier]) : freeze([modifier])
});
},
cloneWith(node, params) {
return freeze({
...node,
...params
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/schemable-identifier-node.js
var SchemableIdentifierNode;
var init_schemable_identifier_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
SchemableIdentifierNode = freeze({
is(node) {
return node.kind === "SchemableIdentifierNode";
},
create(identifier) {
return freeze({
kind: "SchemableIdentifierNode",
identifier: IdentifierNode.create(identifier)
});
},
createWithSchema(schema, identifier) {
return freeze({
kind: "SchemableIdentifierNode",
schema: IdentifierNode.create(schema),
identifier: IdentifierNode.create(identifier)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/drop-index-node.js
var DropIndexNode;
var init_drop_index_node = __esmMin((() => {
init_object_utils();
init_schemable_identifier_node();
DropIndexNode = freeze({
is(node) {
return node.kind === "DropIndexNode";
},
create(name, params) {
return freeze({
kind: "DropIndexNode",
name: SchemableIdentifierNode.create(name),
...params
});
},
cloneWith(dropIndex, props) {
return freeze({
...dropIndex,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/drop-schema-node.js
var DropSchemaNode;
var init_drop_schema_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
DropSchemaNode = freeze({
is(node) {
return node.kind === "DropSchemaNode";
},
create(schema, params) {
return freeze({
kind: "DropSchemaNode",
schema: IdentifierNode.create(schema),
...params
});
},
cloneWith(dropSchema, params) {
return freeze({
...dropSchema,
...params
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/drop-table-node.js
var DropTableNode;
var init_drop_table_node = __esmMin((() => {
init_object_utils();
DropTableNode = freeze({
is(node) {
return node.kind === "DropTableNode";
},
create(table, params) {
return freeze({
kind: "DropTableNode",
table,
...params
});
},
cloneWith(dropIndex, params) {
return freeze({
...dropIndex,
...params
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/alias-node.js
var AliasNode;
var init_alias_node = __esmMin((() => {
init_object_utils();
AliasNode = freeze({
is(node) {
return node.kind === "AliasNode";
},
create(node, alias) {
return freeze({
kind: "AliasNode",
node,
alias
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/table-node.js
var TableNode;
var init_table_node = __esmMin((() => {
init_object_utils();
init_schemable_identifier_node();
TableNode = freeze({
is(node) {
return node.kind === "TableNode";
},
create(table) {
return freeze({
kind: "TableNode",
table: SchemableIdentifierNode.create(table)
});
},
createWithSchema(schema, table) {
return freeze({
kind: "TableNode",
table: SchemableIdentifierNode.createWithSchema(schema, table)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/operation-node-source.js
function isOperationNodeSource(obj) {
return isObject$1(obj) && isFunction(obj.toOperationNode);
}
var init_operation_node_source = __esmMin((() => {
init_object_utils();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/expression/expression.js
function isExpression(obj) {
return isObject$1(obj) && "expressionType" in obj && isOperationNodeSource(obj);
}
function isAliasedExpression(obj) {
return isObject$1(obj) && "expression" in obj && isString(obj.alias) && isOperationNodeSource(obj);
}
var init_expression = __esmMin((() => {
init_operation_node_source();
init_object_utils();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/select-modifier-node.js
var SelectModifierNode;
var init_select_modifier_node = __esmMin((() => {
init_object_utils();
SelectModifierNode = freeze({
is(node) {
return node.kind === "SelectModifierNode";
},
create(modifier, of) {
return freeze({
kind: "SelectModifierNode",
modifier,
of
});
},
createWithExpression(modifier) {
return freeze({
kind: "SelectModifierNode",
rawModifier: modifier
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/and-node.js
var AndNode;
var init_and_node = __esmMin((() => {
init_object_utils();
AndNode = freeze({
is(node) {
return node.kind === "AndNode";
},
create(left, right) {
return freeze({
kind: "AndNode",
left,
right
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/or-node.js
var OrNode;
var init_or_node = __esmMin((() => {
init_object_utils();
OrNode = freeze({
is(node) {
return node.kind === "OrNode";
},
create(left, right) {
return freeze({
kind: "OrNode",
left,
right
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/on-node.js
var OnNode;
var init_on_node = __esmMin((() => {
init_object_utils();
init_and_node();
init_or_node();
OnNode = freeze({
is(node) {
return node.kind === "OnNode";
},
create(filter) {
return freeze({
kind: "OnNode",
on: filter
});
},
cloneWithOperation(onNode, operator, operation) {
return freeze({
...onNode,
on: operator === "And" ? AndNode.create(onNode.on, operation) : OrNode.create(onNode.on, operation)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/join-node.js
var JoinNode;
var init_join_node = __esmMin((() => {
init_object_utils();
init_on_node();
JoinNode = freeze({
is(node) {
return node.kind === "JoinNode";
},
create(joinType, table) {
return freeze({
kind: "JoinNode",
joinType,
table,
on: void 0
});
},
createWithOn(joinType, table, on) {
return freeze({
kind: "JoinNode",
joinType,
table,
on: OnNode.create(on)
});
},
cloneWithOn(joinNode, operation) {
return freeze({
...joinNode,
on: joinNode.on ? OnNode.cloneWithOperation(joinNode.on, "And", operation) : OnNode.create(operation)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/binary-operation-node.js
var BinaryOperationNode;
var init_binary_operation_node = __esmMin((() => {
init_object_utils();
BinaryOperationNode = freeze({
is(node) {
return node.kind === "BinaryOperationNode";
},
create(leftOperand, operator, rightOperand) {
return freeze({
kind: "BinaryOperationNode",
leftOperand,
operator,
rightOperand
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/operator-node.js
function isBinaryOperator(op) {
return isString(op) && BINARY_OPERATORS_DICTIONARY[op];
}
function isJSONOperator(op) {
return isString(op) && JSON_OPERATORS_DICTIONARY[op];
}
function isUnaryOperator(op) {
return isString(op) && UNARY_OPERATORS_DICTIONARY[op];
}
var COMPARISON_OPERATORS_DICTIONARY, ARITHMETIC_OPERATORS_DICTIONARY, JSON_OPERATORS_DICTIONARY, JSON_OPERATORS, BINARY_OPERATORS_DICTIONARY, BINARY_OPERATORS, UNARY_FILTER_OPERATORS_DICTIONARY, UNARY_OPERATORS_DICTIONARY, UNARY_OPERATORS, OperatorNode;
var init_operator_node = __esmMin((() => {
init_object_utils();
COMPARISON_OPERATORS_DICTIONARY = freeze({
"=": true,
"==": true,
"!=": true,
"<>": true,
">": true,
">=": true,
"<": true,
"<=": true,
in: true,
"not in": true,
is: true,
"is not": true,
like: true,
"not like": true,
match: true,
ilike: true,
"not ilike": true,
"@>": true,
"<@": true,
"^@": true,
"&&": true,
"?": true,
"?&": true,
"?|": true,
"!<": true,
"!>": true,
"<=>": true,
"!~": true,
"~": true,
"~*": true,
"!~*": true,
"@@": true,
"@@@": true,
"!!": true,
"<->": true,
regexp: true,
"is distinct from": true,
"is not distinct from": true
});
Object.keys(COMPARISON_OPERATORS_DICTIONARY);
ARITHMETIC_OPERATORS_DICTIONARY = freeze({
"+": true,
"-": true,
"*": true,
"/": true,
"%": true,
"^": true,
"&": true,
"|": true,
"#": true,
"<<": true,
">>": true
});
Object.keys(ARITHMETIC_OPERATORS_DICTIONARY);
JSON_OPERATORS_DICTIONARY = freeze({
"->": true,
"->>": true
});
JSON_OPERATORS = Object.keys(JSON_OPERATORS_DICTIONARY);
BINARY_OPERATORS_DICTIONARY = freeze({
...COMPARISON_OPERATORS_DICTIONARY,
...ARITHMETIC_OPERATORS_DICTIONARY,
"||": true
});
BINARY_OPERATORS = Object.keys(BINARY_OPERATORS_DICTIONARY);
UNARY_FILTER_OPERATORS_DICTIONARY = freeze({
exists: true,
"not exists": true
});
Object.keys(UNARY_FILTER_OPERATORS_DICTIONARY);
UNARY_OPERATORS_DICTIONARY = freeze({
...UNARY_FILTER_OPERATORS_DICTIONARY,
"-": true,
not: true
});
UNARY_OPERATORS = Object.keys(UNARY_OPERATORS_DICTIONARY);
[
...BINARY_OPERATORS,
...JSON_OPERATORS,
...UNARY_OPERATORS
];
OperatorNode = freeze({
is(node) {
return node.kind === "OperatorNode";
},
create(operator) {
return freeze({
kind: "OperatorNode",
operator
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/column-node.js
var ColumnNode;
var init_column_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
ColumnNode = freeze({
is(node) {
return node.kind === "ColumnNode";
},
create(column) {
return freeze({
kind: "ColumnNode",
column: IdentifierNode.create(column)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/select-all-node.js
var SelectAllNode;
var init_select_all_node = __esmMin((() => {
init_object_utils();
SelectAllNode = freeze({
is(node) {
return node.kind === "SelectAllNode";
},
create() {
return freeze({ kind: "SelectAllNode" });
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/reference-node.js
var ReferenceNode;
var init_reference_node = __esmMin((() => {
init_select_all_node();
init_object_utils();
ReferenceNode = freeze({
is(node) {
return node.kind === "ReferenceNode";
},
create(column, table) {
return freeze({
kind: "ReferenceNode",
table,
column
});
},
createSelectAll(table) {
return freeze({
kind: "ReferenceNode",
table,
column: SelectAllNode.create()
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dynamic/dynamic-reference-builder.js
function isDynamicReferenceBuilder(obj) {
return isObject$1(obj) && isOperationNodeSource(obj) && isString(obj.dynamicReference);
}
var DynamicReferenceBuilder;
var init_dynamic_reference_builder = __esmMin((() => {
init_operation_node_source();
init_reference_parser();
init_object_utils();
DynamicReferenceBuilder = class {
#dynamicReference;
get dynamicReference() {
return this.#dynamicReference;
}
/**
* @private
*
* This needs to be here just so that the typings work. Without this
* the generated .d.ts file contains no reference to the type param R
* which causes this type to be equal to DynamicReferenceBuilder with
* any R.
*/
get refType() {}
constructor(reference) {
this.#dynamicReference = reference;
}
toOperationNode() {
return parseSimpleReferenceExpression(this.#dynamicReference);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/order-by-item-node.js
var OrderByItemNode;
var init_order_by_item_node = __esmMin((() => {
init_object_utils();
OrderByItemNode = freeze({
is(node) {
return node.kind === "OrderByItemNode";
},
create(orderBy, direction) {
return freeze({
kind: "OrderByItemNode",
orderBy,
direction
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/raw-node.js
var RawNode;
var init_raw_node = __esmMin((() => {
init_object_utils();
RawNode = freeze({
is(node) {
return node.kind === "RawNode";
},
create(sqlFragments, parameters) {
return freeze({
kind: "RawNode",
sqlFragments: freeze(sqlFragments),
parameters: freeze(parameters)
});
},
createWithSql(sql) {
return RawNode.create([sql], []);
},
createWithChild(child) {
return RawNode.create(["", ""], [child]);
},
createWithChildren(children) {
return RawNode.create(new Array(children.length + 1).fill(""), children);
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/collate-node.js
var CollateNode;
var init_collate_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
CollateNode = freeze({
is(node) {
return node.kind === "CollateNode";
},
create(collation) {
return freeze({
kind: "CollateNode",
collation: IdentifierNode.create(collation)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/order-by-item-builder.js
var OrderByItemBuilder;
var init_order_by_item_builder = __esmMin((() => {
init_collate_node();
init_order_by_item_node();
init_raw_node();
init_object_utils();
OrderByItemBuilder = class OrderByItemBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Adds `desc` to the `order by` item.
*
* See {@link asc} for the opposite.
*/
desc() {
return new OrderByItemBuilder({ node: OrderByItemNode.cloneWith(this.#props.node, { direction: RawNode.createWithSql("desc") }) });
}
/**
* Adds `asc` to the `order by` item.
*
* See {@link desc} for the opposite.
*/
asc() {
return new OrderByItemBuilder({ node: OrderByItemNode.cloneWith(this.#props.node, { direction: RawNode.createWithSql("asc") }) });
}
/**
* Adds `nulls last` to the `order by` item.
*
* This is only supported by some dialects like PostgreSQL and SQLite.
*
* See {@link nullsFirst} for the opposite.
*/
nullsLast() {
return new OrderByItemBuilder({ node: OrderByItemNode.cloneWith(this.#props.node, { nulls: "last" }) });
}
/**
* Adds `nulls first` to the `order by` item.
*
* This is only supported by some dialects like PostgreSQL and SQLite.
*
* See {@link nullsLast} for the opposite.
*/
nullsFirst() {
return new OrderByItemBuilder({ node: OrderByItemNode.cloneWith(this.#props.node, { nulls: "first" }) });
}
/**
* Adds `collate <collationName>` to the `order by` item.
*/
collate(collation) {
return new OrderByItemBuilder({ node: OrderByItemNode.cloneWith(this.#props.node, { collation: CollateNode.create(collation) }) });
}
toOperationNode() {
return this.#props.node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/log-once.js
/**
* Use for system-level logging, such as deprecation messages.
* Logs a message and ensures it won't be logged again.
*/
function logOnce(message) {
if (LOGGED_MESSAGES.has(message)) return;
LOGGED_MESSAGES.add(message);
console.log(message);
}
var LOGGED_MESSAGES;
var init_log_once = __esmMin((() => {
LOGGED_MESSAGES = /* @__PURE__ */ new Set();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/order-by-parser.js
function isOrderByDirection(thing) {
return thing === "asc" || thing === "desc";
}
function parseOrderBy(args) {
if (args.length === 2) return [parseOrderByItem(args[0], args[1])];
if (args.length === 1) {
const [orderBy] = args;
if (Array.isArray(orderBy)) {
logOnce("orderBy(array) is deprecated, use multiple orderBy calls instead.");
return orderBy.map((item) => parseOrderByItem(item));
}
return [parseOrderByItem(orderBy)];
}
throw new Error(`Invalid number of arguments at order by! expected 1-2, received ${args.length}`);
}
function parseOrderByItem(expr, modifiers) {
const parsedRef = parseOrderByExpression(expr);
if (OrderByItemNode.is(parsedRef)) {
if (modifiers) throw new Error("Cannot specify direction twice!");
return parsedRef;
}
return parseOrderByWithModifiers(parsedRef, modifiers);
}
function parseOrderByExpression(expr) {
if (isExpressionOrFactory(expr)) return parseExpression(expr);
if (isDynamicReferenceBuilder(expr)) return expr.toOperationNode();
const [ref, direction] = expr.split(" ");
if (direction) {
logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead.");
return parseOrderByWithModifiers(parseStringReference(ref), direction);
}
return parseStringReference(expr);
}
function parseOrderByWithModifiers(expr, modifiers) {
if (typeof modifiers === "string") {
if (!isOrderByDirection(modifiers)) throw new Error(`Invalid order by direction: ${modifiers}`);
return OrderByItemNode.create(expr, RawNode.createWithSql(modifiers));
}
if (isExpression(modifiers)) {
logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead.");
return OrderByItemNode.create(expr, modifiers.toOperationNode());
}
const node = OrderByItemNode.create(expr);
if (!modifiers) return node;
return modifiers(new OrderByItemBuilder({ node })).toOperationNode();
}
var init_order_by_parser = __esmMin((() => {
init_dynamic_reference_builder();
init_expression();
init_order_by_item_node();
init_raw_node();
init_order_by_item_builder();
init_log_once();
init_expression_parser();
init_reference_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/json-reference-node.js
var JSONReferenceNode;
var init_json_reference_node = __esmMin((() => {
init_object_utils();
JSONReferenceNode = freeze({
is(node) {
return node.kind === "JSONReferenceNode";
},
create(reference, traversal) {
return freeze({
kind: "JSONReferenceNode",
reference,
traversal
});
},
cloneWithTraversal(node, traversal) {
return freeze({
...node,
traversal
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/json-operator-chain-node.js
var JSONOperatorChainNode;
var init_json_operator_chain_node = __esmMin((() => {
init_object_utils();
JSONOperatorChainNode = freeze({
is(node) {
return node.kind === "JSONOperatorChainNode";
},
create(operator) {
return freeze({
kind: "JSONOperatorChainNode",
operator,
values: freeze([])
});
},
cloneWithValue(node, value) {
return freeze({
...node,
values: freeze([...node.values, value])
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/json-path-node.js
var JSONPathNode;
var init_json_path_node = __esmMin((() => {
init_object_utils();
JSONPathNode = freeze({
is(node) {
return node.kind === "JSONPathNode";
},
create(inOperator) {
return freeze({
kind: "JSONPathNode",
inOperator,
pathLegs: freeze([])
});
},
cloneWithLeg(jsonPathNode, pathLeg) {
return freeze({
...jsonPathNode,
pathLegs: freeze([...jsonPathNode.pathLegs, pathLeg])
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/reference-parser.js
function parseSimpleReferenceExpression(exp) {
if (isString(exp)) return parseStringReference(exp);
return exp.toOperationNode();
}
function parseReferenceExpressionOrList(arg) {
if (isReadonlyArray(arg)) return arg.map((it) => parseReferenceExpression(it));
else return [parseReferenceExpression(arg)];
}
function parseReferenceExpression(exp) {
if (isExpressionOrFactory(exp)) return parseExpression(exp);
return parseSimpleReferenceExpression(exp);
}
function parseJSONReference(ref, op) {
if (isJSONOperator(op)) return JSONReferenceNode.create(parseStringReference(ref), JSONOperatorChainNode.create(OperatorNode.create(op)));
if (op === "->$" || op === "->>$") return JSONReferenceNode.create(parseStringReference(ref), JSONPathNode.create(OperatorNode.create(op.slice(0, -1))));
throw new Error(`Invalid JSON operator: ${op}`);
}
function parseStringReference(ref) {
const COLUMN_SEPARATOR = ".";
if (!ref.includes(COLUMN_SEPARATOR)) return ReferenceNode.create(ColumnNode.create(ref));
const parts = ref.split(COLUMN_SEPARATOR).map(trim$2);
if (parts.length === 3) return parseStringReferenceWithTableAndSchema(parts);
if (parts.length === 2) return parseStringReferenceWithTable(parts);
throw new Error(`invalid column reference ${ref}`);
}
function parseAliasedStringReference(ref) {
const ALIAS_SEPARATOR = " as ";
if (ref.includes(ALIAS_SEPARATOR)) {
const [columnRef, alias] = ref.split(ALIAS_SEPARATOR).map(trim$2);
return AliasNode.create(parseStringReference(columnRef), IdentifierNode.create(alias));
} else return parseStringReference(ref);
}
function parseColumnName(column) {
return ColumnNode.create(column);
}
function parseOrderedColumnName(column) {
const ORDER_SEPARATOR = " ";
if (column.includes(ORDER_SEPARATOR)) {
const [columnName, order] = column.split(ORDER_SEPARATOR).map(trim$2);
if (!isOrderByDirection(order)) throw new Error(`invalid order direction "${order}" next to "${columnName}"`);
return parseOrderBy([columnName, order])[0];
} else return parseColumnName(column);
}
function parseStringReferenceWithTableAndSchema(parts) {
const [schema, table, column] = parts;
return ReferenceNode.create(ColumnNode.create(column), TableNode.createWithSchema(schema, table));
}
function parseStringReferenceWithTable(parts) {
const [table, column] = parts;
return ReferenceNode.create(ColumnNode.create(column), TableNode.create(table));
}
function trim$2(str) {
return str.trim();
}
var init_reference_parser = __esmMin((() => {
init_alias_node();
init_column_node();
init_reference_node();
init_table_node();
init_object_utils();
init_expression_parser();
init_identifier_node();
init_order_by_parser();
init_operator_node();
init_json_reference_node();
init_json_operator_chain_node();
init_json_path_node();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/primitive-value-list-node.js
var PrimitiveValueListNode;
var init_primitive_value_list_node = __esmMin((() => {
init_object_utils();
PrimitiveValueListNode = freeze({
is(node) {
return node.kind === "PrimitiveValueListNode";
},
create(values) {
return freeze({
kind: "PrimitiveValueListNode",
values: freeze([...values])
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/value-list-node.js
var ValueListNode;
var init_value_list_node = __esmMin((() => {
init_object_utils();
ValueListNode = freeze({
is(node) {
return node.kind === "ValueListNode";
},
create(values) {
return freeze({
kind: "ValueListNode",
values: freeze(values)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/value-node.js
var ValueNode;
var init_value_node = __esmMin((() => {
init_object_utils();
ValueNode = freeze({
is(node) {
return node.kind === "ValueNode";
},
create(value) {
return freeze({
kind: "ValueNode",
value
});
},
createImmediate(value) {
return freeze({
kind: "ValueNode",
value,
immediate: true
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/value-parser.js
function parseValueExpressionOrList(arg) {
if (isReadonlyArray(arg)) return parseValueExpressionList(arg);
return parseValueExpression(arg);
}
function parseValueExpression(exp) {
if (isExpressionOrFactory(exp)) return parseExpression(exp);
return ValueNode.create(exp);
}
function isSafeImmediateValue(value) {
return isNumber(value) || isBoolean(value) || isNull(value);
}
function parseSafeImmediateValue(value) {
if (!isSafeImmediateValue(value)) throw new Error(`unsafe immediate value ${JSON.stringify(value)}`);
return ValueNode.createImmediate(value);
}
function parseValueExpressionList(arg) {
if (arg.some(isExpressionOrFactory)) return ValueListNode.create(arg.map((it) => parseValueExpression(it)));
return PrimitiveValueListNode.create(arg);
}
var init_value_parser = __esmMin((() => {
init_primitive_value_list_node();
init_value_list_node();
init_value_node();
init_object_utils();
init_expression_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/parens-node.js
var ParensNode;
var init_parens_node = __esmMin((() => {
init_object_utils();
ParensNode = freeze({
is(node) {
return node.kind === "ParensNode";
},
create(node) {
return freeze({
kind: "ParensNode",
node
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/binary-operation-parser.js
function parseValueBinaryOperationOrExpression(args) {
if (args.length === 3) return parseValueBinaryOperation(args[0], args[1], args[2]);
else if (args.length === 1) return parseValueExpression(args[0]);
throw new Error(`invalid arguments: ${JSON.stringify(args)}`);
}
function parseValueBinaryOperation(left, operator, right) {
if (isIsOperator(operator) && needsIsOperator(right)) return BinaryOperationNode.create(parseReferenceExpression(left), parseBinaryOperator(operator), ValueNode.createImmediate(right));
return BinaryOperationNode.create(parseReferenceExpression(left), parseBinaryOperator(operator), parseValueExpressionOrList(right));
}
function parseReferentialBinaryOperation(left, operator, right) {
return BinaryOperationNode.create(parseReferenceExpression(left), parseBinaryOperator(operator), parseReferenceExpression(right));
}
function parseFilterObject(obj, combinator) {
return parseFilterList(Object.entries(obj).filter(([, v]) => !isUndefined(v)).map(([k, v]) => parseValueBinaryOperation(k, needsIsOperator(v) ? "is" : "=", v)), combinator);
}
function parseFilterList(list, combinator, withParens = true) {
const combine = combinator === "and" ? AndNode.create : OrNode.create;
if (list.length === 0) return BinaryOperationNode.create(ValueNode.createImmediate(1), OperatorNode.create("="), ValueNode.createImmediate(combinator === "and" ? 1 : 0));
let node = toOperationNode(list[0]);
for (let i = 1; i < list.length; ++i) node = combine(node, toOperationNode(list[i]));
if (list.length > 1 && withParens) return ParensNode.create(node);
return node;
}
function isIsOperator(operator) {
return operator === "is" || operator === "is not";
}
function needsIsOperator(value) {
return isNull(value) || isBoolean(value);
}
function parseBinaryOperator(operator) {
if (isBinaryOperator(operator)) return OperatorNode.create(operator);
if (isOperationNodeSource(operator)) return operator.toOperationNode();
throw new Error(`invalid operator ${JSON.stringify(operator)}`);
}
function toOperationNode(nodeOrSource) {
return isOperationNodeSource(nodeOrSource) ? nodeOrSource.toOperationNode() : nodeOrSource;
}
var init_binary_operation_parser = __esmMin((() => {
init_binary_operation_node();
init_object_utils();
init_operation_node_source();
init_operator_node();
init_reference_parser();
init_value_parser();
init_value_node();
init_and_node();
init_parens_node();
init_or_node();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/order-by-node.js
var OrderByNode;
var init_order_by_node = __esmMin((() => {
init_object_utils();
OrderByNode = freeze({
is(node) {
return node.kind === "OrderByNode";
},
create(items) {
return freeze({
kind: "OrderByNode",
items: freeze([...items])
});
},
cloneWithItems(orderBy, items) {
return freeze({
...orderBy,
items: freeze([...orderBy.items, ...items])
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/partition-by-node.js
var PartitionByNode;
var init_partition_by_node = __esmMin((() => {
init_object_utils();
PartitionByNode = freeze({
is(node) {
return node.kind === "PartitionByNode";
},
create(items) {
return freeze({
kind: "PartitionByNode",
items: freeze(items)
});
},
cloneWithItems(partitionBy, items) {
return freeze({
...partitionBy,
items: freeze([...partitionBy.items, ...items])
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/over-node.js
var OverNode;
var init_over_node = __esmMin((() => {
init_object_utils();
init_order_by_node();
init_partition_by_node();
OverNode = freeze({
is(node) {
return node.kind === "OverNode";
},
create() {
return freeze({ kind: "OverNode" });
},
cloneWithOrderByItems(overNode, items) {
return freeze({
...overNode,
orderBy: overNode.orderBy ? OrderByNode.cloneWithItems(overNode.orderBy, items) : OrderByNode.create(items)
});
},
cloneWithPartitionByItems(overNode, items) {
return freeze({
...overNode,
partitionBy: overNode.partitionBy ? PartitionByNode.cloneWithItems(overNode.partitionBy, items) : PartitionByNode.create(items)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/from-node.js
var FromNode;
var init_from_node = __esmMin((() => {
init_object_utils();
FromNode = freeze({
is(node) {
return node.kind === "FromNode";
},
create(froms) {
return freeze({
kind: "FromNode",
froms: freeze(froms)
});
},
cloneWithFroms(from, froms) {
return freeze({
...from,
froms: freeze([...from.froms, ...froms])
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/group-by-node.js
var GroupByNode;
var init_group_by_node = __esmMin((() => {
init_object_utils();
GroupByNode = freeze({
is(node) {
return node.kind === "GroupByNode";
},
create(items) {
return freeze({
kind: "GroupByNode",
items: freeze(items)
});
},
cloneWithItems(groupBy, items) {
return freeze({
...groupBy,
items: freeze([...groupBy.items, ...items])
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/having-node.js
var HavingNode;
var init_having_node = __esmMin((() => {
init_object_utils();
init_and_node();
init_or_node();
HavingNode = freeze({
is(node) {
return node.kind === "HavingNode";
},
create(filter) {
return freeze({
kind: "HavingNode",
having: filter
});
},
cloneWithOperation(havingNode, operator, operation) {
return freeze({
...havingNode,
having: operator === "And" ? AndNode.create(havingNode.having, operation) : OrNode.create(havingNode.having, operation)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/insert-query-node.js
var InsertQueryNode;
var init_insert_query_node = __esmMin((() => {
init_object_utils();
InsertQueryNode = freeze({
is(node) {
return node.kind === "InsertQueryNode";
},
create(into, withNode, replace) {
return freeze({
kind: "InsertQueryNode",
into,
...withNode && { with: withNode },
replace
});
},
createWithoutInto() {
return freeze({ kind: "InsertQueryNode" });
},
cloneWith(insertQuery, props) {
return freeze({
...insertQuery,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/list-node.js
var ListNode;
var init_list_node = __esmMin((() => {
init_object_utils();
ListNode = freeze({
is(node) {
return node.kind === "ListNode";
},
create(items) {
return freeze({
kind: "ListNode",
items: freeze(items)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/update-query-node.js
var UpdateQueryNode;
var init_update_query_node = __esmMin((() => {
init_object_utils();
init_from_node();
init_list_node();
UpdateQueryNode = freeze({
is(node) {
return node.kind === "UpdateQueryNode";
},
create(tables, withNode) {
return freeze({
kind: "UpdateQueryNode",
table: tables.length === 1 ? tables[0] : ListNode.create(tables),
...withNode && { with: withNode }
});
},
createWithoutTable() {
return freeze({ kind: "UpdateQueryNode" });
},
cloneWithFromItems(updateQuery, fromItems) {
return freeze({
...updateQuery,
from: updateQuery.from ? FromNode.cloneWithFroms(updateQuery.from, fromItems) : FromNode.create(fromItems)
});
},
cloneWithUpdates(updateQuery, updates) {
return freeze({
...updateQuery,
updates: updateQuery.updates ? freeze([...updateQuery.updates, ...updates]) : updates
});
},
cloneWithLimit(updateQuery, limit) {
return freeze({
...updateQuery,
limit
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/using-node.js
var UsingNode;
var init_using_node = __esmMin((() => {
init_object_utils();
UsingNode = freeze({
is(node) {
return node.kind === "UsingNode";
},
create(tables) {
return freeze({
kind: "UsingNode",
tables: freeze(tables)
});
},
cloneWithTables(using, tables) {
return freeze({
...using,
tables: freeze([...using.tables, ...tables])
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/delete-query-node.js
var DeleteQueryNode;
var init_delete_query_node = __esmMin((() => {
init_object_utils();
init_from_node();
init_using_node();
init_query_node();
DeleteQueryNode = freeze({
is(node) {
return node.kind === "DeleteQueryNode";
},
create(fromItems, withNode) {
return freeze({
kind: "DeleteQueryNode",
from: FromNode.create(fromItems),
...withNode && { with: withNode }
});
},
/**
* @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.
*/
cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),
/**
* @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.
*/
cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),
cloneWithLimit(deleteNode, limit) {
return freeze({
...deleteNode,
limit
});
},
cloneWithoutLimit(deleteNode) {
return freeze({
...deleteNode,
limit: void 0
});
},
cloneWithUsing(deleteNode, tables) {
return freeze({
...deleteNode,
using: deleteNode.using !== void 0 ? UsingNode.cloneWithTables(deleteNode.using, tables) : UsingNode.create(tables)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/where-node.js
var WhereNode;
var init_where_node = __esmMin((() => {
init_object_utils();
init_and_node();
init_or_node();
WhereNode = freeze({
is(node) {
return node.kind === "WhereNode";
},
create(filter) {
return freeze({
kind: "WhereNode",
where: filter
});
},
cloneWithOperation(whereNode, operator, operation) {
return freeze({
...whereNode,
where: operator === "And" ? AndNode.create(whereNode.where, operation) : OrNode.create(whereNode.where, operation)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/returning-node.js
var ReturningNode;
var init_returning_node = __esmMin((() => {
init_object_utils();
ReturningNode = freeze({
is(node) {
return node.kind === "ReturningNode";
},
create(selections) {
return freeze({
kind: "ReturningNode",
selections: freeze(selections)
});
},
cloneWithSelections(returning, selections) {
return freeze({
...returning,
selections: returning.selections ? freeze([...returning.selections, ...selections]) : freeze(selections)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/explain-node.js
var ExplainNode;
var init_explain_node = __esmMin((() => {
init_object_utils();
ExplainNode = freeze({
is(node) {
return node.kind === "ExplainNode";
},
create(format, options) {
return freeze({
kind: "ExplainNode",
format,
options
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/when-node.js
var WhenNode;
var init_when_node = __esmMin((() => {
init_object_utils();
WhenNode = freeze({
is(node) {
return node.kind === "WhenNode";
},
create(condition) {
return freeze({
kind: "WhenNode",
condition
});
},
cloneWithResult(whenNode, result) {
return freeze({
...whenNode,
result
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/merge-query-node.js
var MergeQueryNode;
var init_merge_query_node = __esmMin((() => {
init_object_utils();
init_when_node();
MergeQueryNode = freeze({
is(node) {
return node.kind === "MergeQueryNode";
},
create(into, withNode) {
return freeze({
kind: "MergeQueryNode",
into,
...withNode && { with: withNode }
});
},
cloneWithUsing(mergeNode, using) {
return freeze({
...mergeNode,
using
});
},
cloneWithWhen(mergeNode, when) {
return freeze({
...mergeNode,
whens: mergeNode.whens ? freeze([...mergeNode.whens, when]) : freeze([when])
});
},
cloneWithThen(mergeNode, then) {
return freeze({
...mergeNode,
whens: mergeNode.whens ? freeze([...mergeNode.whens.slice(0, -1), WhenNode.cloneWithResult(mergeNode.whens[mergeNode.whens.length - 1], then)]) : void 0
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/output-node.js
var OutputNode;
var init_output_node = __esmMin((() => {
init_object_utils();
OutputNode = freeze({
is(node) {
return node.kind === "OutputNode";
},
create(selections) {
return freeze({
kind: "OutputNode",
selections: freeze(selections)
});
},
cloneWithSelections(output, selections) {
return freeze({
...output,
selections: output.selections ? freeze([...output.selections, ...selections]) : freeze(selections)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/query-node.js
var QueryNode;
var init_query_node = __esmMin((() => {
init_insert_query_node();
init_select_query_node();
init_update_query_node();
init_delete_query_node();
init_where_node();
init_object_utils();
init_returning_node();
init_explain_node();
init_merge_query_node();
init_output_node();
init_order_by_node();
QueryNode = freeze({
is(node) {
return SelectQueryNode.is(node) || InsertQueryNode.is(node) || UpdateQueryNode.is(node) || DeleteQueryNode.is(node) || MergeQueryNode.is(node);
},
cloneWithEndModifier(node, modifier) {
return freeze({
...node,
endModifiers: node.endModifiers ? freeze([...node.endModifiers, modifier]) : freeze([modifier])
});
},
cloneWithWhere(node, operation) {
return freeze({
...node,
where: node.where ? WhereNode.cloneWithOperation(node.where, "And", operation) : WhereNode.create(operation)
});
},
cloneWithJoin(node, join) {
return freeze({
...node,
joins: node.joins ? freeze([...node.joins, join]) : freeze([join])
});
},
cloneWithReturning(node, selections) {
return freeze({
...node,
returning: node.returning ? ReturningNode.cloneWithSelections(node.returning, selections) : ReturningNode.create(selections)
});
},
cloneWithoutReturning(node) {
return freeze({
...node,
returning: void 0
});
},
cloneWithoutWhere(node) {
return freeze({
...node,
where: void 0
});
},
cloneWithExplain(node, format, options) {
return freeze({
...node,
explain: ExplainNode.create(format, options?.toOperationNode())
});
},
cloneWithTop(node, top) {
return freeze({
...node,
top
});
},
cloneWithOutput(node, selections) {
return freeze({
...node,
output: node.output ? OutputNode.cloneWithSelections(node.output, selections) : OutputNode.create(selections)
});
},
cloneWithOrderByItems(node, items) {
return freeze({
...node,
orderBy: node.orderBy ? OrderByNode.cloneWithItems(node.orderBy, items) : OrderByNode.create(items)
});
},
cloneWithoutOrderBy(node) {
return freeze({
...node,
orderBy: void 0
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/select-query-node.js
var SelectQueryNode;
var init_select_query_node = __esmMin((() => {
init_object_utils();
init_from_node();
init_group_by_node();
init_having_node();
init_query_node();
SelectQueryNode = freeze({
is(node) {
return node.kind === "SelectQueryNode";
},
create(withNode) {
return freeze({
kind: "SelectQueryNode",
...withNode && { with: withNode }
});
},
createFrom(fromItems, withNode) {
return freeze({
kind: "SelectQueryNode",
from: FromNode.create(fromItems),
...withNode && { with: withNode }
});
},
cloneWithSelections(select, selections) {
return freeze({
...select,
selections: select.selections ? freeze([...select.selections, ...selections]) : freeze(selections)
});
},
cloneWithDistinctOn(select, expressions) {
return freeze({
...select,
distinctOn: select.distinctOn ? freeze([...select.distinctOn, ...expressions]) : freeze(expressions)
});
},
cloneWithFrontModifier(select, modifier) {
return freeze({
...select,
frontModifiers: select.frontModifiers ? freeze([...select.frontModifiers, modifier]) : freeze([modifier])
});
},
/**
* @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.
*/
cloneWithOrderByItems: (node, items) => QueryNode.cloneWithOrderByItems(node, items),
cloneWithGroupByItems(selectNode, items) {
return freeze({
...selectNode,
groupBy: selectNode.groupBy ? GroupByNode.cloneWithItems(selectNode.groupBy, items) : GroupByNode.create(items)
});
},
cloneWithLimit(selectNode, limit) {
return freeze({
...selectNode,
limit
});
},
cloneWithOffset(selectNode, offset) {
return freeze({
...selectNode,
offset
});
},
cloneWithFetch(selectNode, fetch) {
return freeze({
...selectNode,
fetch
});
},
cloneWithHaving(selectNode, operation) {
return freeze({
...selectNode,
having: selectNode.having ? HavingNode.cloneWithOperation(selectNode.having, "And", operation) : HavingNode.create(operation)
});
},
cloneWithSetOperations(selectNode, setOperations) {
return freeze({
...selectNode,
setOperations: selectNode.setOperations ? freeze([...selectNode.setOperations, ...setOperations]) : freeze([...setOperations])
});
},
cloneWithoutSelections(select) {
return freeze({
...select,
selections: []
});
},
cloneWithoutLimit(select) {
return freeze({
...select,
limit: void 0
});
},
cloneWithoutOffset(select) {
return freeze({
...select,
offset: void 0
});
},
/**
* @deprecated Use `QueryNode.cloneWithoutOrderBy` instead.
*/
cloneWithoutOrderBy: (node) => QueryNode.cloneWithoutOrderBy(node),
cloneWithoutGroupBy(select) {
return freeze({
...select,
groupBy: void 0
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/join-builder.js
var JoinBuilder;
var init_join_builder = __esmMin((() => {
init_join_node();
init_raw_node();
init_binary_operation_parser();
init_object_utils();
JoinBuilder = class JoinBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
on(...args) {
return new JoinBuilder({
...this.#props,
joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseValueBinaryOperationOrExpression(args))
});
}
/**
* Just like {@link WhereInterface.whereRef} but adds an item to the join's
* `on` clause instead.
*
* See {@link WhereInterface.whereRef} for documentation and examples.
*/
onRef(lhs, op, rhs) {
return new JoinBuilder({
...this.#props,
joinNode: JoinNode.cloneWithOn(this.#props.joinNode, parseReferentialBinaryOperation(lhs, op, rhs))
});
}
/**
* Adds `on true`.
*/
onTrue() {
return new JoinBuilder({
...this.#props,
joinNode: JoinNode.cloneWithOn(this.#props.joinNode, RawNode.createWithSql("true"))
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.joinNode;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/partition-by-item-node.js
var PartitionByItemNode;
var init_partition_by_item_node = __esmMin((() => {
init_object_utils();
PartitionByItemNode = freeze({
is(node) {
return node.kind === "PartitionByItemNode";
},
create(partitionBy) {
return freeze({
kind: "PartitionByItemNode",
partitionBy
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/partition-by-parser.js
function parsePartitionBy(partitionBy) {
return parseReferenceExpressionOrList(partitionBy).map(PartitionByItemNode.create);
}
var init_partition_by_parser = __esmMin((() => {
init_partition_by_item_node();
init_reference_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/over-builder.js
var OverBuilder;
var init_over_builder = __esmMin((() => {
init_over_node();
init_query_node();
init_order_by_parser();
init_partition_by_parser();
init_object_utils();
OverBuilder = class OverBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
orderBy(...args) {
return new OverBuilder({ overNode: OverNode.cloneWithOrderByItems(this.#props.overNode, parseOrderBy(args)) });
}
clearOrderBy() {
return new OverBuilder({ overNode: QueryNode.cloneWithoutOrderBy(this.#props.overNode) });
}
partitionBy(partitionBy) {
return new OverBuilder({ overNode: OverNode.cloneWithPartitionByItems(this.#props.overNode, parsePartitionBy(partitionBy)) });
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.overNode;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/selection-node.js
var SelectionNode;
var init_selection_node = __esmMin((() => {
init_object_utils();
init_reference_node();
init_select_all_node();
SelectionNode = freeze({
is(node) {
return node.kind === "SelectionNode";
},
create(selection) {
return freeze({
kind: "SelectionNode",
selection
});
},
createSelectAll() {
return freeze({
kind: "SelectionNode",
selection: SelectAllNode.create()
});
},
createSelectAllFromTable(table) {
return freeze({
kind: "SelectionNode",
selection: ReferenceNode.createSelectAll(table)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/select-parser.js
function parseSelectArg(selection) {
if (isFunction(selection)) return parseSelectArg(selection(expressionBuilder()));
else if (isReadonlyArray(selection)) return selection.map((it) => parseSelectExpression(it));
else return [parseSelectExpression(selection)];
}
function parseSelectExpression(selection) {
if (isString(selection)) return SelectionNode.create(parseAliasedStringReference(selection));
else if (isDynamicReferenceBuilder(selection)) return SelectionNode.create(selection.toOperationNode());
else return SelectionNode.create(parseAliasedExpression(selection));
}
function parseSelectAll(table) {
if (!table) return [SelectionNode.createSelectAll()];
else if (Array.isArray(table)) return table.map(parseSelectAllArg);
else return [parseSelectAllArg(table)];
}
function parseSelectAllArg(table) {
if (isString(table)) return SelectionNode.createSelectAllFromTable(parseTable(table));
throw new Error(`invalid value selectAll expression: ${JSON.stringify(table)}`);
}
var init_select_parser = __esmMin((() => {
init_object_utils();
init_selection_node();
init_reference_parser();
init_dynamic_reference_builder();
init_expression_parser();
init_table_parser();
init_expression_builder();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/values-node.js
var ValuesNode;
var init_values_node = __esmMin((() => {
init_object_utils();
ValuesNode = freeze({
is(node) {
return node.kind === "ValuesNode";
},
create(values) {
return freeze({
kind: "ValuesNode",
values: freeze(values)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/default-insert-value-node.js
var DefaultInsertValueNode;
var init_default_insert_value_node = __esmMin((() => {
init_object_utils();
DefaultInsertValueNode = freeze({
is(node) {
return node.kind === "DefaultInsertValueNode";
},
create() {
return freeze({ kind: "DefaultInsertValueNode" });
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/insert-values-parser.js
function parseInsertExpression(arg) {
const objectOrList = isFunction(arg) ? arg(expressionBuilder()) : arg;
return parseInsertColumnsAndValues(isReadonlyArray(objectOrList) ? objectOrList : freeze([objectOrList]));
}
function parseInsertColumnsAndValues(rows) {
const columns = parseColumnNamesAndIndexes(rows);
return [freeze([...columns.keys()].map(ColumnNode.create)), ValuesNode.create(rows.map((row) => parseRowValues(row, columns)))];
}
function parseColumnNamesAndIndexes(rows) {
const columns = /* @__PURE__ */ new Map();
for (const row of rows) {
const cols = Object.keys(row);
for (const col of cols) if (!columns.has(col) && row[col] !== void 0) columns.set(col, columns.size);
}
return columns;
}
function parseRowValues(row, columns) {
const rowColumns = Object.keys(row);
const rowValues = Array.from({ length: columns.size });
let hasUndefinedOrComplexColumns = false;
let indexedRowColumns = rowColumns.length;
for (const col of rowColumns) {
const columnIdx = columns.get(col);
if (isUndefined(columnIdx)) {
indexedRowColumns--;
continue;
}
const value = row[col];
if (isUndefined(value) || isExpressionOrFactory(value)) hasUndefinedOrComplexColumns = true;
rowValues[columnIdx] = value;
}
if (indexedRowColumns < columns.size || hasUndefinedOrComplexColumns) {
const defaultValue = DefaultInsertValueNode.create();
return ValueListNode.create(rowValues.map((it) => isUndefined(it) ? defaultValue : parseValueExpression(it)));
}
return PrimitiveValueListNode.create(rowValues);
}
var init_insert_values_parser = __esmMin((() => {
init_column_node();
init_primitive_value_list_node();
init_value_list_node();
init_object_utils();
init_value_parser();
init_values_node();
init_expression_parser();
init_default_insert_value_node();
init_expression_builder();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/column-update-node.js
var ColumnUpdateNode;
var init_column_update_node = __esmMin((() => {
init_object_utils();
ColumnUpdateNode = freeze({
is(node) {
return node.kind === "ColumnUpdateNode";
},
create(column, value) {
return freeze({
kind: "ColumnUpdateNode",
column,
value
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/update-set-parser.js
function parseUpdate(...args) {
if (args.length === 2) return [ColumnUpdateNode.create(parseReferenceExpression(args[0]), parseValueExpression(args[1]))];
return parseUpdateObjectExpression(args[0]);
}
function parseUpdateObjectExpression(update) {
const updateObj = isFunction(update) ? update(expressionBuilder()) : update;
return Object.entries(updateObj).filter(([_, value]) => value !== void 0).map(([key, value]) => {
return ColumnUpdateNode.create(ColumnNode.create(key), parseValueExpression(value));
});
}
var init_update_set_parser = __esmMin((() => {
init_column_node();
init_column_update_node();
init_expression_builder();
init_object_utils();
init_value_parser();
init_reference_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/on-duplicate-key-node.js
var OnDuplicateKeyNode;
var init_on_duplicate_key_node = __esmMin((() => {
init_object_utils();
OnDuplicateKeyNode = freeze({
is(node) {
return node.kind === "OnDuplicateKeyNode";
},
create(updates) {
return freeze({
kind: "OnDuplicateKeyNode",
updates
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/insert-result.js
var InsertResult;
var init_insert_result = __esmMin((() => {
InsertResult = class {
/**
* The auto incrementing primary key of the inserted row.
*
* This property can be undefined when the query contains an `on conflict`
* clause that makes the query succeed even when nothing gets inserted.
*
* This property is always undefined on dialects like PostgreSQL that
* don't return the inserted id by default. On those dialects you need
* to use the {@link ReturningInterface.returning | returning} method.
*/
insertId;
/**
* Affected rows count.
*/
numInsertedOrUpdatedRows;
constructor(insertId, numInsertedOrUpdatedRows) {
this.insertId = insertId;
this.numInsertedOrUpdatedRows = numInsertedOrUpdatedRows;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/no-result-error.js
function isNoResultErrorConstructor(fn) {
return Object.prototype.hasOwnProperty.call(fn, "prototype");
}
var NoResultError;
var init_no_result_error = __esmMin((() => {
NoResultError = class extends Error {
/**
* The operation node tree of the query that was executed.
*/
node;
constructor(node) {
super("no result");
this.node = node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/on-conflict-node.js
var OnConflictNode;
var init_on_conflict_node = __esmMin((() => {
init_object_utils();
init_where_node();
OnConflictNode = freeze({
is(node) {
return node.kind === "OnConflictNode";
},
create() {
return freeze({ kind: "OnConflictNode" });
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
},
cloneWithIndexWhere(node, operation) {
return freeze({
...node,
indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "And", operation) : WhereNode.create(operation)
});
},
cloneWithIndexOrWhere(node, operation) {
return freeze({
...node,
indexWhere: node.indexWhere ? WhereNode.cloneWithOperation(node.indexWhere, "Or", operation) : WhereNode.create(operation)
});
},
cloneWithUpdateWhere(node, operation) {
return freeze({
...node,
updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "And", operation) : WhereNode.create(operation)
});
},
cloneWithUpdateOrWhere(node, operation) {
return freeze({
...node,
updateWhere: node.updateWhere ? WhereNode.cloneWithOperation(node.updateWhere, "Or", operation) : WhereNode.create(operation)
});
},
cloneWithoutIndexWhere(node) {
return freeze({
...node,
indexWhere: void 0
});
},
cloneWithoutUpdateWhere(node) {
return freeze({
...node,
updateWhere: void 0
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/on-conflict-builder.js
var OnConflictBuilder, OnConflictDoNothingBuilder, OnConflictUpdateBuilder;
var init_on_conflict_builder = __esmMin((() => {
init_column_node();
init_identifier_node();
init_on_conflict_node();
init_binary_operation_parser();
init_update_set_parser();
init_object_utils();
OnConflictBuilder = class OnConflictBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Specify a single column as the conflict target.
*
* Also see the {@link columns}, {@link constraint} and {@link expression}
* methods for alternative ways to specify the conflict target.
*/
column(column) {
const columnNode = ColumnNode.create(column);
return new OnConflictBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { columns: this.#props.onConflictNode.columns ? freeze([...this.#props.onConflictNode.columns, columnNode]) : freeze([columnNode]) })
});
}
/**
* Specify a list of columns as the conflict target.
*
* Also see the {@link column}, {@link constraint} and {@link expression}
* methods for alternative ways to specify the conflict target.
*/
columns(columns) {
const columnNodes = columns.map(ColumnNode.create);
return new OnConflictBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { columns: this.#props.onConflictNode.columns ? freeze([...this.#props.onConflictNode.columns, ...columnNodes]) : freeze(columnNodes) })
});
}
/**
* Specify a specific constraint by name as the conflict target.
*
* Also see the {@link column}, {@link columns} and {@link expression}
* methods for alternative ways to specify the conflict target.
*/
constraint(constraintName) {
return new OnConflictBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { constraint: IdentifierNode.create(constraintName) })
});
}
/**
* Specify an expression as the conflict target.
*
* This can be used if the unique index is an expression index.
*
* Also see the {@link column}, {@link columns} and {@link constraint}
* methods for alternative ways to specify the conflict target.
*/
expression(expression) {
return new OnConflictBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { indexExpression: expression.toOperationNode() })
});
}
where(...args) {
return new OnConflictBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args))
});
}
whereRef(lhs, op, rhs) {
return new OnConflictBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWithIndexWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs))
});
}
clearWhere() {
return new OnConflictBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWithoutIndexWhere(this.#props.onConflictNode)
});
}
/**
* Adds the "do nothing" conflict action.
*
* ### Examples
*
* ```ts
* const id = 1
* const first_name = 'John'
*
* await db
* .insertInto('person')
* .values({ first_name, id })
* .onConflict((oc) => oc
* .column('id')
* .doNothing()
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" ("first_name", "id")
* values ($1, $2)
* on conflict ("id") do nothing
* ```
*/
doNothing() {
return new OnConflictDoNothingBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { doNothing: true })
});
}
/**
* Adds the "do update set" conflict action.
*
* ### Examples
*
* ```ts
* const id = 1
* const first_name = 'John'
*
* await db
* .insertInto('person')
* .values({ first_name, id })
* .onConflict((oc) => oc
* .column('id')
* .doUpdateSet({ first_name })
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" ("first_name", "id")
* values ($1, $2)
* on conflict ("id")
* do update set "first_name" = $3
* ```
*
* In the next example we use the `ref` method to reference
* columns of the virtual table `excluded` in a type-safe way
* to create an upsert operation:
*
* ```ts
* import type { NewPerson } from 'type-editor' // imaginary module
*
* async function upsertPerson(person: NewPerson): Promise<void> {
* await db.insertInto('person')
* .values(person)
* .onConflict((oc) => oc
* .column('id')
* .doUpdateSet((eb) => ({
* first_name: eb.ref('excluded.first_name'),
* last_name: eb.ref('excluded.last_name')
* })
* )
* )
* .execute()
* }
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" ("first_name", "last_name")
* values ($1, $2)
* on conflict ("id")
* do update set
* "first_name" = excluded."first_name",
* "last_name" = excluded."last_name"
* ```
*/
doUpdateSet(update) {
return new OnConflictUpdateBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWith(this.#props.onConflictNode, { updates: parseUpdateObjectExpression(update) })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
};
OnConflictDoNothingBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
toOperationNode() {
return this.#props.onConflictNode;
}
};
OnConflictUpdateBuilder = class OnConflictUpdateBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
where(...args) {
return new OnConflictUpdateBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseValueBinaryOperationOrExpression(args))
});
}
/**
* Specify a where condition for the update operation.
*
* See {@link WhereInterface.whereRef} for more info.
*/
whereRef(lhs, op, rhs) {
return new OnConflictUpdateBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWithUpdateWhere(this.#props.onConflictNode, parseReferentialBinaryOperation(lhs, op, rhs))
});
}
clearWhere() {
return new OnConflictUpdateBuilder({
...this.#props,
onConflictNode: OnConflictNode.cloneWithoutUpdateWhere(this.#props.onConflictNode)
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.onConflictNode;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/top-node.js
var TopNode;
var init_top_node = __esmMin((() => {
init_object_utils();
TopNode = freeze({
is(node) {
return node.kind === "TopNode";
},
create(expression, modifiers) {
return freeze({
kind: "TopNode",
expression,
modifiers
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/top-parser.js
function parseTop(expression, modifiers) {
if (!isNumber(expression) && !isBigInt(expression)) throw new Error(`Invalid top expression: ${expression}`);
if (!isUndefined(modifiers) && !isTopModifiers(modifiers)) throw new Error(`Invalid top modifiers: ${modifiers}`);
return TopNode.create(expression, modifiers);
}
function isTopModifiers(modifiers) {
return modifiers === "percent" || modifiers === "with ties" || modifiers === "percent with ties";
}
var init_top_parser = __esmMin((() => {
init_top_node();
init_object_utils();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/or-action-node.js
var OrActionNode;
var init_or_action_node = __esmMin((() => {
init_object_utils();
OrActionNode = freeze({
is(node) {
return node.kind === "OrActionNode";
},
create(action) {
return freeze({
kind: "OrActionNode",
action
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/insert-query-builder.js
var InsertQueryBuilder;
var init_insert_query_builder = __esmMin((() => {
init_select_parser();
init_insert_values_parser();
init_insert_query_node();
init_query_node();
init_update_set_parser();
init_object_utils();
init_on_duplicate_key_node();
init_insert_result();
init_no_result_error();
init_expression_parser();
init_column_node();
init_on_conflict_builder();
init_on_conflict_node();
init_top_parser();
init_or_action_node();
InsertQueryBuilder = class InsertQueryBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Sets the values to insert for an {@link Kysely.insertInto | insert} query.
*
* This method takes an object whose keys are column names and values are
* values to insert. In addition to the column's type, the values can be
* raw {@link sql} snippets or select queries.
*
* You must provide all fields you haven't explicitly marked as nullable
* or optional using {@link Generated} or {@link ColumnType}.
*
* The return value of an `insert` query is an instance of {@link InsertResult}. The
* {@link InsertResult.insertId | insertId} field holds the auto incremented primary
* key if the database returned one.
*
* On PostgreSQL and some other dialects, you need to call `returning` to get
* something out of the query.
*
* Also see the {@link expression} method for inserting the result of a select
* query or any other expression.
*
* ### Examples
*
* <!-- siteExample("insert", "Single row", 10) -->
*
* Insert a single row:
*
* ```ts
* const result = await db
* .insertInto('person')
* .values({
* first_name: 'Jennifer',
* last_name: 'Aniston',
* age: 40
* })
* .executeTakeFirst()
*
* // `insertId` is only available on dialects that
* // automatically return the id of the inserted row
* // such as MySQL and SQLite. On PostgreSQL, for example,
* // you need to add a `returning` clause to the query to
* // get anything out. See the "returning data" example.
* console.log(result.insertId)
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* insert into `person` (`first_name`, `last_name`, `age`) values (?, ?, ?)
* ```
*
* <!-- siteExample("insert", "Multiple rows", 20) -->
*
* On dialects that support it (for example PostgreSQL) you can insert multiple
* rows by providing an array. Note that the return value is once again very
* dialect-specific. Some databases may only return the id of the *last* inserted
* row and some return nothing at all unless you call `returning`.
*
* ```ts
* await db
* .insertInto('person')
* .values([{
* first_name: 'Jennifer',
* last_name: 'Aniston',
* age: 40,
* }, {
* first_name: 'Arnold',
* last_name: 'Schwarzenegger',
* age: 70,
* }])
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" ("first_name", "last_name", "age") values (($1, $2, $3), ($4, $5, $6))
* ```
*
* <!-- siteExample("insert", "Returning data", 30) -->
*
* On supported dialects like PostgreSQL you need to chain `returning` to the query to get
* the inserted row's columns (or any other expression) as the return value. `returning`
* works just like `select`. Refer to `select` method's examples and documentation for
* more info.
*
* ```ts
* const result = await db
* .insertInto('person')
* .values({
* first_name: 'Jennifer',
* last_name: 'Aniston',
* age: 40,
* })
* .returning(['id', 'first_name as name'])
* .executeTakeFirstOrThrow()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" ("first_name", "last_name", "age") values ($1, $2, $3) returning "id", "first_name" as "name"
* ```
*
* <!-- siteExample("insert", "Complex values", 40) -->
*
* In addition to primitives, the values can also be arbitrary expressions.
* You can build the expressions by using a callback and calling the methods
* on the expression builder passed to it:
*
* ```ts
* import { sql } from 'kysely'
*
* const ani = "Ani"
* const ston = "ston"
*
* const result = await db
* .insertInto('person')
* .values(({ ref, selectFrom, fn }) => ({
* first_name: 'Jennifer',
* last_name: sql<string>`concat(${ani}, ${ston})`,
* middle_name: ref('first_name'),
* age: selectFrom('person')
* .select(fn.avg<number>('age').as('avg_age')),
* }))
* .executeTakeFirst()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" (
* "first_name",
* "last_name",
* "middle_name",
* "age"
* )
* values (
* $1,
* concat($2, $3),
* "first_name",
* (select avg("age") as "avg_age" from "person")
* )
* ```
*
* You can also use the callback version of subqueries or raw expressions:
*
* ```ts
* await db.with('jennifer', (db) => db
* .selectFrom('person')
* .where('first_name', '=', 'Jennifer')
* .select(['id', 'first_name', 'gender'])
* .limit(1)
* ).insertInto('pet').values((eb) => ({
* owner_id: eb.selectFrom('jennifer').select('id'),
* name: eb.selectFrom('jennifer').select('first_name'),
* species: 'cat',
* }))
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* with "jennifer" as (
* select "id", "first_name", "gender"
* from "person"
* where "first_name" = $1
* limit $2
* )
* insert into "pet" ("owner_id", "name", "species")
* values (
* (select "id" from "jennifer"),
* (select "first_name" from "jennifer"),
* $3
* )
* ```
*/
values(insert) {
const [columns, values] = parseInsertExpression(insert);
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, {
columns,
values
})
});
}
/**
* Sets the columns to insert.
*
* The {@link values} method sets both the columns and the values and this method
* is not needed. But if you are using the {@link expression} method, you can use
* this method to set the columns to insert.
*
* ### Examples
*
* ```ts
* await db.insertInto('person')
* .columns(['first_name'])
* .expression((eb) => eb.selectFrom('pet').select('pet.name'))
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" ("first_name")
* select "pet"."name" from "pet"
* ```
*/
columns(columns) {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { columns: freeze(columns.map(ColumnNode.create)) })
});
}
/**
* Insert an arbitrary expression. For example the result of a select query.
*
* ### Examples
*
* <!-- siteExample("insert", "Insert subquery", 50) -->
*
* You can create an `INSERT INTO SELECT FROM` query using the `expression` method.
* This API doesn't follow our WYSIWYG principles and might be a bit difficult to
* remember. The reasons for this design stem from implementation difficulties.
*
* ```ts
* const result = await db.insertInto('person')
* .columns(['first_name', 'last_name', 'age'])
* .expression((eb) => eb
* .selectFrom('pet')
* .select((eb) => [
* 'pet.name',
* eb.val('Petson').as('last_name'),
* eb.lit(7).as('age'),
* ])
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" ("first_name", "last_name", "age")
* select "pet"."name", $1 as "last_name", 7 as "age from "pet"
* ```
*/
expression(expression) {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { values: parseExpression(expression) })
});
}
/**
* Creates an `insert into "person" default values` query.
*
* ### Examples
*
* ```ts
* await db.insertInto('person')
* .defaultValues()
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" default values
* ```
*/
defaultValues() {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { defaultValues: true })
});
}
/**
* This can be used to add any additional SQL to the end of the query.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.insertInto('person')
* .values({
* first_name: 'John',
* last_name: 'Doe',
* gender: 'male',
* })
* .modifyEnd(sql`-- This is a comment`)
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* insert into `person` ("first_name", "last_name", "gender")
* values (?, ?, ?) -- This is a comment
* ```
*/
modifyEnd(modifier) {
return new InsertQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
});
}
/**
* Changes an `insert into` query to an `insert ignore into` query.
*
* This is only supported by some dialects like MySQL.
*
* To avoid a footgun, when invoked with the SQLite dialect, this method will
* be handled like {@link orIgnore}. See also, {@link orAbort}, {@link orFail},
* {@link orReplace}, and {@link orRollback}.
*
* If you use the ignore modifier, ignorable errors that occur while executing the
* insert statement are ignored. For example, without ignore, a row that duplicates
* an existing unique index or primary key value in the table causes a duplicate-key
* error and the statement is aborted. With ignore, the row is discarded and no error
* occurs.
*
* ### Examples
*
* ```ts
* await db.insertInto('person')
* .ignore()
* .values({
* first_name: 'John',
* last_name: 'Doe',
* gender: 'female',
* })
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?)
* ```
*
* The generated SQL (SQLite):
*
* ```sql
* insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
* ```
*/
ignore() {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { orAction: OrActionNode.create("ignore") })
});
}
/**
* Changes an `insert into` query to an `insert or ignore into` query.
*
* This is only supported by some dialects like SQLite.
*
* To avoid a footgun, when invoked with the MySQL dialect, this method will
* be handled like {@link ignore}.
*
* See also, {@link orAbort}, {@link orFail}, {@link orReplace}, and {@link orRollback}.
*
* ### Examples
*
* ```ts
* await db.insertInto('person')
* .orIgnore()
* .values({
* first_name: 'John',
* last_name: 'Doe',
* gender: 'female',
* })
* .execute()
* ```
*
* The generated SQL (SQLite):
*
* ```sql
* insert or ignore into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* insert ignore into `person` (`first_name`, `last_name`, `gender`) values (?, ?, ?)
* ```
*/
orIgnore() {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { orAction: OrActionNode.create("ignore") })
});
}
/**
* Changes an `insert into` query to an `insert or abort into` query.
*
* This is only supported by some dialects like SQLite.
*
* See also, {@link orIgnore}, {@link orFail}, {@link orReplace}, and {@link orRollback}.
*
* ### Examples
*
* ```ts
* await db.insertInto('person')
* .orAbort()
* .values({
* first_name: 'John',
* last_name: 'Doe',
* gender: 'female',
* })
* .execute()
* ```
*
* The generated SQL (SQLite):
*
* ```sql
* insert or abort into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
* ```
*/
orAbort() {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { orAction: OrActionNode.create("abort") })
});
}
/**
* Changes an `insert into` query to an `insert or fail into` query.
*
* This is only supported by some dialects like SQLite.
*
* See also, {@link orIgnore}, {@link orAbort}, {@link orReplace}, and {@link orRollback}.
*
* ### Examples
*
* ```ts
* await db.insertInto('person')
* .orFail()
* .values({
* first_name: 'John',
* last_name: 'Doe',
* gender: 'female',
* })
* .execute()
* ```
*
* The generated SQL (SQLite):
*
* ```sql
* insert or fail into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
* ```
*/
orFail() {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { orAction: OrActionNode.create("fail") })
});
}
/**
* Changes an `insert into` query to an `insert or replace into` query.
*
* This is only supported by some dialects like SQLite.
*
* You can also use {@link Kysely.replaceInto} to achieve the same result.
*
* See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orRollback}.
*
* ### Examples
*
* ```ts
* await db.insertInto('person')
* .orReplace()
* .values({
* first_name: 'John',
* last_name: 'Doe',
* gender: 'female',
* })
* .execute()
* ```
*
* The generated SQL (SQLite):
*
* ```sql
* insert or replace into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
* ```
*/
orReplace() {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { orAction: OrActionNode.create("replace") })
});
}
/**
* Changes an `insert into` query to an `insert or rollback into` query.
*
* This is only supported by some dialects like SQLite.
*
* See also, {@link orIgnore}, {@link orAbort}, {@link orFail}, and {@link orReplace}.
*
* ### Examples
*
* ```ts
* await db.insertInto('person')
* .orRollback()
* .values({
* first_name: 'John',
* last_name: 'Doe',
* gender: 'female',
* })
* .execute()
* ```
*
* The generated SQL (SQLite):
*
* ```sql
* insert or rollback into "person" ("first_name", "last_name", "gender") values (?, ?, ?)
* ```
*/
orRollback() {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { orAction: OrActionNode.create("rollback") })
});
}
/**
* Changes an `insert into` query to an `insert top into` query.
*
* `top` clause is only supported by some dialects like MS SQL Server.
*
* ### Examples
*
* Insert the first 5 rows:
*
* ```ts
* import { sql } from 'kysely'
*
* await db.insertInto('person')
* .top(5)
* .columns(['first_name', 'gender'])
* .expression(
* (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')])
* )
* .execute()
* ```
*
* The generated SQL (MS SQL Server):
*
* ```sql
* insert top(5) into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet"
* ```
*
* Insert the first 50 percent of rows:
*
* ```ts
* import { sql } from 'kysely'
*
* await db.insertInto('person')
* .top(50, 'percent')
* .columns(['first_name', 'gender'])
* .expression(
* (eb) => eb.selectFrom('pet').select(['name', sql.lit('other').as('gender')])
* )
* .execute()
* ```
*
* The generated SQL (MS SQL Server):
*
* ```sql
* insert top(50) percent into "person" ("first_name", "gender") select "name", 'other' as "gender" from "pet"
* ```
*/
top(expression, modifiers) {
return new InsertQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
});
}
/**
* Adds an `on conflict` clause to the query.
*
* `on conflict` is only supported by some dialects like PostgreSQL and SQLite. On MySQL
* you can use {@link ignore} and {@link onDuplicateKeyUpdate} to achieve similar results.
*
* ### Examples
*
* ```ts
* await db
* .insertInto('pet')
* .values({
* name: 'Catto',
* species: 'cat',
* owner_id: 3,
* })
* .onConflict((oc) => oc
* .column('name')
* .doUpdateSet({ species: 'hamster' })
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "pet" ("name", "species", "owner_id")
* values ($1, $2, $3)
* on conflict ("name")
* do update set "species" = $4
* ```
*
* You can provide the name of the constraint instead of a column name:
*
* ```ts
* await db
* .insertInto('pet')
* .values({
* name: 'Catto',
* species: 'cat',
* owner_id: 3,
* })
* .onConflict((oc) => oc
* .constraint('pet_name_key')
* .doUpdateSet({ species: 'hamster' })
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "pet" ("name", "species", "owner_id")
* values ($1, $2, $3)
* on conflict on constraint "pet_name_key"
* do update set "species" = $4
* ```
*
* You can also specify an expression as the conflict target in case
* the unique index is an expression index:
*
* ```ts
* import { sql } from 'kysely'
*
* await db
* .insertInto('pet')
* .values({
* name: 'Catto',
* species: 'cat',
* owner_id: 3,
* })
* .onConflict((oc) => oc
* .expression(sql<string>`lower(name)`)
* .doUpdateSet({ species: 'hamster' })
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "pet" ("name", "species", "owner_id")
* values ($1, $2, $3)
* on conflict (lower(name))
* do update set "species" = $4
* ```
*
* You can add a filter for the update statement like this:
*
* ```ts
* await db
* .insertInto('pet')
* .values({
* name: 'Catto',
* species: 'cat',
* owner_id: 3,
* })
* .onConflict((oc) => oc
* .column('name')
* .doUpdateSet({ species: 'hamster' })
* .where('excluded.name', '!=', 'Catto')
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "pet" ("name", "species", "owner_id")
* values ($1, $2, $3)
* on conflict ("name")
* do update set "species" = $4
* where "excluded"."name" != $5
* ```
*
* You can create an `on conflict do nothing` clauses like this:
*
* ```ts
* await db
* .insertInto('pet')
* .values({
* name: 'Catto',
* species: 'cat',
* owner_id: 3,
* })
* .onConflict((oc) => oc
* .column('name')
* .doNothing()
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "pet" ("name", "species", "owner_id")
* values ($1, $2, $3)
* on conflict ("name") do nothing
* ```
*
* You can refer to the columns of the virtual `excluded` table
* in a type-safe way using a callback and the `ref` method of
* `ExpressionBuilder`:
*
* ```ts
* await db.insertInto('person')
* .values({
* id: 1,
* first_name: 'John',
* last_name: 'Doe',
* gender: 'male',
* })
* .onConflict(oc => oc
* .column('id')
* .doUpdateSet({
* first_name: (eb) => eb.ref('excluded.first_name'),
* last_name: (eb) => eb.ref('excluded.last_name')
* })
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* insert into "person" ("id", "first_name", "last_name", "gender")
* values ($1, $2, $3, $4)
* on conflict ("id")
* do update set
* "first_name" = "excluded"."first_name",
* "last_name" = "excluded"."last_name"
* ```
*/
onConflict(callback) {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { onConflict: callback(new OnConflictBuilder({ onConflictNode: OnConflictNode.create() })).toOperationNode() })
});
}
/**
* Adds `on duplicate key update` to the query.
*
* If you specify `on duplicate key update`, and a row is inserted that would cause
* a duplicate value in a unique index or primary key, an update of the old row occurs.
*
* This is only implemented by some dialects like MySQL. On most dialects you should
* use {@link onConflict} instead.
*
* ### Examples
*
* ```ts
* await db
* .insertInto('person')
* .values({
* id: 1,
* first_name: 'John',
* last_name: 'Doe',
* gender: 'male',
* })
* .onDuplicateKeyUpdate({ updated_at: new Date().toISOString() })
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* insert into `person` (`id`, `first_name`, `last_name`, `gender`)
* values (?, ?, ?, ?)
* on duplicate key update `updated_at` = ?
* ```
*/
onDuplicateKeyUpdate(update) {
return new InsertQueryBuilder({
...this.#props,
queryNode: InsertQueryNode.cloneWith(this.#props.queryNode, { onDuplicateKey: OnDuplicateKeyNode.create(parseUpdateObjectExpression(update)) })
});
}
returning(selection) {
return new InsertQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection))
});
}
returningAll() {
return new InsertQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll())
});
}
output(args) {
return new InsertQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
});
}
outputAll(table) {
return new InsertQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
});
}
/**
* Clears all `returning` clauses from the query.
*
* ### Examples
*
* ```ts
* await db.insertInto('person')
* .values({ first_name: 'James', last_name: 'Smith', gender: 'male' })
* .returning(['first_name'])
* .clearReturning()
* .execute()
* ```
*
* The generated SQL(PostgreSQL):
*
* ```sql
* insert into "person" ("first_name", "last_name", "gender") values ($1, $2, $3)
* ```
*/
clearReturning() {
return new InsertQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode)
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*
* If you want to conditionally call a method on `this`, see
* the {@link $if} method.
*
* ### Examples
*
* The next example uses a helper function `log` to log a query:
*
* ```ts
* import type { Compilable } from 'kysely'
*
* function log<T extends Compilable>(qb: T): T {
* console.log(qb.compile())
* return qb
* }
*
* await db.insertInto('person')
* .values({ first_name: 'John', last_name: 'Doe', gender: 'male' })
* .$call(log)
* .execute()
* ```
*/
$call(func) {
return func(this);
}
/**
* Call `func(this)` if `condition` is true.
*
* This method is especially handy with optional selects. Any `returning` or `returningAll`
* method calls add columns as optional fields to the output type when called inside
* the `func` callback. This is because we can't know if those selections were actually
* made before running the code.
*
* You can also call any other methods inside the callback.
*
* ### Examples
*
* ```ts
* import type { NewPerson } from 'type-editor' // imaginary module
*
* async function insertPerson(values: NewPerson, returnLastName: boolean) {
* return await db
* .insertInto('person')
* .values(values)
* .returning(['id', 'first_name'])
* .$if(returnLastName, (qb) => qb.returning('last_name'))
* .executeTakeFirstOrThrow()
* }
* ```
*
* Any selections added inside the `if` callback will be added as optional fields to the
* output type since we can't know if the selections were actually made before running
* the code. In the example above the return type of the `insertPerson` function is:
*
* ```ts
* Promise<{
* id: number
* first_name: string
* last_name?: string
* }>
* ```
*/
$if(condition, func) {
if (condition) return func(this);
return new InsertQueryBuilder({ ...this.#props });
}
/**
* Change the output type of the query.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of this `InsertQueryBuilder` with a new output type.
*/
$castTo() {
return new InsertQueryBuilder(this.#props);
}
/**
* Narrows (parts of) the output type of the query.
*
* Kysely tries to be as type-safe as possible, but in some cases we have to make
* compromises for better maintainability and compilation performance. At present,
* Kysely doesn't narrow the output type of the query based on {@link values} input
* when using {@link returning} or {@link returningAll}.
*
* This utility method is very useful for these situations, as it removes unncessary
* runtime assertion/guard code. Its input type is limited to the output type
* of the query, so you can't add a column that doesn't exist, or change a column's
* type to something that doesn't exist in its union type.
*
* ### Examples
*
* Turn this code:
*
* ```ts
* import type { Person } from 'type-editor' // imaginary module
*
* const person = await db.insertInto('person')
* .values({
* first_name: 'John',
* last_name: 'Doe',
* gender: 'male',
* nullable_column: 'hell yeah!'
* })
* .returningAll()
* .executeTakeFirstOrThrow()
*
* if (isWithNoNullValue(person)) {
* functionThatExpectsPersonWithNonNullValue(person)
* }
*
* function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {
* return person.nullable_column != null
* }
* ```
*
* Into this:
*
* ```ts
* import type { NotNull } from 'kysely'
*
* const person = await db.insertInto('person')
* .values({
* first_name: 'John',
* last_name: 'Doe',
* gender: 'male',
* nullable_column: 'hell yeah!'
* })
* .returningAll()
* .$narrowType<{ nullable_column: NotNull }>()
* .executeTakeFirstOrThrow()
*
* functionThatExpectsPersonWithNonNullValue(person)
* ```
*/
$narrowType() {
return new InsertQueryBuilder(this.#props);
}
/**
* Asserts that query's output row type equals the given type `T`.
*
* This method can be used to simplify excessively complex types to make TypeScript happy
* and much faster.
*
* Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much
* for TypeScript and you get errors like this:
*
* ```
* error TS2589: Type instantiation is excessively deep and possibly infinite.
* ```
*
* In these case you can often use this method to help TypeScript a little bit. When you use this
* method to assert the output type of a query, Kysely can drop the complex output type that
* consists of multiple nested helper types and replace it with the simple asserted type.
*
* Using this method doesn't reduce type safety at all. You have to pass in a type that is
* structurally equal to the current type.
*
* ### Examples
*
* ```ts
* import type { NewPerson, NewPet, Species } from 'type-editor' // imaginary module
*
* async function insertPersonAndPet(person: NewPerson, pet: Omit<NewPet, 'owner_id'>) {
* return await db
* .with('new_person', (qb) => qb
* .insertInto('person')
* .values(person)
* .returning('id')
* .$assertType<{ id: number }>()
* )
* .with('new_pet', (qb) => qb
* .insertInto('pet')
* .values((eb) => ({
* owner_id: eb.selectFrom('new_person').select('id'),
* ...pet
* }))
* .returning(['name as pet_name', 'species'])
* .$assertType<{ pet_name: string, species: Species }>()
* )
* .selectFrom(['new_person', 'new_pet'])
* .selectAll()
* .executeTakeFirstOrThrow()
* }
* ```
*/
$assertType() {
return new InsertQueryBuilder(this.#props);
}
/**
* Returns a copy of this InsertQueryBuilder instance with the given plugin installed.
*/
withPlugin(plugin) {
return new InsertQueryBuilder({
...this.#props,
executor: this.#props.executor.withPlugin(plugin)
});
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
const compiledQuery = this.compile();
const result = await this.#props.executor.executeQuery(compiledQuery, options);
const { adapter } = this.#props.executor;
const query = compiledQuery.query;
if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) return result.rows;
return [new InsertResult(result.insertId, result.numAffectedRows ?? BigInt(0))];
}
async executeTakeFirst(options) {
const [result] = await this.execute(options);
return result;
}
async executeTakeFirstOrThrow(errorConstructorOrOptions) {
if (typeof errorConstructorOrOptions === "function") errorConstructorOrOptions = { errorConstructor: errorConstructorOrOptions };
const result = await this.executeTakeFirst(errorConstructorOrOptions);
if (result === void 0) {
const errorConstructor = errorConstructorOrOptions?.errorConstructor ?? NoResultError;
throw isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
}
return result;
}
async *stream(chunkSizeOrOptions) {
if (typeof chunkSizeOrOptions !== "object") chunkSizeOrOptions = { chunkSize: chunkSizeOrOptions };
const compiledQuery = this.compile();
const stream = this.#props.executor.stream(compiledQuery, chunkSizeOrOptions.chunkSize ?? 100, chunkSizeOrOptions);
for await (const item of stream) yield* item.rows;
}
async explain(format, options) {
return await new InsertQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options)
}).execute();
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/delete-result.js
var DeleteResult;
var init_delete_result = __esmMin((() => {
DeleteResult = class {
numDeletedRows;
constructor(numDeletedRows) {
this.numDeletedRows = numDeletedRows;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/limit-node.js
var LimitNode;
var init_limit_node = __esmMin((() => {
init_object_utils();
LimitNode = freeze({
is(node) {
return node.kind === "LimitNode";
},
create(limit) {
return freeze({
kind: "LimitNode",
limit
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/delete-query-builder.js
var _a$5, DeleteQueryBuilder;
var init_delete_query_builder = __esmMin((() => {
init_join_parser();
init_table_parser();
init_select_parser();
init_query_node();
init_object_utils();
init_no_result_error();
init_delete_result();
init_delete_query_node();
init_limit_node();
init_order_by_parser();
init_binary_operation_parser();
init_value_parser();
init_top_parser();
DeleteQueryBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
where(...args) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args))
});
}
whereRef(lhs, op, rhs) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs))
});
}
clearWhere() {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode)
});
}
/**
* Changes a `delete from` query into a `delete top from` query.
*
* `top` clause is only supported by some dialects like MS SQL Server.
*
* ### Examples
*
* Delete the first 5 rows:
*
* ```ts
* await db
* .deleteFrom('person')
* .top(5)
* .where('age', '>', 18)
* .executeTakeFirstOrThrow()
* ```
*
* The generated SQL (MS SQL Server):
*
* ```sql
* delete top(5) from "person" where "age" > @1
* ```
*
* Delete the first 50% of rows:
*
* ```ts
* await db
* .deleteFrom('person')
* .top(50, 'percent')
* .where('age', '>', 18)
* .executeTakeFirstOrThrow()
* ```
*
* The generated SQL (MS SQL Server):
*
* ```sql
* delete top(50) percent from "person" where "age" > @1
* ```
*/
top(expression, modifiers) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
});
}
using(tables) {
return new _a$5({
...this.#props,
queryNode: DeleteQueryNode.cloneWithUsing(this.#props.queryNode, parseTableExpressionOrList(tables))
});
}
innerJoin(...args) {
return this.#join("InnerJoin", args);
}
leftJoin(...args) {
return this.#join("LeftJoin", args);
}
rightJoin(...args) {
return this.#join("RightJoin", args);
}
fullJoin(...args) {
return this.#join("FullJoin", args);
}
#join(joinType, args) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args))
});
}
returning(selection) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection))
});
}
returningAll(table) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table))
});
}
output(args) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
});
}
outputAll(table) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
});
}
/**
* Clears all `returning` clauses from the query.
*
* ### Examples
*
* ```ts
* await db.deleteFrom('pet')
* .returningAll()
* .where('name', '=', 'Max')
* .clearReturning()
* .execute()
* ```
*
* The generated SQL(PostgreSQL):
*
* ```sql
* delete from "pet" where "name" = "Max"
* ```
*/
clearReturning() {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode)
});
}
/**
* Clears the `limit` clause from the query.
*
* ### Examples
*
* ```ts
* await db.deleteFrom('pet')
* .returningAll()
* .where('name', '=', 'Max')
* .limit(5)
* .clearLimit()
* .execute()
* ```
*
* The generated SQL(PostgreSQL):
*
* ```sql
* delete from "pet" where "name" = "Max" returning *
* ```
*/
clearLimit() {
return new _a$5({
...this.#props,
queryNode: DeleteQueryNode.cloneWithoutLimit(this.#props.queryNode)
});
}
orderBy(...args) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args))
});
}
clearOrderBy() {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode)
});
}
/**
* Adds a limit clause to the query.
*
* A limit clause in a delete query is only supported by some dialects
* like MySQL.
*
* ### Examples
*
* Delete 5 oldest items in a table:
*
* ```ts
* await db
* .deleteFrom('pet')
* .orderBy('created_at')
* .limit(5)
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* delete from `pet` order by `created_at` limit ?
* ```
*/
limit(limit) {
return new _a$5({
...this.#props,
queryNode: DeleteQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit)))
});
}
/**
* This can be used to add any additional SQL to the end of the query.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.deleteFrom('person')
* .where('first_name', '=', 'John')
* .modifyEnd(sql`-- This is a comment`)
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* delete from `person`
* where `first_name` = "John" -- This is a comment
* ```
*/
modifyEnd(modifier) {
return new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*
* If you want to conditionally call a method on `this`, see
* the {@link $if} method.
*
* ### Examples
*
* The next example uses a helper function `log` to log a query:
*
* ```ts
* import type { Compilable } from 'kysely'
*
* function log<T extends Compilable>(qb: T): T {
* console.log(qb.compile())
* return qb
* }
*
* await db.deleteFrom('person')
* .$call(log)
* .execute()
* ```
*/
$call(func) {
return func(this);
}
/**
* Call `func(this)` if `condition` is true.
*
* This method is especially handy with optional selects. Any `returning` or `returningAll`
* method calls add columns as optional fields to the output type when called inside
* the `func` callback. This is because we can't know if those selections were actually
* made before running the code.
*
* You can also call any other methods inside the callback.
*
* ### Examples
*
* ```ts
* async function deletePerson(id: number, returnLastName: boolean) {
* return await db
* .deleteFrom('person')
* .where('id', '=', id)
* .returning(['id', 'first_name'])
* .$if(returnLastName, (qb) => qb.returning('last_name'))
* .executeTakeFirstOrThrow()
* }
* ```
*
* Any selections added inside the `if` callback will be added as optional fields to the
* output type since we can't know if the selections were actually made before running
* the code. In the example above the return type of the `deletePerson` function is:
*
* ```ts
* Promise<{
* id: number
* first_name: string
* last_name?: string
* }>
* ```
*/
$if(condition, func) {
if (condition) return func(this);
return new _a$5({ ...this.#props });
}
/**
* Change the output type of the query.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of this `DeleteQueryBuilder` with a new output type.
*/
$castTo() {
return new _a$5(this.#props);
}
/**
* Narrows (parts of) the output type of the query.
*
* Kysely tries to be as type-safe as possible, but in some cases we have to make
* compromises for better maintainability and compilation performance. At present,
* Kysely doesn't narrow the output type of the query when using {@link where} and {@link returning} or {@link returningAll}.
*
* This utility method is very useful for these situations, as it removes unncessary
* runtime assertion/guard code. Its input type is limited to the output type
* of the query, so you can't add a column that doesn't exist, or change a column's
* type to something that doesn't exist in its union type.
*
* ### Examples
*
* Turn this code:
*
* ```ts
* import type { Person } from 'type-editor' // imaginary module
*
* const person = await db.deleteFrom('person')
* .where('id', '=', 3)
* .where('nullable_column', 'is not', null)
* .returningAll()
* .executeTakeFirstOrThrow()
*
* if (isWithNoNullValue(person)) {
* functionThatExpectsPersonWithNonNullValue(person)
* }
*
* function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {
* return person.nullable_column != null
* }
* ```
*
* Into this:
*
* ```ts
* import type { NotNull } from 'kysely'
*
* const person = await db.deleteFrom('person')
* .where('id', '=', 3)
* .where('nullable_column', 'is not', null)
* .returningAll()
* .$narrowType<{ nullable_column: NotNull }>()
* .executeTakeFirstOrThrow()
*
* functionThatExpectsPersonWithNonNullValue(person)
* ```
*/
$narrowType() {
return new _a$5(this.#props);
}
/**
* Asserts that query's output row type equals the given type `T`.
*
* This method can be used to simplify excessively complex types to make TypeScript happy
* and much faster.
*
* Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much
* for TypeScript and you get errors like this:
*
* ```
* error TS2589: Type instantiation is excessively deep and possibly infinite.
* ```
*
* In these case you can often use this method to help TypeScript a little bit. When you use this
* method to assert the output type of a query, Kysely can drop the complex output type that
* consists of multiple nested helper types and replace it with the simple asserted type.
*
* Using this method doesn't reduce type safety at all. You have to pass in a type that is
* structurally equal to the current type.
*
* ### Examples
*
* ```ts
* import type { Species } from 'type-editor' // imaginary module
*
* async function deletePersonAndPets(personId: number) {
* return await db
* .with('deleted_person', (qb) => qb
* .deleteFrom('person')
* .where('id', '=', personId)
* .returning('first_name')
* .$assertType<{ first_name: string }>()
* )
* .with('deleted_pets', (qb) => qb
* .deleteFrom('pet')
* .where('owner_id', '=', personId)
* .returning(['name as pet_name', 'species'])
* .$assertType<{ pet_name: string, species: Species }>()
* )
* .selectFrom(['deleted_person', 'deleted_pets'])
* .selectAll()
* .execute()
* }
* ```
*/
$assertType() {
return new _a$5(this.#props);
}
/**
* Returns a copy of this DeleteQueryBuilder instance with the given plugin installed.
*/
withPlugin(plugin) {
return new _a$5({
...this.#props,
executor: this.#props.executor.withPlugin(plugin)
});
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
const compiledQuery = this.compile();
const result = await this.#props.executor.executeQuery(compiledQuery, options);
const { adapter } = this.#props.executor;
const query = compiledQuery.query;
if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) return result.rows;
return [new DeleteResult(result.numAffectedRows ?? BigInt(0))];
}
async executeTakeFirst(options) {
const [result] = await this.execute(options);
return result;
}
async executeTakeFirstOrThrow(errorConstructorOrOptions) {
if (typeof errorConstructorOrOptions === "function") errorConstructorOrOptions = { errorConstructor: errorConstructorOrOptions };
const result = await this.executeTakeFirst(errorConstructorOrOptions);
if (result === void 0) {
const errorConstructor = errorConstructorOrOptions?.errorConstructor ?? NoResultError;
throw isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
}
return result;
}
async *stream(chunkSizeOrOptions) {
if (typeof chunkSizeOrOptions !== "object") chunkSizeOrOptions = { chunkSize: chunkSizeOrOptions };
const compiledQuery = this.compile();
const stream = this.#props.executor.stream(compiledQuery, chunkSizeOrOptions.chunkSize ?? 100, chunkSizeOrOptions);
for await (const item of stream) yield* item.rows;
}
async explain(format, options) {
return await new _a$5({
...this.#props,
queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options)
}).execute();
}
};
_a$5 = DeleteQueryBuilder;
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/update-result.js
var UpdateResult;
var init_update_result = __esmMin((() => {
UpdateResult = class {
/**
* The number of rows the update query updated (even if not changed).
*/
numUpdatedRows;
/**
* The number of rows the update query changed.
*
* This is **optional** and only supported in dialects such as MySQL.
* You would probably use {@link numUpdatedRows} in most cases.
*/
numChangedRows;
constructor(numUpdatedRows, numChangedRows) {
this.numUpdatedRows = numUpdatedRows;
this.numChangedRows = numChangedRows;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/update-query-builder.js
var _a$4, UpdateQueryBuilder;
var init_update_query_builder = __esmMin((() => {
init_join_parser();
init_table_parser();
init_select_parser();
init_query_node();
init_update_query_node();
init_update_set_parser();
init_object_utils();
init_update_result();
init_no_result_error();
init_binary_operation_parser();
init_value_parser();
init_limit_node();
init_top_parser();
init_order_by_parser();
UpdateQueryBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
where(...args) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args))
});
}
whereRef(lhs, op, rhs) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs))
});
}
clearWhere() {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode)
});
}
/**
* Changes an `update` query into a `update top` query.
*
* `top` clause is only supported by some dialects like MS SQL Server.
*
* ### Examples
*
* Update the first row:
*
* ```ts
* await db.updateTable('person')
* .top(1)
* .set({ first_name: 'Foo' })
* .where('age', '>', 18)
* .executeTakeFirstOrThrow()
* ```
*
* The generated SQL (MS SQL Server):
*
* ```sql
* update top(1) "person" set "first_name" = @1 where "age" > @2
* ```
*
* Update the 50% first rows:
*
* ```ts
* await db.updateTable('person')
* .top(50, 'percent')
* .set({ first_name: 'Foo' })
* .where('age', '>', 18)
* .executeTakeFirstOrThrow()
* ```
*
* The generated SQL (MS SQL Server):
*
* ```sql
* update top(50) percent "person" set "first_name" = @1 where "age" > @2
* ```
*/
top(expression, modifiers) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
});
}
from(from) {
return new _a$4({
...this.#props,
queryNode: UpdateQueryNode.cloneWithFromItems(this.#props.queryNode, parseTableExpressionOrList(from))
});
}
innerJoin(...args) {
return this.#join("InnerJoin", args);
}
leftJoin(...args) {
return this.#join("LeftJoin", args);
}
rightJoin(...args) {
return this.#join("RightJoin", args);
}
fullJoin(...args) {
return this.#join("FullJoin", args);
}
#join(joinType, args) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args))
});
}
orderBy(...args) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args))
});
}
clearOrderBy() {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode)
});
}
/**
* Adds a limit clause to the update query for supported databases, such as MySQL.
*
* ### Examples
*
* Update the first 2 rows in the 'person' table:
*
* ```ts
* await db
* .updateTable('person')
* .set({ first_name: 'Foo' })
* .limit(2)
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* update `person` set `first_name` = ? limit ?
* ```
*/
limit(limit) {
return new _a$4({
...this.#props,
queryNode: UpdateQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit)))
});
}
set(...args) {
return new _a$4({
...this.#props,
queryNode: UpdateQueryNode.cloneWithUpdates(this.#props.queryNode, parseUpdate(...args))
});
}
returning(selection) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(selection))
});
}
returningAll(table) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table))
});
}
output(args) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
});
}
outputAll(table) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
});
}
/**
* This can be used to add any additional SQL to the end of the query.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.updateTable('person')
* .set({ age: 39 })
* .where('first_name', '=', 'John')
* .modifyEnd(sql.raw('-- This is a comment'))
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* update `person`
* set `age` = 39
* where `first_name` = "John" -- This is a comment
* ```
*/
modifyEnd(modifier) {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
});
}
/**
* Clears all `returning` clauses from the query.
*
* ### Examples
*
* ```ts
* db.updateTable('person')
* .returningAll()
* .set({ age: 39 })
* .where('first_name', '=', 'John')
* .clearReturning()
* ```
*
* The generated SQL(PostgreSQL):
*
* ```sql
* update "person" set "age" = 39 where "first_name" = "John"
* ```
*/
clearReturning() {
return new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithoutReturning(this.#props.queryNode)
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*
* If you want to conditionally call a method on `this`, see
* the {@link $if} method.
*
* ### Examples
*
* The next example uses a helper function `log` to log a query:
*
* ```ts
* import type { Compilable } from 'kysely'
* import type { PersonUpdate } from 'type-editor' // imaginary module
*
* function log<T extends Compilable>(qb: T): T {
* console.log(qb.compile())
* return qb
* }
*
* const values = {
* first_name: 'John',
* } satisfies PersonUpdate
*
* db.updateTable('person')
* .set(values)
* .$call(log)
* .execute()
* ```
*/
$call(func) {
return func(this);
}
/**
* Call `func(this)` if `condition` is true.
*
* This method is especially handy with optional selects. Any `returning` or `returningAll`
* method calls add columns as optional fields to the output type when called inside
* the `func` callback. This is because we can't know if those selections were actually
* made before running the code.
*
* You can also call any other methods inside the callback.
*
* ### Examples
*
* ```ts
* import type { PersonUpdate } from 'type-editor' // imaginary module
*
* async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) {
* return await db
* .updateTable('person')
* .set(updates)
* .where('id', '=', id)
* .returning(['id', 'first_name'])
* .$if(returnLastName, (qb) => qb.returning('last_name'))
* .executeTakeFirstOrThrow()
* }
* ```
*
* Any selections added inside the `if` callback will be added as optional fields to the
* output type since we can't know if the selections were actually made before running
* the code. In the example above the return type of the `updatePerson` function is:
*
* ```ts
* Promise<{
* id: number
* first_name: string
* last_name?: string
* }>
* ```
*/
$if(condition, func) {
if (condition) return func(this);
return new _a$4({ ...this.#props });
}
/**
* Change the output type of the query.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of this `UpdateQueryBuilder` with a new output type.
*/
$castTo() {
return new _a$4(this.#props);
}
/**
* Narrows (parts of) the output type of the query.
*
* Kysely tries to be as type-safe as possible, but in some cases we have to make
* compromises for better maintainability and compilation performance. At present,
* Kysely doesn't narrow the output type of the query based on {@link set} input
* when using {@link where} and/or {@link returning} or {@link returningAll}.
*
* This utility method is very useful for these situations, as it removes unncessary
* runtime assertion/guard code. Its input type is limited to the output type
* of the query, so you can't add a column that doesn't exist, or change a column's
* type to something that doesn't exist in its union type.
*
* ### Examples
*
* Turn this code:
*
* ```ts
* import type { Person } from 'type-editor' // imaginary module
*
* const id = 1
* const now = new Date().toISOString()
*
* const person = await db.updateTable('person')
* .set({ deleted_at: now })
* .where('id', '=', id)
* .where('nullable_column', 'is not', null)
* .returningAll()
* .executeTakeFirstOrThrow()
*
* if (isWithNoNullValue(person)) {
* functionThatExpectsPersonWithNonNullValue(person)
* }
*
* function isWithNoNullValue(person: Person): person is Person & { nullable_column: string } {
* return person.nullable_column != null
* }
* ```
*
* Into this:
*
* ```ts
* import type { NotNull } from 'kysely'
*
* const id = 1
* const now = new Date().toISOString()
*
* const person = await db.updateTable('person')
* .set({ deleted_at: now })
* .where('id', '=', id)
* .where('nullable_column', 'is not', null)
* .returningAll()
* .$narrowType<{ deleted_at: Date; nullable_column: NotNull }>()
* .executeTakeFirstOrThrow()
*
* functionThatExpectsPersonWithNonNullValue(person)
* ```
*/
$narrowType() {
return new _a$4(this.#props);
}
/**
* Asserts that query's output row type equals the given type `T`.
*
* This method can be used to simplify excessively complex types to make TypeScript happy
* and much faster.
*
* Kysely uses complex type magic to achieve its type safety. This complexity is sometimes too much
* for TypeScript and you get errors like this:
*
* ```
* error TS2589: Type instantiation is excessively deep and possibly infinite.
* ```
*
* In these case you can often use this method to help TypeScript a little bit. When you use this
* method to assert the output type of a query, Kysely can drop the complex output type that
* consists of multiple nested helper types and replace it with the simple asserted type.
*
* Using this method doesn't reduce type safety at all. You have to pass in a type that is
* structurally equal to the current type.
*
* ### Examples
*
* ```ts
* import type { PersonUpdate, PetUpdate, Species } from 'type-editor' // imaginary module
*
* const person = {
* id: 1,
* gender: 'other',
* } satisfies PersonUpdate
*
* const pet = {
* name: 'Fluffy',
* } satisfies PetUpdate
*
* const result = await db
* .with('updated_person', (qb) => qb
* .updateTable('person')
* .set(person)
* .where('id', '=', person.id)
* .returning('first_name')
* .$assertType<{ first_name: string }>()
* )
* .with('updated_pet', (qb) => qb
* .updateTable('pet')
* .set(pet)
* .where('owner_id', '=', person.id)
* .returning(['name as pet_name', 'species'])
* .$assertType<{ pet_name: string, species: Species }>()
* )
* .selectFrom(['updated_person', 'updated_pet'])
* .selectAll()
* .executeTakeFirstOrThrow()
* ```
*/
$assertType() {
return new _a$4(this.#props);
}
/**
* Returns a copy of this UpdateQueryBuilder instance with the given plugin installed.
*/
withPlugin(plugin) {
return new _a$4({
...this.#props,
executor: this.#props.executor.withPlugin(plugin)
});
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
const compiledQuery = this.compile();
const result = await this.#props.executor.executeQuery(compiledQuery, options);
const { adapter } = this.#props.executor;
const query = compiledQuery.query;
if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) return result.rows;
return [new UpdateResult(result.numAffectedRows ?? BigInt(0), result.numChangedRows)];
}
async executeTakeFirst(options) {
const [result] = await this.execute(options);
return result;
}
async executeTakeFirstOrThrow(errorConstructorOrOptions) {
if (typeof errorConstructorOrOptions === "function") errorConstructorOrOptions = { errorConstructor: errorConstructorOrOptions };
const result = await this.executeTakeFirst(errorConstructorOrOptions);
if (result === void 0) {
const errorConstructor = errorConstructorOrOptions?.errorConstructor ?? NoResultError;
throw isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
}
return result;
}
async *stream(chunkSizeOrOptions) {
if (typeof chunkSizeOrOptions !== "object") chunkSizeOrOptions = { chunkSize: chunkSizeOrOptions };
const compiledQuery = this.compile();
const stream = this.#props.executor.stream(compiledQuery, chunkSizeOrOptions.chunkSize ?? 100, chunkSizeOrOptions);
for await (const item of stream) yield* item.rows;
}
async explain(format, options) {
return await new _a$4({
...this.#props,
queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options)
}).execute();
}
};
_a$4 = UpdateQueryBuilder;
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/common-table-expression-name-node.js
var CommonTableExpressionNameNode;
var init_common_table_expression_name_node = __esmMin((() => {
init_object_utils();
init_column_node();
init_table_node();
CommonTableExpressionNameNode = freeze({
is(node) {
return node.kind === "CommonTableExpressionNameNode";
},
create(tableName, columnNames) {
return freeze({
kind: "CommonTableExpressionNameNode",
table: TableNode.create(tableName),
columns: columnNames ? freeze(columnNames.map(ColumnNode.create)) : void 0
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/common-table-expression-node.js
var CommonTableExpressionNode;
var init_common_table_expression_node = __esmMin((() => {
init_object_utils();
CommonTableExpressionNode = freeze({
is(node) {
return node.kind === "CommonTableExpressionNode";
},
create(name, expression) {
return freeze({
kind: "CommonTableExpressionNode",
name,
expression
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/cte-builder.js
var CTEBuilder;
var init_cte_builder = __esmMin((() => {
init_common_table_expression_node();
init_object_utils();
CTEBuilder = class CTEBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Makes the common table expression materialized.
*/
materialized() {
return new CTEBuilder({
...this.#props,
node: CommonTableExpressionNode.cloneWith(this.#props.node, { materialized: true })
});
}
/**
* Makes the common table expression not materialized.
*/
notMaterialized() {
return new CTEBuilder({
...this.#props,
node: CommonTableExpressionNode.cloneWith(this.#props.node, { materialized: false })
});
}
toOperationNode() {
return this.#props.node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/with-parser.js
function parseCommonTableExpression(nameOrBuilderCallback, expression) {
const expressionNode = isOperationNodeSource(expression) ? expression.toOperationNode() : expression(createQueryCreator()).toOperationNode();
if (isFunction(nameOrBuilderCallback)) return nameOrBuilderCallback(cteBuilderFactory(expressionNode)).toOperationNode();
return CommonTableExpressionNode.create(parseCommonTableExpressionName(nameOrBuilderCallback), expressionNode);
}
function cteBuilderFactory(expressionNode) {
return (name) => {
return new CTEBuilder({ node: CommonTableExpressionNode.create(parseCommonTableExpressionName(name), expressionNode) });
};
}
function parseCommonTableExpressionName(name) {
if (name.includes("(")) {
const parts = name.split(/[\(\)]/);
const table = parts[0];
const columns = parts[1].split(",").map((it) => it.trim());
return CommonTableExpressionNameNode.create(table, columns);
} else return CommonTableExpressionNameNode.create(name);
}
var init_with_parser = __esmMin((() => {
init_common_table_expression_name_node();
init_parse_utils();
init_object_utils();
init_cte_builder();
init_common_table_expression_node();
init_operation_node_source();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/with-node.js
var WithNode;
var init_with_node = __esmMin((() => {
init_object_utils();
WithNode = freeze({
is(node) {
return node.kind === "WithNode";
},
create(expression, params) {
return freeze({
kind: "WithNode",
expressions: freeze([expression]),
...params
});
},
cloneWithExpression(withNode, expression) {
return freeze({
...withNode,
expressions: freeze([...withNode.expressions, expression])
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/random-string.js
function randomString(length) {
let chars = "";
for (let i = 0; i < length; ++i) chars += randomChar();
return chars;
}
function randomChar() {
return CHARS[~~(Math.random() * CHARS.length)];
}
var CHARS;
var init_random_string = __esmMin((() => {
CHARS = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9"
];
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/query-id.js
function createQueryId() {
return new LazyQueryId();
}
var LazyQueryId;
var init_query_id = __esmMin((() => {
init_random_string();
LazyQueryId = class {
#queryId;
get queryId() {
if (this.#queryId === void 0) this.#queryId = randomString(8);
return this.#queryId;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/operation-node-transformer.js
var OperationNodeTransformer;
var init_operation_node_transformer = __esmMin((() => {
init_object_utils();
OperationNodeTransformer = class {
nodeStack = [];
#transformers = freeze({
AliasNode: this.transformAlias.bind(this),
ColumnNode: this.transformColumn.bind(this),
IdentifierNode: this.transformIdentifier.bind(this),
SchemableIdentifierNode: this.transformSchemableIdentifier.bind(this),
RawNode: this.transformRaw.bind(this),
ReferenceNode: this.transformReference.bind(this),
SelectQueryNode: this.transformSelectQuery.bind(this),
SelectionNode: this.transformSelection.bind(this),
TableNode: this.transformTable.bind(this),
FromNode: this.transformFrom.bind(this),
SelectAllNode: this.transformSelectAll.bind(this),
AndNode: this.transformAnd.bind(this),
OrNode: this.transformOr.bind(this),
ValueNode: this.transformValue.bind(this),
ValueListNode: this.transformValueList.bind(this),
PrimitiveValueListNode: this.transformPrimitiveValueList.bind(this),
ParensNode: this.transformParens.bind(this),
JoinNode: this.transformJoin.bind(this),
OperatorNode: this.transformOperator.bind(this),
WhereNode: this.transformWhere.bind(this),
InsertQueryNode: this.transformInsertQuery.bind(this),
DeleteQueryNode: this.transformDeleteQuery.bind(this),
ReturningNode: this.transformReturning.bind(this),
CreateTableNode: this.transformCreateTable.bind(this),
AddColumnNode: this.transformAddColumn.bind(this),
ColumnDefinitionNode: this.transformColumnDefinition.bind(this),
DropTableNode: this.transformDropTable.bind(this),
DataTypeNode: this.transformDataType.bind(this),
OrderByNode: this.transformOrderBy.bind(this),
OrderByItemNode: this.transformOrderByItem.bind(this),
GroupByNode: this.transformGroupBy.bind(this),
GroupByItemNode: this.transformGroupByItem.bind(this),
UpdateQueryNode: this.transformUpdateQuery.bind(this),
ColumnUpdateNode: this.transformColumnUpdate.bind(this),
LimitNode: this.transformLimit.bind(this),
OffsetNode: this.transformOffset.bind(this),
OnConflictNode: this.transformOnConflict.bind(this),
OnDuplicateKeyNode: this.transformOnDuplicateKey.bind(this),
CreateIndexNode: this.transformCreateIndex.bind(this),
DropIndexNode: this.transformDropIndex.bind(this),
ListNode: this.transformList.bind(this),
PrimaryKeyConstraintNode: this.transformPrimaryKeyConstraint.bind(this),
UniqueConstraintNode: this.transformUniqueConstraint.bind(this),
ReferencesNode: this.transformReferences.bind(this),
CheckConstraintNode: this.transformCheckConstraint.bind(this),
WithNode: this.transformWith.bind(this),
CommonTableExpressionNode: this.transformCommonTableExpression.bind(this),
CommonTableExpressionNameNode: this.transformCommonTableExpressionName.bind(this),
HavingNode: this.transformHaving.bind(this),
CreateSchemaNode: this.transformCreateSchema.bind(this),
DropSchemaNode: this.transformDropSchema.bind(this),
AlterTableNode: this.transformAlterTable.bind(this),
DropColumnNode: this.transformDropColumn.bind(this),
RenameColumnNode: this.transformRenameColumn.bind(this),
AlterColumnNode: this.transformAlterColumn.bind(this),
ModifyColumnNode: this.transformModifyColumn.bind(this),
AddConstraintNode: this.transformAddConstraint.bind(this),
DropConstraintNode: this.transformDropConstraint.bind(this),
RenameConstraintNode: this.transformRenameConstraint.bind(this),
ForeignKeyConstraintNode: this.transformForeignKeyConstraint.bind(this),
CreateViewNode: this.transformCreateView.bind(this),
RefreshMaterializedViewNode: this.transformRefreshMaterializedView.bind(this),
DropViewNode: this.transformDropView.bind(this),
GeneratedNode: this.transformGenerated.bind(this),
DefaultValueNode: this.transformDefaultValue.bind(this),
OnNode: this.transformOn.bind(this),
ValuesNode: this.transformValues.bind(this),
SelectModifierNode: this.transformSelectModifier.bind(this),
CreateTypeNode: this.transformCreateType.bind(this),
DropTypeNode: this.transformDropType.bind(this),
ExplainNode: this.transformExplain.bind(this),
DefaultInsertValueNode: this.transformDefaultInsertValue.bind(this),
AggregateFunctionNode: this.transformAggregateFunction.bind(this),
OverNode: this.transformOver.bind(this),
PartitionByNode: this.transformPartitionBy.bind(this),
PartitionByItemNode: this.transformPartitionByItem.bind(this),
SetOperationNode: this.transformSetOperation.bind(this),
BinaryOperationNode: this.transformBinaryOperation.bind(this),
UnaryOperationNode: this.transformUnaryOperation.bind(this),
UsingNode: this.transformUsing.bind(this),
FunctionNode: this.transformFunction.bind(this),
CaseNode: this.transformCase.bind(this),
WhenNode: this.transformWhen.bind(this),
JSONReferenceNode: this.transformJSONReference.bind(this),
JSONPathNode: this.transformJSONPath.bind(this),
JSONPathLegNode: this.transformJSONPathLeg.bind(this),
JSONOperatorChainNode: this.transformJSONOperatorChain.bind(this),
TupleNode: this.transformTuple.bind(this),
MergeQueryNode: this.transformMergeQuery.bind(this),
MatchedNode: this.transformMatched.bind(this),
AddIndexNode: this.transformAddIndex.bind(this),
CastNode: this.transformCast.bind(this),
FetchNode: this.transformFetch.bind(this),
TopNode: this.transformTop.bind(this),
OutputNode: this.transformOutput.bind(this),
OrActionNode: this.transformOrAction.bind(this),
CollateNode: this.transformCollate.bind(this),
AlterTypeNode: this.transformAlterType.bind(this),
AddValueNode: this.transformAddValue.bind(this),
RenameValueNode: this.transformRenameValue.bind(this)
});
transformNode(node, queryId) {
if (!node) return node;
this.nodeStack.push(node);
const out = this.transformNodeImpl(node, queryId);
this.nodeStack.pop();
return freeze(out);
}
transformNodeImpl(node, queryId) {
return this.#transformers[node.kind](node, queryId);
}
transformNodeList(list, queryId) {
if (!list) return list;
return freeze(list.map((node) => this.transformNode(node, queryId)));
}
transformSelectQuery(node, queryId) {
return {
kind: "SelectQueryNode",
from: this.transformNode(node.from, queryId),
selections: this.transformNodeList(node.selections, queryId),
distinctOn: this.transformNodeList(node.distinctOn, queryId),
joins: this.transformNodeList(node.joins, queryId),
groupBy: this.transformNode(node.groupBy, queryId),
orderBy: this.transformNode(node.orderBy, queryId),
where: this.transformNode(node.where, queryId),
frontModifiers: this.transformNodeList(node.frontModifiers, queryId),
endModifiers: this.transformNodeList(node.endModifiers, queryId),
limit: this.transformNode(node.limit, queryId),
offset: this.transformNode(node.offset, queryId),
with: this.transformNode(node.with, queryId),
having: this.transformNode(node.having, queryId),
explain: this.transformNode(node.explain, queryId),
setOperations: this.transformNodeList(node.setOperations, queryId),
fetch: this.transformNode(node.fetch, queryId),
top: this.transformNode(node.top, queryId)
};
}
transformSelection(node, queryId) {
return {
kind: "SelectionNode",
selection: this.transformNode(node.selection, queryId)
};
}
transformColumn(node, queryId) {
return {
kind: "ColumnNode",
column: this.transformNode(node.column, queryId)
};
}
transformAlias(node, queryId) {
return {
kind: "AliasNode",
node: this.transformNode(node.node, queryId),
alias: this.transformNode(node.alias, queryId)
};
}
transformTable(node, queryId) {
return {
kind: "TableNode",
table: this.transformNode(node.table, queryId)
};
}
transformFrom(node, queryId) {
return {
kind: "FromNode",
froms: this.transformNodeList(node.froms, queryId)
};
}
transformReference(node, queryId) {
return {
kind: "ReferenceNode",
column: this.transformNode(node.column, queryId),
table: this.transformNode(node.table, queryId)
};
}
transformAnd(node, queryId) {
return {
kind: "AndNode",
left: this.transformNode(node.left, queryId),
right: this.transformNode(node.right, queryId)
};
}
transformOr(node, queryId) {
return {
kind: "OrNode",
left: this.transformNode(node.left, queryId),
right: this.transformNode(node.right, queryId)
};
}
transformValueList(node, queryId) {
return {
kind: "ValueListNode",
values: this.transformNodeList(node.values, queryId)
};
}
transformParens(node, queryId) {
return {
kind: "ParensNode",
node: this.transformNode(node.node, queryId)
};
}
transformJoin(node, queryId) {
return {
kind: "JoinNode",
joinType: node.joinType,
table: this.transformNode(node.table, queryId),
on: this.transformNode(node.on, queryId)
};
}
transformRaw(node, queryId) {
return {
kind: "RawNode",
sqlFragments: freeze([...node.sqlFragments]),
parameters: this.transformNodeList(node.parameters, queryId)
};
}
transformWhere(node, queryId) {
return {
kind: "WhereNode",
where: this.transformNode(node.where, queryId)
};
}
transformInsertQuery(node, queryId) {
return {
kind: "InsertQueryNode",
into: this.transformNode(node.into, queryId),
columns: this.transformNodeList(node.columns, queryId),
values: this.transformNode(node.values, queryId),
returning: this.transformNode(node.returning, queryId),
onConflict: this.transformNode(node.onConflict, queryId),
onDuplicateKey: this.transformNode(node.onDuplicateKey, queryId),
endModifiers: this.transformNodeList(node.endModifiers, queryId),
with: this.transformNode(node.with, queryId),
orAction: this.transformNode(node.orAction, queryId),
replace: node.replace,
explain: this.transformNode(node.explain, queryId),
defaultValues: node.defaultValues,
top: this.transformNode(node.top, queryId),
output: this.transformNode(node.output, queryId)
};
}
transformValues(node, queryId) {
return {
kind: "ValuesNode",
values: this.transformNodeList(node.values, queryId)
};
}
transformDeleteQuery(node, queryId) {
return {
kind: "DeleteQueryNode",
from: this.transformNode(node.from, queryId),
using: this.transformNode(node.using, queryId),
joins: this.transformNodeList(node.joins, queryId),
where: this.transformNode(node.where, queryId),
returning: this.transformNode(node.returning, queryId),
endModifiers: this.transformNodeList(node.endModifiers, queryId),
with: this.transformNode(node.with, queryId),
orderBy: this.transformNode(node.orderBy, queryId),
limit: this.transformNode(node.limit, queryId),
explain: this.transformNode(node.explain, queryId),
top: this.transformNode(node.top, queryId),
output: this.transformNode(node.output, queryId)
};
}
transformReturning(node, queryId) {
return {
kind: "ReturningNode",
selections: this.transformNodeList(node.selections, queryId)
};
}
transformCreateTable(node, queryId) {
return {
kind: "CreateTableNode",
table: this.transformNode(node.table, queryId),
columns: this.transformNodeList(node.columns, queryId),
constraints: this.transformNodeList(node.constraints, queryId),
indexes: this.transformNodeList(node.indexes, queryId),
temporary: node.temporary,
ifNotExists: node.ifNotExists,
onCommit: node.onCommit,
frontModifiers: this.transformNodeList(node.frontModifiers, queryId),
endModifiers: this.transformNodeList(node.endModifiers, queryId),
selectQuery: this.transformNode(node.selectQuery, queryId)
};
}
transformColumnDefinition(node, queryId) {
return {
kind: "ColumnDefinitionNode",
column: this.transformNode(node.column, queryId),
dataType: this.transformNode(node.dataType, queryId),
references: this.transformNode(node.references, queryId),
primaryKey: node.primaryKey,
autoIncrement: node.autoIncrement,
unique: node.unique,
notNull: node.notNull,
unsigned: node.unsigned,
defaultTo: this.transformNode(node.defaultTo, queryId),
check: this.transformNode(node.check, queryId),
generated: this.transformNode(node.generated, queryId),
frontModifiers: this.transformNodeList(node.frontModifiers, queryId),
endModifiers: this.transformNodeList(node.endModifiers, queryId),
nullsNotDistinct: node.nullsNotDistinct,
identity: node.identity,
ifNotExists: node.ifNotExists
};
}
transformAddColumn(node, queryId) {
return {
kind: "AddColumnNode",
column: this.transformNode(node.column, queryId)
};
}
transformDropTable(node, queryId) {
return {
kind: "DropTableNode",
table: this.transformNode(node.table, queryId),
ifExists: node.ifExists,
cascade: node.cascade,
temporary: node.temporary
};
}
transformOrderBy(node, queryId) {
return {
kind: "OrderByNode",
items: this.transformNodeList(node.items, queryId)
};
}
transformOrderByItem(node, queryId) {
return {
kind: "OrderByItemNode",
orderBy: this.transformNode(node.orderBy, queryId),
direction: this.transformNode(node.direction, queryId),
collation: this.transformNode(node.collation, queryId),
nulls: node.nulls
};
}
transformGroupBy(node, queryId) {
return {
kind: "GroupByNode",
items: this.transformNodeList(node.items, queryId)
};
}
transformGroupByItem(node, queryId) {
return {
kind: "GroupByItemNode",
groupBy: this.transformNode(node.groupBy, queryId)
};
}
transformUpdateQuery(node, queryId) {
return {
kind: "UpdateQueryNode",
table: this.transformNode(node.table, queryId),
from: this.transformNode(node.from, queryId),
joins: this.transformNodeList(node.joins, queryId),
where: this.transformNode(node.where, queryId),
updates: this.transformNodeList(node.updates, queryId),
returning: this.transformNode(node.returning, queryId),
endModifiers: this.transformNodeList(node.endModifiers, queryId),
with: this.transformNode(node.with, queryId),
explain: this.transformNode(node.explain, queryId),
limit: this.transformNode(node.limit, queryId),
top: this.transformNode(node.top, queryId),
output: this.transformNode(node.output, queryId),
orderBy: this.transformNode(node.orderBy, queryId)
};
}
transformColumnUpdate(node, queryId) {
return {
kind: "ColumnUpdateNode",
column: this.transformNode(node.column, queryId),
value: this.transformNode(node.value, queryId)
};
}
transformLimit(node, queryId) {
return {
kind: "LimitNode",
limit: this.transformNode(node.limit, queryId)
};
}
transformOffset(node, queryId) {
return {
kind: "OffsetNode",
offset: this.transformNode(node.offset, queryId)
};
}
transformOnConflict(node, queryId) {
return {
kind: "OnConflictNode",
columns: this.transformNodeList(node.columns, queryId),
constraint: this.transformNode(node.constraint, queryId),
indexExpression: this.transformNode(node.indexExpression, queryId),
indexWhere: this.transformNode(node.indexWhere, queryId),
updates: this.transformNodeList(node.updates, queryId),
updateWhere: this.transformNode(node.updateWhere, queryId),
doNothing: node.doNothing
};
}
transformOnDuplicateKey(node, queryId) {
return {
kind: "OnDuplicateKeyNode",
updates: this.transformNodeList(node.updates, queryId)
};
}
transformCreateIndex(node, queryId) {
return {
kind: "CreateIndexNode",
name: this.transformNode(node.name, queryId),
table: this.transformNode(node.table, queryId),
columns: this.transformNodeList(node.columns, queryId),
unique: node.unique,
using: this.transformNode(node.using, queryId),
ifNotExists: node.ifNotExists,
where: this.transformNode(node.where, queryId),
nullsNotDistinct: node.nullsNotDistinct
};
}
transformList(node, queryId) {
return {
kind: "ListNode",
items: this.transformNodeList(node.items, queryId)
};
}
transformDropIndex(node, queryId) {
return {
kind: "DropIndexNode",
name: this.transformNode(node.name, queryId),
table: this.transformNode(node.table, queryId),
ifExists: node.ifExists,
cascade: node.cascade
};
}
transformPrimaryKeyConstraint(node, queryId) {
return {
kind: "PrimaryKeyConstraintNode",
columns: this.transformNodeList(node.columns, queryId),
name: this.transformNode(node.name, queryId),
deferrable: node.deferrable,
initiallyDeferred: node.initiallyDeferred
};
}
transformUniqueConstraint(node, queryId) {
return {
kind: "UniqueConstraintNode",
columns: this.transformNodeList(node.columns, queryId),
name: this.transformNode(node.name, queryId),
nullsNotDistinct: node.nullsNotDistinct,
deferrable: node.deferrable,
initiallyDeferred: node.initiallyDeferred
};
}
transformForeignKeyConstraint(node, queryId) {
return {
kind: "ForeignKeyConstraintNode",
columns: this.transformNodeList(node.columns, queryId),
references: this.transformNode(node.references, queryId),
name: this.transformNode(node.name, queryId),
onDelete: node.onDelete,
onUpdate: node.onUpdate,
deferrable: node.deferrable,
initiallyDeferred: node.initiallyDeferred
};
}
transformSetOperation(node, queryId) {
return {
kind: "SetOperationNode",
operator: node.operator,
expression: this.transformNode(node.expression, queryId),
all: node.all
};
}
transformReferences(node, queryId) {
return {
kind: "ReferencesNode",
table: this.transformNode(node.table, queryId),
columns: this.transformNodeList(node.columns, queryId),
onDelete: node.onDelete,
onUpdate: node.onUpdate
};
}
transformCheckConstraint(node, queryId) {
return {
kind: "CheckConstraintNode",
expression: this.transformNode(node.expression, queryId),
name: this.transformNode(node.name, queryId)
};
}
transformWith(node, queryId) {
return {
kind: "WithNode",
expressions: this.transformNodeList(node.expressions, queryId),
recursive: node.recursive
};
}
transformCommonTableExpression(node, queryId) {
return {
kind: "CommonTableExpressionNode",
name: this.transformNode(node.name, queryId),
materialized: node.materialized,
expression: this.transformNode(node.expression, queryId)
};
}
transformCommonTableExpressionName(node, queryId) {
return {
kind: "CommonTableExpressionNameNode",
table: this.transformNode(node.table, queryId),
columns: this.transformNodeList(node.columns, queryId)
};
}
transformHaving(node, queryId) {
return {
kind: "HavingNode",
having: this.transformNode(node.having, queryId)
};
}
transformCreateSchema(node, queryId) {
return {
kind: "CreateSchemaNode",
schema: this.transformNode(node.schema, queryId),
ifNotExists: node.ifNotExists
};
}
transformDropSchema(node, queryId) {
return {
kind: "DropSchemaNode",
schema: this.transformNode(node.schema, queryId),
ifExists: node.ifExists,
cascade: node.cascade
};
}
transformAlterTable(node, queryId) {
return {
kind: "AlterTableNode",
table: this.transformNode(node.table, queryId),
renameTo: this.transformNode(node.renameTo, queryId),
setSchema: this.transformNode(node.setSchema, queryId),
columnAlterations: this.transformNodeList(node.columnAlterations, queryId),
addConstraint: this.transformNode(node.addConstraint, queryId),
dropConstraint: this.transformNode(node.dropConstraint, queryId),
renameConstraint: this.transformNode(node.renameConstraint, queryId),
addIndex: this.transformNode(node.addIndex, queryId),
dropIndex: this.transformNode(node.dropIndex, queryId)
};
}
transformDropColumn(node, queryId) {
return {
kind: "DropColumnNode",
column: this.transformNode(node.column, queryId),
ifExists: node.ifExists
};
}
transformRenameColumn(node, queryId) {
return {
kind: "RenameColumnNode",
column: this.transformNode(node.column, queryId),
renameTo: this.transformNode(node.renameTo, queryId)
};
}
transformAlterColumn(node, queryId) {
return {
kind: "AlterColumnNode",
column: this.transformNode(node.column, queryId),
dataType: this.transformNode(node.dataType, queryId),
dataTypeExpression: this.transformNode(node.dataTypeExpression, queryId),
setDefault: this.transformNode(node.setDefault, queryId),
dropDefault: node.dropDefault,
setNotNull: node.setNotNull,
dropNotNull: node.dropNotNull
};
}
transformModifyColumn(node, queryId) {
return {
kind: "ModifyColumnNode",
column: this.transformNode(node.column, queryId)
};
}
transformAddConstraint(node, queryId) {
return {
kind: "AddConstraintNode",
constraint: this.transformNode(node.constraint, queryId)
};
}
transformDropConstraint(node, queryId) {
return {
kind: "DropConstraintNode",
constraintName: this.transformNode(node.constraintName, queryId),
ifExists: node.ifExists,
modifier: node.modifier
};
}
transformRenameConstraint(node, queryId) {
return {
kind: "RenameConstraintNode",
oldName: this.transformNode(node.oldName, queryId),
newName: this.transformNode(node.newName, queryId)
};
}
transformCreateView(node, queryId) {
return {
kind: "CreateViewNode",
name: this.transformNode(node.name, queryId),
temporary: node.temporary,
orReplace: node.orReplace,
ifNotExists: node.ifNotExists,
materialized: node.materialized,
columns: this.transformNodeList(node.columns, queryId),
as: this.transformNode(node.as, queryId)
};
}
transformRefreshMaterializedView(node, queryId) {
return {
kind: "RefreshMaterializedViewNode",
name: this.transformNode(node.name, queryId),
concurrently: node.concurrently,
withNoData: node.withNoData
};
}
transformDropView(node, queryId) {
return {
kind: "DropViewNode",
name: this.transformNode(node.name, queryId),
ifExists: node.ifExists,
materialized: node.materialized,
cascade: node.cascade
};
}
transformGenerated(node, queryId) {
return {
kind: "GeneratedNode",
byDefault: node.byDefault,
always: node.always,
identity: node.identity,
stored: node.stored,
expression: this.transformNode(node.expression, queryId)
};
}
transformDefaultValue(node, queryId) {
return {
kind: "DefaultValueNode",
defaultValue: this.transformNode(node.defaultValue, queryId)
};
}
transformOn(node, queryId) {
return {
kind: "OnNode",
on: this.transformNode(node.on, queryId)
};
}
transformSelectModifier(node, queryId) {
return {
kind: "SelectModifierNode",
modifier: node.modifier,
rawModifier: this.transformNode(node.rawModifier, queryId),
of: this.transformNodeList(node.of, queryId)
};
}
transformCreateType(node, queryId) {
return {
kind: "CreateTypeNode",
name: this.transformNode(node.name, queryId),
enum: this.transformNode(node.enum, queryId)
};
}
transformDropType(node, queryId) {
return {
kind: "DropTypeNode",
name: this.transformNode(node.name, queryId),
additionalNames: this.transformNodeList(node.additionalNames, queryId),
cascade: node.cascade,
ifExists: node.ifExists
};
}
transformExplain(node, queryId) {
return {
kind: "ExplainNode",
format: node.format,
options: this.transformNode(node.options, queryId)
};
}
transformSchemableIdentifier(node, queryId) {
return {
kind: "SchemableIdentifierNode",
schema: this.transformNode(node.schema, queryId),
identifier: this.transformNode(node.identifier, queryId)
};
}
transformAggregateFunction(node, queryId) {
return {
kind: "AggregateFunctionNode",
func: node.func,
aggregated: this.transformNodeList(node.aggregated, queryId),
distinct: node.distinct,
orderBy: this.transformNode(node.orderBy, queryId),
withinGroup: this.transformNode(node.withinGroup, queryId),
filter: this.transformNode(node.filter, queryId),
over: this.transformNode(node.over, queryId)
};
}
transformOver(node, queryId) {
return {
kind: "OverNode",
orderBy: this.transformNode(node.orderBy, queryId),
partitionBy: this.transformNode(node.partitionBy, queryId)
};
}
transformPartitionBy(node, queryId) {
return {
kind: "PartitionByNode",
items: this.transformNodeList(node.items, queryId)
};
}
transformPartitionByItem(node, queryId) {
return {
kind: "PartitionByItemNode",
partitionBy: this.transformNode(node.partitionBy, queryId)
};
}
transformBinaryOperation(node, queryId) {
return {
kind: "BinaryOperationNode",
leftOperand: this.transformNode(node.leftOperand, queryId),
operator: this.transformNode(node.operator, queryId),
rightOperand: this.transformNode(node.rightOperand, queryId)
};
}
transformUnaryOperation(node, queryId) {
return {
kind: "UnaryOperationNode",
operator: this.transformNode(node.operator, queryId),
operand: this.transformNode(node.operand, queryId)
};
}
transformUsing(node, queryId) {
return {
kind: "UsingNode",
tables: this.transformNodeList(node.tables, queryId)
};
}
transformFunction(node, queryId) {
return {
kind: "FunctionNode",
func: node.func,
arguments: this.transformNodeList(node.arguments, queryId)
};
}
transformCase(node, queryId) {
return {
kind: "CaseNode",
value: this.transformNode(node.value, queryId),
when: this.transformNodeList(node.when, queryId),
else: this.transformNode(node.else, queryId),
isStatement: node.isStatement
};
}
transformWhen(node, queryId) {
return {
kind: "WhenNode",
condition: this.transformNode(node.condition, queryId),
result: this.transformNode(node.result, queryId)
};
}
transformJSONReference(node, queryId) {
return {
kind: "JSONReferenceNode",
reference: this.transformNode(node.reference, queryId),
traversal: this.transformNode(node.traversal, queryId)
};
}
transformJSONPath(node, queryId) {
return {
kind: "JSONPathNode",
inOperator: this.transformNode(node.inOperator, queryId),
pathLegs: this.transformNodeList(node.pathLegs, queryId)
};
}
transformJSONPathLeg(node, _queryId) {
return {
kind: "JSONPathLegNode",
type: node.type,
value: node.value
};
}
transformJSONOperatorChain(node, queryId) {
return {
kind: "JSONOperatorChainNode",
operator: this.transformNode(node.operator, queryId),
values: this.transformNodeList(node.values, queryId)
};
}
transformTuple(node, queryId) {
return {
kind: "TupleNode",
values: this.transformNodeList(node.values, queryId)
};
}
transformMergeQuery(node, queryId) {
return {
kind: "MergeQueryNode",
into: this.transformNode(node.into, queryId),
using: this.transformNode(node.using, queryId),
whens: this.transformNodeList(node.whens, queryId),
with: this.transformNode(node.with, queryId),
top: this.transformNode(node.top, queryId),
endModifiers: this.transformNodeList(node.endModifiers, queryId),
output: this.transformNode(node.output, queryId),
returning: this.transformNode(node.returning, queryId)
};
}
transformMatched(node, _queryId) {
return {
kind: "MatchedNode",
not: node.not,
bySource: node.bySource
};
}
transformAddIndex(node, queryId) {
return {
kind: "AddIndexNode",
name: this.transformNode(node.name, queryId),
columns: this.transformNodeList(node.columns, queryId),
unique: node.unique,
using: this.transformNode(node.using, queryId),
ifNotExists: node.ifNotExists
};
}
transformCast(node, queryId) {
return {
kind: "CastNode",
expression: this.transformNode(node.expression, queryId),
dataType: this.transformNode(node.dataType, queryId)
};
}
transformFetch(node, queryId) {
return {
kind: "FetchNode",
rowCount: this.transformNode(node.rowCount, queryId),
modifier: node.modifier
};
}
transformTop(node, _queryId) {
return {
kind: "TopNode",
expression: node.expression,
modifiers: node.modifiers
};
}
transformOutput(node, queryId) {
return {
kind: "OutputNode",
selections: this.transformNodeList(node.selections, queryId)
};
}
transformAlterType(node, queryId) {
return {
kind: "AlterTypeNode",
name: this.transformNode(node.name, queryId),
addValue: this.transformNode(node.addValue, queryId),
renameTo: this.transformNode(node.renameTo, queryId),
renameValue: this.transformNode(node.renameValue, queryId),
setSchema: this.transformNode(node.setSchema, queryId)
};
}
transformAddValue(node, queryId) {
return {
kind: "AddValueNode",
value: this.transformNode(node.value, queryId),
ifNotExists: node.ifNotExists,
isBefore: node.isBefore,
neighborValue: this.transformNode(node.neighborValue, queryId)
};
}
transformRenameValue(node, queryId) {
return {
kind: "RenameValueNode",
oldValue: this.transformNode(node.oldValue, queryId),
newValue: this.transformNode(node.newValue, queryId)
};
}
transformDataType(node, _queryId) {
return node;
}
transformSelectAll(node, _queryId) {
return node;
}
transformIdentifier(node, _queryId) {
return node;
}
transformValue(node, _queryId) {
return node;
}
transformPrimitiveValueList(node, _queryId) {
return node;
}
transformOperator(node, _queryId) {
return node;
}
transformDefaultInsertValue(node, _queryId) {
return node;
}
transformOrAction(node, _queryId) {
return node;
}
transformCollate(node, _queryId) {
return node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/operation-node.js
function isOperationNode(thing) {
return isObject$1(thing) && isString(thing.kind);
}
var init_operation_node = __esmMin((() => {
init_object_utils();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/root-operation-node.js
function isRootOperationNode(thing) {
return isOperationNode(thing) && ROOT_OPERATION_NODE_KINDS[thing.kind] === true;
}
var ROOT_OPERATION_NODE_KINDS;
var init_root_operation_node = __esmMin((() => {
init_operation_node();
ROOT_OPERATION_NODE_KINDS = {
AlterTableNode: true,
AlterTypeNode: true,
CreateIndexNode: true,
CreateSchemaNode: true,
CreateTableNode: true,
CreateTypeNode: true,
CreateViewNode: true,
DeleteQueryNode: true,
DropIndexNode: true,
DropSchemaNode: true,
DropTableNode: true,
DropTypeNode: true,
RefreshMaterializedViewNode: true,
DropViewNode: true,
InsertQueryNode: true,
RawNode: true,
SelectQueryNode: true,
UpdateQueryNode: true,
MergeQueryNode: true
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/with-schema/with-schema-transformer.js
var SCHEMALESS_FUNCTIONS, WithSchemaTransformer;
var init_with_schema_transformer = __esmMin((() => {
init_alias_node();
init_identifier_node();
init_join_node();
init_list_node();
init_operation_node_transformer();
init_root_operation_node();
init_schemable_identifier_node();
init_table_node();
init_using_node();
init_object_utils();
SCHEMALESS_FUNCTIONS = freeze({
json_agg: true,
to_json: true
});
WithSchemaTransformer = class extends OperationNodeTransformer {
#schema;
#schemableIds = /* @__PURE__ */ new Set();
#ctes = /* @__PURE__ */ new Set();
constructor(schema) {
super();
this.#schema = schema;
}
transformNodeImpl(node, queryId) {
if (!isRootOperationNode(node)) return super.transformNodeImpl(node, queryId);
const ctes = this.#collectCTEs(node);
for (const cte of ctes) this.#ctes.add(cte);
const tables = this.#collectSchemableIds(node);
for (const table of tables) this.#schemableIds.add(table);
const transformed = super.transformNodeImpl(node, queryId);
for (const table of tables) this.#schemableIds.delete(table);
for (const cte of ctes) this.#ctes.delete(cte);
return transformed;
}
transformSchemableIdentifier(node, queryId) {
const transformed = super.transformSchemableIdentifier(node, queryId);
if (transformed.schema || !this.#schemableIds.has(node.identifier.name)) return transformed;
return {
...transformed,
schema: IdentifierNode.create(this.#schema)
};
}
transformReferences(node, queryId) {
const transformed = super.transformReferences(node, queryId);
if (transformed.table.table.schema) return transformed;
return {
...transformed,
table: TableNode.createWithSchema(this.#schema, transformed.table.table.identifier.name)
};
}
transformAggregateFunction(node, queryId) {
return {
...super.transformAggregateFunction({
...node,
aggregated: []
}, queryId),
aggregated: this.#transformTableArgsWithoutSchemas(node, queryId, "aggregated")
};
}
transformFunction(node, queryId) {
return {
...super.transformFunction({
...node,
arguments: []
}, queryId),
arguments: this.#transformTableArgsWithoutSchemas(node, queryId, "arguments")
};
}
transformSelectModifier(node, queryId) {
return {
...super.transformSelectModifier({
...node,
of: void 0
}, queryId),
of: node.of?.map((item) => TableNode.is(item) && !item.table.schema ? {
...item,
table: this.transformIdentifier(item.table.identifier, queryId)
} : this.transformNode(item, queryId))
};
}
#transformTableArgsWithoutSchemas(node, queryId, argsKey) {
return SCHEMALESS_FUNCTIONS[node.func] ? node[argsKey].map((arg) => !TableNode.is(arg) || arg.table.schema ? this.transformNode(arg, queryId) : {
...arg,
table: this.transformIdentifier(arg.table.identifier, queryId)
}) : this.transformNodeList(node[argsKey], queryId);
}
#collectSchemableIds(node) {
const schemableIds = /* @__PURE__ */ new Set();
if ("name" in node && node.name && SchemableIdentifierNode.is(node.name)) this.#collectSchemableId(node.name, schemableIds);
if ("from" in node && node.from) for (const from of node.from.froms) this.#collectSchemableIdsFromTableExpr(from, schemableIds);
if ("into" in node && node.into) this.#collectSchemableIdsFromTableExpr(node.into, schemableIds);
if ("table" in node && node.table) this.#collectSchemableIdsFromTableExpr(node.table, schemableIds);
if ("joins" in node && node.joins) for (const join of node.joins) this.#collectSchemableIdsFromTableExpr(join.table, schemableIds);
if ("using" in node && node.using) {
if (JoinNode.is(node.using)) this.#collectSchemableIdsFromTableExpr(node.using.table, schemableIds);
else this.#collectSchemableIdsFromTableExpr(node.using, schemableIds);
}
return schemableIds;
}
#collectCTEs(node) {
const ctes = /* @__PURE__ */ new Set();
if ("with" in node && node.with) this.#collectCTEIds(node.with, ctes);
return ctes;
}
#collectSchemableIdsFromTableExpr(node, schemableIds) {
if (TableNode.is(node)) return this.#collectSchemableId(node.table, schemableIds);
if (AliasNode.is(node) && TableNode.is(node.node)) return this.#collectSchemableId(node.node.table, schemableIds);
if (ListNode.is(node)) {
for (const table of node.items) this.#collectSchemableIdsFromTableExpr(table, schemableIds);
return;
}
if (UsingNode.is(node)) {
for (const table of node.tables) this.#collectSchemableIdsFromTableExpr(table, schemableIds);
return;
}
}
#collectSchemableId(node, schemableIds) {
const id = node.identifier.name;
if (!this.#schemableIds.has(id) && !this.#ctes.has(id)) schemableIds.add(id);
}
#collectCTEIds(node, ctes) {
for (const expr of node.expressions) {
const cteId = expr.name.table.table.identifier.name;
if (!this.#ctes.has(cteId)) ctes.add(cteId);
}
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/with-schema/with-schema-plugin.js
var WithSchemaPlugin;
var init_with_schema_plugin = __esmMin((() => {
init_with_schema_transformer();
WithSchemaPlugin = class {
#transformer;
constructor(schema) {
this.#transformer = new WithSchemaTransformer(schema);
}
transformQuery(args) {
return this.#transformer.transformNode(args.node, args.queryId);
}
async transformResult(args) {
return args.result;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/matched-node.js
var MatchedNode;
var init_matched_node = __esmMin((() => {
init_object_utils();
MatchedNode = freeze({
is(node) {
return node.kind === "MatchedNode";
},
create(not, bySource = false) {
return freeze({
kind: "MatchedNode",
not,
bySource
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/merge-parser.js
function parseMergeWhen(type, args, refRight) {
return WhenNode.create(parseFilterList([MatchedNode.create(!type.isMatched, type.bySource), ...args && args.length > 0 ? [args.length === 3 && refRight ? parseReferentialBinaryOperation(args[0], args[1], args[2]) : parseValueBinaryOperationOrExpression(args)] : []], "and", false));
}
function parseMergeThen(result) {
if (isString(result)) return RawNode.create([result], []);
if (isOperationNodeSource(result)) return result.toOperationNode();
return result;
}
var init_merge_parser = __esmMin((() => {
init_matched_node();
init_operation_node_source();
init_raw_node();
init_when_node();
init_object_utils();
init_binary_operation_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/deferred.js
var Deferred;
var init_deferred = __esmMin((() => {
Deferred = class {
#promise;
#resolve;
#reject;
constructor() {
this.#promise = new Promise((resolve, reject) => {
this.#reject = reject;
this.#resolve = resolve;
});
}
get promise() {
return this.#promise;
}
resolve = (value) => {
this.#resolve?.(value);
this.#resolve = this.#reject = void 0;
};
reject = (reason) => {
this.#reject?.(reason);
this.#reject = this.#resolve = void 0;
};
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/provide-controlled-connection.js
async function provideControlledConnection(connectionProvider, options) {
const connectionDefer = new Deferred();
const connectionReleaseDefer = new Deferred();
connectionProvider.provideConnection(async (connection) => {
connectionDefer.resolve(connection);
return await connectionReleaseDefer.promise;
}, options).catch((ex) => connectionDefer.reject(ex));
return freeze({
connection: await connectionDefer.promise,
release: connectionReleaseDefer.resolve
});
}
var init_provide_controlled_connection = __esmMin((() => {
init_deferred();
init_object_utils();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/abort.js
function getInflightQueryAbortHandler(abortStrategy = "ignore query", connection, beforeThrow) {
if (abortStrategy === "ignore query") return;
if (abortStrategy === "cancel query") {
const handler = connection.cancelQuery;
if (!handler) {
beforeThrow();
throwUnsupportedInflightQueryAbortStrategyError(abortStrategy, connection.killSession ? "kill session" : void 0);
}
return handler.bind(connection);
}
if (abortStrategy === "kill session") {
const handler = connection.killSession;
if (!handler) {
beforeThrow();
throwUnsupportedInflightQueryAbortStrategyError(abortStrategy, connection.cancelQuery ? "cancel query" : void 0);
}
return handler.bind(connection);
}
beforeThrow();
throw new Error(`Unexpected \`inflightQueryAbortStrategy\`: "${abortStrategy}"`);
}
function throwUnsupportedInflightQueryAbortStrategyError(abortStrategy, alt) {
throw new Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${abortStrategy}". Use "ignore query"${alt ? ` or "${alt}"` : ""} instead.`);
}
function assertNotAborted(signal, timing, beforeThrow) {
if (signal?.aborted) {
beforeThrow?.();
throwReasonWithTiming(signal.reason, timing);
}
}
function throwReasonWithTiming(reason, timing) {
decorateWithTiming(reason, timing);
throw reason;
}
async function waitOrAbort(promise, signal, name, onAbort) {
if (!signal) return promise;
assertNotAborted(signal, `before ${name}`, onAbort);
const { promise: abortPromise, resolve } = new Deferred();
const abortListener = () => resolve(ABORTED);
signal.addEventListener("abort", abortListener);
try {
assertNotAborted(signal, `before ${name}`, onAbort);
const result = await Promise.race([promise, abortPromise]);
if (result !== ABORTED) return result;
onAbort?.();
throwReasonWithTiming(signal.reason, `during ${name}`);
} finally {
signal.removeEventListener("abort", abortListener);
resolve(ABORTED);
}
}
function printBackgroundFail(name) {
return (reason) => console.error(`\`${name}\` failed in the background after abortion: ${getMessage(reason)}`);
}
function decorateWithTiming(reason, timing) {
if (reason !== null && typeof reason === "object" && !Object.isFrozen(reason)) Object.defineProperty(reason, "__kysely_timing__", {
configurable: true,
enumerable: false,
value: timing,
writable: false
});
}
var ABORTED;
var init_abort = __esmMin((() => {
init_deferred();
init_object_utils();
ABORTED = {};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-executor/query-executor-base.js
var NO_PLUGINS, QueryExecutorBase;
var init_query_executor_base = __esmMin((() => {
init_object_utils();
init_provide_controlled_connection();
init_abort();
init_deferred();
NO_PLUGINS = freeze([]);
QueryExecutorBase = class {
#plugins;
constructor(plugins = NO_PLUGINS) {
this.#plugins = plugins;
}
get plugins() {
return this.#plugins;
}
transformQuery(node, queryId) {
for (const plugin of this.#plugins) {
const transformedNode = plugin.transformQuery({
node,
queryId
});
if (transformedNode.kind === node.kind) node = transformedNode;
else throw new Error([
`KyselyPlugin.transformQuery must return a node`,
`of the same kind that was given to it.`,
`The plugin was given a ${node.kind}`,
`but it returned a ${transformedNode.kind}`
].join(" "));
}
return node;
}
async executeQuery(compiledQuery, options) {
const { inflightQueryAbortStrategy = "ignore query", signal } = options || {};
if (!signal) {
const result = await this.provideConnection(async (connection) => {
return await connection.executeQuery(compiledQuery);
}, options);
return await this.#transformResult(result, compiledQuery.queryId);
}
assertNotAborted(signal, "before query execution");
options = freeze({ signal });
const { connection, release } = await provideControlledConnection(this, options);
const controlConnectionProvider = this.provideConnection.bind(this);
const { promise: abortPromise, resolve } = new Deferred();
const abortListener = () => resolve(ABORTED);
signal.addEventListener("abort", abortListener, { once: true });
try {
assertNotAborted(signal, "before query execution", release);
const inflightQueryAbortHandler = getInflightQueryAbortHandler(inflightQueryAbortStrategy, connection, release);
if (inflightQueryAbortHandler && connection.collectSessionInfo) {
assertNotAborted(signal, "before query execution", release);
const collectPromise = connection.collectSessionInfo();
if (await Promise.race([abortPromise, collectPromise]).catch((error) => {
release();
throw error;
}) === ABORTED) {
collectPromise.catch(printBackgroundFail("collectSessionInfo")).finally(release);
throwReasonWithTiming(signal.reason, "before query execution");
}
}
const queryPromise = connection.executeQuery(compiledQuery, options);
const result = await Promise.race([abortPromise, queryPromise]).catch((error) => {
release();
throw error;
});
if (result === ABORTED) {
Promise.allSettled([queryPromise.catch(printBackgroundFail("query")), inflightQueryAbortHandler?.(controlConnectionProvider).catch(printBackgroundFail("inflightQueryAbortHandler"))]).finally(release);
throwReasonWithTiming(signal.reason, "during query execution");
} else release();
const transformPromise = this.#transformResult(result, compiledQuery.queryId, options);
const transformedResult = await Promise.race([abortPromise, transformPromise]);
if (transformedResult === ABORTED) {
transformPromise.catch(printBackgroundFail("plugins.transformResult"));
throwReasonWithTiming(signal.reason, "during result transformation");
}
return transformedResult;
} finally {
resolve(ABORTED);
signal.removeEventListener("abort", abortListener);
}
}
async *stream(compiledQuery, chunkSize, options) {
const { signal } = options || {};
if (!signal) {
const { connection, release } = await provideControlledConnection(this);
try {
for await (const result of connection.streamQuery(compiledQuery, chunkSize)) yield await this.#transformResult(result, compiledQuery.queryId, options);
} finally {
release();
}
return;
}
options = freeze({ signal });
assertNotAborted(signal, "before connection acquisition");
const { connection, release } = await provideControlledConnection(this, options);
const { promise: abortPromise, resolve } = new Deferred();
const abortListener = () => resolve(ABORTED);
signal.addEventListener("abort", abortListener, { once: true });
let asyncIterator;
let releasePrerequisite;
assertNotAborted(signal, "before query streaming", release);
const { queryId } = compiledQuery;
try {
asyncIterator = connection.streamQuery(compiledQuery, chunkSize, options);
while (true) {
assertNotAborted(signal, "during query streaming");
const nextPromise = asyncIterator.next();
const result = await Promise.race([abortPromise, nextPromise]);
if (result === ABORTED) {
releasePrerequisite = nextPromise.catch(printBackgroundFail("iterator.next"));
throwReasonWithTiming(signal.reason, "during query streaming");
}
if (result.done) break;
const transformPromise = this.#transformResult(result.value, queryId, options);
const transformedResult = await Promise.race([abortPromise, transformPromise]);
if (transformedResult === ABORTED) {
releasePrerequisite = transformPromise.catch(printBackgroundFail("plugins.transformResult"));
throwReasonWithTiming(signal.reason, "during result transformation");
}
yield transformedResult;
}
} finally {
resolve(ABORTED);
signal.removeEventListener("abort", abortListener);
const cleanup = (asyncIterator?.return?.() || Promise.resolve()).finally(() => releasePrerequisite).finally(release);
if (!releasePrerequisite) await cleanup;
}
}
async #transformResult(result, queryId, options) {
const { signal } = options || {};
for (const plugin of this.#plugins) result = await plugin.transformResult(freeze({
queryId,
result,
signal
}));
return result;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-executor/noop-query-executor.js
var NoopQueryExecutor, NOOP_QUERY_EXECUTOR;
var init_noop_query_executor = __esmMin((() => {
init_query_executor_base();
NoopQueryExecutor = class NoopQueryExecutor extends QueryExecutorBase {
get adapter() {
throw new Error("this query cannot be compiled to SQL");
}
compileQuery() {
throw new Error("this query cannot be compiled to SQL");
}
provideConnection() {
throw new Error("this query cannot be executed");
}
withConnectionProvider() {
throw new Error("this query cannot have a connection provider");
}
withPlugin(plugin) {
return new NoopQueryExecutor([...this.plugins, plugin]);
}
withPlugins(plugins) {
return new NoopQueryExecutor([...this.plugins, ...plugins]);
}
withPluginAtFront(plugin) {
return new NoopQueryExecutor([plugin, ...this.plugins]);
}
withoutPlugins() {
return new NoopQueryExecutor([]);
}
};
NOOP_QUERY_EXECUTOR = new NoopQueryExecutor();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/merge-result.js
var MergeResult;
var init_merge_result = __esmMin((() => {
MergeResult = class {
numChangedRows;
constructor(numChangedRows) {
this.numChangedRows = numChangedRows;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/merge-query-builder.js
var MergeQueryBuilder, WheneableMergeQueryBuilder, MatchedThenableMergeQueryBuilder, NotMatchedThenableMergeQueryBuilder;
var init_merge_query_builder = __esmMin((() => {
init_insert_query_node();
init_merge_query_node();
init_query_node();
init_update_query_node();
init_insert_values_parser();
init_join_parser();
init_merge_parser();
init_select_parser();
init_top_parser();
init_noop_query_executor();
init_object_utils();
init_merge_result();
init_no_result_error();
init_update_query_builder();
MergeQueryBuilder = class MergeQueryBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* This can be used to add any additional SQL to the end of the query.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db
* .mergeInto('person')
* .using('pet', 'pet.owner_id', 'person.id')
* .whenMatched()
* .thenDelete()
* .modifyEnd(sql.raw('-- this is a comment'))
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment
* ```
*/
modifyEnd(modifier) {
return new MergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
});
}
/**
* Changes a `merge into` query to an `merge top into` query.
*
* `top` clause is only supported by some dialects like MS SQL Server.
*
* ### Examples
*
* Affect 5 matched rows at most:
*
* ```ts
* await db.mergeInto('person')
* .top(5)
* .using('pet', 'person.id', 'pet.owner_id')
* .whenMatched()
* .thenDelete()
* .execute()
* ```
*
* The generated SQL (MS SQL Server):
*
* ```sql
* merge top(5) into "person"
* using "pet" on "person"."id" = "pet"."owner_id"
* when matched then
* delete
* ```
*
* Affect 50% of matched rows:
*
* ```ts
* await db.mergeInto('person')
* .top(50, 'percent')
* .using('pet', 'person.id', 'pet.owner_id')
* .whenMatched()
* .thenDelete()
* .execute()
* ```
*
* The generated SQL (MS SQL Server):
*
* ```sql
* merge top(50) percent into "person"
* using "pet" on "person"."id" = "pet"."owner_id"
* when matched then
* delete
* ```
*/
top(expression, modifiers) {
return new MergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
});
}
using(...args) {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: MergeQueryNode.cloneWithUsing(this.#props.queryNode, parseJoin("Using", args))
});
}
returning(args) {
return new MergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args))
});
}
returningAll(table) {
return new MergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table))
});
}
output(args) {
return new MergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
});
}
outputAll(table) {
return new MergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
});
}
};
WheneableMergeQueryBuilder = class WheneableMergeQueryBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* This can be used to add any additional SQL to the end of the query.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db
* .mergeInto('person')
* .using('pet', 'pet.owner_id', 'person.id')
* .whenMatched()
* .thenDelete()
* .modifyEnd(sql.raw('-- this is a comment'))
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person" using "pet" on "pet"."owner_id" = "person"."id" when matched then delete -- this is a comment
* ```
*/
modifyEnd(modifier) {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, modifier.toOperationNode())
});
}
/**
* See {@link MergeQueryBuilder.top}.
*/
top(expression, modifiers) {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
});
}
/**
* Adds a simple `when matched` clause to the query.
*
* For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}.
*
* For a simple `when not matched` clause, see {@link whenNotMatched}.
*
* For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}.
*
* ### Examples
*
* ```ts
* const result = await db.mergeInto('person')
* .using('pet', 'person.id', 'pet.owner_id')
* .whenMatched()
* .thenDelete()
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person"
* using "pet" on "person"."id" = "pet"."owner_id"
* when matched then
* delete
* ```
*/
whenMatched() {
return this.#whenMatched([]);
}
whenMatchedAnd(...args) {
return this.#whenMatched(args);
}
/**
* Adds the `when matched` clause to the query with an `and` condition. But unlike
* {@link whenMatchedAnd}, this method accepts a column reference as the 3rd argument.
*
* This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation
* for that method for more examples.
*/
whenMatchedAndRef(lhs, op, rhs) {
return this.#whenMatched([
lhs,
op,
rhs
], true);
}
#whenMatched(args, refRight) {
return new MatchedThenableMergeQueryBuilder({
...this.#props,
queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({ isMatched: true }, args, refRight))
});
}
/**
* Adds a simple `when not matched` clause to the query.
*
* For a `when not matched` clause with an `and` condition, see {@link whenNotMatchedAnd}.
*
* For a simple `when matched` clause, see {@link whenMatched}.
*
* For a `when matched` clause with an `and` condition, see {@link whenMatchedAnd}.
*
* ### Examples
*
* ```ts
* const result = await db.mergeInto('person')
* .using('pet', 'person.id', 'pet.owner_id')
* .whenNotMatched()
* .thenInsertValues({
* first_name: 'John',
* last_name: 'Doe',
* })
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person"
* using "pet" on "person"."id" = "pet"."owner_id"
* when not matched then
* insert ("first_name", "last_name") values ($1, $2)
* ```
*/
whenNotMatched() {
return this.#whenNotMatched([]);
}
whenNotMatchedAnd(...args) {
return this.#whenNotMatched(args);
}
/**
* Adds the `when not matched` clause to the query with an `and` condition. But unlike
* {@link whenNotMatchedAnd}, this method accepts a column reference as the 3rd argument.
*
* Unlike {@link whenMatchedAndRef}, you cannot reference columns from the target table.
*
* This method is similar to {@link SelectQueryBuilder.whereRef}, so see the documentation
* for that method for more examples.
*/
whenNotMatchedAndRef(lhs, op, rhs) {
return this.#whenNotMatched([
lhs,
op,
rhs
], true);
}
/**
* Adds a simple `when not matched by source` clause to the query.
*
* Supported in MS SQL Server.
*
* Similar to {@link whenNotMatched}, but returns a {@link MatchedThenableMergeQueryBuilder}.
*/
whenNotMatchedBySource() {
return this.#whenNotMatched([], false, true);
}
whenNotMatchedBySourceAnd(...args) {
return this.#whenNotMatched(args, false, true);
}
/**
* Adds the `when not matched by source` clause to the query with an `and` condition.
*
* Similar to {@link whenNotMatchedAndRef}, but you can reference columns from
* the target table, and not from source table and returns a {@link MatchedThenableMergeQueryBuilder}.
*/
whenNotMatchedBySourceAndRef(lhs, op, rhs) {
return this.#whenNotMatched([
lhs,
op,
rhs
], true, true);
}
returning(args) {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectArg(args))
});
}
returningAll(table) {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithReturning(this.#props.queryNode, parseSelectAll(table))
});
}
output(args) {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectArg(args))
});
}
outputAll(table) {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: QueryNode.cloneWithOutput(this.#props.queryNode, parseSelectAll(table))
});
}
#whenNotMatched(args, refRight = false, bySource = false) {
const props = {
...this.#props,
queryNode: MergeQueryNode.cloneWithWhen(this.#props.queryNode, parseMergeWhen({
isMatched: false,
bySource
}, args, refRight))
};
return new (bySource ? MatchedThenableMergeQueryBuilder : NotMatchedThenableMergeQueryBuilder)(props);
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*
* If you want to conditionally call a method on `this`, see
* the {@link $if} method.
*
* ### Examples
*
* The next example uses a helper function `log` to log a query:
*
* ```ts
* import type { Compilable } from 'kysely'
*
* function log<T extends Compilable>(qb: T): T {
* console.log(qb.compile())
* return qb
* }
*
* await db.updateTable('person')
* .set({ first_name: 'John' })
* .$call(log)
* .execute()
* ```
*/
$call(func) {
return func(this);
}
/**
* Call `func(this)` if `condition` is true.
*
* This method is especially handy with optional selects. Any `returning` or `returningAll`
* method calls add columns as optional fields to the output type when called inside
* the `func` callback. This is because we can't know if those selections were actually
* made before running the code.
*
* You can also call any other methods inside the callback.
*
* ### Examples
*
* ```ts
* import type { PersonUpdate } from 'type-editor' // imaginary module
*
* async function updatePerson(id: number, updates: PersonUpdate, returnLastName: boolean) {
* return await db
* .updateTable('person')
* .set(updates)
* .where('id', '=', id)
* .returning(['id', 'first_name'])
* .$if(returnLastName, (qb) => qb.returning('last_name'))
* .executeTakeFirstOrThrow()
* }
* ```
*
* Any selections added inside the `if` callback will be added as optional fields to the
* output type since we can't know if the selections were actually made before running
* the code. In the example above the return type of the `updatePerson` function is:
*
* ```ts
* Promise<{
* id: number
* first_name: string
* last_name?: string
* }>
* ```
*/
$if(condition, func) {
if (condition) return func(this);
return new WheneableMergeQueryBuilder({ ...this.#props });
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
const compiledQuery = this.compile();
const result = await this.#props.executor.executeQuery(compiledQuery, options);
const { adapter } = this.#props.executor;
const query = compiledQuery.query;
if (query.returning && adapter.supportsReturning || query.output && adapter.supportsOutput) return result.rows;
return [new MergeResult(result.numAffectedRows)];
}
async executeTakeFirst(options) {
const [result] = await this.execute(options);
return result;
}
async executeTakeFirstOrThrow(errorConstructorOrOptions) {
if (typeof errorConstructorOrOptions === "function") errorConstructorOrOptions = { errorConstructor: errorConstructorOrOptions };
const result = await this.executeTakeFirst(errorConstructorOrOptions);
if (result === void 0) {
const errorConstructor = errorConstructorOrOptions?.errorConstructor ?? NoResultError;
throw isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
}
return result;
}
};
MatchedThenableMergeQueryBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Performs the `delete` action.
*
* To perform the `do nothing` action, see {@link thenDoNothing}.
*
* To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}.
*
* ### Examples
*
* ```ts
* const result = await db.mergeInto('person')
* .using('pet', 'person.id', 'pet.owner_id')
* .whenMatched()
* .thenDelete()
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person"
* using "pet" on "person"."id" = "pet"."owner_id"
* when matched then
* delete
* ```
*/
thenDelete() {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("delete"))
});
}
/**
* Performs the `do nothing` action.
*
* This is supported in PostgreSQL.
*
* To perform the `delete` action, see {@link thenDelete}.
*
* To perform the `update` action, see {@link thenUpdate} or {@link thenUpdateSet}.
*
* ### Examples
*
* ```ts
* const result = await db.mergeInto('person')
* .using('pet', 'person.id', 'pet.owner_id')
* .whenMatched()
* .thenDoNothing()
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person"
* using "pet" on "person"."id" = "pet"."owner_id"
* when matched then
* do nothing
* ```
*/
thenDoNothing() {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("do nothing"))
});
}
/**
* Perform an `update` operation with a full-fledged {@link UpdateQueryBuilder}.
* This is handy when multiple `set` invocations are needed.
*
* For a shorthand version of this method, see {@link thenUpdateSet}.
*
* To perform the `delete` action, see {@link thenDelete}.
*
* To perform the `do nothing` action, see {@link thenDoNothing}.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* const result = await db.mergeInto('person')
* .using('pet', 'person.id', 'pet.owner_id')
* .whenMatched()
* .thenUpdate((ub) => ub
* .set(sql`metadata['has_pets']`, 'Y')
* .set({
* updated_at: new Date().toISOString(),
* })
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person"
* using "pet" on "person"."id" = "pet"."owner_id"
* when matched then
* update set metadata['has_pets'] = $1, "updated_at" = $2
* ```
*/
thenUpdate(set) {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(set(new UpdateQueryBuilder({
queryId: this.#props.queryId,
executor: NOOP_QUERY_EXECUTOR,
queryNode: UpdateQueryNode.createWithoutTable()
}))))
});
}
thenUpdateSet(...args) {
return this.thenUpdate((ub) => ub.set(...args));
}
};
NotMatchedThenableMergeQueryBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Performs the `do nothing` action.
*
* This is supported in PostgreSQL.
*
* To perform the `insert` action, see {@link thenInsertValues}.
*
* ### Examples
*
* ```ts
* const result = await db.mergeInto('person')
* .using('pet', 'person.id', 'pet.owner_id')
* .whenNotMatched()
* .thenDoNothing()
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person"
* using "pet" on "person"."id" = "pet"."owner_id"
* when not matched then
* do nothing
* ```
*/
thenDoNothing() {
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen("do nothing"))
});
}
thenInsertValues(insert) {
const [columns, values] = parseInsertExpression(insert);
return new WheneableMergeQueryBuilder({
...this.#props,
queryNode: MergeQueryNode.cloneWithThen(this.#props.queryNode, parseMergeThen(InsertQueryNode.cloneWith(InsertQueryNode.createWithoutInto(), {
columns,
values
})))
});
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-creator.js
var QueryCreator;
var init_query_creator = __esmMin((() => {
init_select_query_builder();
init_insert_query_builder();
init_delete_query_builder();
init_update_query_builder();
init_delete_query_node();
init_insert_query_node();
init_select_query_node();
init_update_query_node();
init_table_parser();
init_with_parser();
init_with_node();
init_query_id();
init_with_schema_plugin();
init_object_utils();
init_select_parser();
init_merge_query_builder();
init_merge_query_node();
QueryCreator = class QueryCreator {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Creates a `select` query builder for the given table or tables.
*
* The tables passed to this method are built as the query's `from` clause.
*
* ### Examples
*
* Create a select query for one table:
*
* ```ts
* db.selectFrom('person').selectAll()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select * from "person"
* ```
*
* Create a select query for one table with an alias:
*
* ```ts
* const persons = await db.selectFrom('person as p')
* .select(['p.id', 'first_name'])
* .execute()
*
* console.log(persons[0].id)
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "p"."id", "first_name" from "person" as "p"
* ```
*
* Create a select query from a subquery:
*
* ```ts
* const persons = await db.selectFrom(
* (eb) => eb.selectFrom('person').select('person.id as identifier').as('p')
* )
* .select('p.identifier')
* .execute()
*
* console.log(persons[0].identifier)
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "p"."identifier",
* from (
* select "person"."id" as "identifier" from "person"
* ) as p
* ```
*
* Create a select query from raw sql:
*
* ```ts
* import { sql } from 'kysely'
*
* const items = await db
* .selectFrom(sql<{ one: number }>`(select 1 as one)`.as('q'))
* .select('q.one')
* .execute()
*
* console.log(items[0].one)
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "q"."one",
* from (
* select 1 as one
* ) as q
* ```
*
* When you use the `sql` tag you need to also provide the result type of the
* raw snippet / query so that Kysely can figure out what columns are
* available for the rest of the query.
*
* The `selectFrom` method also accepts an array for multiple tables. All
* the above examples can also be used in an array.
*
* ```ts
* import { sql } from 'kysely'
*
* const items = await db.selectFrom([
* 'person as p',
* db.selectFrom('pet').select('pet.species').as('a'),
* sql<{ one: number }>`(select 1 as one)`.as('q')
* ])
* .select(['p.id', 'a.species', 'q.one'])
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "p".id, "a"."species", "q"."one"
* from
* "person" as "p",
* (select "pet"."species" from "pet") as a,
* (select 1 as one) as "q"
* ```
*/
selectFrom(from) {
return createSelectQueryBuilder({
queryId: createQueryId(),
executor: this.#props.executor,
queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(from), this.#props.withNode)
});
}
selectNoFrom(selection) {
return createSelectQueryBuilder({
queryId: createQueryId(),
executor: this.#props.executor,
queryNode: SelectQueryNode.cloneWithSelections(SelectQueryNode.create(this.#props.withNode), parseSelectArg(selection))
});
}
/**
* Creates an insert query.
*
* The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}
* has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of
* the inserted row if the db returned one.
*
* See the {@link InsertQueryBuilder.values | values} method for more info and examples. Also see
* the {@link ReturningInterface.returning | returning} method for a way to return columns
* on supported databases like PostgreSQL.
*
* ### Examples
*
* ```ts
* const result = await db
* .insertInto('person')
* .values({
* first_name: 'Jennifer',
* last_name: 'Aniston'
* })
* .executeTakeFirst()
*
* console.log(result.insertId)
* ```
*
* Some databases like PostgreSQL support the `returning` method:
*
* ```ts
* const { id } = await db
* .insertInto('person')
* .values({
* first_name: 'Jennifer',
* last_name: 'Aniston'
* })
* .returning('id')
* .executeTakeFirstOrThrow()
* ```
*/
insertInto(table) {
return new InsertQueryBuilder({
queryId: createQueryId(),
executor: this.#props.executor,
queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode)
});
}
/**
* Creates a "replace into" query.
*
* This is only supported by some dialects like MySQL or SQLite.
*
* Similar to MySQL's {@link InsertQueryBuilder.onDuplicateKeyUpdate} that deletes
* and inserts values on collision instead of updating existing rows.
*
* An alias of SQLite's {@link InsertQueryBuilder.orReplace}.
*
* The return value of this query is an instance of {@link InsertResult}. {@link InsertResult}
* has the {@link InsertResult.insertId | insertId} field that holds the auto incremented id of
* the inserted row if the db returned one.
*
* See the {@link InsertQueryBuilder.values | values} method for more info and examples.
*
* ### Examples
*
* ```ts
* const result = await db
* .replaceInto('person')
* .values({
* first_name: 'Jennifer',
* last_name: 'Aniston'
* })
* .executeTakeFirstOrThrow()
*
* console.log(result.insertId)
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* replace into `person` (`first_name`, `last_name`) values (?, ?)
* ```
*/
replaceInto(table) {
return new InsertQueryBuilder({
queryId: createQueryId(),
executor: this.#props.executor,
queryNode: InsertQueryNode.create(parseTable(table), this.#props.withNode, true)
});
}
/**
* Creates a delete query.
*
* See the {@link DeleteQueryBuilder.where} method for examples on how to specify
* a where clause for the delete operation.
*
* The return value of the query is an instance of {@link DeleteResult}.
*
* ### Examples
*
* <!-- siteExample("delete", "Single row", 10) -->
*
* Delete a single row:
*
* ```ts
* const result = await db
* .deleteFrom('person')
* .where('person.id', '=', 1)
* .executeTakeFirst()
*
* console.log(result.numDeletedRows)
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* delete from "person" where "person"."id" = $1
* ```
*
* Some databases such as MySQL support deleting from multiple tables:
*
* ```ts
* const result = await db
* .deleteFrom(['person', 'pet'])
* .using('person')
* .innerJoin('pet', 'pet.owner_id', 'person.id')
* .where('person.id', '=', 1)
* .executeTakeFirst()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* delete from `person`, `pet`
* using `person`
* inner join `pet` on `pet`.`owner_id` = `person`.`id`
* where `person`.`id` = ?
* ```
*/
deleteFrom(from) {
return new DeleteQueryBuilder({
queryId: createQueryId(),
executor: this.#props.executor,
queryNode: DeleteQueryNode.create(parseTableExpressionOrList(from), this.#props.withNode)
});
}
/**
* Creates an update query.
*
* See the {@link UpdateQueryBuilder.where} method for examples on how to specify
* a where clause for the update operation.
*
* See the {@link UpdateQueryBuilder.set} method for examples on how to
* specify the updates.
*
* The return value of the query is an {@link UpdateResult}.
*
* ### Examples
*
* ```ts
* const result = await db
* .updateTable('person')
* .set({ first_name: 'Jennifer' })
* .where('person.id', '=', 1)
* .executeTakeFirst()
*
* console.log(result.numUpdatedRows)
* ```
*/
updateTable(tables) {
return new UpdateQueryBuilder({
queryId: createQueryId(),
executor: this.#props.executor,
queryNode: UpdateQueryNode.create(parseTableExpressionOrList(tables), this.#props.withNode)
});
}
/**
* Creates a merge query.
*
* The return value of the query is a {@link MergeResult}.
*
* See the {@link MergeQueryBuilder.using} method for examples on how to specify
* the other table.
*
* ### Examples
*
* <!-- siteExample("merge", "Source row existence", 10) -->
*
* Update a target column based on the existence of a source row:
*
* ```ts
* const result = await db
* .mergeInto('person as target')
* .using('pet as source', 'source.owner_id', 'target.id')
* .whenMatchedAnd('target.has_pets', '!=', 'Y')
* .thenUpdateSet({ has_pets: 'Y' })
* .whenNotMatchedBySourceAnd('target.has_pets', '=', 'Y')
* .thenUpdateSet({ has_pets: 'N' })
* .executeTakeFirstOrThrow()
*
* console.log(result.numChangedRows)
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "person"
* using "pet"
* on "pet"."owner_id" = "person"."id"
* when matched and "has_pets" != $1
* then update set "has_pets" = $2
* when not matched by source and "has_pets" = $3
* then update set "has_pets" = $4
* ```
*
* <!-- siteExample("merge", "Temporary changes table", 20) -->
*
* Merge new entries from a temporary changes table:
*
* ```ts
* const result = await db
* .mergeInto('wine as target')
* .using(
* 'wine_stock_change as source',
* 'source.wine_name',
* 'target.name',
* )
* .whenNotMatchedAnd('source.stock_delta', '>', 0)
* .thenInsertValues(({ ref }) => ({
* name: ref('source.wine_name'),
* stock: ref('source.stock_delta'),
* }))
* .whenMatchedAnd(
* (eb) => eb('target.stock', '+', eb.ref('source.stock_delta')),
* '>',
* 0,
* )
* .thenUpdateSet('stock', (eb) =>
* eb('target.stock', '+', eb.ref('source.stock_delta')),
* )
* .whenMatched()
* .thenDelete()
* .executeTakeFirstOrThrow()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* merge into "wine" as "target"
* using "wine_stock_change" as "source"
* on "source"."wine_name" = "target"."name"
* when not matched and "source"."stock_delta" > $1
* then insert ("name", "stock") values ("source"."wine_name", "source"."stock_delta")
* when matched and "target"."stock" + "source"."stock_delta" > $2
* then update set "stock" = "target"."stock" + "source"."stock_delta"
* when matched
* then delete
* ```
*/
mergeInto(targetTable) {
return new MergeQueryBuilder({
queryId: createQueryId(),
executor: this.#props.executor,
queryNode: MergeQueryNode.create(parseAliasedTable(targetTable), this.#props.withNode)
});
}
/**
* Creates a `with` query (Common Table Expression).
*
* ### Examples
*
* <!-- siteExample("cte", "Simple selects", 10) -->
*
* Common table expressions (CTE) are a great way to modularize complex queries.
* Essentially they allow you to run multiple separate queries within a
* single roundtrip to the DB.
*
* Since CTEs are a part of the main query, query optimizers inside DB
* engines are able to optimize the overall query. For example, postgres
* is able to inline the CTEs inside the using queries if it decides it's
* faster.
*
* ```ts
* const result = await db
* // Create a CTE called `jennifers` that selects all
* // persons named 'Jennifer'.
* .with(
* 'jennifers',
* db
* .selectFrom('person')
* .where('first_name', '=', 'Jennifer')
* .select(['id', 'age']),
* )
* // Select all rows from the `jennifers` CTE and
* // further filter it.
* // To refer to a CTE in another CTE, use the callback variant of `with`.
* .with('adult_jennifers', (db) =>
* db.selectFrom('jennifers').where('age', '>', 18).select(['id', 'age']),
* )
* // Finally select all adult jennifers that are
* // also younger than 60.
* .selectFrom('adult_jennifers')
* .where('age', '<', 60)
* .selectAll()
* .execute()
* ```
*
* <!-- siteExample("cte", "Inserts, updates and deletions", 20) -->
*
* Some databases like postgres also allow you to run other queries than selects
* in CTEs. On these databases CTEs are extremely powerful:
*
* ```ts
* const result = await db
* .with('new_person', (db) => db
* .insertInto('person')
* .values({
* first_name: 'Jennifer',
* age: 35,
* })
* .returning('id')
* )
* .with('new_pet', (db) => db
* .insertInto('pet')
* .values({
* name: 'Doggo',
* species: 'dog',
* is_favorite: true,
* // Use the id of the person we just inserted.
* owner_id: db
* .selectFrom('new_person')
* .select('id')
* })
* .returning('id')
* )
* .selectFrom(['new_person', 'new_pet'])
* .select([
* 'new_person.id as person_id',
* 'new_pet.id as pet_id'
* ])
* .execute()
* ```
*
* The CTE name can optionally specify column names in addition to
* a name. In that case Kysely requires the expression to retun
* rows with the same columns.
*
* ```ts
* await db
* .with('jennifers(id, age)', (db) => db
* .selectFrom('person')
* .where('first_name', '=', 'Jennifer')
* // This is ok since we return columns with the same
* // names as specified by `jennifers(id, age)`.
* .select(['id', 'age'])
* )
* .selectFrom('jennifers')
* .selectAll()
* .execute()
* ```
*
* The first argument can also be a callback. The callback is passed
* a `CTEBuilder` instance that can be used to configure the CTE:
*
* ```ts
* await db
* .with(
* (cte) => cte('jennifers').materialized(),
* (db) => db
* .selectFrom('person')
* .where('first_name', '=', 'Jennifer')
* .select(['id', 'age'])
* )
* .selectFrom('jennifers')
* .selectAll()
* .execute()
* ```
*/
with(nameOrBuilder, expression) {
const cte = parseCommonTableExpression(nameOrBuilder, expression);
return new QueryCreator({
...this.#props,
withNode: this.#props.withNode ? WithNode.cloneWithExpression(this.#props.withNode, cte) : WithNode.create(cte)
});
}
/**
* Creates a recursive `with` query (Common Table Expression).
*
* Note that recursiveness is a property of the whole `with` statement.
* You cannot have recursive and non-recursive CTEs in a same `with` statement.
* Therefore the recursiveness is determined by the **first** `with` or
* `withRecusive` call you make.
*
* See the {@link with} method for examples and more documentation.
*/
withRecursive(nameOrBuilder, expression) {
const cte = parseCommonTableExpression(nameOrBuilder, expression);
return new QueryCreator({
...this.#props,
withNode: this.#props.withNode ? WithNode.cloneWithExpression(this.#props.withNode, cte) : WithNode.create(cte, { recursive: true })
});
}
/**
* Returns a copy of this query creator instance with the given plugin installed.
*/
withPlugin(plugin) {
return new QueryCreator({
...this.#props,
executor: this.#props.executor.withPlugin(plugin)
});
}
/**
* Returns a copy of this query creator instance without any plugins.
*/
withoutPlugins() {
return new QueryCreator({
...this.#props,
executor: this.#props.executor.withoutPlugins()
});
}
/**
* Sets the schema to be used for all table references that don't explicitly
* specify a schema.
*
* This only affects the query created through the builder returned from
* this method and doesn't modify the `db` instance.
*
* See [this recipe](https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0007-schemas.md)
* for a more detailed explanation.
*
* ### Examples
*
* ```
* await db
* .withSchema('mammals')
* .selectFrom('pet')
* .selectAll()
* .innerJoin('public.person', 'public.person.id', 'pet.owner_id')
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select * from "mammals"."pet"
* inner join "public"."person"
* on "public"."person"."id" = "mammals"."pet"."owner_id"
* ```
*
* `withSchema` is smart enough to not add schema for aliases,
* common table expressions or other places where the schema
* doesn't belong to:
*
* ```
* await db
* .withSchema('mammals')
* .selectFrom('pet as p')
* .select('p.name')
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "p"."name" from "mammals"."pet" as "p"
* ```
*/
withSchema(schema) {
return new QueryCreator({
...this.#props,
executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema))
});
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/parse-utils.js
function createQueryCreator() {
return new QueryCreator({ executor: NOOP_QUERY_EXECUTOR });
}
function createJoinBuilder(joinType, table) {
return new JoinBuilder({ joinNode: JoinNode.create(joinType, parseTableExpression(table)) });
}
function createOverBuilder() {
return new OverBuilder({ overNode: OverNode.create() });
}
var init_parse_utils = __esmMin((() => {
init_join_node();
init_over_node();
init_join_builder();
init_over_builder();
init_query_creator();
init_noop_query_executor();
init_table_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/join-parser.js
function parseJoin(joinType, args) {
if (args.length === 3) return parseSingleOnJoin(joinType, args[0], args[1], args[2]);
else if (args.length === 2) return parseCallbackJoin(joinType, args[0], args[1]);
else if (args.length === 1) return parseOnlessJoin(joinType, args[0]);
else throw new Error("not implemented");
}
function parseCallbackJoin(joinType, from, callback) {
return callback(createJoinBuilder(joinType, from)).toOperationNode();
}
function parseSingleOnJoin(joinType, from, lhsColumn, rhsColumn) {
return JoinNode.createWithOn(joinType, parseTableExpression(from), parseReferentialBinaryOperation(lhsColumn, "=", rhsColumn));
}
function parseOnlessJoin(joinType, from) {
return JoinNode.create(joinType, parseTableExpression(from));
}
var init_join_parser = __esmMin((() => {
init_join_node();
init_binary_operation_parser();
init_parse_utils();
init_table_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/offset-node.js
var OffsetNode;
var init_offset_node = __esmMin((() => {
init_object_utils();
OffsetNode = freeze({
is(node) {
return node.kind === "OffsetNode";
},
create(offset) {
return freeze({
kind: "OffsetNode",
offset
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/group-by-item-node.js
var GroupByItemNode;
var init_group_by_item_node = __esmMin((() => {
init_object_utils();
GroupByItemNode = freeze({
is(node) {
return node.kind === "GroupByItemNode";
},
create(groupBy) {
return freeze({
kind: "GroupByItemNode",
groupBy
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/group-by-parser.js
function parseGroupBy(groupBy) {
groupBy = isFunction(groupBy) ? groupBy(expressionBuilder()) : groupBy;
return parseReferenceExpressionOrList(groupBy).map(GroupByItemNode.create);
}
var init_group_by_parser = __esmMin((() => {
init_group_by_item_node();
init_expression_builder();
init_object_utils();
init_reference_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/set-operation-node.js
var SetOperationNode;
var init_set_operation_node = __esmMin((() => {
init_object_utils();
SetOperationNode = freeze({
is(node) {
return node.kind === "SetOperationNode";
},
create(operator, expression, all) {
return freeze({
kind: "SetOperationNode",
operator,
expression,
all
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/set-operation-parser.js
function parseSetOperations(operator, expression, all) {
if (isFunction(expression)) expression = expression(createExpressionBuilder());
if (!isReadonlyArray(expression)) expression = [expression];
return expression.map((expr) => SetOperationNode.create(operator, parseExpression(expr), all));
}
var init_set_operation_parser = __esmMin((() => {
init_expression_builder();
init_set_operation_node();
init_object_utils();
init_expression_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/expression/expression-wrapper.js
var ExpressionWrapper, AliasedExpressionWrapper, OrWrapper, AndWrapper;
var init_expression_wrapper = __esmMin((() => {
init_alias_node();
init_and_node();
init_identifier_node();
init_operation_node_source();
init_or_node();
init_parens_node();
init_binary_operation_parser();
ExpressionWrapper = class ExpressionWrapper {
#node;
constructor(node) {
this.#node = node;
}
/** @private */
get expressionType() {}
as(alias) {
return new AliasedExpressionWrapper(this, alias);
}
or(...args) {
return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));
}
and(...args) {
return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));
}
/**
* Change the output type of the expression.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of this `ExpressionWrapper` with a new output type.
*/
$castTo() {
return new ExpressionWrapper(this.#node);
}
/**
* Omit null from the expression's type.
*
* This function can be useful in cases where you know an expression can't be
* null, but Kysely is unable to infer it.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of `this` with a new output type.
*/
$notNull() {
return new ExpressionWrapper(this.#node);
}
toOperationNode() {
return this.#node;
}
};
AliasedExpressionWrapper = class {
#expr;
#alias;
constructor(expr, alias) {
this.#expr = expr;
this.#alias = alias;
}
/** @private */
get expression() {
return this.#expr;
}
/** @private */
get alias() {
return this.#alias;
}
toOperationNode() {
return AliasNode.create(this.#expr.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias));
}
};
OrWrapper = class OrWrapper {
#node;
constructor(node) {
this.#node = node;
}
/** @private */
get expressionType() {}
as(alias) {
return new AliasedExpressionWrapper(this, alias);
}
or(...args) {
return new OrWrapper(OrNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));
}
/**
* Change the output type of the expression.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of this `OrWrapper` with a new output type.
*/
$castTo() {
return new OrWrapper(this.#node);
}
toOperationNode() {
return ParensNode.create(this.#node);
}
};
AndWrapper = class AndWrapper {
#node;
constructor(node) {
this.#node = node;
}
/** @private */
get expressionType() {}
as(alias) {
return new AliasedExpressionWrapper(this, alias);
}
and(...args) {
return new AndWrapper(AndNode.create(this.#node, parseValueBinaryOperationOrExpression(args)));
}
/**
* Change the output type of the expression.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of this `AndWrapper` with a new output type.
*/
$castTo() {
return new AndWrapper(this.#node);
}
toOperationNode() {
return ParensNode.create(this.#node);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/fetch-node.js
var FetchNode;
var init_fetch_node = __esmMin((() => {
init_object_utils();
init_value_node();
FetchNode = freeze({
is(node) {
return node.kind === "FetchNode";
},
create(rowCount, modifier) {
return {
kind: "FetchNode",
rowCount: ValueNode.create(rowCount),
modifier
};
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/fetch-parser.js
function parseFetch(rowCount, modifier) {
if (!isNumber(rowCount) && !isBigInt(rowCount)) throw new Error(`Invalid fetch row count: ${rowCount}`);
if (!isFetchModifier(modifier)) throw new Error(`Invalid fetch modifier: ${modifier}`);
return FetchNode.create(rowCount, modifier);
}
function isFetchModifier(value) {
return value === "only" || value === "with ties";
}
var init_fetch_parser = __esmMin((() => {
init_fetch_node();
init_object_utils();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/select-query-builder.js
function createSelectQueryBuilder(props) {
return new SelectQueryBuilderImpl(props);
}
var _a$3, SelectQueryBuilderImpl, AliasedSelectQueryBuilderImpl;
var init_select_query_builder = __esmMin((() => {
init_alias_node();
init_select_modifier_node();
init_join_parser();
init_table_parser();
init_select_parser();
init_reference_parser();
init_select_query_node();
init_query_node();
init_order_by_parser();
init_limit_node();
init_offset_node();
init_object_utils();
init_group_by_parser();
init_no_result_error();
init_identifier_node();
init_set_operation_parser();
init_binary_operation_parser();
init_expression_wrapper();
init_value_parser();
init_fetch_parser();
init_top_parser();
SelectQueryBuilderImpl = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
get expressionType() {}
get isSelectQueryBuilder() {
return true;
}
where(...args) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseValueBinaryOperationOrExpression(args))
});
}
whereRef(lhs, op, rhs) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithWhere(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs))
});
}
having(...args) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseValueBinaryOperationOrExpression(args))
});
}
havingRef(lhs, op, rhs) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithHaving(this.#props.queryNode, parseReferentialBinaryOperation(lhs, op, rhs))
});
}
select(selection) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectArg(selection))
});
}
distinctOn(selection) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithDistinctOn(this.#props.queryNode, parseReferenceExpressionOrList(selection))
});
}
modifyFront(modifier) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode()))
});
}
modifyEnd(modifier) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.createWithExpression(modifier.toOperationNode()))
});
}
distinct() {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithFrontModifier(this.#props.queryNode, SelectModifierNode.create("Distinct"))
});
}
forUpdate(of) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForUpdate", of ? asArray(of).map(parseTable) : void 0))
});
}
forShare(of) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForShare", of ? asArray(of).map(parseTable) : void 0))
});
}
forKeyShare(of) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForKeyShare", of ? asArray(of).map(parseTable) : void 0))
});
}
forNoKeyUpdate(of) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("ForNoKeyUpdate", of ? asArray(of).map(parseTable) : void 0))
});
}
skipLocked() {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("SkipLocked"))
});
}
noWait() {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithEndModifier(this.#props.queryNode, SelectModifierNode.create("NoWait"))
});
}
selectAll(table) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithSelections(this.#props.queryNode, parseSelectAll(table))
});
}
innerJoin(...args) {
return this.#join("InnerJoin", args);
}
leftJoin(...args) {
return this.#join("LeftJoin", args);
}
rightJoin(...args) {
return this.#join("RightJoin", args);
}
fullJoin(...args) {
return this.#join("FullJoin", args);
}
crossJoin(...args) {
return this.#join("CrossJoin", args);
}
innerJoinLateral(...args) {
return this.#join("LateralInnerJoin", args);
}
leftJoinLateral(...args) {
return this.#join("LateralLeftJoin", args);
}
crossJoinLateral(...args) {
return this.#join("LateralCrossJoin", args);
}
crossApply(...args) {
return this.#join("CrossApply", args);
}
outerApply(...args) {
return this.#join("OuterApply", args);
}
#join(joinType, args) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithJoin(this.#props.queryNode, parseJoin(joinType, args))
});
}
orderBy(...args) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithOrderByItems(this.#props.queryNode, parseOrderBy(args))
});
}
groupBy(groupBy) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithGroupByItems(this.#props.queryNode, parseGroupBy(groupBy))
});
}
limit(limit) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithLimit(this.#props.queryNode, LimitNode.create(parseValueExpression(limit)))
});
}
offset(offset) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithOffset(this.#props.queryNode, OffsetNode.create(parseValueExpression(offset)))
});
}
fetch(rowCount, modifier = "only") {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithFetch(this.#props.queryNode, parseFetch(rowCount, modifier))
});
}
top(expression, modifiers) {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithTop(this.#props.queryNode, parseTop(expression, modifiers))
});
}
union(expression) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("union", expression, false))
});
}
unionAll(expression) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("union", expression, true))
});
}
intersect(expression) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("intersect", expression, false))
});
}
intersectAll(expression) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("intersect", expression, true))
});
}
except(expression) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("except", expression, false))
});
}
exceptAll(expression) {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithSetOperations(this.#props.queryNode, parseSetOperations("except", expression, true))
});
}
as(alias) {
return new AliasedSelectQueryBuilderImpl(this, alias);
}
clearSelect() {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithoutSelections(this.#props.queryNode)
});
}
clearWhere() {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithoutWhere(this.#props.queryNode)
});
}
clearLimit() {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithoutLimit(this.#props.queryNode)
});
}
clearOffset() {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithoutOffset(this.#props.queryNode)
});
}
clearOrderBy() {
return new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithoutOrderBy(this.#props.queryNode)
});
}
clearGroupBy() {
return new _a$3({
...this.#props,
queryNode: SelectQueryNode.cloneWithoutGroupBy(this.#props.queryNode)
});
}
$call(func) {
return func(this);
}
$if(condition, func) {
if (condition) return func(this);
return new _a$3({ ...this.#props });
}
$castTo() {
return new _a$3(this.#props);
}
$narrowType() {
return new _a$3(this.#props);
}
$assertType() {
return new _a$3(this.#props);
}
$asTuple() {
return new ExpressionWrapper(this.toOperationNode());
}
$asScalar() {
return new ExpressionWrapper(this.toOperationNode());
}
withPlugin(plugin) {
return new _a$3({
...this.#props,
executor: this.#props.executor.withPlugin(plugin)
});
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.queryNode, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
const compiledQuery = this.compile();
return (await this.#props.executor.executeQuery(compiledQuery, options)).rows;
}
async executeTakeFirst(options) {
const [result] = await this.execute(options);
return result;
}
async executeTakeFirstOrThrow(errorConstructorOrOptions) {
if (typeof errorConstructorOrOptions === "function") errorConstructorOrOptions = { errorConstructor: errorConstructorOrOptions };
const result = await this.executeTakeFirst(errorConstructorOrOptions);
if (result === void 0) {
const errorConstructor = errorConstructorOrOptions?.errorConstructor ?? NoResultError;
throw isNoResultErrorConstructor(errorConstructor) ? new errorConstructor(this.toOperationNode()) : errorConstructor(this.toOperationNode());
}
return result;
}
async *stream(chunkSizeOrOptions) {
if (typeof chunkSizeOrOptions !== "object") chunkSizeOrOptions = { chunkSize: chunkSizeOrOptions };
const compiledQuery = this.compile();
const stream = this.#props.executor.stream(compiledQuery, chunkSizeOrOptions.chunkSize ?? 100, chunkSizeOrOptions);
for await (const item of stream) yield* item.rows;
}
async explain(format, options) {
return await new _a$3({
...this.#props,
queryNode: QueryNode.cloneWithExplain(this.#props.queryNode, format, options)
}).execute();
}
};
_a$3 = SelectQueryBuilderImpl;
AliasedSelectQueryBuilderImpl = class {
#queryBuilder;
#alias;
constructor(queryBuilder, alias) {
this.#queryBuilder = queryBuilder;
this.#alias = alias;
}
get expression() {
return this.#queryBuilder;
}
get alias() {
return this.#alias;
}
get isAliasedSelectQueryBuilder() {
return true;
}
toOperationNode() {
return AliasNode.create(this.#queryBuilder.toOperationNode(), IdentifierNode.create(this.#alias));
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/aggregate-function-node.js
var AggregateFunctionNode;
var init_aggregate_function_node = __esmMin((() => {
init_object_utils();
init_where_node();
init_order_by_node();
AggregateFunctionNode = freeze({
is(node) {
return node.kind === "AggregateFunctionNode";
},
create(aggregateFunction, aggregated = []) {
return freeze({
kind: "AggregateFunctionNode",
func: aggregateFunction,
aggregated
});
},
cloneWithDistinct(aggregateFunctionNode) {
return freeze({
...aggregateFunctionNode,
distinct: true
});
},
cloneWithOrderBy(aggregateFunctionNode, orderItems, withinGroup = false) {
const prop = withinGroup ? "withinGroup" : "orderBy";
return freeze({
...aggregateFunctionNode,
[prop]: aggregateFunctionNode[prop] ? OrderByNode.cloneWithItems(aggregateFunctionNode[prop], orderItems) : OrderByNode.create(orderItems)
});
},
cloneWithFilter(aggregateFunctionNode, filter) {
return freeze({
...aggregateFunctionNode,
filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "And", filter) : WhereNode.create(filter)
});
},
cloneWithOrFilter(aggregateFunctionNode, filter) {
return freeze({
...aggregateFunctionNode,
filter: aggregateFunctionNode.filter ? WhereNode.cloneWithOperation(aggregateFunctionNode.filter, "Or", filter) : WhereNode.create(filter)
});
},
cloneWithOver(aggregateFunctionNode, over) {
return freeze({
...aggregateFunctionNode,
over
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/function-node.js
var FunctionNode;
var init_function_node = __esmMin((() => {
init_object_utils();
FunctionNode = freeze({
is(node) {
return node.kind === "FunctionNode";
},
create(func, args) {
return freeze({
kind: "FunctionNode",
func,
arguments: args
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/aggregate-function-builder.js
var AggregateFunctionBuilder, AliasedAggregateFunctionBuilder;
var init_aggregate_function_builder = __esmMin((() => {
init_object_utils();
init_aggregate_function_node();
init_alias_node();
init_identifier_node();
init_parse_utils();
init_binary_operation_parser();
init_order_by_parser();
init_query_node();
AggregateFunctionBuilder = class AggregateFunctionBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/** @private */
get expressionType() {}
/**
* Returns an aliased version of the function.
*
* In addition to slapping `as "the_alias"` to the end of the SQL,
* this method also provides strict typing:
*
* ```ts
* const result = await db
* .selectFrom('person')
* .select(
* (eb) => eb.fn.count<number>('id').as('person_count')
* )
* .executeTakeFirstOrThrow()
*
* // `person_count: number` field exists in the result type.
* console.log(result.person_count)
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select count("id") as "person_count"
* from "person"
* ```
*/
as(alias) {
return new AliasedAggregateFunctionBuilder(this, alias);
}
/**
* Adds a `distinct` clause inside the function.
*
* ### Examples
*
* ```ts
* const result = await db
* .selectFrom('person')
* .select((eb) =>
* eb.fn.count<number>('first_name').distinct().as('first_name_count')
* )
* .executeTakeFirstOrThrow()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select count(distinct "first_name") as "first_name_count"
* from "person"
* ```
*/
distinct() {
return new AggregateFunctionBuilder({
...this.#props,
aggregateFunctionNode: AggregateFunctionNode.cloneWithDistinct(this.#props.aggregateFunctionNode)
});
}
orderBy(...args) {
return new AggregateFunctionBuilder({
...this.#props,
aggregateFunctionNode: QueryNode.cloneWithOrderByItems(this.#props.aggregateFunctionNode, parseOrderBy(args))
});
}
clearOrderBy() {
return new AggregateFunctionBuilder({
...this.#props,
aggregateFunctionNode: QueryNode.cloneWithoutOrderBy(this.#props.aggregateFunctionNode)
});
}
withinGroupOrderBy(...args) {
return new AggregateFunctionBuilder({
...this.#props,
aggregateFunctionNode: AggregateFunctionNode.cloneWithOrderBy(this.#props.aggregateFunctionNode, parseOrderBy(args), true)
});
}
filterWhere(...args) {
return new AggregateFunctionBuilder({
...this.#props,
aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseValueBinaryOperationOrExpression(args))
});
}
/**
* Adds a `filter` clause with a nested `where` clause after the function, where
* both sides of the operator are references to columns.
*
* Similar to {@link WhereInterface}'s `whereRef` method.
*
* ### Examples
*
* Count people with same first and last names versus general public:
*
* ```ts
* const result = await db
* .selectFrom('person')
* .select((eb) => [
* eb.fn
* .count<number>('id')
* .filterWhereRef('first_name', '=', 'last_name')
* .as('repeat_name_count'),
* eb.fn.count<number>('id').as('total_count'),
* ])
* .executeTakeFirstOrThrow()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select
* count("id") filter(where "first_name" = "last_name") as "repeat_name_count",
* count("id") as "total_count"
* from "person"
* ```
*/
filterWhereRef(lhs, op, rhs) {
return new AggregateFunctionBuilder({
...this.#props,
aggregateFunctionNode: AggregateFunctionNode.cloneWithFilter(this.#props.aggregateFunctionNode, parseReferentialBinaryOperation(lhs, op, rhs))
});
}
/**
* Adds an `over` clause (window functions) after the function.
*
* ### Examples
*
* ```ts
* const result = await db
* .selectFrom('person')
* .select(
* (eb) => eb.fn.avg<number>('age').over().as('average_age')
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select avg("age") over() as "average_age"
* from "person"
* ```
*
* Also supports passing a callback that returns an over builder,
* allowing to add partition by and sort by clauses inside over.
*
* ```ts
* const result = await db
* .selectFrom('person')
* .select(
* (eb) => eb.fn.avg<number>('age').over(
* ob => ob.partitionBy('last_name').orderBy('first_name', 'asc')
* ).as('average_age')
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select avg("age") over(partition by "last_name" order by "first_name" asc) as "average_age"
* from "person"
* ```
*/
over(over) {
const builder = createOverBuilder();
return new AggregateFunctionBuilder({
...this.#props,
aggregateFunctionNode: AggregateFunctionNode.cloneWithOver(this.#props.aggregateFunctionNode, (over ? over(builder) : builder).toOperationNode())
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
/**
* Casts the expression to the given type.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of this `AggregateFunctionBuilder` with a new output type.
*/
$castTo() {
return new AggregateFunctionBuilder(this.#props);
}
/**
* Omit null from the expression's type.
*
* This function can be useful in cases where you know an expression can't be
* null, but Kysely is unable to infer it.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of `this` with a new output type.
*/
$notNull() {
return new AggregateFunctionBuilder(this.#props);
}
toOperationNode() {
return this.#props.aggregateFunctionNode;
}
};
AliasedAggregateFunctionBuilder = class {
#aggregateFunctionBuilder;
#alias;
constructor(aggregateFunctionBuilder, alias) {
this.#aggregateFunctionBuilder = aggregateFunctionBuilder;
this.#alias = alias;
}
/** @private */
get expression() {
return this.#aggregateFunctionBuilder;
}
/** @private */
get alias() {
return this.#alias;
}
toOperationNode() {
return AliasNode.create(this.#aggregateFunctionBuilder.toOperationNode(), IdentifierNode.create(this.#alias));
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/function-module.js
function createFunctionModule() {
const fn = (name, args) => {
return new ExpressionWrapper(FunctionNode.create(name, parseReferenceExpressionOrList(args ?? [])));
};
const agg = (name, args) => {
return new AggregateFunctionBuilder({ aggregateFunctionNode: AggregateFunctionNode.create(name, args ? parseReferenceExpressionOrList(args) : void 0) });
};
return Object.assign(fn, {
agg,
avg(column) {
return agg("avg", [column]);
},
coalesce(...values) {
return fn("coalesce", values);
},
count(column) {
return agg("count", [column]);
},
countAll(table) {
return new AggregateFunctionBuilder({ aggregateFunctionNode: AggregateFunctionNode.create("count", parseSelectAll(table)) });
},
max(column) {
return agg("max", [column]);
},
min(column) {
return agg("min", [column]);
},
sum(column) {
return agg("sum", [column]);
},
any(column) {
return fn("any", [column]);
},
jsonAgg(table) {
return new AggregateFunctionBuilder({ aggregateFunctionNode: AggregateFunctionNode.create("json_agg", [isString(table) ? parseTable(table) : table.toOperationNode()]) });
},
toJson(table) {
return new ExpressionWrapper(FunctionNode.create("to_json", [isString(table) ? parseTable(table) : table.toOperationNode()]));
}
});
}
var init_function_module = __esmMin((() => {
init_expression_wrapper();
init_aggregate_function_node();
init_function_node();
init_reference_parser();
init_select_parser();
init_aggregate_function_builder();
init_object_utils();
init_table_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/unary-operation-node.js
var UnaryOperationNode;
var init_unary_operation_node = __esmMin((() => {
init_object_utils();
UnaryOperationNode = freeze({
is(node) {
return node.kind === "UnaryOperationNode";
},
create(operator, operand) {
return freeze({
kind: "UnaryOperationNode",
operator,
operand
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/unary-operation-parser.js
function parseUnaryOperation(operator, operand) {
if (isUnaryOperator(operator)) return UnaryOperationNode.create(OperatorNode.create(operator), parseReferenceExpression(operand));
throw new Error(`invalid unary operator ${JSON.stringify(operator)}`);
}
var init_unary_operation_parser = __esmMin((() => {
init_operator_node();
init_unary_operation_node();
init_reference_parser();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/case-node.js
var CaseNode;
var init_case_node = __esmMin((() => {
init_object_utils();
init_when_node();
CaseNode = freeze({
is(node) {
return node.kind === "CaseNode";
},
create(value) {
return freeze({
kind: "CaseNode",
value
});
},
cloneWithWhen(caseNode, when) {
return freeze({
...caseNode,
when: freeze(caseNode.when ? [...caseNode.when, when] : [when])
});
},
cloneWithThen(caseNode, then) {
return freeze({
...caseNode,
when: caseNode.when ? freeze([...caseNode.when.slice(0, -1), WhenNode.cloneWithResult(caseNode.when[caseNode.when.length - 1], then)]) : void 0
});
},
cloneWith(caseNode, props) {
return freeze({
...caseNode,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/case-builder.js
var CaseBuilder, CaseThenBuilder, CaseWhenBuilder, CaseEndBuilder;
var init_case_builder = __esmMin((() => {
init_expression_wrapper();
init_object_utils();
init_reference_parser();
init_case_node();
init_when_node();
init_binary_operation_parser();
init_value_parser();
CaseBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
when(...args) {
return new CaseThenBuilder({
...this.#props,
node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args)))
});
}
whenRef(lhs, op, rhs) {
return new CaseThenBuilder({
...this.#props,
node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseReferentialBinaryOperation(lhs, op, rhs)))
});
}
};
CaseThenBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
then(valueExpression) {
return new CaseWhenBuilder({
...this.#props,
node: CaseNode.cloneWithThen(this.#props.node, isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression))
});
}
/**
* Adds a `then` clause to the `case` statement where the value is a reference to a column.
*
* See {@link then} for value-first variant.
*
* A `thenRef` call can be followed by {@link Whenable.when}, {@link Whenable.whenRef},
* {@link CaseWhenBuilder.else}, {@link CaseWhenBuilder.elseRef},
* {@link CaseWhenBuilder.end} or {@link CaseWhenBuilder.endCase} call.
*/
thenRef(expression) {
return new CaseWhenBuilder({
...this.#props,
node: CaseNode.cloneWithThen(this.#props.node, parseReferenceExpression(expression))
});
}
};
CaseWhenBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
when(...args) {
return new CaseThenBuilder({
...this.#props,
node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseValueBinaryOperationOrExpression(args)))
});
}
whenRef(lhs, op, rhs) {
return new CaseThenBuilder({
...this.#props,
node: CaseNode.cloneWithWhen(this.#props.node, WhenNode.create(parseReferentialBinaryOperation(lhs, op, rhs)))
});
}
else(valueExpression) {
return new CaseEndBuilder({
...this.#props,
node: CaseNode.cloneWith(this.#props.node, { else: isSafeImmediateValue(valueExpression) ? parseSafeImmediateValue(valueExpression) : parseValueExpression(valueExpression) })
});
}
/**
* Adds an `else` clause to the `case` statement where the value is a reference to a column.
*
* See {@link else} for value-first variant.
*
* An `elseRef` call must be followed by an {@link Endable.end} or {@link Endable.endCase} call.
*/
elseRef(expression) {
return new CaseEndBuilder({
...this.#props,
node: CaseNode.cloneWith(this.#props.node, { else: parseReferenceExpression(expression) })
});
}
end() {
return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));
}
endCase() {
return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));
}
};
CaseEndBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
end() {
return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: false }));
}
endCase() {
return new ExpressionWrapper(CaseNode.cloneWith(this.#props.node, { isStatement: true }));
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/json-path-leg-node.js
var JSONPathLegNode;
var init_json_path_leg_node = __esmMin((() => {
init_object_utils();
JSONPathLegNode = freeze({
is(node) {
return node.kind === "JSONPathLegNode";
},
create(type, value) {
return freeze({
kind: "JSONPathLegNode",
type,
value
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-builder/json-path-builder.js
var HASH_NEGATIVE_INDEX_REGEX, JSONPathBuilder, TraversedJSONPathBuilder, AliasedJSONPathBuilder;
var init_json_path_builder = __esmMin((() => {
init_alias_node();
init_identifier_node();
init_json_operator_chain_node();
init_json_path_leg_node();
init_json_path_node();
init_json_reference_node();
init_operation_node_source();
init_value_node();
HASH_NEGATIVE_INDEX_REGEX = /^#-\d+$/;
JSONPathBuilder = class {
#node;
constructor(node) {
this.#node = node;
}
/**
* Access an element of a JSON array in a specific location.
*
* Since there's no guarantee an element exists in the given array location, the
* resulting type is always nullable. If you're sure the element exists, you
* should use {@link SelectQueryBuilder.$assertType} to narrow the type safely.
*
* See also {@link key} to access properties of JSON objects.
*
* ### Examples
*
* ```ts
* await db.selectFrom('person')
* .select(eb =>
* eb.ref('nicknames', '->').at(0).as('primary_nickname')
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "nicknames"->0 as "primary_nickname" from "person"
*```
*
* Combined with {@link key}:
*
* ```ts
* db.selectFrom('person').select(eb =>
* eb.ref('experience', '->').at(0).key('role').as('first_role')
* )
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "experience"->0->'role' as "first_role" from "person"
* ```
*
* You can use `'last'` to access the last element of the array in MySQL:
*
* ```ts
* db.selectFrom('person').select(eb =>
* eb.ref('nicknames', '->$').at('last').as('last_nickname')
* )
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* select `nicknames`->'$[last]' as `last_nickname` from `person`
* ```
*
* Or `'#-1'` in SQLite:
*
* ```ts
* db.selectFrom('person').select(eb =>
* eb.ref('nicknames', '->>$').at('#-1').as('last_nickname')
* )
* ```
*
* The generated SQL (SQLite):
*
* ```sql
* select "nicknames"->>'$[#-1]' as `last_nickname` from `person`
* ```
*/
at(index) {
if (typeof index !== "number" && typeof index !== "string" || typeof index === "number" && !Number.isInteger(index) || typeof index === "string" && index !== "last" && !HASH_NEGATIVE_INDEX_REGEX.test(index)) throw new Error(`Unexpected index value in .at(...): ${index}`);
return this.#createBuilderWithPathLeg("ArrayLocation", index);
}
/**
* Access a property of a JSON object.
*
* If a field is optional, the resulting type will be nullable.
*
* See also {@link at} to access elements of JSON arrays.
*
* ### Examples
*
* ```ts
* db.selectFrom('person').select(eb =>
* eb.ref('address', '->').key('city').as('city')
* )
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "address"->'city' as "city" from "person"
* ```
*
* Going deeper:
*
* ```ts
* db.selectFrom('person').select(eb =>
* eb.ref('profile', '->$').key('website').key('url').as('website_url')
* )
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* select `profile`->'$.website.url' as `website_url` from `person`
* ```
*
* Combined with {@link at}:
*
* ```ts
* db.selectFrom('person').select(eb =>
* eb.ref('profile', '->').key('addresses').at(0).key('city').as('city')
* )
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "profile"->'addresses'->0->'city' as "city" from "person"
* ```
*/
key(key) {
return this.#createBuilderWithPathLeg("Member", key);
}
#createBuilderWithPathLeg(legType, value) {
if (JSONReferenceNode.is(this.#node)) return new TraversedJSONPathBuilder(JSONReferenceNode.cloneWithTraversal(this.#node, JSONPathNode.is(this.#node.traversal) ? JSONPathNode.cloneWithLeg(this.#node.traversal, JSONPathLegNode.create(legType, value)) : JSONOperatorChainNode.cloneWithValue(this.#node.traversal, ValueNode.createImmediate(value))));
return new TraversedJSONPathBuilder(JSONPathNode.cloneWithLeg(this.#node, JSONPathLegNode.create(legType, value)));
}
};
TraversedJSONPathBuilder = class TraversedJSONPathBuilder extends JSONPathBuilder {
#node;
constructor(node) {
super(node);
this.#node = node;
}
/** @private */
get expressionType() {}
as(alias) {
return new AliasedJSONPathBuilder(this, alias);
}
/**
* Change the output type of the json path.
*
* This method call doesn't change the SQL in any way. This methods simply
* returns a copy of this `JSONPathBuilder` with a new output type.
*/
$castTo() {
return new TraversedJSONPathBuilder(this.#node);
}
$notNull() {
return new TraversedJSONPathBuilder(this.#node);
}
toOperationNode() {
return this.#node;
}
};
AliasedJSONPathBuilder = class {
#jsonPath;
#alias;
constructor(jsonPath, alias) {
this.#jsonPath = jsonPath;
this.#alias = alias;
}
/** @private */
get expression() {
return this.#jsonPath;
}
/** @private */
get alias() {
return this.#alias;
}
toOperationNode() {
return AliasNode.create(this.#jsonPath.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias));
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/tuple-node.js
var TupleNode;
var init_tuple_node = __esmMin((() => {
init_object_utils();
TupleNode = freeze({
is(node) {
return node.kind === "TupleNode";
},
create(values) {
return freeze({
kind: "TupleNode",
values: freeze(values)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/data-type-node.js
function isColumnDataType(dataType) {
return SIMPLE_COLUMN_DATA_TYPES[dataType] || COLUMN_DATA_TYPE_REGEX.some((r) => r.test(dataType));
}
var SIMPLE_COLUMN_DATA_TYPES, COLUMN_DATA_TYPE_REGEX, DataTypeNode;
var init_data_type_node = __esmMin((() => {
init_object_utils();
SIMPLE_COLUMN_DATA_TYPES = freeze({
bigint: true,
bigserial: true,
binary: true,
blob: true,
boolean: true,
bytea: true,
char: true,
date: true,
datemultirange: true,
daterange: true,
datetime: true,
datetime2: true,
decimal: true,
"double precision": true,
float4: true,
float8: true,
int2: true,
int4: true,
int4multirange: true,
int4range: true,
int8: true,
int8multirange: true,
int8range: true,
integer: true,
json: true,
jsonb: true,
numeric: true,
nummultirange: true,
numrange: true,
real: true,
serial: true,
smallint: true,
text: true,
time: true,
timestamp: true,
timestamptz: true,
timetz: true,
tsmultirange: true,
tsrange: true,
tstzmultirange: true,
tstzrange: true,
uuid: true,
varbinary: true,
varchar: true
});
COLUMN_DATA_TYPE_REGEX = freeze([
/^varchar\(\d+\)$/,
/^char\(\d+\)$/,
/^decimal\(\d+, \d+\)$/,
/^numeric\(\d+, \d+\)$/,
/^binary\(\d+\)$/,
/^datetime\(\d+\)$/,
/^time\(\d+\)$/,
/^timetz\(\d+\)$/,
/^timestamp\(\d+\)$/,
/^timestamptz\(\d+\)$/,
/^datetime2\(\d+\)$/,
/^varbinary\(\d+\)$/
]);
DataTypeNode = freeze({
is(node) {
return node.kind === "DataTypeNode";
},
create(dataType) {
return freeze({
kind: "DataTypeNode",
dataType
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/data-type-parser.js
function parseDataTypeExpression(dataType) {
if (isOperationNodeSource(dataType)) return dataType.toOperationNode();
if (isColumnDataType(dataType)) return DataTypeNode.create(dataType);
throw new Error(`invalid column data type ${JSON.stringify(dataType)}`);
}
var init_data_type_parser = __esmMin((() => {
init_data_type_node();
init_operation_node_source();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/cast-node.js
var CastNode;
var init_cast_node = __esmMin((() => {
init_object_utils();
CastNode = freeze({
is(node) {
return node.kind === "CastNode";
},
create(expression, dataType) {
return freeze({
kind: "CastNode",
expression,
dataType
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/expression/expression-builder.js
function createExpressionBuilder(executor = NOOP_QUERY_EXECUTOR) {
function binary(lhs, op, rhs) {
return new ExpressionWrapper(parseValueBinaryOperation(lhs, op, rhs));
}
function unary(op, expr) {
return new ExpressionWrapper(parseUnaryOperation(op, expr));
}
const eb = Object.assign(binary, {
fn: void 0,
eb: void 0,
selectFrom(table) {
return createSelectQueryBuilder({
queryId: createQueryId(),
executor,
queryNode: SelectQueryNode.createFrom(parseTableExpressionOrList(table))
});
},
case(reference) {
return new CaseBuilder({ node: CaseNode.create(isUndefined(reference) ? void 0 : parseReferenceExpression(reference)) });
},
ref(reference, op) {
if (isUndefined(op)) return new ExpressionWrapper(parseStringReference(reference));
return new JSONPathBuilder(parseJSONReference(reference, op));
},
jsonPath() {
return new JSONPathBuilder(JSONPathNode.create());
},
table(table) {
return new ExpressionWrapper(parseTable(table));
},
val(value) {
return new ExpressionWrapper(parseValueExpression(value));
},
refTuple(...values) {
return new ExpressionWrapper(TupleNode.create(values.map(parseReferenceExpression)));
},
tuple(...values) {
return new ExpressionWrapper(TupleNode.create(values.map(parseValueExpression)));
},
lit(value) {
return new ExpressionWrapper(parseSafeImmediateValue(value));
},
unary,
not(expr) {
return unary("not", expr);
},
exists(expr) {
return unary("exists", expr);
},
neg(expr) {
return unary("-", expr);
},
between(expr, start, end) {
return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between"), AndNode.create(parseValueExpression(start), parseValueExpression(end))));
},
betweenSymmetric(expr, start, end) {
return new ExpressionWrapper(BinaryOperationNode.create(parseReferenceExpression(expr), OperatorNode.create("between symmetric"), AndNode.create(parseValueExpression(start), parseValueExpression(end))));
},
and(exprs) {
if (isReadonlyArray(exprs)) return new ExpressionWrapper(parseFilterList(exprs, "and"));
return new ExpressionWrapper(parseFilterObject(exprs, "and"));
},
or(exprs) {
if (isReadonlyArray(exprs)) return new ExpressionWrapper(parseFilterList(exprs, "or"));
return new ExpressionWrapper(parseFilterObject(exprs, "or"));
},
parens(...args) {
const node = parseValueBinaryOperationOrExpression(args);
if (ParensNode.is(node)) return new ExpressionWrapper(node);
else return new ExpressionWrapper(ParensNode.create(node));
},
cast(expr, dataType) {
return new ExpressionWrapper(CastNode.create(parseReferenceExpression(expr), parseDataTypeExpression(dataType)));
}
});
eb.fn = createFunctionModule();
eb.eb = eb;
return eb;
}
function expressionBuilder(_) {
return createExpressionBuilder();
}
var init_expression_builder = __esmMin((() => {
init_select_query_builder();
init_select_query_node();
init_table_parser();
init_query_id();
init_function_module();
init_reference_parser();
init_binary_operation_parser();
init_parens_node();
init_expression_wrapper();
init_operator_node();
init_unary_operation_parser();
init_value_parser();
init_noop_query_executor();
init_case_builder();
init_case_node();
init_object_utils();
init_json_path_builder();
init_binary_operation_node();
init_and_node();
init_tuple_node();
init_json_path_node();
init_data_type_parser();
init_cast_node();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/expression-parser.js
function parseExpression(exp) {
if (isOperationNodeSource(exp)) return exp.toOperationNode();
else if (isFunction(exp)) return exp(expressionBuilder()).toOperationNode();
throw new Error(`invalid expression: ${JSON.stringify(exp)}`);
}
function parseAliasedExpression(exp) {
if (isOperationNodeSource(exp)) return exp.toOperationNode();
else if (isFunction(exp)) return exp(expressionBuilder()).toOperationNode();
throw new Error(`invalid aliased expression: ${JSON.stringify(exp)}`);
}
function isExpressionOrFactory(obj) {
return isExpression(obj) || isAliasedExpression(obj) || isFunction(obj);
}
var init_expression_parser = __esmMin((() => {
init_expression();
init_operation_node_source();
init_expression_builder();
init_object_utils();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dynamic/dynamic-table-builder.js
function isAliasedDynamicTableBuilder(obj) {
return isObject$1(obj) && isOperationNodeSource(obj) && isString(obj.table) && isString(obj.alias);
}
var DynamicTableBuilder, AliasedDynamicTableBuilder;
var init_dynamic_table_builder = __esmMin((() => {
init_alias_node();
init_identifier_node();
init_operation_node_source();
init_table_parser();
init_object_utils();
DynamicTableBuilder = class {
#table;
get table() {
return this.#table;
}
constructor(table) {
this.#table = table;
}
as(alias) {
return new AliasedDynamicTableBuilder(this.#table, alias);
}
};
AliasedDynamicTableBuilder = class {
#table;
#alias;
get table() {
return this.#table;
}
get alias() {
return this.#alias;
}
constructor(table, alias) {
this.#table = table;
this.#alias = alias;
}
toOperationNode() {
return AliasNode.create(parseTable(this.#table), IdentifierNode.create(this.#alias));
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/table-parser.js
function parseTableExpressionOrList(table) {
if (isReadonlyArray(table)) return table.map((it) => parseTableExpression(it));
else return [parseTableExpression(table)];
}
function parseTableExpression(table) {
if (isString(table)) return parseAliasedTable(table);
else if (isAliasedDynamicTableBuilder(table)) return table.toOperationNode();
else return parseAliasedExpression(table);
}
function parseAliasedTable(from) {
const ALIAS_SEPARATOR = " as ";
if (from.includes(ALIAS_SEPARATOR)) {
const [table, alias] = from.split(ALIAS_SEPARATOR).map(trim$1);
return AliasNode.create(parseTable(table), IdentifierNode.create(alias));
} else return parseTable(from);
}
function parseTable(from) {
const SCHEMA_SEPARATOR = ".";
if (from.includes(SCHEMA_SEPARATOR)) {
const [schema, table] = from.split(SCHEMA_SEPARATOR).map(trim$1);
return TableNode.createWithSchema(schema, table);
} else return TableNode.create(from);
}
function trim$1(str) {
return str.trim();
}
var init_table_parser = __esmMin((() => {
init_object_utils();
init_alias_node();
init_table_node();
init_expression_parser();
init_identifier_node();
init_dynamic_table_builder();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/add-column-node.js
var AddColumnNode;
var init_add_column_node = __esmMin((() => {
init_object_utils();
AddColumnNode = freeze({
is(node) {
return node.kind === "AddColumnNode";
},
create(column) {
return freeze({
kind: "AddColumnNode",
column
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/column-definition-node.js
var ColumnDefinitionNode;
var init_column_definition_node = __esmMin((() => {
init_object_utils();
init_column_node();
ColumnDefinitionNode = freeze({
is(node) {
return node.kind === "ColumnDefinitionNode";
},
create(column, dataType) {
return freeze({
kind: "ColumnDefinitionNode",
column: ColumnNode.create(column),
dataType
});
},
cloneWithFrontModifier(node, modifier) {
return freeze({
...node,
frontModifiers: node.frontModifiers ? freeze([...node.frontModifiers, modifier]) : [modifier]
});
},
cloneWithEndModifier(node, modifier) {
return freeze({
...node,
endModifiers: node.endModifiers ? freeze([...node.endModifiers, modifier]) : [modifier]
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/drop-column-node.js
var DropColumnNode;
var init_drop_column_node = __esmMin((() => {
init_object_utils();
init_column_node();
DropColumnNode = freeze({
is(node) {
return node.kind === "DropColumnNode";
},
create(column) {
return freeze({
kind: "DropColumnNode",
column: ColumnNode.create(column)
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/rename-column-node.js
var RenameColumnNode;
var init_rename_column_node = __esmMin((() => {
init_object_utils();
init_column_node();
RenameColumnNode = freeze({
is(node) {
return node.kind === "RenameColumnNode";
},
create(column, newColumn) {
return freeze({
kind: "RenameColumnNode",
column: ColumnNode.create(column),
renameTo: ColumnNode.create(newColumn)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/check-constraint-node.js
var CheckConstraintNode;
var init_check_constraint_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
CheckConstraintNode = freeze({
is(node) {
return node.kind === "CheckConstraintNode";
},
create(expression, constraintName) {
return freeze({
kind: "CheckConstraintNode",
expression,
name: constraintName ? IdentifierNode.create(constraintName) : void 0
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/references-node.js
function isOnModifyForeignAction(thing) {
return isString(thing) && ON_MODIFY_FOREIGN_ACTIONS_DICTIONARY[thing];
}
var ON_MODIFY_FOREIGN_ACTIONS_DICTIONARY, ReferencesNode;
var init_references_node = __esmMin((() => {
init_object_utils();
ON_MODIFY_FOREIGN_ACTIONS_DICTIONARY = freeze({
cascade: true,
"no action": true,
restrict: true,
"set default": true,
"set null": true
});
Object.keys(ON_MODIFY_FOREIGN_ACTIONS_DICTIONARY);
ReferencesNode = freeze({
is(node) {
return node.kind === "ReferencesNode";
},
create(table, columns) {
return freeze({
kind: "ReferencesNode",
table,
columns: freeze([...columns])
});
},
cloneWithOnDelete(references, onDelete) {
return freeze({
...references,
onDelete
});
},
cloneWithOnUpdate(references, onUpdate) {
return freeze({
...references,
onUpdate
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/default-value-parser.js
function parseDefaultValueExpression(value) {
return isOperationNodeSource(value) ? value.toOperationNode() : ValueNode.createImmediate(value);
}
var init_default_value_parser = __esmMin((() => {
init_operation_node_source();
init_value_node();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/generated-node.js
var GeneratedNode;
var init_generated_node = __esmMin((() => {
init_object_utils();
GeneratedNode = freeze({
is(node) {
return node.kind === "GeneratedNode";
},
create(params) {
return freeze({
kind: "GeneratedNode",
...params
});
},
createWithExpression(expression) {
return freeze({
kind: "GeneratedNode",
always: true,
expression
});
},
cloneWith(node, params) {
return freeze({
...node,
...params
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/default-value-node.js
var DefaultValueNode;
var init_default_value_node = __esmMin((() => {
init_object_utils();
DefaultValueNode = freeze({
is(node) {
return node.kind === "DefaultValueNode";
},
create(defaultValue) {
return freeze({
kind: "DefaultValueNode",
defaultValue
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/on-modify-action-parser.js
function parseOnModifyForeignAction(action) {
if (isOnModifyForeignAction(action)) return action;
throw new Error(`invalid OnModifyForeignAction ${action}`);
}
var init_on_modify_action_parser = __esmMin((() => {
init_references_node();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/column-definition-builder.js
var ColumnDefinitionBuilder;
var init_column_definition_builder = __esmMin((() => {
init_check_constraint_node();
init_references_node();
init_select_all_node();
init_reference_parser();
init_column_definition_node();
init_default_value_parser();
init_generated_node();
init_default_value_node();
init_on_modify_action_parser();
ColumnDefinitionBuilder = class ColumnDefinitionBuilder {
#node;
constructor(node) {
this.#node = node;
}
/**
* Adds `auto_increment` or `autoincrement` to the column definition
* depending on the dialect.
*
* Some dialects like PostgreSQL don't support this. On PostgreSQL
* you can use the `serial` or `bigserial` data type instead.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.autoIncrement().primaryKey())
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `id` integer primary key auto_increment
* )
* ```
*/
autoIncrement() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { autoIncrement: true }));
}
/**
* Makes the column an identity column.
*
* This only works on some dialects like MS SQL Server (MSSQL).
*
* For PostgreSQL's `generated always as identity` use {@link generatedAlwaysAsIdentity}.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.identity().primaryKey())
* .execute()
* ```
*
* The generated SQL (MSSQL):
*
* ```sql
* create table "person" (
* "id" integer identity primary key
* )
* ```
*/
identity() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { identity: true }));
}
/**
* Makes the column the primary key.
*
* If you want to specify a composite primary key use the
* {@link CreateTableBuilder.addPrimaryKeyConstraint} method.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.primaryKey())
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `id` integer primary key
* )
*/
primaryKey() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { primaryKey: true }));
}
/**
* Adds a foreign key constraint for the column.
*
* If your database engine doesn't support foreign key constraints in the
* column definition (like MySQL 5) you need to call the table level
* {@link CreateTableBuilder.addForeignKeyConstraint} method instead.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('pet')
* .addColumn('owner_id', 'integer', (col) => col.references('person.id'))
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create table "pet" (
* "owner_id" integer references "person" ("id")
* )
* ```
*/
references(ref) {
const references = parseStringReference(ref);
if (!references.table || SelectAllNode.is(references.column)) throw new Error(`invalid call references('${ref}'). The reference must have format table.column or schema.table.column`);
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { references: ReferencesNode.create(references.table, [references.column]) }));
}
/**
* Adds an `on delete` constraint for the foreign key column.
*
* If your database engine doesn't support foreign key constraints in the
* column definition (like MySQL 5) you need to call the table level
* {@link CreateTableBuilder.addForeignKeyConstraint} method instead.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('pet')
* .addColumn(
* 'owner_id',
* 'integer',
* (col) => col.references('person.id').onDelete('cascade')
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create table "pet" (
* "owner_id" integer references "person" ("id") on delete cascade
* )
* ```
*/
onDelete(onDelete) {
if (!this.#node.references) throw new Error("on delete constraint can only be added for foreign keys");
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { references: ReferencesNode.cloneWithOnDelete(this.#node.references, parseOnModifyForeignAction(onDelete)) }));
}
/**
* Adds an `on update` constraint for the foreign key column.
*
* If your database engine doesn't support foreign key constraints in the
* column definition (like MySQL 5) you need to call the table level
* {@link CreateTableBuilder.addForeignKeyConstraint} method instead.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('pet')
* .addColumn(
* 'owner_id',
* 'integer',
* (col) => col.references('person.id').onUpdate('cascade')
* )
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create table "pet" (
* "owner_id" integer references "person" ("id") on update cascade
* )
* ```
*/
onUpdate(onUpdate) {
if (!this.#node.references) throw new Error("on update constraint can only be added for foreign keys");
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { references: ReferencesNode.cloneWithOnUpdate(this.#node.references, parseOnModifyForeignAction(onUpdate)) }));
}
/**
* Adds a unique constraint for the column.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('email', 'varchar(255)', col => col.unique())
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `email` varchar(255) unique
* )
* ```
*/
unique() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unique: true }));
}
/**
* Adds a `not null` constraint for the column.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('first_name', 'varchar(255)', col => col.notNull())
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `first_name` varchar(255) not null
* )
* ```
*/
notNull() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { notNull: true }));
}
/**
* Adds a `unsigned` modifier for the column.
*
* This only works on some dialects like MySQL.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('age', 'integer', col => col.unsigned())
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `age` integer unsigned
* )
* ```
*/
unsigned() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { unsigned: true }));
}
/**
* Adds a default value constraint for the column.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('pet')
* .addColumn('number_of_legs', 'integer', (col) => col.defaultTo(4))
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `pet` (
* `number_of_legs` integer default 4
* )
* ```
*
* Values passed to `defaultTo` are interpreted as value literals by default. You can define
* an arbitrary SQL expression using the {@link sql} template tag:
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('pet')
* .addColumn(
* 'created_at',
* 'timestamp',
* (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`)
* )
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `pet` (
* `created_at` timestamp default CURRENT_TIMESTAMP
* )
* ```
*/
defaultTo(value) {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { defaultTo: DefaultValueNode.create(parseDefaultValueExpression(value)) }));
}
/**
* Adds a check constraint for the column.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('pet')
* .addColumn('number_of_legs', 'integer', (col) =>
* col.check(sql`number_of_legs < 5`)
* )
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `pet` (
* `number_of_legs` integer check (number_of_legs < 5)
* )
* ```
*/
check(expression) {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { check: CheckConstraintNode.create(expression.toOperationNode()) }));
}
/**
* Makes the column a generated column using a `generated always as` statement.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('person')
* .addColumn('full_name', 'varchar(255)',
* (col) => col.generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`)
* )
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name))
* )
* ```
*/
generatedAlwaysAs(expression) {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { generated: GeneratedNode.createWithExpression(expression.toOperationNode()) }));
}
/**
* Adds the `generated always as identity` specifier.
*
* This only works on some dialects like PostgreSQL.
*
* For MS SQL Server (MSSQL)'s identity column use {@link identity}.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.generatedAlwaysAsIdentity().primaryKey())
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create table "person" (
* "id" integer generated always as identity primary key
* )
* ```
*/
generatedAlwaysAsIdentity() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { generated: GeneratedNode.create({
identity: true,
always: true
}) }));
}
/**
* Adds the `generated by default as identity` specifier on supported dialects.
*
* This only works on some dialects like PostgreSQL.
*
* For MS SQL Server (MSSQL)'s identity column use {@link identity}.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.generatedByDefaultAsIdentity().primaryKey())
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create table "person" (
* "id" integer generated by default as identity primary key
* )
* ```
*/
generatedByDefaultAsIdentity() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { generated: GeneratedNode.create({
identity: true,
byDefault: true
}) }));
}
/**
* Makes a generated column stored instead of virtual. This method can only
* be used with {@link generatedAlwaysAs}
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('person')
* .addColumn('full_name', 'varchar(255)', (col) => col
* .generatedAlwaysAs(sql`concat(first_name, ' ', last_name)`)
* .stored()
* )
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `full_name` varchar(255) generated always as (concat(first_name, ' ', last_name)) stored
* )
* ```
*/
stored() {
if (!this.#node.generated) throw new Error("stored() can only be called after generatedAlwaysAs");
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { generated: GeneratedNode.cloneWith(this.#node.generated, { stored: true }) }));
}
/**
* This can be used to add any additional SQL right after the column's data type.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.primaryKey())
* .addColumn(
* 'first_name',
* 'varchar(36)',
* (col) => col.modifyFront(sql`collate utf8mb4_general_ci`).notNull()
* )
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `id` integer primary key,
* `first_name` varchar(36) collate utf8mb4_general_ci not null
* )
* ```
*/
modifyFront(modifier) {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithFrontModifier(this.#node, modifier.toOperationNode()));
}
/**
* Adds `nulls not distinct` specifier.
* Should be used with `unique` constraint.
*
* This only works on some dialects like PostgreSQL.
*
* ### Examples
*
* ```ts
* db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.primaryKey())
* .addColumn('first_name', 'varchar(30)', col => col.unique().nullsNotDistinct())
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create table "person" (
* "id" integer primary key,
* "first_name" varchar(30) unique nulls not distinct
* )
* ```
*/
nullsNotDistinct() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { nullsNotDistinct: true }));
}
/**
* Adds `if not exists` specifier. This only works for PostgreSQL.
*
* ### Examples
*
* ```ts
* await db.schema
* .alterTable('person')
* .addColumn('email', 'varchar(255)', col => col.unique().ifNotExists())
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* alter table "person" add column if not exists "email" varchar(255) unique
* ```
*/
ifNotExists() {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWith(this.#node, { ifNotExists: true }));
}
/**
* This can be used to add any additional SQL to the end of the column definition.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.primaryKey())
* .addColumn(
* 'age',
* 'integer',
* col => col.unsigned()
* .notNull()
* .modifyEnd(sql`comment ${sql.lit('it is not polite to ask a woman her age')}`)
* )
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `id` integer primary key,
* `age` integer unsigned not null comment 'it is not polite to ask a woman her age'
* )
* ```
*/
modifyEnd(modifier) {
return new ColumnDefinitionBuilder(ColumnDefinitionNode.cloneWithEndModifier(this.#node, modifier.toOperationNode()));
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/modify-column-node.js
var ModifyColumnNode;
var init_modify_column_node = __esmMin((() => {
init_object_utils();
ModifyColumnNode = freeze({
is(node) {
return node.kind === "ModifyColumnNode";
},
create(column) {
return freeze({
kind: "ModifyColumnNode",
column
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/foreign-key-constraint-node.js
var ForeignKeyConstraintNode;
var init_foreign_key_constraint_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
init_references_node();
ForeignKeyConstraintNode = freeze({
is(node) {
return node.kind === "ForeignKeyConstraintNode";
},
create(sourceColumns, targetTable, targetColumns, constraintName) {
return freeze({
kind: "ForeignKeyConstraintNode",
columns: sourceColumns,
references: ReferencesNode.create(targetTable, targetColumns),
name: constraintName ? IdentifierNode.create(constraintName) : void 0
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/foreign-key-constraint-builder.js
var ForeignKeyConstraintBuilder;
var init_foreign_key_constraint_builder = __esmMin((() => {
init_foreign_key_constraint_node();
init_on_modify_action_parser();
ForeignKeyConstraintBuilder = class ForeignKeyConstraintBuilder {
#node;
constructor(node) {
this.#node = node;
}
onDelete(onDelete) {
return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { onDelete: parseOnModifyForeignAction(onDelete) }));
}
onUpdate(onUpdate) {
return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { onUpdate: parseOnModifyForeignAction(onUpdate) }));
}
deferrable() {
return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: true }));
}
notDeferrable() {
return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { deferrable: false }));
}
initiallyDeferred() {
return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { initiallyDeferred: true }));
}
initiallyImmediate() {
return new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.cloneWith(this.#node, { initiallyDeferred: false }));
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/add-constraint-node.js
var AddConstraintNode;
var init_add_constraint_node = __esmMin((() => {
init_object_utils();
AddConstraintNode = freeze({
is(node) {
return node.kind === "AddConstraintNode";
},
create(constraint) {
return freeze({
kind: "AddConstraintNode",
constraint
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/unique-constraint-node.js
var UniqueConstraintNode;
var init_unique_constraint_node = __esmMin((() => {
init_log_once();
init_object_utils();
init_column_node();
init_identifier_node();
UniqueConstraintNode = freeze({
is(node) {
return node.kind === "UniqueConstraintNode";
},
create(columns, constraintName, nullsNotDistinct) {
if (isString(columns.at(0))) {
logOnce("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead.");
columns = columns.map(ColumnNode.create);
}
return freeze({
kind: "UniqueConstraintNode",
columns: freeze(columns),
name: constraintName ? IdentifierNode.create(constraintName) : void 0,
nullsNotDistinct
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/drop-constraint-node.js
var DropConstraintNode;
var init_drop_constraint_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
DropConstraintNode = freeze({
is(node) {
return node.kind === "DropConstraintNode";
},
create(constraintName) {
return freeze({
kind: "DropConstraintNode",
constraintName: IdentifierNode.create(constraintName)
});
},
cloneWith(dropConstraint, props) {
return freeze({
...dropConstraint,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/alter-column-node.js
var AlterColumnNode;
var init_alter_column_node = __esmMin((() => {
init_object_utils();
init_column_node();
AlterColumnNode = freeze({
is(node) {
return node.kind === "AlterColumnNode";
},
create(column, prop, value) {
return freeze({
kind: "AlterColumnNode",
column: ColumnNode.create(column),
[prop]: value
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/alter-column-builder.js
var AlterColumnBuilder, AlteredColumnBuilder;
var init_alter_column_builder = __esmMin((() => {
init_alter_column_node();
init_data_type_parser();
init_default_value_parser();
AlterColumnBuilder = class {
#column;
constructor(column) {
this.#column = column;
}
setDataType(dataType) {
return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dataType", parseDataTypeExpression(dataType)));
}
setDefault(value) {
return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "setDefault", parseDefaultValueExpression(value)));
}
dropDefault() {
return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dropDefault", true));
}
setNotNull() {
return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "setNotNull", true));
}
dropNotNull() {
return new AlteredColumnBuilder(AlterColumnNode.create(this.#column, "dropNotNull", true));
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
};
AlteredColumnBuilder = class {
#alterColumnNode;
constructor(alterColumnNode) {
this.#alterColumnNode = alterColumnNode;
}
toOperationNode() {
return this.#alterColumnNode;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/alter-table-executor.js
var AlterTableExecutor;
var init_alter_table_executor = __esmMin((() => {
init_object_utils();
AlterTableExecutor = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/alter-table-add-foreign-key-constraint-builder.js
var AlterTableAddForeignKeyConstraintBuilder;
var init_alter_table_add_foreign_key_constraint_builder = __esmMin((() => {
init_add_constraint_node();
init_alter_table_node();
init_object_utils();
AlterTableAddForeignKeyConstraintBuilder = class AlterTableAddForeignKeyConstraintBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
onDelete(onDelete) {
return new AlterTableAddForeignKeyConstraintBuilder({
...this.#props,
constraintBuilder: this.#props.constraintBuilder.onDelete(onDelete)
});
}
onUpdate(onUpdate) {
return new AlterTableAddForeignKeyConstraintBuilder({
...this.#props,
constraintBuilder: this.#props.constraintBuilder.onUpdate(onUpdate)
});
}
deferrable() {
return new AlterTableAddForeignKeyConstraintBuilder({
...this.#props,
constraintBuilder: this.#props.constraintBuilder.deferrable()
});
}
notDeferrable() {
return new AlterTableAddForeignKeyConstraintBuilder({
...this.#props,
constraintBuilder: this.#props.constraintBuilder.notDeferrable()
});
}
initiallyDeferred() {
return new AlterTableAddForeignKeyConstraintBuilder({
...this.#props,
constraintBuilder: this.#props.constraintBuilder.initiallyDeferred()
});
}
initiallyImmediate() {
return new AlterTableAddForeignKeyConstraintBuilder({
...this.#props,
constraintBuilder: this.#props.constraintBuilder.initiallyImmediate()
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(AlterTableNode.cloneWithTableProps(this.#props.node, { addConstraint: AddConstraintNode.create(this.#props.constraintBuilder.toOperationNode()) }), this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/alter-table-drop-constraint-builder.js
var AlterTableDropConstraintBuilder;
var init_alter_table_drop_constraint_builder = __esmMin((() => {
init_alter_table_node();
init_drop_constraint_node();
init_object_utils();
AlterTableDropConstraintBuilder = class AlterTableDropConstraintBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
ifExists() {
return new AlterTableDropConstraintBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, { ifExists: true }) })
});
}
cascade() {
return new AlterTableDropConstraintBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, { modifier: "cascade" }) })
});
}
restrict() {
return new AlterTableDropConstraintBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { dropConstraint: DropConstraintNode.cloneWith(this.#props.node.dropConstraint, { modifier: "restrict" }) })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/primary-key-constraint-node.js
var PrimaryKeyConstraintNode;
var init_primary_key_constraint_node = __esmMin((() => {
init_object_utils();
init_column_node();
init_identifier_node();
PrimaryKeyConstraintNode = freeze({
is(node) {
return node.kind === "PrimaryKeyConstraintNode";
},
create(columns, constraintName) {
return freeze({
kind: "PrimaryKeyConstraintNode",
columns: freeze(columns.map(ColumnNode.create)),
name: constraintName ? IdentifierNode.create(constraintName) : void 0
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/add-index-node.js
var AddIndexNode;
var init_add_index_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
AddIndexNode = freeze({
is(node) {
return node.kind === "AddIndexNode";
},
create(name) {
return freeze({
kind: "AddIndexNode",
name: IdentifierNode.create(name)
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
},
cloneWithColumns(node, columns) {
return freeze({
...node,
columns: [...node.columns || [], ...columns]
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/alter-table-add-index-builder.js
var AlterTableAddIndexBuilder;
var init_alter_table_add_index_builder = __esmMin((() => {
init_add_index_node();
init_alter_table_node();
init_raw_node();
init_reference_parser();
init_object_utils();
AlterTableAddIndexBuilder = class AlterTableAddIndexBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Makes the index unique.
*
* ### Examples
*
* ```ts
* await db.schema
* .alterTable('person')
* .addIndex('person_first_name_index')
* .unique()
* .column('email')
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* alter table `person` add unique index `person_first_name_index` (`email`)
* ```
*/
unique() {
return new AlterTableAddIndexBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, { unique: true }) })
});
}
column(arg) {
return new AlterTableAddIndexBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [isString(arg) ? parseOrderedColumnName(arg) : arg.toOperationNode()]) })
});
}
/**
* Specifies a list of columns for the index.
*
* Also see {@link column} for adding a single column or {@link expression} for
* specifying an arbitrary expression.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .alterTable('person')
* .addIndex('person_first_name_and_age_index')
* .columns(['first_name', sql`(left(lower(last_name), 1))`, 'age desc'])
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* alter table `person`
* add index `person_first_name_and_age_index` (
* `first_name`,
* (left(lower(last_name), 1)),
* `age` desc
* )
* ```
*/
columns(columns) {
return new AlterTableAddIndexBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, columns.map((item) => isString(item) ? parseOrderedColumnName(item) : item.toOperationNode())) })
});
}
/**
* Specifies an arbitrary expression for the index.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .alterTable('person')
* .addIndex('person_first_name_index')
* .expression(sql<boolean>`(first_name < 'Sami')`)
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* alter table `person` add index `person_first_name_index` ((first_name < 'Sami'))
* ```
*
* @deprecated Use {@link column} or {@link columns} with an {@link Expression} instead.
*/
expression(expression) {
return new AlterTableAddIndexBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { addIndex: AddIndexNode.cloneWithColumns(this.#props.node.addIndex, [expression.toOperationNode()]) })
});
}
using(indexType) {
return new AlterTableAddIndexBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { addIndex: AddIndexNode.cloneWith(this.#props.node.addIndex, { using: RawNode.createWithSql(indexType) }) })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/unique-constraint-builder.js
var UniqueConstraintNodeBuilder;
var init_unique_constraint_builder = __esmMin((() => {
init_unique_constraint_node();
UniqueConstraintNodeBuilder = class UniqueConstraintNodeBuilder {
#node;
constructor(node) {
this.#node = node;
}
/**
* Adds `nulls not distinct` to the unique constraint definition
*
* Supported by PostgreSQL dialect only
*/
nullsNotDistinct() {
return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { nullsNotDistinct: true }));
}
deferrable() {
return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: true }));
}
notDeferrable() {
return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { deferrable: false }));
}
initiallyDeferred() {
return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { initiallyDeferred: true }));
}
initiallyImmediate() {
return new UniqueConstraintNodeBuilder(UniqueConstraintNode.cloneWith(this.#node, { initiallyDeferred: false }));
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/primary-key-constraint-builder.js
var PrimaryKeyConstraintBuilder;
var init_primary_key_constraint_builder = __esmMin((() => {
init_primary_key_constraint_node();
PrimaryKeyConstraintBuilder = class PrimaryKeyConstraintBuilder {
#node;
constructor(node) {
this.#node = node;
}
deferrable() {
return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: true }));
}
notDeferrable() {
return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { deferrable: false }));
}
initiallyDeferred() {
return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { initiallyDeferred: true }));
}
initiallyImmediate() {
return new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.cloneWith(this.#node, { initiallyDeferred: false }));
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/check-constraint-builder.js
var CheckConstraintBuilder;
var init_check_constraint_builder = __esmMin((() => {
CheckConstraintBuilder = class {
#node;
constructor(node) {
this.#node = node;
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/rename-constraint-node.js
var RenameConstraintNode;
var init_rename_constraint_node = __esmMin((() => {
init_object_utils();
init_identifier_node();
RenameConstraintNode = freeze({
is(node) {
return node.kind === "RenameConstraintNode";
},
create(oldName, newName) {
return freeze({
kind: "RenameConstraintNode",
oldName: IdentifierNode.create(oldName),
newName: IdentifierNode.create(newName)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/drop-column-builder.js
var DropColumnBuilder;
var init_drop_column_builder = __esmMin((() => {
init_drop_column_node();
init_object_utils();
DropColumnBuilder = class DropColumnBuilder {
#props;
constructor(props) {
this.#props = freeze({ ...props });
}
ifExists() {
return new DropColumnBuilder({
...this.#props,
node: DropColumnNode.cloneWith(this.#props.node, { ifExists: true })
});
}
toOperationNode() {
return this.#props.node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/alter-table-builder.js
var AlterTableBuilder, AlterTableColumnAlteringBuilder;
var init_alter_table_builder = __esmMin((() => {
init_add_column_node();
init_alter_table_node();
init_column_definition_node();
init_drop_column_node();
init_identifier_node();
init_rename_column_node();
init_object_utils();
init_column_definition_builder();
init_modify_column_node();
init_data_type_parser();
init_foreign_key_constraint_builder();
init_add_constraint_node();
init_unique_constraint_node();
init_check_constraint_node();
init_foreign_key_constraint_node();
init_column_node();
init_table_parser();
init_drop_constraint_node();
init_alter_column_builder();
init_alter_table_executor();
init_alter_table_add_foreign_key_constraint_builder();
init_alter_table_drop_constraint_builder();
init_primary_key_constraint_node();
init_drop_index_node();
init_add_index_node();
init_alter_table_add_index_builder();
init_unique_constraint_builder();
init_primary_key_constraint_builder();
init_check_constraint_builder();
init_rename_constraint_node();
init_expression_parser();
init_drop_column_builder();
AlterTableBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
renameTo(newTableName) {
return new AlterTableExecutor({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { renameTo: parseTable(newTableName) })
});
}
setSchema(newSchema) {
return new AlterTableExecutor({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { setSchema: IdentifierNode.create(newSchema) })
});
}
alterColumn(column, alteration) {
const builder = alteration(new AlterColumnBuilder(column));
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode())
});
}
dropColumn(column, build = noop) {
const builder = build(new DropColumnBuilder({ node: DropColumnNode.create(column) }));
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode())
});
}
renameColumn(column, newColumn) {
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn))
});
}
addColumn(columnName, dataType, build = noop) {
const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode()))
});
}
modifyColumn(columnName, dataType, build = noop) {
const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode()))
});
}
/**
* See {@link CreateTableBuilder.addUniqueConstraint}
*/
addUniqueConstraint(constraintName, columns, build = noop) {
const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns.map((column) => isString(column) ? ColumnNode.create(column) : parseExpression(column)), constraintName)));
return new AlterTableExecutor({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { addConstraint: AddConstraintNode.create(uniqueConstraintBuilder.toOperationNode()) })
});
}
/**
* See {@link CreateTableBuilder.addCheckConstraint}
*/
addCheckConstraint(constraintName, checkExpression, build = noop) {
const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName)));
return new AlterTableExecutor({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) })
});
}
/**
* See {@link CreateTableBuilder.addForeignKeyConstraint}
*
* Unlike {@link CreateTableBuilder.addForeignKeyConstraint} this method returns
* the constraint builder and doesn't take a callback as the last argument. This
* is because you can only add one column per `ALTER TABLE` query.
*/
addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) {
const constraintBuilder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName)));
return new AlterTableAddForeignKeyConstraintBuilder({
...this.#props,
constraintBuilder
});
}
/**
* See {@link CreateTableBuilder.addPrimaryKeyConstraint}
*/
addPrimaryKeyConstraint(constraintName, columns, build = noop) {
const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName)));
return new AlterTableExecutor({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { addConstraint: AddConstraintNode.create(constraintBuilder.toOperationNode()) })
});
}
dropConstraint(constraintName) {
return new AlterTableDropConstraintBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { dropConstraint: DropConstraintNode.create(constraintName) })
});
}
renameConstraint(oldName, newName) {
return new AlterTableDropConstraintBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { renameConstraint: RenameConstraintNode.create(oldName, newName) })
});
}
/**
* This can be used to add index to table.
*
* ### Examples
*
* ```ts
* db.schema.alterTable('person')
* .addIndex('person_email_index')
* .column('email')
* .unique()
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* alter table `person` add unique index `person_email_index` (`email`)
* ```
*/
addIndex(indexName) {
return new AlterTableAddIndexBuilder({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { addIndex: AddIndexNode.create(indexName) })
});
}
/**
* This can be used to drop index from table.
*
* ### Examples
*
* ```ts
* db.schema.alterTable('person')
* .dropIndex('person_email_index')
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* alter table `person` drop index `test_first_name_index`
* ```
*/
dropIndex(indexName) {
return new AlterTableExecutor({
...this.#props,
node: AlterTableNode.cloneWithTableProps(this.#props.node, { dropIndex: DropIndexNode.create(indexName) })
});
}
/**
* Calls the given function passing `this` as the only argument.
*
* See {@link CreateTableBuilder.$call}
*/
$call(func) {
return func(this);
}
};
AlterTableColumnAlteringBuilder = class AlterTableColumnAlteringBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
alterColumn(column, alteration) {
const builder = alteration(new AlterColumnBuilder(column));
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode())
});
}
dropColumn(column, build = noop) {
const builder = build(new DropColumnBuilder({ node: DropColumnNode.create(column) }));
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, builder.toOperationNode())
});
}
renameColumn(column, newColumn) {
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, RenameColumnNode.create(column, newColumn))
});
}
addColumn(columnName, dataType, build = noop) {
const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, AddColumnNode.create(builder.toOperationNode()))
});
}
modifyColumn(columnName, dataType, build = noop) {
const builder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
return new AlterTableColumnAlteringBuilder({
...this.#props,
node: AlterTableNode.cloneWithColumnAlteration(this.#props.node, ModifyColumnNode.create(builder.toOperationNode()))
});
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/immediate-value/immediate-value-transformer.js
var ImmediateValueTransformer;
var init_immediate_value_transformer = __esmMin((() => {
init_operation_node_transformer();
init_value_list_node();
init_value_node();
ImmediateValueTransformer = class extends OperationNodeTransformer {
transformPrimitiveValueList(node) {
return ValueListNode.create(node.values.map(ValueNode.createImmediate));
}
transformValue(node) {
return ValueNode.createImmediate(node.value);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/create-index-builder.js
var CreateIndexBuilder;
var init_create_index_builder = __esmMin((() => {
init_create_index_node();
init_raw_node();
init_reference_parser();
init_table_parser();
init_object_utils();
init_binary_operation_parser();
init_query_node();
init_immediate_value_transformer();
CreateIndexBuilder = class CreateIndexBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Adds the "if not exists" modifier.
*
* If the index already exists, no error is thrown if this method has been called.
*/
ifNotExists() {
return new CreateIndexBuilder({
...this.#props,
node: CreateIndexNode.cloneWith(this.#props.node, { ifNotExists: true })
});
}
/**
* Makes the index unique.
*/
unique() {
return new CreateIndexBuilder({
...this.#props,
node: CreateIndexNode.cloneWith(this.#props.node, { unique: true })
});
}
/**
* Adds `nulls not distinct` specifier to index.
* This only works on some dialects like PostgreSQL.
*
* ### Examples
*
* ```ts
* db.schema.createIndex('person_first_name_index')
* .on('person')
* .column('first_name')
* .nullsNotDistinct()
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create index "person_first_name_index"
* on "test" ("first_name")
* nulls not distinct;
* ```
*/
nullsNotDistinct() {
return new CreateIndexBuilder({
...this.#props,
node: CreateIndexNode.cloneWith(this.#props.node, { nullsNotDistinct: true })
});
}
/**
* Specifies the table for the index.
*/
on(table) {
return new CreateIndexBuilder({
...this.#props,
node: CreateIndexNode.cloneWith(this.#props.node, { table: parseTable(table) })
});
}
column(arg) {
return new CreateIndexBuilder({
...this.#props,
node: CreateIndexNode.cloneWithColumns(this.#props.node, [isString(arg) ? parseOrderedColumnName(arg) : arg.toOperationNode()])
});
}
/**
* Adds a list of columns to the index.
*
* Also see {@link column} for adding a single column.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createIndex('person_first_name_and_age_index')
* .on('person')
* .columns(['first_name', sql`left(lower("last_name"), 1)`, 'age desc'])
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create index "person_first_name_and_age_index"
* on "person" ("first_name", left(lower("last_name"), 1), "age" desc)
* ```
*/
columns(columns) {
return new CreateIndexBuilder({
...this.#props,
node: CreateIndexNode.cloneWithColumns(this.#props.node, columns.map((item) => isString(item) ? parseOrderedColumnName(item) : item.toOperationNode()))
});
}
/**
* Adds an arbitrary expression as a column to the index.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createIndex('person_first_name_index')
* .on('person')
* .expression(sql`first_name COLLATE "fi_FI"`)
* .column('gender')
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create index "person_first_name_index"
* on "person" (first_name COLLATE "fi_FI", "gender")
* ```
*
* @deprecated Use {@link column} or {@link columns} with an {@link Expression} instead.
*/
expression(expression) {
return new CreateIndexBuilder({
...this.#props,
node: CreateIndexNode.cloneWithColumns(this.#props.node, [expression.toOperationNode()])
});
}
using(indexType) {
return new CreateIndexBuilder({
...this.#props,
node: CreateIndexNode.cloneWith(this.#props.node, { using: RawNode.createWithSql(indexType) })
});
}
where(...args) {
const transformer = new ImmediateValueTransformer();
return new CreateIndexBuilder({
...this.#props,
node: QueryNode.cloneWithWhere(this.#props.node, transformer.transformNode(parseValueBinaryOperationOrExpression(args), this.#props.queryId))
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/create-schema-builder.js
var CreateSchemaBuilder;
var init_create_schema_builder = __esmMin((() => {
init_create_schema_node();
init_object_utils();
CreateSchemaBuilder = class CreateSchemaBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
ifNotExists() {
return new CreateSchemaBuilder({
...this.#props,
node: CreateSchemaNode.cloneWith(this.#props.node, { ifNotExists: true })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/on-commit-action-parse.js
function parseOnCommitAction(action) {
if (ON_COMMIT_ACTIONS.includes(action)) return action;
throw new Error(`invalid OnCommitAction ${action}`);
}
var init_on_commit_action_parse = __esmMin((() => {
init_create_table_node();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/create-table-add-index-builder.js
var CreateTableAddIndexBuilder;
var init_create_table_add_index_builder = __esmMin((() => {
init_add_index_node();
init_raw_node();
CreateTableAddIndexBuilder = class CreateTableAddIndexBuilder {
#node;
constructor(node) {
this.#node = node;
}
using(indexType) {
return new CreateTableAddIndexBuilder(AddIndexNode.cloneWith(this.#node, { using: RawNode.createWithSql(indexType) }));
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#node;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/create-table-builder.js
var CreateTableBuilder;
var init_create_table_builder = __esmMin((() => {
init_column_definition_node();
init_create_table_node();
init_column_definition_builder();
init_object_utils();
init_foreign_key_constraint_node();
init_column_node();
init_foreign_key_constraint_builder();
init_data_type_parser();
init_primary_key_constraint_node();
init_unique_constraint_node();
init_check_constraint_node();
init_table_parser();
init_on_commit_action_parse();
init_unique_constraint_builder();
init_expression_parser();
init_primary_key_constraint_builder();
init_check_constraint_builder();
init_add_index_node();
init_create_table_add_index_builder();
CreateTableBuilder = class CreateTableBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Adds the "temporary" modifier.
*
* Use this to create a temporary table.
*/
temporary() {
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWith(this.#props.node, { temporary: true })
});
}
/**
* Adds an "on commit" statement.
*
* This can be used in conjunction with temporary tables on supported databases
* like PostgreSQL.
*/
onCommit(onCommit) {
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWith(this.#props.node, { onCommit: parseOnCommitAction(onCommit) })
});
}
/**
* Adds the "if not exists" modifier.
*
* If the table already exists, no error is thrown if this method has been called.
*/
ifNotExists() {
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWith(this.#props.node, { ifNotExists: true })
});
}
/**
* Adds a column to the table.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', (col) => col.autoIncrement().primaryKey())
* .addColumn('first_name', 'varchar(50)', (col) => col.notNull())
* .addColumn('last_name', 'varchar(255)')
* .addColumn('bank_balance', 'numeric(8, 2)')
* // You can specify any data type using the `sql` tag if the types
* // don't include it.
* .addColumn('data', sql`any_type_here`)
* .addColumn('parent_id', 'integer', (col) =>
* col.references('person.id').onDelete('cascade')
* )
* ```
*
* With this method, it's once again good to remember that Kysely just builds the
* query and doesn't provide the same API for all databases. For example, some
* databases like older MySQL don't support the `references` statement in the
* column definition. Instead foreign key constraints need to be defined in the
* `create table` query. See the next example:
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', (col) => col.primaryKey())
* .addColumn('parent_id', 'integer')
* .addForeignKeyConstraint(
* 'person_parent_id_fk',
* ['parent_id'],
* 'person',
* ['id'],
* (cb) => cb.onDelete('cascade')
* )
* .execute()
* ```
*
* Another good example is that PostgreSQL doesn't support the `auto_increment`
* keyword and you need to define an autoincrementing column for example using
* `serial`:
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'serial', (col) => col.primaryKey())
* .execute()
* ```
*/
addColumn(columnName, dataType, build = noop) {
const columnBuilder = build(new ColumnDefinitionBuilder(ColumnDefinitionNode.create(columnName, parseDataTypeExpression(dataType))));
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWithColumn(this.#props.node, columnBuilder.toOperationNode())
});
}
/**
* Adds a primary key constraint for one or more columns.
*
* The constraint name can be anything you want, but it must be unique
* across the whole database.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('first_name', 'varchar(64)')
* .addColumn('last_name', 'varchar(64)')
* .addPrimaryKeyConstraint('primary_key', ['first_name', 'last_name'])
* .execute()
* ```
*/
addPrimaryKeyConstraint(constraintName, columns, build = noop) {
const constraintBuilder = build(new PrimaryKeyConstraintBuilder(PrimaryKeyConstraintNode.create(columns, constraintName)));
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode())
});
}
/**
* Adds a unique constraint for one or more columns.
*
* The constraint name can be anything you want, but it must be unique
* across the whole database.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('first_name', 'varchar(64)')
* .addColumn('last_name', 'varchar(64)')
* .addUniqueConstraint(
* 'first_name_last_name_unique',
* ['first_name', 'last_name']
* )
* .execute()
* ```
*
* In dialects such as PostgreSQL you can specify `nulls not distinct` as follows:
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('first_name', 'varchar(64)')
* .addColumn('last_name', 'varchar(64)')
* .addUniqueConstraint(
* 'first_name_last_name_unique',
* ['first_name', 'last_name'],
* (cb) => cb.nullsNotDistinct()
* )
* .execute()
* ```
*
* In dialects such as MySQL you create unique constraints on expressions as follows:
*
* ```ts
*
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('person')
* .addColumn('first_name', 'varchar(64)')
* .addColumn('last_name', 'varchar(64)')
* .addUniqueConstraint(
* 'first_name_last_name_unique',
* [sql`(lower('first_name'))`, 'last_name']
* )
* .execute()
* ```
*/
addUniqueConstraint(constraintName, columns, build = noop) {
const uniqueConstraintBuilder = build(new UniqueConstraintNodeBuilder(UniqueConstraintNode.create(columns.map((column) => isString(column) ? ColumnNode.create(column) : parseExpression(column)), constraintName)));
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWithConstraint(this.#props.node, uniqueConstraintBuilder.toOperationNode())
});
}
/**
* Adds an index that includes one or more columns.
*
* This is only supported by some dialects like MySQL.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('first_name', 'varchar(64)')
* .addColumn('last_name', 'varchar(64)')
* .addIndex('last_name_key', ['last_name'])
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `id` integer primary key,
* `first_name` varchar(64) not null,
* `last_name` varchar(64) not null,
* index `last_name_key` (`last_name`)
* )
* ```
*/
addIndex(indexName, columns, build = noop) {
const addIndexBuilder = build(new CreateTableAddIndexBuilder(AddIndexNode.cloneWithColumns(AddIndexNode.create(indexName), columns.map((column) => isString(column) ? ColumnNode.create(column) : parseExpression(column)))));
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWithIndex(this.#props.node, addIndexBuilder.toOperationNode())
});
}
/**
* Adds a check constraint.
*
* The constraint name can be anything you want, but it must be unique
* across the whole database.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('animal')
* .addColumn('number_of_legs', 'integer')
* .addCheckConstraint('check_legs', sql`number_of_legs < 5`)
* .execute()
* ```
*/
addCheckConstraint(constraintName, checkExpression, build = noop) {
const constraintBuilder = build(new CheckConstraintBuilder(CheckConstraintNode.create(checkExpression.toOperationNode(), constraintName)));
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWithConstraint(this.#props.node, constraintBuilder.toOperationNode())
});
}
/**
* Adds a foreign key constraint.
*
* The constraint name can be anything you want, but it must be unique
* across the whole database.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('pet')
* .addColumn('owner_id', 'integer')
* .addForeignKeyConstraint(
* 'owner_id_foreign',
* ['owner_id'],
* 'person',
* ['id'],
* )
* .execute()
* ```
*
* Add constraint for multiple columns:
*
* ```ts
* await db.schema
* .createTable('pet')
* .addColumn('owner_id1', 'integer')
* .addColumn('owner_id2', 'integer')
* .addForeignKeyConstraint(
* 'owner_id_foreign',
* ['owner_id1', 'owner_id2'],
* 'person',
* ['id1', 'id2'],
* (cb) => cb.onDelete('cascade')
* )
* .execute()
* ```
*/
addForeignKeyConstraint(constraintName, columns, targetTable, targetColumns, build = noop) {
const builder = build(new ForeignKeyConstraintBuilder(ForeignKeyConstraintNode.create(columns.map(ColumnNode.create), parseTable(targetTable), targetColumns.map(ColumnNode.create), constraintName)));
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWithConstraint(this.#props.node, builder.toOperationNode())
});
}
/**
* This can be used to add any additional SQL to the front of the query __after__ the `create` keyword.
*
* Also see {@link temporary}.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('person')
* .modifyFront(sql`global temporary`)
* .addColumn('id', 'integer', col => col.primaryKey())
* .addColumn('first_name', 'varchar(64)', col => col.notNull())
* .addColumn('last_name', 'varchar(64)', col => col.notNull())
* .execute()
* ```
*
* The generated SQL (Postgres):
*
* ```sql
* create global temporary table "person" (
* "id" integer primary key,
* "first_name" varchar(64) not null,
* "last_name" varchar(64) not null
* )
* ```
*/
modifyFront(modifier) {
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWithFrontModifier(this.#props.node, modifier.toOperationNode())
});
}
/**
* This can be used to add any additional SQL to the end of the query.
*
* Also see {@link onCommit}.
*
* ### Examples
*
* ```ts
* import { sql } from 'kysely'
*
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.primaryKey())
* .addColumn('first_name', 'varchar(64)', col => col.notNull())
* .addColumn('last_name', 'varchar(64)', col => col.notNull())
* .modifyEnd(sql`collate utf8_unicode_ci`)
* .execute()
* ```
*
* The generated SQL (MySQL):
*
* ```sql
* create table `person` (
* `id` integer primary key,
* `first_name` varchar(64) not null,
* `last_name` varchar(64) not null
* ) collate utf8_unicode_ci
* ```
*/
modifyEnd(modifier) {
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWithEndModifier(this.#props.node, modifier.toOperationNode())
});
}
/**
* Allows to create table from `select` query.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('copy')
* .temporary()
* .as(db.selectFrom('person').select(['first_name', 'last_name']))
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* create temporary table "copy" as
* select "first_name", "last_name" from "person"
* ```
*/
as(expression) {
return new CreateTableBuilder({
...this.#props,
node: CreateTableNode.cloneWith(this.#props.node, { selectQuery: parseExpression(expression) })
});
}
/**
* Calls the given function passing `this` as the only argument.
*
* ### Examples
*
* ```ts
* await db.schema
* .createTable('test')
* .$call((builder) => builder.addColumn('id', 'integer'))
* .execute()
* ```
*
* This is useful for creating reusable functions that can be called with a builder.
*
* ```ts
* import { type CreateTableBuilder, sql } from 'kysely'
*
* const addDefaultColumns = (ctb: CreateTableBuilder<any, any>) => {
* return ctb
* .addColumn('id', 'integer', (col) => col.notNull())
* .addColumn('created_at', 'date', (col) =>
* col.notNull().defaultTo(sql`now()`)
* )
* .addColumn('updated_at', 'date', (col) =>
* col.notNull().defaultTo(sql`now()`)
* )
* }
*
* await db.schema
* .createTable('test')
* .$call(addDefaultColumns)
* .execute()
* ```
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/drop-index-builder.js
var DropIndexBuilder;
var init_drop_index_builder = __esmMin((() => {
init_drop_index_node();
init_table_parser();
init_object_utils();
DropIndexBuilder = class DropIndexBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Specifies the table the index was created for. This is not needed
* in all dialects.
*/
on(table) {
return new DropIndexBuilder({
...this.#props,
node: DropIndexNode.cloneWith(this.#props.node, { table: parseTable(table) })
});
}
ifExists() {
return new DropIndexBuilder({
...this.#props,
node: DropIndexNode.cloneWith(this.#props.node, { ifExists: true })
});
}
cascade() {
return new DropIndexBuilder({
...this.#props,
node: DropIndexNode.cloneWith(this.#props.node, { cascade: true })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/drop-schema-builder.js
var DropSchemaBuilder;
var init_drop_schema_builder = __esmMin((() => {
init_drop_schema_node();
init_object_utils();
DropSchemaBuilder = class DropSchemaBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
ifExists() {
return new DropSchemaBuilder({
...this.#props,
node: DropSchemaNode.cloneWith(this.#props.node, { ifExists: true })
});
}
cascade() {
return new DropSchemaBuilder({
...this.#props,
node: DropSchemaNode.cloneWith(this.#props.node, { cascade: true })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/drop-table-builder.js
var DropTableBuilder;
var init_drop_table_builder = __esmMin((() => {
init_drop_table_node();
init_object_utils();
DropTableBuilder = class DropTableBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Adds the "temporary" modifier.
*
* This is only supported by some dialects like MySQL.
*/
temporary() {
return new DropTableBuilder({
...this.#props,
node: DropTableNode.cloneWith(this.#props.node, { temporary: true })
});
}
ifExists() {
return new DropTableBuilder({
...this.#props,
node: DropTableNode.cloneWith(this.#props.node, { ifExists: true })
});
}
cascade() {
return new DropTableBuilder({
...this.#props,
node: DropTableNode.cloneWith(this.#props.node, { cascade: true })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/create-view-node.js
var CreateViewNode;
var init_create_view_node = __esmMin((() => {
init_object_utils();
init_schemable_identifier_node();
CreateViewNode = freeze({
is(node) {
return node.kind === "CreateViewNode";
},
create(name) {
return freeze({
kind: "CreateViewNode",
name: SchemableIdentifierNode.create(name)
});
},
cloneWith(createView, params) {
return freeze({
...createView,
...params
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/immediate-value/immediate-value-plugin.js
var ImmediateValuePlugin;
var init_immediate_value_plugin = __esmMin((() => {
init_immediate_value_transformer();
ImmediateValuePlugin = class {
#transformer = new ImmediateValueTransformer();
transformQuery(args) {
return this.#transformer.transformNode(args.node, args.queryId);
}
transformResult(args) {
return Promise.resolve(args.result);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/create-view-builder.js
var CreateViewBuilder;
var init_create_view_builder = __esmMin((() => {
init_object_utils();
init_create_view_node();
init_reference_parser();
init_immediate_value_plugin();
CreateViewBuilder = class CreateViewBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Adds the "temporary" modifier.
*
* Use this to create a temporary view.
*/
temporary() {
return new CreateViewBuilder({
...this.#props,
node: CreateViewNode.cloneWith(this.#props.node, { temporary: true })
});
}
materialized() {
return new CreateViewBuilder({
...this.#props,
node: CreateViewNode.cloneWith(this.#props.node, { materialized: true })
});
}
/**
* Only implemented on some dialects like SQLite. On most dialects, use {@link orReplace}.
*/
ifNotExists() {
return new CreateViewBuilder({
...this.#props,
node: CreateViewNode.cloneWith(this.#props.node, { ifNotExists: true })
});
}
orReplace() {
return new CreateViewBuilder({
...this.#props,
node: CreateViewNode.cloneWith(this.#props.node, { orReplace: true })
});
}
columns(columns) {
return new CreateViewBuilder({
...this.#props,
node: CreateViewNode.cloneWith(this.#props.node, { columns: columns.map(parseColumnName) })
});
}
/**
* Sets the select query or a `values` statement that creates the view.
*
* WARNING!
* Some dialects don't support parameterized queries in DDL statements and therefore
* the query or raw {@link sql } expression passed here is interpolated into a single
* string opening an SQL injection vulnerability. DO NOT pass unchecked user input
* into the query or raw expression passed to this method!
*/
as(query) {
const queryNode = query.withPlugin(new ImmediateValuePlugin()).toOperationNode();
return new CreateViewBuilder({
...this.#props,
node: CreateViewNode.cloneWith(this.#props.node, { as: queryNode })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/drop-view-node.js
var DropViewNode;
var init_drop_view_node = __esmMin((() => {
init_object_utils();
init_schemable_identifier_node();
DropViewNode = freeze({
is(node) {
return node.kind === "DropViewNode";
},
create(name) {
return freeze({
kind: "DropViewNode",
name: SchemableIdentifierNode.create(name)
});
},
cloneWith(dropView, params) {
return freeze({
...dropView,
...params
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/drop-view-builder.js
var DropViewBuilder;
var init_drop_view_builder = __esmMin((() => {
init_object_utils();
init_drop_view_node();
DropViewBuilder = class DropViewBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
materialized() {
return new DropViewBuilder({
...this.#props,
node: DropViewNode.cloneWith(this.#props.node, { materialized: true })
});
}
ifExists() {
return new DropViewBuilder({
...this.#props,
node: DropViewNode.cloneWith(this.#props.node, { ifExists: true })
});
}
cascade() {
return new DropViewBuilder({
...this.#props,
node: DropViewNode.cloneWith(this.#props.node, { cascade: true })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/create-type-node.js
var CreateTypeNode;
var init_create_type_node = __esmMin((() => {
init_object_utils();
init_value_list_node();
init_value_node();
CreateTypeNode = freeze({
is(node) {
return node.kind === "CreateTypeNode";
},
create(name) {
return freeze({
kind: "CreateTypeNode",
name
});
},
cloneWithEnum(createType, values) {
return freeze({
...createType,
enum: ValueListNode.create(values.map(ValueNode.createImmediate))
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/create-type-builder.js
var CreateTypeBuilder;
var init_create_type_builder = __esmMin((() => {
init_object_utils();
init_create_type_node();
CreateTypeBuilder = class CreateTypeBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
/**
* Creates an enum type.
*
* ### Examples
*
* ```ts
* db.schema.createType('species').asEnum(['cat', 'dog', 'frog'])
* ```
*/
asEnum(values) {
return new CreateTypeBuilder({
...this.#props,
node: CreateTypeNode.cloneWithEnum(this.#props.node, values)
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/drop-type-node.js
var DropTypeNode;
var init_drop_type_node = __esmMin((() => {
init_object_utils();
DropTypeNode = freeze({
is(node) {
return node.kind === "DropTypeNode";
},
create(names) {
if (!Array.isArray(names)) names = [names];
return freeze({
kind: "DropTypeNode",
name: names[0],
additionalNames: names.slice(1)
});
},
cloneWith(dropType, params) {
return freeze({
...dropType,
...params
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/drop-type-builder.js
var DropTypeBuilder;
var init_drop_type_builder = __esmMin((() => {
init_drop_type_node();
init_object_utils();
DropTypeBuilder = class DropTypeBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Adds `if exists` to the query.
*/
ifExists() {
return new DropTypeBuilder({
...this.#props,
node: DropTypeNode.cloneWith(this.#props.node, { ifExists: true })
});
}
/**
* Adds `cascade` to the query.
*/
cascade() {
return new DropTypeBuilder({
...this.#props,
node: DropTypeNode.cloneWith(this.#props.node, { cascade: true })
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/identifier-parser.js
function parseSchemableIdentifier(id) {
const SCHEMA_SEPARATOR = ".";
if (id.includes(SCHEMA_SEPARATOR)) {
const parts = id.split(SCHEMA_SEPARATOR).map(trim);
if (parts.length === 2) return SchemableIdentifierNode.createWithSchema(parts[0], parts[1]);
else throw new Error(`invalid schemable identifier ${id}`);
} else return SchemableIdentifierNode.create(id);
}
function parseSchemableIdentifierArray(id) {
if (!Array.isArray(id)) id = [id];
return id.map(parseSchemableIdentifier);
}
function trim(str) {
return str.trim();
}
var init_identifier_parser = __esmMin((() => {
init_schemable_identifier_node();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/refresh-materialized-view-node.js
var RefreshMaterializedViewNode;
var init_refresh_materialized_view_node = __esmMin((() => {
init_object_utils();
init_schemable_identifier_node();
RefreshMaterializedViewNode = freeze({
is(node) {
return node.kind === "RefreshMaterializedViewNode";
},
create(name) {
return freeze({
kind: "RefreshMaterializedViewNode",
name: SchemableIdentifierNode.create(name)
});
},
cloneWith(createView, params) {
return freeze({
...createView,
...params
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/refresh-materialized-view-builder.js
var RefreshMaterializedViewBuilder;
var init_refresh_materialized_view_builder = __esmMin((() => {
init_object_utils();
init_refresh_materialized_view_node();
RefreshMaterializedViewBuilder = class RefreshMaterializedViewBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Adds the "concurrently" modifier.
*
* Use this to refresh the view without locking out concurrent selects on the materialized view.
*
* WARNING!
* This cannot be used with the "with no data" modifier.
*/
concurrently() {
return new RefreshMaterializedViewBuilder({
...this.#props,
node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {
concurrently: true,
withNoData: false
})
});
}
/**
* Adds the "with data" modifier.
*
* If specified (or defaults) the backing query is executed to provide the new data, and the materialized view is left in a scannable state
*/
withData() {
return new RefreshMaterializedViewBuilder({
...this.#props,
node: RefreshMaterializedViewNode.cloneWith(this.#props.node, { withNoData: false })
});
}
/**
* Adds the "with no data" modifier.
*
* If specified, no new data is generated and the materialized view is left in an unscannable state.
*
* WARNING!
* This cannot be used with the "concurrently" modifier.
*/
withNoData() {
return new RefreshMaterializedViewBuilder({
...this.#props,
node: RefreshMaterializedViewNode.cloneWith(this.#props.node, {
withNoData: true,
concurrently: false
})
});
}
/**
* Simply calls the provided function passing `this` as the only argument. `$call` returns
* what the provided function returns.
*/
$call(func) {
return func(this);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
async execute(options) {
await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/alter-type-node.js
var AlterTypeNode;
var init_alter_type_node = __esmMin((() => {
init_object_utils();
AlterTypeNode = freeze({
is(node) {
return node.kind === "AlterTypeNode";
},
create(name) {
return freeze({
kind: "AlterTypeNode",
name
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/add-value-node.js
var AddValueNode;
var init_add_value_node = __esmMin((() => {
init_object_utils();
AddValueNode = freeze({
is(node) {
return node.kind === "AddValueNode";
},
create(value) {
return freeze({
kind: "AddValueNode",
value
});
},
cloneWith(node, props) {
return freeze({
...node,
...props
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-finalizer.js
var QueryFinalizer;
var init_query_finalizer = __esmMin((() => {
init_object_utils();
QueryFinalizer = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
toOperationNode() {
return this.#props.executor.transformQuery(this.#props.node, this.#props.queryId);
}
/**
* Compiles the query.
*/
compile() {
return this.#props.executor.compileQuery(this.toOperationNode(), this.#props.queryId);
}
/**
* Executes the query.
*/
async execute(options) {
return await this.#props.executor.executeQuery(this.compile(), options);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/alter-type-add-value-builder.js
var _a$2, AlterTypeAddValueBuilder;
var init_alter_type_add_value_builder = __esmMin((() => {
init_add_value_node();
init_value_node();
init_alter_type_node();
init_query_finalizer();
AlterTypeAddValueBuilder = class extends QueryFinalizer {
#props;
constructor(props) {
super(props);
this.#props = props;
}
/**
* Adds an `if not exists` clause.
*/
ifNotExists() {
return new _a$2({
...this.#props,
node: AlterTypeNode.cloneWith(this.#props.node, { addValue: AddValueNode.cloneWith(this.#props.node.addValue, { ifNotExists: true }) })
});
}
/**
* Sets a `before <value>` clause.
*/
before(neighborValue) {
return this.#setNeighbor(neighborValue, true);
}
/**
* Sets an `after <value>` clause.
*/
after(neighborValue) {
return this.#setNeighbor(neighborValue, false);
}
#setNeighbor(neighborValue, isBefore) {
return new _a$2({
...this.#props,
node: AlterTypeNode.cloneWith(this.#props.node, { addValue: AddValueNode.cloneWith(this.#props.node.addValue, {
isBefore,
neighborValue: ValueNode.createImmediate(neighborValue)
}) })
});
}
};
_a$2 = AlterTypeAddValueBuilder;
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/rename-value-node.js
var RenameValueNode;
var init_rename_value_node = __esmMin((() => {
init_object_utils();
RenameValueNode = freeze({
is(node) {
return node.kind === "RenameValueNode";
},
create(oldValue, newValue) {
return freeze({
kind: "RenameValueNode",
oldValue,
newValue
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/alter-type-builder.js
var AlterTypeBuilder;
var init_alter_type_builder = __esmMin((() => {
init_object_utils();
init_alter_type_node();
init_identifier_node();
init_alter_type_add_value_builder();
init_add_value_node();
init_value_node();
init_query_finalizer();
init_rename_value_node();
AlterTypeBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
/**
* Adds a new value to an enum type.
*/
addValue(value) {
return new AlterTypeAddValueBuilder({
...this.#props,
node: AlterTypeNode.cloneWith(this.#props.node, { addValue: AddValueNode.create(ValueNode.createImmediate(value)) })
});
}
/**
* Rename the type.
*/
renameTo(newName) {
return new QueryFinalizer({
...this.#props,
node: AlterTypeNode.cloneWith(this.#props.node, { renameTo: IdentifierNode.create(newName) })
});
}
/**
* Renames a value of an enum type.
*/
renameValue(oldValue, newValue) {
return new QueryFinalizer({
...this.#props,
node: AlterTypeNode.cloneWith(this.#props.node, { renameValue: RenameValueNode.create(ValueNode.createImmediate(oldValue), ValueNode.createImmediate(newValue)) })
});
}
/**
* Changes the type's schema.
*/
setSchema(schema) {
return new QueryFinalizer({
...this.#props,
node: AlterTypeNode.cloneWith(this.#props.node, { setSchema: IdentifierNode.create(schema) })
});
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/schema/schema-module.js
var SchemaModule;
var init_schema_module = __esmMin((() => {
init_alter_table_node();
init_create_index_node();
init_create_schema_node();
init_create_table_node();
init_drop_index_node();
init_drop_schema_node();
init_drop_table_node();
init_table_parser();
init_alter_table_builder();
init_create_index_builder();
init_create_schema_builder();
init_create_table_builder();
init_drop_index_builder();
init_drop_schema_builder();
init_drop_table_builder();
init_query_id();
init_with_schema_plugin();
init_create_view_builder();
init_create_view_node();
init_drop_view_builder();
init_drop_view_node();
init_create_type_builder();
init_drop_type_builder();
init_create_type_node();
init_drop_type_node();
init_identifier_parser();
init_refresh_materialized_view_builder();
init_refresh_materialized_view_node();
init_alter_type_builder();
init_alter_type_node();
SchemaModule = class SchemaModule {
#executor;
constructor(executor) {
this.#executor = executor;
}
/**
* Create a new table.
*
* ### Examples
*
* This example creates a new table with columns `id`, `first_name`,
* `last_name` and `gender`:
*
* ```ts
* await db.schema
* .createTable('person')
* .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
* .addColumn('first_name', 'varchar', col => col.notNull())
* .addColumn('last_name', 'varchar', col => col.notNull())
* .addColumn('gender', 'varchar')
* .execute()
* ```
*
* This example creates a table with a foreign key. Not all database
* engines support column-level foreign key constraint definitions.
* For example if you are using MySQL 5.X see the next example after
* this one.
*
* ```ts
* await db.schema
* .createTable('pet')
* .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
* .addColumn('owner_id', 'integer', col => col
* .references('person.id')
* .onDelete('cascade')
* )
* .execute()
* ```
*
* This example adds a foreign key constraint for a columns just
* like the previous example, but using a table-level statement.
* On MySQL 5.X you need to define foreign key constraints like
* this:
*
* ```ts
* await db.schema
* .createTable('pet')
* .addColumn('id', 'integer', col => col.primaryKey().autoIncrement())
* .addColumn('owner_id', 'integer')
* .addForeignKeyConstraint(
* 'pet_owner_id_foreign', ['owner_id'], 'person', ['id'],
* (constraint) => constraint.onDelete('cascade')
* )
* .execute()
* ```
*/
createTable(table) {
return new CreateTableBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: CreateTableNode.create(parseTable(table))
});
}
/**
* Drop a table.
*
* ### Examples
*
* ```ts
* await db.schema
* .dropTable('person')
* .execute()
* ```
*/
dropTable(table) {
return new DropTableBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: DropTableNode.create(parseTable(table))
});
}
/**
* Create a new index.
*
* ### Examples
*
* ```ts
* await db.schema
* .createIndex('person_full_name_unique_index')
* .on('person')
* .columns(['first_name', 'last_name'])
* .execute()
* ```
*/
createIndex(indexName) {
return new CreateIndexBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: CreateIndexNode.create(indexName)
});
}
/**
* Drop an index.
*
* ### Examples
*
* ```ts
* await db.schema
* .dropIndex('person_full_name_unique_index')
* .execute()
* ```
*/
dropIndex(indexName) {
return new DropIndexBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: DropIndexNode.create(indexName)
});
}
/**
* Create a new schema.
*
* ### Examples
*
* ```ts
* await db.schema
* .createSchema('some_schema')
* .execute()
* ```
*/
createSchema(schema) {
return new CreateSchemaBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: CreateSchemaNode.create(schema)
});
}
/**
* Drop a schema.
*
* ### Examples
*
* ```ts
* await db.schema
* .dropSchema('some_schema')
* .execute()
* ```
*/
dropSchema(schema) {
return new DropSchemaBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: DropSchemaNode.create(schema)
});
}
/**
* Alter a table.
*
* ### Examples
*
* ```ts
* await db.schema
* .alterTable('person')
* .alterColumn('first_name', (ac) => ac.setDataType('text'))
* .execute()
* ```
*/
alterTable(table) {
return new AlterTableBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: AlterTableNode.create(parseTable(table))
});
}
/**
* Create a new view.
*
* ### Examples
*
* ```ts
* await db.schema
* .createView('dogs')
* .orReplace()
* .as(db.selectFrom('pet').selectAll().where('species', '=', 'dog'))
* .execute()
* ```
*/
createView(viewName) {
return new CreateViewBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: CreateViewNode.create(viewName)
});
}
/**
* Refresh a materialized view.
*
* ### Examples
*
* ```ts
* await db.schema
* .refreshMaterializedView('my_view')
* .concurrently()
* .execute()
* ```
*/
refreshMaterializedView(viewName) {
return new RefreshMaterializedViewBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: RefreshMaterializedViewNode.create(viewName)
});
}
/**
* Drop a view.
*
* ### Examples
*
* ```ts
* await db.schema
* .dropView('dogs')
* .ifExists()
* .execute()
* ```
*/
dropView(viewName) {
return new DropViewBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: DropViewNode.create(viewName)
});
}
/**
* Create a new type.
*
* Only some dialects like PostgreSQL have user-defined types.
*
* ### Examples
*
* ```ts
* await db.schema
* .createType('species')
* .asEnum(['dog', 'cat', 'frog'])
* .execute()
* ```
*/
createType(typeName) {
return new CreateTypeBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: CreateTypeNode.create(parseSchemableIdentifier(typeName))
});
}
/**
* Alter a type. Rename it, change schema or add/rename enum type values.
*
* Only some dialects like PostgreSQL have user-defined types.
*
* ```ts
* await db.schema
* .alterType('species')
* .addValue('capybara')
* .execute()
* ```
*/
alterType(name) {
return new AlterTypeBuilder({
executor: this.#executor,
node: AlterTypeNode.create(parseSchemableIdentifier(name)),
queryId: createQueryId()
});
}
/**
* Drop a type.
*
* Only some dialects like PostgreSQL have user-defined types.
*
* ### Examples
*
* ```ts
* await db.schema
* .dropType('species')
* .ifExists()
* .execute()
* ```
*
* You can also provide multiple type names:
*
* ```ts
* await db.schema
* .dropType(['species', 'colors'])
* .ifExists()
* .cascade()
* .execute()
* ```
*/
dropType(typeName) {
return new DropTypeBuilder({
queryId: createQueryId(),
executor: this.#executor,
node: DropTypeNode.create(parseSchemableIdentifierArray(typeName))
});
}
/**
* Returns a copy of this schema module with the given plugin installed.
*/
withPlugin(plugin) {
return new SchemaModule(this.#executor.withPlugin(plugin));
}
/**
* Returns a copy of this schema module without any plugins.
*/
withoutPlugins() {
return new SchemaModule(this.#executor.withoutPlugins());
}
/**
* See {@link QueryCreator.withSchema}
*/
withSchema(schema) {
return new SchemaModule(this.#executor.withPluginAtFront(new WithSchemaPlugin(schema)));
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dynamic/dynamic.js
var DynamicModule;
var init_dynamic = __esmMin((() => {
init_dynamic_reference_builder();
init_dynamic_table_builder();
DynamicModule = class {
/**
* Creates a dynamic reference to a column that is not know at compile time.
*
* Kysely is built in a way that by default you can't refer to tables or columns
* that are not actually visible in the current query and context. This is all
* done by TypeScript at compile time, which means that you need to know the
* columns and tables at compile time. This is not always the case of course.
*
* This method is meant to be used in those cases where the column names
* come from the user input or are not otherwise known at compile time.
*
* WARNING! Unlike values, column names are not escaped by the database engine
* or Kysely and if you pass in unchecked column names using this method, you
* create an SQL injection vulnerability. Always __always__ validate the user
* input before passing it to this method.
*
* There are couple of examples below for some use cases, but you can pass
* `ref` to other methods as well. If the types allow you to pass a `ref`
* value to some place, it should work.
*
* ### Examples
*
* Filter by a column not know at compile time:
*
* ```ts
* async function someQuery(filterColumn: string, filterValue: string) {
* const { ref } = db.dynamic
*
* return await db
* .selectFrom('person')
* .selectAll()
* .where(ref(filterColumn), '=', filterValue)
* .execute()
* }
*
* someQuery('first_name', 'Arnold')
* someQuery('person.last_name', 'Aniston')
* ```
*
* Order by a column not know at compile time:
*
* ```ts
* async function someQuery(orderBy: string) {
* const { ref } = db.dynamic
*
* return await db
* .selectFrom('person')
* .select('person.first_name as fn')
* .orderBy(ref(orderBy))
* .execute()
* }
*
* someQuery('fn')
* ```
*
* In this example we add selections dynamically:
*
* ```ts
* const { ref } = db.dynamic
*
* // Some column name provided by the user. Value not known at compile time.
* const columnFromUserInput: PossibleColumns = 'birthdate';
*
* // A type that lists all possible values `columnFromUserInput` can have.
* // You can use `keyof Person` if any column of an interface is allowed.
* type PossibleColumns = 'last_name' | 'first_name' | 'birthdate'
*
* const [person] = await db.selectFrom('person')
* .select([
* ref<PossibleColumns>(columnFromUserInput),
* 'id'
* ])
* .execute()
*
* // The resulting type contains all `PossibleColumns` as optional fields
* // because we cannot know which field was actually selected before
* // running the code.
* const lastName: string | null | undefined = person?.last_name
* const firstName: string | undefined = person?.first_name
* const birthDate: Date | null | undefined = person?.birthdate
*
* // The result type also contains the compile time selection `id`.
* person?.id
* ```
*/
ref(reference) {
return new DynamicReferenceBuilder(reference);
}
/**
* Creates a table reference to a table that's not fully known at compile time.
*
* The type `T` is allowed to be a union of multiple tables.
*
* <!-- siteExample("select", "Generic find query", 130) -->
*
* A generic type-safe helper function for finding a row by a column value:
*
* ```ts
* import { SelectType } from 'kysely'
* import { Database } from 'type-editor'
*
* async function getRowByColumn<
* T extends keyof Database,
* C extends keyof Database[T] & string,
* V extends SelectType<Database[T][C]>,
* >(t: T, c: C, v: V) {
* // We need to use the dynamic module since the table name
* // is not known at compile time.
* const { table, ref } = db.dynamic
*
* return await db
* .selectFrom(table(t).as('t'))
* .selectAll()
* .where(ref(c), '=', v)
* .orderBy('t.id')
* .executeTakeFirstOrThrow()
* }
*
* const person = await getRowByColumn('person', 'first_name', 'Arnold')
* ```
*/
table(table) {
return new DynamicTableBuilder(table);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/driver/default-connection-provider.js
var DefaultConnectionProvider;
var init_default_connection_provider = __esmMin((() => {
DefaultConnectionProvider = class {
#driver;
constructor(driver) {
this.#driver = driver;
}
async provideConnection(consumer, options) {
const connection = await this.#driver.acquireConnection(options);
try {
return await consumer(connection);
} finally {
await this.#driver.releaseConnection(connection, options);
}
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-executor/default-query-executor.js
var DefaultQueryExecutor;
var init_default_query_executor = __esmMin((() => {
init_query_executor_base();
DefaultQueryExecutor = class DefaultQueryExecutor extends QueryExecutorBase {
#compiler;
#adapter;
#connectionProvider;
constructor(compiler, adapter, connectionProvider, plugins = []) {
super(plugins);
this.#compiler = compiler;
this.#adapter = adapter;
this.#connectionProvider = connectionProvider;
}
get adapter() {
return this.#adapter;
}
compileQuery(node, queryId) {
return this.#compiler.compileQuery(node, queryId);
}
provideConnection(consumer, options) {
return this.#connectionProvider.provideConnection(consumer, options);
}
withPlugins(plugins) {
return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, ...plugins]);
}
withPlugin(plugin) {
return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [...this.plugins, plugin]);
}
withPluginAtFront(plugin) {
return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, [plugin, ...this.plugins]);
}
withConnectionProvider(connectionProvider) {
return new DefaultQueryExecutor(this.#compiler, this.#adapter, connectionProvider, [...this.plugins]);
}
withoutPlugins() {
return new DefaultQueryExecutor(this.#compiler, this.#adapter, this.#connectionProvider, []);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/performance-now.js
function performanceNow() {
if (typeof performance !== "undefined" && isFunction(performance.now)) return performance.now();
else return Date.now();
}
var init_performance_now = __esmMin((() => {
init_object_utils();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/driver/connection-mutex.js
var ConnectionMutex;
var init_connection_mutex = __esmMin((() => {
ConnectionMutex = class {
#promise;
#resolve;
async obtainLock() {
while (this.#promise) await this.#promise;
this.#promise = new Promise((resolve) => {
this.#resolve = resolve;
});
}
releaseLock() {
const resolve = this.#resolve;
this.#promise = void 0;
this.#resolve = void 0;
resolve?.();
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/driver/runtime-driver.js
var RuntimeDriver;
var init_runtime_driver = __esmMin((() => {
init_abort();
init_performance_now();
init_connection_mutex();
RuntimeDriver = class {
#driver;
#log;
#initPromise;
#initDone;
#destroyPromise;
#connections = /* @__PURE__ */ new WeakSet();
#connectionMutex;
constructor(driver, adapter, log) {
this.#driver = driver;
this.#initDone = false;
this.#log = log;
if (adapter.supportsMultipleConnections === false) this.#connectionMutex = new ConnectionMutex();
}
async init(options) {
if (this.#destroyPromise) throw new Error("driver has already been destroyed");
this.#initPromise ??= this.#driver.init(options).then(() => {
this.#initDone = true;
}).catch((reason) => {
this.#initPromise = void 0;
throw reason;
});
await waitOrAbort(this.#initPromise, options?.signal, "init");
}
async acquireConnection(options) {
if (this.#destroyPromise) throw new Error("driver has already been destroyed");
if (!this.#initDone) await this.init(options);
if (this.#connectionMutex) {
const lockPromise = this.#connectionMutex.obtainLock();
await waitOrAbort(lockPromise, options?.signal, "acquireConnection:mutex", () => lockPromise.then(() => this.#connectionMutex?.releaseLock()));
}
const connectionPromise = this.#driver.acquireConnection(options);
const connection = await waitOrAbort(connectionPromise, options?.signal, "acquireConnection:acquire", () => connectionPromise?.then((connection) => this.releaseConnection(connection).catch(printBackgroundFail("driver.releaseConnection"))).catch(printBackgroundFail("driver.acquireConnection")));
if (!this.#connections.has(connection)) {
if (this.#needsLogging()) this.#addLogging(connection);
this.#connections.add(connection);
}
return connection;
}
async releaseConnection(connection, options) {
await this.#driver.releaseConnection(connection, options);
this.#connectionMutex?.releaseLock();
}
async beginTransaction(connection, settings) {
return await this.#driver.beginTransaction(connection, settings);
}
async commitTransaction(connection) {
return await this.#driver.commitTransaction(connection);
}
async rollbackTransaction(connection) {
return await this.#driver.rollbackTransaction(connection);
}
async savepoint(connection, savepointName, compileQuery) {
if (this.#driver.savepoint) return await this.#driver.savepoint(connection, savepointName, compileQuery);
throw new Error("The `savepoint` method is not supported by this driver");
}
async rollbackToSavepoint(connection, savepointName, compileQuery) {
if (this.#driver.rollbackToSavepoint) return await this.#driver.rollbackToSavepoint(connection, savepointName, compileQuery);
throw new Error("The `rollbackToSavepoint` method is not supported by this driver");
}
async releaseSavepoint(connection, savepointName, compileQuery) {
if (this.#driver.releaseSavepoint) return await this.#driver.releaseSavepoint(connection, savepointName, compileQuery);
throw new Error("The `releaseSavepoint` method is not supported by this driver");
}
async destroy(options) {
if (!this.#initPromise) return;
await waitOrAbort(this.#initPromise, options?.signal, "destroy:initPromise");
this.#destroyPromise ??= this.#driver.destroy(options).catch((reason) => {
this.#destroyPromise = void 0;
throw reason;
});
await waitOrAbort(this.#destroyPromise, options?.signal, "destroy");
}
#needsLogging() {
return this.#log.isLevelEnabled("query") || this.#log.isLevelEnabled("error");
}
#addLogging(connection) {
const executeQuery = connection.executeQuery;
const streamQuery = connection.streamQuery;
const dis = this;
connection.executeQuery = async (compiledQuery, options) => {
let caughtError;
const startTime = performanceNow();
try {
return await executeQuery.call(connection, compiledQuery, options);
} catch (error) {
caughtError = error;
await dis.#logError(error, compiledQuery, startTime);
throw error;
} finally {
if (!caughtError) await dis.#logQuery(compiledQuery, startTime);
}
};
connection.streamQuery = async function* (compiledQuery, chunkSize, options) {
let caughtError;
const startTime = performanceNow();
try {
for await (const result of streamQuery.call(connection, compiledQuery, chunkSize, options)) yield result;
} catch (error) {
caughtError = error;
await dis.#logError(error, compiledQuery, startTime);
throw error;
} finally {
if (!caughtError) await dis.#logQuery(compiledQuery, startTime, true);
}
};
}
async #logError(error, compiledQuery, startTime) {
await this.#log.error(() => ({
level: "error",
error,
query: compiledQuery,
queryDurationMillis: this.#calculateDurationMillis(startTime)
}));
}
async #logQuery(compiledQuery, startTime, isStream = false) {
await this.#log.query(() => ({
level: "query",
isStream,
query: compiledQuery,
queryDurationMillis: this.#calculateDurationMillis(startTime)
}));
}
#calculateDurationMillis(startTime) {
return performanceNow() - startTime;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/driver/single-connection-provider.js
var ignoreError, SingleConnectionProvider;
var init_single_connection_provider = __esmMin((() => {
ignoreError = () => {};
SingleConnectionProvider = class {
#connection;
#runningPromise;
constructor(connection) {
this.#connection = connection;
}
async provideConnection(consumer) {
while (this.#runningPromise) await this.#runningPromise.catch(ignoreError);
this.#runningPromise = this.#run(consumer).finally(() => {
this.#runningPromise = void 0;
});
return this.#runningPromise;
}
async #run(runner) {
return await runner(this.#connection);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/driver/driver.js
function validateTransactionSettings(settings) {
if (settings.accessMode && !TRANSACTION_ACCESS_MODES.includes(settings.accessMode)) throw new Error(`invalid transaction access mode ${settings.accessMode}`);
if (settings.isolationLevel && !TRANSACTION_ISOLATION_LEVELS.includes(settings.isolationLevel)) throw new Error(`invalid transaction isolation level ${settings.isolationLevel}`);
}
var TRANSACTION_ACCESS_MODES, TRANSACTION_ISOLATION_LEVELS;
var init_driver = __esmMin((() => {
TRANSACTION_ACCESS_MODES = ["read only", "read write"];
TRANSACTION_ISOLATION_LEVELS = [
"read uncommitted",
"read committed",
"repeatable read",
"serializable",
"snapshot"
];
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/log.js
function defaultLogger(event) {
if (event.level === "query") {
const prefix = `kysely:query:${event.isStream ? "stream:" : ""}`;
console.log(`${prefix} ${event.query.sql}`);
console.log(`${prefix} duration: ${event.queryDurationMillis.toFixed(1)}ms`);
} else if (event.level === "error") {
if (event.error instanceof Error) console.error(`kysely:error: ${event.error.stack ?? event.error.message}`);
else console.error(`kysely:error: ${JSON.stringify({
error: event.error,
query: event.query.sql,
queryDurationMillis: event.queryDurationMillis
})}`);
}
}
var logLevels, Log;
var init_log = __esmMin((() => {
init_object_utils();
logLevels = ["query", "error"];
freeze(logLevels);
Log = class {
#levels;
#logger;
constructor(config) {
if (isFunction(config)) {
this.#logger = config;
this.#levels = freeze({
query: true,
error: true
});
} else {
this.#logger = defaultLogger;
this.#levels = freeze({
query: config.includes("query"),
error: config.includes("error")
});
}
}
isLevelEnabled(level) {
return this.#levels[level];
}
async query(getEvent) {
if (this.#levels.query) await this.#logger(getEvent());
}
async error(getEvent) {
if (this.#levels.error) await this.#logger(getEvent());
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/util/compilable.js
function isCompilable(value) {
return isObject$1(value) && isFunction(value.compile);
}
var init_compilable = __esmMin((() => {
init_object_utils();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/kysely.js
function isKyselyProps(obj) {
return isObject$1(obj) && isObject$1(obj.config) && isObject$1(obj.driver) && isObject$1(obj.executor) && isObject$1(obj.dialect);
}
function assertNotCommittedOrRolledBack(state) {
if (state.isCommitted) throw new Error("Transaction is already committed");
if (state.isRolledBack) throw new Error("Transaction is already rolled back");
}
var Kysely, Transaction, ConnectionBuilder, TransactionBuilder, ControlledTransactionBuilder, ControlledTransaction, Command, NotCommittedOrRolledBackAssertingExecutor;
var init_kysely = __esmMin((() => {
init_schema_module();
init_dynamic();
init_default_connection_provider();
init_query_creator();
init_default_query_executor();
init_object_utils();
init_runtime_driver();
init_single_connection_provider();
init_driver();
init_function_module();
init_log();
init_query_id();
init_compilable();
init_case_builder();
init_case_node();
init_expression_parser();
init_with_schema_plugin();
init_provide_controlled_connection();
Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
Kysely = class Kysely extends QueryCreator {
#props;
constructor(args) {
let superProps;
let props;
if (isKyselyProps(args)) {
superProps = { executor: args.executor };
props = { ...args };
} else {
const dialect = args.dialect;
const driver = dialect.createDriver();
const compiler = dialect.createQueryCompiler();
const adapter = dialect.createAdapter();
const log = new Log(args.log ?? []);
const runtimeDriver = new RuntimeDriver(driver, adapter, log);
const connectionProvider = new DefaultConnectionProvider(runtimeDriver);
const executor = new DefaultQueryExecutor(compiler, adapter, connectionProvider, args.plugins ?? []);
superProps = { executor };
props = {
config: args,
executor,
dialect,
driver: runtimeDriver
};
}
super(superProps);
this.#props = freeze(props);
}
/**
* Returns the {@link SchemaModule} module for building database schema.
*/
get schema() {
return new SchemaModule(this.#props.executor);
}
/**
* Returns a the {@link DynamicModule} module.
*
* The {@link DynamicModule} module can be used to bypass strict typing and
* passing in dynamic values for the queries.
*/
get dynamic() {
return new DynamicModule();
}
/**
* Returns a {@link DatabaseIntrospector | database introspector}.
*/
get introspection() {
return this.#props.dialect.createIntrospector(this.withoutPlugins());
}
case(value) {
return new CaseBuilder({ node: CaseNode.create(isUndefined(value) ? void 0 : parseExpression(value)) });
}
/**
* Returns a {@link FunctionModule} that can be used to write somewhat type-safe function
* calls.
*
* ```ts
* const { count } = db.fn
*
* await db.selectFrom('person')
* .innerJoin('pet', 'pet.owner_id', 'person.id')
* .select([
* 'id',
* count('pet.id').as('person_count'),
* ])
* .groupBy('person.id')
* .having(count('pet.id'), '>', 10)
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "person"."id", count("pet"."id") as "person_count"
* from "person"
* inner join "pet" on "pet"."owner_id" = "person"."id"
* group by "person"."id"
* having count("pet"."id") > $1
* ```
*
* Why "somewhat" type-safe? Because the function calls are not bound to the
* current query context. They allow you to reference columns and tables that
* are not in the current query. E.g. remove the `innerJoin` from the previous
* query and TypeScript won't even complain.
*
* If you want to make the function calls fully type-safe, you can use the
* {@link ExpressionBuilder.fn} getter for a query context-aware, stricter {@link FunctionModule}.
*
* ```ts
* await db.selectFrom('person')
* .innerJoin('pet', 'pet.owner_id', 'person.id')
* .select((eb) => [
* 'person.id',
* eb.fn.count('pet.id').as('pet_count')
* ])
* .groupBy('person.id')
* .having((eb) => eb.fn.count('pet.id'), '>', 10)
* .execute()
* ```
*/
get fn() {
return createFunctionModule();
}
/**
* Creates a {@link TransactionBuilder} that can be used to run queries inside a transaction.
*
* The returned {@link TransactionBuilder} can be used to configure the transaction. The
* {@link TransactionBuilder.execute} method can then be called to run the transaction.
* {@link TransactionBuilder.execute} takes a function that is run inside the
* transaction. If the function throws an exception,
* 1. the exception is caught,
* 2. the transaction is rolled back, and
* 3. the exception is thrown again.
* Otherwise the transaction is committed.
*
* The callback function passed to the {@link TransactionBuilder.execute | execute}
* method gets the transaction object as its only argument. The transaction is
* of type {@link Transaction} which inherits {@link Kysely}. Any query
* started through the transaction object is executed inside the transaction.
*
* To run a controlled transaction, allowing you to commit and rollback manually,
* use {@link startTransaction} instead.
*
* ### Examples
*
* <!-- siteExample("transactions", "Simple transaction", 10) -->
*
* This example inserts two rows in a transaction. If an exception is thrown inside
* the callback passed to the `execute` method,
* 1. the exception is caught,
* 2. the transaction is rolled back, and
* 3. the exception is thrown again.
* Otherwise the transaction is committed.
*
* ```ts
* const catto = await db.transaction().execute(async (trx) => {
* const jennifer = await trx.insertInto('person')
* .values({
* first_name: 'Jennifer',
* last_name: 'Aniston',
* age: 40,
* })
* .returning('id')
* .executeTakeFirstOrThrow()
*
* return await trx.insertInto('pet')
* .values({
* owner_id: jennifer.id,
* name: 'Catto',
* species: 'cat',
* is_favorite: false,
* })
* .returningAll()
* .executeTakeFirst()
* })
* ```
*
* Setting the isolation level:
*
* ```ts
* import type { Kysely } from 'kysely'
*
* await db
* .transaction()
* .setIsolationLevel('serializable')
* .execute(async (trx) => {
* await doStuff(trx)
* })
*
* async function doStuff(kysely: typeof db) {
* // ...
* }
* ```
*/
transaction() {
return new TransactionBuilder({ ...this.#props });
}
/**
* Creates a {@link ControlledTransactionBuilder} that can be used to run queries inside a controlled transaction.
*
* The returned {@link ControlledTransactionBuilder} can be used to configure the transaction.
* The {@link ControlledTransactionBuilder.execute} method can then be called
* to start the transaction and return a {@link ControlledTransaction}.
*
* A {@link ControlledTransaction} allows you to commit and rollback manually,
* execute savepoint commands. It extends {@link Transaction} which extends {@link Kysely},
* so you can run queries inside the transaction. Once the transaction is committed,
* or rolled back, it can't be used anymore - all queries will throw an error.
* This is to prevent accidentally running queries outside the transaction - where
* atomicity is not guaranteed anymore.
*
* ### Examples
*
* <!-- siteExample("transactions", "Controlled transaction", 11) -->
*
* A controlled transaction allows you to commit and rollback manually, execute
* savepoint commands, and queries in general.
*
* In this example we start a transaction, use it to insert two rows and then commit
* the transaction. If an error is thrown, we catch it and rollback the transaction.
*
* ```ts
* const trx = await db.startTransaction().execute()
*
* try {
* const jennifer = await trx.insertInto('person')
* .values({
* first_name: 'Jennifer',
* last_name: 'Aniston',
* age: 40,
* })
* .returning('id')
* .executeTakeFirstOrThrow()
*
* const catto = await trx.insertInto('pet')
* .values({
* owner_id: jennifer.id,
* name: 'Catto',
* species: 'cat',
* is_favorite: false,
* })
* .returningAll()
* .executeTakeFirstOrThrow()
*
* await trx.commit().execute()
*
* // ...
* } catch (error) {
* await trx.rollback().execute()
* }
* ```
*
* <!-- siteExample("transactions", "Controlled transaction /w savepoints", 12) -->
*
* A controlled transaction allows you to commit and rollback manually, execute
* savepoint commands, and queries in general.
*
* In this example we start a transaction, insert a person, create a savepoint,
* try inserting a toy and a pet, and if an error is thrown, we rollback to the
* savepoint. Eventually we release the savepoint, insert an audit record and
* commit the transaction. If an error is thrown, we catch it and rollback the
* transaction.
*
* ```ts
* const trx = await db.startTransaction().execute()
*
* try {
* const jennifer = await trx
* .insertInto('person')
* .values({
* first_name: 'Jennifer',
* last_name: 'Aniston',
* age: 40,
* })
* .returning('id')
* .executeTakeFirstOrThrow()
*
* const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()
*
* try {
* const catto = await trxAfterJennifer
* .insertInto('pet')
* .values({
* owner_id: jennifer.id,
* name: 'Catto',
* species: 'cat',
* })
* .returning('id')
* .executeTakeFirstOrThrow()
*
* await trxAfterJennifer
* .insertInto('toy')
* .values({ name: 'Bone', price: 1.99, pet_id: catto.id })
* .execute()
* } catch (error) {
* await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()
* }
*
* await trxAfterJennifer.releaseSavepoint('after_jennifer').execute()
*
* await trx.insertInto('audit').values({ action: 'added Jennifer' }).execute()
*
* await trx.commit().execute()
* } catch (error) {
* await trx.rollback().execute()
* }
* ```
*/
startTransaction() {
return new ControlledTransactionBuilder({ ...this.#props });
}
/**
* Provides a kysely instance bound to a single database connection.
*
* ### Examples
*
* ```ts
* await db
* .connection()
* .execute(async (db) => {
* // `db` is an instance of `Kysely` that's bound to a single
* // database connection. All queries executed through `db` use
* // the same connection.
* await doStuff(db)
* })
*
* async function doStuff(kysely: typeof db) {
* // ...
* }
* ```
*/
connection() {
return new ConnectionBuilder({ ...this.#props });
}
/**
* Returns a copy of this Kysely instance with the given plugin installed.
*/
withPlugin(plugin) {
return new Kysely({
...this.#props,
executor: this.#props.executor.withPlugin(plugin)
});
}
/**
* Returns a copy of this Kysely instance without any plugins.
*/
withoutPlugins() {
return new Kysely({
...this.#props,
executor: this.#props.executor.withoutPlugins()
});
}
/**
* @override
*/
withSchema(schema) {
return new Kysely({
...this.#props,
executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema))
});
}
/**
* Returns a copy of this Kysely instance with tables added to its
* database type.
*
* This method only modifies the types and doesn't affect any of the
* executed queries in any way.
*
* ### Examples
*
* The following example adds and uses a temporary table:
*
* ```ts
* await db.schema
* .createTable('temp_table')
* .temporary()
* .addColumn('some_column', 'integer')
* .execute()
*
* const tempDb = db.$extendTables<{
* temp_table: {
* some_column: number
* }
* }>()
*
* await tempDb
* .insertInto('temp_table')
* .values({ some_column: 100 })
* .execute()
* ```
*/
$extendTables() {
return new Kysely({ ...this.#props });
}
/**
* Returns a copy of this Kysely instance without the given tables (provided as
* a union type of table names).
*
* This method only modifies the types and doesn't affect any of the executed
* queries in any way.
*
* See also {@link $pickTables} and {@link $extendTables}.
*
* ### Examples
*
* The following example omits tables not used in the downstream query. This
* can help with compile-time performance as downstream checks and calculations
* work against a smaller scope of the database - less tables and columns.
*
* Don't optimize prematurely! Build your queries first, measure later. If you
* realize the query has a noticeable impact on compilation - try the helper.
*
* ```ts
* const results = await db
* .$omitTables<'toy'>()
* .selectFrom('person')
* .innerJoin('pet', 'pet.owner_id', 'person.id')
* .selectAll()
* .execute()
* ```
*
* The query is arguably less readable now, and changing it is less obvious -
* e.g. adding another table.
*/
$omitTables() {
return new Kysely({ ...this.#props });
}
/**
* Returns a copy of this Kysely instance with just the given tables (provided as
* a union type of table names).
*
* This method only modifies the types and doesn't affect any of the executed
* queries in any way.
*
* See also {@link $omitTables} and {@link $extendTables}.
*
* ### Examples
*
* The following example picks the tables used in the downstream query. This
* can help with compile-time performance as downstream checks and calculations
* work against a smaller scope of the database - less tables and columns.
*
* Don't optimize prematurely! Build your queries first, measure later. If you
* realize the query has a noticeable impact on compilation - try the helper.
*
* ```ts
* const results = await db
* .$pickTables<'person' | 'pet'>()
* .selectFrom('person')
* .innerJoin('pet', 'pet.owner_id', 'person.id')
* .selectAll()
* .execute()
* ```
*
* The query is arguably less readable now, and changing it is less obvious -
* e.g. adding another table.
*/
$pickTables() {
return new Kysely({ ...this.#props });
}
/**
* @deprecated use {@link $extendTables} instead.
*/
withTables() {
return this.$extendTables();
}
/**
* Releases all resources and disconnects from the database.
*
* You need to call this when you are done using the `Kysely` instance.
*/
async destroy() {
await this.#props.driver.destroy();
}
/**
* Returns true if this `Kysely` instance is a transaction.
*
* You can also use `db instanceof Transaction`.
*/
get isTransaction() {
return false;
}
/**
* @internal
* @private
*/
getExecutor() {
return this.#props.executor;
}
/**
* Executes a given compiled query or query builder.
*
* See {@link https://github.com/kysely-org/kysely/blob/master/site/docs/recipes/0004-splitting-query-building-and-execution.md#execute-compiled-queries splitting build, compile and execute code recipe} for more information.
*/
async executeQuery(query, options) {
const compiledQuery = isCompilable(query) ? query.compile() : query;
return await this.#props.executor.executeQuery(compiledQuery, options);
}
async [Symbol.asyncDispose]() {
await this.destroy();
}
};
Transaction = class Transaction extends Kysely {
#props;
constructor(props) {
super(props);
this.#props = props;
}
get isTransaction() {
return true;
}
/**
* @deprecated calling the transaction method for a Transaction is not supported
*/
transaction() {
throw new Error("calling the transaction method for a Transaction is not supported");
}
/**
* @deprecated calling the controlled transaction method for a Transaction is not supported
*/
startTransaction() {
throw new Error("calling the controlled transaction method for a Transaction is not supported");
}
/**
* @deprecated calling the connection method for a Transaction is not supported
*/
connection() {
throw new Error("calling the connection method for a Transaction is not supported");
}
/**
* @deprecated calling the destroy method for a Transaction is not supported
*/
destroy() {
throw new Error("calling the destroy method for a Transaction is not supported");
}
/**
* Similar to {@link Kysely.withPlugin} but returns the transaction.
*/
withPlugin(plugin) {
return new Transaction({
...this.#props,
executor: this.#props.executor.withPlugin(plugin)
});
}
/**
* Similar to {@link Kysely.withoutPlugins} but returns the transaction.
*/
withoutPlugins() {
return new Transaction({
...this.#props,
executor: this.#props.executor.withoutPlugins()
});
}
/**
* Similar to {@link Kysely.withSchema} but returns the transaction.
*/
withSchema(schema) {
return new Transaction({
...this.#props,
executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema))
});
}
/**
* Similar to {@link Kysely.withTables} but returns the transaction.
*
* @deprecated use {@link $extendTables} instead.
*/
withTables() {
return new Transaction({ ...this.#props });
}
/**
* Similar to {@link Kysely.$extendTables} but returns the transaction.
*/
$extendTables() {
return new Transaction({ ...this.#props });
}
/**
* Similar to {@link Kysely.$omitTables} but returns the transaction.
*/
$omitTables() {
return new Transaction({ ...this.#props });
}
/**
* Similar to {@link Kysely.$pickTables} but returns the transaction.
*/
$pickTables() {
return new Transaction({ ...this.#props });
}
};
ConnectionBuilder = class {
#props;
constructor(props) {
this.#props = freeze(props);
}
async execute(callback, options) {
return this.#props.executor.provideConnection(async (connection) => {
const executor = this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection));
return await callback(new Kysely({
...this.#props,
executor
}));
}, freeze({ signal: options?.signal }));
}
};
TransactionBuilder = class TransactionBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
setAccessMode(accessMode) {
return new TransactionBuilder({
...this.#props,
accessMode
});
}
setIsolationLevel(isolationLevel) {
return new TransactionBuilder({
...this.#props,
isolationLevel
});
}
async execute(callback) {
const { isolationLevel, accessMode, ...kyselyProps } = this.#props;
const settings = {
isolationLevel,
accessMode
};
validateTransactionSettings(settings);
return this.#props.executor.provideConnection(async (connection) => {
const state = {
isCommitted: false,
isRolledBack: false
};
const executor = new NotCommittedOrRolledBackAssertingExecutor(this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection)), state);
const transaction = new Transaction({
...kyselyProps,
executor
});
let transactionBegun = false;
try {
await this.#props.driver.beginTransaction(connection, settings);
transactionBegun = true;
const result = await callback(transaction);
await this.#props.driver.commitTransaction(connection);
state.isCommitted = true;
return result;
} catch (error) {
if (transactionBegun) {
await this.#props.driver.rollbackTransaction(connection);
state.isRolledBack = true;
}
throw error;
}
});
}
};
ControlledTransactionBuilder = class ControlledTransactionBuilder {
#props;
constructor(props) {
this.#props = freeze(props);
}
setAccessMode(accessMode) {
return new ControlledTransactionBuilder({
...this.#props,
accessMode
});
}
setIsolationLevel(isolationLevel) {
return new ControlledTransactionBuilder({
...this.#props,
isolationLevel
});
}
async execute() {
const { isolationLevel, accessMode, ...props } = this.#props;
const settings = {
isolationLevel,
accessMode
};
validateTransactionSettings(settings);
const connection = await provideControlledConnection(this.#props.executor);
await this.#props.driver.beginTransaction(connection.connection, settings);
return new ControlledTransaction({
...props,
connection,
executor: this.#props.executor.withConnectionProvider(new SingleConnectionProvider(connection.connection))
});
}
};
ControlledTransaction = class ControlledTransaction extends Transaction {
#props;
#compileQuery;
#state;
constructor(props) {
const state = {
isCommitted: false,
isRolledBack: false
};
props = {
...props,
executor: new NotCommittedOrRolledBackAssertingExecutor(props.executor, state)
};
const { connection, ...transactionProps } = props;
super(transactionProps);
this.#props = freeze(props);
this.#state = state;
const queryId = createQueryId();
this.#compileQuery = (node) => props.executor.compileQuery(node, queryId);
}
get isCommitted() {
return this.#state.isCommitted;
}
get isRolledBack() {
return this.#state.isRolledBack;
}
/**
* Commits the transaction.
*
* See {@link rollback}.
*
* ### Examples
*
* ```ts
* import type { Kysely } from 'kysely'
* import type { Database } from 'type-editor' // imaginary module
*
* const trx = await db.startTransaction().execute()
*
* try {
* await doSomething(trx)
*
* await trx.commit().execute()
* } catch (error) {
* await trx.rollback().execute()
* }
*
* async function doSomething(kysely: Kysely<Database>) {}
* ```
*/
commit() {
assertNotCommittedOrRolledBack(this.#state);
return new Command(async () => {
await this.#props.driver.commitTransaction(this.#props.connection.connection);
this.#state.isCommitted = true;
this.#props.connection.release();
});
}
/**
* Rolls back the transaction.
*
* See {@link commit} and {@link rollbackToSavepoint}.
*
* ### Examples
*
* ```ts
* import type { Kysely } from 'kysely'
* import type { Database } from 'type-editor' // imaginary module
*
* const trx = await db.startTransaction().execute()
*
* try {
* await doSomething(trx)
*
* await trx.commit().execute()
* } catch (error) {
* await trx.rollback().execute()
* }
*
* async function doSomething(kysely: Kysely<Database>) {}
* ```
*/
rollback() {
assertNotCommittedOrRolledBack(this.#state);
return new Command(async () => {
await this.#props.driver.rollbackTransaction(this.#props.connection.connection);
this.#state.isRolledBack = true;
this.#props.connection.release();
});
}
/**
* Creates a savepoint with a given name.
*
* See {@link rollbackToSavepoint} and {@link releaseSavepoint}.
*
* For a type-safe experience, you should use the returned instance from now on.
*
* ### Examples
*
* ```ts
* import type { Kysely } from 'kysely'
* import type { Database } from 'type-editor' // imaginary module
*
* const trx = await db.startTransaction().execute()
*
* await insertJennifer(trx)
*
* const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()
*
* try {
* await doSomething(trxAfterJennifer)
* } catch (error) {
* await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()
* }
*
* async function insertJennifer(kysely: Kysely<Database>) {}
* async function doSomething(kysely: Kysely<Database>) {}
* ```
*/
savepoint(savepointName) {
assertNotCommittedOrRolledBack(this.#state);
return new Command(async () => {
await this.#props.driver.savepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery);
return new ControlledTransaction({ ...this.#props });
});
}
/**
* Rolls back to a savepoint with a given name.
*
* See {@link savepoint} and {@link releaseSavepoint}.
*
* You must use the same instance returned by {@link savepoint}, or
* escape the type-check by using `as any`.
*
* ### Examples
*
* ```ts
* import type { Kysely } from 'kysely'
* import type { Database } from 'type-editor' // imaginary module
*
* const trx = await db.startTransaction().execute()
*
* await insertJennifer(trx)
*
* const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()
*
* try {
* await doSomething(trxAfterJennifer)
* } catch (error) {
* await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()
* }
*
* async function insertJennifer(kysely: Kysely<Database>) {}
* async function doSomething(kysely: Kysely<Database>) {}
* ```
*/
rollbackToSavepoint(savepointName) {
assertNotCommittedOrRolledBack(this.#state);
return new Command(async () => {
await this.#props.driver.rollbackToSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery);
return new ControlledTransaction({ ...this.#props });
});
}
/**
* Releases a savepoint with a given name.
*
* See {@link savepoint} and {@link rollbackToSavepoint}.
*
* You must use the same instance returned by {@link savepoint}, or
* escape the type-check by using `as any`.
*
* ### Examples
*
* ```ts
* import type { Kysely } from 'kysely'
* import type { Database } from 'type-editor' // imaginary module
*
* const trx = await db.startTransaction().execute()
*
* await insertJennifer(trx)
*
* const trxAfterJennifer = await trx.savepoint('after_jennifer').execute()
*
* try {
* await doSomething(trxAfterJennifer)
* } catch (error) {
* await trxAfterJennifer.rollbackToSavepoint('after_jennifer').execute()
* }
*
* await trxAfterJennifer.releaseSavepoint('after_jennifer').execute()
*
* await doSomethingElse(trx)
*
* async function insertJennifer(kysely: Kysely<Database>) {}
* async function doSomething(kysely: Kysely<Database>) {}
* async function doSomethingElse(kysely: Kysely<Database>) {}
* ```
*/
releaseSavepoint(savepointName) {
assertNotCommittedOrRolledBack(this.#state);
return new Command(async () => {
await this.#props.driver.releaseSavepoint?.(this.#props.connection.connection, savepointName, this.#compileQuery);
return new ControlledTransaction({ ...this.#props });
});
}
withPlugin(plugin) {
return new ControlledTransaction({
...this.#props,
executor: this.#props.executor.withPlugin(plugin)
});
}
withoutPlugins() {
return new ControlledTransaction({
...this.#props,
executor: this.#props.executor.withoutPlugins()
});
}
withSchema(schema) {
return new ControlledTransaction({
...this.#props,
executor: this.#props.executor.withPluginAtFront(new WithSchemaPlugin(schema))
});
}
withTables() {
return new ControlledTransaction({ ...this.#props });
}
$extendTables() {
return new ControlledTransaction({ ...this.#props });
}
$omitTables() {
return new ControlledTransaction({ ...this.#props });
}
$pickTables() {
return new ControlledTransaction({ ...this.#props });
}
};
Command = class {
#cb;
constructor(cb) {
this.#cb = cb;
}
/**
* Executes the command.
*/
async execute() {
return await this.#cb();
}
};
NotCommittedOrRolledBackAssertingExecutor = class NotCommittedOrRolledBackAssertingExecutor {
#executor;
#state;
constructor(executor, state) {
this.#executor = executor instanceof NotCommittedOrRolledBackAssertingExecutor ? executor.#executor : executor;
this.#state = state;
}
get adapter() {
return this.#executor.adapter;
}
get plugins() {
return this.#executor.plugins;
}
transformQuery(node, queryId) {
return this.#executor.transformQuery(node, queryId);
}
compileQuery(node, queryId) {
return this.#executor.compileQuery(node, queryId);
}
provideConnection(consumer, options) {
return this.#executor.provideConnection(consumer, options);
}
executeQuery(compiledQuery, options) {
assertNotCommittedOrRolledBack(this.#state);
return this.#executor.executeQuery(compiledQuery, options);
}
stream(compiledQuery, chunkSize, options) {
assertNotCommittedOrRolledBack(this.#state);
return this.#executor.stream(compiledQuery, chunkSize, options);
}
withConnectionProvider(connectionProvider) {
return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withConnectionProvider(connectionProvider), this.#state);
}
withPlugin(plugin) {
return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugin(plugin), this.#state);
}
withPlugins(plugins) {
return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPlugins(plugins), this.#state);
}
withPluginAtFront(plugin) {
return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withPluginAtFront(plugin), this.#state);
}
withoutPlugins() {
return new NotCommittedOrRolledBackAssertingExecutor(this.#executor.withoutPlugins(), this.#state);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/raw-builder/raw-builder.js
function createRawBuilder(props) {
return new RawBuilderImpl(props);
}
var RawBuilderImpl, AliasedRawBuilderImpl;
var init_raw_builder = __esmMin((() => {
init_alias_node();
init_object_utils();
init_noop_query_executor();
init_identifier_node();
init_operation_node_source();
RawBuilderImpl = class RawBuilderImpl {
#props;
constructor(props) {
this.#props = freeze(props);
}
get expressionType() {}
get isRawBuilder() {
return true;
}
as(alias) {
return new AliasedRawBuilderImpl(this, alias);
}
$castTo() {
return new RawBuilderImpl({ ...this.#props });
}
$notNull() {
return new RawBuilderImpl(this.#props);
}
withPlugin(plugin) {
return new RawBuilderImpl({
...this.#props,
plugins: this.#props.plugins !== void 0 ? freeze([...this.#props.plugins, plugin]) : freeze([plugin])
});
}
toOperationNode() {
return this.#toOperationNode(this.#getExecutor());
}
compile(executorProvider) {
return this.#compile(this.#getExecutor(executorProvider));
}
async execute(executorProvider, options) {
const executor = this.#getExecutor(executorProvider);
return executor.executeQuery(this.#compile(executor), options);
}
#getExecutor(executorProvider) {
const executor = executorProvider !== void 0 ? executorProvider.getExecutor() : NOOP_QUERY_EXECUTOR;
return this.#props.plugins !== void 0 ? executor.withPlugins(this.#props.plugins) : executor;
}
#toOperationNode(executor) {
return executor.transformQuery(this.#props.rawNode, this.#props.queryId);
}
#compile(executor) {
return executor.compileQuery(this.#toOperationNode(executor), this.#props.queryId);
}
};
AliasedRawBuilderImpl = class {
#rawBuilder;
#alias;
constructor(rawBuilder, alias) {
this.#rawBuilder = rawBuilder;
this.#alias = alias;
}
get expression() {
return this.#rawBuilder;
}
get alias() {
return this.#alias;
}
get rawBuilder() {
return this.#rawBuilder;
}
toOperationNode() {
return AliasNode.create(this.#rawBuilder.toOperationNode(), isOperationNodeSource(this.#alias) ? this.#alias.toOperationNode() : IdentifierNode.create(this.#alias));
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/raw-builder/sql.js
function parseParameter(param) {
if (isOperationNodeSource(param)) return param.toOperationNode();
return parseValueExpression(param);
}
var sql;
var init_sql = __esmMin((() => {
init_identifier_node();
init_operation_node_source();
init_raw_node();
init_value_node();
init_reference_parser();
init_table_parser();
init_value_parser();
init_query_id();
init_raw_builder();
sql = Object.assign((sqlFragments, ...parameters) => {
return createRawBuilder({
queryId: createQueryId(),
rawNode: RawNode.create(sqlFragments, parameters?.map(parseParameter) ?? [])
});
}, {
ref(columnReference) {
return createRawBuilder({
queryId: createQueryId(),
rawNode: RawNode.createWithChild(parseStringReference(columnReference))
});
},
val(value) {
return createRawBuilder({
queryId: createQueryId(),
rawNode: RawNode.createWithChild(parseValueExpression(value))
});
},
table(tableReference) {
return createRawBuilder({
queryId: createQueryId(),
rawNode: RawNode.createWithChild(parseTable(tableReference))
});
},
id(...ids) {
const fragments = new Array(ids.length + 1).fill(".");
fragments[0] = "";
fragments[fragments.length - 1] = "";
return createRawBuilder({
queryId: createQueryId(),
rawNode: RawNode.create(fragments, ids.map(IdentifierNode.create))
});
},
lit(value) {
return createRawBuilder({
queryId: createQueryId(),
rawNode: RawNode.createWithChild(ValueNode.createImmediate(value))
});
},
raw(sql) {
return createRawBuilder({
queryId: createQueryId(),
rawNode: RawNode.createWithSql(sql)
});
},
join(array, separator = sql`, `) {
const nodes = new Array(Math.max(2 * array.length - 1, 0));
const sep = separator.toOperationNode();
for (let i = 0; i < array.length; ++i) {
nodes[2 * i] = parseParameter(array[i]);
if (i !== array.length - 1) nodes[2 * i + 1] = sep;
}
return createRawBuilder({
queryId: createQueryId(),
rawNode: RawNode.createWithChildren(nodes)
});
}
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/operation-node-visitor.js
var OperationNodeVisitor;
var init_operation_node_visitor = __esmMin((() => {
init_object_utils();
OperationNodeVisitor = class {
nodeStack = [];
get parentNode() {
return this.nodeStack[this.nodeStack.length - 2];
}
#visitors = freeze({
AliasNode: this.visitAlias.bind(this),
ColumnNode: this.visitColumn.bind(this),
IdentifierNode: this.visitIdentifier.bind(this),
SchemableIdentifierNode: this.visitSchemableIdentifier.bind(this),
RawNode: this.visitRaw.bind(this),
ReferenceNode: this.visitReference.bind(this),
SelectQueryNode: this.visitSelectQuery.bind(this),
SelectionNode: this.visitSelection.bind(this),
TableNode: this.visitTable.bind(this),
FromNode: this.visitFrom.bind(this),
SelectAllNode: this.visitSelectAll.bind(this),
AndNode: this.visitAnd.bind(this),
OrNode: this.visitOr.bind(this),
ValueNode: this.visitValue.bind(this),
ValueListNode: this.visitValueList.bind(this),
PrimitiveValueListNode: this.visitPrimitiveValueList.bind(this),
ParensNode: this.visitParens.bind(this),
JoinNode: this.visitJoin.bind(this),
OperatorNode: this.visitOperator.bind(this),
WhereNode: this.visitWhere.bind(this),
InsertQueryNode: this.visitInsertQuery.bind(this),
DeleteQueryNode: this.visitDeleteQuery.bind(this),
ReturningNode: this.visitReturning.bind(this),
CreateTableNode: this.visitCreateTable.bind(this),
AddColumnNode: this.visitAddColumn.bind(this),
ColumnDefinitionNode: this.visitColumnDefinition.bind(this),
DropTableNode: this.visitDropTable.bind(this),
DataTypeNode: this.visitDataType.bind(this),
OrderByNode: this.visitOrderBy.bind(this),
OrderByItemNode: this.visitOrderByItem.bind(this),
GroupByNode: this.visitGroupBy.bind(this),
GroupByItemNode: this.visitGroupByItem.bind(this),
UpdateQueryNode: this.visitUpdateQuery.bind(this),
ColumnUpdateNode: this.visitColumnUpdate.bind(this),
LimitNode: this.visitLimit.bind(this),
OffsetNode: this.visitOffset.bind(this),
OnConflictNode: this.visitOnConflict.bind(this),
OnDuplicateKeyNode: this.visitOnDuplicateKey.bind(this),
CreateIndexNode: this.visitCreateIndex.bind(this),
DropIndexNode: this.visitDropIndex.bind(this),
ListNode: this.visitList.bind(this),
PrimaryKeyConstraintNode: this.visitPrimaryKeyConstraint.bind(this),
UniqueConstraintNode: this.visitUniqueConstraint.bind(this),
ReferencesNode: this.visitReferences.bind(this),
CheckConstraintNode: this.visitCheckConstraint.bind(this),
WithNode: this.visitWith.bind(this),
CommonTableExpressionNode: this.visitCommonTableExpression.bind(this),
CommonTableExpressionNameNode: this.visitCommonTableExpressionName.bind(this),
HavingNode: this.visitHaving.bind(this),
CreateSchemaNode: this.visitCreateSchema.bind(this),
DropSchemaNode: this.visitDropSchema.bind(this),
AlterTableNode: this.visitAlterTable.bind(this),
DropColumnNode: this.visitDropColumn.bind(this),
RenameColumnNode: this.visitRenameColumn.bind(this),
AlterColumnNode: this.visitAlterColumn.bind(this),
ModifyColumnNode: this.visitModifyColumn.bind(this),
AddConstraintNode: this.visitAddConstraint.bind(this),
DropConstraintNode: this.visitDropConstraint.bind(this),
RenameConstraintNode: this.visitRenameConstraint.bind(this),
ForeignKeyConstraintNode: this.visitForeignKeyConstraint.bind(this),
CreateViewNode: this.visitCreateView.bind(this),
RefreshMaterializedViewNode: this.visitRefreshMaterializedView.bind(this),
DropViewNode: this.visitDropView.bind(this),
GeneratedNode: this.visitGenerated.bind(this),
DefaultValueNode: this.visitDefaultValue.bind(this),
OnNode: this.visitOn.bind(this),
ValuesNode: this.visitValues.bind(this),
SelectModifierNode: this.visitSelectModifier.bind(this),
CreateTypeNode: this.visitCreateType.bind(this),
DropTypeNode: this.visitDropType.bind(this),
ExplainNode: this.visitExplain.bind(this),
DefaultInsertValueNode: this.visitDefaultInsertValue.bind(this),
AggregateFunctionNode: this.visitAggregateFunction.bind(this),
OverNode: this.visitOver.bind(this),
PartitionByNode: this.visitPartitionBy.bind(this),
PartitionByItemNode: this.visitPartitionByItem.bind(this),
SetOperationNode: this.visitSetOperation.bind(this),
BinaryOperationNode: this.visitBinaryOperation.bind(this),
UnaryOperationNode: this.visitUnaryOperation.bind(this),
UsingNode: this.visitUsing.bind(this),
FunctionNode: this.visitFunction.bind(this),
CaseNode: this.visitCase.bind(this),
WhenNode: this.visitWhen.bind(this),
JSONReferenceNode: this.visitJSONReference.bind(this),
JSONPathNode: this.visitJSONPath.bind(this),
JSONPathLegNode: this.visitJSONPathLeg.bind(this),
JSONOperatorChainNode: this.visitJSONOperatorChain.bind(this),
TupleNode: this.visitTuple.bind(this),
MergeQueryNode: this.visitMergeQuery.bind(this),
MatchedNode: this.visitMatched.bind(this),
AddIndexNode: this.visitAddIndex.bind(this),
CastNode: this.visitCast.bind(this),
FetchNode: this.visitFetch.bind(this),
TopNode: this.visitTop.bind(this),
OutputNode: this.visitOutput.bind(this),
OrActionNode: this.visitOrAction.bind(this),
CollateNode: this.visitCollate.bind(this),
AlterTypeNode: this.visitAlterType.bind(this),
AddValueNode: this.visitAddValue.bind(this),
RenameValueNode: this.visitRenameValue.bind(this)
});
visitNode = (node) => {
this.nodeStack.push(node);
this.#visitors[node.kind](node);
this.nodeStack.pop();
};
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-compiler/default-query-compiler.js
var LIT_WRAP_REGEX, JSON_PATH_MEMBER_WRAP_REGEX, DefaultQueryCompiler, SELECT_MODIFIER_SQL, SELECT_MODIFIER_PRIORITY, JOIN_TYPE_SQL;
var init_default_query_compiler = __esmMin((() => {
init_create_table_node();
init_insert_query_node();
init_operation_node_visitor();
init_operator_node();
init_parens_node();
init_raw_node();
init_object_utils();
init_create_view_node();
init_set_operation_node();
init_when_node();
LIT_WRAP_REGEX = /'/g;
JSON_PATH_MEMBER_WRAP_REGEX = /['"]/g;
DefaultQueryCompiler = class extends OperationNodeVisitor {
#sql = "";
#parameters = [];
get numParameters() {
return this.#parameters.length;
}
compileQuery(node, queryId) {
this.#sql = "";
this.#parameters = [];
this.nodeStack.splice(0, this.nodeStack.length);
this.visitNode(node);
return freeze({
query: node,
queryId,
sql: this.getSql(),
parameters: [...this.#parameters]
});
}
getSql() {
return this.#sql;
}
visitSelectQuery(node) {
const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !InsertQueryNode.is(this.parentNode) && !CreateTableNode.is(this.parentNode) && !CreateViewNode.is(this.parentNode) && !SetOperationNode.is(this.parentNode);
if (this.parentNode === void 0 && node.explain) {
this.visitNode(node.explain);
this.append(" ");
}
if (wrapInParens) this.append("(");
if (node.with) {
this.visitNode(node.with);
this.append(" ");
}
this.append("select");
if (node.distinctOn) {
this.append(" ");
this.compileDistinctOn(node.distinctOn);
}
if (node.frontModifiers?.length) {
this.append(" ");
this.compileList(node.frontModifiers, " ");
}
if (node.top) {
this.append(" ");
this.visitNode(node.top);
}
if (node.selections) {
this.append(" ");
this.compileList(node.selections);
}
if (node.from) {
this.append(" ");
this.visitNode(node.from);
}
if (node.joins) {
this.append(" ");
this.compileList(node.joins, " ");
}
if (node.where) {
this.append(" ");
this.visitNode(node.where);
}
if (node.groupBy) {
this.append(" ");
this.visitNode(node.groupBy);
}
if (node.having) {
this.append(" ");
this.visitNode(node.having);
}
if (node.setOperations) {
this.append(" ");
this.compileList(node.setOperations, " ");
}
if (node.orderBy) {
this.append(" ");
this.visitNode(node.orderBy);
}
if (node.limit) {
this.append(" ");
this.visitNode(node.limit);
}
if (node.offset) {
this.append(" ");
this.visitNode(node.offset);
}
if (node.fetch) {
this.append(" ");
this.visitNode(node.fetch);
}
if (node.endModifiers?.length) {
this.append(" ");
this.compileList(this.sortSelectModifiers(node.endModifiers), " ");
}
if (wrapInParens) this.append(")");
}
visitFrom(node) {
this.append("from ");
this.compileList(node.froms);
}
visitSelection(node) {
this.visitNode(node.selection);
}
visitColumn(node) {
this.visitNode(node.column);
}
compileDistinctOn(expressions) {
this.append("distinct on (");
this.compileList(expressions);
this.append(")");
}
compileList(nodes, separator = ", ") {
const lastIndex = nodes.length - 1;
for (let i = 0; i <= lastIndex; i++) {
this.visitNode(nodes[i]);
if (i < lastIndex) this.append(separator);
}
}
visitWhere(node) {
this.append("where ");
this.visitNode(node.where);
}
visitHaving(node) {
this.append("having ");
this.visitNode(node.having);
}
visitInsertQuery(node) {
const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode);
if (this.parentNode === void 0 && node.explain) {
this.visitNode(node.explain);
this.append(" ");
}
if (wrapInParens) this.append("(");
if (node.with) {
this.visitNode(node.with);
this.append(" ");
}
this.append(node.replace ? "replace" : "insert");
if (node.orAction) {
this.append(" ");
this.visitNode(node.orAction);
}
if (node.top) {
this.append(" ");
this.visitNode(node.top);
}
if (node.into) {
this.append(" into ");
this.visitNode(node.into);
}
if (node.columns) {
this.append(" (");
this.compileList(node.columns);
this.append(")");
}
if (node.output) {
this.append(" ");
this.visitNode(node.output);
}
if (node.values) {
this.append(" ");
this.visitNode(node.values);
}
if (node.defaultValues) {
this.append(" ");
this.append("default values");
}
if (node.onConflict) {
this.append(" ");
this.visitNode(node.onConflict);
}
if (node.onDuplicateKey) {
this.append(" ");
this.visitNode(node.onDuplicateKey);
}
if (node.returning) {
this.append(" ");
this.visitNode(node.returning);
}
if (wrapInParens) this.append(")");
if (node.endModifiers?.length) {
this.append(" ");
this.compileList(node.endModifiers, " ");
}
}
visitValues(node) {
this.append("values ");
this.compileList(node.values);
}
visitDeleteQuery(node) {
const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode);
if (this.parentNode === void 0 && node.explain) {
this.visitNode(node.explain);
this.append(" ");
}
if (wrapInParens) this.append("(");
if (node.with) {
this.visitNode(node.with);
this.append(" ");
}
this.append("delete ");
if (node.top) {
this.visitNode(node.top);
this.append(" ");
}
this.visitNode(node.from);
if (node.output) {
this.append(" ");
this.visitNode(node.output);
}
if (node.using) {
this.append(" ");
this.visitNode(node.using);
}
if (node.joins) {
this.append(" ");
this.compileList(node.joins, " ");
}
if (node.where) {
this.append(" ");
this.visitNode(node.where);
}
if (node.returning) {
this.append(" ");
this.visitNode(node.returning);
}
if (node.orderBy) {
this.append(" ");
this.visitNode(node.orderBy);
}
if (node.limit) {
this.append(" ");
this.visitNode(node.limit);
}
if (wrapInParens) this.append(")");
if (node.endModifiers?.length) {
this.append(" ");
this.compileList(node.endModifiers, " ");
}
}
visitReturning(node) {
this.append("returning ");
this.compileList(node.selections);
}
visitAlias(node) {
this.visitNode(node.node);
this.append(" as ");
this.visitNode(node.alias);
}
visitReference(node) {
if (node.table) {
this.visitNode(node.table);
this.append(".");
}
this.visitNode(node.column);
}
visitSelectAll(_) {
this.append("*");
}
visitIdentifier(node) {
this.append(this.getLeftIdentifierWrapper());
this.compileUnwrappedIdentifier(node);
this.append(this.getRightIdentifierWrapper());
}
compileUnwrappedIdentifier(node) {
if (!isString(node.name)) throw new Error("a non-string identifier was passed to compileUnwrappedIdentifier.");
this.append(this.sanitizeIdentifier(node.name));
}
visitAnd(node) {
this.visitNode(node.left);
this.append(" and ");
this.visitNode(node.right);
}
visitOr(node) {
this.visitNode(node.left);
this.append(" or ");
this.visitNode(node.right);
}
visitValue(node) {
if (node.immediate) this.appendImmediateValue(node.value);
else this.appendValue(node.value);
}
visitValueList(node) {
this.append("(");
this.compileList(node.values);
this.append(")");
}
visitTuple(node) {
this.append("(");
this.compileList(node.values);
this.append(")");
}
visitPrimitiveValueList(node) {
this.append("(");
const { values } = node;
for (let i = 0; i < values.length; ++i) {
this.appendValue(values[i]);
if (i !== values.length - 1) this.append(", ");
}
this.append(")");
}
visitParens(node) {
this.append("(");
this.visitNode(node.node);
this.append(")");
}
visitJoin(node) {
this.append(JOIN_TYPE_SQL[node.joinType]);
this.append(" ");
this.visitNode(node.table);
if (node.on) {
this.append(" ");
this.visitNode(node.on);
}
}
visitOn(node) {
this.append("on ");
this.visitNode(node.on);
}
visitRaw(node) {
const { sqlFragments, parameters: params } = node;
for (let i = 0; i < sqlFragments.length; ++i) {
this.append(sqlFragments[i]);
if (params.length > i) this.visitNode(params[i]);
}
}
visitOperator(node) {
this.append(node.operator);
}
visitTable(node) {
this.visitNode(node.table);
}
visitSchemableIdentifier(node) {
if (node.schema) {
this.visitNode(node.schema);
this.append(".");
}
this.visitNode(node.identifier);
}
visitCreateTable(node) {
this.append("create ");
if (node.frontModifiers?.length) {
this.compileList(node.frontModifiers, " ");
this.append(" ");
}
if (node.temporary) this.append("temporary ");
this.append("table ");
if (node.ifNotExists) this.append("if not exists ");
this.visitNode(node.table);
if (!node.selectQuery) {
this.append(" (");
this.compileList([
...node.columns,
...node.constraints ?? [],
...node.indexes ?? []
]);
this.append(")");
}
if (node.onCommit) {
this.append(" on commit ");
this.append(node.onCommit);
}
if (node.endModifiers?.length) {
this.append(" ");
this.compileList(node.endModifiers, " ");
}
if (node.selectQuery) {
this.append(" as ");
this.visitNode(node.selectQuery);
}
}
visitColumnDefinition(node) {
if (node.ifNotExists) this.append("if not exists ");
this.visitNode(node.column);
this.append(" ");
this.visitNode(node.dataType);
if (node.unsigned) this.append(" unsigned");
if (node.frontModifiers && node.frontModifiers.length > 0) {
this.append(" ");
this.compileList(node.frontModifiers, " ");
}
if (node.generated) {
this.append(" ");
this.visitNode(node.generated);
}
if (node.identity) this.append(" identity");
if (node.defaultTo) {
this.append(" ");
this.visitNode(node.defaultTo);
}
if (node.notNull) this.append(" not null");
if (node.unique) this.append(" unique");
if (node.nullsNotDistinct) this.append(" nulls not distinct");
if (node.primaryKey) this.append(" primary key");
if (node.autoIncrement) {
this.append(" ");
this.append(this.getAutoIncrement());
}
if (node.references) {
this.append(" ");
this.visitNode(node.references);
}
if (node.check) {
this.append(" ");
this.visitNode(node.check);
}
if (node.endModifiers && node.endModifiers.length > 0) {
this.append(" ");
this.compileList(node.endModifiers, " ");
}
}
getAutoIncrement() {
return "auto_increment";
}
visitReferences(node) {
this.append("references ");
this.visitNode(node.table);
this.append(" (");
this.compileList(node.columns);
this.append(")");
if (node.onDelete) {
this.append(" on delete ");
this.append(node.onDelete);
}
if (node.onUpdate) {
this.append(" on update ");
this.append(node.onUpdate);
}
}
visitDropTable(node) {
this.append("drop ");
if (node.temporary) this.append("temporary ");
this.append("table ");
if (node.ifExists) this.append("if exists ");
this.visitNode(node.table);
if (node.cascade) this.append(" cascade");
}
visitDataType(node) {
this.append(node.dataType);
}
visitOrderBy(node) {
this.append("order by ");
this.compileList(node.items);
}
visitOrderByItem(node) {
this.visitNode(node.orderBy);
if (node.collation) {
this.append(" ");
this.visitNode(node.collation);
}
if (node.direction) {
this.append(" ");
this.visitNode(node.direction);
}
if (node.nulls) {
this.append(" nulls ");
this.append(node.nulls);
}
}
visitGroupBy(node) {
this.append("group by ");
this.compileList(node.items);
}
visitGroupByItem(node) {
this.visitNode(node.groupBy);
}
visitUpdateQuery(node) {
const wrapInParens = this.parentNode !== void 0 && !ParensNode.is(this.parentNode) && !RawNode.is(this.parentNode) && !WhenNode.is(this.parentNode);
if (this.parentNode === void 0 && node.explain) {
this.visitNode(node.explain);
this.append(" ");
}
if (wrapInParens) this.append("(");
if (node.with) {
this.visitNode(node.with);
this.append(" ");
}
this.append("update ");
if (node.top) {
this.visitNode(node.top);
this.append(" ");
}
if (node.table) {
this.visitNode(node.table);
this.append(" ");
}
this.append("set ");
if (node.updates) this.compileList(node.updates);
if (node.output) {
this.append(" ");
this.visitNode(node.output);
}
if (node.from) {
this.append(" ");
this.visitNode(node.from);
}
if (node.joins) {
if (!node.from) throw new Error("Joins in an update query are only supported as a part of a PostgreSQL 'update set from join' query. If you want to create a MySQL 'update join set' query, see https://kysely.dev/docs/examples/update/my-sql-joins");
this.append(" ");
this.compileList(node.joins, " ");
}
if (node.where) {
this.append(" ");
this.visitNode(node.where);
}
if (node.returning) {
this.append(" ");
this.visitNode(node.returning);
}
if (node.orderBy) {
this.append(" ");
this.visitNode(node.orderBy);
}
if (node.limit) {
this.append(" ");
this.visitNode(node.limit);
}
if (wrapInParens) this.append(")");
if (node.endModifiers?.length) {
this.append(" ");
this.compileList(node.endModifiers, " ");
}
}
visitColumnUpdate(node) {
this.visitNode(node.column);
this.append(" = ");
this.visitNode(node.value);
}
visitLimit(node) {
this.append("limit ");
this.visitNode(node.limit);
}
visitOffset(node) {
this.append("offset ");
this.visitNode(node.offset);
}
visitOnConflict(node) {
this.append("on conflict");
if (node.columns) {
this.append(" (");
this.compileList(node.columns);
this.append(")");
} else if (node.constraint) {
this.append(" on constraint ");
this.visitNode(node.constraint);
} else if (node.indexExpression) {
this.append(" (");
this.visitNode(node.indexExpression);
this.append(")");
}
if (node.indexWhere) {
this.append(" ");
this.visitNode(node.indexWhere);
}
if (node.doNothing === true) this.append(" do nothing");
else if (node.updates) {
this.append(" do update set ");
this.compileList(node.updates);
if (node.updateWhere) {
this.append(" ");
this.visitNode(node.updateWhere);
}
}
}
visitOnDuplicateKey(node) {
this.append("on duplicate key update ");
this.compileList(node.updates);
}
visitCreateIndex(node) {
this.append("create ");
if (node.unique) this.append("unique ");
this.append("index ");
if (node.ifNotExists) this.append("if not exists ");
this.visitNode(node.name);
if (node.table) {
this.append(" on ");
this.visitNode(node.table);
}
if (node.using) {
this.append(" using ");
this.visitNode(node.using);
}
if (node.columns) {
this.append(" (");
this.compileList(node.columns);
this.append(")");
}
if (node.nullsNotDistinct) this.append(" nulls not distinct");
if (node.where) {
this.append(" ");
this.visitNode(node.where);
}
}
visitDropIndex(node) {
this.append("drop index ");
if (node.ifExists) this.append("if exists ");
this.visitNode(node.name);
if (node.table) {
this.append(" on ");
this.visitNode(node.table);
}
if (node.cascade) this.append(" cascade");
}
visitCreateSchema(node) {
this.append("create schema ");
if (node.ifNotExists) this.append("if not exists ");
this.visitNode(node.schema);
}
visitDropSchema(node) {
this.append("drop schema ");
if (node.ifExists) this.append("if exists ");
this.visitNode(node.schema);
if (node.cascade) this.append(" cascade");
}
visitPrimaryKeyConstraint(node) {
if (node.name) {
this.append("constraint ");
this.visitNode(node.name);
this.append(" ");
}
this.append("primary key (");
this.compileList(node.columns);
this.append(")");
this.buildDeferrable(node);
}
buildDeferrable(node) {
if (node.deferrable !== void 0) {
if (node.deferrable) this.append(" deferrable");
else this.append(" not deferrable");
}
if (node.initiallyDeferred !== void 0) {
if (node.initiallyDeferred) this.append(" initially deferred");
else this.append(" initially immediate");
}
}
visitUniqueConstraint(node) {
if (node.name) {
this.append("constraint ");
this.visitNode(node.name);
this.append(" ");
}
this.append("unique");
if (node.nullsNotDistinct) this.append(" nulls not distinct");
this.append(" (");
this.compileList(node.columns);
this.append(")");
this.buildDeferrable(node);
}
visitCheckConstraint(node) {
if (node.name) {
this.append("constraint ");
this.visitNode(node.name);
this.append(" ");
}
this.append("check (");
this.visitNode(node.expression);
this.append(")");
}
visitForeignKeyConstraint(node) {
if (node.name) {
this.append("constraint ");
this.visitNode(node.name);
this.append(" ");
}
this.append("foreign key (");
this.compileList(node.columns);
this.append(") ");
this.visitNode(node.references);
if (node.onDelete) {
this.append(" on delete ");
this.append(node.onDelete);
}
if (node.onUpdate) {
this.append(" on update ");
this.append(node.onUpdate);
}
this.buildDeferrable(node);
}
visitList(node) {
this.compileList(node.items);
}
visitWith(node) {
this.append("with ");
if (node.recursive) this.append("recursive ");
this.compileList(node.expressions);
}
visitCommonTableExpression(node) {
this.visitNode(node.name);
this.append(" as ");
if (isBoolean(node.materialized)) {
if (!node.materialized) this.append("not ");
this.append("materialized ");
}
this.visitNode(node.expression);
}
visitCommonTableExpressionName(node) {
this.visitNode(node.table);
if (node.columns) {
this.append("(");
this.compileList(node.columns);
this.append(")");
}
}
visitAlterTable(node) {
this.append("alter table ");
this.visitNode(node.table);
this.append(" ");
if (node.renameTo) {
this.append("rename to ");
this.visitNode(node.renameTo);
}
if (node.setSchema) {
this.append("set schema ");
this.visitNode(node.setSchema);
}
if (node.addConstraint) this.visitNode(node.addConstraint);
if (node.dropConstraint) this.visitNode(node.dropConstraint);
if (node.renameConstraint) this.visitNode(node.renameConstraint);
if (node.columnAlterations) this.compileColumnAlterations(node.columnAlterations);
if (node.addIndex) this.visitNode(node.addIndex);
if (node.dropIndex) this.visitNode(node.dropIndex);
}
visitAddColumn(node) {
this.append("add column ");
this.visitNode(node.column);
}
visitRenameColumn(node) {
this.append("rename column ");
this.visitNode(node.column);
this.append(" to ");
this.visitNode(node.renameTo);
}
visitDropColumn(node) {
this.append("drop column ");
if (node.ifExists) this.append("if exists ");
this.visitNode(node.column);
}
visitAlterColumn(node) {
this.append("alter column ");
this.visitNode(node.column);
this.append(" ");
if (node.dataType) {
if (this.announcesNewColumnDataType()) this.append("type ");
this.visitNode(node.dataType);
if (node.dataTypeExpression) {
this.append("using ");
this.visitNode(node.dataTypeExpression);
}
}
if (node.setDefault) {
this.append("set default ");
this.visitNode(node.setDefault);
}
if (node.dropDefault) this.append("drop default");
if (node.setNotNull) this.append("set not null");
if (node.dropNotNull) this.append("drop not null");
}
visitModifyColumn(node) {
this.append("modify column ");
this.visitNode(node.column);
}
visitAddConstraint(node) {
this.append("add ");
this.visitNode(node.constraint);
}
visitDropConstraint(node) {
this.append("drop constraint ");
if (node.ifExists) this.append("if exists ");
this.visitNode(node.constraintName);
if (node.modifier === "cascade") this.append(" cascade");
else if (node.modifier === "restrict") this.append(" restrict");
}
visitRenameConstraint(node) {
this.append("rename constraint ");
this.visitNode(node.oldName);
this.append(" to ");
this.visitNode(node.newName);
}
visitSetOperation(node) {
this.append(node.operator);
this.append(" ");
if (node.all) this.append("all ");
this.visitNode(node.expression);
}
visitCreateView(node) {
this.append("create ");
if (node.orReplace) this.append("or replace ");
if (node.materialized) this.append("materialized ");
if (node.temporary) this.append("temporary ");
this.append("view ");
if (node.ifNotExists) this.append("if not exists ");
this.visitNode(node.name);
this.append(" ");
if (node.columns) {
this.append("(");
this.compileList(node.columns);
this.append(") ");
}
if (node.as) {
this.append("as ");
this.visitNode(node.as);
}
}
visitRefreshMaterializedView(node) {
this.append("refresh materialized view ");
if (node.concurrently) this.append("concurrently ");
this.visitNode(node.name);
if (node.withNoData) this.append(" with no data");
else this.append(" with data");
}
visitDropView(node) {
this.append("drop ");
if (node.materialized) this.append("materialized ");
this.append("view ");
if (node.ifExists) this.append("if exists ");
this.visitNode(node.name);
if (node.cascade) this.append(" cascade");
}
visitGenerated(node) {
this.append("generated ");
if (node.always) this.append("always ");
if (node.byDefault) this.append("by default ");
this.append("as ");
if (node.identity) this.append("identity");
if (node.expression) {
this.append("(");
this.visitNode(node.expression);
this.append(")");
}
if (node.stored) this.append(" stored");
}
visitDefaultValue(node) {
this.append("default ");
this.visitNode(node.defaultValue);
}
visitSelectModifier(node) {
if (node.rawModifier) this.visitNode(node.rawModifier);
else this.append(SELECT_MODIFIER_SQL[node.modifier]);
if (node.of) {
this.append(" of ");
this.compileList(node.of, ", ");
}
}
visitCreateType(node) {
this.append("create type ");
this.visitNode(node.name);
if (node.enum) {
this.append(" as enum ");
this.visitNode(node.enum);
}
}
visitDropType(node) {
this.append("drop type ");
if (node.ifExists) this.append("if exists ");
this.visitNode(node.name);
if (node.additionalNames?.length) {
this.append(", ");
this.compileList(node.additionalNames);
}
if (node.cascade) this.append(" cascade");
}
visitAlterType(node) {
this.append("alter type ");
this.visitNode(node.name);
this.append(" ");
if (node.addValue) this.visitNode(node.addValue);
else if (node.renameTo) {
this.append("rename to ");
this.visitNode(node.renameTo);
} else if (node.renameValue) this.visitNode(node.renameValue);
else if (node.setSchema) {
this.append("set schema ");
this.visitNode(node.setSchema);
}
}
visitAddValue(node) {
this.append("add value ");
if (node.ifNotExists) this.append("if not exists ");
this.visitNode(node.value);
if (node.neighborValue) {
this.append(node.isBefore ? " before " : " after ");
this.visitNode(node.neighborValue);
}
}
visitRenameValue(node) {
this.append("rename value ");
this.visitNode(node.oldValue);
this.append(" to ");
this.visitNode(node.newValue);
}
visitExplain(node) {
this.append("explain");
if (node.options || node.format) {
this.append(" ");
this.append(this.getLeftExplainOptionsWrapper());
if (node.options) {
this.visitNode(node.options);
if (node.format) this.append(this.getExplainOptionsDelimiter());
}
if (node.format) {
this.append("format");
this.append(this.getExplainOptionAssignment());
this.append(node.format);
}
this.append(this.getRightExplainOptionsWrapper());
}
}
visitDefaultInsertValue(_) {
this.append("default");
}
visitAggregateFunction(node) {
this.append(node.func);
this.append("(");
if (node.distinct) this.append("distinct ");
this.compileList(node.aggregated);
if (node.orderBy) {
this.append(" ");
this.visitNode(node.orderBy);
}
this.append(")");
if (node.withinGroup) {
this.append(" within group (");
this.visitNode(node.withinGroup);
this.append(")");
}
if (node.filter) {
this.append(" filter(");
this.visitNode(node.filter);
this.append(")");
}
if (node.over) {
this.append(" ");
this.visitNode(node.over);
}
}
visitOver(node) {
this.append("over(");
if (node.partitionBy) {
this.visitNode(node.partitionBy);
if (node.orderBy) this.append(" ");
}
if (node.orderBy) this.visitNode(node.orderBy);
this.append(")");
}
visitPartitionBy(node) {
this.append("partition by ");
this.compileList(node.items);
}
visitPartitionByItem(node) {
this.visitNode(node.partitionBy);
}
visitBinaryOperation(node) {
this.visitNode(node.leftOperand);
this.append(" ");
this.visitNode(node.operator);
this.append(" ");
this.visitNode(node.rightOperand);
}
visitUnaryOperation(node) {
this.visitNode(node.operator);
if (!this.isMinusOperator(node.operator)) this.append(" ");
this.visitNode(node.operand);
}
isMinusOperator(node) {
return OperatorNode.is(node) && node.operator === "-";
}
visitUsing(node) {
this.append("using ");
this.compileList(node.tables);
}
visitFunction(node) {
this.append(node.func);
this.append("(");
this.compileList(node.arguments);
this.append(")");
}
visitCase(node) {
this.append("case");
if (node.value) {
this.append(" ");
this.visitNode(node.value);
}
if (node.when) {
this.append(" ");
this.compileList(node.when, " ");
}
if (node.else) {
this.append(" else ");
this.visitNode(node.else);
}
this.append(" end");
if (node.isStatement) this.append(" case");
}
visitWhen(node) {
this.append("when ");
this.visitNode(node.condition);
if (node.result) {
this.append(" then ");
this.visitNode(node.result);
}
}
visitJSONReference(node) {
this.visitNode(node.reference);
this.visitNode(node.traversal);
}
visitJSONPath(node) {
if (node.inOperator) this.visitNode(node.inOperator);
this.append("'$");
for (const pathLeg of node.pathLegs) this.visitNode(pathLeg);
this.append("'");
}
visitJSONPathLeg(node) {
const isArrayLocation = node.type === "ArrayLocation";
const value = String(node.value);
if (isArrayLocation) {
this.append("[");
this.append(this.sanitizeStringLiteral(value));
this.append("]");
} else {
this.append(".\"");
this.append(this.sanitizeJSONPathMemberValue(value));
this.append("\"");
}
}
visitJSONOperatorChain(node) {
for (let i = 0, len = node.values.length; i < len; i++) {
if (i === len - 1) this.visitNode(node.operator);
else this.append("->");
this.visitNode(node.values[i]);
}
}
visitMergeQuery(node) {
if (node.with) {
this.visitNode(node.with);
this.append(" ");
}
this.append("merge ");
if (node.top) {
this.visitNode(node.top);
this.append(" ");
}
this.append("into ");
this.visitNode(node.into);
if (node.using) {
this.append(" ");
this.visitNode(node.using);
}
if (node.whens) {
this.append(" ");
this.compileList(node.whens, " ");
}
if (node.returning) {
this.append(" ");
this.visitNode(node.returning);
}
if (node.output) {
this.append(" ");
this.visitNode(node.output);
}
if (node.endModifiers?.length) {
this.append(" ");
this.compileList(node.endModifiers, " ");
}
}
visitMatched(node) {
if (node.not) this.append("not ");
this.append("matched");
if (node.bySource) this.append(" by source");
}
visitAddIndex(node) {
if (!this.parentNode || !CreateTableNode.is(this.parentNode)) this.append("add ");
if (node.unique) this.append("unique ");
this.append("index ");
this.visitNode(node.name);
if (node.columns) {
this.append(" (");
this.compileList(node.columns);
this.append(")");
}
if (node.using) {
this.append(" using ");
this.visitNode(node.using);
}
}
visitCast(node) {
this.append("cast(");
this.visitNode(node.expression);
this.append(" as ");
this.visitNode(node.dataType);
this.append(")");
}
visitFetch(node) {
this.append("fetch next ");
this.visitNode(node.rowCount);
this.append(` rows ${node.modifier}`);
}
visitOutput(node) {
this.append("output ");
this.compileList(node.selections);
}
visitTop(node) {
this.append(`top(${node.expression})`);
if (node.modifiers) this.append(` ${node.modifiers}`);
}
visitOrAction(node) {
this.append(node.action);
}
visitCollate(node) {
this.append("collate ");
this.visitNode(node.collation);
}
append(str) {
this.#sql += str;
}
appendValue(parameter) {
this.addParameter(parameter);
this.append(this.getCurrentParameterPlaceholder());
}
getLeftIdentifierWrapper() {
return "\"";
}
getRightIdentifierWrapper() {
return "\"";
}
getCurrentParameterPlaceholder() {
return "$" + this.numParameters;
}
getLeftExplainOptionsWrapper() {
return "(";
}
getExplainOptionAssignment() {
return " ";
}
getExplainOptionsDelimiter() {
return ", ";
}
getRightExplainOptionsWrapper() {
return ")";
}
sanitizeIdentifier(identifier) {
const leftWrap = this.getLeftIdentifierWrapper();
const rightWrap = this.getRightIdentifierWrapper();
let sanitized = "";
for (const c of identifier) {
sanitized += c;
if (c === leftWrap) sanitized += leftWrap;
else if (c === rightWrap) sanitized += rightWrap;
}
return sanitized;
}
sanitizeStringLiteral(value) {
return value.replace(LIT_WRAP_REGEX, "''");
}
sanitizeJSONPathMemberValue(value) {
return value.replace(JSON_PATH_MEMBER_WRAP_REGEX, (char) => char === "'" ? "''" : "\\\"");
}
addParameter(parameter) {
this.#parameters.push(parameter);
}
appendImmediateValue(value) {
if (isString(value)) this.appendStringLiteral(value);
else if (isNumber(value) || isBoolean(value) || isBigInt(value)) this.append(value.toString());
else if (isNull(value)) this.append("null");
else if (isDate(value)) this.appendImmediateValue(value.toISOString());
else throw new Error(`invalid immediate value ${value}`);
}
appendStringLiteral(value) {
this.append("'");
this.append(this.sanitizeStringLiteral(value));
this.append("'");
}
sortSelectModifiers(arr) {
return freeze(arr.toSorted((left, right) => left.modifier && right.modifier ? SELECT_MODIFIER_PRIORITY[left.modifier] - SELECT_MODIFIER_PRIORITY[right.modifier] : 1));
}
compileColumnAlterations(columnAlterations) {
this.compileList(columnAlterations);
}
/**
* controls whether the dialect adds a "type" keyword before a column's new data
* type in an ALTER TABLE statement.
*/
announcesNewColumnDataType() {
return true;
}
};
SELECT_MODIFIER_SQL = freeze({
ForKeyShare: "for key share",
ForNoKeyUpdate: "for no key update",
ForUpdate: "for update",
ForShare: "for share",
NoWait: "nowait",
SkipLocked: "skip locked",
Distinct: "distinct"
});
SELECT_MODIFIER_PRIORITY = freeze({
ForKeyShare: 1,
ForNoKeyUpdate: 1,
ForUpdate: 1,
ForShare: 1,
NoWait: 2,
SkipLocked: 2,
Distinct: 0
});
JOIN_TYPE_SQL = freeze({
InnerJoin: "inner join",
LeftJoin: "left join",
RightJoin: "right join",
FullJoin: "full join",
CrossJoin: "cross join",
LateralInnerJoin: "inner join lateral",
LateralLeftJoin: "left join lateral",
LateralCrossJoin: "cross join lateral",
OuterApply: "outer apply",
CrossApply: "cross apply",
Using: "using"
});
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/query-compiler/compiled-query.js
var CompiledQuery;
var init_compiled_query = __esmMin((() => {
init_raw_node();
init_object_utils();
init_query_id();
CompiledQuery = freeze({ raw(sql, parameters = []) {
return freeze({
sql,
query: RawNode.createWithSql(sql),
parameters: freeze(parameters),
queryId: createQueryId()
});
} });
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/driver/dummy-driver.js
var init_dummy_driver = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/dialect-adapter-base.js
var DialectAdapterBase;
var init_dialect_adapter_base = __esmMin((() => {
DialectAdapterBase = class {
get supportsCreateIfNotExists() {
return true;
}
get supportsMultipleConnections() {
return true;
}
get supportsTransactionalDdl() {
return false;
}
get supportsReturning() {
return false;
}
get supportsOutput() {
return false;
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/parser/savepoint-parser.js
function parseSavepointCommand(command, savepointName) {
return RawNode.createWithChildren([RawNode.createWithSql(`${command} `), IdentifierNode.create(savepointName)]);
}
var init_savepoint_parser = __esmMin((() => {
init_identifier_node();
init_raw_node();
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/sqlite/sqlite-driver.js
var SqliteDriver, SqliteConnection;
var init_sqlite_driver = __esmMin((() => {
init_select_query_node();
init_savepoint_parser();
init_compiled_query();
init_object_utils();
init_query_id();
SqliteDriver = class {
#config;
#db;
#connection;
constructor(config) {
this.#config = freeze({ ...config });
}
async init(options) {
this.#db = isFunction(this.#config.database) ? await this.#config.database(options) : this.#config.database;
this.#connection = new SqliteConnection(this.#db);
if (this.#config.onCreateConnection) await this.#config.onCreateConnection(this.#connection, options);
}
async acquireConnection() {
return this.#connection;
}
async beginTransaction(connection) {
await connection.executeQuery(CompiledQuery.raw("begin"));
}
async commitTransaction(connection) {
await connection.executeQuery(CompiledQuery.raw("commit"));
}
async rollbackTransaction(connection) {
await connection.executeQuery(CompiledQuery.raw("rollback"));
}
async savepoint(connection, savepointName, compileQuery) {
await connection.executeQuery(compileQuery(parseSavepointCommand("savepoint", savepointName), createQueryId()));
}
async rollbackToSavepoint(connection, savepointName, compileQuery) {
await connection.executeQuery(compileQuery(parseSavepointCommand("rollback to", savepointName), createQueryId()));
}
async releaseSavepoint(connection, savepointName, compileQuery) {
await connection.executeQuery(compileQuery(parseSavepointCommand("release", savepointName), createQueryId()));
}
async releaseConnection() {}
async destroy() {
this.#db?.close();
}
};
SqliteConnection = class {
#db;
constructor(db) {
this.#db = db;
}
async executeQuery(compiledQuery) {
const { sql, parameters } = compiledQuery;
const stmt = this.#db.prepare(sql);
if (stmt.reader) return { rows: stmt.all(parameters) };
const { changes, lastInsertRowid } = stmt.run(parameters);
return {
insertId: lastInsertRowid != null ? BigInt(lastInsertRowid) : void 0,
numAffectedRows: changes != null ? BigInt(changes) : void 0,
rows: []
};
}
async *streamQuery(compiledQuery, _chunkSize) {
const { sql, parameters, query } = compiledQuery;
const stmt = this.#db.prepare(sql);
if (!SelectQueryNode.is(query)) throw new Error("Sqlite driver only supports streaming of select queries");
const iter = stmt.iterate(parameters);
for (const row of iter) yield { rows: [row] };
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/sqlite/sqlite-query-compiler.js
var ID_WRAP_REGEX, JSON_PATH_MEMBER_ESCAPE_REGEX, SqliteQueryCompiler;
var init_sqlite_query_compiler = __esmMin((() => {
init_default_query_compiler();
ID_WRAP_REGEX = /"/g;
JSON_PATH_MEMBER_ESCAPE_REGEX = /[\\'"]/g;
SqliteQueryCompiler = class extends DefaultQueryCompiler {
visitOrAction(node) {
this.append("or ");
this.append(node.action);
}
getCurrentParameterPlaceholder() {
return "?";
}
getLeftExplainOptionsWrapper() {
return "";
}
getRightExplainOptionsWrapper() {
return "";
}
getLeftIdentifierWrapper() {
return "\"";
}
getRightIdentifierWrapper() {
return "\"";
}
getAutoIncrement() {
return "autoincrement";
}
sanitizeIdentifier(identifier) {
return identifier.replace(ID_WRAP_REGEX, "\"\"");
}
sanitizeJSONPathMemberValue(value) {
return value.replace(JSON_PATH_MEMBER_ESCAPE_REGEX, (char) => char === "\\" ? "\\\\" : char === "'" ? "''" : "\\\"");
}
visitDefaultInsertValue(_) {
this.append("null");
}
};
})), DEFAULT_MIGRATION_TABLE, DEFAULT_MIGRATION_LOCK_TABLE;
var init_migrator = __esmMin((() => {
init_object_utils();
DEFAULT_MIGRATION_TABLE = "kysely_migration";
DEFAULT_MIGRATION_LOCK_TABLE = "kysely_migration_lock";
freeze({ __noMigrations__: true });
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/sqlite/sqlite-introspector.js
var SqliteIntrospector;
var init_sqlite_introspector = __esmMin((() => {
init_migrator();
init_sql();
SqliteIntrospector = class {
#db;
constructor(db) {
this.#db = db;
}
async getSchemas() {
return [];
}
async getTables(options = { withInternalKyselyTables: false }) {
return await this.#getTableMetadata(options);
}
#tablesQuery(qb, options) {
let tablesQuery = qb.selectFrom("sqlite_master").where("type", "in", ["table", "view"]).where("name", "not like", "sqlite_%").select([
"name",
"sql",
"type"
]).orderBy("name");
if (!options.withInternalKyselyTables) tablesQuery = tablesQuery.where("name", "!=", DEFAULT_MIGRATION_TABLE).where("name", "!=", DEFAULT_MIGRATION_LOCK_TABLE);
return tablesQuery;
}
async #getTableMetadata(options) {
const tablesResult = await this.#tablesQuery(this.#db, options).execute();
const tableMetadata = await this.#db.with("table_list", (qb) => this.#tablesQuery(qb, options)).selectFrom(["table_list as tl", sql`pragma_table_info(tl.name)`.as("p")]).select([
"tl.name as table",
"p.cid",
"p.name",
"p.type",
"p.notnull",
"p.dflt_value",
"p.pk"
]).orderBy("tl.name").orderBy("p.cid").execute();
const columnsByTable = {};
for (const row of tableMetadata) {
columnsByTable[row.table] ??= [];
columnsByTable[row.table].push(row);
}
return tablesResult.map(({ name, sql, type }) => {
let autoIncrementCol = sql?.split(/[\(\),]/)?.find((it) => it.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g, "");
const columns = columnsByTable[name] ?? [];
if (!autoIncrementCol) {
const pkCols = columns.filter((r) => r.pk > 0);
if (pkCols.length === 1 && pkCols[0].type.toLowerCase() === "integer") autoIncrementCol = pkCols[0].name;
}
return {
name,
isView: type === "view",
isForeign: false,
columns: columns.map((col) => ({
name: col.name,
dataType: col.type,
isNullable: !col.notnull,
isAutoIncrementing: col.name === autoIncrementCol,
hasDefaultValue: col.dflt_value != null,
comment: void 0
}))
};
});
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/sqlite/sqlite-adapter.js
var SqliteAdapter;
var init_sqlite_adapter = __esmMin((() => {
init_dialect_adapter_base();
SqliteAdapter = class extends DialectAdapterBase {
get supportsMultipleConnections() {
return false;
}
get supportsTransactionalDdl() {
return false;
}
get supportsReturning() {
return true;
}
async acquireMigrationLock(_db, _opt) {}
async releaseMigrationLock(_db, _opt) {}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/sqlite/sqlite-dialect.js
var SqliteDialect;
var init_sqlite_dialect = __esmMin((() => {
init_sqlite_driver();
init_sqlite_query_compiler();
init_sqlite_introspector();
init_sqlite_adapter();
init_object_utils();
SqliteDialect = class {
#config;
constructor(config) {
this.#config = freeze({ ...config });
}
createDriver() {
return new SqliteDriver(this.#config);
}
createQueryCompiler() {
return new SqliteQueryCompiler();
}
createAdapter() {
return new SqliteAdapter();
}
createIntrospector(db) {
return new SqliteIntrospector(db);
}
};
}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mysql/mysql-driver.js
var init_mysql_driver = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mysql/mysql-query-compiler.js
var init_mysql_query_compiler = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mysql/mysql-introspector.js
var init_mysql_introspector = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mysql/mysql-adapter.js
var init_mysql_adapter = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mysql/mysql-dialect.js
var init_mysql_dialect = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/postgres/postgres-driver.js
var init_postgres_driver = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/postgres/postgres-introspector.js
var init_postgres_introspector = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/postgres/postgres-query-compiler.js
var init_postgres_query_compiler = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/postgres/postgres-adapter.js
var init_postgres_adapter = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/postgres/postgres-dialect.js
var init_postgres_dialect = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mssql/mssql-adapter.js
var init_mssql_adapter = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mssql/mssql-driver.js
var init_mssql_driver = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mssql/mssql-introspector.js
var init_mssql_introspector = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mssql/mssql-query-compiler.js
var init_mssql_query_compiler = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/mssql/mssql-dialect.js
var init_mssql_dialect = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/pglite/pglite-adapter.js
var init_pglite_adapter = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/pglite/pglite-driver.js
var init_pglite_driver = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/dialect/pglite/pglite-dialect.js
var init_pglite_dialect = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/camel-case/camel-case-plugin.js
var init_camel_case_plugin = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/deduplicate-joins/deduplicate-joins-plugin.js
var init_deduplicate_joins_plugin = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/parse-json-results/parse-json-results-plugin.js
var init_parse_json_results_plugin = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/handle-empty-in-lists/handle-empty-in-lists-plugin.js
var init_handle_empty_in_lists_plugin = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/handle-empty-in-lists/handle-empty-in-lists.js
var init_handle_empty_in_lists = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/plugin/safe-null-comparison/safe-null-comparison-plugin.js
var init_safe_null_comparison_plugin = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/constraint-node.js
var init_constraint_node = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/operation-node/simple-reference-expression-node.js
var init_simple_reference_expression_node = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/kysely@0.29.6/node_modules/kysely/dist/index.js
var init_dist = __esmMin((() => {
init_kysely();
init_query_creator();
init_query_finalizer();
init_expression();
init_expression_builder();
init_expression_wrapper();
init_select_query_builder();
init_insert_query_builder();
init_update_query_builder();
init_delete_query_builder();
init_no_result_error();
init_join_builder();
init_function_module();
init_insert_result();
init_delete_result();
init_update_result();
init_on_conflict_builder();
init_aggregate_function_builder();
init_case_builder();
init_json_path_builder();
init_merge_query_builder();
init_merge_result();
init_order_by_item_builder();
init_raw_builder();
init_sql();
init_default_query_executor();
init_noop_query_executor();
init_default_query_compiler();
init_compiled_query();
init_schema_module();
init_create_table_builder();
init_create_type_builder();
init_drop_table_builder();
init_drop_type_builder();
init_create_index_builder();
init_drop_index_builder();
init_create_schema_builder();
init_drop_schema_builder();
init_column_definition_builder();
init_foreign_key_constraint_builder();
init_alter_table_builder();
init_create_view_builder();
init_refresh_materialized_view_builder();
init_drop_view_builder();
init_alter_column_builder();
init_drop_column_builder();
init_dynamic();
init_dynamic_reference_builder();
init_dynamic_table_builder();
init_driver();
init_default_connection_provider();
init_single_connection_provider();
init_dummy_driver();
init_dialect_adapter_base();
init_sqlite_dialect();
init_sqlite_driver();
init_sqlite_query_compiler();
init_sqlite_introspector();
init_sqlite_adapter();
init_mysql_dialect();
init_mysql_driver();
init_mysql_query_compiler();
init_mysql_introspector();
init_mysql_adapter();
init_postgres_driver();
init_postgres_dialect();
init_postgres_query_compiler();
init_postgres_introspector();
init_postgres_adapter();
init_mssql_adapter();
init_mssql_dialect();
init_mssql_driver();
init_mssql_introspector();
init_mssql_query_compiler();
init_pglite_adapter();
init_pglite_driver();
init_pglite_dialect();
init_default_query_compiler();
init_camel_case_plugin();
init_deduplicate_joins_plugin();
init_with_schema_plugin();
init_parse_json_results_plugin();
init_handle_empty_in_lists_plugin();
init_handle_empty_in_lists();
init_safe_null_comparison_plugin();
init_add_column_node();
init_add_constraint_node();
init_add_index_node();
init_aggregate_function_node();
init_alias_node();
init_alter_column_node();
init_alter_table_node();
init_and_node();
init_binary_operation_node();
init_case_node();
init_cast_node();
init_check_constraint_node();
init_collate_node();
init_column_definition_node();
init_column_node();
init_column_update_node();
init_common_table_expression_name_node();
init_common_table_expression_node();
init_constraint_node();
init_create_index_node();
init_create_schema_node();
init_create_table_node();
init_create_type_node();
init_create_view_node();
init_refresh_materialized_view_node();
init_data_type_node();
init_default_insert_value_node();
init_default_value_node();
init_delete_query_node();
init_drop_column_node();
init_drop_constraint_node();
init_drop_index_node();
init_drop_schema_node();
init_drop_table_node();
init_drop_type_node();
init_drop_view_node();
init_explain_node();
init_fetch_node();
init_foreign_key_constraint_node();
init_from_node();
init_function_node();
init_generated_node();
init_group_by_item_node();
init_group_by_node();
init_having_node();
init_identifier_node();
init_insert_query_node();
init_join_node();
init_json_operator_chain_node();
init_json_path_leg_node();
init_json_path_node();
init_json_reference_node();
init_limit_node();
init_list_node();
init_matched_node();
init_merge_query_node();
init_modify_column_node();
init_offset_node();
init_on_conflict_node();
init_on_duplicate_key_node();
init_on_node();
init_operation_node_source();
init_operation_node_transformer();
init_operation_node_visitor();
init_operator_node();
init_or_action_node();
init_or_node();
init_order_by_item_node();
init_order_by_node();
init_output_node();
init_over_node();
init_parens_node();
init_partition_by_item_node();
init_partition_by_node();
init_primary_key_constraint_node();
init_primitive_value_list_node();
init_query_node();
init_raw_node();
init_reference_node();
init_references_node();
init_rename_column_node();
init_rename_constraint_node();
init_returning_node();
init_schemable_identifier_node();
init_select_all_node();
init_select_modifier_node();
init_select_query_node();
init_selection_node();
init_set_operation_node();
init_simple_reference_expression_node();
init_table_node();
init_top_node();
init_tuple_node();
init_unary_operation_node();
init_unique_constraint_node();
init_update_query_node();
init_using_node();
init_value_list_node();
init_value_node();
init_values_node();
init_when_node();
init_where_node();
init_with_node();
init_alter_type_node();
init_add_value_node();
init_rename_value_node();
init_compilable();
init_log();
init_log_once();
init_query_id();
}));
//#endregion
//#region node-version.mjs
/** Parses an anchored release SemVer, allowing a leading v and valid build metadata. */
function parseNodeReleaseVersion(value) {
if (typeof value !== "string") return null;
const match = NODE_RELEASE_VERSION_RE.exec(value.trim());
if (!match) return null;
const version = {
major: Number(match[1]),
minor: Number(match[2]),
patch: Number(match[3])
};
return Object.values(version).every(Number.isSafeInteger) ? version : null;
}
function isNodeVersionAtLeast(version, minimum) {
if (!version) return false;
if (version.major !== minimum.major) return version.major > minimum.major;
if (version.minor !== minimum.minor) return version.minor > minimum.minor;
return version.patch >= minimum.patch;
}
function renderProcessNodeVersionCheck() {
return `((value) => {
if (typeof value !== "string") return false;
const match = new RegExp(${JSON.stringify(NODE_RELEASE_VERSION_RE.source)}, "u").exec(value.trim());
if (!match) return false;
const version = { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) };
if (!Object.values(version).every(Number.isSafeInteger)) return false;
const floors = ${JSON.stringify(NODE_RELEASE_FLOORS)};
const minimum = floors.find((floor) => floor.major === version.major);
const atLeast = (floor) =>
version.major > floor.major ||
(version.major === floor.major &&
(version.minor > floor.minor ||
(version.minor === floor.minor && version.patch >= floor.patch)));
return minimum ? atLeast(minimum) : version.major > floors[floors.length - 1].major;
})(process.versions.node)`;
}
var NODE_RELEASE_VERSION_RE, NODE_RELEASE_FLOORS, SUPPORTED_NODE_VERSION_RANGE;
var init_node_version = __esmMin((() => {
NODE_RELEASE_VERSION_RE = /^v?((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u;
NODE_RELEASE_FLOORS = [{
major: 24,
minor: 16,
patch: 0
}, {
major: 26,
minor: 1,
patch: 0
}];
NODE_RELEASE_FLOORS[NODE_RELEASE_FLOORS.length - 1];
SUPPORTED_NODE_VERSION_RANGE = NODE_RELEASE_FLOORS.map(({ major, minor, patch }, index) => `>=${major}.${minor}.${patch}${index < NODE_RELEASE_FLOORS.length - 1 ? ` <${major + 1}` : ""}`).join(" || ");
`${SUPPORTED_NODE_VERSION_RANGE.replaceAll(" || ", ", ").replace(/, ([^,]+)$/, ", or $1")}`;
renderProcessNodeVersionCheck();
}));
//#endregion
//#region src/shared/global-singleton.ts
function resolveGlobalSingletonResetRegistry() {
const globalStore = globalThis;
const existing = globalStore[GLOBAL_SINGLETON_RESETS_KEY];
if (existing instanceof Map) return existing;
const created = /* @__PURE__ */ new Map();
globalStore[GLOBAL_SINGLETON_RESETS_KEY] = created;
return created;
}
/** Resolves a process-local singleton for caches and registries that tolerate helper lookup. */
function resolveGlobalSingleton(key, create, reset, lifecycle = "close-and-restart") {
const globalStore = globalThis;
let value;
if (Object.hasOwn(globalStore, key)) value = globalStore[key];
else {
value = create();
globalStore[key] = value;
}
if (reset) resolveGlobalSingletonResetRegistry().set(key, {
lifecycle,
reset: () => reset(value)
});
return value;
}
/** Resolves a lifecycle-owned process-local Set singleton. */
function resolveGlobalSet(key, lifecycle) {
return resolveGlobalSingleton(key, () => /* @__PURE__ */ new Set(), (value) => value.clear(), lifecycle);
}
var GLOBAL_SINGLETON_RESETS_KEY;
var init_global_singleton = __esmMin((() => {
GLOBAL_SINGLETON_RESETS_KEY = Symbol.for("openclaw.globalSingletonLifecycleResets");
}));
//#endregion
//#region src/infra/map-size.ts
/** Prunes a Map in insertion order until it fits the requested maximum size. */
function pruneMapToMaxSize(map, maxSize) {
if (Number.isNaN(maxSize) || maxSize === Number.POSITIVE_INFINITY) return;
const limit = Math.max(0, Math.floor(maxSize));
if (limit <= 0) {
map.clear();
return;
}
if (map.size <= limit) return;
const keys = map.keys();
while (map.size > limit) {
const oldest = keys.next();
if (oldest.done) break;
map.delete(oldest.value);
}
}
var init_map_size = __esmMin((() => {}));
//#endregion
//#region src/infra/kysely-sync-cache-state.ts
/** Retire dependent native resources before this connection closes or is replaced. */
function registerNodeSqliteDisposeCallback(db, callback) {
const owner = db;
installStatementInvalidation(owner);
const callbacks = owner[disposeCallbacksSymbol] ??= /* @__PURE__ */ new Set();
callbacks.add(callback);
return () => {
callbacks.delete(callback);
};
}
function disposeNodeSqliteDependents(owner, reason = "close") {
for (const callback of owner[disposeCallbacksSymbol] ?? []) callback(reason);
}
/** Register the lifecycle owner's handler for synchronous Kysely query failures. */
function registerNodeSqliteKyselyQueryErrorHandler(db, handler) {
queryErrorHandlerByDatabase.set(db, handler);
}
/** Drop cached Kysely state for a DatabaseSync. */
function clearNodeSqliteKyselyCacheForDatabase(db) {
delete db[statementCacheSymbol];
kyselyByDatabase.delete(db);
queryErrorHandlerByDatabase.delete(db);
}
function installStatementInvalidation(owner) {
if (owner[statementInvalidationSymbol]) return;
if (typeof owner.setAuthorizer === "function") {
const setAuthorizer = owner.setAuthorizer.bind(owner);
Object.defineProperty(owner, "setAuthorizer", {
configurable: true,
writable: true,
value(callback) {
setAuthorizer(callback);
this[authorizerActiveSymbol] = callback !== null;
delete this[statementCacheSymbol];
}
});
}
if (typeof owner.deserialize === "function") {
const deserialize = owner.deserialize.bind(owner);
Object.defineProperty(owner, "deserialize", {
configurable: true,
writable: true,
value(...args) {
disposeNodeSqliteDependents(this, "replace");
try {
deserialize(...args);
} finally {
delete this[statementCacheSymbol];
}
}
});
}
for (const method of ["close", Symbol.dispose]) if (typeof owner[method] === "function") {
const dispose = owner[method].bind(owner);
Object.defineProperty(owner, method, {
configurable: true,
writable: true,
value() {
disposeNodeSqliteDependents(this);
clearNodeSqliteKyselyCacheForDatabase(this);
return dispose();
}
});
}
Object.defineProperty(owner, statementInvalidationSymbol, {
configurable: true,
value: true
});
}
function queryFitsStatementCache(sql, parameters) {
let bytes = Buffer.byteLength(sql);
if (bytes > statementCacheEntryBytes) return false;
for (const parameter of parameters) {
if (typeof parameter === "string") {
if (parameter.length > statementCacheEntryBytes - bytes) return false;
bytes += Buffer.byteLength(parameter);
} else if (ArrayBuffer.isView(parameter)) bytes += parameter.byteLength;
if (bytes > statementCacheEntryBytes) return false;
}
return true;
}
function executeWithCachedStatement(db, sql, parameters, execute) {
const owner = db;
if (!owner[statementCacheEnabledSymbol] || owner[authorizerActiveSymbol] || !queryFitsStatementCache(sql, parameters)) return execute(db.prepare(sql));
let cache = owner[statementCacheSymbol];
if (!cache) {
cache = {
statements: /* @__PURE__ */ new Map(),
candidates: /* @__PURE__ */ new Set(),
active: /* @__PURE__ */ new WeakSet()
};
Object.defineProperty(owner, statementCacheSymbol, {
configurable: true,
value: cache
});
}
const cached = cache.statements.get(sql);
let statement;
if (cached && !cache.active.has(cached)) {
cache.statements.delete(sql);
cache.statements.set(sql, cached);
statement = cached;
} else {
statement = db.prepare(sql);
if (!cached && cache.candidates.delete(sql)) {
cache.statements.set(sql, statement);
pruneMapToMaxSize(cache.statements, statementCacheCapacity);
} else if (!cached) {
cache.candidates.add(sql);
if (cache.candidates.size > statementCacheCapacity) {
const oldestCandidate = cache.candidates.values().next().value;
if (oldestCandidate !== void 0) cache.candidates.delete(oldestCandidate);
}
}
}
cache.active.add(statement);
try {
return execute(statement);
} finally {
cache.active.delete(statement);
}
}
var kyselyByDatabase, queryErrorHandlerByDatabase, statementCacheSymbol, statementInvalidationSymbol, statementCacheEnabledSymbol, authorizerActiveSymbol, disposeCallbacksSymbol, statementCacheCapacity, statementCacheEntryBytes;
var init_kysely_sync_cache_state = __esmMin((() => {
init_global_singleton();
init_map_size();
({kyselyByDatabase, queryErrorHandlerByDatabase} = resolveGlobalSingleton(Symbol.for("openclaw.sqliteKyselyCacheState"), () => ({
kyselyByDatabase: /* @__PURE__ */ new WeakMap(),
queryErrorHandlerByDatabase: /* @__PURE__ */ new WeakMap()
})));
statementCacheSymbol = Symbol.for("openclaw.kyselySyncStatementCache");
statementInvalidationSymbol = Symbol.for("openclaw.kyselySyncStatementInvalidation");
statementCacheEnabledSymbol = Symbol.for("openclaw.kyselySyncStatementCacheEnabled");
authorizerActiveSymbol = Symbol.for("openclaw.kyselySyncAuthorizerActive");
disposeCallbacksSymbol = Symbol.for("openclaw.sqliteDisposeCallbacks");
statementCacheCapacity = 64;
statementCacheEntryBytes = 65536;
}));
//#endregion
//#region src/infra/sqlite-reader-lifecycle.ts
/** The same Windows file can arrive with a namespaced or differently cased path. */
function sqliteReaderDatabasePathKey(databasePath) {
const resolved = path.resolve(databasePath);
return process.platform === "win32" ? normalizeWindowsPathForComparison(resolved) : resolved;
}
function boundedOperation(operation) {
return (operation.trim() || "sqlite reader").slice(0, 120);
}
function captureSqliteReaderOwner() {
const owner = readerOwners.getStore();
return owner ? { ...owner } : void 0;
}
function currentOwner(fallbackOperation, capturedOwner) {
const inherited = capturedOwner ?? readerOwners.getStore();
return {
operation: boundedOperation(inherited?.operation ?? fallbackOperation),
ownerKind: inherited?.ownerKind ?? (isMainThread ? "main" : "worker"),
...inherited?.actorId !== void 0 ? { actorId: inherited.actorId } : {}
};
}
function connectionFor(database) {
let connection = connections.byDatabase.get(database);
if (!connection) {
const now = Date.now();
const location = database.location();
connection = {
id: ++connections.nextId,
path: location ? sqliteReaderDatabasePathKey(location) : void 0,
database: new WeakRef(database),
owner: currentOwner("sqlite connection"),
openedAtMs: now
};
connections.byDatabase.set(database, connection);
if (connection.path) {
const entries = connections.byPath.get(connection.path) ?? /* @__PURE__ */ new Map();
entries.set(connection.id, connection);
connections.byPath.set(connection.path, entries);
}
connections.finalizer.register(database, connection, connection);
}
return connection;
}
/** Forget observations only; explicit reader custody belongs to its caller. */
function forgetConnection(connection) {
if (connection.path) {
const entries = connections.byPath.get(connection.path);
entries?.delete(connection.id);
if (entries?.size === 0) connections.byPath.delete(connection.path);
}
const database = connection.database.deref();
if (database && connections.byDatabase.get(database) === connection) connections.byDatabase.delete(database);
connections.finalizer.unregister(connection);
}
/** Register weak metadata without replacing native methods or acquiring lifecycle custody. */
function registerSqliteReaderConnection(database) {
if (database.isOpen) connectionFor(database);
}
function retainSqliteReader(database, fallbackOperation, capturedOwner) {
const connection = connectionFor(database);
const now = Date.now();
const reader = {
...currentOwner(fallbackOperation, capturedOwner),
kind: "iterator",
connectionId: connection.id,
threadId,
startedAtMs: now,
lastProgressAtMs: now
};
const token = Symbol(reader.operation);
const databaseReaders = activeReaders.byDatabase.get(database) ?? /* @__PURE__ */ new Map();
databaseReaders.set(token, reader);
activeReaders.byDatabase.set(database, databaseReaders);
const databasePath = connection.path;
const pathReaders = databasePath ? activeReaders.byPath.get(databasePath) ?? /* @__PURE__ */ new Map() : void 0;
pathReaders?.set(token, reader);
if (databasePath && pathReaders) activeReaders.byPath.set(databasePath, pathReaders);
let released = false;
return {
progress() {
if (!released) reader.lastProgressAtMs = Date.now();
},
release() {
if (released) return;
released = true;
databaseReaders.delete(token);
if (databaseReaders.size === 0 && activeReaders.byDatabase.get(database) === databaseReaders) activeReaders.byDatabase.delete(database);
pathReaders?.delete(token);
if (databasePath && pathReaders?.size === 0 && activeReaders.byPath.get(databasePath) === pathReaders) activeReaders.byPath.delete(databasePath);
}
};
}
var readerOwners, activeReaders, connections;
var init_sqlite_reader_lifecycle = __esmMin((() => {
init_global_singleton();
readerOwners = resolveGlobalSingleton(Symbol.for("openclaw.sqliteReaderOwners"), () => new AsyncLocalStorage());
activeReaders = resolveGlobalSingleton(Symbol.for("openclaw.sqliteActiveReaders"), () => ({
byDatabase: /* @__PURE__ */ new WeakMap(),
byPath: /* @__PURE__ */ new Map()
}));
connections = resolveGlobalSingleton(Symbol.for("openclaw.sqliteReaderConnections"), () => ({
nextId: 0,
byDatabase: /* @__PURE__ */ new WeakMap(),
byPath: /* @__PURE__ */ new Map(),
finalizer: new FinalizationRegistry((connection) => forgetConnection(connection))
}));
}));
//#endregion
//#region src/infra/kysely-sync.ts
function getNodeSqliteKysely(db) {
const existing = kyselyByDatabase.get(db);
if (existing) return existing;
const kysely = new Kysely({ dialect: compileOnlySqliteDialect });
kyselyByDatabase.set(db, kysely);
return kysely;
}
function reportNodeSqliteKyselyQueryError(db, error) {
try {
queryErrorHandlerByDatabase.get(db)?.(error);
} catch {}
}
/** Execute a compiled Kysely query synchronously against node:sqlite. */
function executeCompiledSqliteQuerySync(db, compiledQuery, firstRowOnly = false, parameters = compiledQuery.parameters) {
try {
const sql = compiledQuery.sql;
installStatementInvalidation(db);
return executeWithCachedStatement(db, sql, parameters, (statement) => {
if (firstRowOnly && SelectQueryNode.is(compiledQuery.query)) {
const row = statement.get(...parameters);
return { rows: row === void 0 ? [] : [row] };
}
if (SelectQueryNode.is(compiledQuery.query) || statement.columns().length > 0) {
if (supportsRepreparedAll) return { rows: statement.all(...parameters) };
const iterator = statement.iterate(...parameters);
const reader = retainSqliteReader(db, "kysely eager query");
let cleanupError;
let failed = false;
let failure;
const rows = [];
try {
for (const row of iterator) {
reader.progress();
rows.push(row);
}
} catch (error) {
failed = true;
failure = error;
}
try {
iterator.return?.();
} catch (error) {
cleanupError = error;
}
reader.release();
if (failed) throw toErrorObject(failure, "SQLite query failed");
if (cleanupError !== void 0) throw toErrorObject(cleanupError, "SQLite query cleanup failed");
return { rows };
}
statement.setReadBigInts(true);
let outcome;
try {
outcome = statement.run(...parameters);
} finally {
statement.setReadBigInts(false);
}
const { changes, lastInsertRowid } = outcome;
const result = {
numAffectedRows: BigInt(changes),
rows: []
};
if (InsertQueryNode.is(compiledQuery.query) && changes > 0) return {
...result,
insertId: BigInt(lastInsertRowid)
};
return result;
});
} catch (error) {
reportNodeSqliteKyselyQueryError(db, error);
throw error;
}
}
/** Compile and execute a Kysely query synchronously. */
function executeSqliteQuerySync(db, query) {
return executeCompiledSqliteQuerySync(db, query.compile());
}
/** Compile fixed SQL and fresh bindings without taking ownership of a native statement. */
function compileSqliteQueryBindings(build) {
const bindings = /* @__PURE__ */ new Map();
const compiled = build((read) => {
const marker = Symbol("sqlite-query-parameter");
bindings.set(marker, read);
return sql`${marker}`;
}).compile();
const readers = compiled.parameters.map((value) => bindings.get(value) ?? (() => value));
return {
compiled,
bind: (params) => readers.map((read) => read(params))
};
}
/** Compile a fixed query once; bind fresh values through the normal sync executor on each call. */
function prepareSqliteQuerySync(db, build) {
const { compiled, bind } = compileSqliteQueryBindings(build);
return (params) => executeCompiledSqliteQuerySync(db, compiled, false, bind(params));
}
/** Execute a Kysely query synchronously and return its first row. */
function executeSqliteQueryTakeFirstSync(db, query) {
return executeCompiledSqliteQuerySync(db, query.compile(), true).rows[0];
}
var nodeVersion, supportsRepreparedAll, compileOnlySqliteDialect;
var init_kysely_sync = __esmMin((() => {
init_error_coercion();
init_dist();
init_node_version();
init_kysely_sync_cache_state();
init_sqlite_reader_lifecycle();
nodeVersion = parseNodeReleaseVersion(process.versions.node);
supportsRepreparedAll = !process.versions.bun && (nodeVersion?.major === 24 && isNodeVersionAtLeast(nodeVersion, {
major: 24,
minor: 20,
patch: 0
}) || isNodeVersionAtLeast(nodeVersion, {
major: 26,
minor: 6,
patch: 0
}));
compileOnlySqliteDialect = new SqliteDialect({ database: async () => {
throw new Error("getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.");
} });
}));
//#endregion
//#region src/infra/sqlite-schema-sql.ts
/** Select canonical DDL without opening a database or changing its installation lifecycle. */
function extractSqliteTableSchema(schema, table, options = {}) {
const start = schema.indexOf(`CREATE TABLE IF NOT EXISTS ${table} (`);
const endMarker = options.endMarker ?? "\n) STRICT;";
const end = schema.indexOf(endMarker, start);
if (start < 0 || end < start) throw new Error(options.errorMessage ?? `Canonical schema markers are missing for ${table}`);
return schema.slice(start, end + (options.includeEndMarker === false ? 0 : endMarker.length));
}
function readTableConstraintKeyword(sql, first) {
let token = first;
if (token.keyword === "CONSTRAINT") {
const name = readSqlToken(sql, token.end);
token = name ? readSqlToken(sql, name.end) : null;
}
return token?.keyword && TABLE_CONSTRAINT_KEYWORDS.has(token.keyword) ? token.keyword : null;
}
function readSqlToken(sql, start) {
let index = start;
while (index < sql.length && /\s/u.test(sql[index] ?? "")) index += 1;
const char = sql[index];
if (!char) return null;
if (char === "\"" || char === "`" || char === "[") {
const end = skipSqlQuoted(sql, index, char);
return {
end,
keyword: null,
raw: sql.slice(index, end)
};
}
let end = index;
while (end < sql.length && !/[\s(,]/u.test(sql[end] ?? "")) end += 1;
const raw = sql.slice(index, end);
return {
end,
keyword: raw.toUpperCase(),
raw
};
}
function normalizeSqlIdentifier(identifier) {
if (identifier.startsWith("\"") && identifier.endsWith("\"")) return identifier.slice(1, -1).replaceAll("\"\"", "\"").toLowerCase();
if (identifier.startsWith("`") && identifier.endsWith("`")) return identifier.slice(1, -1).replaceAll("``", "`").toLowerCase();
if (identifier.startsWith("[") && identifier.endsWith("]")) return identifier.slice(1, -1).toLowerCase();
return identifier.toLowerCase();
}
function normalizeSchemaSql(sql) {
if (sql === null) return null;
return normalizeSqlWhitespace(sql).replace(/;\s*$/u, "").trim().replace(/^(CREATE (?:TABLE|VIRTUAL TABLE|UNIQUE INDEX|INDEX|TRIGGER)) IF NOT EXISTS /iu, "$1 ");
}
function splitSqlList(sql) {
const items = [];
let depth = 0;
let start = 0;
let index = 0;
while (index < sql.length) {
const next = skipSqlQuotedOrComment(sql, index);
if (next !== index) {
index = next;
continue;
}
const char = sql[index];
if (char === "(") depth += 1;
else if (char === ")") depth -= 1;
else if (char === "," && depth === 0) {
items.push(sql.slice(start, index));
start = index + 1;
}
index += 1;
}
items.push(sql.slice(start));
return items;
}
function findSqlCharacter(sql, character) {
let index = 0;
while (index < sql.length) {
const next = skipSqlQuotedOrComment(sql, index);
if (next !== index) {
index = next;
continue;
}
if (sql[index] === character) return index;
index += 1;
}
return -1;
}
function findSqlClosingParenthesis(sql, open) {
let depth = 0;
let index = open;
while (index < sql.length) {
const next = skipSqlQuotedOrComment(sql, index);
if (next !== index) {
index = next;
continue;
}
const char = sql[index];
if (char === "(") depth += 1;
else if (char === ")") {
depth -= 1;
if (depth === 0) return index;
}
index += 1;
}
throw new Error("SQLite schema contains an unterminated table definition.");
}
function normalizeSqlWhitespace(sql) {
let normalized = "";
let pendingSpace = false;
const segments = /[^\s'"`[/-]+|\s+|./gsu;
let segment;
while (segment = segments.exec(sql)) {
const index = segment.index;
const char = segment[0][0] ?? "";
const quoted = skipSqlQuoted(sql, index, char);
if (quoted !== index) {
if (pendingSpace && normalized.length > 0) normalized += " ";
normalized += sql.slice(index, quoted);
pendingSpace = false;
segments.lastIndex = quoted;
continue;
}
const comment = skipSqlComment(sql, index);
if (comment !== index) {
pendingSpace = true;
segments.lastIndex = comment;
continue;
}
if (/\s/u.test(char)) pendingSpace = true;
else {
if (pendingSpace && normalized.length > 0) normalized += " ";
normalized += segment[0];
pendingSpace = false;
}
}
return normalized.trim();
}
function quoteSqliteIdentifier(identifier) {
return `"${identifier.replaceAll("\"", "\"\"")}"`;
}
function skipSqlQuotedOrComment(sql, index) {
const quoted = skipSqlQuoted(sql, index, sql[index] ?? "");
return quoted !== index ? quoted : skipSqlComment(sql, index);
}
function skipSqlQuoted(sql, index, quote) {
if (quote !== "'" && quote !== "\"" && quote !== "`" && quote !== "[") return index;
const closingQuote = quote === "[" ? "]" : quote;
let cursor = index + 1;
while (cursor < sql.length) {
if (sql[cursor] !== closingQuote) {
cursor += 1;
continue;
}
if (quote !== "[" && sql[cursor + 1] === closingQuote) {
cursor += 2;
continue;
}
return cursor + 1;
}
return sql.length;
}
function skipSqlComment(sql, index) {
if (sql.startsWith("--", index)) {
const newline = sql.indexOf("\n", index + 2);
return newline === -1 ? sql.length : newline + 1;
}
if (sql.startsWith("/*", index)) {
const close = sql.indexOf("*/", index + 2);
return close === -1 ? sql.length : close + 2;
}
return index;
}
var TABLE_CONSTRAINT_KEYWORDS;
var init_sqlite_schema_sql = __esmMin((() => {
TABLE_CONSTRAINT_KEYWORDS = /* @__PURE__ */ new Set([
"CHECK",
"FOREIGN",
"PRIMARY",
"UNIQUE"
]);
}));
//#endregion
//#region src/infra/sqlite-busy-timeout.ts
function normalizeSqliteNonNegativeInteger(value, label) {
if (!Number.isInteger(value) || value < 0) throw new Error(`${label} must be a non-negative integer`);
return value;
}
function readSqliteBusyTimeout(database) {
const row = database.prepare("PRAGMA busy_timeout").get();
const value = row?.busy_timeout ?? row?.timeout;
return typeof value === "bigint" ? Number(value) : Number(value ?? 0);
}
function setSqliteBusyTimeout(database, busyTimeoutMs) {
const normalizedTimeoutMs = normalizeSqliteNonNegativeInteger(busyTimeoutMs, "busyTimeoutMs");
database.exec(`PRAGMA busy_timeout = ${normalizedTimeoutMs}`);
}
function shouldReportSqliteLockFailure(database) {
return lockFailureReportingByDatabase.get(database) !== "suppress";
}
/** Run with a temporary busy policy; restore early when write admission finishes. */
function runWithSqliteBusyTimeout(database, busyTimeoutMs, operation, options = {}) {
const normalizedTimeoutMs = normalizeSqliteNonNegativeInteger(busyTimeoutMs, "busyTimeoutMs");
const previousBusyTimeoutMs = readSqliteBusyTimeout(database);
const previousLockFailureReporting = lockFailureReportingByDatabase.get(database);
if (options.lockFailureReporting) lockFailureReportingByDatabase.set(database, options.lockFailureReporting);
if (previousBusyTimeoutMs !== normalizedTimeoutMs) setSqliteBusyTimeout(database, normalizedTimeoutMs);
const restore = () => {
if (database.isOpen && previousBusyTimeoutMs !== normalizedTimeoutMs) setSqliteBusyTimeout(database, previousBusyTimeoutMs);
if (previousLockFailureReporting) lockFailureReportingByDatabase.set(database, previousLockFailureReporting);
else lockFailureReportingByDatabase.delete(database);
};
try {
return operation(restore);
} finally {
restore();
}
}
var lockFailureReportingByDatabase;
var init_sqlite_busy_timeout = __esmMin((() => {
lockFailureReportingByDatabase = /* @__PURE__ */ new WeakMap();
}));
//#endregion
//#region node-sqlite.mjs
function probeSqlite(DatabaseSync) {
const result = {
available: false,
version: null,
text: false,
blob: false,
json: false
};
let database;
try {
database = new DatabaseSync(":memory:");
result.available = true;
const version = database.prepare("SELECT sqlite_version() AS version").get()?.version;
result.version = typeof version === "string" ? version : null;
const text = "a\0b\0";
const bytes = Buffer.from(text, "utf8");
const json = JSON.stringify({ value: text });
database.exec("CREATE TABLE probe (text_value TEXT, blob_value BLOB, json_value TEXT)");
database.prepare("INSERT INTO probe VALUES (?, ?, ?)").run(text, bytes, json);
const row = database.prepare("SELECT text_value, blob_value, json_value FROM probe").get();
result.text = typeof row?.text_value === "string" && row.text_value.length === 4 && Buffer.from(row.text_value, "utf8").equals(bytes);
result.blob = row?.blob_value instanceof Uint8Array && Buffer.from(row.blob_value).equals(bytes);
result.json = row?.json_value === json && JSON.parse(row.json_value).value === text;
} catch (error) {
result.error = error instanceof Error ? error.message : String(error);
} finally {
database?.close();
}
return result;
}
function isSqliteWalResetSafeVersion(value) {
const match = /^(\d+)\.(\d+)\.(\d+)$/u.exec(value.trim());
if (!match) return false;
const [major, minor, patch] = match.slice(1).map(Number);
if (![
major,
minor,
patch
].every(Number.isSafeInteger)) return false;
return major > 3 || major === 3 && (minor > 51 || minor === 51 && patch >= 3 || minor === 50 && patch >= 7 || minor === 44 && patch >= 6);
}
var init_node_sqlite$1 = __esmMin((() => {
init_node_version();
`${probeSqlite.toString()}`;
}));
//#endregion
//#region src/infra/sqlite-runtime-version.ts
var init_sqlite_runtime_version = __esmMin((() => {
init_node_sqlite$1();
}));
//#endregion
//#region src/infra/bun-sqlite-library.ts
function probeLibrary(path) {
const { dlopen, FFIType } = createRequire(import.meta.url)("bun:ffi");
const library = dlopen(path, {
sqlite3_libversion: {
args: [],
returns: FFIType.cstring
},
sqlite3_compileoption_used: {
args: [FFIType.cstring],
returns: FFIType.i32
}
});
try {
return {
version: String(library.symbols.sqlite3_libversion()),
extensionLoadingSupported: library.symbols.sqlite3_compileoption_used(Buffer.from("OMIT_LOAD_EXTENSION\0")) === 0
};
} finally {
library.close();
}
}
function selectLibrary(path) {
const { Database } = createRequire(import.meta.url)("bun:sqlite");
Database.setCustomSQLite(path);
}
function createSelector(deps) {
let selection;
let failure;
return (options = {}) => {
if (failure) throw failure;
if (selection) return selection;
const override = options.explicitPath ?? (deps.env.OPENCLAW_SQLITE_LIBRARY?.trim() || void 0);
if (!deps.isBun || deps.platform !== "darwin") {
selection = override ? {
source: "runtime",
ignoredOverride: "OPENCLAW_SQLITE_LIBRARY requires Bun on macOS"
} : { source: "runtime" };
return selection;
}
const prefix = deps.env.HOMEBREW_PREFIX?.trim();
const candidates = override !== void 0 ? [override] : [.../* @__PURE__ */ new Set([
...prefix ? [posix.join(prefix, "opt/sqlite/lib/libsqlite3.dylib")] : [],
"/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib",
"/usr/local/opt/sqlite/lib/libsqlite3.dylib",
"/opt/local/lib/libsqlite3.dylib"
])];
for (const path of candidates) {
let probe;
try {
try {
probe = deps.probe(path);
} catch (error) {
throw deps.exists(path) ? error : new Error("missing file", { cause: error });
}
if (!isSqliteWalResetSafeVersion(probe.version)) throw new Error(`SQLite version ${probe.version} below the WAL safety floor`);
if (!probe.extensionLoadingSupported) throw new Error("built with SQLITE_OMIT_LOAD_EXTENSION");
} catch (error) {
if (override === void 0) continue;
failure = selectionError(path, error);
throw failure;
}
try {
deps.select(path);
} catch (error) {
failure = selectionError(path, error);
throw failure;
}
selection = {
source: override === void 0 ? "discovered" : "env",
path,
version: probe.version,
extensionLoadingSupported: true
};
return selection;
}
selection = { source: "runtime" };
return selection;
};
}
function selectionError(path, error) {
return new Error(`Cannot use SQLite library ${path}: ${error instanceof Error ? error.message : String(error)}. Fix or unset OPENCLAW_SQLITE_LIBRARY; install a supported library with brew install sqlite.`, { cause: error });
}
function inheritedSelection() {
const value = getEnvironmentData(WORKER_SELECTION_KEY);
if (value === void 0) return;
if (value !== null && typeof value === "object" && !Array.isArray(value)) {
const source = "source" in value ? value.source : void 0;
if (source === "runtime") return { source: "runtime" };
const path = "path" in value ? value.path : void 0;
const version = "version" in value ? value.version : void 0;
const extensionLoadingSupported = "extensionLoadingSupported" in value ? value.extensionLoadingSupported : void 0;
if ((source === "env" || source === "discovered") && typeof path === "string" && typeof version === "string" && extensionLoadingSupported === true) return {
source,
path,
version,
extensionLoadingSupported: true
};
}
throw new Error("Invalid inherited SQLite library selection");
}
function createRuntimeSelector() {
const isBun = Boolean(process.versions.bun);
const sharedLibrary = isBun && process.platform === "darwin";
const inherited = sharedLibrary && !isMainThread ? inheritedSelection() : void 0;
if (inherited) return () => inherited;
const select = createSelector({
isBun,
platform: process.platform,
env: process.env,
exists: existsSync,
probe: probeLibrary,
select: selectLibrary
});
let published = false;
return (options) => {
const selection = select(options);
if (sharedLibrary && isMainThread && !published) {
setEnvironmentData(WORKER_SELECTION_KEY, Object.freeze({ ...selection }));
published = true;
}
return selection;
};
}
/** Select once, before any SQLite open; shared across CLI and bundled SDK module graphs. */
function ensureSqliteLibrarySelected(options) {
const dependencies = options?.internals;
return (dependencies ? dependencies.selector ??= createSelector(dependencies) : resolveGlobalSingleton(Symbol.for("openclaw.bunSqliteLibrarySelection"), createRuntimeSelector))(options);
}
var WORKER_SELECTION_KEY;
var init_bun_sqlite_library = __esmMin((() => {
init_global_singleton();
init_sqlite_runtime_version();
WORKER_SELECTION_KEY = "openclaw.bunSqliteLibrarySelection";
}));
//#endregion
//#region packages/normalization-core/src/string-coerce.ts
/** Trims string input and returns null for non-strings or empty strings. */
function normalizeNullableString(value) {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed ? trimmed : null;
}
/** Trims string input and returns undefined for non-strings or empty strings. */
function normalizeOptionalString(value) {
return normalizeNullableString(value) ?? void 0;
}
/** Lowercases a normalized optional string. */
function normalizeOptionalLowercaseString(value) {
return normalizeOptionalString(value)?.toLowerCase();
}
/** Lowercases a normalized string or returns an empty string when absent. */
function normalizeLowercaseStringOrEmpty(value) {
return normalizeOptionalLowercaseString(value) ?? "";
}
var init_string_coerce = __esmMin((() => {}));
//#endregion
//#region packages/net-policy/src/redact-sensitive-url.ts
function normalizeUrlQueryParamName(name) {
let current = name.replace(URL_QUERY_NAME_SEPARATOR_RE, "");
for (let depth = 0; depth <= MAX_NESTED_URL_REDACTION_DEPTH; depth += 1) {
let decoded;
try {
decoded = decodeURIComponent(current).replace(URL_QUERY_NAME_SEPARATOR_RE, "");
} catch {
break;
}
if (decoded === current) return {
value: normalizeLowercaseStringOrEmpty(current).replaceAll("-", "_"),
unresolvedEncoding: false
};
current = decoded;
}
return {
value: normalizeLowercaseStringOrEmpty(current).replaceAll("-", "_"),
unresolvedEncoding: current.includes("%")
};
}
/** True for auth-like URL query parameter names that should be redacted. */
function isSensitiveUrlQueryParamName(name) {
const normalized = normalizeUrlQueryParamName(name);
return normalized.unresolvedEncoding || SENSITIVE_URL_QUERY_PARAM_NAMES.has(normalized.value) || SUFFIXED_OR_SCOPED_TOKEN_QUERY_PARAM_RE.test(normalized.value);
}
var SENSITIVE_URL_QUERY_PARAM_NAMES, URL_QUERY_NAME_SEPARATOR_RE, SUFFIXED_OR_SCOPED_TOKEN_QUERY_PARAM_RE, MAX_NESTED_URL_REDACTION_DEPTH;
var init_redact_sensitive_url = __esmMin((() => {
init_string_coerce();
SENSITIVE_URL_QUERY_PARAM_NAMES = /* @__PURE__ */ new Set([
"token",
"key",
"api_key",
"apikey",
"secret",
"access_token",
"auth_token",
"password",
"pass",
"passwd",
"auth",
"jwt",
"session",
"id_token",
"code",
"client_secret",
"app_secret",
"hook_token",
"refresh_token",
"signature",
"x_amz_signature",
"x_amz_security_token",
"private_key",
"credential",
"authorization",
"sig",
"x_api_key",
"x_access_token",
"x_auth_token"
]);
URL_QUERY_NAME_SEPARATOR_RE = /[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu;
SUFFIXED_OR_SCOPED_TOKEN_QUERY_PARAM_RE = /(?:^|_)token(?:_[a-f0-9]{16,})?$/u;
MAX_NESTED_URL_REDACTION_DEPTH = 8;
}));
//#endregion
//#region packages/normalization-core/src/utf16-slice.ts
function isHighSurrogate(codeUnit) {
return codeUnit >= 55296 && codeUnit <= 56319;
}
function isLowSurrogate(codeUnit) {
return codeUnit >= 56320 && codeUnit <= 57343;
}
/** Slices a UTF-16 string without returning dangling surrogate halves at either edge. */
function sliceUtf16Safe(input, start, end) {
const len = input.length;
let from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len);
let to = end === void 0 ? len : end < 0 ? Math.max(len + end, 0) : Math.min(end, len);
if (to <= from) return "";
if (from > 0 && from < len) {
if (isLowSurrogate(input.charCodeAt(from)) && isHighSurrogate(input.charCodeAt(from - 1))) from += 1;
}
if (to > 0 && to < len) {
if (isHighSurrogate(input.charCodeAt(to - 1)) && isLowSurrogate(input.charCodeAt(to))) to -= 1;
}
return input.slice(from, to);
}
/** Truncates a UTF-16 string without cutting a surrogate pair in half. */
function truncateUtf16Safe(input, maxLen) {
const limit = Math.max(0, Math.floor(maxLen));
if (input.length <= limit) return input;
return sliceUtf16Safe(input, 0, limit);
}
var init_utf16_slice = __esmMin((() => {}));
//#endregion
//#region packages/acp-core/src/structured-auth-redaction.ts
function skipHorizontalWhitespace(value, start) {
let cursor = start;
while (value[cursor] === " " || value[cursor] === " ") cursor += 1;
return cursor;
}
function readSerializedLineEnd(value, start) {
let cursor = start;
let slashCount = 0;
while (slashCount < 64 && value[cursor] === "\\") {
slashCount += 1;
cursor += 1;
}
if (slashCount === 0) return null;
if (value[cursor] === "n") return cursor + 1;
if (value[cursor] !== "r") return null;
cursor += 1;
slashCount = 0;
while (slashCount < 64 && value[cursor] === "\\") {
slashCount += 1;
cursor += 1;
}
return slashCount > 0 && value[cursor] === "n" ? cursor + 1 : null;
}
function readSerializedTabEnd(value, start) {
let cursor = start;
let slashCount = 0;
while (slashCount < 64 && value[cursor] === "\\") {
slashCount += 1;
cursor += 1;
}
return slashCount > 0 && value[cursor] === "t" ? cursor + 1 : null;
}
function skipAuthWhitespace(value, start) {
let cursor = start;
for (;;) {
cursor = skipHorizontalWhitespace(value, cursor);
const tabEnd = readSerializedTabEnd(value, cursor);
if (tabEnd !== null) {
cursor = tabEnd;
continue;
}
const lineEnd = value[cursor] === "\r" && value[cursor + 1] === "\n" ? cursor + 2 : value[cursor] === "\n" ? cursor + 1 : readSerializedLineEnd(value, cursor);
if (lineEnd === null || value[lineEnd] !== " " && value[lineEnd] !== " " && readSerializedTabEnd(value, lineEnd) === null) return cursor;
cursor = lineEnd;
}
}
function readAuthParamName(value, start) {
const match = AUTH_PARAM_TOKEN_RE.exec(value.slice(start));
return match ? {
name: match[0].toLowerCase(),
end: start + match[0].length
} : null;
}
function isAuthHeaderStart(value, index) {
const previous = value[index - 1];
let serializedLineBoundary = false;
if (previous === "n" || previous === "r") {
let slashCursor = index - 2;
let slashCount = 0;
while (slashCount < 64 && value[slashCursor] === "\\") {
slashCount += 1;
slashCursor -= 1;
}
serializedLineBoundary = slashCount > 0;
}
if (!serializedLineBoundary && previous !== void 0 && /[A-Za-z0-9_-]/u.test(previous)) return false;
const proxyName = "proxy-authorization";
const directName = "authorization";
const candidate = value.slice(index, index + 19).toLowerCase();
const name = candidate === proxyName ? proxyName : candidate.startsWith(directName) ? directName : null;
if (!name) return false;
let cursor = index + name.length;
let slashCount = 0;
while (slashCount < 64 && value[cursor] === "\\") {
slashCount += 1;
cursor += 1;
}
if (value[cursor] === "\"" || value[cursor] === "'") cursor += 1;
else if (slashCount > 0) return false;
cursor = skipHorizontalWhitespace(value, cursor);
return value[cursor] === ":" || value[cursor] === "=";
}
function findNextAuthParamStart(value, start) {
let cursor = start;
for (;;) {
cursor = skipAuthWhitespace(value, cursor);
if (cursor > start && isAuthHeaderStart(value, cursor)) return null;
if (cursor >= value.length || value[cursor] === "\r" || value[cursor] === "\n" || value[cursor] === ";") return null;
if (value[cursor] === ",") {
cursor += 1;
continue;
}
const param = readAuthParamName(value, cursor);
if (param) {
const equals = skipAuthWhitespace(value, param.end);
if (value[equals] === "=" && value[equals + 1] !== "=") return cursor;
}
while (cursor < value.length) {
const whitespaceEnd = skipAuthWhitespace(value, cursor);
if (whitespaceEnd > cursor) {
cursor = whitespaceEnd;
continue;
}
if (cursor > start && isAuthHeaderStart(value, cursor)) return null;
const char = value[cursor];
if (char === "\r" || char === "\n" || char === ";") return null;
cursor += 1;
if (char === ",") break;
}
}
}
function usesAuthParams(scheme) {
return scheme === "digest" || scheme === "hawk" || scheme.startsWith("aws4-");
}
function isAuthFieldEnd(char) {
return char === void 0 || char === "\r" || char === "\n" || char === ";" || char === "\\" || char === "\"" || char === "'" || char === "}" || char === "]";
}
function findAuthFieldEnd(value, start) {
let cursor = start;
while (cursor < value.length) {
const whitespaceEnd = skipAuthWhitespace(value, cursor);
if (whitespaceEnd > cursor) {
cursor = whitespaceEnd;
continue;
}
if (cursor > start && isAuthHeaderStart(value, cursor)) break;
if (isAuthFieldEnd(value[cursor])) break;
cursor += 1;
}
return cursor;
}
function readParamValue(value, start, options) {
let escapedQuoteSlashCount = 0;
while (value[start + escapedQuoteSlashCount] === "\\") escapedQuoteSlashCount += 1;
const escapedQuotes = escapedQuoteSlashCount > 0 && value[start + escapedQuoteSlashCount] === "\"";
const quote = value[start] === "\"" || value[start] === "'" ? value[start] : void 0;
if (quote || escapedQuotes) {
let cursor = start + (escapedQuotes ? escapedQuoteSlashCount + 1 : 1);
while (cursor < value.length) {
if (value[cursor] === "\r" || value[cursor] === "\n") {
const whitespaceEnd = skipAuthWhitespace(value, cursor);
if (whitespaceEnd === cursor) break;
cursor = whitespaceEnd;
continue;
}
if (escapedQuotes && value[cursor] === "\\") {
let slashEnd = cursor + 1;
while (value[slashEnd] === "\\") slashEnd += 1;
if (value[slashEnd] === "\"") {
if ((slashEnd - cursor) % (2 * (escapedQuoteSlashCount + 1)) === escapedQuoteSlashCount) return slashEnd + 1;
cursor = slashEnd + 1;
continue;
}
cursor = slashEnd;
continue;
}
if (!escapedQuotes && value[cursor] === "\\" && cursor + 1 < value.length) {
cursor += 2;
continue;
}
if (!escapedQuotes && value[cursor] === quote) return cursor + 1;
cursor += 1;
}
return cursor > start + 1 ? cursor : null;
}
if (options.signedHeaders) {
const match = /^:?[A-Za-z0-9!#$%&'*+.^_`|~-]+(?:;:?[A-Za-z0-9!#$%&'*+.^_`|~-]+)*/u.exec(value.slice(start));
if (!match) return null;
const end = start + match[0].length;
const next = value[end];
return next === void 0 || next === "," || next === " " || next === " " || next === "\r" || next === "\n" ? end : null;
}
const match = (options.awsScope ? AWS_SCOPE_VALUE_RE : AUTH_PARAM_TOKEN_RE).exec(value.slice(start));
return match ? start + match[0].length : null;
}
function findStructuredAuthParamRanges(value) {
const ranges = [];
for (const header of value.matchAll(STRUCTURED_AUTH_HEADER_RE)) {
const scheme = (header[2] ?? "").toLowerCase();
let cursor = (header.index ?? 0) + header[0].length;
const rangeStart = cursor;
let rangeEnd = cursor;
const directParam = readAuthParamName(value, cursor);
const directEquals = directParam ? skipAuthWhitespace(value, directParam.end) : void 0;
if (!directParam || directEquals === void 0 || value[directEquals] !== "=" || value[directEquals + 1] === "=") {
if (value[skipAuthWhitespace(value, cursor)] !== "," && !usesAuthParams(scheme)) continue;
const firstParamStart = findNextAuthParamStart(value, cursor);
if (firstParamStart === null) continue;
cursor = firstParamStart;
}
for (;;) {
const param = readAuthParamName(value, cursor);
if (!param) break;
cursor = skipAuthWhitespace(value, param.end);
if (value[cursor] !== "=") break;
cursor = skipAuthWhitespace(value, cursor + 1);
const valueEnd = readParamValue(value, cursor, {
awsScope: scheme.startsWith("aws4-") && param.name === "credential",
signedHeaders: param.name === "signedheaders"
});
if (valueEnd === null) {
const nextParamStart = findNextAuthParamStart(value, cursor);
if (nextParamStart !== null) {
cursor = nextParamStart;
continue;
}
rangeEnd = Math.max(rangeEnd, findAuthFieldEnd(value, cursor));
break;
}
rangeEnd = valueEnd;
const separator = skipAuthWhitespace(value, valueEnd);
if (value[separator] !== ",") {
if (!isAuthFieldEnd(value[separator])) {
const nextParamStart = findNextAuthParamStart(value, separator);
if (nextParamStart !== null) {
cursor = nextParamStart;
continue;
}
rangeEnd = Math.max(rangeEnd, findAuthFieldEnd(value, separator));
}
break;
}
const nextParamStart = findNextAuthParamStart(value, separator + 1);
if (nextParamStart === null) break;
cursor = nextParamStart;
}
if (rangeEnd > rangeStart) ranges.push({
start: rangeStart,
end: rangeEnd
});
}
return ranges;
}
function redactStructuredAuthHeaders(value, replacement) {
const parts = [];
let cursor = 0;
for (const range of findStructuredAuthParamRanges(value)) {
if (parts.length === 0 || range.start > cursor) parts.push(value.slice(cursor, range.start), replacement);
cursor = Math.max(cursor, range.end);
}
parts.push(value.slice(cursor));
return parts.join("");
}
var HTTP_AUTH_SCHEME_PATTERN, HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN, HTTP_AUTH_SERIALIZED_TAB_PATTERN, HTTP_AUTH_SERIALIZED_INDENT_PATTERN, HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN, HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN, HTTP_AUTH_LEGACY_VALUE_WHITESPACE_PATTERN, HTTP_AUTH_HEADER_BOUNDARY_PATTERN, HTTP_AUTH_SERIALIZED_QUOTE_PATTERN, STRUCTURED_AUTH_HEADER_RE, AUTH_PARAM_TOKEN_RE, AWS_SCOPE_VALUE_RE;
var init_structured_auth_redaction = __esmMin((() => {
HTTP_AUTH_SCHEME_PATTERN = "[A-Za-z0-9!#$%&'*+.^_`|~-]+";
HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN = String.raw`(?:\[REDACTED\]|[^\s\\"',;&#?<>)}\]]+)`;
HTTP_AUTH_SERIALIZED_TAB_PATTERN = String.raw`\\{1,64}t`;
HTTP_AUTH_SERIALIZED_INDENT_PATTERN = String.raw`(?:[ \t]+|${HTTP_AUTH_SERIALIZED_TAB_PATTERN})`;
HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN = String.raw`(?:[ \t]*\r?\n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*\\{1,64}r\\{1,64}n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*\\{1,64}n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*${HTTP_AUTH_SERIALIZED_TAB_PATTERN}[ \t]*|[ \t]*)`;
HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN = String.raw`(?:[ \t]*\r?\n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*\\{1,64}r\\{1,64}n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*\\{1,64}n${HTTP_AUTH_SERIALIZED_INDENT_PATTERN}|[ \t]*${HTTP_AUTH_SERIALIZED_TAB_PATTERN}[ \t]*|[ \t]+)`;
HTTP_AUTH_LEGACY_VALUE_WHITESPACE_PATTERN = String.raw`(?:[ \t\r\n]*|[ \t]*\\{1,64}r\\{1,64}n(?:[ \t]*|${HTTP_AUTH_SERIALIZED_TAB_PATTERN})|[ \t]*\\{1,64}n(?:[ \t]*|${HTTP_AUTH_SERIALIZED_TAB_PATTERN})|[ \t]*${HTTP_AUTH_SERIALIZED_TAB_PATTERN}[ \t]*)`;
HTTP_AUTH_HEADER_BOUNDARY_PATTERN = String.raw`(^|[^A-Za-z0-9_-]|\\{1,64}[rn])`;
HTTP_AUTH_SERIALIZED_QUOTE_PATTERN = String.raw`(?:\\{1,64}["']|["']|)`;
String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}(?:x-goog-api-key|api-key|apikey|x-api-token|x-access-token)${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}([^\s\\"',;]+)`;
STRUCTURED_AUTH_HEADER_RE = new RegExp(String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}(?:Proxy-)?Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(${HTTP_AUTH_SCHEME_PATTERN})${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}`, "giu");
AUTH_PARAM_TOKEN_RE = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+/u;
AWS_SCOPE_VALUE_RE = /^[A-Za-z0-9!#$%&'*+.^_`|~:/-]+/u;
}));
//#endregion
//#region packages/normalization-core/src/balanced-json.ts
var init_balanced_json = __esmMin((() => {}));
//#endregion
//#region packages/normalization-core/src/boolean-coercion.ts
var init_boolean_coercion = __esmMin((() => {})), WEIGHTED_CJK_RANGES;
var init_cjk_chars = __esmMin((() => {
WEIGHTED_CJK_RANGES = [
[
[183, 183],
[12288, 12703],
[19968, 40869],
[44032, 55215],
[65281, 65376]
],
[
[4352, 4607],
[11904, 12287],
[12704, 19967],
[40870, 40959],
[40960, 42239],
[42752, 42759],
[43360, 43391],
[55216, 55295],
[63744, 64255]
],
[
[711, 711],
[713, 715],
[729, 729],
[746, 747],
[773, 773],
[803, 803],
[65040, 65103],
[65377, 65500],
[65504, 65510]
],
[[119648, 119665]],
[
[94176, 94207],
[110576, 110591],
[110592, 110959],
[127488, 127743],
[131072, 195103],
[196608, 210047]
]
];
new RegExp(`[${WEIGHTED_CJK_RANGES.flatMap((ranges) => ranges.map(([start, end]) => `\\u{${start.toString(16)}}-\\u{${end.toString(16)}}`)).join("")}]`, "u");
(() => {
const maxCodePoint = Math.max(...WEIGHTED_CJK_RANGES.flatMap((ranges) => ranges.map(([, end]) => end)));
const categories = new Uint8Array(maxCodePoint + 1);
for (const [bucket, ranges] of WEIGHTED_CJK_RANGES.entries()) for (const [start, end] of ranges) categories.fill(bucket + 1, start, end + 1);
return categories;
})();
}));
//#endregion
//#region packages/normalization-core/src/code-points.ts
var init_code_points = __esmMin((() => {}));
//#endregion
//#region packages/normalization-core/src/expect.ts
/** Returns the value or throws with the named context; use for genuine invariants only. */
function expectDefined(value, context) {
if (value === null || value === void 0) throw new Error("expected " + context + " to be defined");
return value;
}
var init_expect = __esmMin((() => {}));
//#endregion
//#region packages/normalization-core/src/format.ts
/** Formats a byte count with caller-explicit scale, labels, precision, and unit cap. */
function formatByteSize(bytes, options) {
const { base, labels } = BYTE_SIZE_STYLES[options.style];
const maxUnitIndex = BYTE_SIZE_UNITS.indexOf(options.maxUnit);
let unitIndex = 0;
let value = bytes;
while (value >= base && unitIndex < maxUnitIndex) {
value /= base;
unitIndex += 1;
}
const unit = expectDefined(BYTE_SIZE_UNITS[unitIndex], "byte-size unit");
const label = expectDefined(labels[unitIndex], "byte-size label");
const fractionDigits = typeof options.fractionDigits === "function" ? options.fractionDigits(value, unit) : options.fractionDigits;
if (fractionDigits === null) return `${value}${options.separator}${label}`;
if (options.floorUnits?.includes(unit)) value = Math.floor(value * 10 ** fractionDigits) / 10 ** fractionDigits;
return `${value.toFixed(fractionDigits)}${options.separator}${label}`;
}
var BYTE_SIZE_UNITS, BYTE_SIZE_STYLES;
var init_format = __esmMin((() => {
init_expect();
BYTE_SIZE_UNITS = [
"byte",
"kilo",
"mega",
"giga",
"tera"
];
BYTE_SIZE_STYLES = {
iec: {
base: 1024,
labels: [
"B",
"KiB",
"MiB",
"GiB",
"TiB"
]
},
"legacy-binary": {
base: 1024,
labels: [
"B",
"KB",
"MB",
"GB",
"TB"
]
}
};
}));
//#endregion
//#region packages/normalization-core/src/json-coercion.ts
var init_json_coercion = __esmMin((() => {}));
//#endregion
//#region packages/normalization-core/src/number-coercion.ts
/** Returns a number only when the input is already finite. */
function asFiniteNumber(value) {
return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
/** Returns a safe integer only when it satisfies the supplied inclusive bounds. */
function asSafeIntegerInRange(value, range) {
if (typeof value !== "number" || !Number.isSafeInteger(value)) return;
if (range.min !== void 0 && value < range.min) return;
if (range.max !== void 0 && value > range.max) return;
return value;
}
/** Resolves arbitrary timeout input with fallback and minimum timer bounds. */
function resolveTimerTimeoutMs(valueMs, fallbackMs, minMs = 1) {
const value = asFiniteNumber(valueMs) ?? asFiniteNumber(fallbackMs);
const min = Math.max(0, Math.floor(minMs));
if (value === void 0) return min;
return Math.min(Math.max(Math.floor(value), min), MAX_TIMER_TIMEOUT_MS$1);
}
/** Resolves an integer option from finite numeric input or fallback, then clamps bounds. */
function resolveIntegerOption(value, fallback, range = {}) {
const candidate = asFiniteNumber(value) ?? fallback;
const floored = Math.floor(candidate);
const minBounded = range.min === void 0 ? floored : Math.max(range.min, floored);
return range.max === void 0 ? minBounded : Math.min(range.max, minBounded);
}
/** Resolves an integer option with a non-negative lower bound. */
function resolveNonNegativeIntegerOption(value, fallback) {
return resolveIntegerOption(value, fallback, { min: 0 });
}
var MAX_TIMER_TIMEOUT_MS$1, MAX_DATE_TIMESTAMP_MS;
var init_number_coercion = __esmMin((() => {
MAX_TIMER_TIMEOUT_MS$1 = 2147e6;
Math.floor(MAX_TIMER_TIMEOUT_MS$1 / 1e3);
MAX_DATE_TIMESTAMP_MS = 864e13;
}));
//#endregion
//#region packages/normalization-core/src/response-bytes.ts
var init_response_bytes = __esmMin((() => {}));
//#endregion
//#region packages/normalization-core/src/stable-stringify.ts
var init_stable_stringify = __esmMin((() => {}));
//#endregion
//#region packages/normalization-core/src/string-normalization.ts
var init_string_normalization = __esmMin((() => {}));
//#endregion
//#region packages/normalization-core/src/text-decoding.ts
var init_text_decoding = __esmMin((() => {}));
//#endregion
//#region packages/normalization-core/src/index.ts
var init_src$2 = __esmMin((() => {
init_balanced_json();
init_boolean_coercion();
init_cjk_chars();
init_code_points();
init_error_coercion();
init_expect();
init_format();
init_json_coercion();
init_number_coercion();
init_record_coerce();
init_response_bytes();
init_stable_stringify();
init_string_coerce();
init_string_normalization();
init_text_decoding();
init_utf16_slice();
}));
//#endregion
//#region src/security/safe-regex.ts
function createParseFrame() {
return {
lastToken: null,
containsRepetition: false,
hasAlternation: false,
branchMinLength: 0,
branchMaxLength: 0,
altMinLength: null,
altMaxLength: null
};
}
function addLength(left, right) {
if (!Number.isFinite(left) || !Number.isFinite(right)) return Number.POSITIVE_INFINITY;
return left + right;
}
function multiplyLength(length, factor) {
if (!Number.isFinite(length)) return factor === 0 ? 0 : Number.POSITIVE_INFINITY;
return length * factor;
}
function recordAlternative(frame) {
if (frame.altMinLength === null || frame.altMaxLength === null) {
frame.altMinLength = frame.branchMinLength;
frame.altMaxLength = frame.branchMaxLength;
return;
}
frame.altMinLength = Math.min(frame.altMinLength, frame.branchMinLength);
frame.altMaxLength = Math.max(frame.altMaxLength, frame.branchMaxLength);
}
function readQuantifier(source, index) {
const ch = source[index];
const consumed = source[index + 1] === "?" ? 2 : 1;
if (ch === "*") return {
consumed,
minRepeat: 0,
maxRepeat: null
};
if (ch === "+") return {
consumed,
minRepeat: 1,
maxRepeat: null
};
if (ch === "?") return {
consumed,
minRepeat: 0,
maxRepeat: 1
};
if (ch !== "{") return null;
let i = index + 1;
while (i < source.length && /\d/.test(source.charAt(i))) i += 1;
if (i === index + 1) return null;
const minRepeat = Number.parseInt(source.slice(index + 1, i), 10);
let maxRepeat = minRepeat;
if (source[i] === ",") {
i += 1;
const maxStart = i;
while (i < source.length && /\d/.test(source.charAt(i))) i += 1;
maxRepeat = i === maxStart ? null : Number.parseInt(source.slice(maxStart, i), 10);
}
if (source[i] !== "}") return null;
i += 1;
if (source[i] === "?") i += 1;
if (maxRepeat !== null && maxRepeat < minRepeat) return null;
return {
consumed: i - index,
minRepeat,
maxRepeat
};
}
function tokenizePattern(source) {
const tokens = [];
let inCharClass = false;
for (let i = 0; i < source.length; i += 1) {
const ch = source[i];
if (inCharClass) {
if (ch === "\\") {
i += 1;
continue;
}
if (ch === "]") inCharClass = false;
continue;
}
if (ch === "\\") {
i += 1;
tokens.push({ kind: "simple-token" });
continue;
}
if (ch === "[") {
inCharClass = true;
tokens.push({ kind: "simple-token" });
continue;
}
if (ch === "(") {
tokens.push({ kind: "group-open" });
continue;
}
if (ch === ")") {
tokens.push({ kind: "group-close" });
continue;
}
if (ch === "|") {
tokens.push({ kind: "alternation" });
continue;
}
const quantifier = readQuantifier(source, i);
if (quantifier) {
tokens.push({
kind: "quantifier",
quantifier
});
i += quantifier.consumed - 1;
continue;
}
tokens.push({ kind: "simple-token" });
}
return tokens;
}
function analyzeTokensForNestedRepetition(tokens) {
const frames = [createParseFrame()];
const emitToken = (token) => {
const frame = expectDefined(frames[frames.length - 1], "frames entry at frames.length 1");
frame.lastToken = token;
if (token.containsRepetition) frame.containsRepetition = true;
frame.branchMinLength = addLength(frame.branchMinLength, token.minLength);
frame.branchMaxLength = addLength(frame.branchMaxLength, token.maxLength);
};
const emitSimpleToken = () => {
emitToken({
containsRepetition: false,
hasAmbiguousAlternation: false,
minLength: 1,
maxLength: 1
});
};
for (const token of tokens) {
if (token.kind === "simple-token") {
emitSimpleToken();
continue;
}
if (token.kind === "group-open") {
frames.push(createParseFrame());
continue;
}
if (token.kind === "group-close") {
if (frames.length > 1) {
const frame = frames.pop();
if (frame.hasAlternation) recordAlternative(frame);
const groupMinLength = frame.hasAlternation ? frame.altMinLength ?? 0 : frame.branchMinLength;
const groupMaxLength = frame.hasAlternation ? frame.altMaxLength ?? 0 : frame.branchMaxLength;
emitToken({
containsRepetition: frame.containsRepetition,
hasAmbiguousAlternation: frame.hasAlternation && frame.altMinLength !== null && frame.altMaxLength !== null && frame.altMinLength !== frame.altMaxLength,
minLength: groupMinLength,
maxLength: groupMaxLength
});
}
continue;
}
if (token.kind === "alternation") {
const frame = expectDefined(frames[frames.length - 1], "frames entry at frames.length 1");
frame.hasAlternation = true;
recordAlternative(frame);
frame.branchMinLength = 0;
frame.branchMaxLength = 0;
frame.lastToken = null;
continue;
}
const frame = expectDefined(frames[frames.length - 1], "frames entry at frames.length 1");
const previousToken = frame.lastToken;
if (!previousToken) continue;
if (previousToken.containsRepetition) return true;
if (previousToken.hasAmbiguousAlternation && token.quantifier.maxRepeat === null) return true;
const previousMinLength = previousToken.minLength;
const previousMaxLength = previousToken.maxLength;
previousToken.minLength = multiplyLength(previousToken.minLength, token.quantifier.minRepeat);
previousToken.maxLength = token.quantifier.maxRepeat === null ? Number.POSITIVE_INFINITY : multiplyLength(previousToken.maxLength, token.quantifier.maxRepeat);
previousToken.containsRepetition = true;
frame.containsRepetition = true;
frame.branchMinLength = frame.branchMinLength - previousMinLength + previousToken.minLength;
frame.branchMaxLength = addLength(Number.isFinite(frame.branchMaxLength) && Number.isFinite(previousMaxLength) ? frame.branchMaxLength - previousMaxLength : Number.POSITIVE_INFINITY, previousToken.maxLength);
}
return false;
}
function hasNestedRepetition(source) {
return analyzeTokensForNestedRepetition(tokenizePattern(source));
}
function compileSafeRegexDetailed(source, flags = "") {
const trimmed = source.trim();
if (!trimmed) return {
regex: null,
source: trimmed,
flags,
reason: "empty"
};
const cacheKey = `${flags}::${trimmed}`;
const cached = safeRegexCache.get(cacheKey);
if (cached) return cached;
let result;
if (hasNestedRepetition(trimmed)) result = {
regex: null,
source: trimmed,
flags,
reason: "unsafe-nested-repetition"
};
else try {
result = {
regex: new RegExp(trimmed, flags),
source: trimmed,
flags,
reason: null
};
} catch {
result = {
regex: null,
source: trimmed,
flags,
reason: "invalid-regex"
};
}
safeRegexCache.set(cacheKey, result);
pruneMapToMaxSize(safeRegexCache, SAFE_REGEX_CACHE_MAX);
return result;
}
var SAFE_REGEX_CACHE_MAX, safeRegexCache;
var init_safe_regex = __esmMin((() => {
init_src$2();
init_map_size();
SAFE_REGEX_CACHE_MAX = 256;
safeRegexCache = /* @__PURE__ */ new Map();
}));
//#endregion
//#region src/security/config-regex.ts
function normalizeRejectReason(result) {
if (result.reason === null || result.reason === "empty") return null;
return result.reason;
}
/**
* Compile a single user-configured regex with the shared safe-regex guardrails.
* Returns null for blank patterns so optional config entries can be skipped silently.
*/
function compileConfigRegex(pattern, flags = "") {
const result = compileSafeRegexDetailed(pattern, flags);
if (result.reason === "empty") return null;
return {
regex: result.regex,
pattern: result.source,
flags: result.flags,
reason: normalizeRejectReason(result)
};
}
var init_config_regex = __esmMin((() => {
init_safe_regex();
}));
//#endregion
//#region src/infra/prototype-keys.ts
/** Return true when assigning `key` could mutate an object prototype. */
function isBlockedObjectKey(key) {
return BLOCKED_OBJECT_KEYS.has(key);
}
var BLOCKED_OBJECT_KEYS;
var init_prototype_keys = __esmMin((() => {
BLOCKED_OBJECT_KEYS = /* @__PURE__ */ new Set([
"__proto__",
"prototype",
"constructor"
]);
}));
//#endregion
//#region src/shared/dot-path.ts
/** Appends one config path segment without confusing literal record keys with traversal. */
function appendConfigPathSegment(path, segment) {
if (typeof segment === "number") return `${path}[${segment}]`;
if (!/^[A-Za-z_$][A-Za-z0-9_$:-]*$/.test(segment)) return `${path}[${JSON.stringify(segment)}]`;
return path ? `${path}.${segment}` : segment;
}
var init_dot_path = __esmMin((() => {}));
//#endregion
//#region packages/normalization-core/src/home-dir.ts
function normalizeHomeDirValue(value) {
const trimmed = value?.trim();
return trimmed && trimmed !== "undefined" && trimmed !== "null" ? trimmed : void 0;
}
function normalizeSafe(homedir) {
try {
return normalizeHomeDirValue(homedir());
} catch {
return;
}
}
function resolveTermuxHome(env) {
const prefix = normalizeHomeDirValue(env.PREFIX);
if (!prefix || !normalizeHomeDirValue(env.ANDROID_DATA)) return;
if (!/(?:^|\/)com\.termux\/files\/usr\/?$/u.test(prefix.replace(/\\/gu, "/"))) return;
return path.resolve(prefix, "..", "home");
}
function resolveRawOsHomeDir(env, homedir) {
return normalizeHomeDirValue(env.HOME) ?? normalizeHomeDirValue(env.USERPROFILE) ?? resolveTermuxHome(env) ?? normalizeSafe(homedir);
}
function resolveOsHomeDir(env = process.env, homedir = os.homedir) {
const raw = resolveRawOsHomeDir(env, homedir);
return raw ? path.resolve(raw) : void 0;
}
function resolveEffectiveHomeDir(env = process.env, homedir = os.homedir, options) {
const explicitHome = normalizeHomeDirValue(env.OPENCLAW_HOME);
if (!explicitHome) return resolveOsHomeDir(env, homedir);
if (explicitHome === "~" || explicitHome.startsWith("~/") || explicitHome.startsWith("~\\")) {
const osHome = resolveRawOsHomeDir(env, homedir);
if (!osHome) return options?.preserveUnresolvedTilde ? path.resolve(explicitHome) : void 0;
return path.resolve(explicitHome.replace(/^~(?=$|[\\/])/, () => osHome));
}
return path.resolve(explicitHome);
}
var init_home_dir$1 = __esmMin((() => {}));
//#endregion
//#region src/infra/safe-cwd.ts
function tryProcessCwd() {
try {
return process.cwd();
} catch {
return;
}
}
var init_safe_cwd = __esmMin((() => {}));
//#endregion
//#region src/infra/home-dir.ts
/** Resolves the effective home or falls back to cwd when no home source exists. */
function resolveRequiredHomeDir(env = process.env, homedir = os.homedir) {
const resolved = resolveEffectiveHomeDir(env, homedir) ?? tryProcessCwd();
if (resolved) return path.resolve(resolved);
throw new Error("Unable to resolve an OpenClaw home: set OPENCLAW_HOME, HOME, or USERPROFILE, or run from an existing directory.");
}
/** Resolves the OS home or falls back to cwd when no OS home source exists. */
function resolveRequiredOsHomeDir(env = process.env, homedir = os.homedir) {
const resolved = resolveOsHomeDir(env, homedir) ?? tryProcessCwd();
if (resolved) return path.resolve(resolved);
throw new Error("Unable to resolve an OS home: set HOME or USERPROFILE, or run from an existing directory.");
}
/** Expands leading `~`, `~/`, or `~\` with the effective home when one is known. */
function expandHomePrefix(input, opts) {
if (!input.startsWith("~")) return input;
const home = normalizeHomeDirValue(opts?.home) ?? resolveEffectiveHomeDir(opts?.env ?? process.env, opts?.homedir ?? os.homedir);
if (!home) return input;
return input.replace(/^~(?=$|[\\/])/, () => home);
}
function resolvePathWithHome(input, opts, resolveHome) {
const trimmed = input.trim();
if (!trimmed) return trimmed;
if (trimmed.startsWith("~")) {
const expanded = expandHomePrefix(trimmed, {
home: resolveHome(opts?.env ?? process.env, opts?.homedir ?? os.homedir),
env: opts?.env,
homedir: opts?.homedir
});
return path.resolve(expanded);
}
return path.resolve(trimmed);
}
/** Resolves a user-supplied path after trimming and expanding against the effective home. */
function resolveHomeRelativePath(input, opts) {
return resolvePathWithHome(input, opts, resolveRequiredHomeDir);
}
/** Resolves a user path against the effective home, preserving an empty input. */
function resolveUserPath(input, env = process.env, homedir = os.homedir) {
if (!input) return "";
return resolveHomeRelativePath(input, {
env,
homedir
});
}
var init_home_dir = __esmMin((() => {
init_home_dir$1();
init_safe_cwd();
}));
//#endregion
//#region src/infra/config-dir.ts
/** Resolves the OpenClaw config directory from state/config env overrides or home. */
function resolveConfigDir(env = process.env, homedir = os.homedir) {
const override = env.OPENCLAW_STATE_DIR?.trim();
if (override) return resolveUserPath(override, env, homedir);
const configPath = env.OPENCLAW_CONFIG_PATH?.trim();
if (configPath) return path.dirname(resolveUserPath(configPath, env, homedir));
return path.join(resolveRequiredHomeDir(env, homedir), ".openclaw");
}
var init_config_dir = __esmMin((() => {
init_home_dir();
}));
//#endregion
//#region src/infra/path-guards.ts
/**
* Normalize a Windows path for boundary math whose result is handed back to callers.
*
* Unlike `normalizeWindowsPathForComparison`, this preserves case: `path.win32.relative`
* already matches roots case-insensitively, so lowercasing only corrupts the returned
* relative path — and callers create files from it on a case-preserving filesystem.
* Extended-length prefix stripping stays, or `\\?\`-prefixed inputs read as boundary escapes.
*/
function normalizeWindowsPathPreservingCase(input) {
const normalized = path.win32.normalize(input);
if (!normalized.startsWith("\\\\?\\")) return normalized;
const withoutPrefix = normalized.slice(4);
return withoutPrefix.toUpperCase().startsWith("UNC\\") ? `\\\\${withoutPrefix.slice(4)}` : withoutPrefix;
}
var init_path_guards = __esmMin((() => {}));
//#endregion
//#region src/infra/home-display.ts
var init_home_display = __esmMin((() => {
init_path_guards();
}));
//#endregion
//#region src/infra/plain-object.ts
/**
* Config merge/patch uses the object tag, not prototype identity: class instances
* and custom prototypes remain accepted, while Date/Map/Set values are excluded.
*/
function isPlainObject$1(value) {
return typeof value === "object" && value !== null && !Array.isArray(value) && Object.prototype.toString.call(value) === "[object Object]";
}
var init_plain_object = __esmMin((() => {}));
//#endregion
//#region src/shared/regexp.ts
/** Escape text so it can be embedded literally inside a RegExp pattern. */
function escapeRegExp(value) {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
var init_regexp = __esmMin((() => {}));
//#endregion
//#region packages/retry/src/index.ts
function clampNumber(value, fallback, min, max) {
if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
return Math.min(Math.max(value, min ?? Number.NEGATIVE_INFINITY), max ?? Number.POSITIVE_INFINITY);
}
function resolveAttemptCount(value, fallback) {
return Math.max(1, Math.round(clampNumber(value, fallback)));
}
function resolveRetryDelayMs(value) {
return Math.min(Math.max(Math.round(value === Number.POSITIVE_INFINITY ? MAX_TIMER_TIMEOUT_MS : Number.isFinite(value) ? value : 0), 0), MAX_TIMER_TIMEOUT_MS);
}
function resolveJitterConfig(value, fallback) {
if (value === "full") return "full";
return typeof value === "number" && Number.isFinite(value) ? Math.min(Math.max(value, 0), 1) : fallback;
}
function resolveRetryConfig(defaults = DEFAULT_RETRY_CONFIG, overrides) {
const attempts = resolveAttemptCount(overrides?.attempts, defaults.attempts);
const minDelayMs = resolveRetryDelayMs(clampNumber(overrides?.minDelayMs, defaults.minDelayMs, 0));
return {
attempts,
minDelayMs,
maxDelayMs: Math.max(minDelayMs, resolveRetryDelayMs(clampNumber(overrides?.maxDelayMs, defaults.maxDelayMs, 0))),
jitter: resolveJitterConfig(overrides?.jitter, defaults.jitter)
};
}
function applyJitter(delayMs, jitter, mode, random) {
if (jitter === "full") {
if (mode === "symmetric") return Math.max(0, Math.round(delayMs * (.5 + random() * .5)));
return Math.max(0, Math.ceil(delayMs * (1 + random())));
}
if (jitter <= 0) return mode === "positive" ? Math.ceil(delayMs) : delayMs;
const fraction = random();
const raw = delayMs * (1 + (mode === "positive" ? fraction * jitter : (fraction * 2 - 1) * jitter));
return Math.max(0, mode === "positive" ? Math.ceil(raw) : Math.round(raw));
}
function toRetryError(value, fallbackMessage = "Non-Error thrown") {
if (value instanceof Error) return value;
if (typeof value === "string") return new Error(value);
const error = new Error(fallbackMessage, { cause: value });
if (typeof value === "object" && value !== null || typeof value === "function") Object.assign(error, value);
return error;
}
function createRetryRunner(runtime = {}) {
const runtimeSleep = runtime.sleep ?? defaultSleep;
const runtimeRandom = runtime.random ?? Math.random;
const createFailure = runtime.createFailure ?? ((errors) => toRetryError(errors.at(-1) ?? /* @__PURE__ */ new Error("Retry failed")));
return async function retryAsync(fn, attemptsOrOptions = 3, initialDelayMs = 300) {
const attemptErrors = [];
if (typeof attemptsOrOptions === "number") {
const attempts = resolveAttemptCount(attemptsOrOptions, DEFAULT_RETRY_CONFIG.attempts);
for (let index = 0; index < attempts; index += 1) try {
return await fn();
} catch (err) {
attemptErrors.push(err);
if (index === attempts - 1) break;
await runtimeSleep(resolveRetryDelayMs(initialDelayMs * 2 ** index));
}
throw createFailure(attemptErrors);
}
const options = attemptsOrOptions;
const resolved = resolveRetryConfig(DEFAULT_RETRY_CONFIG, options);
const maxAttempts = resolved.attempts;
const minDelayMs = resolved.minDelayMs;
const maxDelayMs = resolved.maxDelayMs > 0 ? resolved.maxDelayMs : Number.POSITIVE_INFINITY;
const retryAfterMaxDelayMs = options.retryAfterMaxDelayMs === void 0 ? maxDelayMs : Math.max(minDelayMs, resolveRetryDelayMs(clampNumber(options.retryAfterMaxDelayMs, maxDelayMs, 0)));
const random = options.random ?? runtimeRandom;
const sleep = options.sleep ?? runtimeSleep;
const shouldRetry = options.shouldRetry ?? (() => true);
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) try {
return await fn();
} catch (err) {
attemptErrors.push(err);
if (attempt >= maxAttempts || !shouldRetry(err, attempt)) break;
const context = {
attempt,
maxAttempts,
err,
label: options.label
};
const retryAfterMs = options.retryAfterMs?.(err);
const hasRetryAfter = typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs);
const configuredDelay = typeof options.delayMs === "function" ? options.delayMs(context) : options.delayMs;
const resolvedConfiguredDelay = configuredDelay === void 0 ? void 0 : resolveRetryDelayMs(configuredDelay);
const baseDelay = hasRetryAfter ? Math.max(retryAfterMs, minDelayMs) : resolvedConfiguredDelay === void 0 ? minDelayMs * 2 ** (attempt - 1) : Math.max(resolvedConfiguredDelay, minDelayMs);
const delayCap = hasRetryAfter ? retryAfterMaxDelayMs : maxDelayMs;
let delay = Math.min(baseDelay, delayCap);
const canHonorRetryAfter = hasRetryAfter && (retryAfterMs ?? 0) <= delayCap;
const wantsPositiveDraw = resolved.jitter === "full" ? !hasRetryAfter || canHonorRetryAfter : canHonorRetryAfter;
delay = applyJitter(delay, resolved.jitter, wantsPositiveDraw ? "positive" : "symmetric", random);
delay = Math.min(Math.max(delay, minDelayMs), delayCap);
await options.onRetry?.({
...context,
delayMs: delay
});
if (delay > 0) await sleep(delay);
}
throw createFailure(attemptErrors);
};
}
var MAX_TIMER_TIMEOUT_MS, DEFAULT_RETRY_CONFIG, defaultSleep;
var init_src$1 = __esmMin((() => {
MAX_TIMER_TIMEOUT_MS = 2147e6;
DEFAULT_RETRY_CONFIG = {
attempts: 3,
minDelayMs: 300,
maxDelayMs: 3e4,
jitter: 0
};
defaultSleep = async (ms) => {
let remainingMs = ms;
do {
const delayMs = Math.min(remainingMs, MAX_TIMER_TIMEOUT_MS);
await new Promise((resolve) => {
setTimeout(resolve, delayMs);
});
remainingMs -= delayMs;
} while (remainingMs > 0);
};
createRetryRunner();
}));
//#endregion
//#region src/infra/abort-signal.ts
function isAbortError(error) {
if (!error || typeof error !== "object") return false;
try {
if (("name" in error ? String(error.name) : "") === "AbortError") return true;
return ("message" in error && typeof error.message === "string" ? error.message : "") === "This operation was aborted";
} catch {
return false;
}
}
var init_abort_signal = __esmMin((() => {}));
//#endregion
//#region src/utils/sleep.ts
var init_sleep = __esmMin((() => {
init_number_coercion();
init_src$1();
}));
var init_utils = __esmMin((() => {
init_config_dir();
init_home_display();
init_plain_object();
init_sleep();
resolveConfigDir();
}));
//#endregion
//#region src/secrets/ref-contract.ts
var DEFAULT_SECRET_PROVIDER_ALIAS;
var init_ref_contract = __esmMin((() => {
DEFAULT_SECRET_PROVIDER_ALIAS = "default";
}));
//#endregion
//#region src/config/types.secrets.ts
/** Parse `$NAME` and `${NAME}` env-secret shorthand strings into env SecretRefs. */
function parseEnvTemplateSecretRef(value, provider = DEFAULT_SECRET_PROVIDER_ALIAS) {
if (typeof value !== "string") return null;
const trimmed = value.trim();
const match = ENV_SECRET_TEMPLATE_RE.exec(trimmed) ?? ENV_SECRET_SHORTHAND_RE.exec(trimmed);
if (!match) return null;
return {
source: "env",
provider: provider.trim() || "default",
id: expectDefined(match[1], "types.secrets regex capture 1")
};
}
var ENV_SECRET_TEMPLATE_RE, ENV_SECRET_SHORTHAND_RE;
var init_types_secrets = __esmMin((() => {
init_src$2();
init_ref_contract();
ENV_SECRET_TEMPLATE_RE = /^\$\{([A-Z][A-Z0-9_]{0,127})\}$/;
ENV_SECRET_SHORTHAND_RE = /^\$([A-Z][A-Z0-9_]{0,127})$/;
}));
//#endregion
//#region src/config/env-substitution.ts
/**
* Parses the text between `${` and the first following `}`.
*
* A fallback is recognized only when it carries no `$` and no `{`. That keeps the scan
* for the closing brace a plain `indexOf("}")`, so no input that is left literal today
* starts parsing differently: `${A:-${B}}` still falls through to the literal path and
* its inner `${B}` is still the only thing that substitutes, exactly as before.
*/
function parseEnvTokenBody(body) {
if (ENV_VAR_NAME_PATTERN.test(body)) return { name: body };
const operatorIndex = body.indexOf(DEFAULT_VALUE_OPERATOR);
if (operatorIndex === -1) return null;
const name = body.slice(0, operatorIndex);
if (!ENV_VAR_NAME_PATTERN.test(name)) return null;
const defaultValue = body.slice(operatorIndex + 2);
if (defaultValue.includes("$") || defaultValue.includes("{")) return null;
return {
name,
defaultValue
};
}
/** Rebuilds the authored placeholder text for a parsed token. */
function renderEnvTemplateToken(token) {
return token.defaultValue === void 0 ? `\${${token.name}}` : `\${${token.name}${DEFAULT_VALUE_OPERATOR}${token.defaultValue}}`;
}
function parseEnvTokenAt(value, index) {
if (value[index] !== "$") return null;
const escaped = value[index + 1] === "$" && value[index + 2] === "{";
if (escaped || value[index + 1] === "{") {
const start = index + (escaped ? 3 : 2);
const end = value.indexOf("}", start);
if (end !== -1) {
const body = parseEnvTokenBody(value.slice(start, end));
if (body) return {
kind: escaped ? "escaped" : "substitution",
...body,
end
};
}
}
return null;
}
function* iterateEnvTemplateTokens(value) {
for (let index = value.indexOf("$"); index !== -1; index = value.indexOf("$", index + 1)) {
const token = parseEnvTokenAt(value, index);
if (token) {
yield {
...token,
start: index
};
index = token.end;
}
}
}
function substituteString(value, env, configPath, opts) {
if (!value.includes("$")) return value;
const authoredRef = parseEnvTemplateSecretRef(value);
if (authoredRef && !containsEnvVarReference(value)) opts?.onPendingEnvSecretRef?.(authoredRef.id, configPath);
const chunks = [];
let end = 0;
for (const token of iterateEnvTemplateTokens(value)) {
chunks.push(value.slice(end, token.start));
end = token.end + 1;
if (token.kind === "escaped") {
chunks.push(renderEnvTemplateToken(token));
continue;
}
const envValue = env[token.name];
if (envValue === void 0 || envValue === "") {
if (token.defaultValue !== void 0) {
chunks.push(token.defaultValue);
continue;
}
if (opts?.onMissing) {
opts.onMissing({
varName: token.name,
configPath
});
if (authoredRef?.id === token.name) opts.onPendingEnvSecretRef?.(token.name, configPath);
chunks.push(renderEnvTemplateToken(token));
continue;
}
throw new MissingEnvVarError(token.name, configPath);
}
if (authoredRef?.id === token.name) opts?.onResolvedEnvSecretRef?.(token.name, configPath);
chunks.push(envValue);
}
chunks.push(value.slice(end));
return chunks.join("");
}
/** Detects unescaped `${VAR}` references without treating escaped `$${VAR}` as references. */
function containsEnvVarReference(value) {
for (const token of iterateEnvTemplateTokens(value)) if (token.kind === "substitution") return true;
return false;
}
function substituteAny(value, env, path, opts) {
const pending = [];
const visit = (current, currentPath) => {
if (typeof current === "string") return substituteString(current, env, currentPath, opts);
if (Array.isArray(current)) {
const length = current.length;
const result = [];
result.length = length;
let index = 0;
pending.push(() => {
while (index < length) {
const key = index++;
if (key in current) {
result[key] = visit(current[key], `${currentPath}[${key}]`);
return true;
}
}
return false;
});
return result;
}
if (isPlainObject$1(current)) {
const result = {};
const entries = Object.entries(current)[Symbol.iterator]();
pending.push(() => {
const entry = entries.next();
if (entry.done) return false;
const [key, child] = entry.value;
result[key] = visit(child, appendConfigPathSegment(currentPath, key));
return true;
});
return result;
}
return current;
};
const result = visit(value, path);
for (let next = pending.at(-1); next; next = pending.at(-1)) if (!next()) pending.pop();
return result;
}
/**
* Resolves `${VAR_NAME}` environment variable references in config values.
*
* @param obj - The parsed config object (after JSON5 parse and $include resolution)
* @param env - Environment variables to use for substitution (defaults to process.env)
* @param opts - Options: `onMissing` callback to collect warnings instead of throwing.
* @returns The config object with env vars substituted
* @throws {MissingEnvVarError} If a referenced env var is not set or empty (unless `onMissing` is set)
*/
function resolveConfigEnvVars(obj, env = process.env, opts) {
return substituteAny(obj, env, "", opts);
}
var ENV_VAR_NAME_PATTERN, DEFAULT_VALUE_OPERATOR, MissingEnvVarError;
var init_env_substitution = __esmMin((() => {
init_dot_path();
init_utils();
init_types_secrets();
ENV_VAR_NAME_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
DEFAULT_VALUE_OPERATOR = ":-";
MissingEnvVarError = class extends Error {
constructor(varName, configPath) {
super(`Missing env var "${varName}" referenced at config path: ${configPath}`);
this.varName = varName;
this.configPath = configPath;
this.name = "MissingEnvVarError";
}
};
}));
//#endregion
//#region src/infra/boundary-file-read.ts
var init_boundary_file_read = __esmMin((() => {}));
//#endregion
//#region src/infra/boundary-path.ts
function resolveIdentityPathViaExistingAncestorSync(targetPath) {
const fallback = path.resolve(targetPath);
const missingSegments = [];
let cursor = fallback;
while (true) try {
return path.join(fs.realpathSync.native(cursor), ...missingSegments.toReversed());
} catch {
const parent = path.dirname(cursor);
if (parent === cursor) return fallback;
missingSegments.push(path.basename(cursor));
cursor = parent;
}
}
var init_boundary_path = __esmMin((() => {
AsyncLocalStorage.snapshot();
}));
//#endregion
//#region src/infra/deep-merge.ts
function sanitizePlainObject(value) {
const sanitized = {};
for (const [key, entry] of Object.entries(value)) {
if (isBlockedObjectKey(key)) continue;
sanitized[key] = isPlainObject$1(entry) ? sanitizePlainObject(entry) : entry;
}
return sanitized;
}
/** Merge plain objects while preserving OpenClaw's null, undefined, and array policies. */
function mergeDeep(base, override, options = {}) {
const arrays = options.arrays ?? "replace";
const undefinedValues = options.undefinedValues ?? "skip";
if (Array.isArray(base) && Array.isArray(override)) return arrays === "concat" ? [...base, ...override] : override;
if (!isPlainObject$1(base) || !isPlainObject$1(override)) return override === void 0 && undefinedValues === "skip" ? base : override;
const merged = sanitizePlainObject(base);
for (const [key, value] of Object.entries(override)) {
if (isBlockedObjectKey(key) || value === void 0 && undefinedValues === "skip") continue;
const current = merged[key];
if (isPlainObject$1(value)) merged[key] = isPlainObject$1(current) ? mergeDeep(current, value, options) : sanitizePlainObject(value);
else if (arrays === "concat" && Array.isArray(current) && Array.isArray(value)) merged[key] = [...current, ...value];
else merged[key] = value;
}
return merged;
}
var init_deep_merge = __esmMin((() => {
init_plain_object();
init_prototype_keys();
}));
//#endregion
//#region src/infra/errno.ts
/** Classifies missing filesystem paths across Node and fs-safe boundaries. */
function isMissingPathError(err) {
return hasErrnoCode(err, "ENOENT") || hasErrnoCode(err, "ENOTDIR") || hasErrnoCode(err, "not-found");
}
var init_errno = __esmMin((() => {}));
//#endregion
//#region src/security/scan-paths.ts
var init_scan_paths = __esmMin((() => {}));
//#endregion
//#region src/infra/sealed-runtime-registry.ts
function getSealedRuntimeJson5() {
return runtime?.json5;
}
function getSealedRuntimeSecureTempRoot() {
return runtime?.resolveSecureTempRoot;
}
var runtime;
var init_sealed_runtime_registry = __esmMin((() => {}));
//#endregion
//#region src/utils/parse-json-compat.ts
/**
* JSON parser compatibility helper for persisted config, manifests, and legacy stores.
* Strict JSON stays the fast path; JSON5 is only the authored/legacy fallback.
*/
function isJson5Parser(value) {
return typeof value === "object" && value !== null && "parse" in value && typeof value.parse === "function";
}
function setJson5Runtime(runtime) {
const parser = isJson5Parser(runtime) ? runtime : typeof runtime === "object" && runtime !== null && "default" in runtime ? runtime.default : void 0;
if (!isJson5Parser(parser)) throw new Error("json5 parser unavailable");
json5Runtime = parser;
return parser;
}
function loadJson5Parser() {
if (json5Runtime) return json5Runtime;
const injected = getSealedRuntimeJson5();
if (injected !== void 0) return setJson5Runtime(injected);
if (typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) throw new Error("sealed JSON5 runtime was not registered before use");
return setJson5Runtime(createRequire(import.meta.url)("json5"));
}
/** Parses strict JSON first, then accepts JSON5 syntax such as comments and trailing commas. */
function parseJsonWithJson5Fallback(raw, json5) {
try {
return JSON.parse(raw);
} catch {
return (json5 ?? loadJson5Parser()).parse(raw);
}
}
var json5Runtime;
var init_parse_json_compat = __esmMin((() => {
init_sealed_runtime_registry();
}));
//#endregion
//#region src/config/includes.ts
function isConfigContainer(value) {
return Array.isArray(value) || isPlainObject$1(value);
}
function includeLogicalPath(link) {
const parts = [];
for (let current = link; current; current = current.parent) parts.push(current.key);
return parts.toReversed();
}
/** Deep merge: arrays concatenate, objects merge recursively, primitives: source wins */
function deepMerge(target, source) {
return mergeDeep(target, source, {
arrays: "concat",
undefinedValues: "replace"
});
}
function safeRealpath(target) {
try {
return fs.realpathSync(target);
} catch {
return target;
}
}
/** Capture the lexical and canonical include roots once for a resolver traversal. */
function createConfigIncludeBoundary(configPath, allowedRoots = []) {
const configRootDir = path.normalize(path.dirname(configPath));
return {
configRoot: {
rootDir: configRootDir,
rootRealDir: path.normalize(safeRealpath(configRootDir))
},
allowedRoots: allowedRoots.filter((entry) => typeof entry === "string" && entry.length > 0 && path.isAbsolute(entry)).map((entry) => {
const rootDir = path.normalize(entry);
return {
rootDir,
rootRealDir: path.normalize(safeRealpath(rootDir))
};
})
};
}
function readConfigIncludeFileWithGuards(params) {
const ioFs = params.ioFs ?? fs;
const maxBytes = params.maxBytes ?? MAX_INCLUDE_FILE_BYTES;
if (!canUseRootFileOpen(ioFs)) {
const raw = ioFs.readFileSync(params.resolvedPath, "utf-8");
try {
params.onResolvedPath?.(path.normalize(ioFs.realpathSync(params.resolvedPath)));
} catch {}
return raw;
}
const opened = openRootFileSync({
absolutePath: params.resolvedPath,
rootPath: params.rootRealDir,
rootRealPath: params.rootRealDir,
boundaryLabel: "config directory",
skipLexicalRootCheck: true,
rejectSymlinks: false,
maxBytes,
ioFs
});
if (!opened.ok) {
if (opened.reason === "validation") throw new ConfigIncludeError(`Include file failed security checks (regular file, max ${maxBytes} bytes, no hardlinks): ${params.includePath}`, params.includePath);
throw new ConfigIncludeReadError(`Failed to read include file: ${params.includePath} (resolved: ${params.resolvedPath})`, params.includePath, opened.error instanceof Error ? opened.error : void 0);
}
try {
const raw = ioFs.readFileSync(opened.fd, "utf-8");
params.onResolvedPath?.(path.normalize(opened.path));
return raw;
} finally {
ioFs.closeSync(opened.fd);
}
}
/**
* Resolves all $include directives in a parsed config object.
*/
function resolveConfigIncludes(obj, configPath, resolver = defaultResolver, options = {}) {
const boundary = createConfigIncludeBoundary(configPath, options.allowedRoots ?? []);
return new IncludeProcessor(configPath, resolver, boundary).process(obj);
}
/**
* Resolves one top-level config field through the canonical include graph while
* leaving unrelated top-level branches untouched. Early bootstrap readers use
* this when a malformed sibling must not hide an independently valid setting.
*/
function resolveConfigIncludesForTopLevelKey(obj, configPath, key, resolver = defaultResolver, options = {}) {
const boundary = createConfigIncludeBoundary(configPath, options.allowedRoots ?? []);
return new IncludeProcessor(configPath, resolver, boundary, /* @__PURE__ */ new Set([key])).process(obj);
}
var INCLUDE_KEY, MAX_INCLUDE_FILE_BYTES, MAX_INCLUDE_PATH_LENGTH, ConfigIncludeError, ConfigIncludeReadError, CircularIncludeError, IncludeProcessor, defaultResolver;
var init_includes = __esmMin((() => {
init_src$2();
init_boundary_file_read();
init_boundary_path();
init_deep_merge();
init_errno();
init_scan_paths();
init_utils();
init_parse_json_compat();
INCLUDE_KEY = "$include";
MAX_INCLUDE_FILE_BYTES = 2097152;
MAX_INCLUDE_PATH_LENGTH = 4096;
ConfigIncludeError = class extends Error {
constructor(message, includePath, cause) {
super(message);
this.includePath = includePath;
this.cause = cause;
this.name = "ConfigIncludeError";
}
};
ConfigIncludeReadError = class extends ConfigIncludeError {
constructor(..._args) {
super(..._args);
this.name = "ConfigIncludeReadError";
}
};
CircularIncludeError = class extends ConfigIncludeError {
constructor(chain) {
super(`Circular include detected: ${chain.join(" -> ")}`, expectDefined(chain[chain.length - 1], "chain entry at chain.length 1"));
this.chain = chain;
this.name = "CircularIncludeError";
}
};
IncludeProcessor = class {
constructor(basePath, resolver, boundary, rootProjectionKeys) {
this.basePath = basePath;
this.resolver = resolver;
this.boundary = boundary;
this.rootProjectionKeys = rootProjectionKeys;
}
get rootDir() {
return this.boundary.configRoot.rootDir;
}
process(obj) {
const stack = [];
let current = this.traverseValue(obj, null, false, {
basePath: this.basePath,
visited: /* @__PURE__ */ new Set([path.normalize(this.basePath)]),
depth: 0
});
let delivered = void 0;
for (;;) {
const step = current.next(delivered);
if (step.done) {
const parent = stack.pop();
if (!parent) return step.value;
delivered = step.value;
current = parent;
continue;
}
stack.push(current);
current = this.traverseValue(step.value.value, step.value.pathLink, step.value.hasArrayAncestor, step.value.context);
}
}
*traverseValue(value, pathLink, hasArrayAncestor, context) {
if (Array.isArray(value)) {
const result = [];
for (const [index, item] of value.entries()) result.push(isConfigContainer(item) ? yield {
value: item,
pathLink: {
parent: pathLink,
key: String(index)
},
hasArrayAncestor: true,
context
} : item);
return result;
}
if (!isPlainObject$1(value)) return value;
if (!("$include" in value)) {
const isRoot = pathLink === null;
const result = {};
for (const [key, entry] of Object.entries(value)) {
if (isRoot && this.rootProjectionKeys && !this.rootProjectionKeys.has(key)) continue;
result[key] = isConfigContainer(entry) ? yield {
value: entry,
pathLink: {
parent: pathLink,
key
},
hasArrayAncestor,
context
} : entry;
}
return result;
}
return yield* this.traverseInclude(value, pathLink, hasArrayAncestor, context);
}
*traverseInclude(obj, pathLink, hasArrayAncestor, context) {
const includeValue = obj[INCLUDE_KEY];
const isRoot = pathLink === null;
const siblingKeys = Object.keys(obj).filter((key) => key !== "$include" && (!isRoot || !this.rootProjectionKeys || this.rootProjectionKeys.has(key)));
let included;
let targetPath;
let targetPaths;
if (typeof includeValue === "string") {
const loaded = this.loadFileSync(includeValue, context);
included = yield {
value: loaded.parsed,
pathLink,
hasArrayAncestor,
context: loaded.nestedContext
};
targetPath = loaded.resolvedPath;
} else if (Array.isArray(includeValue)) {
const entries = [];
for (const item of includeValue) {
if (typeof item !== "string") throw new ConfigIncludeError(`Invalid $include array item: expected string, got ${typeof item}`, String(item));
const loaded = this.loadFileSync(item, context);
entries.push({
value: yield {
value: loaded.parsed,
pathLink,
hasArrayAncestor,
context: loaded.nestedContext
},
targetPath: loaded.resolvedPath
});
}
included = entries.reduce((current, entry) => deepMerge(current, entry.value), {});
targetPaths = entries.map((entry) => entry.targetPath);
} else throw new ConfigIncludeError(`Invalid $include value: expected string or array of strings, got ${typeof includeValue}`, String(includeValue));
this.resolver.onIncludeResolved?.({
path: includeLogicalPath(pathLink),
value: included,
kind: Array.isArray(includeValue) ? "multiple" : "single",
hasSiblingOverrides: siblingKeys.length > 0,
hasArrayAncestor,
...targetPath ? { targetPath } : {},
...targetPaths ? { targetPaths } : {}
});
if (siblingKeys.length === 0) return included;
if (!isPlainObject$1(included)) throw new ConfigIncludeError("Sibling keys require included content to be an object", typeof includeValue === "string" ? includeValue : INCLUDE_KEY);
const rest = {};
for (const key of siblingKeys) {
const sibling = obj[key];
rest[key] = isConfigContainer(sibling) ? yield {
value: sibling,
pathLink: {
parent: pathLink,
key
},
hasArrayAncestor,
context
} : sibling;
}
return deepMerge(included, rest);
}
loadFileSync(includePath, context) {
const { resolvedPath, root } = this.resolvePath(includePath, context);
if (context.visited.has(resolvedPath)) throw new CircularIncludeError([...context.visited, resolvedPath]);
if (context.depth >= 10) throw new ConfigIncludeError(`Maximum include depth (10) exceeded at: ${includePath}`, includePath);
const raw = this.readFile(includePath, resolvedPath, root);
return {
parsed: this.parseFile(includePath, resolvedPath, raw),
resolvedPath,
nestedContext: {
basePath: resolvedPath,
visited: /* @__PURE__ */ new Set([...context.visited, resolvedPath]),
depth: context.depth + 1
}
};
}
resolvePath(includePath, context) {
if (includePath.includes("\0")) throw new ConfigIncludeError("Include path must not contain null bytes", includePath);
if (includePath.length >= MAX_INCLUDE_PATH_LENGTH) throw new ConfigIncludeError(`Include path exceeds maximum length (${MAX_INCLUDE_PATH_LENGTH} characters)`, includePath);
const configDir = path.dirname(context.basePath);
const resolved = path.isAbsolute(includePath) ? includePath : path.resolve(configDir, includePath);
const normalized = path.normalize(resolved);
if (normalized.length >= MAX_INCLUDE_PATH_LENGTH) throw new ConfigIncludeError(`Resolved include path exceeds maximum length (${MAX_INCLUDE_PATH_LENGTH} characters)`, includePath);
const lexicalMatch = this.findContainingRoot(normalized, "rootDir");
if (!lexicalMatch) throw new ConfigIncludeError(`Include path escapes config directory: ${includePath} (root: ${this.rootDir})`, includePath);
this.resolver.onLexicalPath?.(normalized);
try {
const real = fs.realpathSync(normalized);
const realMatch = this.findContainingRoot(real, "rootRealDir");
if (!realMatch) throw new ConfigIncludeError(`Include path resolves outside config directory (symlink): ${includePath} (root: ${this.rootDir})`, includePath);
return {
resolvedPath: normalized,
root: realMatch
};
} catch (err) {
if (err instanceof ConfigIncludeError) throw err;
if (isMissingPathError(err)) return {
resolvedPath: normalized,
root: lexicalMatch
};
throw new ConfigIncludeReadError(`Failed to resolve include file realpath: ${includePath} (resolved: ${normalized})`, includePath, err instanceof Error ? err : void 0);
}
}
findContainingRoot(candidate, field) {
if (isPathInside(this.boundary.configRoot[field], candidate)) return this.boundary.configRoot;
for (const root of this.boundary.allowedRoots) if (isPathInside(root[field], candidate)) return root;
return null;
}
readFile(includePath, resolvedPath, root) {
try {
if (this.resolver.readFileWithGuards) return this.resolver.readFileWithGuards({
includePath,
resolvedPath,
rootRealDir: root.rootRealDir
});
return this.resolver.readFile(resolvedPath);
} catch (err) {
if (err instanceof ConfigIncludeError) throw err;
throw new ConfigIncludeReadError(`Failed to read include file: ${includePath} (resolved: ${resolvedPath})`, includePath, err instanceof Error ? err : void 0);
}
}
parseFile(includePath, resolvedPath, raw) {
try {
return this.resolver.parseJson(raw);
} catch (err) {
throw new ConfigIncludeError(`Failed to parse include file: ${includePath} (resolved: ${resolvedPath})`, includePath, err instanceof Error ? err : void 0);
}
}
};
defaultResolver = {
readFile: (p) => fs.readFileSync(p, "utf-8"),
readFileWithGuards: readConfigIncludeFileWithGuards,
parseJson: parseJsonWithJson5Fallback
};
}));
//#endregion
//#region src/cli/profile-utils.ts
function isValidProfileName(value) {
return PROFILE_NAME_RE.test(value);
}
/** Resolve the canonical home-scoped state root for a validated CLI profile. */
function resolveProfileStateDir(profile, env, homedir) {
const trimmed = profile.trim();
if (!isValidProfileName(trimmed)) throw new Error(`Invalid profile name: ${JSON.stringify(profile)}`);
const suffix = normalizeLowercaseStringOrEmpty(trimmed) === "default" ? "" : `-${trimmed}`;
return path.join(resolveRequiredHomeDir(env, homedir), `.openclaw${suffix}`);
}
var PROFILE_NAME_RE;
var init_profile_utils = __esmMin((() => {
init_string_coerce();
init_home_dir();
PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
}));
//#endregion
//#region src/infra/tcp-port.ts
var init_tcp_port = __esmMin((() => {
init_number_coercion();
}));
//#endregion
//#region src/infra/test-runtime-env.ts
/** Detects Vitest/test execution from the env shape used by local and worker processes. */
function isVitestRuntimeEnv(env = process.env) {
const vitest = env.VITEST;
return vitest === "true" || vitest === "1" || env.VITEST_POOL_ID !== void 0 || env.VITEST_WORKER_ID !== void 0 || env.NODE_ENV === "test";
}
/** Enables the shared fast-test shortcuts only inside a detected test runtime. */
function isFastTestRuntimeEnv(env = process.env) {
return env.OPENCLAW_TEST_FAST === "1" && (isVitestRuntimeEnv(env) || env !== process.env && isVitestRuntimeEnv(process.env));
}
var init_test_runtime_env = __esmMin((() => {}));
//#endregion
//#region src/config/state-dir.ts
function resolveDefaultHomeDir() {
return resolveRequiredHomeDir(process.env, os.homedir);
}
function resolveLegacyStateDirs(homedir = resolveDefaultHomeDir) {
return LEGACY_STATE_DIRNAMES.map((dir) => path.join(homedir(), dir));
}
function resolveNewStateDir(homedir = resolveDefaultHomeDir) {
return path.join(homedir(), NEW_STATE_DIRNAME);
}
/**
* State directory for mutable data (sessions, logs, caches).
* Can be overridden via OPENCLAW_STATE_DIR.
* Default: ~/.openclaw
*/
function resolveStateDir(env = process.env, homedir = () => resolveRequiredHomeDir(env, os.homedir)) {
const effectiveHomedir = () => resolveRequiredHomeDir(env, homedir);
const override = env.OPENCLAW_STATE_DIR?.trim();
if (override) return resolveHomeRelativePath(override, {
env,
homedir: effectiveHomedir
});
return resolveStateDirFromHome(env, effectiveHomedir);
}
/** Select a default state directory from the caller's already resolved home. */
function resolveStateDirFromHome(env, effectiveHomedir) {
const newDir = resolveNewStateDir(effectiveHomedir);
if (isFastTestRuntimeEnv(env)) return newDir;
if (fs.existsSync(newDir)) return newDir;
const existingLegacy = resolveLegacyStateDirs(effectiveHomedir).find((dir) => {
try {
return fs.existsSync(dir);
} catch {
return false;
}
});
if (existingLegacy) return existingLegacy;
return newDir;
}
var LEGACY_STATE_DIRNAMES, NEW_STATE_DIRNAME;
var init_state_dir = __esmMin((() => {
init_home_dir();
init_test_runtime_env();
LEGACY_STATE_DIRNAMES = [".clawdbot"];
NEW_STATE_DIRNAME = ".openclaw";
}));
//#endregion
//#region src/config/paths.ts
/**
* Nix mode detection: When OPENCLAW_NIX_MODE=1, the gateway is running under Nix.
* In this mode:
* - No auto-install flows should be attempted
* - Missing dependencies should produce actionable Nix-specific error messages
* - Config is managed externally (read-only from Nix perspective)
*/
function resolveIsNixMode(env = process.env) {
return env.OPENCLAW_NIX_MODE === "1";
}
/** Build a homedir thunk that respects OPENCLAW_HOME for the given env. */
function envHomedir(env) {
return () => resolveRequiredHomeDir(env, os.homedir);
}
function normalizePathForComparison(candidate) {
const resolved = path.resolve(candidate);
try {
return fs.realpathSync.native(resolved);
} catch {
return resolved;
}
}
/**
* Optional allowlist of directories that `$include` directives may resolve
* outside the config directory. Set via `OPENCLAW_INCLUDE_ROOTS` as a
* platform-delimited path list (`:` on POSIX, `;` on Windows).
*
* Each entry is tilde-expanded and resolved to an absolute path. Entries that
* cannot be resolved or that are not absolute after expansion are dropped.
*
* Returns an empty array when the var is unset or contains no usable entries,
* preserving the historical behavior where `$include` is confined to the
* directory containing `openclaw.json`.
*/
function resolveIncludeRoots(env = process.env, homedir = envHomedir(env)) {
const raw = env.OPENCLAW_INCLUDE_ROOTS?.trim();
if (!raw) return [];
const effectiveHomedir = () => resolveRequiredHomeDir(env, homedir);
const seen = /* @__PURE__ */ new Set();
const roots = [];
for (const entry of raw.split(path.delimiter)) {
const trimmed = entry.trim();
if (!trimmed) continue;
const resolved = path.resolve(resolveHomeRelativePath(trimmed, {
env,
homedir: effectiveHomedir
}));
if (!path.isAbsolute(resolved) || seen.has(resolved)) continue;
seen.add(resolved);
roots.push(resolved);
}
return roots;
}
/**
* Config file path (JSON or JSON5).
* Can be overridden via OPENCLAW_CONFIG_PATH.
* Default: ~/.openclaw/openclaw.json (or $OPENCLAW_STATE_DIR/openclaw.json)
*/
function resolveCanonicalConfigPath(env = process.env, stateDir) {
const override = env.OPENCLAW_CONFIG_PATH?.trim();
if (override) return resolveUserPath(override, env, envHomedir(env));
return path.join(stateDir ?? resolveStateDir(env, envHomedir(env)), CONFIG_FILENAME);
}
/**
* Resolve the active config path by preferring existing config candidates
* before falling back to the canonical path.
*/
function resolveConfigPathCandidate(env = process.env, homedir = envHomedir(env)) {
const override = env.OPENCLAW_CONFIG_PATH?.trim();
if (override) return resolveUserPath(override, env, homedir);
if (isFastTestRuntimeEnv(env)) return resolveCanonicalConfigPath(env, resolveStateDir(env, homedir));
const existing = resolveDefaultConfigCandidates(env, homedir).find((candidate) => {
try {
return fs.existsSync(candidate);
} catch {
return false;
}
});
if (existing) return existing;
return resolveCanonicalConfigPath(env, resolveStateDir(env, homedir));
}
/**
* Active config path (prefers existing config files).
*/
function resolveConfigPath(env = process.env, stateDir, homedir = envHomedir(env)) {
const override = env.OPENCLAW_CONFIG_PATH?.trim();
if (override) return resolveUserPath(override, env, homedir);
const selectedStateDir = stateDir ?? resolveStateDir(env, envHomedir(env));
if (isFastTestRuntimeEnv(env)) return path.join(selectedStateDir, CONFIG_FILENAME);
const stateOverride = env.OPENCLAW_STATE_DIR?.trim();
const existing = [path.join(selectedStateDir, CONFIG_FILENAME), ...LEGACY_CONFIG_FILENAMES.map((name) => path.join(selectedStateDir, name))].find((candidate) => {
try {
return fs.existsSync(candidate);
} catch {
return false;
}
});
if (existing) return existing;
if (stateOverride) return path.join(selectedStateDir, CONFIG_FILENAME);
const defaultStateDir = resolveStateDir(env, homedir);
if (path.resolve(selectedStateDir) === path.resolve(defaultStateDir)) return resolveConfigPathCandidate(env, homedir);
return path.join(selectedStateDir, CONFIG_FILENAME);
}
/**
* Resolve default config path candidates across default locations.
* Order: explicit config path → state-dir-derived paths → new default.
*/
function resolveDefaultConfigCandidates(env = process.env, homedir = envHomedir(env)) {
const effectiveHomedir = () => resolveRequiredHomeDir(env, homedir);
const explicit = env.OPENCLAW_CONFIG_PATH?.trim();
if (explicit) return [resolveUserPath(explicit, env, effectiveHomedir)];
const candidates = [];
const openclawStateDir = env.OPENCLAW_STATE_DIR?.trim();
if (openclawStateDir) {
const resolved = resolveUserPath(openclawStateDir, env, effectiveHomedir);
candidates.push(path.join(resolved, CONFIG_FILENAME));
candidates.push(...LEGACY_CONFIG_FILENAMES.map((name) => path.join(resolved, name)));
}
const defaultDirs = [resolveNewStateDir(effectiveHomedir), ...resolveLegacyStateDirs(effectiveHomedir)];
for (const dir of defaultDirs) {
candidates.push(path.join(dir, CONFIG_FILENAME));
candidates.push(...LEGACY_CONFIG_FILENAMES.map((name) => path.join(dir, name)));
}
return candidates;
}
/**
* Gateway lock directory inside the selected state tree.
* Default: $OPENCLAW_STATE_DIR/tmp/openclaw-<uid> (uid suffix when available).
*/
function resolveGatewayLockDir(stateDir = resolveStateDir(), uid = typeof process.getuid === "function" ? process.getuid() : void 0) {
return resolveGatewayLockDirForCanonicalStateDir(normalizePathForComparison(stateDir), uid);
}
/** Append the lock layout when the caller has already resolved the state directory. */
function resolveGatewayLockDirForCanonicalStateDir(stateDir, uid = typeof process.getuid === "function" ? process.getuid() : void 0) {
const suffix = uid != null ? `openclaw-${uid}` : "openclaw";
return path.join(stateDir, "tmp", suffix);
}
var CONFIG_FILENAME, LEGACY_CONFIG_FILENAMES;
var init_paths$1 = __esmMin((() => {
init_home_dir();
init_tcp_port();
init_test_runtime_env();
init_state_dir();
resolveIsNixMode();
CONFIG_FILENAME = "openclaw.json";
LEGACY_CONFIG_FILENAMES = ["clawdbot.json"];
resolveStateDir();
resolveConfigPathCandidate();
}));
//#endregion
//#region src/logging/state.ts
function createUnownedAppliedLoggingConfig() {
return APPLIED_LOGGING_CONFIG_UNOWNED;
}
function createLoggingState() {
return {
appliedConfig: createUnownedAppliedLoggingConfig(),
cachedLogger: null,
cachedSettings: null,
cachedConsoleSettings: null,
overrideSettings: null,
invalidEnvLogLevelValue: null,
consolePatched: false,
forceConsoleToStderr: false,
earlyConsoleRoutingRestore: null,
consoleTimestampPrefix: false,
consoleSubsystemFilter: null,
streamErrorHandlersInstalled: false,
rawConsole: null
};
}
var LOGGING_STATE_KEY, APPLIED_LOGGING_CONFIG_UNOWNED, globalStore, loggingState;
var init_state = __esmMin((() => {
LOGGING_STATE_KEY = Symbol.for("openclaw.loggingState");
APPLIED_LOGGING_CONFIG_UNOWNED = "unowned";
globalStore = globalThis;
loggingState = globalStore[LOGGING_STATE_KEY] ?? createLoggingState();
if (!Object.hasOwn(loggingState, "appliedConfig")) loggingState.appliedConfig = APPLIED_LOGGING_CONFIG_UNOWNED;
globalStore[LOGGING_STATE_KEY] = loggingState;
}));
//#endregion
//#region src/logging/config.ts
function resolveLoggingConfigSelector() {
const env = process.env;
return [
env.OPENCLAW_CONFIG_PATH,
env.OPENCLAW_STATE_DIR,
env.OPENCLAW_HOME,
env.OPENCLAW_PROFILE,
env.HOME,
env.USERPROFILE,
env.HOMEDRIVE,
env.HOMEPATH,
env.PREFIX,
env.ANDROID_DATA,
env.OPENCLAW_TEST_FAST,
tryProcessCwd() ?? ""
].map((value) => value ?? "").join("\0");
}
function resolvePartialDiagnosticLoggingConfig(logging) {
if (!isRecord(logging)) return;
const partial = {};
if (typeof logging.consoleStyle === "string") try {
const resolved = resolveConfigEnvVars({ consoleStyle: logging.consoleStyle });
if (isRecord(resolved) && (resolved.consoleStyle === "pretty" || resolved.consoleStyle === "compact" || resolved.consoleStyle === "json")) partial.consoleStyle = resolved.consoleStyle;
} catch {}
if (Array.isArray(logging.redactPatterns)) try {
const resolved = resolveConfigEnvVars({ redactPatterns: logging.redactPatterns });
if (isRecord(resolved) && Array.isArray(resolved.redactPatterns) && resolved.redactPatterns.every((entry) => typeof entry === "string")) partial.redactPatterns = resolved.redactPatterns;
} catch {}
return Object.keys(partial).length > 0 ? partial : void 0;
}
/** Reads the logging block from config, caching by resolved config path. */
function readLoggingConfig() {
try {
if (loggingState.appliedConfig !== "unowned") return loggingState.appliedConfig;
const selector = resolveLoggingConfigSelector();
if (cachedLoggingConfig?.selector === selector) return cachedLoggingConfig.logging;
const configPath = resolveConfigPath();
if (!fs.existsSync(configPath)) {
cachedLoggingConfig = {
selector,
logging: void 0
};
return;
}
const parsed = parseJsonWithJson5Fallback(fs.readFileSync(configPath, "utf8"));
const allowedRoots = resolveIncludeRoots();
let includedConfig;
try {
includedConfig = resolveConfigIncludesForTopLevelKey(parsed, configPath, "logging", void 0, { allowedRoots });
} catch {
const directLogging = isRecord(parsed) ? parsed.logging : void 0;
if (directLogging === void 0) return;
try {
includedConfig = resolveConfigIncludes({ logging: directLogging }, configPath, void 0, { allowedRoots });
} catch {
return resolvePartialDiagnosticLoggingConfig(directLogging);
}
}
let resolvedConfig;
try {
resolvedConfig = resolveConfigEnvVars(includedConfig);
} catch {
return resolvePartialDiagnosticLoggingConfig(isRecord(includedConfig) ? includedConfig.logging : void 0);
}
const logging = isRecord(resolvedConfig) ? resolvedConfig.logging : void 0;
const resolvedLogging = isRecord(logging) ? logging : void 0;
cachedLoggingConfig = {
selector,
logging: resolvedLogging
};
return resolvedLogging;
} catch {
return;
}
}
var cachedLoggingConfig;
var init_config = __esmMin((() => {
init_record_coerce();
init_env_substitution();
init_includes();
init_paths$1();
init_safe_cwd();
init_parse_json_compat();
init_state();
}));
//#endregion
//#region src/logging/redact-bounded.ts
/** Applies a regex replacement in chunks once input crosses the redaction size threshold. */
function replacePatternBounded(text, pattern, replacer, options) {
const chunkThreshold = options?.chunkThreshold ?? REDACT_REGEX_CHUNK_THRESHOLD;
const chunkSize = options?.chunkSize ?? REDACT_REGEX_CHUNK_SIZE;
if (chunkThreshold <= 0 || chunkSize <= 0 || text.length <= chunkThreshold) return text.replace(pattern, replacer);
let output;
for (let index = 0; index < text.length; index += chunkSize) {
const chunk = text.slice(index, index + chunkSize);
const replaced = chunk.replace(pattern, replacer);
if (output !== void 0) output += replaced;
else if (replaced !== chunk) output = text.slice(0, index) + replaced;
}
return output ?? text;
}
var REDACT_REGEX_CHUNK_THRESHOLD, REDACT_REGEX_CHUNK_SIZE;
var init_redact_bounded = __esmMin((() => {
REDACT_REGEX_CHUNK_THRESHOLD = 32768;
REDACT_REGEX_CHUNK_SIZE = 16384;
}));
//#endregion
//#region src/logging/redact-edit-composition.ts
/** Compose sorted, disjoint current-value edits while retaining original source spans. */
function composeRedactionEdits(length, previous, edits) {
if (previous.length === 0) return edits;
const pieces = [];
let source = 0;
for (const edit of previous) {
if (source < edit.start) pieces.push({
start: source,
end: edit.start
});
pieces.push(edit);
source = edit.end;
}
if (source < length) pieces.push({
start: source,
end: length
});
const output = [];
let index = 0;
let offset = 0;
let position = 0;
const consume = (end, keep) => {
if (end === position) {
const piece = pieces[index];
if (!piece) return {
start: length,
end: length
};
const start = piece.replacement === void 0 ? piece.start + offset : piece.start;
return {
start,
end: piece.replacement !== void 0 && offset > 0 ? piece.end : start
};
}
let sourceStart;
let sourceEnd = 0;
while (position < end) {
const piece = expectDefined(pieces[index], "current redaction piece");
const size = piece.replacement?.length ?? piece.end - piece.start;
const count = Math.min(size - offset, end - position);
const start = piece.replacement === void 0 ? piece.start + offset : piece.start;
const finish = piece.replacement === void 0 ? start + count : piece.end;
sourceStart ??= start;
sourceEnd = finish;
if (keep && count > 0) output.push({
start,
end: finish,
replacement: piece.replacement?.slice(offset, offset + count)
});
position += count;
offset += count;
if (offset === size) {
index += 1;
offset = 0;
}
}
return {
start: sourceStart ?? sourceEnd,
end: sourceEnd
};
};
for (const edit of edits) {
consume(edit.start, true);
output.push({
...consume(edit.end, false),
replacement: edit.replacement
});
}
while (index < pieces.length) {
const piece = expectDefined(pieces[index], "remaining redaction piece");
consume(position + (piece.replacement?.length ?? piece.end - piece.start) - offset, true);
}
const composed = [];
let fragments = [];
let pending;
const flush = () => {
if (pending) {
pending.replacement = fragments.join("");
composed.push(pending);
pending = void 0;
fragments = [];
}
};
for (const piece of output) {
if (piece.replacement === void 0) {
flush();
continue;
}
const sameEmptySpan = pending && pending.start === piece.start && pending.end === piece.end && piece.start === piece.end;
if (!pending || piece.start >= pending.end && !sameEmptySpan) {
flush();
pending = {
start: piece.start,
end: piece.end,
replacement: ""
};
} else pending.end = Math.max(pending.end, piece.end);
fragments.push(piece.replacement);
}
flush();
return composed;
}
/** Project source-span replacements onto a value that already contains replacements. */
function rebaseRedactionEdits(previous, edits) {
let shift = 0;
const spans = previous.map((edit) => {
const start = edit.start + shift;
shift += edit.replacement.length - (edit.end - edit.start);
return {
...edit,
currentStart: start,
currentEnd: edit.end + shift
};
});
const boundary = (position, end) => {
let low = 0;
let high = spans.length;
while (low < high) {
const middle = low + high >>> 1;
const span = expectDefined(spans[middle], "source redaction span");
if (span.end < position || span.end === position && span.start !== span.end) low = middle + 1;
else high = middle;
}
const span = spans[low];
if (span && (position > span.start || position === span.start && span.start === span.end)) return end ? span.currentEnd : span.currentStart;
const before = spans[low - 1];
return position + (before ? before.currentEnd - before.end : 0);
};
return edits.map((edit) => ({
start: boundary(edit.start, false),
end: boundary(edit.end, true),
replacement: edit.replacement
}));
}
function mergeRedactionEdits(edits) {
edits.sort((left, right) => left.start - right.start || left.end - right.end);
const merged = [];
for (const edit of edits) {
const previous = merged.at(-1);
if (!previous || edit.start >= previous.end) merged.push({ ...edit });
else if (edit.start !== previous.start || edit.end !== previous.end || edit.replacement !== previous.replacement) {
previous.end = Math.max(previous.end, edit.end);
previous.replacement = "***";
}
}
return merged;
}
function applyRedactionEdits(value, edits) {
const parts = [];
let cursor = 0;
for (const edit of mergeRedactionEdits(edits)) {
parts.push(value.slice(cursor, edit.start), edit.replacement);
cursor = edit.end;
}
return parts.join("") + value.slice(cursor);
}
var init_redact_edit_composition = __esmMin((() => {
init_src$2();
}));
//#endregion
//#region src/logging/secret-redaction-registry.ts
function invalidateMatcher() {
state$2.registryRevision += 1;
state$2.registeredValueRedactor = void 0;
}
/** Replaces registered exact values while preserving the caller's mask convention. */
function redactRegisteredSecretValues(text, mask) {
if (!text || state$2.registeredValues.size === 0) return text;
state$2.registeredValueRedactor ??= createSecretValueRedactor([...state$2.registeredValues.keys()]);
return state$2.registeredValueRedactor(text, mask);
}
function createSecretValueRedactor(values) {
let compiledMatcher;
let firstChars;
return (text, mask) => {
if (!text || values.length === 0) return text;
let couldMatch = false;
firstChars ??= new Set(values.map((value) => value.charAt(0)));
for (const firstChar of firstChars) if (text.includes(firstChar)) {
couldMatch = true;
break;
}
if (!couldMatch) return text;
if (!compiledMatcher) {
const buckets = /* @__PURE__ */ new Map();
for (const value of values.toSorted((left, right) => right.length - left.length)) {
const prefix = value.slice(0, MIN_SECRET_VALUE_LENGTH);
const bucket = buckets.get(prefix);
if (bucket) bucket.push(value);
else buckets.set(prefix, [value]);
}
compiledMatcher = {
prefixes: new RegExp([...buckets.keys()].map(escapeRegExp).join("|"), "g"),
buckets
};
}
const { prefixes, buckets } = compiledMatcher;
const matches = [];
prefixes.lastIndex = 0;
for (let match = prefixes.exec(text); match; match = prefixes.exec(text)) {
const index = match.index;
const value = buckets.get(match[0])?.find((candidate) => text.startsWith(candidate, index));
if (value !== void 0) matches.push({
index,
value
});
prefixes.lastIndex = index + (value?.length ?? 1);
}
let result = "";
let cursor = 0;
for (const match of matches) {
result += `${text.slice(cursor, match.index)}${mask(match.value, match.index)}`;
cursor = match.index + match.value.length;
}
return result + text.slice(cursor);
};
}
function resetSecretRedactionRegistryForTest() {
state$2.registeredValues.clear();
invalidateMatcher();
}
var MIN_SECRET_VALUE_LENGTH, state$2;
var init_secret_redaction_registry = __esmMin((() => {
init_global_singleton();
init_regexp();
MIN_SECRET_VALUE_LENGTH = 6;
state$2 = resolveGlobalSingleton(Symbol.for("openclaw.secretRedactionRegistry"), () => ({
registeredValues: /* @__PURE__ */ new Map(),
registryRevision: 0,
registeredValueRedactor: void 0
}));
if (process.env.VITEST || false) globalThis[Symbol.for("openclaw.secretRedactionRegistryTestApi")] = { resetSecretRedactionRegistryForTest };
}));
//#endregion
//#region src/logging/redact-internal-state.ts
var init_redact_internal_state = __esmMin((() => {
init_secret_redaction_registry();
}));
//#endregion
//#region src/logging/redact-internal.ts
var init_redact_internal = __esmMin((() => {
init_redact_internal_state();
}));
//#endregion
//#region src/logging/redact-json-tokens.ts
function skipWhitespace(text, start) {
let offset = start;
while (text[offset] === " " || text[offset] === " " || text[offset] === "\r" || text[offset] === "\n") offset += 1;
return offset;
}
function readScalarTokens(text, origins) {
const tokens = [];
const containers = [];
const root = {
key: "",
path: [],
origins,
origin: origins.value,
objectPath: true
};
const valueContext = (parent) => !parent ? root : parent.array ? {
...parent.context,
origin: parent.context.origins?.value ?? parent.context.origin,
origins: parent.context.origins?.children.get(String(parent.nextIndex++))
} : expectDefined(parent.field, "JSON object field context");
for (const match of text.matchAll(JSON_TOKEN_RE)) {
const raw = match[0];
const parent = containers.at(-1);
if (raw === "{" || raw === "[") {
const context = valueContext(parent);
const array = raw === "[";
containers.push({
array,
nextIndex: 0,
context: array ? {
...context,
objectPath: false
} : context,
start: match.index,
tokenStart: tokens.length
});
continue;
}
if (raw === "}" || raw === "]") {
const container = expectDefined(containers.pop(), "JSON container");
if (container.tokenStart === tokens.length) {
const end = match.index + 1;
const value = text.slice(container.start, end);
tokens.push({
...container.context,
isKey: false,
string: false,
value,
start: container.start,
end,
escaped: false,
edits: [],
projectedEdits: [],
currentValue: value,
currentStart: container.start,
currentEnd: end
});
}
continue;
}
const start = match.index;
const end = start + raw.length;
const string = raw.startsWith("\"");
const value = string ? JSON.parse(raw) : raw;
const next = skipWhitespace(text, end);
const isKey = string && text[next] === ":";
let context;
if (isKey) {
const container = expectDefined(parent, "JSON property container");
const inherited = container.context;
context = {
key: "",
path: [],
origin: inherited.origin,
objectPath: false,
rootKey: inherited.rootKey,
rootValueStart: inherited.rootValueStart
};
const valueStart = skipWhitespace(text, next + 1);
container.field = {
key: value,
path: [...inherited.path, value],
origins: inherited.origins?.children.get(value),
origin: inherited.origins?.value ?? inherited.origin,
objectPath: inherited.objectPath,
rootKey: containers.length === 1 ? value : inherited.rootKey,
rootValueStart: containers.length === 1 ? valueStart : inherited.rootValueStart
};
} else context = valueContext(parent);
const origin = isKey ? {
structured: false,
primitiveMask: false
} : context.origins?.value ?? context.origin;
tokens.push({
...context,
origin,
start,
end,
isKey,
string,
value,
escaped: string && raw.includes("\\"),
edits: [],
projectedEdits: [],
currentValue: value,
currentStart: start,
currentEnd: end
});
}
return tokens;
}
function readBatchTokens(input, origins, preserveLines = false) {
const tokens = [];
let offset = 0;
for (const line of input.split("\n")) {
let json = false;
try {
JSON.parse(line);
json = true;
} catch {}
if (json) for (const token of readScalarTokens(line, origins)) {
token.deferEncoding = !token.string;
token.start += offset;
token.end += offset;
token.currentStart += offset;
token.currentEnd += offset;
tokens.push(token);
}
else {
const previous = tokens.at(-1);
if (!preserveLines && previous?.raw && previous.end + 1 === offset) {
previous.value += `\n${line}`;
previous.currentValue = previous.value;
previous.end = previous.currentEnd = offset + line.length;
} else tokens.push({
raw: true,
origin: origins.value,
key: "",
path: [],
objectPath: false,
isKey: false,
string: false,
value: line,
escaped: false,
start: offset,
end: offset + line.length,
currentStart: offset,
currentEnd: offset + line.length,
currentValue: line,
edits: [],
projectedEdits: []
});
}
offset += line.length + 1;
}
return tokens;
}
var JSON_TOKEN_RE;
var init_redact_json_tokens = __esmMin((() => {
init_src$2();
JSON_TOKEN_RE = /"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|[{}[\]]/g;
}));
//#endregion
//#region src/logging/redact-pattern-runtime.ts
function parseRedactPatternSource(raw) {
const literal = raw.match(/^\/(.+)\/([gimsuy]*)$/);
if (!literal) return [raw, "gi"];
const source = literal[1] ?? "";
const flags = literal[2] ?? "";
return [source, flags.includes("g") ? flags : `${flags}g`];
}
function readRedactMatch(args) {
const inputIndex = args.length > 0 && typeof args[args.length - 1] === "object" && args[args.length - 1] !== null ? args.length - 2 : args.length - 1;
const offsetIndex = inputIndex - 1;
const match = typeof args[0] === "string" ? args[0] : "";
const groups = args.slice(1, offsetIndex).map((value) => typeof value === "string" ? value : "");
const offset = typeof args[offsetIndex] === "number" ? args[offsetIndex] : -1;
return {
match,
groups,
input: typeof args[inputIndex] === "string" ? args[inputIndex] : "",
offset
};
}
function getIndexedCaptureStart(pattern, input, match, matchOffset, captureIndex) {
if (!(pattern instanceof RegExp) || matchOffset < 0 || !input) return null;
try {
const flags = pattern.flags.includes("d") ? pattern.flags : `${pattern.flags}d`;
const indexedPattern = new RegExp(pattern.source, flags);
indexedPattern.lastIndex = matchOffset;
const indexedMatch = indexedPattern.exec(input);
const captureIndices = indexedMatch?.indices?.[captureIndex + 1];
if (!indexedMatch || indexedMatch.index !== matchOffset || indexedMatch[0] !== match) return null;
if (!captureIndices) return null;
return captureIndices[0] - matchOffset;
} catch {
return null;
}
}
function hasBackreferenceToGroup(pattern, groupNumber) {
return new RegExp(String.raw`\\${groupNumber}(?!\d)`).test(pattern.source);
}
function selectSecretCapture(match, groups) {
const selected = {
index: -1,
value: match,
captureCount: 0
};
for (let index = 0; index < groups.length; index++) {
const value = groups[index];
if (typeof value === "string" && value.length > 0) {
selected.index = index;
selected.value = value;
selected.captureCount++;
}
}
return selected;
}
function getSecretCaptureStart(pattern, input, match, matchOffset, selected) {
const indexedTokenStart = getIndexedCaptureStart(pattern, input, match, matchOffset, selected.index);
if (indexedTokenStart !== null) return indexedTokenStart;
return pattern instanceof RegExp && selected.captureCount === 1 && selected.index >= 0 && hasBackreferenceToGroup(pattern, selected.index + 1) ? match.indexOf(selected.value) : match.lastIndexOf(selected.value);
}
function* iterateRedactMatches(text, pattern) {
if (!(pattern instanceof RegExp)) {
yield* pattern.exec(text);
return;
}
let regex = pattern;
if (!pattern.global) {
const cached = globalPatterns.get(pattern);
regex = cached ?? new RegExp(pattern.source, `${pattern.flags}g`);
if (!cached) globalPatterns.set(pattern, regex);
}
const unicode = regex.unicode || regex.flags.includes("v");
let cursor = 0;
while (cursor <= text.length) {
const previousIndex = regex.lastIndex;
let match;
try {
regex.lastIndex = cursor;
match = regex.exec(text);
} finally {
regex.lastIndex = previousIndex;
}
if (!match) return;
cursor = match.index + match[0].length;
if (!match[0]) {
const codePoint = text.codePointAt(cursor);
cursor += unicode && codePoint !== void 0 && codePoint > 65535 ? 2 : 1;
}
yield {
match: match[0],
groups: match.slice(1).map((group) => group ?? ""),
input: text,
offset: match.index
};
}
}
function replaceRedactPattern(text, pattern, replace, replaceRegex) {
if (pattern instanceof RegExp) return text.replace(pattern, replaceRegex ?? ((...args) => replace(readRedactMatch(args))));
const parts = [];
let end = 0;
for (const match of iterateRedactMatches(text, pattern)) {
parts.push(text.slice(end, match.offset), replace(match));
end = match.offset + match.match.length;
}
return parts.length ? parts.join("") + text.slice(end) : text;
}
function redactPemBlock(block, marker) {
const lines = block.split(/\r?\n/).filter(Boolean);
if (lines.length < 2) return "***";
return `${lines[0]}\n${marker}\n${lines[lines.length - 1]}`;
}
var globalPatterns;
var init_redact_pattern_runtime = __esmMin((() => {
globalPatterns = /* @__PURE__ */ new WeakMap();
}));
//#endregion
//#region src/logging/redact-json.ts
function getPatternRedactionEdits(value, pattern, getCapture) {
const edits = [];
for (const match of iterateRedactMatches(value, pattern)) {
const capture = getCapture(match, pattern);
const edit = capture?.redact({
start: capture.start,
end: capture.end,
value: value.slice(capture.start, capture.end)
});
if (edit && edit.end >= edit.start) edits.push(edit);
}
return edits;
}
function stringBoundaries(text, start, end) {
const boundaries = /* @__PURE__ */ new Map();
let decoded = 0;
for (let offset = start; offset < end; decoded += 1) {
boundaries.set(offset, decoded);
offset += text[offset] === "\\" ? text[offset + 1] === "u" ? 6 : 2 : 1;
}
boundaries.set(end, decoded);
return boundaries;
}
function decodedBoundary(text, token, offset) {
if (!token.escaped) return offset - token.start - 1;
token.boundaries ??= stringBoundaries(text, token.start + 1, token.end - 1);
return token.boundaries.get(offset);
}
function encodedBoundary(text, token, offset) {
if (!token.escaped) return token.start + 1 + offset;
if (!token.encodedBoundaries) {
token.boundaries ??= stringBoundaries(text, token.start + 1, token.end - 1);
token.encodedBoundaries = [];
for (const [encoded, decoded] of token.boundaries) token.encodedBoundaries[decoded] = encoded;
}
return expectDefined(token.encodedBoundaries[offset], "decoded JSON edit boundary");
}
function projectMessageEdits(input, tokens, message, getEdits) {
const parts = new Map(message.parts.map((part) => [part.key, part]));
const projected = [];
for (const token of tokens) {
if (!token.isKey && token.path.length === 1 && token.key === "message") continue;
const part = token.rootKey === void 0 ? void 0 : parts.get(token.rootKey);
if (!part) continue;
if (!part.json && (token.isKey || (part.messageField ? token.path.length !== 2 || token.key !== "message" : token.path.length !== 1))) continue;
const edits = getEdits(token);
for (const edit of edits) {
let start;
let end;
let replacement = edit.replacement;
if (part.json) {
const base = part.start - expectDefined(token.rootValueStart, "displayed JSON argument");
if (token.string) {
start = base + encodedBoundary(input, token, edit.start);
end = base + encodedBoundary(input, token, edit.end);
replacement = JSON.stringify(replacement).slice(1, -1);
} else {
start = base + token.start;
end = base + token.end;
replacement = JSON.stringify(replacement);
}
} else {
start = part.start + edit.start;
end = part.start + (part.primitiveLength ?? edit.end);
}
if (start < message.contentLength) projected.push({
start,
end: Math.min(end, message.contentLength),
replacement,
scalar: part.json && !token.string
});
}
}
return projected.toSorted((left, right) => left.start - right.start || left.end - right.end);
}
function firstIntersectingToken(tokens, start) {
let low = 0;
let high = tokens.length;
while (low < high) {
const middle = low + high >>> 1;
if (expectDefined(tokens[middle], "bounded JSON token search").currentEnd <= start) low = middle + 1;
else high = middle;
}
return low;
}
function updateCurrentToken(input, token) {
if (token.raw || token.deferEncoding) {
token.currentRaw = token.currentValue;
return;
}
const parts = [];
const encodedEdits = [];
let cursor = token.start + (token.string ? 1 : 0);
let encodedLength = 0;
let decodedShift = 0;
for (const edit of token.edits) {
const start = token.string ? encodedBoundary(input, token, edit.start) : token.start + edit.start;
const end = token.string ? encodedBoundary(input, token, edit.end) : token.start + edit.end;
const replacement = JSON.stringify(edit.replacement).slice(1, -1);
const encodedStart = encodedLength + start - cursor;
const encodedEnd = encodedStart + replacement.length;
encodedEdits.push({
start: encodedStart,
end: encodedEnd,
decodedStart: edit.start + decodedShift,
decodedEnd: edit.start + decodedShift + edit.replacement.length,
sourceEnd: end,
sourceDecodedEnd: edit.end,
replacement
});
parts.push(input.slice(cursor, start), replacement);
encodedLength = encodedEnd;
decodedShift += edit.replacement.length - (edit.end - edit.start);
cursor = end;
}
parts.push(input.slice(cursor, token.end - (token.string ? 1 : 0)));
token.currentRaw = `"${parts.join("")}"`;
token.encodedEdits = encodedEdits;
}
function currentDecodedBoundary(input, token, position, replacements) {
const offset = position - token.currentStart - 1;
const edits = token.encodedEdits;
if (!edits) return decodedBoundary(input, token, token.start + 1 + offset);
let low = 0;
let high = edits.length;
while (low < high) {
const middle = low + high >>> 1;
if (expectDefined(edits[middle], "current encoded edit").end < offset) low = middle + 1;
else high = middle;
}
const edit = edits[low];
if (edit && offset >= edit.start) {
const within = offset - edit.start;
if (!edit.replacement.includes("\\")) return edit.decodedStart + within;
let boundaries = replacements.get(edit.replacement);
if (!boundaries) {
boundaries = stringBoundaries(edit.replacement, 0, edit.replacement.length);
replacements.set(edit.replacement, boundaries);
}
const decoded = boundaries.get(within);
return decoded === void 0 ? void 0 : edit.decodedStart + decoded;
}
const previous = edits[low - 1];
const decoded = decodedBoundary(input, token, offset + (previous ? previous.sourceEnd - previous.end : token.start + 1));
return decoded === void 0 ? void 0 : decoded + (previous ? previous.decodedEnd - previous.sourceDecodedEnd : 0);
}
function commitPatternEdits(token) {
const pending = token.pending;
token.pending = void 0;
if (!pending) return false;
const edits = mergeRedactionEdits(pending);
const value = applyRedactionEdits(token.currentValue, edits);
if (value === token.currentValue) return false;
token.edits = composeRedactionEdits(token.value.length, token.edits, edits);
token.currentValue = value;
return true;
}
function changedRedactionEdits(previous, current) {
let index = 0;
return current.filter((edit) => {
while (previous[index] && expectDefined(previous[index], "previous configured edit").start < edit.start) index += 1;
const before = previous[index];
return !before || before.start !== edit.start || before.end !== edit.end || before.replacement !== edit.replacement;
});
}
function commitOriginalEdits(token, edits) {
if (edits.length === 0) return false;
const combined = mergeRedactionEdits([...token.edits, ...edits]);
const value = applyRedactionEdits(token.value, combined);
if (value === token.currentValue) return false;
token.edits = combined;
token.currentValue = value;
return true;
}
function updateCurrentRecord(input, current, tokens, changed) {
const parts = [];
let cursor = 0;
let shift = 0;
for (const token of tokens) {
const start = token.currentStart;
const end = token.currentEnd;
if (changed.has(token)) {
updateCurrentToken(input, token);
const raw = expectDefined(token.currentRaw, "changed JSON token");
parts.push(current.slice(cursor, start), raw);
cursor = end;
token.currentStart = start + shift;
shift += raw.length - (end - start);
} else token.currentStart = start + shift;
token.currentEnd = end + shift;
}
parts.push(current.slice(cursor));
return parts.join("");
}
function projectedStringEnd(input, tokens, message, token, start, end) {
const jsonParts = new Set(message.parts.filter((part) => part.json).map((part) => part.key));
const spans = projectMessageEdits(input, tokens, message, (source) => source.string && !source.isKey && source.rootKey !== void 0 && jsonParts.has(source.rootKey) ? [{
start: 0,
end: source.value.length,
replacement: ""
}] : []).filter((span) => span.end < message.contentLength);
const containing = rebaseRedactionEdits(token.edits, spans).filter((span) => span.start <= start && start < span.end && end <= span.end);
return containing.length === 1 ? expectDefined(containing[0], "displayed source string").end : token.currentValue.length;
}
function redactJsonRecord(input, origins, patternPhases, getCapture, legacyFieldEdits, fieldEdits, prepEdits, skipDecodedPatterns, message, batch) {
let tokens = batch ? [] : readScalarTokens(input, origins);
const messageToken = message ? tokens.find((token) => !token.isKey && token.path.length === 1 && token.key === "message") : void 0;
const replacementBoundaries = /* @__PURE__ */ new Map();
let projectedMessageEdits = [];
let projectedMessageValue = messageToken?.value ?? "";
let current = input;
const prepared = /* @__PURE__ */ new Set();
for (const token of tokens) if (commitOriginalEdits(token, prepEdits(token))) prepared.add(token);
if (prepared.size > 0) current = updateCurrentRecord(input, current, tokens, prepared);
const decodedTokens = tokens.filter((token) => !token.isKey && token.string && !skipDecodedPatterns(token, token.currentValue));
const projectMessage = () => {
if (!messageToken || !message) return false;
const projected = projectMessageEdits(input, tokens, message, (token) => {
const edits = changedRedactionEdits(token.projectedEdits, token.edits);
token.projectedEdits = token.edits;
return edits;
});
if (projected.length === 0) return false;
const sourceEdits = rebaseRedactionEdits(projectedMessageEdits, projected);
const messageEdits = rebaseRedactionEdits(messageToken.edits, projected);
let generatedIndex = 0;
for (let index = 0; index < messageEdits.length; index += 1) {
const edit = expectDefined(messageEdits[index], "projected message edit");
const sourceEdit = expectDefined(sourceEdits[index], "projected source edit");
const projection = expectDefined(projected[index], "source projection");
while (messageToken.edits[generatedIndex] && expectDefined(messageToken.edits[generatedIndex], "generated message span").start < projection.start) generatedIndex += 1;
const generated = messageToken.edits[generatedIndex];
const scalarPromotion = projection.scalar && generated?.start === projection.start && generated.end === projection.end && edit.replacement === JSON.stringify(generated.replacement);
const before = messageToken.currentValue.slice(edit.start, edit.end);
if (!scalarPromotion && before !== edit.replacement && before !== projectedMessageValue.slice(sourceEdit.start, sourceEdit.end)) edit.replacement = projection.scalar ? JSON.stringify("***") : "***";
}
messageToken.pending = messageEdits;
projectedMessageValue = applyRedactionEdits(projectedMessageValue, sourceEdits);
projectedMessageEdits = composeRedactionEdits(messageToken.value.length, projectedMessageEdits, sourceEdits);
return commitPatternEdits(messageToken);
};
for (const [phase, groups] of patternPhases.entries()) {
const changed = /* @__PURE__ */ new Set();
const pending = /* @__PURE__ */ new Set();
const add = (token, edit) => {
(token.pending ??= []).push(edit);
pending.add(token);
};
for (const group of groups) {
if (group.couldMatch && !group.couldMatch(current)) continue;
for (const pattern of group.patterns) {
if (phase === 0) for (const token of decodedTokens) for (const edit of getPatternRedactionEdits(token.currentValue, pattern, getCapture)) add(token, edit);
else for (const match of iterateRedactMatches(current, pattern)) {
const capture = getCapture(match, pattern);
if (!capture || capture.end < capture.start) continue;
if (batch && tokens.length === 0) tokens = readBatchTokens(input, origins, batch.preserveLines);
for (let index = firstIntersectingToken(tokens, capture.start); index < tokens.length; index += 1) {
const token = expectDefined(tokens[index], "serialized capture token");
if (token.currentStart >= capture.end) break;
const unquoted = token.raw || token.deferEncoding;
const padding = unquoted ? 0 : 1;
const captureInsideToken = capture.start >= token.currentStart + padding && capture.end <= token.currentEnd - padding;
if (batch && token.isKey && !captureInsideToken) continue;
const value = token.currentValue;
if (!token.raw && !token.string && token.edits.length === 0) {
add(token, {
start: 0,
end: value.length,
replacement: "***"
});
continue;
}
let startPosition = Math.max(capture.start, token.currentStart + padding);
let start = unquoted ? startPosition - token.currentStart : currentDecodedBoundary(input, token, startPosition, replacementBoundaries);
let endPosition = Math.min(capture.end, token.currentEnd - padding);
let end = unquoted ? endPosition - token.currentStart : currentDecodedBoundary(input, token, endPosition, replacementBoundaries);
if (start === void 0 || end === void 0) {
while (start === void 0) start = currentDecodedBoundary(input, token, --startPosition, replacementBoundaries);
while (end === void 0) end = currentDecodedBoundary(input, token, ++endPosition, replacementBoundaries);
const maskEnd = token === messageToken && message ? projectedStringEnd(input, tokens, message, token, start, end) : value.length;
add(token, {
start,
end: maskEnd,
replacement: "***"
});
continue;
}
if (end < start || batch && end === start) continue;
const { start: captureStart, end: captureEnd } = capture;
const edit = capture.redact({
start,
end,
value: current.slice(Math.max(captureStart, token.currentStart + padding), Math.min(captureEnd, token.currentEnd - padding))
});
if (!edit) continue;
let replacement = "***";
if (captureInsideToken) try {
replacement = unquoted ? edit.replacement : JSON.parse(`"${edit.replacement}"`);
} catch {}
add(token, {
...edit,
replacement
});
}
}
if (pending.size === 0) continue;
for (const token of pending) if (!commitPatternEdits(token)) pending.delete(token);
else if (phase === 0) changed.add(token);
if (phase !== 0 && pending.size > 0) current = updateCurrentRecord(input, current, tokens, pending);
pending.clear();
}
}
for (const token of tokens) if (phase === 0) {
token.pending = legacyFieldEdits(token, token.currentValue);
if (commitPatternEdits(token)) changed.add(token);
} else if (commitOriginalEdits(token, fieldEdits(token))) changed.add(token);
if ((phase !== 0 || prepared.size > 0 || changed.size > 0) && projectMessage() && messageToken) changed.add(messageToken);
if (changed.size > 0) current = updateCurrentRecord(input, current, tokens, changed);
}
if (messageToken && message) {
const finished = message.finish(messageToken.currentValue);
if (finished !== messageToken.currentValue) return applyRedactionEdits(current, [{
start: messageToken.currentStart,
end: messageToken.currentEnd,
replacement: JSON.stringify(finished)
}]);
}
return applyRedactionEdits(current, tokens.flatMap((token) => token.deferEncoding && token.edits.length > 0 ? [{
start: token.currentStart,
end: token.currentEnd,
replacement: JSON.stringify(token.currentValue)
}] : []));
}
var init_redact_json = __esmMin((() => {
init_src$2();
init_redact_edit_composition();
init_redact_json_tokens();
init_redact_pattern_runtime();
}));
//#endregion
//#region src/logging/redact-pem.ts
function createState() {
return {
scanner: {
offset: 0,
phase: "search",
dashes: 0,
keyword: "BEGIN ",
keywordOffset: 0,
start: 0,
suffix: ""
},
matchEnd: 0
};
}
function resetScanner(scanner, char) {
scanner.phase = "search";
scanner.dashes = char === "-" ? 1 : 0;
scanner.suffix = "";
}
function* readDelimiters(text, scanner) {
for (let index = 0; index < text.length; index += 1) {
if (scanner.phase === "search" && scanner.dashes === 0) {
const nextDash = text.indexOf("-", index);
if (nextDash === -1) {
scanner.offset += text.length - index;
return;
}
scanner.offset += nextDash - index;
index = nextDash;
}
const code = text.charCodeAt(index);
const char = code >= 97 && code <= 122 ? String.fromCharCode(code - 32) : text.charAt(index);
const offset = scanner.offset++;
switch (scanner.phase) {
case "search":
if (char === "-") scanner.dashes = Math.min(5, scanner.dashes + 1);
else if (scanner.dashes === 5 && (char === "B" || char === "E")) {
scanner.phase = "keyword";
scanner.keyword = char === "B" ? "BEGIN " : "END ";
scanner.keywordOffset = 1;
scanner.start = offset - 5;
} else scanner.dashes = 0;
break;
case "keyword":
if (char !== scanner.keyword.charAt(scanner.keywordOffset)) resetScanner(scanner, char);
else if (++scanner.keywordOffset === scanner.keyword.length) {
scanner.phase = "label";
scanner.suffix = "";
}
break;
case "label":
if (char >= "A" && char <= "Z" || char === " ") scanner.suffix = (scanner.suffix + char).slice(-11);
else if (char === "-" && scanner.suffix === "PRIVATE KEY") {
scanner.phase = "close";
scanner.dashes = 1;
} else resetScanner(scanner, char);
break;
case "close": if (char !== "-") resetScanner(scanner, char);
else if (++scanner.dashes === 5) {
scanner.phase = "search";
scanner.suffix = "";
yield {
kind: scanner.keyword === "BEGIN " ? "begin" : "end",
start: scanner.start,
end: offset + 1
};
}
}
}
}
function consumeDelimiter(state, delimiter) {
if (!state.open) {
if (delimiter.kind === "begin" && delimiter.start >= state.matchEnd) state.open = {
start: delimiter.start,
end: delimiter.end
};
return;
}
if (delimiter.kind !== "end" || delimiter.start <= state.open.end) return;
const block = {
start: state.open.start,
end: delimiter.end,
bodyStart: state.open.end,
bodyEnd: delimiter.start
};
state.open = void 0;
state.matchEnd = delimiter.end;
return block;
}
function* matchPem(text, context, incomplete) {
const state = {
...context,
scanner: { ...context.scanner },
open: context.open && { ...context.open }
};
const origin = state.scanner.offset;
for (const delimiter of readDelimiters(text, state.scanner)) {
const block = consumeDelimiter(state, delimiter);
if (!block) continue;
const start = Math.max(0, (incomplete ? block.bodyStart : block.start) - origin);
const end = (incomplete ? block.bodyEnd : block.end) - origin;
if (end <= start) continue;
yield {
match: text.slice(start, end),
groups: [],
input: text,
offset: start,
...incomplete ? { replacement: "…redacted…" } : {}
};
}
if (incomplete && state.open) {
const start = Math.max(0, state.open.end - origin);
if (start < text.length) yield {
match: text.slice(start),
groups: [],
input: text,
offset: start,
replacement: "…redacted…"
};
}
}
var PEM_REDACT_PATTERN_SOURCE, PEM_REDACT_MATCHER;
var init_redact_pem = __esmMin((() => {
PEM_REDACT_PATTERN_SOURCE = String.raw`-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]+?-----END [A-Z ]*PRIVATE KEY-----`;
PEM_REDACT_MATCHER = {
source: PEM_REDACT_PATTERN_SOURCE,
exec(text) {
return matchPem(text, createState(), false);
},
createContext() {
let whenClosed = false;
let whenOpen = true;
return {
prepend() {
const closed = createState();
const open = createState();
open.open = {
start: -1,
end: -1
};
return {
consume(text) {
for (const delimiter of readDelimiters(text, closed.scanner)) {
consumeDelimiter(closed, delimiter);
consumeDelimiter(open, delimiter);
}
},
finish() {
const nextClosed = closed.open ? whenOpen : whenClosed;
const nextOpen = open.open ? whenOpen : whenClosed;
whenClosed = nextClosed;
whenOpen = nextOpen;
return whenClosed === whenOpen;
}
};
},
pattern: {
source: PEM_REDACT_PATTERN_SOURCE,
exec(text) {
const state = createState();
if (whenClosed) state.open = {
start: -1,
end: -1
};
return matchPem(text, state, true);
}
}
};
}
};
}));
//#endregion
//#region src/logging/redact-patterns.ts
function isAwsValueCharacter(char) {
const code = char.charCodeAt(0);
return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || char === "/" || char === "+" || char === "=";
}
function couldMatchAwsSecretAccessKey(text) {
return text.length >= 40 && AWS_SECRET_ACCESS_KEY_RUN_RE.test(text) && AWS_SECRET_ACCESS_KEY_VALUE_RE.test(text);
}
function* matchAwsSecretAccessKeys(text) {
if (!couldMatchAwsSecretAccessKey(text)) return;
const closingDelimiters = {
"\"": "\"",
"'": "'",
"`": "`",
"<": ">",
"(": ")",
"[": "]",
"{": "}"
};
let runStart = -1;
let schemeStart = -1;
let url;
let backslashes = 0;
const runs = [];
for (let index = 0; index <= text.length; index++) {
const char = text[index] ?? "";
const whitespace = index === text.length || AWS_VALUE_WHITESPACE_RE.test(char);
const escapeDepth = backslashes;
backslashes = char === "\\" ? backslashes + 1 : 0;
if (char && isAwsValueCharacter(char)) {
if (runStart === -1) runStart = index;
} else if (runStart !== -1) {
if (index - runStart === 40) runs.push({
start: runStart,
end: index,
origin: runStart,
url
});
else if (index - runStart > 40 && char === "@" && text[index - 41] === "/") runs.push({
start: index - 40,
end: index,
origin: runStart,
url
});
runStart = -1;
}
if (whitespace) {
if (url) url.end = Math.min(url.end, index);
for (const run of runs) {
const context = run.url;
const publicUrl = context && !context.hasAt && context.portValid && (context.portStart === -1 || (context.authorityEnd === -1 ? context.end : context.authorityEnd) > context.portStart + 1);
const before = text[run.start - 1] ?? "";
const after = text[run.end] ?? "";
const slashCredential = run.start !== run.origin;
const portCredential = context && context.portStart !== -1 && run.origin === context.portStart + 1 && context.authorityEnd > run.origin && run.end > context.authorityEnd && after === "@";
if (!slashCredential && (before === "_" || isAwsValueCharacter(before)) || after === "_" || text.slice(run.origin - 8, run.origin) === ";base64," || publicUrl && !portCredential && run.start >= context.start && run.end <= context.end) continue;
const match = text.slice(run.start, run.end);
if (AWS_SECRET_ACCESS_KEY_VALUE_RE.test(match)) yield {
match,
groups: [match],
input: text,
offset: run.start
};
}
runs.length = 0;
schemeStart = -1;
url = void 0;
continue;
}
if (url && index >= url.start) {
if (char === url.closing && escapeDepth === url.closingEscapeDepth) {
url.end = Math.min(url.end, index);
url = void 0;
} else {
if ("?#\"'<>`|()[]{}".includes(char)) url.end = Math.min(url.end, index);
url.queryOrFragment ||= char === "?" || char === "#";
if (url.authorityEnd === -1) {
url.hasAt ||= char === "@";
if ("/?#".includes(char)) url.authorityEnd = index;
else if (index < url.end) {
if (char === ":") {
url.portValid &&= url.portStart === -1;
url.portStart = index;
} else if (url.portStart !== -1 && (char < "0" || char > "9")) url.portValid = false;
}
}
}
}
if (AWS_URL_SCHEME_CHARACTER_RE.test(char)) {
if (schemeStart === -1) schemeStart = index;
} else {
if ((!url || index >= url.end && !url.queryOrFragment) && char === ":" && text.startsWith("//", index + 1) && schemeStart !== -1 && AWS_URL_SCHEME_START_RE.test(text[schemeStart])) {
const opening = text[schemeStart - 1];
let closingEscapeDepth = 0;
for (let offset = schemeStart - 2; offset >= 0 && text[offset] === "\\"; offset--) closingEscapeDepth++;
url = {
start: index + 3,
end: text.length,
authorityEnd: -1,
portStart: -1,
portValid: true,
hasAt: false,
queryOrFragment: false,
closing: opening ? closingDelimiters[opening] : void 0,
closingEscapeDepth
};
}
schemeStart = -1;
}
}
}
var PAYMENT_CREDENTIAL_ENV_KEYS, PAYMENT_CREDENTIAL_QUERY_KEYS, PAYMENT_CREDENTIAL_JSON_KEYS, AWS_SECRET_ACCESS_KEY_FIELD_KEYS, AUTH_QUERY_KEYS, FORM_BODY_FIRST_PAIR_KEYS, STANDALONE_ASSIGNMENT_SECRET_KEYS, CONFIG_ASSIGNMENT_SECRET_KEYS, CONFIG_DIRECT_ASSIGNMENT_SECRET_KEYS, CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_SECRET_KEYS, CLI_SECRET_FLAG_KEYS, BODY_SECRET_KEYS, FORM_BODY_KEY_INVISIBLE_CHARS, ENV_ASSIGNMENT_REDACT_PATTERN, ESCAPED_ENV_ASSIGNMENT_REDACT_PATTERN, STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN, STANDALONE_ASSIGNMENT_REDACT_PATTERN, CONFIG_QUOTED_ASSIGNMENT_SECRET_KEYS, CONFIG_QUOTED_ASSIGNMENT_REDACT_PATTERN, CONFIG_ASSIGNMENT_REDACT_PATTERN, CONFIG_DIRECT_ASSIGNMENT_REDACT_PATTERN, CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_REDACT_PATTERN, CONFIG_NAMESPACED_ASSIGNMENT_REDACT_PATTERN, STRUCTURED_JSON_SECRET_REDACT_PATTERN, STRUCTURED_JSON_PAYMENT_REDACT_PATTERN, AMBIGUOUS_QUOTED_SECRET_FIELD_REDACT_PATTERN, AMBIGUOUS_QUOTED_AUTH_FIELD_REDACT_PATTERN, BASE64_SAFE_TOKEN_BOUNDARY, IDENTIFIER_SAFE_TOKEN_BOUNDARY, AWS_SECRET_ACCESS_KEY_VALUE_RE, AWS_SECRET_ACCESS_KEY_RUN_RE, AWS_VALUE_WHITESPACE_RE, AWS_URL_SCHEME_CHARACTER_RE, AWS_URL_SCHEME_START_RE, AWS_SECRET_ACCESS_KEY_MATCHER, TELEGRAM_BOT_TOKEN_REDACT_PATTERN, TELEGRAM_TOKEN_REDACT_PATTERN, CREDENTIAL_STYLE_HEADER_KEYS, GATEWAY_SECURITY_HEADER_KEYS, CREDENTIAL_HEADER_FIELD_RE, LOG_HEADER_BOUNDARY_PATTERN, CREDENTIAL_STYLE_COLON_HEADER_REDACT_PATTERN, CREDENTIAL_STYLE_EQUALS_ASSIGNMENT_REDACT_PATTERN, GATEWAY_SECURITY_COLON_HEADER_REDACT_PATTERN, GATEWAY_SECURITY_EQUALS_ASSIGNMENT_REDACT_PATTERN, FORM_AWARE_EQUALS_ASSIGNMENT_PATTERN_SOURCES, HTTP_AUTH_HEADER_REDACT_PATTERNS, AUTHORIZATION_BEARER_REDACT_PATTERN, AUTHORIZATION_BASIC_REDACT_PATTERN, AUTHORIZATION_BOT_REDACT_PATTERN, STANDALONE_BEARER_REDACT_PATTERN, SHELL_REFERENCE_PRESERVING_PATTERN_SOURCES, CHUNK_UNSAFE_PATTERN_SOURCES, DEFAULT_REDACT_FIELD_PATTERNS, VENDOR_TOKEN_REDACT_PATTERNS, DEFAULT_REDACT_STRING_PATTERNS, DEFAULT_REDACT_PATTERNS, TOOL_PAYLOAD_AMBIGUOUS_ASSIGNMENT_PATTERNS, TOOL_PAYLOAD_REDACT_PATTERNS;
var init_redact_patterns = __esmMin((() => {
init_structured_auth_redaction();
init_redact_pem();
PAYMENT_CREDENTIAL_ENV_KEYS = String.raw`CARD[_-]?NUMBER|CARD[_-]?CVC|CARD[_-]?CVV|CVC|CVV|SECURITY[_-]?CODE|PAYMENT[_-]?CREDENTIAL|SHARED[_-]?PAYMENT[_-]?TOKEN`;
PAYMENT_CREDENTIAL_QUERY_KEYS = String.raw`card[-_]?number|card[-_]?cvc|card[-_]?cvv|cvc|cvv|security[-_]?code|payment[-_]?credential|shared[-_]?payment[-_]?token`;
PAYMENT_CREDENTIAL_JSON_KEYS = String.raw`cardNumber|card_number|cardCvc|card_cvc|cardCvv|card_cvv|cvc|cvv|securityCode|security_code|paymentCredential|payment_credential|sharedPaymentToken|shared_payment_token`;
AWS_SECRET_ACCESS_KEY_FIELD_KEYS = String.raw`aws[-_]?secret[-_]?access[-_]?key|awsSecretAccessKey|SecretAccessKey`;
AUTH_QUERY_KEYS = String.raw`access[-_]?token|auth[-_]?token|hook[-_]?token|refresh[-_]?token|id[-_]?token|api[-_]?key|apikey|client[-_]?secret|app[-_]?secret|private[-_]?key|${AWS_SECRET_ACCESS_KEY_FIELD_KEYS}|credential|authorization|token|key|secret|password|pass|passwd|auth|jwt|session|code|signature|x[-_]?amz[-_]?(?:signature|security[-_]?token)`;
FORM_BODY_FIRST_PAIR_KEYS = String.raw`${AUTH_QUERY_KEYS}|app[-_]?secret|credential|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
STANDALONE_ASSIGNMENT_SECRET_KEYS = String.raw`access_token|refresh_token|id_token|auth[-_]?token|hook[-_]?token|api[-_]?key|client[-_]?secret|app[-_]?secret|private[-_]?key|authorization|jwt|token|secret|password|pass|passwd|credential|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
CONFIG_ASSIGNMENT_SECRET_KEYS = String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|client[-_]?secret|app[-_]?secret|private[-_]?key|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|pass|passwd|credential|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
CONFIG_DIRECT_ASSIGNMENT_SECRET_KEYS = String.raw`access-token|refresh-token|id-token|auth-token|hook-token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|passphrase`;
CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_SECRET_KEYS = String.raw`password|passphrase|pass|passwd`;
CLI_SECRET_FLAG_KEYS = String.raw`${AWS_SECRET_ACCESS_KEY_FIELD_KEYS}|api[-_]?key|hook[-_]?token|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|password|passwd|credential|private[-_]?key|client[-_]?secret|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
BODY_SECRET_KEYS = /* @__PURE__ */ new Set([
"access_token",
"auth_token",
"awssecretaccesskey",
"aws_secret_access_key",
"hook_token",
"refresh_token",
"id_token",
"token",
"api_key",
"apikey",
"client_secret",
"app_secret",
"password",
"pass",
"passwd",
"auth",
"jwt",
"session",
"code",
"signature",
"x_amz_signature",
"x_amz_security_token",
"secret",
"secretaccesskey",
"credential",
"private_key",
"authorization",
"key",
"card_number",
"card_cvc",
"card_cvv",
"cvc",
"cvv",
"security_code",
"payment_credential",
"shared_payment_token"
]);
FORM_BODY_KEY_INVISIBLE_CHARS = String.raw`\p{C}\u00A0\u1680\u2000-\u200A\u202F\u205F\u3000\u115F\u1160\u3164\uFFA0`;
ENV_ASSIGNMENT_REDACT_PATTERN = String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${PAYMENT_CREDENTIAL_ENV_KEYS})\b\s*[=:]\s*(["']?)([^\s"'\\]+)\1/g`;
ESCAPED_ENV_ASSIGNMENT_REDACT_PATTERN = String.raw`/\b[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|${PAYMENT_CREDENTIAL_ENV_KEYS})\b\s*[=:]\s*\\+(["'])([^\s"'\\]+)\\+\1/g`;
STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN = String.raw`(^|[\s,;({\["])(?:${STANDALONE_ASSIGNMENT_SECRET_KEYS})=(["'\x60])((?:(?!\2)[^\r\n])+)\2`;
STANDALONE_ASSIGNMENT_REDACT_PATTERN = String.raw`(^|[\s,;({\["])(?:${STANDALONE_ASSIGNMENT_SECRET_KEYS})=(["'\x60]?[^\s&#"'\x60<>]+)`;
CONFIG_QUOTED_ASSIGNMENT_SECRET_KEYS = String.raw`access[-_]?token|refresh[-_]?token|id[-_]?token|auth[-_]?token|hook[-_]?token|api[-_]?(?:key|secret)|secret[-_]?key|key[-_]?material|authorization|jwt|token|secret|password|passphrase|pass|passwd|${PAYMENT_CREDENTIAL_QUERY_KEYS}`;
CONFIG_QUOTED_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])(?:(?:${CONFIG_QUOTED_ASSIGNMENT_SECRET_KEYS})(?:\s*:\s*|\s+=\s*|=\s*)|[a-z0-9][a-z0-9._-]{0,79}[-_](?:${CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*|[a-z0-9_.-]{1,80}\.(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*)(["'\x60])((?:(?!\2)[^\r\n])+)\2/g`;
CONFIG_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})(?:\s*:\s*|\s+=\s*|=\s+)([^\s#"'\x60<>]+)/g`;
CONFIG_DIRECT_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])(?:${CONFIG_DIRECT_ASSIGNMENT_SECRET_KEYS})=([^\s#"'\x60<>]+)/g`;
CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])[a-z0-9][a-z0-9._-]{0,79}[-_](?:${CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*([^\s#"'\x60<>]+)/g`;
CONFIG_NAMESPACED_ASSIGNMENT_REDACT_PATTERN = String.raw`/(^|[\s,{])[a-z0-9_.-]{1,80}\.(?:${CONFIG_ASSIGNMENT_SECRET_KEYS})\s*[:=]\s*([^\s#"'\x60<>]+)/g`;
STRUCTURED_JSON_SECRET_REDACT_PATTERN = String.raw`"(?:apiKey|api_key|apiToken|api_token|bearerToken|bearer_token|token|secret|password|passwd|${AWS_SECRET_ACCESS_KEY_FIELD_KEYS}|credential|authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token|accessToken|access_token|refreshToken|refresh_token|idToken|id_token|authToken|auth_token|clientSecret|client_secret|privateKey|private_key|secret_value|raw_secret|secret_input|key_material)"\s*:\s*"([^"]+)"`;
STRUCTURED_JSON_PAYMENT_REDACT_PATTERN = String.raw`"(?:${PAYMENT_CREDENTIAL_JSON_KEYS})"\s*:\s*"([^"]+)"`;
AMBIGUOUS_QUOTED_SECRET_FIELD_REDACT_PATTERN = String.raw`(^|[\s,{])["']?(?:api[-_]key|access[-_]token|refresh[-_]token|id[-_]token|authToken|auth[-_]token|clientSecret|client[-_]secret|appSecret|app[-_]secret|private[-_]key|credential|authorization|secret[-_]value|raw[-_]secret|secret[-_]input|key[-_]material)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`;
AMBIGUOUS_QUOTED_AUTH_FIELD_REDACT_PATTERN = String.raw`(^|[\s,{])["']?(?:authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token)["']?\s*[:=]\s*(["'])([^"'\r\n]+)\2`;
BASE64_SAFE_TOKEN_BOUNDARY = String.raw`(^|[^A-Za-z0-9])(?<!;base64,[A-Za-z0-9+/=]*)`;
IDENTIFIER_SAFE_TOKEN_BOUNDARY = String.raw`(^|[^A-Za-z0-9_])`;
AWS_SECRET_ACCESS_KEY_VALUE_RE = /(?=[A-Za-z0-9/+=]{0,39}[A-Z])(?=[A-Za-z0-9/+=]{0,39}[a-z])(?=[A-Za-z0-9/+=]{0,39}[0-9/+=])(?=[A-Za-z0-9/+=]{0,39}[G-Zg-z/+=])[A-Za-z0-9/+=]{40}/u;
AWS_SECRET_ACCESS_KEY_RUN_RE = /[A-Za-z0-9/+=]{40}/u;
AWS_VALUE_WHITESPACE_RE = /\s/;
AWS_URL_SCHEME_CHARACTER_RE = /[A-Za-z0-9+.-]/;
AWS_URL_SCHEME_START_RE = /[A-Za-z]/;
AWS_SECRET_ACCESS_KEY_MATCHER = Object.freeze({
source: "aws-secret-access-key",
exec: matchAwsSecretAccessKeys,
couldMatch: couldMatchAwsSecretAccessKey
});
TELEGRAM_BOT_TOKEN_REDACT_PATTERN = String.raw`\bbot(\d{6,}:[A-Za-z0-9_-]{20,})\b`;
TELEGRAM_TOKEN_REDACT_PATTERN = String.raw`\b(\d{6,}:[A-Za-z0-9_-]{20,})\b`;
CREDENTIAL_STYLE_HEADER_KEYS = "x-goog-api-key|api-key|apikey|x-api-token|x-access-token";
GATEWAY_SECURITY_HEADER_KEYS = "X-OpenClaw-Token|x-pomerium-jwt-assertion|X-Api-Key|X-Auth-Token";
CREDENTIAL_HEADER_FIELD_RE = new RegExp(`^(?:${CREDENTIAL_STYLE_HEADER_KEYS}|${GATEWAY_SECURITY_HEADER_KEYS})$`, "i");
LOG_HEADER_BOUNDARY_PATTERN = String.raw`(^|[^A-Za-z0-9_?&-]|\\{1,64}[rn])`;
CREDENTIAL_STYLE_COLON_HEADER_REDACT_PATTERN = String.raw`${LOG_HEADER_BOUNDARY_PATTERN}(?:${CREDENTIAL_STYLE_HEADER_KEYS})${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*:${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}([^\s\\"',;]+)`;
CREDENTIAL_STYLE_EQUALS_ASSIGNMENT_REDACT_PATTERN = String.raw`${LOG_HEADER_BOUNDARY_PATTERN}(?:${CREDENTIAL_STYLE_HEADER_KEYS})${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*=${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}([^\s\\"',;]+)`;
GATEWAY_SECURITY_COLON_HEADER_REDACT_PATTERN = String.raw`${LOG_HEADER_BOUNDARY_PATTERN}(?:${GATEWAY_SECURITY_HEADER_KEYS})\s*:\s*([^\s"',;]+)`;
GATEWAY_SECURITY_EQUALS_ASSIGNMENT_REDACT_PATTERN = String.raw`${LOG_HEADER_BOUNDARY_PATTERN}(?:${GATEWAY_SECURITY_HEADER_KEYS})\s*=\s*([^\s"',;]+)`;
FORM_AWARE_EQUALS_ASSIGNMENT_PATTERN_SOURCES = /* @__PURE__ */ new Set([CREDENTIAL_STYLE_EQUALS_ASSIGNMENT_REDACT_PATTERN, GATEWAY_SECURITY_EQUALS_ASSIGNMENT_REDACT_PATTERN]);
HTTP_AUTH_HEADER_REDACT_PATTERNS = [
String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}Proxy-Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}${HTTP_AUTH_SCHEME_PATTERN}${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`,
String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}Proxy-Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})[ \t]*(?=${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,
String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(?!(?:Bearer|Basic|Bot)(?=${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}))${HTTP_AUTH_SCHEME_PATTERN}${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`,
String.raw`${HTTP_AUTH_HEADER_BOUNDARY_PATTERN}Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_OPTIONAL_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(?!(?:Bearer|Basic|Bot)(?=${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}))(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})[ \t]*(?=${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}(?:$|[,;)}\]]|\r?\n(?![ \t])))`,
CREDENTIAL_STYLE_COLON_HEADER_REDACT_PATTERN,
CREDENTIAL_STYLE_EQUALS_ASSIGNMENT_REDACT_PATTERN
];
AUTHORIZATION_BEARER_REDACT_PATTERN = String.raw`Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_LEGACY_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}Bearer${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`;
AUTHORIZATION_BASIC_REDACT_PATTERN = String.raw`Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_LEGACY_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}Basic${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`;
AUTHORIZATION_BOT_REDACT_PATTERN = String.raw`Authorization${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}[ \t]*[:=]${HTTP_AUTH_LEGACY_VALUE_WHITESPACE_PATTERN}${HTTP_AUTH_SERIALIZED_QUOTE_PATTERN}Bot${HTTP_AUTH_REQUIRED_VALUE_WHITESPACE_PATTERN}(${HTTP_AUTH_OPAQUE_CREDENTIAL_PATTERN})`;
STANDALONE_BEARER_REDACT_PATTERN = String.raw`\bBearer\s+([-A-Za-z0-9._~+/=]{18,})(?![-A-Za-z0-9._~+/=])`;
SHELL_REFERENCE_PRESERVING_PATTERN_SOURCES = /* @__PURE__ */ new Set([
ENV_ASSIGNMENT_REDACT_PATTERN,
ESCAPED_ENV_ASSIGNMENT_REDACT_PATTERN,
STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN,
STANDALONE_ASSIGNMENT_REDACT_PATTERN
]);
CHUNK_UNSAFE_PATTERN_SOURCES = /* @__PURE__ */ new Set([
TELEGRAM_BOT_TOKEN_REDACT_PATTERN,
TELEGRAM_TOKEN_REDACT_PATTERN,
AUTHORIZATION_BEARER_REDACT_PATTERN,
AUTHORIZATION_BASIC_REDACT_PATTERN,
AUTHORIZATION_BOT_REDACT_PATTERN,
STANDALONE_BEARER_REDACT_PATTERN,
...HTTP_AUTH_HEADER_REDACT_PATTERNS
]);
DEFAULT_REDACT_FIELD_PATTERNS = [
ENV_ASSIGNMENT_REDACT_PATTERN,
ESCAPED_ENV_ASSIGNMENT_REDACT_PATTERN,
STRUCTURED_JSON_SECRET_REDACT_PATTERN,
STRUCTURED_JSON_PAYMENT_REDACT_PATTERN,
AMBIGUOUS_QUOTED_SECRET_FIELD_REDACT_PATTERN,
AMBIGUOUS_QUOTED_AUTH_FIELD_REDACT_PATTERN,
String.raw`--(?:${CLI_SECRET_FLAG_KEYS})=([^\s"']+)`,
String.raw`--(?:${CLI_SECRET_FLAG_KEYS})\s+(?!(?:or|and)\b(?=\s+--))(["']?)([^\s"']+)\1`,
AUTHORIZATION_BEARER_REDACT_PATTERN,
AUTHORIZATION_BASIC_REDACT_PATTERN,
AUTHORIZATION_BOT_REDACT_PATTERN,
...HTTP_AUTH_HEADER_REDACT_PATTERNS,
GATEWAY_SECURITY_COLON_HEADER_REDACT_PATTERN,
GATEWAY_SECURITY_EQUALS_ASSIGNMENT_REDACT_PATTERN,
STANDALONE_BEARER_REDACT_PATTERN,
String.raw`\b(?:https?|wss?|ftp):\/\/[^\/\s:@]*:([^\/\s@]+)@`,
String.raw`\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?|amqps?):\/\/[^:\s/@]*:([^@\s]+)@`,
String.raw`(^|[\s,;])(?:${FORM_BODY_FIRST_PAIR_KEYS})=([^&\s]+)(?=&[A-Za-z_][A-Za-z0-9_.-]*=)`,
STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN,
STANDALONE_ASSIGNMENT_REDACT_PATTERN,
CONFIG_QUOTED_ASSIGNMENT_REDACT_PATTERN,
CONFIG_ASSIGNMENT_REDACT_PATTERN,
CONFIG_DIRECT_ASSIGNMENT_REDACT_PATTERN,
CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_REDACT_PATTERN,
CONFIG_NAMESPACED_ASSIGNMENT_REDACT_PATTERN,
PEM_REDACT_PATTERN_SOURCE,
String.raw`(^|[\s,{])["']?(?:${AWS_SECRET_ACCESS_KEY_FIELD_KEYS})["']?\s*[:=]\s*(["']?)([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])\2`
];
VENDOR_TOKEN_REDACT_PATTERNS = [
String.raw`\b(sk-[A-Za-z0-9_-]{8,})\b`,
String.raw`(ghp_[A-Za-z0-9]{10,})`,
String.raw`(github_pat_[A-Za-z0-9_]{10,})`,
String.raw`(gho_[A-Za-z0-9]{10,})`,
String.raw`(ghu_[A-Za-z0-9]{10,})`,
String.raw`(ghs_[A-Za-z0-9]{10,})`,
String.raw`(ghr_[A-Za-z0-9]{10,})`,
String.raw`(glpat-[A-Za-z0-9._=\-]{20,})`,
String.raw`(gloas-(?:[A-Fa-f0-9]{65,}|[A-Za-z0-9_-]{64}|[A-Fa-f0-9]{32,}))`,
String.raw`(gldt-[A-Za-z0-9_-]{20,})`,
String.raw`(glcbt-[A-Za-z0-9]{1,5}_[A-Za-z0-9_-]{20,})`,
String.raw`(glptt-[A-Za-z0-9_-]{40,})`,
String.raw`(glft-(?:[A-Za-z0-9_-]{20,}|[a-h0-9]+-[0-9]+_))`,
String.raw`(glimt-[A-Za-z0-9_-]{25,})`,
String.raw`(glagent-[A-Za-z0-9_-]{50,})`,
String.raw`(glwt-[A-Za-z0-9_-]{20,})`,
String.raw`(glsoat-[A-Za-z0-9_-]{20,})`,
String.raw`(glffct-[A-Za-z0-9_-]{20,})`,
String.raw`(glrt-[A-Za-z0-9._-]{20,})`,
String.raw`(glrtr?-[A-Za-z0-9_-]{27,300}\.[0-9a-z]{2}\.[0-9a-z]{9})`,
String.raw`(GR1348941[A-Za-z0-9_-]{20,})`,
String.raw`(_gitlab_session=[A-Za-z0-9%._-]{20,})`,
String.raw`(xox[baprs]-[A-Za-z0-9-]{10,})`,
String.raw`(xapp-[A-Za-z0-9-]{10,})`,
String.raw`(https:\/\/hooks\.slack\.com\/(?:services\/T[A-Z0-9]+\/B[A-Z0-9]+|workflows\/T[A-Z0-9]+\/A[A-Z0-9]+\/[0-9]{17,19})\/[A-Za-z0-9]{20,})`,
String.raw`(https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]{17,20}\/[A-Za-z0-9_-]{60,})`,
String.raw`discord(?:.|\n|\r){0,40}?\b([A-Za-z0-9_-]{24}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27})\b`,
String.raw`(gsk_[A-Za-z0-9_-]{10,})`,
String.raw`(AIza[0-9A-Za-z\-_]{20,})`,
String.raw`(ya29\.[0-9A-Za-z_\-./+=]{10,})`,
String.raw`(1//0[0-9A-Za-z_\-./+=]{10,})`,
String.raw`(eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,
String.raw`(pplx-[A-Za-z0-9_-]{10,})`,
String.raw`(fal_[A-Za-z0-9_-]{10,})`,
String.raw`${IDENTIFIER_SAFE_TOKEN_BOUNDARY}(fc-[A-Za-z0-9]{10,})`,
String.raw`(bb_live_[A-Za-z0-9_-]{10,})`,
String.raw`${BASE64_SAFE_TOKEN_BOUNDARY}(gAAAA[A-Za-z0-9_=-]{20,})`,
String.raw`(sk_live_[A-Za-z0-9]{10,})`,
String.raw`(sk_test_[A-Za-z0-9]{10,})`,
String.raw`(rk_live_[A-Za-z0-9]{10,})`,
String.raw`(SG\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})`,
String.raw`(npm_[A-Za-z0-9]{10,})`,
String.raw`(pypi-[A-Za-z0-9_-]{10,})`,
String.raw`(dop_v1_[A-Za-z0-9]{10,})`,
String.raw`(doo_v1_[A-Za-z0-9]{10,})`,
String.raw`(dor_v1_[A-Za-z0-9]{10,})`,
String.raw`(dp\.(?:ct|pt|sa|scim|audit)\.[A-Za-z0-9]{40,44})`,
String.raw`(dp\.st\.[A-Za-z0-9]{40,44})`,
String.raw`(dp\.st\.[a-z0-9_-]{2,35}\.[A-Za-z0-9]{40,44})`,
String.raw`(dckr_(?:pat|oat)_[A-Za-z0-9_-]{27,32})`,
String.raw`(bkua_[a-z0-9]{40})`,
String.raw`(CCIPAT_[A-Za-z0-9]{22}_[A-Fa-f0-9]{40})`,
String.raw`(sbp_[a-z0-9]{40})`,
String.raw`${BASE64_SAFE_TOKEN_BOUNDARY}(dapi[0-9a-f]{32}(?:-\d)?)`,
String.raw`(dd[pw]_[A-Za-z0-9]{36})`,
String.raw`(glsa_[A-Za-z0-9_]{41})`,
String.raw`(glc_eyJ[A-Za-z0-9+/=]{60,160})`,
String.raw`(nfp_[A-Za-z0-9_]{36})`,
String.raw`(CFPAT-[A-Za-z0-9_\-]{40,})`,
String.raw`${BASE64_SAFE_TOKEN_BOUNDARY}(ATCTT3xFfG[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8})`,
String.raw`${BASE64_SAFE_TOKEN_BOUNDARY}(ATATT[A-Za-z0-9+/=_-]+=[A-Za-z0-9]{8})`,
String.raw`${BASE64_SAFE_TOKEN_BOUNDARY}(ATBB[A-Za-z0-9_=.-]{16,})`,
String.raw`(BBDC-[A-Za-z0-9+/@_-]{40,50})`,
String.raw`(HRKU-AA[A-Za-z0-9_-]{20,})`,
String.raw`(pat-(?:eu|na)1-[A-Za-z0-9]{8}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{4}\-[A-Za-z0-9]{12})`,
String.raw`(apify_api_[A-Za-z0-9\-]{20,})`,
String.raw`(FlyV1 fm\d+_[A-Za-z0-9+/=,_-]{100,})`,
String.raw`(fio-u-[A-Za-z0-9_-]{40,})`,
String.raw`(^|[^A-Za-z0-9_])(am_[A-Za-z0-9_-]{10,})`,
String.raw`(^|[^A-Za-z0-9_])(sk_[A-Za-z0-9_]{10,})`,
String.raw`(tvly-[A-Za-z0-9]{10,})`,
String.raw`(exa_[A-Za-z0-9]{10,})`,
String.raw`(syt_[A-Za-z0-9]{10,})`,
String.raw`(retaindb_[A-Za-z0-9]{10,})`,
String.raw`(hsk-[A-Za-z0-9]{10,})`,
String.raw`(mem0_[A-Za-z0-9]{10,})`,
String.raw`(brv_[A-Za-z0-9]{10,})`,
String.raw`(xai-[A-Za-z0-9]{30,})`,
String.raw`${IDENTIFIER_SAFE_TOKEN_BOUNDARY}(fw-[A-Za-z0-9]{30,})`,
String.raw`${IDENTIFIER_SAFE_TOKEN_BOUNDARY}(fw_[A-Za-z0-9]{30,})`,
String.raw`${IDENTIFIER_SAFE_TOKEN_BOUNDARY}(fpk_[A-Za-z0-9]{30,})`,
String.raw`${BASE64_SAFE_TOKEN_BOUNDARY}(AKIA[A-Z0-9]{16})`,
String.raw`${BASE64_SAFE_TOKEN_BOUNDARY}(ASIA[A-Z0-9]{16})`,
String.raw`(AKID[A-Za-z0-9]{10,})`,
String.raw`(LTAI[A-Za-z0-9]{10,})`,
String.raw`(hf_[A-Za-z0-9]{10,})`,
String.raw`(api_org_[A-Za-z0-9]{20,})`,
String.raw`(r8_[A-Za-z0-9]{10,})`,
TELEGRAM_BOT_TOKEN_REDACT_PATTERN,
TELEGRAM_TOKEN_REDACT_PATTERN
];
DEFAULT_REDACT_STRING_PATTERNS = [...DEFAULT_REDACT_FIELD_PATTERNS, ...VENDOR_TOKEN_REDACT_PATTERNS];
DEFAULT_REDACT_PATTERNS = [...DEFAULT_REDACT_STRING_PATTERNS, AWS_SECRET_ACCESS_KEY_MATCHER];
TOOL_PAYLOAD_AMBIGUOUS_ASSIGNMENT_PATTERNS = /* @__PURE__ */ new Set([
ENV_ASSIGNMENT_REDACT_PATTERN,
ESCAPED_ENV_ASSIGNMENT_REDACT_PATTERN,
STRUCTURED_JSON_SECRET_REDACT_PATTERN,
AMBIGUOUS_QUOTED_SECRET_FIELD_REDACT_PATTERN,
AMBIGUOUS_QUOTED_AUTH_FIELD_REDACT_PATTERN,
STANDALONE_ASSIGNMENT_QUOTED_REDACT_PATTERN,
STANDALONE_ASSIGNMENT_REDACT_PATTERN,
CONFIG_QUOTED_ASSIGNMENT_REDACT_PATTERN,
CONFIG_ASSIGNMENT_REDACT_PATTERN,
CONFIG_DIRECT_ASSIGNMENT_REDACT_PATTERN,
CONFIG_PREFIXED_PASSWORD_ASSIGNMENT_REDACT_PATTERN,
CONFIG_NAMESPACED_ASSIGNMENT_REDACT_PATTERN
]);
TOOL_PAYLOAD_REDACT_PATTERNS = DEFAULT_REDACT_PATTERNS.filter((pattern) => typeof pattern !== "string" || !TOOL_PAYLOAD_AMBIGUOUS_ASSIGNMENT_PATTERNS.has(pattern));
}));
//#endregion
//#region src/logging/redact-performance.ts
/** The capture subscriber receives counts and synchronous CPU time, never text or patterns. */
function startRedactionMeasurement(operation) {
if (!redactionPerformance.hasSubscribers) return;
const startedAt = performance$1.now();
const cpu = process.threadCpuUsage();
return (outcome, inputChars, patternCount) => {
const elapsedMs = performance$1.now() - startedAt;
const used = process.threadCpuUsage(cpu);
redactionPerformance.publish({
operation,
outcome,
pid: process.pid,
threadId,
isMainThread,
elapsedMs,
threadCpuMs: (used.user + used.system) / 1e3,
...inputChars === void 0 ? {} : { inputChars },
...patternCount === void 0 ? {} : { patternCount }
});
};
}
var redactionPerformance;
var init_redact_performance = __esmMin((() => {
redactionPerformance = channel("openclaw.redaction");
}));
//#endregion
//#region src/logging/redact-prefilter.ts
function couldMatchDefaultRedactPatterns(text) {
return DEFAULT_REDACT_PREFILTER_RE.test(text) || AWS_SECRET_ACCESS_KEY_MATCHER.couldMatch(text);
}
function couldMatchDefaultFullContextPatterns(text) {
return couldMatchDefaultRedactPatterns(text) || FULL_CONTEXT_REDACT_EXTRA_TRIGGERS_RE.test(text);
}
function createRedactPrefilter(probe) {
const matches = /* @__PURE__ */ new Map();
return (text) => {
const cached = matches.get(text);
if (cached !== void 0) return cached;
const result = probe(text);
matches.set(text, result);
return result;
};
}
var DEFAULT_REDACT_PREFILTER_SOURCES, DEFAULT_REDACT_PREFILTER_RE, FULL_CONTEXT_REDACT_EXTRA_TRIGGERS_RE;
var init_redact_prefilter = __esmMin((() => {
init_redact_patterns();
DEFAULT_REDACT_PREFILTER_SOURCES = [
String.raw`KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH|COOKIE|SIGNATURE|CREDENTIAL|CARD|CVC|CVV|PAYMENT|PRIVATE KEY`,
String.raw`security[-_]?code|\bpass\s*[=:]|\bpassphrase\s*[=:]|_(?:password|pass|passphrase|passwd)\s*[=:]|jwt\s*[=:]|session=|code=|\bsig\s*=`,
String.raw`\bBearer\s+`,
String.raw`:\/\/[^\/\s:@]*:[^\s@]+@`,
String.raw`sk-|gh[opsur]_|github_pat_|glpat-|gloas-|gldt-|glcbt-|glptt-|glft-|glimt-|glagent-|glwt-|glsoat-|glffct-|glrt-|glrtr-|GR1348941|_gitlab_session=|xox[baprs]-|xapp-|hooks\.slack\.com|discord|gsk_|AIza|ya29\.|1\/\/0|eyJ|pplx-|fal_|fc-|bb_live_|gAAAA|[sr]k_(?:live|test)_|SG\.|npm_|pypi-|do[opr]_v1_|dp\.(?:ct|pt|sa|st|scim|audit)\.|dckr_|bkua_|CCIPAT_|sbp_|dapi[0-9a-f]|dd[pw]_|glsa_|nfp_|CFPAT-|ATCTT3|ATATT|ATBB|BBDC-|HRKU-|pat-(?:eu|na)1-|apify_api_|FlyV1|fio-u-|tvly-|exa_|syt_|retaindb_|mem0_|brv_|xai-|fw-|fw_|fpk_`,
String.raw`(?:^|[^A-Za-z0-9_])(?:am_|sk_)`,
String.raw`A[KS]IA[A-Z0-9]|AKID|LTAI|hf_|api_org_|r8_`,
String.raw`\bbot\d{6,}:|\b\d{6,}:[A-Za-z0-9_-]{20,}`,
String.raw`%[0-9A-Fa-f]{2}[${FORM_BODY_KEY_INVISIBLE_CHARS}+A-Za-z0-9_%.-]*=`,
String.raw`=(?<=[${FORM_BODY_KEY_INVISIBLE_CHARS}+][${FORM_BODY_KEY_INVISIBLE_CHARS}+A-Za-z0-9_%.-]*=)(?<=[A-Za-z0-9_%.-][${FORM_BODY_KEY_INVISIBLE_CHARS}+A-Za-z0-9_%.-]*=)`
];
DEFAULT_REDACT_PREFILTER_RE = new RegExp(`(?:${DEFAULT_REDACT_PREFILTER_SOURCES.join("|")})`, "iu");
FULL_CONTEXT_REDACT_EXTRA_TRIGGERS_RE = /JWT|Bearer\s+|am_|sk_|(?<!\d)\d{6,}:[A-Za-z0-9_-]{20,}/i;
}));
//#endregion
//#region src/shared/assistant-error-format.ts
function isKnownTransportErrorCode(value) {
return TRANSPORT_ERRORS.some(({ code }) => code?.exec(value)?.[0] === value);
}
var HTTP_STATUS_DELIMITER_RE, TRANSPORT_ERRORS;
var init_assistant_error_format = __esmMin((() => {
HTTP_STATUS_DELIMITER_RE = /(?:\s*:\s*|\s+)/;
new RegExp(`^(?:http\\s*)?(\\d{3})${HTTP_STATUS_DELIMITER_RE.source}(.+)$`, "i");
new RegExp(`^(?:http\\s*)?(\\d{3})(?:${HTTP_STATUS_DELIMITER_RE.source}([\\s\\S]+))?$`, "i");
TRANSPORT_ERRORS = [
{
code: /\beconnrefused\b/i,
phrases: ["connection refused", "actively refused"],
message: "LLM request failed: connection refused by the provider endpoint."
},
{
code: /\beconnreset\b|\beconnaborted\b|\benetreset\b|\bepipe\b/i,
phrases: [
"socket hang up",
"connection reset",
"connection aborted"
],
message: "LLM request failed: network connection was interrupted."
},
{
code: /\benotfound\b|\beai_again\b/i,
phrases: [
"getaddrinfo",
"no such host",
"dns"
],
message: "LLM request failed: DNS lookup for the provider endpoint failed."
},
{
code: /\benetunreach\b|\behostunreach\b|\behostdown\b/i,
phrases: ["network is unreachable", "host is unreachable"],
message: "LLM request failed: the provider endpoint is unreachable from this host."
},
{
phrases: [
"fetch failed",
"connection error",
"network request failed"
],
message: "LLM request failed: network connection error."
}
];
}));
//#endregion
//#region src/logging/structured-authorization-code.ts
function pathEndsWith(path, suffix) {
if (path.length < suffix.length) return false;
return suffix.every((part, index) => path[path.length - suffix.length + index] === part);
}
function shouldRedactStructuredAuthorizationCode(normalizedKey, path, transportCode) {
if (normalizedKey !== "code") return false;
const normalizedPath = path.map((part) => part.toLowerCase());
if (normalizedPath.length === 1 || pathEndsWith(normalizedPath, ["error", "code"]) || pathEndsWith(normalizedPath, ["nodeerror", "code"]) || pathEndsWith(normalizedPath, ["status", "code"]) || pathEndsWith(normalizedPath, ["details", "code"]) || pathEndsWith(normalizedPath, ["warnings", "code"])) return false;
return !(transportCode !== void 0 && normalizedPath.length > 1 && normalizedPath.slice(0, -1).every((part) => part === "cause") && isKnownTransportErrorCode(transportCode));
}
var init_structured_authorization_code = __esmMin((() => {
init_assistant_error_format();
}));
//#endregion
//#region src/logging/redact.ts
function normalizeMode(value) {
return value === "off" ? "off" : DEFAULT_REDACT_MODE;
}
function parsePattern(raw) {
if (raw === PEM_REDACT_PATTERN_SOURCE) return PEM_REDACT_MATCHER;
if (typeof raw !== "string" && !(raw instanceof RegExp)) return raw;
let pattern = null;
if (raw instanceof RegExp) {
if (raw.flags.includes("g")) pattern = raw;
else pattern = new RegExp(raw.source, `${raw.flags}g`);
} else if (raw.trim()) pattern = compileConfigRegex(...parseRedactPatternSource(raw))?.regex ?? null;
if (pattern && typeof raw === "string" && SHELL_REFERENCE_PRESERVING_PATTERN_SOURCES.has(raw)) shellReferencePreservingPatterns.add(pattern);
if (pattern && typeof raw === "string" && TOOL_PAYLOAD_AMBIGUOUS_ASSIGNMENT_PATTERNS.has(raw)) sourceAssignmentPatterns.add(pattern);
if (pattern && typeof raw === "string" && FORM_AWARE_EQUALS_ASSIGNMENT_PATTERN_SOURCES.has(raw)) formAwareEqualsAssignmentPatterns.add(pattern);
if (pattern && typeof raw === "string" && (raw.startsWith(BASE64_SAFE_TOKEN_BOUNDARY) || raw.startsWith(IDENTIFIER_SAFE_TOKEN_BOUNDARY) || CHUNK_UNSAFE_PATTERN_SOURCES.has(raw))) chunkUnsafePatterns.add(pattern);
return pattern;
}
function resolvePatterns(value) {
if (value === TOOL_PAYLOAD_REDACT_PATTERNS) {
toolPayloadResolvedPatterns ??= TOOL_PAYLOAD_REDACT_PATTERNS.map(parsePattern).filter((re) => Boolean(re));
return toolPayloadResolvedPatterns;
}
if (!value?.length || value === DEFAULT_REDACT_PATTERNS) {
defaultResolvedPatterns ??= DEFAULT_REDACT_PATTERNS.map(parsePattern).filter((re) => Boolean(re));
return defaultResolvedPatterns;
}
return [.../* @__PURE__ */ new Set([...value.map(parsePattern).filter((re) => Boolean(re)), AWS_SECRET_ACCESS_KEY_MATCHER])];
}
function usesBuiltInRedactPatterns(value) {
return !value?.length || value === DEFAULT_REDACT_PATTERNS || value === TOOL_PAYLOAD_REDACT_PATTERNS;
}
function maskToken(token) {
if (token === "***") return token;
if (token.length < DEFAULT_REDACT_MIN_LENGTH) return "***";
return `${sliceUtf16Safe(token, 0, DEFAULT_REDACT_KEEP_START)}…${sliceUtf16Safe(token, -4)}`;
}
function splitSecretValueForMask(token) {
const openingQuote = token[0] ?? "";
const contentStart = SECRET_VALUE_QUOTE_CHARS.has(openingQuote) ? 1 : 0;
if (contentStart) {
const closingQuoteIndex = token.lastIndexOf(openingQuote);
if (closingQuoteIndex > 0) {
const suffix = token.slice(closingQuoteIndex + 1);
if (SECRET_VALUE_SUFFIX_RE.test(suffix)) return {
maskable: token.slice(1, closingQuoteIndex),
suffix,
maskStart: 0,
maskEnd: closingQuoteIndex + 1
};
}
}
const content = token.slice(contentStart);
const trailingDelimiter = content.match(SECRET_VALUE_TRAILING_DELIMITER_RE)?.[1] ?? "";
const maskable = trailingDelimiter && trailingDelimiter.length < content.length ? content.slice(0, -trailingDelimiter.length) : content;
return {
maskable,
suffix: maskable === content ? "" : trailingDelimiter,
maskStart: 0,
maskEnd: contentStart + maskable.length
};
}
function splitFormAwareCredentialValue(token) {
const pairBoundary = token.search(/&[A-Za-z_][A-Za-z0-9_.-]*=/u);
return pairBoundary < 0 ? {
secret: token,
suffix: ""
} : {
secret: token.slice(0, pairBoundary),
suffix: token.slice(pairBoundary)
};
}
function maskSecretValue(token, options) {
const { maskable, suffix } = splitSecretValueForMask(token);
return `${options?.hinted ? maskToken(maskable) : "***"}${suffix}`;
}
function normalizeSensitiveKeyName(value) {
const stripped = value.replace(FORM_BODY_KEY_SEPARATOR_RE, "");
try {
return decodeURIComponent(stripped).replace(FORM_BODY_KEY_SEPARATOR_RE, "").toLowerCase().replaceAll("-", "_");
} catch {
return stripped.toLowerCase().replaceAll("-", "_");
}
}
function isSensitiveBodyKey(key) {
return isSensitiveUrlQueryParamName(key) || BODY_SECRET_KEYS.has(normalizeSensitiveKeyName(key));
}
function hasEncodedOrInvisibleFormKey(key) {
return FORM_BODY_PERCENT_ESCAPE_RE.test(key) || key.replace(FORM_BODY_KEY_OBFUSCATION_RE, "") !== key;
}
function visitSensitiveAssignments(text, kind, visit) {
if (!text || kind === "url" && !text.includes("?")) return;
if (kind === "encoded" && !text.includes("%") && text.replace(FORM_BODY_KEY_OBFUSCATION_RE, "") === text) return;
if (kind === "context" && !/[=:]/u.test(text)) return;
const visitPair = (key, token, valueOffset) => {
if (kind === "encoded" && !hasEncodedOrInvisibleFormKey(key)) return;
if (!isSensitiveBodyKey(key)) return;
const { maskable, maskStart, maskEnd } = splitSecretValueForMask(token);
visit(valueOffset + maskStart, valueOffset + maskEnd, maskable);
};
if (kind === "form") {
let cursor = 0;
for (const pair of text.split("&")) {
const equalsIndex = pair.indexOf("=");
if (equalsIndex >= 0) visitPair(pair.slice(0, equalsIndex), pair.slice(equalsIndex + 1), cursor + equalsIndex + 1);
cursor += pair.length + 1;
}
return;
}
const pattern = kind === "url" ? URL_QUERY_PAIR_RE : kind === "encoded" ? ENCODED_FORM_PAIR_RE : FORM_BODY_CONTEXT_SINGLE_PAIR_RE;
const keyIndex = kind === "context" ? 3 : 2;
pattern.lastIndex = 0;
try {
for (let match = pattern.exec(text); match; match = pattern.exec(text)) {
const prefix = match[1] ?? "";
const key = match[keyIndex] ?? "";
visitPair(key, match[keyIndex + 1] ?? "", match.index + prefix.length + key.length + 1);
}
} finally {
pattern.lastIndex = 0;
}
}
function redactAssignmentValues(text, kind, onEdits) {
const parts = [];
const edits = [];
let cursor = 0;
visitSensitiveAssignments(text, kind, (start, end, maskable) => {
const replacement = kind === "url" ? maskToken(maskable) : "***";
parts.push(text.slice(cursor, start), replacement);
if (onEdits) edits.push({
start,
end,
replacement
});
cursor = end;
});
if (edits.length > 0) onEdits?.(edits);
return parts.length > 0 ? parts.join("") + text.slice(cursor) : text;
}
function redactFormBodyLine(text, onEdits) {
if (!text) return text;
const contextRedacted = redactAssignmentValues(redactAssignmentValues(text, "encoded", onEdits), "context", onEdits);
if (!contextRedacted.includes("&")) return contextRedacted;
if (FORM_BODY_RE.test(contextRedacted)) return redactAssignmentValues(contextRedacted, "form", onEdits);
const substringEdits = [];
const redacted = contextRedacted.replace(FORM_BODY_SUBSTRING_RE, (match, prefix, body, offset) => {
const redactedBody = redactAssignmentValues(body, "form", onEdits ? (edits) => {
for (const edit of edits) substringEdits.push({
...edit,
start: offset + prefix.length + edit.start,
end: offset + prefix.length + edit.end
});
} : void 0);
return redactedBody === body ? match : `${prefix}${redactedBody}`;
});
if (substringEdits.length > 0) onEdits?.(substringEdits);
return redactAssignmentValues(redactAssignmentValues(redacted, "encoded", onEdits), "context", onEdits);
}
function redactFormBody(text, onEdits) {
if (!text.includes("=")) return text;
if (FORM_BODY_LINE_BREAK_SPLIT_RE.test(text)) {
let offset = 0;
return text.split(FORM_BODY_LINE_BREAK_SPLIT_RE).map((segment) => {
const result = FORM_BODY_LINE_BREAK_SEGMENT_RE.test(segment) ? segment : redactFormBodyLine(segment, onEdits ? (edits) => onEdits(edits.map((edit) => ({
...edit,
start: offset + edit.start,
end: offset + edit.end
}))) : void 0);
offset += result.length;
return result;
}).join("");
}
return redactFormBodyLine(text, onEdits);
}
function isShellReferenceToKey(key, value) {
if (!/^[A-Z_][A-Z0-9_]*$/.test(key)) return false;
const bare = value.match(/^\$([A-Z_][A-Z0-9_]*)$/);
if (bare) return bare[1] === key;
return value.match(/^\$\{([A-Z_][A-Z0-9_]*)(?::[-=?+])?\}$/)?.[1] === key;
}
function maskSecretFieldValue(key, value) {
const expansion = value.match(/^\$\{([A-Z_][A-Z0-9_]*):[-=?+][^{}]+\}(?![\s\S])/);
if (expansion && expansion[1] === key) return `${value.slice(0, value.indexOf(":") + 2)}***}`;
return "***";
}
function readEnvAssignmentKey(match) {
return match.match(/\b([A-Z_][A-Z0-9_]*)\b\s*[=:]/)?.[1];
}
function shouldPreserveShellReferenceMatch(match, token) {
const key = readEnvAssignmentKey(match);
return key ? isShellReferenceToKey(key, token) : false;
}
function isEmptyShellParameterExpansionTail(token) {
return /^[-=?+]\}$/.test(token);
}
function prepareRedactionCapture({ match, groups, input, offset, replacement: policyReplacement }, pattern, preserveSourceAssignment) {
if (match.includes("PRIVATE KEY-----")) return {
start: offset,
end: offset + match.length,
value: match,
redact: (target) => ({
start: target.start,
end: target.end,
value: target.value,
replacement: policyReplacement ?? redactPemBlock(target.value, "…redacted…")
})
};
const selected = selectSecretCapture(match, groups);
if (selected.value === "***") return;
const tokenIndex = selected.value === match ? 0 : getSecretCaptureStart(pattern, input, match, offset, selected);
if (tokenIndex < 0) return;
const start = offset + tokenIndex;
return {
start,
end: start + selected.value.length,
value: selected.value,
redact: (target) => {
const token = target.value;
if (sourceAssignmentPatterns.has(pattern) && preserveSourceAssignment?.(input, offset + getSecretCaptureStart(pattern, input, match, offset, selected))) return;
const formAwareValue = formAwareEqualsAssignmentPatterns.has(pattern) ? splitFormAwareCredentialValue(token) : {
secret: token,
suffix: ""
};
if (splitSecretValueForMask(formAwareValue.secret).maskable === "***") return;
const isShellReferencePattern = shellReferencePreservingPatterns.has(pattern);
if (isShellReferencePattern && (shouldPreserveShellReferenceMatch(match, token) || isEmptyShellParameterExpansionTail(token))) return;
const masked = policyReplacement ?? (preserveSourceAssignment && sourceAssignmentPatterns.has(pattern) ? maskSecretValue(token) : isShellReferencePattern ? maskToken(token) : `${maskSecretValue(formAwareValue.secret, { hinted: true })}${formAwareValue.suffix}`);
return {
start: target.start,
end: target.end,
replacement: masked
};
}
};
}
function redactMatch(match, pattern, preserveSourceAssignment) {
const capture = prepareRedactionCapture(match, pattern, preserveSourceAssignment);
const edit = capture?.redact(capture);
return edit ? match.match.slice(0, edit.start - match.offset) + edit.replacement + match.match.slice(edit.end - match.offset) : match.match;
}
function redactText(text, patterns, options) {
const finishMeasurement = startRedactionMeasurement("text");
let outcome = "error";
try {
let next = redactFormBody(redactAssignmentValues(redactStructuredAuthHeaders(text, "***"), "url"));
let pattern;
const replace = (match) => redactMatch(match, pattern, options?.preserveSourceAssignment);
const replaceRegex = (...args) => replace(readRedactMatch(args));
for (pattern of patterns) next = pattern instanceof RegExp && !options?.fullContext && !chunkUnsafePatterns.has(pattern) ? replacePatternBounded(next, pattern, replaceRegex) : replaceRedactPattern(next, pattern, replace, replaceRegex);
outcome = "ok";
return next;
} finally {
finishMeasurement?.(outcome, text.length, patterns.length);
}
}
function looksLikeAppSpecificPassword(candidate) {
return candidate.split("-").every((part) => !BENIGN_APP_PASSWORD_WORDS.has(part.toLowerCase()));
}
function redactAppSpecificPasswords(text) {
return replacePatternBounded(text, APP_SPECIFIC_PASSWORD_RE, (match, token) => looksLikeAppSpecificPassword(token) ? maskToken(token) : match);
}
function resolveConfigRedaction() {
const cfg = readLoggingConfig();
return {
mode: DEFAULT_REDACT_MODE,
patterns: cfg?.redactPatterns
};
}
function resolveRedactOptions(options) {
const resolved = options ?? resolveConfigRedaction();
const mode = normalizeMode(resolved.mode);
return {
mode,
patterns: mode === "off" ? [] : resolvePatterns(resolved.patterns)
};
}
function redactSensitiveText(text, options) {
if (!text) return text;
return redactSensitiveTextWithOptions(redactRegisteredSecretValues(text, maskToken), options ?? resolveConfigRedaction());
}
function redactSensitiveTextWithOptions(exactRedacted, resolvedOptions) {
if (normalizeMode(resolvedOptions.mode) === "off") return exactRedacted;
if (usesBuiltInRedactPatterns(resolvedOptions.patterns) && !couldMatchDefaultRedactPatterns(exactRedacted)) return exactRedacted;
return redactText(exactRedacted, resolveRedactOptions(resolvedOptions).patterns);
}
function resolveToolPayloadRedaction(loggingConfig = readLoggingConfig()) {
const userPatterns = loggingConfig?.redactPatterns;
return {
mode: "tools",
patterns: userPatterns && userPatterns.length > 0 ? [...userPatterns, ...DEFAULT_REDACT_PATTERNS] : void 0
};
}
function isSensitiveFieldKey(key) {
return STRUCTURED_SECRET_FIELD_RE.test(key) || STRUCTURED_SECRET_ENV_FIELD_RE.test(key);
}
function isPublicShareIdPath(path) {
if (path.at(-1)?.toLowerCase() !== "id") return false;
return path.at(-2)?.toLowerCase().replaceAll("-", "").replaceAll("_", "") === "publicshare";
}
function redactSensitiveFieldValueWithOptions(key, value, options, path = [key], objectPath = true, couldMatch = couldMatchDefaultRedactPatterns) {
const exactRedacted = redactRegisteredSecretValues(value, maskToken);
if (isPublicShareIdPath(path)) return maskToken(exactRedacted);
const fieldOptions = isSensitiveFieldKey(key) && options.sensitiveFieldPatterns ? {
...options,
patterns: options.sensitiveFieldPatterns
} : options;
const resolved = resolveRedactOptions(fieldOptions);
if (resolved.mode === "off") return exactRedacted;
const redacted = !usesBuiltInRedactPatterns(fieldOptions.patterns) || couldMatch(exactRedacted) ? redactText(exactRedacted, resolved.patterns) : exactRedacted;
if (redacted !== value || STRUCTURED_APP_PASSWORD_FIELD_RE.test(key)) {
const appRedacted = redactAppSpecificPasswords(redacted);
if (appRedacted !== value) return appRedacted;
}
if (redacted !== value) return redacted;
return shouldRedactStructuredStringField(key, exactRedacted, path, objectPath) ? maskToken(exactRedacted) : exactRedacted;
}
function shouldRedactStructuredPrimitiveField(key, path) {
const normalizedKey = key.toLowerCase();
return isPublicShareIdPath(path) || shouldRedactStructuredAuthorizationCode(normalizedKey, path) || isSensitiveFieldKey(key);
}
function isPlainRedactableObject(value) {
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function redactStructuredSecretValue(key, value, seen, options, couldMatch, path = key ? [key] : [], objectPath = true) {
if (typeof value === "string") return redactSensitiveFieldValueWithOptions(key, value, options, path, objectPath, couldMatch);
if (value === null || value === void 0) return value;
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return shouldRedactStructuredPrimitiveField(key, path) ? "***" : value;
if (Array.isArray(value)) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
const out = value.map((entry) => redactStructuredSecretValue(key, entry, seen, options, couldMatch, path, false));
seen.delete(value);
return out;
}
if (typeof value === "object") {
if (seen.has(value)) return "[Circular]";
if (!isPlainRedactableObject(value)) return value;
seen.add(value);
const entries = Object.entries(value);
for (const entry of entries) {
const [name, child] = entry;
entry[1] = redactStructuredSecretValue(name, child, seen, options, couldMatch, [...path, name], objectPath);
}
seen.delete(value);
return Object.fromEntries(entries);
}
return value;
}
function redactSecretsWithOptions(value, options) {
if (typeof value === "string") return redactSensitiveText(value, options);
if (value === null || typeof value !== "object") return value;
return redactStructuredSecretValue("", value, /* @__PURE__ */ new WeakSet(), options, createRedactPrefilter(couldMatchDefaultRedactPatterns));
}
function redactSecrets(value) {
return redactSecretsWithOptions(value, resolveToolPayloadRedaction());
}
function preservesStructuredReference(key, value) {
return key.toLowerCase() === "session" && STRUCTURED_INTERNAL_SOURCE_PATH_VALUE_RE.test(value) || isShellReferenceToKey(key, value);
}
function shouldRedactStructuredStringField(key, value, path, objectPath) {
return shouldRedactStructuredAuthorizationCode(key.toLowerCase(), path, objectPath ? value : void 0) || isSensitiveFieldKey(key) && !preservesStructuredReference(key, value);
}
function classifyLogFieldProtection(key, path, objectPath, value) {
return (value === void 0 ? shouldRedactStructuredPrimitiveField(key, path) : isPublicShareIdPath(path) || shouldRedactStructuredStringField(key, value, path, objectPath)) ? "legacy" : CREDENTIAL_HEADER_FIELD_RE.test(key) ? "header" : void 0;
}
function getFieldRecordEdits(field, mode) {
const { key, value, path, objectPath } = field;
if (mode === "off" || !field.string && value === "null" || !classifyLogFieldProtection(key, path, objectPath, field.string ? value : void 0)) return [];
return [{
start: 0,
end: value.length,
replacement: maskSecretFieldValue(key, value)
}];
}
function getTextRecordEdits(field, mode, fileFields) {
const { value } = field;
if (field.isKey || fileFields && !field.origin.structured) return [];
if (fileFields && field.origin.primitiveMask) return [{
start: 0,
end: value.length,
replacement: "***"
}];
if (!field.string) return [];
const edits = [];
const registered = redactRegisteredSecretValues(value, (secret, start) => {
const replacement = maskToken(secret);
edits.push({
start,
end: start + secret.length,
replacement
});
return replacement;
});
if (fileFields && isPublicShareIdPath(field.path)) return [{
start: 0,
end: value.length,
replacement: maskToken(registered)
}];
if (mode === "off") return edits;
let combined = edits;
const receive = (added) => {
combined = composeRedactionEdits(value.length, combined, added);
};
const headers = findStructuredAuthParamRanges(registered).map(({ start, end }) => ({
start,
end,
replacement: "***"
}));
receive(headers);
redactFormBody(redactAssignmentValues(applyRedactionEdits(registered, headers), "url", receive), receive);
return combined;
}
function getLegacyFieldRecordEdits(field, value, beforeConversion = false) {
const { key, value: original, path, objectPath } = field;
if (field.isKey || !field.origin.structured || !field.string) return [];
if (isPublicShareIdPath(path)) return [];
const edits = [];
if (value !== original || STRUCTURED_APP_PASSWORD_FIELD_RE.test(key)) {
for (const match of value.matchAll(APP_SPECIFIC_PASSWORD_RE)) if (looksLikeAppSpecificPassword(match[0])) edits.push({
start: match.index,
end: match.index + match[0].length,
replacement: maskToken(match[0])
});
}
if (edits.length > 0 || value !== original) return edits;
const protection = classifyLogFieldProtection(key, path, objectPath, value);
return protection === "legacy" || beforeConversion && protection === "header" ? [{
start: 0,
end: value.length,
replacement: maskToken(value)
}] : [];
}
function resolveFileLogRedactOptions() {
return resolveRedactOptions(resolveToolPayloadRedaction());
}
function* redactionEditMatches(input, edits) {
for (const edit of edits) yield {
match: input.slice(edit.start, edit.end),
groups: [],
input,
offset: edit.start,
replacement: edit.replacement
};
}
function prepareFileToJsonReceivers(record, patterns) {
const decoded = /* @__PURE__ */ new WeakSet();
const active = /* @__PURE__ */ new WeakSet();
const visit = (value, key, path, objectPath, decode) => {
if (typeof value === "string" && decode) {
const field = {
key,
path,
objectPath,
value,
isKey: false,
string: true,
origin: {
structured: true,
primitiveMask: false
}
};
let current = applyRedactionEdits(value, getTextRecordEdits(field, "tools", true));
if (!isPublicShareIdPath(path)) for (const pattern of patterns) current = applyRedactionEdits(current, getPatternRedactionEdits(current, pattern, prepareRedactionCapture));
return applyRedactionEdits(current, getLegacyFieldRecordEdits(field, current, true));
}
if (value === null || typeof value !== "object") return decode && [
"number",
"boolean",
"bigint"
].includes(typeof value) && classifyLogFieldProtection(key, path, objectPath, void 0) ? "***" : value;
if (!Array.isArray(value) && !isPlainRedactableObject(value)) return value;
if (active.has(value)) return "[Circular]";
active.add(value);
let clone;
let decodeFields = decode;
if (Array.isArray(value)) clone = value.map((entry) => visit(entry, key, path, false, decodeFields));
else {
const entries = Object.entries(value);
decodeFields ||= entries.some(([name, entry]) => name === "toJSON" && typeof entry === "function");
clone = Object.fromEntries(entries.map(([name, entry]) => [name, visit(entry, name, [...path, name], objectPath, decodeFields)]));
}
if (decodeFields) decoded.add(clone);
active.delete(value);
return clone;
};
return {
record: visit(record, "", [], true, false),
decoded
};
}
/** Converts native values once and applies configured and structural protection before output. */
function redactLogRecord(record, options, finish) {
const finishMeasurement = startRedactionMeasurement("log-record");
let outcome = "error";
let inputChars;
try {
const resolved = resolveRedactOptions();
const prepared = options.format === "console" ? {
record,
decoded: /* @__PURE__ */ new WeakSet()
} : prepareFileToJsonReceivers(record, options.decodedOptions?.patterns ?? resolved.patterns);
const ordinary = {
structured: true,
primitiveMask: false
};
const origins = {
value: ordinary,
children: /* @__PURE__ */ new Map()
};
const ancestors = [];
const json = JSON.stringify(prepared.record, function(key, value) {
while (ancestors.length > 0 && ancestors.at(-1)?.value !== this) ancestors.pop();
const parent = ancestors.at(-1);
const array = Array.isArray(this);
const fieldKey = array && parent ? parent.key : key;
const path = array && parent ? parent.path : parent ? [...parent.path, key] : [];
const source = !parent ? prepared.record : parent.structured && options.format !== "console" ? Reflect.get(this, key) : value;
const structured = (parent?.structured ?? true) && (source === null || typeof source !== "object" || !prepared.decoded.has(source) && source === value && (Array.isArray(source) || isPlainRedactableObject(source)));
const primitiveMask = structured && [
"number",
"boolean",
"bigint"
].includes(typeof source) && classifyLogFieldProtection(fieldKey, path, !array, void 0) === "legacy";
const circular = value !== null && typeof value === "object" && ancestors.some((frame) => frame.value === value);
const emitted = circular ? "[Circular]" : typeof value === "bigint" ? String(value) : value;
const container = emitted !== null && typeof emitted === "object";
let node = origins;
if (parent && parent.structured && (container || !structured || primitiveMask || circular)) {
node = {
value: {
structured: structured && !circular,
primitiveMask
},
children: /* @__PURE__ */ new Map()
};
parent.origins.children.set(key, node);
} else if (parent) node = parent.origins;
else origins.value = {
structured,
primitiveMask
};
if (container) ancestors.push({
value: emitted,
path,
key: fieldKey,
origins: node,
structured
});
return emitted;
});
inputChars = json.length;
let materialized = JSON.parse(json);
const message = options.deriveMessage?.(materialized);
if (message) {
origins.children.set("message", {
value: ordinary,
children: /* @__PURE__ */ new Map()
});
if (Object.hasOwn(materialized, "message")) materialized.message = message.text;
else {
const entries = Object.entries(materialized);
entries.splice(entries.findIndex(([key]) => key === "hostname") + 1, 0, ["message", message.text]);
materialized = Object.fromEntries(entries);
}
}
const serialized = message ? JSON.stringify(materialized) : json;
const decodedPatterns = options.decodedOptions?.patterns ?? resolved.patterns;
const couldMatch = createRedactPrefilter(couldMatchDefaultFullContextPatterns);
const result = finish(redactJsonRecord(serialized, origins, [[{ patterns: decodedPatterns }], [{ patterns: preparationPatterns }, {
patterns: resolved.patterns,
...resolved.patterns === defaultResolvedPatterns ? { couldMatch } : {}
}]], prepareRedactionCapture, options.format === "console" ? () => [] : getLegacyFieldRecordEdits, (field) => getFieldRecordEdits(field, resolved.mode), (field) => getTextRecordEdits(field, resolved.mode, options.format !== "console"), (field, currentValue) => (options.format === "console" ? field.path.length === 1 && CONSOLE_STRUCTURAL_FIELDS.has(field.key) : !field.origin.structured || field.origin.primitiveMask || isPublicShareIdPath(field.path)) || decodedPatterns === defaultResolvedPatterns && !couldMatch(currentValue), message), message ? serialized : void 0);
outcome = "ok";
return result;
} finally {
finishMeasurement?.(outcome, inputChars);
}
}
function redactLogRecordForTransport(record, options = {}) {
return redactLogRecord(record, options, (redacted) => JSON.parse(redacted));
}
function serializeRedactedFileLogRecord(record, options = {}) {
return redactLogRecord(record, options, (redacted, canonical) => redacted === canonical ? redacted : JSON.stringify(JSON.parse(redacted)));
}
var DEFAULT_REDACT_MODE, DEFAULT_REDACT_MIN_LENGTH, DEFAULT_REDACT_KEEP_START, shellReferencePreservingPatterns, chunkUnsafePatterns, formAwareEqualsAssignmentPatterns, sourceAssignmentPatterns, defaultResolvedPatterns, toolPayloadResolvedPatterns, FORM_BODY_KEY_OBFUSCATION_RE, FORM_BODY_KEY_SEPARATOR_RE, FORM_BODY_PERCENT_ESCAPE_RE, FORM_BODY_KEY, FORM_BODY_VALUE, URL_QUERY_VALUE, FORM_BODY_PAIR, FORM_BODY_RE, FORM_BODY_SUBSTRING_RE, ENCODED_FORM_PAIR_RE, FORM_BODY_CONTEXT_SINGLE_PAIR_RE, URL_QUERY_PAIR_RE, SECRET_VALUE_TRAILING_DELIMITER_RE, SECRET_VALUE_SUFFIX_RE, SECRET_VALUE_QUOTE_CHARS, FORM_BODY_LINE_BREAK_SPLIT_RE, FORM_BODY_LINE_BREAK_SEGMENT_RE, STRUCTURED_SECRET_FIELD_RE, STRUCTURED_INTERNAL_SOURCE_PATH_VALUE_RE, STRUCTURED_APP_PASSWORD_FIELD_RE, APP_SPECIFIC_PASSWORD_RE, BENIGN_APP_PASSWORD_WORDS, STRUCTURED_SECRET_ENV_FIELD_RE, preparationPatterns, CONSOLE_STRUCTURAL_FIELDS;
var init_redact = __esmMin((() => {
init_redact_sensitive_url();
init_utf16_slice();
init_structured_auth_redaction();
init_config_regex();
init_config();
init_redact_bounded();
init_redact_edit_composition();
init_redact_internal_state();
init_redact_internal();
init_redact_json();
init_redact_pattern_runtime();
init_redact_patterns();
init_redact_pem();
init_redact_performance();
init_redact_prefilter();
init_secret_redaction_registry();
init_structured_authorization_code();
DEFAULT_REDACT_MODE = "tools";
DEFAULT_REDACT_MIN_LENGTH = 18;
DEFAULT_REDACT_KEEP_START = 6;
shellReferencePreservingPatterns = /* @__PURE__ */ new WeakSet();
chunkUnsafePatterns = /* @__PURE__ */ new WeakSet();
formAwareEqualsAssignmentPatterns = /* @__PURE__ */ new WeakSet();
sourceAssignmentPatterns = /* @__PURE__ */ new WeakSet();
FORM_BODY_KEY_OBFUSCATION_RE = new RegExp(String.raw`[${FORM_BODY_KEY_INVISIBLE_CHARS}+]`, "gu");
FORM_BODY_KEY_SEPARATOR_RE = /[\p{C}\p{Z}\u115F\u1160\u3164\uFFA0+]/gu;
FORM_BODY_PERCENT_ESCAPE_RE = /%[0-9A-Fa-f]{2}/u;
FORM_BODY_KEY = String.raw`[${FORM_BODY_KEY_INVISIBLE_CHARS}+]*(?:[A-Za-z_]|%[0-9A-Fa-f]{2})(?:[A-Za-z0-9_.-]|%[0-9A-Fa-f]{2}|[${FORM_BODY_KEY_INVISIBLE_CHARS}+])*`;
FORM_BODY_VALUE = "[^&\\s<>]*";
URL_QUERY_VALUE = "[^&#\\s<>]*";
FORM_BODY_PAIR = String.raw`${FORM_BODY_KEY}=${FORM_BODY_VALUE}`;
FORM_BODY_RE = new RegExp(String.raw`^${FORM_BODY_PAIR}(?:&${FORM_BODY_PAIR})+$`, "u");
FORM_BODY_SUBSTRING_RE = new RegExp(String.raw`(^|[\s:({\[,="'` + "`" + String.raw`])(${FORM_BODY_PAIR}(?:&${FORM_BODY_PAIR})+)`, "gu");
ENCODED_FORM_PAIR_RE = new RegExp(String.raw`(^|[\s:({\[,="'` + "`" + String.raw`&])(${FORM_BODY_KEY})=(${FORM_BODY_VALUE})`, "gu");
FORM_BODY_CONTEXT_SINGLE_PAIR_RE = new RegExp(String.raw`(\b(?:body|form(?:[-_\s]?body)?)\s*[:=]\s*(["'\x60]?))(${FORM_BODY_KEY})=(${FORM_BODY_VALUE})(["'\x60]?)`, "giu");
URL_QUERY_PAIR_RE = new RegExp(String.raw`([?&])(${FORM_BODY_KEY})=(${URL_QUERY_VALUE})`, "gu");
SECRET_VALUE_TRAILING_DELIMITER_RE = /(["'`,;)}\]]+)$/u;
SECRET_VALUE_SUFFIX_RE = /^["'`,;)}\]]*$/u;
SECRET_VALUE_QUOTE_CHARS = /* @__PURE__ */ new Set([
"\"",
"'",
"`"
]);
FORM_BODY_LINE_BREAK_SPLIT_RE = /(\r\n|\r|\n)/u;
FORM_BODY_LINE_BREAK_SEGMENT_RE = /^(?:\r\n|\r|\n)$/u;
STRUCTURED_SECRET_FIELD_RE = new RegExp(String.raw`^(?:api[-_]?key|apiKey|api[-_]?token|apiToken|bearer[-_]?token|bearerToken|token|secret|password|passwd|${AWS_SECRET_ACCESS_KEY_FIELD_KEYS}|credential|authorization|private[-_]?key|privateKey|access[-_]?token|accessToken|refresh[-_]?token|refreshToken|id[-_]?token|idToken|auth[-_]?token|authToken|client[-_]?secret|clientSecret|app[-_]?secret|appSecret|secret[-_]?value|secretValue|raw[-_]?secret|rawSecret|secret[-_]?input|secretInput|key|key[-_]?material|keyMaterial|jwt|session|signature|cookie|set[-_]?cookie|${PAYMENT_CREDENTIAL_QUERY_KEYS}|${PAYMENT_CREDENTIAL_JSON_KEYS})$`, "i");
STRUCTURED_INTERNAL_SOURCE_PATH_VALUE_RE = /^\$WORKSPACE_DIR\/[A-Za-z0-9._/-]+\.jsonl$/u;
STRUCTURED_APP_PASSWORD_FIELD_RE = /^(?:apple|icloud|app[-_]?specific[-_]?password|appSpecificPassword|application[-_]?password|text|content|message|error|errorMessage|detail|details|reason)$/i;
APP_SPECIFIC_PASSWORD_RE = /\b([a-z]{4}-[a-z]{4}-[a-z]{4}-[a-z]{4})\b/g;
BENIGN_APP_PASSWORD_WORDS = /* @__PURE__ */ new Set([
"case",
"claw",
"demo",
"file",
"main",
"name",
"open",
"path",
"slug",
"test"
]);
STRUCTURED_SECRET_ENV_FIELD_RE = new RegExp(String.raw`^(?:(?:[A-Z0-9]+[_-])+(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD)|API[_-]?KEY|TOKEN|SECRET|PASSWORD|PASSWD|${PAYMENT_CREDENTIAL_ENV_KEYS})$`, "i");
preparationPatterns = [
{
source: "registered secret values",
*exec(input) {
const matches = [];
redactRegisteredSecretValues(input, (secret, offset) => {
matches.push({
match: secret,
groups: [],
input,
offset,
replacement: maskToken(secret)
});
return secret;
});
yield* matches;
}
},
{
source: "structured authorization parameters",
*exec(input) {
for (const { start, end } of findStructuredAuthParamRanges(input)) yield {
match: input.slice(start, end),
groups: [],
input,
offset: start,
replacement: "***"
};
}
},
{
source: "URL query assignments",
*exec(input) {
const edits = [];
redactAssignmentValues(input, "url", (added) => edits.push(...added));
yield* redactionEditMatches(input, edits);
}
},
{
source: "form bodies",
*exec(input) {
let edits = [];
redactFormBody(input, (added) => {
edits = composeRedactionEdits(input.length, edits, added);
});
yield* redactionEditMatches(input, edits);
}
}
];
CONSOLE_STRUCTURAL_FIELDS = /* @__PURE__ */ new Set(["time", "level"]);
}));
//#endregion
//#region src/infra/errors.ts
function formatErrorMessage(err) {
return formatErrorMessage$1(err, { redact: redactSensitiveText });
}
var init_errors$2 = __esmMin((() => {
init_error_coercion();
init_redact();
init_errno();
}));
//#endregion
//#region src/infra/semver.ts
function compareValidSemver(left, right) {
const parsedLeft = parse(left);
const parsedRight = parse(right);
return parsedLeft && parsedRight ? parsedLeft.compare(parsedRight) : null;
}
var init_semver = __esmMin((() => {}));
//#endregion
//#region src/infra/sqlite-pinned-read-snapshot.ts
function getSqlitePinnedReadSnapshot(db) {
return snapshots.get(db);
}
/** Pin an implicit read snapshot without requiring transaction-control authorization. */
function runSqlitePinnedReadSnapshotSync(db, operation) {
const parent = snapshots.get(db);
snapshots.set(db, parent ?? {});
try {
return executeWithCachedStatement(db, "PRAGMA schema_version", [], (statement) => {
const snapshot = statement.iterate();
try {
const first = snapshot.next();
if (first.done) throw new Error("SQLite schema version query returned no row");
return operation(Number(first.value.schema_version));
} finally {
snapshot.return?.();
}
});
} finally {
if (!parent) snapshots.delete(db);
}
}
var snapshots;
var init_sqlite_pinned_read_snapshot = __esmMin((() => {
init_global_singleton();
init_kysely_sync_cache_state();
snapshots = resolveGlobalSingleton(Symbol.for("openclaw.sqlitePinnedReadSnapshots"), () => /* @__PURE__ */ new WeakMap());
}));
//#endregion
//#region src/infra/sqlite-worker-identity.ts
/** Native SQLite namespaces are filesystem locators, not distinct database owners. */
function normalizeDatabasePath(location) {
const normalized = process.platform === "win32" ? normalizeWindowsPathPreservingCase(location) : location;
return process.platform === "win32" && !/^(?:[a-z]:[\\/]|[\\/]{2})/iu.test(normalized) ? location : normalized;
}
function databaseFileIdentityKey(file) {
return `${file.dev}:${file.ino}`;
}
function readDatabaseIdentityBirthtime(file) {
return useDatabaseBirthtime ? file.birthtimeNs.toString() : "0";
}
function existingIdentity(file, canonicalFile, canonicalPath) {
if (!file.isFile()) throw new Error("SQLite worker database path must identify a regular file");
if (file.dev !== canonicalFile.dev || file.ino !== canonicalFile.ino || readDatabaseIdentityBirthtime(file) !== readDatabaseIdentityBirthtime(canonicalFile)) throw new Error("SQLite database pathname changed during admission");
return {
key: `file:${databaseFileIdentityKey(file)}`,
canonicalPath: normalizeDatabasePath(canonicalPath),
birthtime: readDatabaseIdentityBirthtime(file)
};
}
/** In-process owner key only; never rewrite a configured or persisted database locator. */
function resolveDatabasePathKey(databasePath) {
const missing = [];
let ancestor = path.resolve(databasePath);
while (true) try {
return normalizeDatabasePath(path.join(realpathSync.native(ancestor), ...missing));
} catch (error) {
if (!hasErrnoCode(error, "ENOENT")) throw error;
missing.unshift(path.basename(ancestor));
const parent = path.dirname(ancestor);
if (parent === ancestor) throw error;
ancestor = parent;
}
}
/** Inspect a native-owner path without replacing its diagnostic for a non-file target. */
function inspectDatabasePathIdentitySync(databasePath) {
const resolvedPath = path.resolve(databasePath);
let file;
try {
file = statSync(resolvedPath, { bigint: true });
} catch (error) {
if (!hasErrnoCode(error, "ENOENT")) throw error;
}
if (file) {
if (!file.isFile()) return;
const canonicalPath = resolveDatabasePathKey(resolvedPath);
return existingIdentity(file, statSync(canonicalPath, { bigint: true }), canonicalPath);
}
const canonicalPath = resolveDatabasePathKey(resolvedPath);
return {
key: `path:${canonicalPath}`,
canonicalPath
};
}
/** Capture identity before yielding; worker admission requires a regular file or absent path. */
function readDatabasePathIdentitySync(databasePath) {
const identity = inspectDatabasePathIdentitySync(databasePath);
if (!identity) throw new Error("SQLite worker database path must identify a regular file");
return identity;
}
/** Inspect retained aliases only while binding a newly observed database path. */
function findChangedDatabasePaths(paths, observed) {
return [...paths].filter((pathname) => inspectDatabasePathIdentitySync(pathname)?.key !== observed.key);
}
async function readDatabasePathIdentity(databasePath) {
const file = await stat(databasePath, { bigint: true }).catch((error) => {
if (hasErrnoCode(error, "ENOENT")) return;
throw error;
});
if (file) try {
const canonicalPath = await realpath(databasePath);
return existingIdentity(file, await stat(canonicalPath, { bigint: true }), canonicalPath);
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) throw new Error("SQLite database pathname changed during admission", { cause: error });
throw error;
}
const missing = [];
let ancestor = databasePath;
while (true) try {
const canonicalPath = normalizeDatabasePath(path.join(await realpath(ancestor), ...missing));
return {
key: `path:${canonicalPath}`,
canonicalPath
};
} catch (error) {
if (!hasErrnoCode(error, "ENOENT")) throw error;
missing.unshift(path.basename(ancestor));
const parent = path.dirname(ancestor);
if (parent === ancestor) throw error;
ancestor = parent;
}
}
function assertExistingDatabaseIdentity(databasePath, expected, expectedBirthtime) {
const file = statSync(databasePath, { bigint: true });
if (!file.isFile() || `file:${file.dev}:${file.ino}` !== expected || expectedBirthtime !== void 0 && readDatabaseIdentityBirthtime(file) !== expectedBirthtime) throw new Error("SQLite database file identity changed before existing-only open");
}
var useDatabaseBirthtime;
var init_sqlite_worker_identity = __esmMin((() => {
init_errno();
init_path_guards();
useDatabaseBirthtime = process.platform !== "linux";
}));
//#endregion
//#region src/infra/sqlite-schema-facts.ts
function invalidate(owner) {
owner.revision += 1;
owner.facts = void 0;
}
function bindScope(database, owner) {
if (owner.scope) return owner.scope;
const location = database.location();
const key = location ? readDatabasePathIdentitySync(location).key : void 0;
const scope = key && scopes.byIdentity.get(key) || {
key,
revision: 0,
users: 0
};
if (key) scopes.byIdentity.set(key, scope);
scope.users += 1;
owner.scope = scope;
owner.scopeRevision = scope.revision;
scopes.finalizer.register(database, scope, owner);
return scope;
}
function publishSchemaChange(database, owner) {
const scope = bindScope(database, owner);
scope.revision += 1;
owner.scopeRevision = scope.revision;
}
/** Schema publications outside DDL (such as a deferred version marker) share this revision. */
function invalidateSqliteSchemaFacts(database) {
const owner = owners$1.get(database);
if (owner) {
bindScope(database, owner);
invalidate(owner);
owner.transactionalSchema ||= database.isTransaction;
if (!database.isTransaction) publishSchemaChange(database, owner);
}
}
function changesSchema(sql) {
return /\b(?:CREATE|ALTER|DROP|REINDEX|VACUUM)\b|\bPRAGMA\b[\s\S]*\b(?:user_version|schema_version|writable_schema)\b[\s\S]*[=(]/i.test(sql);
}
function batchTransactionControl(sql) {
let control;
let remaining = sql;
while (remaining) {
const next = transactionControlPrefix.exec(remaining)?.[1]?.toUpperCase();
if (next === "ROLLBACK") return next;
control ||= next;
const end = remaining.includes(";") ? findSqlCharacter(remaining, ";") : -1;
if (end < 0) break;
remaining = remaining.slice(end + 1);
}
return control;
}
function callStatement(method, [first, ...remaining]) {
if (first === void 0) return method();
if (typeof first === "object" && first !== null && !ArrayBuffer.isView(first)) return method(first, ...remaining);
return method(first, ...remaining);
}
function trackSchemaChanges(database, owner, native) {
const settle = (boundary = false) => {
if ((boundary || !database.isTransaction) && (owner.transactionalSchema || owner.transactionalFacts)) {
if (owner.transactionalSchema) publishSchemaChange(database, owner);
invalidate(owner);
owner.transactionalSchema &&= database.isTransaction;
owner.transactionalFacts = false;
}
};
const execute = (operation, schemaChange, control) => {
if (owner.transactionalSchema && !owner.scope) bindScope(database, owner);
settle();
const invalidates = schemaChange || control === "ROLLBACK" && owner.transactionalSchema;
if (invalidates) invalidateSqliteSchemaFacts(database);
try {
return operation();
} finally {
if (invalidates) invalidateSqliteSchemaFacts(database);
settle(Boolean(control));
}
};
database.exec = (sql) => execute(() => native.DatabaseSync.prototype.exec.call(database, sql), changesSchema(sql), batchTransactionControl(sql));
database.prepare = (...prepareArgs) => {
const [sql] = prepareArgs;
const statement = native.DatabaseSync.prototype.prepare.call(database, ...prepareArgs);
const schemaChange = changesSchema(sql);
const control = transactionControlPrefix.exec(sql)?.[1]?.toUpperCase();
if (schemaChange || control) {
const run = Object.hasOwn(statement, "run") ? statement.run.bind(statement) : void 0;
const get = Object.hasOwn(statement, "get") ? statement.get.bind(statement) : void 0;
const all = Object.hasOwn(statement, "all") ? statement.all.bind(statement) : void 0;
const iterate = Object.hasOwn(statement, "iterate") ? statement.iterate.bind(statement) : void 0;
statement.run = (...bindings) => execute(() => callStatement(run ?? native.StatementSync.prototype.run.bind(statement), bindings), schemaChange, control);
statement.get = (...bindings) => execute(() => callStatement(get ?? native.StatementSync.prototype.get.bind(statement), bindings), schemaChange, control);
statement.all = (...bindings) => execute(() => callStatement(all ?? native.StatementSync.prototype.all.bind(statement), bindings), schemaChange, control);
statement.iterate = function* (...bindings) {
if (owner.transactionalSchema && !owner.scope) bindScope(database, owner);
settle();
const invalidates = schemaChange || control === "ROLLBACK" && owner.transactionalSchema;
if (invalidates) invalidateSqliteSchemaFacts(database);
try {
yield* callStatement(iterate ?? native.StatementSync.prototype.iterate.bind(statement), bindings);
} finally {
if (invalidates) invalidateSqliteSchemaFacts(database);
settle(Boolean(control));
}
};
}
return statement;
};
if (typeof database.setAuthorizer === "function") database.setAuthorizer = (callback) => {
native.DatabaseSync.prototype.setAuthorizer.call(database, callback);
owner.authorizerActive = callback !== null;
invalidate(owner);
};
registerNodeSqliteDisposeCallback(database, () => {
invalidate(owner);
owner.dataVersion = void 0;
owner.readDataVersion = void 0;
if (owner.scope) {
scopes.finalizer.unregister(owner);
scopes.release(owner.scope);
owner.scope = void 0;
owner.scopeRevision = void 0;
}
});
}
/** Foreign commits are observed on the next operation; SQLite owns snapshot visibility. */
function readSqliteCacheDataVersion(database) {
const tracked = owners$1.get(database);
const owner = tracked?.admitted ? tracked : void 0;
if (owner && !owner.authorizerActive && owner.readDataVersion !== void 0) return owner.readDataVersion;
const row = executeWithCachedStatement(database, "PRAGMA data_version", [], (statement) => statement.get());
if (typeof row?.data_version !== "number") throw new Error("SQLite did not return a numeric PRAGMA data_version");
if (owner) {
if (owner.dataVersion !== row.data_version) {
const facts = owner.facts;
if (!(facts && runSqlitePinnedReadSnapshotSync(database, (schemaVersion) => {
const userVersion = executeWithCachedStatement(database, "PRAGMA user_version", [], (s) => s.get());
return facts.schemaVersion === schemaVersion && facts.userVersion === userVersion?.user_version;
}))) invalidate(owner);
owner.dataVersion = row.data_version;
}
if (owner.readDepth > 0 && !owner.authorizerActive) owner.readDataVersion = row.data_version;
}
return row.data_version;
}
/** Install at native open, before callers can retain statements or install an authorizer. */
function trackSqliteSchema(database, native) {
if (!owners$1.has(database)) {
const owner = {
admitted: false,
revision: 0,
readDepth: 0,
transactionalSchema: false,
transactionalFacts: false,
authorizerActive: false
};
owners$1.set(database, owner);
trackSchemaChanges(database, owner, native);
}
}
/** Only database admission opts a connection into retained schema facts. */
function admitSqliteSchema(database) {
const owner = owners$1.get(database);
if (!owner) throw new Error("SQLite schema admission requires a connection tracked from native open");
owner.admitted = true;
getAdmittedSqliteSchemaFacts(database);
}
/** Schema changes revoke the admission; ordinary reads consume its recorded facts. */
function getAdmittedSqliteSchemaFacts(database) {
const owner = owners$1.get(database);
if (!owner?.admitted || owner.authorizerActive) return;
readSqliteCacheDataVersion(database);
const snapshot = getSqlitePinnedReadSnapshot(database);
if (owner.snapshot && owner.snapshot !== snapshot) {
invalidate(owner);
owner.snapshot = void 0;
}
const scope = bindScope(database, owner);
if (owner.scopeRevision !== scope.revision) {
invalidate(owner);
owner.scopeRevision = scope.revision;
}
if ((owner.transactionalSchema || owner.transactionalFacts) && !database.isTransaction) {
if (owner.transactionalSchema) publishSchemaChange(database, owner);
invalidate(owner);
owner.transactionalSchema = false;
owner.transactionalFacts = false;
}
if (!owner.facts) {
owner.snapshot = snapshot;
owner.transactionalFacts = database.isTransaction;
owner.facts = runSqlitePinnedReadSnapshotSync(database, (schemaVersion) => {
const userVersion = executeWithCachedStatement(database, "PRAGMA user_version", [], (s) => s.get());
const tables = executeWithCachedStatement(database, "SELECT name, sql FROM main.sqlite_schema WHERE type = 'table'", [], (s) => s.all());
return {
revision: owner.revision,
userVersion: Number(userVersion?.user_version ?? 0),
schemaVersion,
tables: new Set(tables.flatMap((row) => typeof row.name === "string" ? [row.name] : [])),
tableSql: new Map(tables.flatMap((row) => typeof row.name === "string" ? [[row.name, typeof row.sql === "string" ? row.sql : null]] : []))
};
});
}
return owner.facts;
}
var scopes, owners$1, transactionControlPrefix;
var init_sqlite_schema_facts = __esmMin((() => {
init_global_singleton();
init_kysely_sync_cache_state();
init_sqlite_pinned_read_snapshot();
init_sqlite_schema_sql();
init_sqlite_worker_identity();
scopes = resolveGlobalSingleton(Symbol.for("openclaw.sqliteSchemaScopes"), () => {
const byIdentity = /* @__PURE__ */ new Map();
const release = (scope) => {
scope.users -= 1;
if (scope.users === 0 && scope.key && byIdentity.get(scope.key) === scope) byIdentity.delete(scope.key);
};
return {
byIdentity,
release,
finalizer: new FinalizationRegistry(release)
};
});
owners$1 = resolveGlobalSingleton(Symbol.for("openclaw.sqliteSchemaFacts"), () => /* @__PURE__ */ new WeakMap());
transactionControlPrefix = /^(?:\s|;|--[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*\*\/)*(BEGIN|SAVEPOINT|COMMIT|END|RELEASE|ROLLBACK)\b/i;
}));
//#endregion
//#region src/infra/warning-filter.ts
function shouldIgnoreWarning(warning) {
return Boolean(warning.code === "DEP0040" && warning.message?.includes("punycode") || warning.code === "DEP0060" && warning.message?.includes("util._extend") || warning.name === "ExperimentalWarning" && warning.message?.includes("SQLite is an experimental feature"));
}
function normalizeWarningArgs(args) {
const warningArg = args[0];
const secondArg = args[1];
const thirdArg = args[2];
let name;
let code;
let message;
if (warningArg instanceof Error) {
name = warningArg.name;
message = warningArg.message;
code = warningArg.code;
} else if (typeof warningArg === "string") message = warningArg;
if (secondArg && typeof secondArg === "object" && !Array.isArray(secondArg)) {
const options = secondArg;
if (typeof options.type === "string") name = options.type;
if (typeof options.code === "string") code = options.code;
} else {
if (typeof secondArg === "string") name = secondArg;
if (typeof thirdArg === "string") code = thirdArg;
}
return {
name,
code,
message
};
}
/** Installs the global process warning filter once for the current JS realm. */
function installProcessWarningFilter() {
const state = resolveGlobalSingleton(warningFilterKey, () => ({ installed: false }));
if (state.installed) return;
const originalEmitWarning = process.emitWarning.bind(process);
const wrappedEmitWarning = ((...args) => {
if (shouldIgnoreWarning(normalizeWarningArgs(args))) return;
if (args[0] instanceof Error && args[1] && typeof args[1] === "object" && !Array.isArray(args[1])) {
const warning = args[0];
const emitted = Object.assign(new Error(warning.message), {
name: warning.name,
code: warning.code
});
process.emit("warning", emitted);
return;
}
Reflect.apply(originalEmitWarning, process, args);
});
process.emitWarning = wrappedEmitWarning;
state.installed = true;
}
var warningFilterKey;
var init_warning_filter = __esmMin((() => {
init_global_singleton();
warningFilterKey = Symbol.for("openclaw.warning-filter");
}));
//#endregion
//#region src/infra/node-sqlite.ts
function resolveSqliteFilesystemPath(pathname) {
if (process.platform !== "win32") return pathname;
return path.toNamespacedPath(path.resolve(pathname));
}
function resolveNodeSqliteLocation(location) {
if (location === "" || location === ":memory:" || location.startsWith("file:")) return location;
return resolveSqliteFilesystemPath(location);
}
/** Preserve native Windows path prefixes before adding SQLite URI parameters. */
function resolveSqliteFileUriPath(pathname, platform) {
if (platform === "win32") {
const namespacedPath = path.win32.toNamespacedPath(path.win32.resolve(pathname));
return `file:${encodeURIComponent(namespacedPath)}`;
}
return pathToFileURL(path.resolve(pathname)).href;
}
/** Open an existing writable database without SQLite's create-if-missing flag. */
function resolveExistingSqliteFileUri(pathname, platform = process.platform) {
return `${resolveSqliteFileUriPath(pathname, platform)}?mode=rw`;
}
function assertSqliteWalResetSafeVersion(version, nodeVersion) {
if (isSqliteWalResetSafeVersion(version)) return;
const variables = process.config?.variables;
const isShared = variables?.node_shared_sqlite === true || variables?.node_shared_sqlite === "true";
throw new Error(`OpenClaw requires SQLite 3.51.3+, 3.50.7+ within 3.50.x, or 3.44.6+ within 3.44.x for WAL safety; Node ${nodeVersion} ${isShared ? "uses shared system" : "embeds"} SQLite ${version}, which is affected by the upstream WAL-reset database corruption bug. ${isShared ? "Upgrade the system SQLite library to one of those safe versions, or use a Node build embedding a safe version." : "Upgrade to Node 24.16.0+ or 26.1.0+ before retrying."}`);
}
function assertSafeSqliteRuntime(sqlite) {
if (validatedSqliteModule === sqlite) return;
const database = new sqlite.DatabaseSync(":memory:");
try {
const row = database.prepare("SELECT sqlite_version() AS version").get();
const version = typeof row?.version === "string" ? row.version : "unknown";
assertSqliteWalResetSafeVersion(version, process.versions.node);
jsonbSupported = (compareValidSemver(version, "3.45.0") ?? -1) >= 0;
extensionLoadingSupported = database.prepare("SELECT sqlite_compileoption_used('OMIT_LOAD_EXTENSION') AS omitted").get()?.omitted === 0;
validatedSqliteModule = sqlite;
} finally {
database.close();
}
}
/** Load node:sqlite after installing the process warning filter. */
function requireNodeSqlite() {
installProcessWarningFilter();
try {
ensureSqliteLibrarySelected();
const sqlite = require$1("node:sqlite");
assertSafeSqliteRuntime(sqlite);
return sqlite;
} catch (err) {
const message = formatErrorMessage(err);
throw new Error(`SQLite support is unavailable or unsafe in this Node runtime. ${message}`, { cause: err });
}
}
/** Open node:sqlite through OpenClaw's runtime and filesystem-location boundary. */
function openNodeSqliteDatabase(location, options) {
const sqlite = requireNodeSqlite();
const resolvedLocation = resolveNodeSqliteLocation(location);
const database = options === void 0 ? new sqlite.DatabaseSync(resolvedLocation) : new sqlite.DatabaseSync(resolvedLocation, options);
trackSqliteSchema(database, sqlite);
registerSqliteReaderConnection(database);
return database;
}
var require$1, validatedSqliteModule, extensionLoadingSupported, jsonbSupported;
var init_node_sqlite = __esmMin((() => {
init_bun_sqlite_library();
init_errors$2();
init_semver();
init_sqlite_reader_lifecycle();
init_sqlite_runtime_version();
init_sqlite_schema_facts();
init_warning_filter();
require$1 = createRequire(import.meta.url);
}));
//#endregion
//#region src/infra/sqlite-error-diagnostics.ts
function markSqliteNativeOpenFailure(error) {
if (error !== null && typeof error === "object") nativeOpenFailures.add(error);
}
/** Record the native effect without changing its error or tagging surrounding authority checks. */
function withSqliteNativeOpen(open) {
try {
return open();
} catch (error) {
markSqliteNativeOpenFailure(error);
throw error;
}
}
function markSqliteInspectionOperation(error, operation) {
if (error !== null && typeof error === "object" && !inspectionOperations.has(error)) inspectionOperations.set(error, operation);
return error;
}
function sqliteErrorCode(error) {
const code = asOptionalObjectRecord(error)?.code;
return typeof code === "string" ? code : void 0;
}
function sqliteExtendedResultCode(error) {
const errcode = asOptionalObjectRecord(error)?.errcode;
return typeof errcode === "number" && Number.isInteger(errcode) ? errcode : void 0;
}
function sqlitePrimaryResultCode(error) {
const errcode = sqliteExtendedResultCode(error);
return errcode === void 0 ? void 0 : errcode & SQLITE_PRIMARY_RESULT_CODE_MASK;
}
function isSqliteLockError(error) {
const code = sqliteErrorCode(error);
if (code !== void 0 && SQLITE_LOCK_ERROR_CODES.has(code)) return true;
const primaryCode = sqlitePrimaryResultCode(error);
return primaryCode === SQLITE_BUSY_RESULT_CODE || primaryCode === SQLITE_LOCKED_RESULT_CODE;
}
/** Report proven file damage (corrupt page or non-database header), not transient failure. */
function isSqliteCorruptionError(error) {
const primaryCode = sqlitePrimaryResultCode(error);
return primaryCode === SQLITE_CORRUPT_RESULT_CODE || primaryCode === SQLITE_NOTADB_RESULT_CODE;
}
var inspectionOperations, nativeOpenFailures, SQLITE_LOCK_ERROR_CODES, SQLITE_BUSY_RESULT_CODE, SQLITE_LOCKED_RESULT_CODE, SQLITE_CORRUPT_RESULT_CODE, SQLITE_NOTADB_RESULT_CODE, SQLITE_PRIMARY_RESULT_CODE_MASK;
var init_sqlite_error_diagnostics = __esmMin((() => {
init_record_coerce();
init_global_singleton();
inspectionOperations = resolveGlobalSingleton(Symbol.for("openclaw.sqliteInspectionOperations"), () => /* @__PURE__ */ new WeakMap());
nativeOpenFailures = resolveGlobalSingleton(Symbol.for("openclaw.sqliteNativeOpenFailures"), () => /* @__PURE__ */ new WeakSet());
SQLITE_LOCK_ERROR_CODES = /* @__PURE__ */ new Set(["SQLITE_BUSY", "SQLITE_LOCKED"]);
SQLITE_BUSY_RESULT_CODE = 5;
SQLITE_LOCKED_RESULT_CODE = 6;
SQLITE_CORRUPT_RESULT_CODE = 11;
SQLITE_NOTADB_RESULT_CODE = 26;
SQLITE_PRIMARY_RESULT_CODE_MASK = 255;
}));
//#endregion
//#region src/infra/file-descriptor.ts
/** Strict field equality; callers own any platform-specific identity tolerance. */
function sameFileMutationFingerprint(left, right) {
return left.birthtimeNs === right.birthtimeNs && left.ctimeNs === right.ctimeNs && left.dev === right.dev && left.ino === right.ino && left.mtimeNs === right.mtimeNs && left.size === right.size;
}
/** Maps the borrowed-descriptor digest to OpenClaw's persisted artifact fields. */
function hashFileDescriptorSync(fd, maxBytes) {
const { digest, bytes } = sha256FileSync(fd, { maxBytes });
return {
sha256: digest,
sizeBytes: bytes
};
}
var init_file_descriptor = __esmMin((() => {}));
//#endregion
//#region src/infra/sqlite-file-generation.ts
function assertRegularFile(stat) {
if (!stat.isFile()) throw new Error("SQLite generation target must be a regular file");
}
function sameFileState(left, right) {
return sameFileIdentity(left, right) && left.birthtimeNs === right.birthtimeNs && left.ctimeNs === right.ctimeNs && left.mtimeNs === right.mtimeNs && left.size === right.size;
}
function fingerprintFile(pathname) {
const fd = fs.openSync(pathname, "r");
try {
const before = fs.fstatSync(fd, { bigint: true });
assertRegularFile(before);
const { sha256 } = hashFileDescriptorSync(fd);
const after = fs.fstatSync(fd, { bigint: true });
const current = fs.statSync(pathname, { bigint: true });
if (!sameFileState(before, after) || !sameFileState(after, current)) throw new Error(`SQLite generation target changed while hashing: ${pathname}`);
return {
birthtimeNs: after.birthtimeNs,
ctimeNs: after.ctimeNs,
dev: after.dev,
ino: after.ino,
mtimeNs: after.mtimeNs,
sha256,
size: after.size
};
} finally {
fs.closeSync(fd);
}
}
function readOptionalFile(pathname) {
try {
return fingerprintFile(pathname);
} catch (error) {
if (error.code === "ENOENT") return;
throw error;
}
}
function readGeneration(pathname) {
const database = fingerprintFile(pathname);
const journal = readOptionalFile(`${pathname}-journal`);
const wal = readOptionalFile(`${pathname}-wal`);
return {
database,
...journal ? { journal } : {},
...wal ? { wal } : {}
};
}
function readStableSqliteFileGeneration(pathname) {
const first = readGeneration(pathname);
const second = readGeneration(pathname);
if (!sameSqliteFileGeneration(first, second)) throw new Error(`SQLite file generation changed while reading: ${pathname}`);
return second;
}
function sameFileFingerprint(left, right) {
return sameFileMutationFingerprint(left, right) && left.sha256 === right.sha256;
}
function sameOptionalFileFingerprint(left, right) {
return left === void 0 ? right === void 0 : right !== void 0 && sameFileFingerprint(left, right);
}
function sameSqliteFileGeneration(left, right) {
return sameFileFingerprint(left.database, right.database) && sameOptionalFileFingerprint(left.journal, right.journal) && sameOptionalFileFingerprint(left.wal, right.wal);
}
function parseFileFingerprint(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("SQLite file fingerprint must be an object");
const fingerprint = value;
for (const field of [
"birthtimeNs",
"ctimeNs",
"dev",
"ino",
"mtimeNs",
"size"
]) if (typeof fingerprint[field] !== "string" || !/^-?\d+$/u.test(fingerprint[field])) throw new Error(`SQLite file fingerprint ${field} is invalid`);
if (typeof fingerprint.sha256 !== "string" || !/^[a-f0-9]{64}$/u.test(fingerprint.sha256)) throw new Error("SQLite file fingerprint sha256 is invalid");
return {
birthtimeNs: BigInt(fingerprint.birthtimeNs),
ctimeNs: BigInt(fingerprint.ctimeNs),
dev: BigInt(fingerprint.dev),
ino: BigInt(fingerprint.ino),
mtimeNs: BigInt(fingerprint.mtimeNs),
sha256: fingerprint.sha256,
size: BigInt(fingerprint.size)
};
}
function parseSqliteFileGeneration(serialized) {
const value = JSON.parse(serialized);
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("SQLite file generation must be an object");
const generation = value;
return {
database: parseFileFingerprint(generation.database),
...generation.journal === void 0 ? {} : { journal: parseFileFingerprint(generation.journal) },
...generation.wal === void 0 ? {} : { wal: parseFileFingerprint(generation.wal) }
};
}
var init_sqlite_file_generation = __esmMin((() => {
init_file_descriptor();
}));
//#endregion
//#region src/infra/sqlite-integrity.ts
/** Require structural, table/index, and referential consistency before trusting a database. */
function assertSqliteIntegrity(database, databaseLabel, check = "integrity_check", tables, timing) {
if (tables) {
if (timing) timing.tables = [];
for (const entry of tables) {
const startedAt = performance$1.now();
try {
runSqliteCheck(database, databaseLabel, entry.check, entry.table);
runSqliteForeignKeyCheck(database, databaseLabel, entry.table);
} finally {
timing?.tables?.push({
...entry,
elapsedMs: Math.floor(performance$1.now() - startedAt)
});
}
}
return { integrityCheck: "ok" };
}
const integrityCheck = runSqliteCheck(database, databaseLabel, check);
runSqliteForeignKeyCheck(database, databaseLabel);
return { integrityCheck };
}
function runSqliteCheck(database, databaseLabel, pragma, tableName) {
const argument = tableName ? `('${tableName.replaceAll("'", "''")}')` : "";
let rows;
try {
rows = database.prepare(`PRAGMA ${pragma}${argument};`).all();
} catch (error) {
throw createSqliteIntegrityError(`SQLite ${pragma} failed for ${databaseLabel}: ${error instanceof Error ? error.message : String(error)}`, error);
}
const results = rows.map((row) => row[pragma] ?? Object.values(row)[0]);
if (results.length === 1 && results[0] === "ok") return "ok";
throw createSqliteIntegrityError(`SQLite ${pragma} failed for ${databaseLabel}: ${results.map((result) => String(result)).join("; ") || "no result"}. Run openclaw doctor --fix for explicit repair; if repair is refused, preserve the database and WAL and restore a verified backup.`);
}
function runSqliteForeignKeyCheck(database, databaseLabel, table) {
let violationCount = 0;
let repairable = true;
let taskDeliveryForeignKeyId;
const violations = [];
try {
const argument = table ? `('${table.replaceAll("'", "''")}')` : "";
const statement = database.prepare(`PRAGMA foreign_key_check${argument};`);
statement.setReadBigInts(true);
for (const violation of statement.iterate()) {
violationCount += 1;
retainSortedForeignKeyViolation(violations, violation);
if (repairable) {
if (violation.table === "task_delivery_state" && violation.parent === "task_runs") {
taskDeliveryForeignKeyId ??= readTaskDeliveryCascadeForeignKeyId(database);
repairable = violation.fkid === taskDeliveryForeignKeyId;
} else repairable = false;
}
}
} catch (error) {
throw createSqliteIntegrityError(`SQLite foreign_key_check failed for ${databaseLabel}: ${error instanceof Error ? error.message : String(error)}`, error);
}
if (violations.length === 0) return;
if (repairable) throw new SqliteRepairableForeignKeyError(databaseLabel, violationCount);
const details = violations.map(formatSqliteForeignKeyViolation);
if (violationCount > MAX_REPORTED_FOREIGN_KEY_VIOLATIONS) details.push("additional violations omitted");
throw createSqliteIntegrityError(`SQLite foreign_key_check failed for ${databaseLabel}: ${details.join("; ")}`);
}
function readTaskDeliveryCascadeForeignKeyId(database) {
const statement = database.prepare("PRAGMA foreign_key_list(task_delivery_state);");
statement.setReadBigInts(true);
const foreignKeys = statement.all();
const taskKey = foreignKeys.find((key) => key.table === "task_runs" && key.from === "task_id" && key.to === "task_id" && key.on_delete === "CASCADE");
return taskKey && typeof taskKey.id === "bigint" && foreignKeys.filter((key) => key.id === taskKey.id).length === 1 ? taskKey.id : void 0;
}
function createSqliteIntegrityError(message, cause) {
const error = cause === void 0 ? new Error(message) : new Error(message, { cause });
error.name = "SqliteIntegrityError";
return error;
}
function retainSortedForeignKeyViolation(retained, violation) {
retained.push(violation);
retained.sort(compareSqliteForeignKeyViolations);
if (retained.length > MAX_REPORTED_FOREIGN_KEY_VIOLATIONS) retained.pop();
}
function compareSqliteForeignKeyViolations(left, right) {
const tableOrder = Buffer.compare(Buffer.from(left.table), Buffer.from(right.table));
if (tableOrder !== 0) return tableOrder;
if (left.rowid === null || right.rowid === null) {
if (left.rowid !== right.rowid) return left.rowid === null ? -1 : 1;
} else if (left.rowid !== right.rowid) return left.rowid < right.rowid ? -1 : 1;
const parentOrder = Buffer.compare(Buffer.from(left.parent), Buffer.from(right.parent));
if (parentOrder !== 0) return parentOrder;
if (left.fkid === right.fkid) return 0;
return left.fkid < right.fkid ? -1 : 1;
}
function formatSqliteForeignKeyViolation(violation) {
const row = violation.rowid === null ? "row without rowid" : `row ${violation.rowid.toString()}`;
return `${violation.table} ${row} references ${violation.parent} (foreign key ${violation.fkid.toString()})`;
}
var MAX_REPORTED_FOREIGN_KEY_VIOLATIONS, SqliteRepairableForeignKeyError;
var init_sqlite_integrity = __esmMin((() => {
init_node_sqlite();
init_sqlite_error_diagnostics();
init_sqlite_file_generation();
MAX_REPORTED_FOREIGN_KEY_VIOLATIONS = 5;
SqliteRepairableForeignKeyError = class extends Error {
constructor(databaseLabel, orphanCount) {
super(`SQLite foreign_key_check failed for ${databaseLabel}: repairable task_delivery_state.task_id references task_runs.task_id cascade-owned orphans (${orphanCount} rows). Run openclaw doctor --fix to migrate this legacy state before retrying.`);
this.name = "SqliteRepairableForeignKeyError";
this.repair = {
kind: "task-delivery-orphans",
relation: "task_delivery_state.task_id",
parentTable: "task_runs",
orphanCount
};
}
};
}));
//#endregion
//#region src/infra/sqlite-schema-contract-assembly.ts
function createSqliteTableContract(tableName, table, tableList, indexes, triggers) {
const normalizedTriggers = triggers.map((trigger) => ({
name: trigger.name,
sql: normalizeSchemaSql(trigger.sql)
}));
const normalizedTableSql = table.sql?.startsWith("CREATE TABLE ") ? null : normalizeSchemaSql(table.sql);
const isVirtualTable = normalizedTableSql !== null && /^CREATE VIRTUAL TABLE /iu.test(normalizedTableSql);
return {
definition: isVirtualTable ? null : parseSqliteTableDefinition(table.sql, tableName),
indexes,
strict: tableList.strict,
triggers: normalizedTriggers,
virtualTableSql: isVirtualTable ? normalizedTableSql : null,
withoutRowid: tableList.wr
};
}
function createSqliteIndexContract(index, schemaSql, rows) {
const terms = rows.map(({ cid, coll, desc, key, name, seqno }) => ({
coll,
desc,
key,
kind: sqliteIndexTermKind(cid),
name,
seqno
}));
return {
name: index.name.startsWith("sqlite_autoindex_") ? null : index.name,
origin: index.origin,
partial: index.partial,
sql: normalizeSchemaSql(schemaSql),
terms,
unique: index.unique
};
}
function sqliteIndexTermKind(cid) {
return cid === -2 ? "expression" : cid === -1 ? "rowid" : "column";
}
function parseSqliteTableDefinition(sql, tableName) {
if (sql === null) throw new Error(`Could not inspect SQLite table definition for ${tableName}.`);
const open = findSqlCharacter(sql, "(");
if (open === -1) throw new Error(`SQLite table ${tableName} has no column definition.`);
const close = findSqlClosingParenthesis(sql, open);
const columns = /* @__PURE__ */ new Map();
const constraints = [];
for (const rawDefinition of splitSqlList(sql.slice(open + 1, close))) {
const definition = normalizeSqlWhitespace(rawDefinition);
if (!definition) continue;
const token = readSqlToken(definition, 0);
if (!token) throw new Error(`SQLite table ${tableName} contains an unreadable definition.`);
if (readTableConstraintKeyword(definition, token)) {
constraints.push(definition);
continue;
}
const columnName = normalizeSqlIdentifier(token.raw);
if (columns.has(columnName)) throw new Error(`SQLite table ${tableName} contains duplicate column ${columnName}.`);
columns.set(columnName, definition);
}
return {
columns: new Map([...columns].toSorted(([left], [right]) => left.localeCompare(right))),
constraints: constraints.toSorted()
};
}
var init_sqlite_schema_contract_assembly = __esmMin((() => {
init_sqlite_schema_sql();
}));
//#endregion
//#region src/infra/sqlite-schema-issues.ts
function defaultIssueMessage(code, objectName) {
const tableName = objectName.split(".", 1)[0];
switch (code) {
case "missing-table": return `missing table ${objectName}`;
case "missing-column":
case "unexpected-column":
case "column-definition-drift": return `column definitions differ for ${tableName}`;
case "table-constraint-drift": return `table constraints differ for ${objectName}`;
case "table-definition-drift": return `table definition differs for ${objectName}`;
case "missing-or-drifted-index": return `missing or drifted index ${objectName}`;
case "unexpected-unique-index": return `unexpected unique index ${objectName}`;
case "missing-or-drifted-trigger": return `missing or drifted trigger ${objectName}`;
case "unexpected-trigger": return `unexpected trigger ${objectName}`;
case "virtual-table-definition-drift": return `virtual table definition differs for ${objectName}`;
case "table-options-drift": return `table options differ for ${objectName}`;
}
throw new Error("Unsupported SQLite schema issue code", { cause: code });
}
function createSqliteSchemaIssue(code, objectName, message) {
return {
code,
objectName,
message: message ?? defaultIssueMessage(code, objectName)
};
}
function legacySqliteSchemaIssueMessages(issues) {
const isColumnIssue = (issue) => issue.code === "column-definition-drift" || issue.code === "missing-column" || issue.code === "unexpected-column";
const columnIssueTables = new Set(issues.filter(isColumnIssue).map((issue) => issue.objectName.split(".", 1)[0]));
return [...new Set(issues.filter((issue) => issue.code !== "table-constraint-drift" || !columnIssueTables.has(issue.objectName)).map((issue) => issue.message))];
}
function throwSqliteSchemaMismatches(databaseLabel, mismatches) {
const shown = mismatches.slice(0, 8);
if (mismatches.length > shown.length) shown.push(`${mismatches.length - shown.length} additional mismatch(es)`);
throw new SqliteSchemaMismatchError(`SQLite schema is incomplete or noncanonical for ${databaseLabel}: ${shown.join("; ")}; run openclaw doctor --fix to repair it.`);
}
var SqliteSchemaMismatchError;
var init_sqlite_schema_issues = __esmMin((() => {
SqliteSchemaMismatchError = class extends Error {
constructor(..._args) {
super(..._args);
this.name = "SqliteSchemaMismatchError";
}
};
}));
//#endregion
//#region src/infra/sqlite-schema-contract.ts
/** Reuse actual table facts only within one unchanged read transaction on this connection. */
function createSqliteTableContractReader(database) {
const tables = /* @__PURE__ */ new Map();
return (tableName) => {
if (!tables.has(tableName)) tables.set(tableName, collectSqliteTableContract(database, tableName));
return tables.get(tableName);
};
}
/**
* Require every object from one committed schema while allowing unrelated
* tables and indexes that do not replace a canonical object.
*/
function assertSqliteSchemaContains(database, databaseLabel, schemaSql, compatibility = {}, readTable) {
const issues = collectSqliteSchemaIssues(database, schemaSql, compatibility, readTable);
if (issues.length > 0) throwSqliteSchemaMismatches(databaseLabel, legacySqliteSchemaIssueMessages(issues));
}
/** Collect stable, machine-readable differences from one committed schema. */
function collectSqliteSchemaIssues(database, schemaSql, compatibility = {}, readTable) {
return runSqlitePinnedReadSnapshotSync(database, () => collectSqliteSchemaIssuesInSnapshot(database, schemaSql, compatibility, readTable));
}
function collectSqliteSchemaIssuesInSnapshot(database, schemaSql, compatibility, readTable) {
const expected = getSqliteSchemaContract(schemaSql);
const allowedMissingTables = new Set(compatibility.allowedMissingTables ?? []);
const allowedMissingIndexes = new Set(compatibility.allowedMissingIndexes ?? []);
const issues = [];
const add = (code, objectName, message) => {
issues.push(createSqliteSchemaIssue(code, objectName, message));
};
for (const [tableName, expectedTable] of expected) {
const actualTable = readTable ? readTable(tableName) : collectSqliteTableContract(database, tableName);
if (!actualTable) {
if (allowedMissingTables.has(tableName)) continue;
add("missing-table", tableName);
continue;
}
issues.push(...compareTableDefinitions(tableName, actualTable.definition, expectedTable.definition, compatibility, !allowedMissingTables.has(tableName)));
const actualIndexFingerprints = new Set(actualTable.indexes.map((index) => JSON.stringify(index)));
const expectedIndexFingerprints = /* @__PURE__ */ new Set();
for (const expectedIndex of expectedTable.indexes) {
const fingerprint = JSON.stringify(expectedIndex);
expectedIndexFingerprints.add(fingerprint);
if (!actualIndexFingerprints.has(fingerprint)) {
const objectName = expectedIndex.name ?? tableName;
if (expectedIndex.name && allowedMissingIndexes.has(expectedIndex.name) && !database.prepare("SELECT 1 FROM main.sqlite_schema WHERE type = 'index' AND name = ? COLLATE NOCASE LIMIT 1").get(expectedIndex.name)) continue;
add("missing-or-drifted-index", objectName, `missing or drifted index ${expectedIndex.name ?? `on ${tableName}`}`);
}
}
for (const actualIndex of actualTable.indexes) if (actualIndex.unique === 1 && !expectedIndexFingerprints.has(JSON.stringify(actualIndex))) add("unexpected-unique-index", actualIndex.name ?? tableName, `unexpected unique index ${actualIndex.name ?? `on ${tableName}`}`);
const optionalCanonicalTriggerGroups = collectOptionalCanonicalTriggerGroups(database, compatibility, tableName);
const optionalCanonicalTriggers = optionalCanonicalTriggerGroups.flatMap((group) => group.triggers);
const allowedMissingCanonicalTriggers = optionalCanonicalTriggerGroups.filter((group) => group.optional).flatMap((group) => group.triggers);
for (const expectedTrigger of expectedTable.triggers) {
if (allowedMissingCanonicalTriggers.some((canonicalTrigger) => canonicalTrigger.name === expectedTrigger.name)) continue;
if (!containsTrigger(actualTable.triggers, expectedTrigger)) add("missing-or-drifted-trigger", expectedTrigger.name);
}
for (const triggerGroup of optionalCanonicalTriggerGroups) {
const isPresent = actualTable.triggers.some((actualTrigger) => triggerGroup.triggers.some((canonicalTrigger) => actualTrigger.name === canonicalTrigger.name));
if (triggerGroup.optional && !isPresent) continue;
for (const canonicalTrigger of triggerGroup.triggers) if (!containsTrigger(actualTable.triggers, canonicalTrigger)) add("missing-or-drifted-trigger", canonicalTrigger.name);
}
for (const actualTrigger of actualTable.triggers) if (!containsTrigger(expectedTable.triggers, actualTrigger) && !containsTrigger(optionalCanonicalTriggers, actualTrigger)) add("unexpected-trigger", actualTrigger.name);
if (actualTable.virtualTableSql !== expectedTable.virtualTableSql) add("virtual-table-definition-drift", tableName);
if (actualTable.strict !== expectedTable.strict || actualTable.withoutRowid !== expectedTable.withoutRowid) add("table-options-drift", tableName);
}
return issues;
}
/** Require stable canonical tables before a version-specific additive migration. */
function assertSqliteSchemaTablesPresent(database, databaseLabel, schemaSql, options = {}) {
const allowedMissingTables = new Set(options.allowedMissingTables ?? []);
const requiredTables = getCanonicalSqliteTableNames(schemaSql).filter((tableName) => !allowedMissingTables.has(tableName));
const missingTables = [];
const batchSize = 500;
for (let offset = 0; offset < requiredTables.length; offset += batchSize) {
const tables = requiredTables.slice(offset, offset + batchSize);
const expected = tables.map((_table, ordinal) => `(${ordinal}, ?)`).join(", ");
const present = database.prepare(`WITH expected(ordinal, name) AS (VALUES ${expected})
SELECT ordinal FROM expected
WHERE EXISTS (
SELECT 1 FROM main.sqlite_schema
WHERE type = 'table' AND name = expected.name LIMIT 1
)`).all(...tables);
const presentOrdinals = new Set(present.map((row) => row.ordinal));
for (const [ordinal, tableName] of tables.entries()) if (!presentOrdinals.has(ordinal)) missingTables.push(`missing table ${tableName}`);
}
if (missingTables.length > 0) throwSqliteSchemaMismatches(databaseLabel, missingTables);
}
/** Return every table owned by one committed schema. */
function getCanonicalSqliteTableNames(schemaSql) {
return [...getSqliteSchemaContract(schemaSql).keys()];
}
function collectOptionalCanonicalTriggerGroups(database, compatibility, tableName) {
return (compatibility.optionalCanonicalTriggerGroups ?? []).filter((group) => group.tableName === tableName).map((group) => ({
optional: !group.optionalWhenTableMissing || !database.prepare("SELECT 1 FROM main.sqlite_schema WHERE type = 'table' AND name = ? LIMIT 1").get(group.optionalWhenTableMissing),
triggers: group.triggers.map((trigger) => ({
name: trigger.name,
sql: normalizeOptionalCanonicalTriggerSql(trigger.sql)
}))
}));
}
function normalizeOptionalCanonicalTriggerSql(sql) {
return normalizeSchemaSql(sql)?.replace(/^(CREATE TRIGGER) main\./iu, "$1 ") ?? null;
}
function getSqliteSchemaContract(schemaSql) {
let expected = schemaContractCache.get(schemaSql);
if (!expected) {
expected = buildSqliteSchemaContract(schemaSql);
schemaContractCache.set(schemaSql, expected);
}
return expected;
}
function collectCanonicalSqliteFacts(database) {
const tableOptions = database.prepare("PRAGMA table_list").all();
if (tableOptions.some((row) => {
const name = row.name.toLowerCase();
return name === "pragma_index_list" || name === "pragma_index_xinfo";
})) return;
const indexes = database.prepare(`
SELECT CAST(t.rowid AS TEXT) AS table_id, i.seq AS index_seq,
i.name, i.origin, i.partial, i."unique", d.sql
FROM sqlite_schema AS t
CROSS JOIN pragma_index_list(t.name) AS i
LEFT JOIN sqlite_schema AS d ON d.type = 'index' AND d.name = i.name
WHERE t.type = 'table' AND t.name NOT LIKE 'sqlite_%'
`).all();
const terms = database.prepare(`
SELECT CAST(t.rowid AS TEXT) AS table_id, i.seq AS index_seq,
x.seqno, x.cid, x.name, x."desc", x.coll, x."key"
FROM sqlite_schema AS t
CROSS JOIN pragma_index_list(t.name) AS i
CROSS JOIN pragma_index_xinfo(i.name) AS x
WHERE t.type = 'table' AND t.name NOT LIKE 'sqlite_%'
ORDER BY t.rowid, i.seq, x.seqno
`).all();
const triggers = database.prepare(`
SELECT tbl_name, name, sql FROM sqlite_schema WHERE type = 'trigger' ORDER BY tbl_name, name
`).all();
return {
tableOptions,
indexes: groupCanonicalRows(indexes, (row) => row.table_id),
terms: groupCanonicalRows(terms, (row) => row.table_id),
triggers: groupCanonicalRows(triggers, (row) => row.tbl_name)
};
}
function groupCanonicalRows(rows, key) {
const groups = /* @__PURE__ */ new Map();
for (const row of rows) {
const name = key(row);
const group = groups.get(name);
if (group) group.push(row);
else groups.set(name, [row]);
}
return groups;
}
function buildSqliteSchemaContract(schemaSql) {
const database = openNodeSqliteDatabase(":memory:");
try {
database.exec(schemaSql);
const rows = database.prepare(`
SELECT CAST(rowid AS TEXT) AS table_id, name, sql
FROM sqlite_schema
WHERE type = 'table'
AND name NOT LIKE 'sqlite_%'
ORDER BY name
`).all();
if (rows.length === 0) return /* @__PURE__ */ new Map();
const facts = collectCanonicalSqliteFacts(database);
if (!facts) return new Map(rows.map((table) => [table.name, collectSqliteTableContractFromRow(database, table.name, table)]));
return new Map(rows.map((table) => {
const tableList = facts.tableOptions.find((entry) => entry.name === table.name);
if (!tableList) throw new Error(`Could not inspect SQLite table options for ${table.name}.`);
const termsByIndex = groupCanonicalRows(facts.terms.get(table.table_id) ?? [], (term) => term.index_seq);
const indexes = (facts.indexes.get(table.table_id) ?? []).map((index) => createSqliteIndexContract(index, index.sql, termsByIndex.get(index.index_seq) ?? [])).toSorted(compareJson);
return [table.name, createSqliteTableContract(table.name, table, tableList, indexes, facts.triggers.get(table.name) ?? [])];
}));
} finally {
database.close();
}
}
function collectSqliteTableContract(database, tableName) {
const table = executeWithCachedStatement(database, "SELECT name, sql FROM sqlite_schema WHERE type = 'table' AND name = ?", [tableName], (statement) => statement.get(tableName));
if (!table) return;
return collectSqliteTableContractFromRow(database, tableName, table);
}
function collectSqliteTableContractFromRow(database, tableName, table) {
const quotedTable = quoteSqliteIdentifier(tableName);
const tableList = database.prepare(`PRAGMA table_list(${quotedTable})`).all().find((entry) => entry.name === tableName);
if (!tableList) throw new Error(`Could not inspect SQLite table options for ${tableName}.`);
return createSqliteTableContract(tableName, table, tableList, database.prepare(`PRAGMA index_list(${quotedTable})`).all().map((index) => collectSqliteIndexContract(database, index)).toSorted(compareJson), executeWithCachedStatement(database, `
SELECT name, sql
FROM sqlite_schema
WHERE type = 'trigger' AND tbl_name = ?
ORDER BY name
`, [tableName], (statement) => statement.all(tableName)));
}
function compareTableDefinitions(tableName, actual, expected, compatibility, allowCompatibleAdditiveColumns) {
const issues = [];
const add = (code, objectName) => {
issues.push(createSqliteSchemaIssue(code, objectName));
};
if (!actual || !expected) {
if (actual !== expected) add("table-definition-drift", tableName);
return issues;
}
const allowedMissingColumns = new Set(compatibility.allowedMissingColumns ?? []);
for (const [columnName, definition] of actual.columns) if (!expected.columns.has(columnName)) {
if (allowCompatibleAdditiveColumns && compatibility.allowCompatibleAdditiveColumns && isCompatibleAdditiveColumnDefinition(definition)) continue;
add("unexpected-column", `${tableName}.${columnName}`);
}
for (const [columnName, expectedDefinition] of expected.columns) {
const objectName = `${tableName}.${columnName}`;
const actualDefinition = actual.columns.get(columnName);
if (actualDefinition === void 0) {
if (!allowedMissingColumns.has(objectName)) add("missing-column", objectName);
continue;
}
if (actualDefinition === expectedDefinition) continue;
if (!(compatibility.allowedColumnDefinitions?.[objectName] ?? []).some((definition) => normalizeSqlWhitespace(definition) === actualDefinition)) add("column-definition-drift", objectName);
}
if (JSON.stringify(actual.constraints) !== JSON.stringify(expected.constraints)) add("table-constraint-drift", tableName);
return issues;
}
function isCompatibleAdditiveColumnDefinition(definition) {
const name = readSqlToken(definition, 0);
const type = name ? readSqlToken(definition, name.end) : null;
return Boolean(type?.keyword && SQLITE_STRICT_DATATYPES.has(type.keyword) && definition.slice(type.end).trim().length === 0);
}
function collectSqliteIndexContract(database, index) {
const row = executeWithCachedStatement(database, "SELECT sql FROM sqlite_schema WHERE type = 'index' AND name = ?", [index.name], (statement) => statement.get(index.name));
const terms = database.prepare(`PRAGMA index_xinfo(${quoteSqliteIdentifier(index.name)})`).all();
return createSqliteIndexContract(index, typeof row?.sql === "string" ? row.sql : null, terms);
}
function containsTrigger(triggers, expected) {
return triggers.some((trigger) => trigger.name === expected.name && trigger.sql === expected.sql);
}
function compareJson(left, right) {
return JSON.stringify(left).localeCompare(JSON.stringify(right));
}
function readSqliteSchemaCookie(database) {
return database.prepare("PRAGMA schema_version").get()?.schema_version;
}
var schemaContractCache, SQLITE_STRICT_DATATYPES;
var init_sqlite_schema_contract = __esmMin((() => {
init_kysely_sync_cache_state();
init_node_sqlite();
init_sqlite_pinned_read_snapshot();
init_sqlite_schema_contract_assembly();
init_sqlite_schema_issues();
init_sqlite_schema_sql();
schemaContractCache = /* @__PURE__ */ new Map();
SQLITE_STRICT_DATATYPES = /* @__PURE__ */ new Set([
"ANY",
"BLOB",
"INT",
"INTEGER",
"REAL",
"TEXT"
]);
})), DOCTOR_OWNED_STATE_TABLES, FIRST_USE_STATE_TABLES, FIRST_USE_STATE_INDEXES, LAZY_ADDITIVE_STATE_TABLES, LAZY_ADDITIVE_STATE_INDEXES, OPENCLAW_DATABASE_SCHEMA_DOCS_URL;
var init_openclaw_state_db_contract = __esmMin((() => {
DOCTOR_OWNED_STATE_TABLES = ["agent_deletion_journal"];
FIRST_USE_STATE_TABLES = [
"user_profile_identities",
"local_workspace_projections",
"update_runs",
"session_repository_workspaces",
"github_repository_publication_requests",
"github_publication_session_lifecycles",
"skill_library_entries",
"skill_library_revisions",
"skill_library_events",
"skill_library_uploads",
"github_personal_publication_requests",
"cron_job_runtime_authorities",
"cron_run_trigger_state_retirements",
"execution_identity_contexts",
"mcp_oauth_pending_authorizations",
"node_worker_launch_containers",
"node_worker_launch_cleanup",
"node_worker_launches",
"node_worker_prepared_workspaces",
"node_worker_turns",
"operator_approval_execution_identities",
"operator_approval_standing_grants",
"operator_approval_standing_grant_generations",
"web_push_approval_deliveries",
"execution_decision_facts",
"execution_owner_lifecycle_bindings",
"outbound_message_execution_bindings",
"outbound_message_progress"
];
FIRST_USE_STATE_INDEXES = [
"idx_user_profile_identities_profile_id",
"idx_user_profile_identities_authorization",
"idx_update_runs_created",
"idx_update_runs_active",
"idx_github_repository_publication_shared_request",
"idx_github_repository_publication_personal_request",
"idx_github_personal_publication_owner_session",
"idx_github_personal_publication_pending",
"idx_node_worker_launches_terminal_completed",
"idx_node_worker_turns_terminal_completed",
"idx_node_worker_turns_active_owner",
"idx_operator_approval_standing_grants_binding",
"idx_web_push_approval_deliveries_subscription",
"execution_identity_contexts_run_created_idx",
"execution_decision_facts_context_occurred_idx",
"execution_decision_facts_run_occurred_idx",
"outbound_message_execution_bindings_execution_event_idx",
"outbound_message_progress_occurred_idx",
"outbound_message_progress_run_occurred_idx"
];
LAZY_ADDITIVE_STATE_TABLES = [
...FIRST_USE_STATE_TABLES,
"agent_provenance",
"cron_run_receipts",
"config_revision_keys",
"secret_store_entries",
"projects",
"worktree_templates",
"user_preferences",
"device_pair_setup_completions",
"github_publication_requests",
"device_pairing_join_codes",
"skill_workshop_proposal_events",
"skill_workshop_collection_reviews",
"skill_workshop_proposal_rollbacks",
"skill_workshop_proposals",
"worker_environment_ssh_fallback_ports",
"worker_session_placement_moves"
];
LAZY_ADDITIVE_STATE_INDEXES = [
...FIRST_USE_STATE_INDEXES,
"idx_cron_run_receipts_active_job",
"idx_cron_run_receipts_job_history",
"idx_github_publication_requests_pending",
"secret_store_entries_live_idx",
"idx_skill_workshop_collection_reviews_owner_time"
];
OPENCLAW_DATABASE_SCHEMA_DOCS_URL = "https://docs.openclaw.ai/reference/database-schemas";
}));
//#endregion
//#region src/infra/git-root.ts
function walkUpFrom(startDir, opts, resolveAtDir) {
let current = path.resolve(startDir);
for (let i = 0; opts.maxDepth === void 0 || i < opts.maxDepth; i += 1) {
const resolved = resolveAtDir(current);
if (resolved !== null && resolved !== void 0) return resolved;
const parent = path.dirname(current);
if (parent === current) break;
current = parent;
}
return null;
}
function resolveGitDirFromMarker(repoRoot) {
const gitPath = path.join(repoRoot, ".git");
try {
const stat = fs.statSync(gitPath);
if (stat.isDirectory()) return gitPath;
if (!stat.isFile()) return null;
const match = fs.readFileSync(gitPath, "utf-8").match(/gitdir:\s*(.+)/i);
if (!match?.[1]) return null;
return path.resolve(repoRoot, match[1].trim());
} catch {
return null;
}
}
function resolveGitHeadPath(startDir, opts = {}) {
return walkUpFrom(startDir, opts, (repoRoot) => {
const gitDir = resolveGitDirFromMarker(repoRoot);
return gitDir ? path.join(gitDir, "HEAD") : null;
});
}
/** Read at most `limit` bytes from Git or build metadata. */
function readGitMetadataPrefix(filePath, limit = 256) {
const fd = fs.openSync(filePath, "r");
try {
const buf = Buffer.alloc(limit);
const bytesRead = readFileWindowFullySync(fd, buf, 0);
return buf.subarray(0, bytesRead).toString("utf-8");
} finally {
fs.closeSync(fd);
}
}
function readGitHead(startDir, opts = {}) {
const headPath = resolveGitHeadPath(startDir, opts);
if (!headPath) return;
const head = fs.readFileSync(headPath, "utf-8").trim();
if (!head.startsWith("ref:")) return {
headPath,
ref: null,
value: head || null
};
const ref = head.replace(/^ref:\s*/i, "").trim();
const refsBase = resolveGitRefsBase(headPath);
return {
headPath,
ref,
value: readGitRefs(refsBase, [ref]).get(ref) ?? null,
refsBase
};
}
function resolveGitRefsBase(headPath) {
const gitDir = path.dirname(headPath);
try {
const commonDir = readGitMetadataPrefix(path.join(gitDir, "commondir")).trim();
if (commonDir) return path.resolve(gitDir, commonDir);
} catch (error) {
if (!isMissingPathError(error)) throw error;
}
return gitDir;
}
/** Raw ref contents, sharing one packed inventory across the requested names. */
function readGitRefs(refsBase, refs) {
const values = new Map(refs.map((ref) => [ref, null]));
const missing = /* @__PURE__ */ new Set();
for (const ref of refs) {
const refPath = resolveRefPath(refsBase, ref);
if (!refPath) continue;
try {
values.set(ref, readGitMetadataPrefix(refPath).trim());
} catch (error) {
if (!isMissingPathError(error)) throw error;
missing.add(ref);
}
}
if (missing.size === 0) return values;
try {
const packedRefs = fs.readFileSync(path.join(refsBase, "packed-refs"), "utf-8");
for (const line of packedRefs.split("\n")) {
if (!line || line.startsWith("#") || line.startsWith("^")) continue;
const [value, packedRef] = line.trim().split(/\s+/, 2);
if (packedRef && missing.delete(packedRef)) values.set(packedRef, value ?? null);
}
} catch (error) {
if (!isMissingPathError(error)) throw error;
}
return values;
}
/** Safely resolve a Git ref path, rejecting traversal from a crafted HEAD file. */
function resolveRefPath(refsBase, ref) {
if (!ref.startsWith("refs/")) return null;
if (path.isAbsolute(ref)) return null;
if (ref.split(/[/]/).includes("..")) return null;
const resolved = path.resolve(refsBase, ref);
const rel = path.relative(refsBase, resolved);
if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null;
return resolved;
}
var init_git_root = __esmMin((() => {
init_errors$2();
}));
//#endregion
//#region src/shared/async-work-scope.ts
/** Outside a managed scope, the returned promise remains the caller's responsibility. */
async function trackAsyncWork(run) {
const scope = currentWorkScope.getStore();
return await (scope ? scope.track(run) : run());
}
/** Runs under the context-free async root initialized before managed work can begin. */
function runInDetachedAsyncContext(run) {
return detachedAsyncContext.runInAsyncScope(run);
}
var currentWorkScope, currentWorkScopeAncestry, detachedAsyncContext, AsyncWorkScope;
var init_async_work_scope = __esmMin((() => {
init_global_singleton();
currentWorkScope = resolveGlobalSingleton(Symbol.for("openclaw.asyncWorkScope"), () => new AsyncLocalStorage());
currentWorkScopeAncestry = resolveGlobalSingleton(Symbol.for("openclaw.asyncWorkScopeAncestry"), () => new AsyncLocalStorage());
detachedAsyncContext = resolveGlobalSingleton(Symbol.for("openclaw.detachedAsyncContext"), () => new AsyncResource("openclaw.detached-async-context"));
AsyncWorkScope = class AsyncWorkScope {
constructor(failures) {
this.failures = failures;
this.pending = /* @__PURE__ */ new Set();
this.controller = new AbortController();
this.phase = "open";
}
get signal() {
return this.controller.signal;
}
get hasPendingWork() {
return this.pending.size > 0;
}
get isClosing() {
return this.phase !== "open";
}
enter(run) {
const owner = currentWorkScope.getStore();
const ancestry = currentWorkScopeAncestry.getStore();
const parent = owner ? ancestry?.scope === owner ? ancestry : { scope: owner } : void 0;
return currentWorkScopeAncestry.run({
scope: this,
parent
}, () => currentWorkScope.run(this, run));
}
/** Enters synchronous work without inspecting or assimilating its return value. */
run(run) {
if (this.phase === "closed") throw new Error("Async work scope is closed");
const operation = createDeferredCore();
this.pending.add(operation.promise);
try {
return this.enter(run);
} finally {
operation.resolve();
this.pending.delete(operation.promise);
}
}
track(run) {
if (this.phase === "closed") return Promise.reject(/* @__PURE__ */ new Error("Async work scope is closed"));
const operation = this.registerWork();
try {
operation.resolve(this.enter(run));
} catch (error) {
operation.reject(error);
}
return operation.promise;
}
registerWork() {
const operation = createDeferredCore();
this.pending.add(operation.promise);
operation.promise.then(() => this.pending.delete(operation.promise), (error) => {
this.pending.delete(operation.promise);
this.failures?.add(error);
});
return operation;
}
beginClose(reason) {
if (this.phase !== "open") return;
this.phase = "closing";
this.controller.abort(reason);
}
/** Starts the next phase in the same continuation that observes settled pending work. */
runWhenIdle(run) {
return AsyncWorkScope.runWhenAllIdle(() => [this], () => this.track(run));
}
/** Reselects owners so work admitted into a later phase is not mistaken for earlier work. */
static async runWhenAllIdle(selectScopes, run) {
let scopes = selectScopes();
while (scopes.some((scope) => scope.pending.size > 0)) {
await Promise.allSettled(scopes.flatMap((scope) => Array.from(scope.pending)));
scopes = selectScopes();
}
return run();
}
async drain() {
this.beginClose();
while (this.pending.size > 0) await Promise.allSettled(this.pending);
this.phase = "closed";
}
};
}));
//#endregion
//#region src/plugins/host-hook-cleanup-result.ts
/** Merge raw instance outcomes without duplicating their existing host or instance report. */
function appendPluginInstanceCleanupFailures(failures, pluginId, result) {
for (const error of result.errors) {
if (failures.some((failure) => failure.pluginId === pluginId && failure.error === error && (failure.hookId === "instance" || result.hostCleanupErrors?.includes(error)))) continue;
failures.push({
pluginId,
hookId: "instance",
error
});
}
}
var init_host_hook_cleanup_result = __esmMin((() => {}));
//#endregion
//#region src/plugins/plugin-cache-artifacts.ts
function createPluginCacheArtifacts() {
return {
moduleLoaders: /* @__PURE__ */ new Map(),
sources: /* @__PURE__ */ new Map(),
sourceAliases: /* @__PURE__ */ new Map(),
runtimeRecordRoots: /* @__PURE__ */ new WeakMap()
};
}
var init_plugin_cache_artifacts = __esmMin((() => {}));
//#endregion
//#region src/plugins/plugin-cache-sdk.ts
/** Derived SDK facts share the plugin cache lifetime; none owns a separate expiry. */
function createPluginCacheSdk() {
return {
hosts: /* @__PURE__ */ new Map(),
contexts: /* @__PURE__ */ new Map(),
packageNames: /* @__PURE__ */ new Map(),
packageSearches: /* @__PURE__ */ new Map(),
argvDirectories: /* @__PURE__ */ new Map(),
devSourceRoots: /* @__PURE__ */ new Map(),
runtimeModules: /* @__PURE__ */ new Map(),
usableDistArtifacts: /* @__PURE__ */ new Map(),
normalizedJitiAliases: /* @__PURE__ */ new Map(),
aliasFacts: /* @__PURE__ */ new WeakMap(),
native: {
sdkProviders: /* @__PURE__ */ new Map(),
nextSdkProviderOrder: 0,
aliases: /* @__PURE__ */ new Map(),
registeredHosts: /* @__PURE__ */ new Set(),
hostRoots: /* @__PURE__ */ new Map(),
nearestPackageRoots: /* @__PURE__ */ new Map(),
loaderPackageRoots: /* @__PURE__ */ new Map(),
allowedParentRoots: /* @__PURE__ */ new Map()
}
};
}
var init_plugin_cache_sdk = __esmMin((() => {})), PluginInstanceDrainTimeoutError;
var init_plugin_instance_error = __esmMin((() => {
init_global_singleton();
resolveGlobalSingleton(Symbol.for("openclaw.pluginSourceRecoveryUnavailableError"), () => class SourceRecoveryUnavailableError extends Error {
constructor(cause) {
super("Captured plugin source is missing; its previous code cannot be recovered.", { cause });
this.name = "PluginSourceRecoveryUnavailableError";
}
});
PluginInstanceDrainTimeoutError = resolveGlobalSingleton(Symbol.for("openclaw.pluginInstanceDrainTimeoutError"), () => class DrainTimeoutError extends Error {
constructor(message, settled, options, forcedRetirement) {
super(message, options);
this.settled = settled;
this.forcedRetirement = forcedRetirement;
this.name = "PluginInstanceDrainTimeoutError";
}
});
}));
//#endregion
//#region src/plugins/plugin-instance-invocation.ts
/** Copy core scopes through the current owner so runtime-only fields survive. */
function createPluginExecutionFrame(scopes, current) {
return current ? current.withScopes(scopes) : new InvocationFrame(scopes);
}
var InvocationFrame, pluginExecutionContext, getPluginExecutionFrame;
var init_plugin_instance_invocation = __esmMin((() => {
init_global_singleton();
InvocationFrame = class InvocationFrame {
constructor(scopes) {
this.invocation = scopes.invocation;
this.metadataScope = scopes.metadataScope;
this.cacheScope = scopes.cacheScope;
}
withScopes(scopes) {
return new InvocationFrame(scopes);
}
};
pluginExecutionContext = resolveGlobalSingleton(Symbol.for("openclaw.pluginInstanceInvocation"), () => {
const frames = new AsyncLocalStorage();
return {
invocation: {
getStore() {
return frames.getStore()?.invocation;
},
run(invocation, run) {
const current = frames.getStore();
return frames.run(current?.invocation === invocation ? current : createPluginExecutionFrame({
...current,
invocation
}, current), run);
},
exit(run) {
const current = frames.getStore();
return current?.invocation ? frames.run(current.withScopes({
...current,
invocation: void 0
}), run) : run();
}
},
getFrame() {
return frames.getStore();
},
runFrame(frame, run) {
return frames.run(frame, run);
}
};
});
pluginExecutionContext.invocation;
getPluginExecutionFrame = pluginExecutionContext.getFrame;
pluginExecutionContext.runFrame;
}));
//#endregion
//#region src/plugins/plugin-cache.ts
/** Cached diagnostics must not retain the caller through V8's lazy stack frames. */
function materializePluginCacheError(failure) {
let error = failure;
const seen = /* @__PURE__ */ new Set();
while (error instanceof Error && !seen.has(error)) {
seen.add(error);
try {
error.stack = String(error.stack);
} catch {
error.stack = "Stack trace unavailable: custom formatter failed";
}
error = error.cause;
}
}
/** A retiring inventory releases its own custody; terminal disposal releases every birth cache. */
function releasePluginCacheInstance(instance, cache) {
const owners = instanceCacheOwners.get(instance);
if (cache) {
cache.instances.delete(instance);
owners?.delete(cache);
} else {
for (const owner of owners ?? []) owner.instances.delete(instance);
owners?.clear();
}
if (owners?.size === 0) instanceCacheOwners.delete(instance);
}
function getPluginCacheRetainers(cache) {
let retained = cacheRetainers.get(cache);
if (!retained) {
retained = {
references: /* @__PURE__ */ new Set(),
controller: new AbortController(),
settled: createDeferredCore()
};
cacheRetainers.set(cache, retained);
}
return retained;
}
function createPluginMetadataCache() {
return {
current: {
snapshot: void 0,
owner: "operation",
configFingerprint: void 0,
agentWorkspaceFingerprint: void 0,
envFingerprint: void 0,
defaultDiscoveryCompatible: false,
compatiblePolicyHashes: void 0,
compatibleConfigFingerprints: void 0,
revision: Symbol("plugin-metadata-snapshot"),
configIdentities: /* @__PURE__ */ new WeakSet()
},
snapshots: /* @__PURE__ */ new Map(),
discovery: /* @__PURE__ */ new Map(),
sharedDiscovery: /* @__PURE__ */ new Map(),
projections: /* @__PURE__ */ new WeakMap(),
projectionSources: /* @__PURE__ */ new WeakMap(),
completions: /* @__PURE__ */ new WeakMap(),
indexFacts: /* @__PURE__ */ new WeakMap(),
providerPolicyOwners: /* @__PURE__ */ new WeakMap(),
channelAdapters: /* @__PURE__ */ new WeakMap(),
bundledChannelCatalogs: /* @__PURE__ */ new Map(),
bundledProviderPolicySurfaces: /* @__PURE__ */ new Map(),
staticCatalogStates: /* @__PURE__ */ new WeakMap(),
modelSuppressionResolvers: /* @__PURE__ */ new WeakMap(),
mcpAuthDeclarations: /* @__PURE__ */ new WeakMap()
};
}
/** Each inventory owns its acquired facts and reusable load results; publication owns activation. */
function createPluginCache(options = {}) {
return {
async [Symbol.asyncDispose]() {
await retirePluginCache(this);
},
kind: options.kind ?? "operation",
roots: /* @__PURE__ */ new Map(),
rootAliases: /* @__PURE__ */ new Map(),
sdk: createPluginCacheSdk(),
setupModules: /* @__PURE__ */ new Map(),
instances: /* @__PURE__ */ new Set(),
metadata: createPluginMetadataCache(),
installRecords: /* @__PURE__ */ new Map(),
persistedInstalledIndex: /* @__PURE__ */ new Map(),
preparedBundledDiscoveryModes: /* @__PURE__ */ new Map(),
dependencyStatus: /* @__PURE__ */ new WeakMap(),
...createPluginCacheArtifacts()
};
}
function getProcessPluginCache() {
return state$1.current ??= createPluginCache({ kind: "process" });
}
function getScopedPluginCache() {
return getPluginExecutionFrame()?.cacheScope?.cache;
}
function getPluginCache() {
return getScopedPluginCache() ?? getProcessPluginCache();
}
/** Stop new setup calls immediately; the owner awaits in-flight calls and graph cleanup. */
function retirePluginCache(cache, beforeRetire) {
const retained = getPluginCacheRetainers(cache);
if (retained.retirement) return retained.retirement;
const completion = createDeferredCore();
retained.retirement = completion.promise;
const trackRetirement = async (run) => {
const work = new AsyncWorkScope();
try {
return await work.track(run);
} finally {
await work.run(() => work.drain());
}
};
retained.beginRetirement = (track = trackAsyncWork) => {
let admitted = false;
track(() => {
admitted = true;
retained.beginRetirement = void 0;
return beginPluginCacheRetirement(cache, beforeRetire);
}).then(completion.resolve, (error) => {
if (admitted) completion.reject(error);
else retained.beginRetirement?.(trackRetirement);
});
};
retained.controller.abort();
materializePluginCacheError(retained.controller.signal.reason);
if (retained.references.size === 0) retained.beginRetirement?.();
else retained.settled.promise.then(() => {
retained.beginRetirement?.(trackRetirement);
});
return completion.promise;
}
function beginPluginCacheRetirement(cache, beforeRetire) {
if (cache.retirement) return cache.retirement;
const retirement = createDeferredCore();
cache.retirement = retirement.promise;
const cleanup = async () => {
beforeRetire?.();
const registries = cache.retireRegistryLoads?.();
const resources = /* @__PURE__ */ new Set([...cache.setupModules.values(), ...cache.instances]);
for (const resource of resources) resource.quiesce();
const [registry] = await Promise.allSettled([registries]);
const outcomes = await Promise.allSettled([...resources].map(async (resource) => ({
resource,
result: await resource.dispose()
})));
const nativeAdmissions = cache.sourceAdmissions;
if (nativeAdmissions) {
const pending = outcomes.flatMap((outcome) => outcome.status === "fulfilled" ? outcome.value.result.errors.flatMap((error) => error instanceof PluginInstanceDrainTimeoutError ? [error.settled] : []) : []);
if (pending.length > 0) Promise.allSettled(pending).then(() => nativeAdmissions.dispose()).catch((error) => process.emitWarning(`Plugin native capture cleanup failed: ${String(error)}`));
else await nativeAdmissions.dispose();
}
cache.setupModules.clear();
for (const instance of cache.instances) releasePluginCacheInstance(instance, cache);
const unexpected = [...registry.status === "rejected" ? [registry.reason] : [], ...outcomes.flatMap((result) => result.status === "rejected" ? [result.reason] : [])];
if (unexpected.length) throw new AggregateError(unexpected, "Plugin cache resources failed to retire");
const host = registry.status === "fulfilled" ? registry.value : void 0;
const failures = [...host?.failures ?? []];
for (const outcome of outcomes) {
if (outcome.status !== "fulfilled") continue;
const { resource, result } = outcome.value;
appendPluginInstanceCleanupFailures(failures, resource.pluginId, result);
}
return {
cleanupCount: host?.cleanupCount ?? 0,
failures
};
};
cleanup().then(retirement.resolve, retirement.reject);
return retirement.promise;
}
var state$1, cacheRetainers, instanceCacheOwners;
var init_plugin_cache = __esmMin((() => {
init_async_work_scope();
init_deferred$1();
init_global_singleton();
init_host_hook_cleanup_result();
init_plugin_cache_artifacts();
init_plugin_cache_sdk();
init_plugin_instance_error();
init_plugin_instance_invocation();
state$1 = resolveGlobalSingleton(Symbol.for("openclaw.pluginCache"), () => ({
snapshotOwners: /* @__PURE__ */ new WeakMap(),
retirements: []
}));
cacheRetainers = resolveGlobalSingleton(Symbol.for("openclaw.pluginCacheRetainers"), () => /* @__PURE__ */ new WeakMap());
instanceCacheOwners = resolveGlobalSingleton(Symbol.for("openclaw.pluginInstanceCacheOwners"), () => /* @__PURE__ */ new WeakMap());
}));
//#endregion
//#region src/infra/openclaw-root.fs.runtime.ts
var init_openclaw_root_fs_runtime = __esmMin((() => {}));
//#endregion
//#region src/infra/openclaw-root.ts
function parsePackageName(raw) {
const parsed = JSON.parse(raw);
return typeof parsed.name === "string" ? parsed.name : null;
}
function readPackageNameSync(dir) {
const packageNameCache = getPluginCache().sdk.packageNames;
const packageJsonPath = path.join(path.resolve(dir), "package.json");
if (packageNameCache.has(packageJsonPath)) return packageNameCache.get(packageJsonPath) ?? null;
try {
const name = parsePackageName(openClawRootFsSync.readFileSync(packageJsonPath, "utf-8"));
packageNameCache.set(packageJsonPath, name);
return name;
} catch {
packageNameCache.set(packageJsonPath, null);
return null;
}
}
function findPackageRootSync(startDir, maxDepth = 12) {
for (const current of iterAncestorDirs(startDir, maxDepth)) if (readPackageNameSync(current) === "openclaw") return current;
return null;
}
function* iterAncestorDirs(startDir, maxDepth) {
let current = path.resolve(startDir);
for (let i = 0; i < maxDepth; i += 1) {
yield current;
if (path.basename(current) === "node_modules") break;
const parent = path.dirname(current);
if (parent === current) break;
current = parent;
}
}
function candidateDirsFromArgv1(argv1) {
const argv1CandidateCache = getPluginCache().sdk.argvDirectories;
const cacheKey = path.resolve(argv1);
const cached = argv1CandidateCache.get(cacheKey);
if (cached) return [...cached];
const normalized = cacheKey;
const candidates = [];
try {
const resolved = openClawRootFsSync.realpathSync(normalized);
if (resolved !== normalized) candidates.push(path.dirname(resolved));
} catch {}
candidates.push(path.dirname(normalized));
const parts = normalized.split(path.sep);
const binIndex = parts.lastIndexOf(".bin");
if (binIndex > 0 && parts[binIndex - 1] === "node_modules") {
const binName = path.basename(normalized);
const nodeModulesDir = parts.slice(0, binIndex).join(path.sep);
candidates.push(path.join(nodeModulesDir, binName));
}
const deduped = dedupeCandidates(candidates);
argv1CandidateCache.set(cacheKey, deduped);
return [...deduped];
}
function resolveOpenClawPackageRootSync(opts) {
const candidates = buildCandidates(opts);
const cacheKey = candidates.join("\0");
const searches = getPluginCache().sdk.packageSearches;
const cached = searches.get(cacheKey);
if (cached?.all) return cached.all[0] ?? null;
if (cached?.first !== void 0) return cached.first;
for (const candidate of candidates) {
const found = findPackageRootSync(candidate);
if (found) {
searches.set(cacheKey, { first: found });
return found;
}
}
searches.set(cacheKey, { first: null });
return null;
}
function buildCandidates(opts) {
const candidates = [];
if (opts.moduleUrl) try {
candidates.push(path.dirname(fileURLToPath(opts.moduleUrl)));
} catch {}
if (opts.argv1) candidates.push(...candidateDirsFromArgv1(opts.argv1));
if (opts.cwd) candidates.push(opts.cwd);
return dedupeCandidates(candidates);
}
function dedupeCandidates(candidates) {
return [...new Set(candidates.map((candidate) => path.resolve(candidate)))];
}
var init_openclaw_root = __esmMin((() => {
init_plugin_cache();
init_openclaw_root_fs_runtime();
}));
//#endregion
//#region src/infra/git-commit.ts
/** Resolve the commit that produced the loaded artifact, not the checkout's current revision. */
function resolveLoadedCommitHash(options = {}) {
const moduleUrl = options.moduleUrl ?? import.meta.url;
const loaded = readLoadedCommit(moduleUrl);
return loaded === void 0 ? resolveCommitHash({
moduleUrl,
...options.env ? { env: options.env } : {}
}) : loaded;
}
var formatCommit, cachedGitCommitBySearchDir, GIT_COMMIT_CACHE_LIMIT, resolveCommitSearchDir, cacheGitCommit, resolveGitLookupDepth, readCommitFromGit, readCommitFromPackageJson, readCommitProbe, readCommitFromBuildInfo, readLoadedCommit, resolveCommitHash;
var init_git_commit = __esmMin((() => {
init_record_coerce();
init_string_coerce();
init_errors$2();
init_git_root();
init_map_size();
init_openclaw_root();
formatCommit = (value) => {
const match = value?.match(/[0-9a-fA-F]{7,40}/);
return match ? normalizeLowercaseStringOrEmpty(match[0].slice(0, 7)) : null;
};
cachedGitCommitBySearchDir = /* @__PURE__ */ new Map();
GIT_COMMIT_CACHE_LIMIT = 256;
resolveCommitSearchDir = (options) => {
if (options.cwd) return path.resolve(options.cwd);
if (options.moduleUrl) try {
return path.dirname(fileURLToPath(options.moduleUrl));
} catch {}
return process.cwd();
};
cacheGitCommit = (searchDir, commit) => {
cachedGitCommitBySearchDir.set(searchDir, commit);
pruneMapToMaxSize(cachedGitCommitBySearchDir, GIT_COMMIT_CACHE_LIMIT);
return commit;
};
resolveGitLookupDepth = (searchDir, packageRoot) => {
if (!packageRoot) return;
const relative = path.relative(packageRoot, searchDir);
if (relative.startsWith("..") || path.isAbsolute(relative)) return;
return (relative ? relative.split(path.sep).filter(Boolean).length : 0) + 1;
};
readCommitFromGit = (searchDir, packageRoot) => {
const head = readGitHead(searchDir, { maxDepth: resolveGitLookupDepth(searchDir, packageRoot) });
return head === void 0 ? void 0 : formatCommit(head.value);
};
readCommitFromPackageJson = () => {
try {
const pkg = createRequire(import.meta.url)("../../package.json");
return formatCommit(pkg.gitHead ?? pkg.githead ?? null);
} catch {
return null;
}
};
readCommitProbe = (moduleUrl, candidates, field) => {
try {
for (const candidate of candidates) {
const filePath = fileURLToPath(new URL(candidate, moduleUrl));
let raw;
try {
raw = readGitMetadataPrefix(filePath, 1024);
} catch (error) {
if (isMissingPathError(error)) continue;
return null;
}
try {
const value = asNullableRecord(JSON.parse(raw))?.[field];
return typeof value === "string" ? formatCommit(value) : null;
} catch {
return null;
}
}
} catch {}
};
readCommitFromBuildInfo = (moduleUrl = import.meta.url) => {
return readCommitProbe(moduleUrl, ["../build-info.json", "./build-info.json"], "commit") ?? null;
};
readLoadedCommit = (moduleUrl) => {
const buildStamp = readCommitProbe(moduleUrl, ["../.buildstamp", "./.buildstamp"], "head");
const runtimeStamp = readCommitProbe(moduleUrl, ["../.runtime-postbuildstamp", "./.runtime-postbuildstamp"], "head");
if (buildStamp !== void 0 || runtimeStamp !== void 0) {
if (buildStamp || runtimeStamp) return buildStamp && buildStamp === runtimeStamp ? buildStamp : null;
return readCommitFromBuildInfo(moduleUrl);
}
return readCommitProbe(moduleUrl, ["../build-info.json", "./build-info.json"], "commit");
};
resolveCommitHash = (options = {}) => {
const env = options.env ?? process.env;
const readers = options.readers ?? {};
const readGitCommit = readers.readGitCommit ?? readCommitFromGit;
const envCommit = env.GIT_COMMIT?.trim() || env.GIT_SHA?.trim();
const normalized = formatCommit(envCommit);
if (normalized) return normalized;
const searchDir = resolveCommitSearchDir(options);
if (cachedGitCommitBySearchDir.has(searchDir)) {
const cached = cachedGitCommitBySearchDir.get(searchDir) ?? null;
cachedGitCommitBySearchDir.delete(searchDir);
cachedGitCommitBySearchDir.set(searchDir, cached);
return cached;
}
const packageRoot = resolveOpenClawPackageRootSync({
cwd: options.cwd,
moduleUrl: options.moduleUrl
});
try {
const gitCommit = readGitCommit(searchDir, packageRoot);
if (gitCommit !== void 0) return cacheGitCommit(searchDir, gitCommit);
} catch {}
const buildInfoCommit = readers.readBuildInfoCommit?.() ?? readCommitFromBuildInfo();
if (buildInfoCommit) return cacheGitCommit(searchDir, buildInfoCommit);
const pkgCommit = readers.readPackageJsonCommit?.() ?? readCommitFromPackageJson();
if (pkgCommit) return cacheGitCommit(searchDir, pkgCommit);
try {
return cacheGitCommit(searchDir, readGitCommit(searchDir, packageRoot) ?? null);
} catch {
return cacheGitCommit(searchDir, null);
}
};
}));
//#endregion
//#region src/version.ts
function readVersionFromJsonCandidates(moduleUrl, candidates, opts = {}) {
try {
const require = createRequire(moduleUrl);
for (const candidate of candidates) try {
const parsed = require(candidate);
const version = normalizeOptionalString(parsed.version);
if (!version) continue;
if (opts.requirePackageName && parsed.name !== CORE_PACKAGE_NAME) continue;
return version;
} catch {}
return null;
} catch {
return null;
}
}
function readBuildIdFromJsonCandidates(moduleUrl) {
try {
const require = createRequire(moduleUrl);
for (const candidate of BUILD_INFO_CANDIDATES) try {
const buildId = normalizeOptionalString(require(candidate).buildId);
if (buildId && buildId.length <= 96) return buildId;
} catch {}
return null;
} catch {
return null;
}
}
function firstNonEmpty(...values) {
for (const value of values) {
const trimmed = normalizeOptionalString(value);
if (trimmed && trimmed.toLowerCase() !== "undefined" && trimmed.toLowerCase() !== "null") return trimmed;
}
}
function readVersionFromPackageJsonForModuleUrl(moduleUrl) {
return readVersionFromJsonCandidates(moduleUrl, PACKAGE_JSON_CANDIDATES, { requirePackageName: true });
}
function readVersionFromBuildInfoForModuleUrl(moduleUrl) {
return readVersionFromJsonCandidates(moduleUrl, BUILD_INFO_CANDIDATES);
}
function readBuildIdFromBuildInfoForModuleUrl(moduleUrl) {
return readBuildIdFromJsonCandidates(moduleUrl);
}
function resolveVersionFromModuleUrl(moduleUrl) {
return readVersionFromBuildInfoForModuleUrl(moduleUrl) || readVersionFromPackageJsonForModuleUrl(moduleUrl);
}
function resolveBinaryVersion(params) {
return resolveVersionFromModuleUrl(params.moduleUrl) || firstNonEmpty(params.bundledVersion) || params.fallback || "0.0.0";
}
function resolveRuntimeServiceCommit() {
return RUNTIME_SERVICE_COMMIT;
}
var CORE_PACKAGE_NAME, PACKAGE_JSON_CANDIDATES, BUILD_INFO_CANDIDATES, RUNTIME_SERVICE_COMMIT, VERSION;
var init_version$1 = __esmMin((() => {
init_string_coerce();
init_git_commit();
CORE_PACKAGE_NAME = "openclaw";
PACKAGE_JSON_CANDIDATES = [
"../package.json",
"../../package.json",
"../../../package.json",
"./package.json"
];
BUILD_INFO_CANDIDATES = [
"../build-info.json",
"../../build-info.json",
"./build-info.json"
];
readBuildIdFromBuildInfoForModuleUrl(import.meta.url);
RUNTIME_SERVICE_COMMIT = resolveLoadedCommitHash({ moduleUrl: import.meta.url });
VERSION = resolveBinaryVersion({
moduleUrl: import.meta.url,
bundledVersion: process.env.OPENCLAW_BUNDLED_VERSION
});
}));
//#endregion
//#region src/infra/startup-maintenance-required.ts
function isStartupMaintenanceKind(value) {
return typeof value === "string" && Object.hasOwn(maintenanceReasons, value);
}
var GATEWAY_STARTUP_MAINTENANCE_REQUIRED_REASON, maintenanceReasons, StartupMaintenanceRequiredError;
var init_startup_maintenance_required = __esmMin((() => {
GATEWAY_STARTUP_MAINTENANCE_REQUIRED_REASON = "gateway.maintenance_required";
maintenanceReasons = {
"state-migrations": "state migration",
"newer-schema": "a newer OpenClaw build",
"agent-media": "offline media migration",
"agent-databases-composite-primary-key": "state database schema migration",
"audit-events-v2": "state database schema migration",
"legacy-workshop-review-index": "state database schema migration",
"legacy-cron-run-logs": "cron run history migration",
"legacy-workspace": "workspace setup state migration",
"legacy-session-store": "session store migration"
};
StartupMaintenanceRequiredError = class extends Error {
constructor(kind, message, options) {
super(message, options);
this.kind = kind;
this.code = GATEWAY_STARTUP_MAINTENANCE_REQUIRED_REASON;
this.name = "StartupMaintenanceRequiredError";
}
get reason() {
return maintenanceReasons[this.kind];
}
};
}));
//#endregion
//#region src/infra/sqlite-user-version.ts
function isSqliteSchemaVersionError(error) {
return error instanceof SqliteSchemaVersionError || error instanceof Error && error.name === SQLITE_SCHEMA_VERSION_ERROR_NAME;
}
function readSqliteUserVersion(db) {
const row = executeWithCachedStatement(db, "PRAGMA user_version", [], (statement) => statement.get());
return Number(row?.user_version ?? 0);
}
/**
* Name the refusing build from immutable loaded metadata, plus its install root.
* The path remains actionable when multiple installs share a version or build.
*/
function describeRunningOpenClawBuild() {
const commit = resolveRuntimeServiceCommit();
const root = resolveOpenClawPackageRootSync({ moduleUrl: import.meta.url });
const identity = commit ? `OpenClaw ${VERSION} (${commit})` : `OpenClaw ${VERSION}`;
return root ? `${identity} installed at ${root}` : identity;
}
function createNewerSqliteSchemaVersionError(databaseLabel, pathname, schemaVersion, supportedVersion) {
return new SqliteSchemaVersionError(`This OpenClaw build cannot open your existing data.
${databaseLabel} ${pathname} uses newer schema version ${schemaVersion}; this build supports ${supportedVersion}.\nRefused by ${describeRunningOpenClawBuild()}.\nUse a build that supports schema ${schemaVersion} or newer with this state directory. To use an older build, restore your pre-update backup created with openclaw backup create.\nSee ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.`);
}
var SQLITE_SCHEMA_VERSION_ERROR_NAME, SqliteSchemaVersionError;
var init_sqlite_user_version = __esmMin((() => {
init_openclaw_state_db_contract();
init_version$1();
init_kysely_sync_cache_state();
init_openclaw_root();
init_startup_maintenance_required();
SQLITE_SCHEMA_VERSION_ERROR_NAME = "SqliteSchemaVersionError";
SqliteSchemaVersionError = class extends StartupMaintenanceRequiredError {
constructor(message) {
super("newer-schema", message);
this.name = SQLITE_SCHEMA_VERSION_ERROR_NAME;
}
};
}));
//#endregion
//#region packages/normalization-core/src/promise-like.ts
/** Canonical thenable guard; use instead of local isPromiseLike copies. */
function isPromiseLike(value) {
if (value === null || typeof value !== "object" && typeof value !== "function") return false;
try {
return typeof value.then === "function";
} catch {
return false;
}
}
var init_promise_like = __esmMin((() => {}));
//#endregion
//#region src/infra/sqlite-lifecycle-errors.ts
function createSqliteLifecycleAggregateError(errors, message, cause) {
return new AggregateError(errors, message, { cause });
}
/** Keep the first failure as the cause while retaining independent cleanup errors. */
function throwSqliteLifecycleErrors(errors, message) {
if (errors.length === 1) throw errors[0];
if (errors.length > 1) throw createSqliteLifecycleAggregateError(errors, message, errors[0]);
}
/** Settle a synchronous SQLite operation and preserve both operation and cleanup failures. */
function runWithSqliteCleanup(resource, operationLabel, operation) {
let result;
try {
result = operation();
if (isPromiseLike(result)) throw new SqliteCoordinatorError(`${operationLabel} must remain synchronous`);
} catch (operationError) {
try {
resource.release();
} catch (releaseError) {
throw createSqliteLifecycleAggregateError([operationError, releaseError], `${operationLabel} and resource release both failed`, operationError);
}
throw operationError;
}
try {
resource.release();
} catch (releaseError) {
throw new SqliteCoordinatorError(`${operationLabel} completed, but releasing its resource failed`, releaseError);
}
return result;
}
var OpenClawStateOwnershipError, OpenClawStateOwnershipMetadataError, OpenClawStateExternalOwnershipError, SqliteCoordinatorError;
var init_sqlite_lifecycle_errors = __esmMin((() => {
init_promise_like();
init_global_singleton();
OpenClawStateOwnershipError = class extends Error {};
OpenClawStateOwnershipMetadataError = class extends OpenClawStateOwnershipError {
constructor(databasePath, message) {
super(`OpenClaw shared state ownership metadata is invalid at ${databasePath}: ${message}. Repair it with OPENCLAW_SUPERVISOR_MODE=external openclaw database ownership claim --manager <manager-id>.`);
this.databasePath = databasePath;
this.name = "OpenClawStateOwnershipMetadataError";
}
};
OpenClawStateExternalOwnershipError = class extends OpenClawStateOwnershipError {
constructor(databasePath, managerId) {
super(`OpenClaw shared state database ${databasePath} is externally supervised by ${managerId}. Use that external supervisor with OPENCLAW_SUPERVISOR_MODE=external for writable operations.`);
this.databasePath = databasePath;
this.managerId = managerId;
this.name = "OpenClawStateExternalOwnershipError";
}
};
SqliteCoordinatorError = resolveGlobalSingleton(Symbol.for("openclaw.sqliteCoordinatorError"), () => class CoordinatorError extends Error {
constructor(message, cause) {
super(message);
this.cause = cause;
this.name = "SqliteCoordinatorError";
}
});
}));
//#endregion
//#region src/state/openclaw-state-db-async-lifecycle.ts
function isStateDatabaseReadAdmissionInvalidatedError(error) {
return extractErrorCode(error) === STATE_DATABASE_READ_ADMISSION_INVALIDATED;
}
function getOpenClawDatabaseMaintenanceScope() {
return maintenanceResources.current.getStore()?.scope;
}
function isOpenClawDatabaseMaintenanceResourceOwned(resource, scope) {
return maintenanceResources.claims.get(resource)?.scope === scope;
}
function getOpenClawDatabaseMaintenanceResourceScope(resource) {
return maintenanceResources.claims.get(resource)?.scope;
}
function runMaintenance(scope, operation) {
const accepted = {
scope,
active: true
};
try {
const result = maintenanceResources.current.run(accepted, operation);
if (result instanceof Promise) {
const settled = () => {
accepted.active = false;
};
result.then(settled, settled);
scope.track(result);
} else accepted.active = false;
return result;
} catch (error) {
accepted.active = false;
throw error;
}
}
/** Retain one exact resource claim for finite commands while its maintenance scope drains. */
function captureOpenClawDatabaseMaintenanceResource(resource, expectedScope) {
const claim = maintenanceResources.claims.get(resource);
const assertCurrent = () => {
expectedScope.assertOwnerCurrent();
if (claim?.scope !== expectedScope || maintenanceResources.claims.get(resource) !== claim) throw new Error("Database maintenance resource owner changed");
};
assertCurrent();
return {
assertCurrent,
async run(operation) {
assertCurrent();
return runMaintenance(expectedScope, operation);
}
};
}
/** A cached handle used by an independent caller remains with the ordinary cache owner. */
function observeOpenClawDatabaseMaintenanceResource(resource) {
if (!resource) return;
const claim = maintenanceResources.claims.get(resource);
const current = getOpenClawDatabaseMaintenanceScope();
if (!claim) return;
const owner = commonMaintenanceAncestor(claim.scope, current);
if (owner === claim.scope) return;
claim.scope.assertAdmission();
claim.release();
maintenanceResources.claims.delete(resource);
if (owner) owner.own(resource, claim.phase, claim.close);
}
function commonMaintenanceAncestor(owner, scope) {
const ancestors = /* @__PURE__ */ new Set();
for (let current = owner; current; current = maintenanceResources.parents.get(current)) ancestors.add(current);
for (let current = scope; current; current = maintenanceResources.parents.get(current)) if (ancestors.has(current)) return current;
}
/** The cache owns physical identity and admission across drainage and file exclusion. */
function createOpenClawStateDatabaseAsyncLifecycle() {
const resources = /* @__PURE__ */ new Set();
const records = /* @__PURE__ */ new Map();
const recordsByPath = /* @__PURE__ */ new Map();
const seals = /* @__PURE__ */ new Set();
const attempts = /* @__PURE__ */ new Map();
let tail = Promise.resolve();
const known = (pathname) => recordsByPath.get(pathname) ?? recordsByPath.get(path.resolve(pathname));
const bindPath = (record, pathname) => {
record.paths.add(pathname);
if (!recordsByPath.has(pathname)) recordsByPath.set(pathname, record);
};
const overlaps = (left, right) => {
if (left.identity.key === right.identity.key) return true;
for (const pathname of left.paths) if (right.paths.has(pathname)) return true;
return false;
};
const isSealed = (record) => {
if (seals.size === 0) return false;
for (const held of seals) if (held.record === void 0 || overlaps(held.record, record)) return true;
return false;
};
const hasCloseCustody = (record) => isSealed(record) || attempts.has(record);
const assertOpen = (record) => {
if (isSealed(record)) throw new StateDatabaseReadAdmissionInvalidatedError("OpenClaw state database read admission is closed");
};
const findPhysicalRecord = (identity) => {
const record = records.get(identity.key);
if (!record || !identity.key.startsWith("file:") || hasCloseCustody(record)) return record;
for (const pathname of findChangedDatabasePaths(record.paths, identity)) {
record.admissions.delete(pathname);
record.paths.delete(pathname);
if (recordsByPath.get(pathname) === record) recordsByPath.delete(pathname);
}
if (record.paths.size > 0) {
if (!record.paths.has(record.identity.canonicalPath)) record.identity = identity;
return record;
}
invalidate(record);
forget(record);
};
const resolve = (resolvedPath, preparedIdentity) => {
const cached = recordsByPath.get(resolvedPath);
if (cached && (!preparedIdentity || cached.identity.key === preparedIdentity.key)) return !preparedIdentity && cached.identity.key.startsWith("path:") ? resolve(resolvedPath, readDatabasePathIdentitySync(resolvedPath)) : cached;
const identity = preparedIdentity ?? readDatabasePathIdentitySync(resolvedPath);
let record = findPhysicalRecord(identity);
if (!record && identity.key.startsWith("file:")) {
record = [...records.values()].find((candidate) => {
if (!candidate.identity.key.startsWith("path:")) return false;
try {
return readDatabasePathIdentitySync(candidate.identity.canonicalPath).key === identity.key;
} catch {
return false;
}
});
if (record) {
records.delete(record.identity.key);
record.identity = identity;
records.set(identity.key, record);
}
}
if (!record) {
record = {
coordinationKey: identity.key,
identity,
paths: /* @__PURE__ */ new Set(),
generation: {},
admissions: /* @__PURE__ */ new Map()
};
records.set(identity.key, record);
}
bindPath(record, resolvedPath);
bindPath(record, identity.canonicalPath);
return record;
};
const resolveForNative = (pathname) => {
const resolvedPath = path.resolve(pathname);
const cached = recordsByPath.get(resolvedPath);
if (cached) return cached;
const identity = inspectDatabasePathIdentitySync(resolvedPath);
return identity ? resolve(resolvedPath, identity) : void 0;
};
const invalidate = (record) => {
for (const current of record ? [record] : records.values()) {
current.generation = {};
current.admissions.clear();
}
};
const seal = (record) => {
invalidate(record);
const held = { record };
seals.add(held);
return held;
};
const release = (attempt) => {
if (attempt.seal) {
seals.delete(attempt.seal);
attempt.seal = void 0;
}
};
const forget = (record) => {
if (!hasCloseCustody(record) && records.get(record.identity.key) === record) {
records.delete(record.identity.key);
for (const pathname of record.paths) if (recordsByPath.get(pathname) === record) {
recordsByPath.delete(pathname);
for (const replacement of records.values()) if (replacement.paths.has(pathname)) {
recordsByPath.set(pathname, replacement);
break;
}
}
}
};
const captureRecord = (record, databasePath) => {
const previous = record.admissions.get(databasePath);
if (previous) return previous;
const generation = record.generation;
const admission = Object.freeze({
databasePath,
coordinationKey: record.coordinationKey,
get identity() {
return record.identity;
},
assertCurrent() {
assertOpen(record);
if (records.get(record.identity.key) !== record || record.generation !== generation || record.admissions.get(databasePath) !== admission) throw new StateDatabaseReadAdmissionInvalidatedError("OpenClaw state database read admission changed");
}
});
record.admissions.set(databasePath, admission);
return admission;
};
const captureResolved = (databasePath) => {
const record = resolve(databasePath);
assertOpen(record);
return captureRecord(record, databasePath);
};
return {
identity(pathname) {
return known(pathname)?.identity ?? inspectDatabasePathIdentitySync(pathname);
},
knownIdentity(pathname) {
return known(pathname)?.identity;
},
publish(pathname) {
const resolvedPath = path.resolve(pathname);
const identity = readDatabasePathIdentitySync(resolvedPath);
const previous = recordsByPath.get(resolvedPath);
let record = findPhysicalRecord(identity);
if (previous && previous.identity.key !== identity.key) {
if (previous.identity.key.startsWith("path:") && !record) {
records.delete(previous.identity.key);
previous.identity = identity;
records.set(identity.key, previous);
record = previous;
} else {
const failed = attempts.get(previous);
if (failed) {
failed.superseded = true;
failed.seal ??= seal(previous);
} else invalidate(previous);
forget(previous);
}
}
if (!record) record = resolve(resolvedPath, identity);
bindPath(record, resolvedPath);
bindPath(record, identity.canonicalPath);
return {
identity,
admission: captureRecord(record, resolvedPath)
};
},
invalidate(pathname) {
if (pathname === void 0) invalidate();
else {
const record = known(pathname);
if (record) invalidate(record);
}
},
register(resource) {
resources.add(resource);
for (const attempt of attempts.values()) attempt.queue?.add(resource);
return () => {
resources.delete(resource);
};
},
capture(pathname) {
const cached = recordsByPath.get(pathname);
const retained = cached?.admissions.get(pathname);
if (cached && retained && cached.identity.key.startsWith("file:")) {
retained.assertCurrent();
return retained;
}
return captureResolved(path.resolve(pathname));
},
holdExclusion(pathname) {
const record = resolve(path.resolve(pathname));
const held = seal(record);
return () => {
seals.delete(held);
for (const current of records.values()) if (overlaps(record, current)) forget(current);
};
},
close(pathname, retireNative) {
const record = pathname === void 0 ? void 0 : resolveForNative(pathname);
if (pathname !== void 0 && !record) return Promise.resolve(retireNative());
let attempt = attempts.get(record);
if (attempt?.pending) return attempt.pending;
if (!attempt) {
attempt = { retained: /* @__PURE__ */ new Set() };
attempts.set(record, attempt);
}
attempt.seal ??= seal(record);
const current = attempt;
const pending = tail.then(async () => {
const closing = /* @__PURE__ */ new Set([...resources, ...current.retained]);
for (const entry of attempts.values()) for (const resource of entry.retained) closing.add(resource);
current.queue = closing;
const errors = [];
while (current.queue.size) {
const ordinary = [...current.queue].filter((resource) => resource.phase !== "after-resources");
if (!ordinary.length && errors.length) {
for (const resource of current.queue) current.retained.add(resource);
break;
}
const batch = ordinary.length ? ordinary : [...current.queue];
for (const resource of batch) current.queue.delete(resource);
await Promise.all(batch.map(async (resource) => {
try {
await resource.close(record?.identity);
current.retained.delete(resource);
} catch (error) {
current.retained.add(resource);
errors.push(error);
}
}));
}
if (errors.length && !current.superseded) release(current);
throwSqliteLifecycleErrors(errors, "OpenClaw state resource drainage failed");
const retired = retireNative(record?.identity);
attempts.delete(record);
release(current);
if (record === void 0) {
for (const [key, entry] of attempts) if (!entry.pending) {
attempts.delete(key);
release(entry);
}
for (const entry of records.values()) forget(entry);
} else forget(record);
return retired;
}).finally(() => {
current.queue = void 0;
});
current.pending = pending;
tail = pending.then(() => void 0, () => void 0);
pending.catch(() => {
current.pending = void 0;
});
return pending;
}
};
}
var STATE_DATABASE_READ_ADMISSION_INVALIDATED, StateDatabaseReadAdmissionInvalidatedError, maintenanceResources;
var init_openclaw_state_db_async_lifecycle = __esmMin((() => {
init_error_coercion();
init_sqlite_lifecycle_errors();
init_sqlite_worker_identity();
init_global_singleton();
STATE_DATABASE_READ_ADMISSION_INVALIDATED = "STATE_DATABASE_READ_ADMISSION_INVALIDATED";
StateDatabaseReadAdmissionInvalidatedError = class extends Error {
constructor(..._args) {
super(..._args);
this.code = STATE_DATABASE_READ_ADMISSION_INVALIDATED;
}
};
maintenanceResources = resolveGlobalSingleton(Symbol.for("openclaw.databaseMaintenanceResources"), () => ({
current: new AsyncLocalStorage(),
claims: /* @__PURE__ */ new WeakMap(),
parents: /* @__PURE__ */ new WeakMap()
}));
}));
//#endregion
//#region src/state/openclaw-state-db.paths.ts
/** Resolve the directory that contains the shared state SQLite file. */
function resolveOpenClawStateSqliteDir(env = process.env) {
return path.join(resolveStateDir(env), "state");
}
/** Resolve the shared state SQLite file path. */
function resolveOpenClawStateSqlitePath(env = process.env) {
return path.join(resolveStateDir(env), "state", "openclaw.sqlite");
}
/** Resolve the state owner directory for a canonical or explicit shared database path. */
function resolveOpenClawStateDirForDatabasePath(databasePath) {
const databaseDir = path.dirname(path.resolve(databasePath));
return path.basename(databaseDir) === "state" ? path.dirname(databaseDir) : databaseDir;
}
/** Resolve the integrity/quarantine store that survives loss of the primary state database. */
function resolveQuarantineStorePath(env) {
return path.join(resolveOpenClawStateSqliteDir(env), "openclaw-quarantine.sqlite");
}
var init_openclaw_state_db_paths = __esmMin((() => {
init_paths$1();
init_boundary_path();
init_errno();
init_path_guards();
}));
//#endregion
//#region packages/normalization-core/src/node-crypto.ts
function sha256Hex(input) {
return hash("sha256", input, "hex");
}
function sha256HexPrefixCore(input, length) {
return sha256Hex(input).slice(0, length);
}
var init_node_crypto = __esmMin((() => {}));
//#endregion
//#region src/infra/crypto-digest.ts
var init_crypto_digest = __esmMin((() => {
init_node_crypto();
}));
//#endregion
//#region src/infra/file-lock-manager.ts
var init_file_lock_manager = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/util.js
function getEnumValues(entries) {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
}
function joinValues(array, separator = "|") {
return array.map((val) => stringifyPrimitive(val)).join(separator);
}
function jsonStringifyReplacer(_, value) {
if (typeof value === "bigint") return value.toString();
return value;
}
function cached(getter) {
return new Cached(getter);
}
function nullish(input) {
return input === null || input === void 0;
}
function cleanRegex(source) {
const start = source.startsWith("^") ? 1 : 0;
const end = source.endsWith("$") ? source.length - 1 : source.length;
return source.slice(start, end);
}
function floatSafeRemainder(val, step) {
const ratio = val / step;
const roundedRatio = Math.round(ratio);
const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1);
if (Math.abs(ratio - roundedRatio) < tolerance) return 0;
return ratio - roundedRatio;
}
function assignProp(target, prop, value) {
Object.defineProperty(target, prop, {
value,
writable: true,
enumerable: true,
configurable: true
});
}
/**
* Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it.
*
* Its keys and descriptors read without invoking anything, which is what lets a discriminated union check its discriminator, and the cycle walk read a shape, without resolving a getter that references the schema being constructed. A def that answers `shape` from an accessor of its own has none.
*/
function rawShape(def) {
const desc = Object.getOwnPropertyDescriptor(def, "shape");
return desc?.get ? desc.get.raw : desc?.value;
}
function sourceShape(schema) {
return rawShape(schema._zod.def) ?? schema._zod.def.shape;
}
function deferProp(target, key, getter) {
Object.defineProperty(target, key, {
get() {
const value = getter();
assignProp(this, key, value);
return value;
},
enumerable: true,
configurable: true
});
}
function putProp(target, key, value) {
if (key in target) assignProp(target, key, value);
else target[key] = value;
}
/**
* Copies `keys` of `source`'s shape onto `target`, each value passed through `wrap`.
*
* A key the source has resolved is copied through now, so the derived shape states it outright and nothing has to resolve it to learn what it holds. A key the source still defers stays deferred, and reads back through the source's own `shape`, so it resolves once and both shapes get that one schema.
*/
function mirrorShape(target, source, keys, wrap) {
const raw = sourceShape(source);
for (const key of keys) {
const desc = Object.getOwnPropertyDescriptor(raw, key);
if (!desc.enumerable) continue;
if (desc.get) deferProp(target, key, () => {
const value = source._zod.def.shape[key];
return wrap ? wrap(value, key) : value;
});
else putProp(target, key, wrap ? wrap(desc.value, key) : desc.value);
}
}
function mirrorProps(target, source) {
for (const key of Reflect.ownKeys(source)) {
const desc = Object.getOwnPropertyDescriptor(source, key);
if (!desc.enumerable) continue;
if (desc.get) deferProp(target, key, () => source[key]);
else putProp(target, key, desc.value);
}
}
function mergeDefs(...defs) {
const mergedDescriptors = {};
for (const def of defs) {
const descriptors = Object.getOwnPropertyDescriptors(def);
Object.assign(mergedDescriptors, descriptors);
}
return Object.defineProperties({}, mergedDescriptors);
}
function esc(str) {
return JSON.stringify(str);
}
function slugify(input) {
return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
function isObject(data) {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
function isPlainObject(o) {
if (isObject(o) === false) return false;
const ctor = o.constructor;
if (ctor === void 0) return true;
if (typeof ctor !== "function") return true;
const prot = ctor.prototype;
if (isObject(prot) === false) return false;
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false;
return true;
}
function shallowClone(o) {
if (isPlainObject(o)) return { ...o };
if (Array.isArray(o)) return [...o];
if (o instanceof Map) return new Map(o);
if (o instanceof Set) return new Set(o);
return o;
}
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def, params) {
const cl = new inst._zod.constr(def ?? inst._zod.def);
if (!def || params?.parent) cl._zod.parent = inst;
return cl;
}
function normalizeParams(_params) {
const params = _params;
if (!params) return {};
if (typeof params === "string") return { error: () => params };
if (params?.message !== void 0) {
if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params");
params.error = params.message;
}
delete params.message;
if (typeof params.error === "string") return {
...params,
error: () => params.error
};
return params;
}
function stringifyPrimitive(value) {
if (typeof value === "bigint") return value.toString() + "n";
if (typeof value === "string") return `"${value}"`;
return `${value}`;
}
function optionalKeys(shape) {
return Object.keys(shape).filter((k) => {
return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional";
});
}
function pick(schema, mask) {
const currDef = schema._zod.def;
const checks = currDef.checks;
if (checks && checks.length > 0) throw new Error(".pick() cannot be used on object schemas containing refinements");
const newShape = {};
mirrorShape(newShape, schema, maskedKeys(schema, mask));
return clone(schema, mergeDefs(currDef, {
shape: newShape,
checks: []
}));
}
function maskedKeys(schema, mask) {
const raw = sourceShape(schema);
const keys = [];
for (const key of Reflect.ownKeys(mask)) {
if (!Object.getOwnPropertyDescriptor(raw, key)?.enumerable) throw new Error(`Unrecognized key: "${String(key)}"`);
if (mask[key]) keys.push(key);
}
return keys;
}
function omit(schema, mask) {
const currDef = schema._zod.def;
const checks = currDef.checks;
if (checks && checks.length > 0) throw new Error(".omit() cannot be used on object schemas containing refinements");
const omitted = new Set(maskedKeys(schema, mask));
const newShape = {};
mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)).filter((key) => !omitted.has(key)));
return clone(schema, mergeDefs(currDef, {
shape: newShape,
checks: []
}));
}
function extend(schema, shape) {
if (!isPlainObject(shape)) throw new Error("Invalid input to extend: expected a plain object");
const checks = schema._zod.def.checks;
if (checks && checks.length > 0) {
const existingShape = sourceShape(schema);
for (const key of Reflect.ownKeys(shape)) if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
}
return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
}
function extended(schema, shape) {
const newShape = {};
mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)));
mirrorProps(newShape, shape);
return newShape;
}
function safeExtend(schema, shape) {
if (!isPlainObject(shape)) throw new Error("Invalid input to safeExtend: expected a plain object");
return clone(schema, mergeDefs(schema._zod.def, { shape: extended(schema, shape) }));
}
function merge(a, b) {
if (!b?._zod?.def) throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");
if (a._zod.def.checks?.length) throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
const newShape = {};
mirrorShape(newShape, a, Reflect.ownKeys(sourceShape(a)));
mirrorShape(newShape, b, Reflect.ownKeys(sourceShape(b)));
return clone(a, mergeDefs(a._zod.def, {
shape: newShape,
get catchall() {
return b._zod.def.catchall;
},
checks: b._zod.def.checks ?? []
}));
}
function partial(Class, schema, mask, name = "partial") {
const checks = schema._zod.def.checks;
if (checks && checks.length > 0) throw new Error(`.${name}() cannot be used on object schemas containing refinements`);
const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0;
const newShape = {};
mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), Class && ((value, key) => selected && !selected.has(key) ? value : new Class({
type: "optional",
innerType: value
})));
return clone(schema, mergeDefs(schema._zod.def, {
shape: newShape,
checks: []
}));
}
function required(Class, schema, mask) {
const selected = mask ? new Set(maskedKeys(schema, mask)) : void 0;
const newShape = {};
mirrorShape(newShape, schema, Reflect.ownKeys(sourceShape(schema)), (value, key) => selected && !selected.has(key) ? value : new Class({
type: "nonoptional",
innerType: value
}));
return clone(schema, mergeDefs(schema._zod.def, { shape: newShape }));
}
function aborted(x, startIndex = 0) {
if (x.aborted === true) return true;
for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true;
return false;
}
function explicitlyAborted(x, startIndex = 0) {
if (x.aborted === true) return true;
for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true;
return false;
}
function prefixIssues(path, issues) {
return issues.map((iss) => {
var _a;
(_a = iss).path ?? (_a.path = []);
iss.path.unshift(path);
return iss;
});
}
function unwrapMessage(message) {
return typeof message === "string" ? message : message?.message;
}
function attachSchema(issues, start, inst) {
var _a;
for (let i = start; i < issues.length; i++) (_a = issues[i]).schema ?? (_a.schema = inst);
}
function finalizeIssue(iss, ctx, config) {
var _a;
const traits = iss.inst?._zod?.traits;
if (traits?.has("$ZodType")) {
if (traits.has("$ZodCheck")) (_a = iss).schema ?? (_a.schema = iss.inst);
else iss.schema = iss.inst;
}
const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0;
const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input";
const full = {};
for (const k of Object.keys(iss)) {
if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") continue;
full[k] = iss[k];
}
full.path ?? (full.path = []);
full.message = message;
if (ctx?.reportInput) full.input = iss.input;
return full;
}
function codePointLength(str) {
const units = str.length;
if (!highSurrogate.test(str)) return units;
let count = units;
for (let i = 0; i < units - 1; i++) if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) {
count--;
i++;
}
return count;
}
function getLengthableOrigin(input) {
if (Array.isArray(input)) return "array";
if (typeof input === "string") return "string";
return "unknown";
}
function parsedType(data) {
const t = typeof data;
switch (t) {
case "number": return Number.isNaN(data) ? "nan" : "number";
case "object": {
if (data === null) return "null";
if (Array.isArray(data)) return "array";
const obj = data;
if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) return obj.constructor.name;
}
}
return t;
}
function issue(...args) {
const [iss, input, inst] = args;
if (typeof iss === "string") return {
message: iss,
code: "custom",
input,
inst
};
return { ...iss };
}
/**
* Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working.
*
* Call this from a `proto` initializer, which runs once per prototype — never per instance.
*/
function members(proto, table) {
for (const key in table) {
const desc = Object.getOwnPropertyDescriptor(table, key);
if (desc.get) Object.defineProperty(proto, key, {
...desc,
enumerable: false
});
else defineBound(proto, key, desc.value);
}
}
/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */
function own(inst, key, value, enumerable = true) {
Object.defineProperty(inst, key, {
configurable: true,
writable: true,
enumerable,
value
});
return value;
}
/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */
function hide(inst, key, value) {
return own(inst, key, value, false);
}
/** Adds members a table derives from the instance: each builds on first read and shadows as own data, and assignment shadows the same way, as when these were own properties. */
function derived(computes, table) {
for (const key in computes) {
const compute = computes[key];
Object.defineProperty(table, key, {
configurable: true,
enumerable: true,
get() {
return own(this, key, compute(this));
},
set(value) {
own(this, key, value);
}
});
}
return table;
}
function defineBound(proto, key, fn) {
Object.defineProperty(proto, key, {
configurable: true,
get() {
return this == null ? fn : own(this, key, fn.bind(this));
},
set(value) {
own(this, key, value);
}
});
}
/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */
function claim(inst, sentinel) {
const proto = Object.getPrototypeOf(inst);
return sentinel in proto ? void 0 : proto;
}
/**
* Installs a lazily-derived internal on the `_zod` prototype of `inst`'s
* constructor, computed from the internals object itself and cached there on
* first read. One accessor per constructor rather than one per instance.
*/
function defineLazyInternal(inst, key, compute) {
const proto = Object.getPrototypeOf(inst._zod);
if (key in proto && installing !== inst._zod) {
installing = void 0;
return;
}
installing = inst._zod;
Object.defineProperty(proto, key, {
configurable: true,
get() {
Object.defineProperty(this, key, breaker);
const outer = broke;
broke = false;
try {
const value = compute(this);
if (broke) delete this[key];
else Object.defineProperty(this, key, {
configurable: true,
writable: true,
value
});
broke = broke || outer;
return value;
} catch (err) {
delete this[key];
broke = broke || outer;
throw err;
}
},
set(value) {
Object.defineProperty(this, key, {
configurable: true,
writable: true,
value
});
}
});
}
/**
* Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own
* data property. One accessor per constructor rather than one per instance, because an own accessor
* puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel.
*/
function installLazyProp(inst, key, make, enumerable) {
const proto = claim(inst, key);
if (!proto) return;
Object.defineProperty(proto, key, {
configurable: true,
get() {
const desc = {
configurable: true,
writable: true,
enumerable,
value: void 0
};
Object.defineProperty(this, key, desc);
desc.value = make(this);
Object.defineProperty(this, key, desc);
return desc.value;
},
set(value) {
Object.defineProperty(this, key, {
configurable: true,
writable: true,
enumerable,
value
});
}
});
}
/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */
function constantCatch(value) {
const fn = () => value;
fn[CONSTANT_CATCH] = true;
return fn;
}
var Cached, captureStackTrace, allowsEval, propertyKeyTypes, NUMBER_FORMAT_RANGES, BIGINT_FORMAT_RANGES, highSurrogate, installing, broke, breaker, CONSTANT_CATCH;
var init_util = __esmMin((() => {
init_core$1();
Cached = class {
constructor(getter) {
this._getter = getter;
this._value = void 0;
}
get value() {
const getter = this._getter;
if (getter !== void 0) {
this._value = getter();
this._getter = void 0;
}
return this._value;
}
};
captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {};
allowsEval = /* @__PURE__*/ cached(() => {
if (globalConfig.jitless) return false;
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) return false;
try {
new Function("");
return true;
} catch (_) {
return false;
}
});
propertyKeyTypes = /* @__PURE__*/ new Set([
"string",
"number",
"symbol"
]);
NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-34028234663852886e22, 34028234663852886e22],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE]
}))();
BIGINT_FORMAT_RANGES = {
int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")],
uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")]
};
highSurrogate = /[\uD800-\uDBFF]/;
broke = false;
breaker = {
configurable: true,
get() {
broke = true;
}
};
CONSTANT_CATCH = "~constantCatch";
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/core.js
function newError(Definition) {
const E = _E;
if (E) {
const saved = E.stackTraceLimit;
if (typeof saved === "number") {
try {
E.stackTraceLimit = 0;
} catch {
_E = null;
return new Definition();
}
try {
return new Definition();
} finally {
E.stackTraceLimit = saved;
}
}
}
return new Definition();
}
function $constructor(name, initializer, proto, params) {
const zodProto = {};
function Internals(def) {
this.def = def;
this.constr = _;
this.traits = /* @__PURE__ */ new Set();
}
Internals.prototype = zodProto;
const protoMembers = proto;
const initialized = protoMembers && /* @__PURE__ */ new WeakSet();
function init(inst, def) {
if (!inst._zod) {
_zodDesc.value = new Internals(def);
try {
Object.defineProperty(inst, "_zod", _zodDesc);
} finally {
_zodDesc.value = void 0;
}
} else if (inst._zod.traits.has(name)) return;
inst._zod.traits.add(name);
initializer(inst, def);
if (initialized) {
const own = Object.getPrototypeOf(inst);
const ctorProto = inst._zod.constr.prototype;
let up = own;
while (up && up !== ctorProto) up = Object.getPrototypeOf(up);
const target = up ?? own;
if (!initialized.has(target)) {
initialized.add(target);
members(target, protoMembers);
}
}
const proto = _.prototype;
for (const k in proto) {
if (!Object.prototype.hasOwnProperty.call(proto, k)) continue;
if (!(k in inst)) inst[k] = proto[k].bind(inst);
}
}
const Parent = params?.Parent ?? Object;
class Definition extends Parent {}
Object.defineProperty(Definition, "name", { value: name });
function _(def) {
const inst = params?.Parent ? newError(Definition) : this;
init(inst, def);
const deferred = inst._zod.deferred;
if (deferred) {
for (const fn of deferred) fn();
inst._zod.deferred = void 0;
}
const pp = globalThis.__zod_globalConfig?.postProcessor;
if (pp) pp(inst);
return inst;
}
Object.defineProperty(_, "init", { value: init });
Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => {
if (params?.Parent && inst instanceof params.Parent) return true;
return inst?._zod?.traits?.has(name);
} });
Object.defineProperty(_, "name", { value: name });
return _;
}
function config(newConfig) {
if (newConfig) Object.assign(globalConfig, newConfig);
return globalConfig;
}
var _a$1, _zodDesc, _E, $ZodAsyncError, $ZodEncodeError, globalConfig;
var init_core$1 = __esmMin((() => {
init_util();
_zodDesc = {
value: void 0,
enumerable: false
};
_E = "captureStackTrace" in Error ? Error : null;
$ZodAsyncError = class extends Error {
constructor() {
super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
}
};
$ZodEncodeError = class extends Error {
constructor(name) {
super(`Encountered unidirectional transform during encode: ${name}`);
this.name = "ZodEncodeError";
}
};
(_a$1 = globalThis).__zod_globalConfig ?? (_a$1.__zod_globalConfig = {});
globalConfig = globalThis.__zod_globalConfig;
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/errors.js
function _getMessage() {
const internals = this._zod;
internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
return internals.message;
}
function _setMessage(value) {
this._zod.message = value;
}
/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member
* ("toString", "constructor") would otherwise read through to the prototype, and assigning
* "__proto__" would hit the setter instead of creating a key. */
function node(obj, key, make) {
if (!Object.prototype.hasOwnProperty.call(obj, key)) {
if (key === "__proto__") Object.defineProperty(obj, key, {
value: make(),
writable: true,
enumerable: true,
configurable: true
});
else obj[key] = make();
}
return obj[key];
}
function flattenError(error, mapper = (issue) => issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of error.issues) if (sub.path.length > 0) node(fieldErrors, sub.path[0], () => []).push(mapper(sub));
else formErrors.push(mapper(sub));
return {
formErrors,
fieldErrors
};
}
function formatError(error, mapper = (issue) => issue.message) {
const fieldErrors = { _errors: [] };
const processError = (error, path = []) => {
for (const issue of error.issues) if (issue.code === "invalid_union" && issue.errors.length) issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));
else if (issue.code === "invalid_key") processError({ issues: issue.issues }, [...path, ...issue.path]);
else if (issue.code === "invalid_element") processError({ issues: issue.issues }, [...path, ...issue.path]);
else {
const fullpath = [...path, ...issue.path];
if (fullpath.length === 0) fieldErrors._errors.push(mapper(issue));
else {
let curr = fieldErrors;
let i = 0;
while (i < fullpath.length) {
const el = fullpath[i];
const terminal = i === fullpath.length - 1;
if (el === "_errors") {
if (terminal) curr._errors.push(mapper(issue));
i++;
continue;
}
if (!Object.prototype.hasOwnProperty.call(curr, el)) Object.defineProperty(curr, el, {
value: { _errors: [] },
enumerable: true,
writable: true,
configurable: true
});
const node = curr[el];
if (terminal) node._errors.push(mapper(issue));
curr = node;
i++;
}
}
}
};
processError(error);
return fieldErrors;
}
var _messageDesc, _issuesDesc, _installedToString, initializer$1, $ZodError;
var init_errors$1 = __esmMin((() => {
init_core$1();
init_util();
_messageDesc = {
get: _getMessage,
set: _setMessage,
enumerable: true,
configurable: true
};
_issuesDesc = {
value: void 0,
enumerable: false
};
_installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
initializer$1 = (inst, def) => {
inst.name = "$ZodError";
_issuesDesc.value = def;
Object.defineProperty(inst, "issues", _issuesDesc);
_issuesDesc.value = void 0;
Object.defineProperty(inst, "message", _messageDesc);
const proto = Object.getPrototypeOf(inst);
if (!_installedToString.has(proto)) {
_installedToString.add(proto);
Object.defineProperty(proto, "toString", {
configurable: true,
enumerable: false,
get() {
const value = () => this.message;
Object.defineProperty(this, "toString", {
value,
configurable: true,
writable: true
});
return value;
},
set(value) {
Object.defineProperty(this, "toString", {
value,
configurable: true,
writable: true
});
}
});
}
};
$ZodError = $constructor("$ZodError", initializer$1);
$constructor("$ZodError", initializer$1, void 0, { Parent: Error });
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/parse.js
function finalizeParams(callee, params) {
return {
callee: params?.callee ?? callee,
Err: params?.Err
};
}
function failure(Err, issues, ctx) {
let error;
return {
success: false,
get error() {
if (!error) {
error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config())));
issues = void 0;
ctx = void 0;
}
return error;
},
set error(e) {
error = e;
issues = void 0;
ctx = void 0;
}
};
}
function validateFallback(schema, value, _ctx) {
const ctx = _ctx ? {
..._ctx,
async: false,
abortEarly: true
} : {
async: false,
abortEarly: true
};
const fallbackRun = schema._zod.bag.fallbackRun;
let result;
if (fallbackRun) {
ctx[COMPILE_FALLBACK] = true;
result = fallbackRun({
value,
issues: []
}, ctx);
} else result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) throw new $ZodAsyncError();
return result.issues.length === 0;
}
var _parse, _parseAsync, _safeParse, _safeParseAsync, COMPILE_INVALID, COMPILE_FALLBACK, validate, validateAsync$1, _encode, _decode, _encodeAsync, _decodeAsync, _safeEncode, _safeDecode, _safeEncodeAsync, _safeDecodeAsync;
var init_parse$1 = __esmMin((() => {
init_core$1();
init_util();
_parse = (_Err) => {
const fn = (schema, value, _ctx, _params) => {
const ctx = _ctx ? {
..._ctx,
async: false
} : { async: false };
const result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) throw new $ZodAsyncError();
if (result.issues.length) {
const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
captureStackTrace(e, _params?.callee ?? fn);
throw e;
}
return result.value;
};
return fn;
};
_parseAsync = (_Err) => {
const fn = async (schema, value, _ctx, params) => {
const ctx = _ctx ? {
..._ctx,
async: true
} : { async: true };
let result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) result = await result;
if (result.issues.length) {
const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
captureStackTrace(e, params?.callee ?? fn);
throw e;
}
return result.value;
};
return fn;
};
_safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? {
..._ctx,
async: false
} : { async: false };
const result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) throw new $ZodAsyncError();
return result.issues.length ? failure(_Err, result.issues, ctx) : {
success: true,
data: result.value
};
};
_safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? {
..._ctx,
async: true
} : { async: true };
let result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) result = await result;
return result.issues.length ? failure(_Err, result.issues, ctx) : {
success: true,
data: result.value
};
};
COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
validate = ((schema, value, _ctx) => {
const validator = schema._zod.bag.validator;
if (validator !== void 0) {
if (validator(value) !== COMPILE_INVALID) return true;
if (validator.definite === true && _ctx === void 0) return false;
}
return validateFallback(schema, value, _ctx);
});
validateAsync$1 = async (schema, value, _ctx) => {
const ctx = _ctx ? {
..._ctx,
async: true,
abortEarly: true
} : {
async: true,
abortEarly: true
};
let result = schema._zod.run({
value,
issues: []
}, ctx);
if (result instanceof Promise) result = await result;
return result.issues.length === 0;
};
_encode = (_Err) => {
const parse = _parse(_Err);
const fn = (schema, value, _ctx, _params) => {
const ctx = _ctx ? {
..._ctx,
direction: "backward"
} : { direction: "backward" };
return parse(schema, value, ctx, finalizeParams(fn, _params));
};
return fn;
};
_decode = (_Err) => {
const parse = _parse(_Err);
const fn = (schema, value, _ctx, _params) => {
return parse(schema, value, _ctx, finalizeParams(fn, _params));
};
return fn;
};
_encodeAsync = (_Err) => {
const parseAsync = _parseAsync(_Err);
const fn = async (schema, value, _ctx, _params) => {
const ctx = _ctx ? {
..._ctx,
direction: "backward"
} : { direction: "backward" };
return await parseAsync(schema, value, ctx, finalizeParams(fn, _params));
};
return fn;
};
_decodeAsync = (_Err) => {
const parseAsync = _parseAsync(_Err);
const fn = async (schema, value, _ctx, _params) => {
return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params));
};
return fn;
};
_safeEncode = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? {
..._ctx,
direction: "backward"
} : { direction: "backward" };
return _safeParse(_Err)(schema, value, ctx);
};
_safeDecode = (_Err) => (schema, value, _ctx) => {
return _safeParse(_Err)(schema, value, _ctx);
};
_safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? {
..._ctx,
direction: "backward"
} : { direction: "backward" };
return _safeParseAsync(_Err)(schema, value, ctx);
};
_safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
return _safeParseAsync(_Err)(schema, value, _ctx);
};
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/regexes.js
function nanoidOfLength(length) {
return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`);
}
function emoji() {
return new RegExp(_emoji$1, "u");
}
/** Anchors a pattern source. The interpolation lives here rather than at the call site because
* esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it
* will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */
function anchor(source) {
return new RegExp(`^${source}$`);
}
function timeSource(args) {
const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
return typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : args.seconds ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
}
function time(args) {
return new RegExp(`^${timeSource(args)}$`);
}
function datetime(args) {
const opts = ["Z"];
if (args.offset) opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
const qualified = `${timeSource({
precision: args.precision,
seconds: true
})}(?:${opts.join("|")})`;
const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified;
return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
var cuid, cuid2, ulid, xid, ksuid, nanoid, duration, guid, uuid, email, _emoji$1, ipv4, ipv6, cidrv4, cidrv6, base64, base64url, httpProtocol, e164, dateSource, date, anyString, number$1, boolean$1, lowercase, uppercase;
var init_regexes = __esmMin((() => {
cuid = /^[cC][0-9a-z]{6,}$/;
cuid2 = /^[0-9a-z]+$/;
ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;
xid = /^[0-9a-vA-V]{20}$/;
ksuid = /^[A-Za-z0-9]{27}$/;
nanoid = /^[a-zA-Z0-9_-]{21}$/;
duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;
uuid = (version) => {
if (!version) return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
email = /^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
_emoji$1 = `^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;
ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;
cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/;
cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
base64url = /^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;
httpProtocol = /^https?$/;
e164 = /^\+[1-9]\d{6,14}$/;
dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;
date = /*@__PURE__*/ anchor(dateSource);
anyString = /^[\s\S]{0,}$/;
number$1 = /^-?\d+(?:\.\d+)?$/;
boolean$1 = /^(?:true|false)$/i;
lowercase = /^[^A-Z]*$/;
uppercase = /^[^a-z]*$/;
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/checks.js
var $ZodCheck, _whenHasLength, numericOriginMap, $ZodCheckLessThan, $ZodCheckGreaterThan, $ZodCheckMultipleOf, $ZodCheckNumberFormat, $ZodCheckMaxLength, $ZodCheckMinLength, $ZodCheckLengthEquals, $ZodCheckStringFormat, $ZodCheckRegex, $ZodCheckLowerCase, $ZodCheckUpperCase, $ZodCheckIncludes, $ZodCheckStartsWith, $ZodCheckEndsWith, $ZodCheckOverwrite;
var init_checks$1 = __esmMin((() => {
init_core$1();
init_regexes();
init_util();
$ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
var _a;
inst._zod ?? (inst._zod = {});
inst._zod.def = def;
(_a = inst._zod).onattach ?? (_a.onattach = []);
});
_whenHasLength = (payload) => {
const val = payload.value;
return !nullish(val) && val.length !== void 0;
};
numericOriginMap = {
number: "number",
bigint: "bigint",
object: "date"
};
$ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value <= def.value : payload.value < def.value) return;
payload.issues.push({
origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_big",
maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort
});
};
});
$ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => {
$ZodCheck.init(inst, def);
const origin = numericOriginMap[typeof def.value];
inst._zod.check = (payload) => {
if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return;
payload.issues.push({
origin: numericOriginMap[typeof payload.value] ?? origin,
code: "too_small",
minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
input: payload.value,
inclusive: def.inclusive,
inst,
continue: !def.abort
});
};
});
$ZodCheckMultipleOf = /*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
if (typeof payload.value !== typeof def.value) throw new Error("Cannot mix number and bigint in multiple_of check.");
if (typeof payload.value === "bigint" ? def.value !== BigInt(0) && payload.value % def.value === BigInt(0) : floatSafeRemainder(payload.value, def.value) === 0) return;
payload.issues.push({
origin: typeof payload.value,
code: "not_multiple_of",
divisor: def.value,
input: payload.value,
inst,
continue: !def.abort
});
};
});
$ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => {
$ZodCheck.init(inst, def);
def.format = def.format || "float64";
const isInt = def.format?.includes("int");
const origin = isInt ? "int" : "number";
const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
inst._zod.check = (payload) => {
const input = payload.value;
if (isInt) {
if (!Number.isInteger(input)) {
payload.issues.push({
expected: origin,
format: def.format,
code: "invalid_type",
continue: false,
input,
inst
});
return;
}
if (!Number.isSafeInteger(input)) {
if (input > 0) payload.issues.push({
input,
code: "too_big",
maximum: Number.MAX_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort
});
else payload.issues.push({
input,
code: "too_small",
minimum: Number.MIN_SAFE_INTEGER,
note: "Integers must be within the safe integer range.",
inst,
origin,
inclusive: true,
continue: !def.abort
});
return;
}
}
if (input < minimum) payload.issues.push({
origin: "number",
input,
code: "too_small",
minimum,
inclusive: true,
inst,
continue: !def.abort
});
if (input > maximum) payload.issues.push({
origin: "number",
input,
code: "too_big",
maximum,
inclusive: true,
inst,
continue: !def.abort
});
};
});
$ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
const units = input.length;
if ((typeof input === "string" && units > def.maximum ? codePointLength(input) : units) <= def.maximum) return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_big",
maximum: def.maximum,
inclusive: true,
input,
inst,
continue: !def.abort
});
};
});
$ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
const units = input.length;
if ((typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units) >= def.minimum) return;
const origin = getLengthableOrigin(input);
payload.issues.push({
origin,
code: "too_small",
minimum: def.minimum,
inclusive: true,
input,
inst,
continue: !def.abort
});
};
});
$ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => {
var _a;
$ZodCheck.init(inst, def);
(_a = inst._zod.def).when ?? (_a.when = _whenHasLength);
inst._zod.check = (payload) => {
const input = payload.value;
const units = input.length;
const length = typeof input === "string" && units >= def.length && units <= def.length * 2 ? codePointLength(input) : units;
if (length === def.length) return;
const origin = getLengthableOrigin(input);
const tooBig = length > def.length;
payload.issues.push({
origin,
...tooBig ? {
code: "too_big",
maximum: def.length
} : {
code: "too_small",
minimum: def.length
},
inclusive: true,
exact: true,
input: payload.value,
inst,
continue: !def.abort
});
};
});
$ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => {
var _a, _b;
$ZodCheck.init(inst, def);
if (def.pattern) (_a = inst._zod).check ?? (_a.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: def.format,
input: payload.value,
...def.pattern ? { pattern: def.pattern.toString() } : {},
inst,
continue: !def.abort
});
});
else (_b = inst._zod).check ?? (_b.check = () => {});
});
$ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => {
$ZodCheckStringFormat.init(inst, def);
inst._zod.check = (payload) => {
def.pattern.lastIndex = 0;
if (def.pattern.test(payload.value)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "regex",
input: payload.value,
pattern: def.pattern.toString(),
inst,
continue: !def.abort
});
};
});
$ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => {
def.pattern ?? (def.pattern = lowercase);
$ZodCheckStringFormat.init(inst, def);
});
$ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => {
def.pattern ?? (def.pattern = uppercase);
$ZodCheckStringFormat.init(inst, def);
});
$ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => {
$ZodCheck.init(inst, def);
const escapedRegex = escapeRegex(def.includes);
def.pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex);
inst._zod.check = (payload) => {
if (payload.value.includes(def.includes, def.position)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "includes",
includes: def.includes,
input: payload.value,
inst,
continue: !def.abort
});
};
});
$ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
def.pattern ?? (def.pattern = pattern);
inst._zod.check = (payload) => {
if (payload.value.startsWith(def.prefix)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "starts_with",
prefix: def.prefix,
input: payload.value,
inst,
continue: !def.abort
});
};
});
$ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => {
$ZodCheck.init(inst, def);
const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
def.pattern ?? (def.pattern = pattern);
inst._zod.check = (payload) => {
if (payload.value.endsWith(def.suffix)) return;
payload.issues.push({
origin: "string",
code: "invalid_format",
format: "ends_with",
suffix: def.suffix,
input: payload.value,
inst,
continue: !def.abort
});
};
});
$ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => {
$ZodCheck.init(inst, def);
inst._zod.check = (payload) => {
payload.value = def.tx(payload.value);
};
});
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/doc.js
var Doc;
var init_doc = __esmMin((() => {
Doc = class {
constructor(args = [], closed = {}) {
this.content = [];
this.indent = 0;
this.args = args;
this.closed = closed;
}
indented(fn) {
this.indent += 1;
try {
fn(this);
} finally {
this.indent -= 1;
}
}
write(arg) {
if (typeof arg === "function") {
arg(this, { execution: "sync" });
arg(this, { execution: "async" });
return;
}
const lines = arg.split("\n").filter((x) => x);
const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
for (const line of dedented) this.content.push(line);
}
compile() {
const F = Function;
const content = this?.content ?? [``];
return new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`)(...Object.values(this.closed));
}
};
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/versions.js
var version;
var init_versions = __esmMin((() => {
version = {
major: 4,
minor: 6,
patch: 5
};
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/schemas.js
async function validateAsync(inst, value) {
const ctx = { async: true };
return toStandardResult(await inst._zod.run({
value,
issues: []
}, ctx), ctx);
}
function standardProps(inst) {
return {
validate: (value) => {
const ctx = { async: false };
try {
const r = inst._zod.run({
value,
issues: []
}, ctx);
if (!(r instanceof Promise)) return toStandardResult(r, ctx);
} catch (_) {}
return validateAsync(inst, value);
},
vendor: "zod",
version: 1
};
}
function canParseURL(input) {
try {
if (typeof URL !== "undefined" && typeof URL.canParse === "function") return URL.canParse(input);
new URL(input);
return true;
} catch {
return false;
}
}
function validateURL(trimmed, def) {
if (!("normalize" in def) && !("hostname" in def) && !("protocol" in def)) return canParseURL(trimmed) || 2;
return parseURLObject(trimmed, def);
}
/** Parses a URL while preserving the non-normalizing HTTP guard. */
function parseURLObject(trimmed, def) {
if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) return 1;
try {
if (typeof URL !== "undefined") {
const URLStatic = URL;
if (typeof URLStatic.parse === "function") return URLStatic.parse(trimmed) ?? 2;
}
return new URL(trimmed);
} catch {
return 2;
}
}
/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */
function stripTabAndNewline(value) {
return value.replace(asciiTabOrNewline, "");
}
function urlHostnameOk(url, hostname) {
hostname.lastIndex = 0;
return hostname.test(url.hostname);
}
function urlProtocolOk(url, protocol) {
protocol.lastIndex = 0;
return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol);
}
function isValidIPv6(value) {
if (!ipv6Alphabet.test(value)) return false;
return canParseURL(`http://[${value}]`);
}
function isValidCIDRv6(value) {
const parts = value.split("/");
if (parts.length !== 2) return false;
const [address, prefix] = parts;
if (!prefix) return false;
const prefixNum = Number(prefix);
if (`${prefixNum}` !== prefix) return false;
if (prefixNum < 0 || prefixNum > 128) return false;
return isValidIPv6(address);
}
function isValidBase64(data) {
if (data === "") return true;
if (/\s/.test(data)) return false;
if (data.length % 4 !== 0) return false;
try {
atob(data);
return true;
} catch {
return false;
}
}
function isValidBase64URL(data) {
if (!base64urlCharset.test(data)) return false;
const base64 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
return isValidBase64(base64.padEnd(Math.ceil(base64.length / 4) * 4, "="));
}
function isValidJWT(token, algorithm = null) {
try {
const tokensParts = token.split(".");
if (tokensParts.length !== 3) return false;
const [header] = tokensParts;
if (!header) return false;
const parsedHeader = JSON.parse(atob(header));
if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") return false;
if (!parsedHeader.alg) return false;
if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) return false;
return true;
} catch {
return false;
}
}
function handleArrayResult(result, final, index) {
if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
final.value[index] = result.value;
}
function handlePropertyResult(result, final, key, input, optin, optout) {
const isPresent = key in input;
const isOptionalOut = optout === "optional";
if (!isPresent && isOptionalOut && optin === "optional") return;
if (result.issues.length) {
if (optin !== void 0 && isOptionalOut && !isPresent) return;
final.issues.push(...prefixIssues(key, result.issues));
}
if (!isPresent && optin === void 0) {
if (!result.issues.length) final.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: void 0,
path: [key]
});
return;
}
if (result.value === void 0) {
if (isPresent || optin === "defaulted" && !isOptionalOut) final.value[key] = void 0;
} else final.value[key] = result.value;
}
function normalizeDef(def) {
const keys = Object.keys(def.shape);
const ownSymbols = Object.getOwnPropertySymbols(def.shape);
const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS;
const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys;
for (const k of allKeys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`);
const okeys = optionalKeys(def.shape);
return {
...def,
allKeys,
symbolKeys,
keySet: new Set(keys),
numKeys: keys.length,
optionalKeys: new Set(okeys)
};
}
function handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) {
const unrecognized = [];
const keySet = def.keySet;
const _catchall = def.catchall._zod;
const t = _catchall.def.type;
const optin = _catchall.optin;
const optout = _catchall.optout;
let seen = 0;
for (const key in input) {
if (abortEarly && payload.issues.length !== seen) {
if (aborted(payload, seen)) break;
seen = payload.issues.length;
}
if (keySet.has(key)) continue;
if (key === "__proto__") {
if (t === "never") unrecognized.push(key);
continue;
}
if (t === "never") {
unrecognized.push(key);
continue;
}
const r = _catchall.run({
value: input[key],
issues: []
}, ctx);
if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
else handlePropertyResult(r, payload, key, input, optin, optout);
}
if (unrecognized.length) payload.issues.push({
code: "unrecognized_keys",
keys: unrecognized,
input,
inst,
continue: true
});
if (!proms.length) return payload;
return Promise.all(proms).then(() => {
return payload;
});
}
function handleUnionResults(results, final, inst, ctx) {
for (const result of results) if (result.issues.length === 0) {
final.value = result.value;
return final;
}
const nonaborted = results.filter((r) => !aborted(r));
if (nonaborted.length === 1) {
final.value = nonaborted[0].value;
return nonaborted[0];
}
final.issues.push({
code: "invalid_union",
input: final.value,
inst,
errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
});
return final;
}
function mergeValues(a, b) {
if (a === b) return {
valid: true,
data: a
};
if (a instanceof Date && b instanceof Date && +a === +b) return {
valid: true,
data: a
};
if (isPlainObject(a) && isPlainObject(b)) {
const bKeys = Object.keys(b);
const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
const newObj = {
...a,
...b
};
if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) delete newObj.__proto__;
for (const key of sharedKeys) {
if (key === "__proto__") continue;
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) return {
valid: false,
mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
};
newObj[key] = sharedValue.data;
}
return {
valid: true,
data: newObj
};
}
if (Array.isArray(a) && Array.isArray(b)) {
if (a.length !== b.length) return {
valid: false,
mergeErrorPath: []
};
const newArray = [];
for (let index = 0; index < a.length; index++) {
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) return {
valid: false,
mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
};
newArray.push(sharedValue.data);
}
return {
valid: true,
data: newArray
};
}
return {
valid: false,
mergeErrorPath: []
};
}
function handleIntersectionResults(result, left, right) {
const unrecKeys = /* @__PURE__ */ new Map();
let unrecIssue;
const keyIssues = /* @__PURE__ */ new Map();
const collect = (iss, side) => {
let keys;
if (iss.code === "unrecognized_keys" && !iss.path?.length) {
unrecIssue ?? (unrecIssue = iss);
keys = iss.keys;
} else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) {
const k = String(iss.path[0]);
if (!keyIssues.has(k)) keyIssues.set(k, iss);
keys = [k];
} else return false;
for (const k of keys) {
if (!unrecKeys.has(k)) unrecKeys.set(k, {});
unrecKeys.get(k)[side] = true;
}
return true;
};
for (const iss of left.issues) if (!collect(iss, "l")) result.issues.push(iss);
for (const iss of right.issues) if (!collect(iss, "r")) result.issues.push(iss);
const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
if (bothKeys.length) {
const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : [];
if (aggregated.length) result.issues.push({
...unrecIssue,
keys: aggregated
});
for (const k of bothKeys) if (!aggregated.includes(k) && keyIssues.has(k)) result.issues.push(keyIssues.get(k));
}
const merged = mergeValues(left.value, right.value);
if (!merged.valid) {
if (aborted(result)) return result;
throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
}
result.value = merged.data;
return result;
}
function handleOptionalResult(payload, result) {
payload.value = result.issues.length ? void 0 : result.value;
return payload;
}
function handleDefaultResult(payload, def) {
if (payload.value === void 0) payload.value = def.defaultValue;
return payload;
}
function handleNonOptionalResult(payload, inst) {
if (!payload.issues.length && payload.value === void 0) payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: payload.value,
inst
});
return payload;
}
function handleCatchResult(payload, result, def, ctx) {
if (!result.issues.length) {
payload.value = result.value;
if (result.memo) payload.memo = true;
return payload;
}
payload.value = def.catchValue({
...result,
value: payload.value,
error: { issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())) },
input: payload.value
});
return payload;
}
function handlePipeResult(left, next, ctx) {
if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) {
left.aborted = true;
return left;
}
return next._zod.run({
value: left.value,
issues: left.issues
}, ctx);
}
function handleReadonlyResult(payload) {
if (!payload.memo) payload.value = Object.freeze(payload.value);
return payload;
}
function handleRefineResult(result, payload, input, inst) {
if (!result) {
const _iss = {
code: "custom",
input,
inst,
path: [...inst._zod.def.path ?? []],
continue: !inst._zod.def.abort
};
if (inst._zod.def.params) _iss.params = inst._zod.def.params;
payload.issues.push(issue(_iss));
}
}
var $ZodType, toStandardResult, $ZodString, $ZodStringFormat, $ZodGUID, $ZodUUID, $ZodEmail, asciiTabOrNewline, $ZodURL, $ZodEmoji, $ZodNanoID, $ZodCUID, $ZodCUID2, $ZodULID, $ZodXID, $ZodKSUID, $ZodISODateTime, $ZodISODate, $ZodISOTime, $ZodISODuration, $ZodIPv4, ipv6Alphabet, $ZodIPv6, $ZodCIDRv4, $ZodCIDRv6, base64Charset, $ZodBase64, base64urlCharset, $ZodBase64URL, $ZodE164, $ZodJWT, $ZodNumber, $ZodNumberFormat, $ZodBoolean, $ZodUnknown, $ZodNever, $ZodArray, NO_SYMBOL_KEYS, $ZodObject, $ZodObjectJIT, $ZodUnion, $ZodIntersection, $ZodEnum, $ZodLiteral, $ZodTransform, $ZodOptional, $ZodExactOptional, $ZodNullable, $ZodDefault, $ZodPrefault, $ZodNonOptional, $ZodCatch, $ZodPipe, $ZodReadonly, $ZodCustom;
var init_schemas$1 = __esmMin((() => {
init_checks$1();
init_core$1();
init_doc();
init_regexes();
init_util();
init_versions();
$ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
var _a;
inst ?? (inst = {});
inst._zod.def = def;
inst._zod.bag = inst._zod.bag || {};
inst._zod.version = version;
const defChecks = inst._zod.def.checks;
const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : [];
for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst);
if (checks.length === 0) {
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred?.push(() => {
inst._zod.run = inst._zod.parse;
});
} else {
const runChecks = (payload, checks, ctx) => {
if (payload.memo) return payload;
let isAborted = aborted(payload);
let asyncResult;
for (const ch of checks) {
if (ch._zod.def.when) {
if (explicitlyAborted(payload)) continue;
if (!ch._zod.def.when(payload)) continue;
} else if (isAborted) continue;
const currLen = payload.issues.length;
const _ = ch._zod.check(payload);
if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError();
if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
await _;
if (payload.issues.length === currLen) return;
attachSchema(payload.issues, currLen, inst);
if (!isAborted) isAborted = aborted(payload, currLen);
});
else {
if (payload.issues.length === currLen) continue;
attachSchema(payload.issues, currLen, inst);
if (!isAborted) isAborted = aborted(payload, currLen);
}
}
if (asyncResult) return asyncResult.then(() => {
return payload;
});
return payload;
};
const handleCanaryResult = (canary, payload, ctx) => {
if (aborted(canary)) {
canary.aborted = true;
return canary;
}
const checkResult = runChecks(payload, checks, ctx);
if (checkResult instanceof Promise) {
if (ctx.async === false) throw new $ZodAsyncError();
return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));
}
return inst._zod.parse(checkResult, ctx);
};
inst._zod.run = (payload, ctx) => {
if (ctx.skipChecks) return inst._zod.parse(payload, ctx);
if (ctx.direction === "backward") {
const canary = inst._zod.parse({
value: payload.value,
issues: []
}, {
...ctx,
skipChecks: true
});
if (canary instanceof Promise) return canary.then((canary) => {
return handleCanaryResult(canary, payload, ctx);
});
return handleCanaryResult(canary, payload, ctx);
}
const result = inst._zod.parse(payload, ctx);
if (result instanceof Promise) {
if (ctx.async === false) throw new $ZodAsyncError();
return result.then((result) => runChecks(result, checks, ctx));
}
return runChecks(result, checks, ctx);
};
}
}, {
get "~standard"() {
return hide(this, "~standard", standardProps(this));
},
set "~standard"(value) {
own(this, "~standard", value);
}
});
toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value };
$ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = def.pattern ?? anyString;
inst._zod.parse = (payload, _) => {
if (def.coerce) try {
payload.value = String(payload.value);
} catch (_) {}
if (typeof payload.value === "string") return payload;
payload.issues.push({
expected: "string",
code: "invalid_type",
input: payload.value,
inst
});
return payload;
};
});
$ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => {
$ZodCheckStringFormat.init(inst, def);
$ZodString.init(inst, def);
});
$ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => {
def.pattern ?? (def.pattern = guid);
$ZodStringFormat.init(inst, def);
});
$ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => {
if (def.version) {
const v = {
v1: 1,
v2: 2,
v3: 3,
v4: 4,
v5: 5,
v6: 6,
v7: 7,
v8: 8
}[def.version];
if (v === void 0) throw new Error(`Invalid UUID version: "${def.version}"`);
def.pattern ?? (def.pattern = uuid(v));
} else def.pattern ?? (def.pattern = uuid());
$ZodStringFormat.init(inst, def);
});
$ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => {
def.pattern ?? (def.pattern = email);
$ZodStringFormat.init(inst, def);
});
asciiTabOrNewline = /[\t\n\r]/g;
$ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
try {
const trimmed = payload.value.trim();
const url = validateURL(trimmed, def);
if (url === 1) {
payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid URL format",
input: payload.value,
inst,
continue: !def.abort
});
return;
}
if (url === 2) {
payload.issues.push({
code: "invalid_format",
format: "url",
input: payload.value,
inst,
continue: !def.abort
});
return;
}
if (url === true) {
payload.value = stripTabAndNewline(trimmed);
return;
}
if (def.hostname && !urlHostnameOk(url, def.hostname)) payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid hostname",
pattern: def.hostname.source,
input: payload.value,
inst,
continue: !def.abort
});
if (def.protocol && !urlProtocolOk(url, def.protocol)) payload.issues.push({
code: "invalid_format",
format: "url",
note: "Invalid protocol",
pattern: def.protocol.source,
input: payload.value,
inst,
continue: !def.abort
});
payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed);
return;
} catch (_) {
payload.issues.push({
code: "invalid_format",
format: "url",
input: payload.value,
inst,
continue: !def.abort
});
}
};
});
$ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => {
def.pattern ?? (def.pattern = emoji());
$ZodStringFormat.init(inst, def);
});
$ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => {
if (def.length !== void 0 && (!Number.isInteger(def.length) || def.length < 1)) throw new Error(`Invalid nanoid length: ${def.length}`);
def.pattern ?? (def.pattern = def.length === void 0 ? nanoid : nanoidOfLength(def.length));
$ZodStringFormat.init(inst, def);
});
$ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => {
def.pattern ?? (def.pattern = cuid);
$ZodStringFormat.init(inst, def);
});
$ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => {
def.pattern ?? (def.pattern = cuid2);
$ZodStringFormat.init(inst, def);
});
$ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => {
def.pattern ?? (def.pattern = ulid);
$ZodStringFormat.init(inst, def);
});
$ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => {
def.pattern ?? (def.pattern = xid);
$ZodStringFormat.init(inst, def);
});
$ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => {
def.pattern ?? (def.pattern = ksuid);
$ZodStringFormat.init(inst, def);
});
$ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => {
def.pattern ?? (def.pattern = datetime(def));
$ZodStringFormat.init(inst, def);
});
$ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => {
def.pattern ?? (def.pattern = date);
$ZodStringFormat.init(inst, def);
});
$ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => {
def.pattern ?? (def.pattern = time(def));
$ZodStringFormat.init(inst, def);
});
$ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => {
def.pattern ?? (def.pattern = duration);
$ZodStringFormat.init(inst, def);
});
$ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => {
def.pattern ?? (def.pattern = ipv4);
$ZodStringFormat.init(inst, def);
});
ipv6Alphabet = /^[0-9a-fA-F:.]+$/;
$ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => {
def.pattern ?? (def.pattern = ipv6);
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
if (!isValidIPv6(payload.value)) payload.issues.push({
code: "invalid_format",
format: "ipv6",
input: payload.value,
inst,
continue: !def.abort
});
};
});
$ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => {
def.pattern ?? (def.pattern = cidrv4);
$ZodStringFormat.init(inst, def);
});
$ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => {
def.pattern ?? (def.pattern = cidrv6);
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
if (!isValidCIDRv6(payload.value)) payload.issues.push({
code: "invalid_format",
format: "cidrv6",
input: payload.value,
inst,
continue: !def.abort
});
};
});
base64Charset = /^[0-9a-zA-Z+/]*={0,2}$/;
$ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => {
def.pattern ?? (def.pattern = base64Charset);
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
if (isValidBase64(payload.value)) return;
payload.issues.push({
code: "invalid_format",
format: "base64",
input: payload.value,
inst,
continue: !def.abort
});
};
});
base64urlCharset = /^[A-Za-z0-9_-]*$/;
$ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => {
def.pattern ?? (def.pattern = base64urlCharset);
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
if (isValidBase64URL(payload.value)) return;
payload.issues.push({
code: "invalid_format",
format: "base64url",
input: payload.value,
inst,
continue: !def.abort
});
};
});
$ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => {
def.pattern ?? (def.pattern = e164);
$ZodStringFormat.init(inst, def);
});
$ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => {
$ZodStringFormat.init(inst, def);
inst._zod.check = (payload) => {
if (isValidJWT(payload.value, def.alg)) return;
payload.issues.push({
code: "invalid_format",
format: "jwt",
input: payload.value,
inst,
continue: !def.abort
});
};
});
$ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = number$1;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce) try {
payload.value = Number(payload.value);
} catch (_) {}
const input = payload.value;
if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload;
const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? String(input) : void 0 : void 0;
payload.issues.push({
expected: "number",
code: "invalid_type",
input,
inst,
...received ? { received } : {}
});
return payload;
};
});
$ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => {
$ZodCheckNumberFormat.init(inst, def);
$ZodNumber.init(inst, def);
});
$ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.pattern = boolean$1;
inst._zod.parse = (payload, _ctx) => {
if (def.coerce) try {
payload.value = Boolean(payload.value);
} catch (_) {}
const input = payload.value;
if (typeof input === "boolean") return payload;
payload.issues.push({
expected: "boolean",
code: "invalid_type",
input,
inst
});
return payload;
};
});
$ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload) => payload;
});
$ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, _ctx) => {
payload.issues.push({
expected: "never",
code: "invalid_type",
input: payload.value,
inst
});
return payload;
};
});
$ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
$ZodType.init(inst, def);
const memo = globalConfig.memoizer;
memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
if (!Array.isArray(input)) {
payload.issues.push({
expected: "array",
code: "invalid_type",
input,
inst
});
return payload;
}
payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length);
const proms = [];
const abortEarly = ctx?.abortEarly;
for (let i = 0; i < input.length; i++) {
const item = input[i];
const result = def.element._zod.run({
value: item,
issues: []
}, ctx);
if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i)));
else {
handleArrayResult(result, payload, i);
if (abortEarly && result.issues.length !== 0 && aborted(result)) break;
}
}
if (proms.length) return Promise.all(proms).then(() => payload);
return payload;
};
});
NO_SYMBOL_KEYS = [];
$ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
$ZodType.init(inst, def);
const desc = Object.getOwnPropertyDescriptor(def, "shape");
const sh = desc?.get ? desc.get.raw : def.shape ?? {};
if (sh) {
const get = () => {
const newSh = { ...sh };
Object.defineProperty(def, "shape", { value: newSh });
get.raw = newSh;
return newSh;
};
get.raw = sh;
Object.defineProperty(def, "shape", { get });
}
const _normalized = cached(() => normalizeDef(def));
defineLazyInternal(inst, "propValues", (zod) => {
const shape = zod.def.shape;
const propValues = {};
for (const key in shape) {
const field = shape[key]._zod;
if (field.values) {
if (!Object.prototype.hasOwnProperty.call(propValues, key)) assignProp(propValues, key, /* @__PURE__ */ new Set());
for (const v of field.values) propValues[key].add(v);
if (field.optin !== void 0) propValues[key].add(void 0);
}
}
return propValues;
});
const isObject$3 = isObject;
const catchall = def.catchall;
let value;
const memo = globalConfig.memoizer;
memo?.attach(inst);
inst._zod.parse = (payload, ctx) => {
value ?? (value = _normalized.value);
const input = payload.value;
if (!isObject$3(input)) {
payload.issues.push({
expected: "object",
code: "invalid_type",
input,
inst
});
return payload;
}
payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
const proms = [];
const shape = value.shape;
const abortEarly = ctx?.abortEarly;
let seen = payload.issues.length;
for (const key of value.allKeys) {
if (abortEarly && payload.issues.length !== seen) {
if (aborted(payload, seen)) break;
seen = payload.issues.length;
}
if (key === "__proto__") continue;
const el = shape[key];
const optin = el._zod.optin;
const optout = el._zod.optout;
const r = el._zod.run({
value: input[key],
issues: []
}, ctx);
if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout)));
else handlePropertyResult(r, payload, key, input, optin, optout);
}
if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload;
return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true);
};
});
$ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => {
$ZodObject.init(inst, def);
const superParse = inst._zod.parse;
const _normalized = cached(() => normalizeDef(def));
const memo = globalConfig.memoizer;
const generateFastpass = (shape) => {
const normalized = _normalized.value;
const syms = normalized.symbolKeys;
const doc = new Doc(["payload", "ctx"], {
shape,
inst,
memo,
syms
});
const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;
const prefixStr = (id, k) => `
let ${id}_ab = false;
for (let i = 0; i < ${id}.issues.length; i++) {
const iss = ${id}.issues[i];
iss.path = iss.path ? [${k}, ...iss.path] : [${k}];
payload.issues.push(iss);
if (iss.continue !== true) ${id}_ab = true;
}
if (${id}_ab && ctx && ctx.abortEarly) {
payload.value = newResult;
return payload;
}`;
doc.write(`const input = payload.value;`);
const ids = Object.create(null);
let counter = 0;
for (const key of normalized.allKeys) ids[key] = `key_${counter++}`;
doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`);
for (const key of normalized.allKeys) {
if (key === "__proto__") continue;
const id = ids[key];
const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : esc(key);
const isPresent = `${k} in input`;
const schema = shape[key];
const optin = schema?._zod?.optin;
const isOptionalIn = optin !== void 0;
const isOptionalOut = schema?._zod?.optout === "optional";
doc.write(`const ${id} = ${parseStr(k)};`);
if (isOptionalIn && isOptionalOut) {
const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`;
doc.write(`
const ${id}_present = ${isPresent};
if (!${id}.issues.length || ${id}_present) {
if (${id}.issues.length) {${prefixStr(id, k)}
}
if (${assign}) {
newResult[${k}] = ${id}.value;
}
}
`);
} else if (!isOptionalIn) doc.write(`
const ${id}_present = ${isPresent};
if (${id}.issues.length) {${prefixStr(id, k)}
}
if (!${id}_present && !${id}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${k}]
});
if (ctx && ctx.abortEarly) {
payload.value = newResult;
return payload;
}
}
if (${id}_present) {
newResult[${k}] = ${id}.value;
}
`);
else {
doc.write(`
if (${id}.issues.length) {${prefixStr(id, k)}
}
`);
if (optin === "defaulted") doc.write(`newResult[${k}] = ${id}.value;`);
else doc.write(`
if (${id}.value !== undefined || ${isPresent}) {
newResult[${k}] = ${id}.value;
}
`);
}
}
doc.write(`payload.value = newResult;`);
doc.write(`return payload;`);
return doc.compile();
};
let fastpass;
const isObject$2 = isObject;
const jit = !globalConfig.jitless;
const fastEnabled = jit && allowsEval.value;
const catchall = def.catchall;
let value;
inst._zod.parse = (payload, ctx) => {
value ?? (value = _normalized.value);
const input = payload.value;
if (!isObject$2(input)) {
payload.issues.push({
expected: "object",
code: "invalid_type",
input,
inst
});
return payload;
}
if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {
if (!fastpass) fastpass = generateFastpass(def.shape);
payload = fastpass(payload, ctx);
if (!catchall) return payload;
return handleCatchall([], input, payload, ctx, value, inst, ctx?.abortEarly === true);
}
return superParse(payload, ctx);
};
});
$ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => {
$ZodType.init(inst, def);
defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") ? "defaulted" : zod.def.options.some((o) => o._zod.optin !== void 0) ? "optional" : void 0);
defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
defineLazyInternal(inst, "values", (zod) => {
if (zod.def.options.every((o) => o._zod.values)) return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values)));
});
defineLazyInternal(inst, "pattern", (zod) => {
if (zod.def.options.every((o) => o._zod.pattern)) {
const patterns = zod.def.options.map((o) => o._zod.pattern);
return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
}
});
const first = def.options.length === 1 ? def.options[0]._zod.run : null;
inst._zod.parse = (payload, ctx) => {
if (first) return first(payload, ctx);
let async = false;
const results = [];
for (const option of def.options) {
const result = option._zod.run({
value: payload.value,
issues: []
}, ctx);
if (result instanceof Promise) {
results.push(result);
async = true;
} else {
if (result.issues.length === 0) return result;
results.push(result);
}
}
if (!async) return handleUnionResults(results, payload, inst, ctx);
return Promise.all(results).then((results) => {
return handleUnionResults(results, payload, inst, ctx);
});
};
});
$ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.parse = (payload, ctx) => {
const input = payload.value;
const left = def.left._zod.run({
value: input,
issues: []
}, ctx);
const right = def.right._zod.run({
value: input,
issues: []
}, ctx);
if (left instanceof Promise || right instanceof Promise) return Promise.all([left, right]).then(([left, right]) => {
return handleIntersectionResults(payload, left, right);
});
return handleIntersectionResults(payload, left, right);
};
});
$ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
$ZodType.init(inst, def);
const values = getEnumValues(def.entries);
const valuesSet = new Set(values);
inst._zod.values = valuesSet;
defineLazyInternal(inst, "pattern", (zod) => {
const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k));
return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$");
});
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (valuesSet.has(input)) return payload;
payload.issues.push({
code: "invalid_value",
values,
input,
inst
});
return payload;
};
});
$ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => {
$ZodType.init(inst, def);
const values = new Set(def.values);
inst._zod.values = values;
defineLazyInternal(inst, "pattern", (zod) => {
const vals = zod.def.values;
return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$");
});
inst._zod.parse = (payload, _ctx) => {
const input = payload.value;
if (values.has(input)) return payload;
payload.issues.push({
code: "invalid_value",
values: def.values,
input,
inst
});
return payload;
};
});
$ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "optional";
globalConfig.memoizer?.guard(inst);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
const _out = def.transform(payload.value, payload);
if (ctx.async) return (_out instanceof Promise ? _out : Promise.resolve(_out)).then((output) => {
payload.value = output;
return payload;
});
if (_out instanceof Promise) throw new $ZodAsyncError();
payload.value = _out;
return payload;
};
});
$ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => {
$ZodType.init(inst, def);
defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
inst._zod.optout = "optional";
defineLazyInternal(inst, "values", (zod) => {
const values = zod.def.innerType._zod.values;
return values ? /* @__PURE__ */ new Set([...values, void 0]) : void 0;
});
defineLazyInternal(inst, "pattern", (zod) => {
const pattern = zod.def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
});
inst._zod.parse = (payload, ctx) => {
if (payload.value === void 0) {
if (def.innerType._zod.optin !== "defaulted") return payload;
const result = def.innerType._zod.run({
value: payload.value,
issues: []
}, ctx);
if (result instanceof Promise) return result.then((result) => handleOptionalResult(payload, result));
return handleOptionalResult(payload, result);
}
return def.innerType._zod.run(payload, ctx);
};
});
$ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => {
$ZodOptional.init(inst, def);
defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern);
inst._zod.parse = (payload, ctx) => {
return def.innerType._zod.run(payload, ctx);
};
});
$ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => {
$ZodType.init(inst, def);
defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin);
defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
defineLazyInternal(inst, "pattern", (zod) => {
const pattern = zod.def.innerType._zod.pattern;
return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
});
defineLazyInternal(inst, "values", (zod) => {
return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0;
});
inst._zod.parse = (payload, ctx) => {
if (payload.value === null) return payload;
return def.innerType._zod.run(payload, ctx);
};
});
$ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "defaulted";
defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
if (payload.value === void 0) {
payload.value = def.defaultValue;
/**
* $ZodDefault returns the default value immediately in forward direction.
* It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */
return payload;
}
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result) => handleDefaultResult(result, def));
return handleDefaultResult(result, def);
};
});
$ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => {
$ZodType.init(inst, def);
inst._zod.optin = "defaulted";
defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
if (payload.value === void 0) payload.value = def.defaultValue;
return def.innerType._zod.run(payload, ctx);
};
});
$ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => {
$ZodType.init(inst, def);
defineLazyInternal(inst, "values", (zod) => {
const v = zod.def.innerType._zod.values;
return v ? new Set([...v].filter((x) => x !== void 0)) : void 0;
});
inst._zod.parse = (payload, ctx) => {
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then((result) => handleNonOptionalResult(result, inst));
return handleNonOptionalResult(result, inst);
};
});
$ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => {
$ZodType.init(inst, def);
defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional");
defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout);
defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
const result = def.innerType._zod.run({
value: payload.value,
issues: []
}, ctx);
if (result instanceof Promise) return result.then((result) => handleCatchResult(payload, result, def, ctx));
return handleCatchResult(payload, result, def, ctx);
};
});
$ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => {
$ZodType.init(inst, def);
defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values);
defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin);
defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout);
defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") {
const right = def.out._zod.run(payload, ctx);
if (right instanceof Promise) return right.then((right) => handlePipeResult(right, def.in, ctx));
return handlePipeResult(right, def.in, ctx);
}
const left = def.in._zod.run(payload, ctx);
if (left instanceof Promise) return left.then((left) => handlePipeResult(left, def.out, ctx));
return handlePipeResult(left, def.out, ctx);
};
});
$ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => {
$ZodType.init(inst, def);
defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues);
defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values);
defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin);
defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout);
inst._zod.parse = (payload, ctx) => {
if (ctx.direction === "backward") return def.innerType._zod.run(payload, ctx);
const result = def.innerType._zod.run(payload, ctx);
if (result instanceof Promise) return result.then(handleReadonlyResult);
return handleReadonlyResult(result);
};
});
$ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => {
$ZodCheck.init(inst, def);
$ZodType.init(inst, def);
inst._zod.parse = (payload, _) => {
return payload;
};
inst._zod.check = (payload) => {
const input = payload.value;
const r = def.fn(input);
if (r instanceof Promise) return r.then((r) => handleRefineResult(r, payload, input, inst));
handleRefineResult(r, payload, input, inst);
};
});
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/memoizer.js
function isRef(value) {
return value !== null && typeof value === "object";
}
function cloneIssues(issues) {
return issues.map((iss) => iss.path ? {
...iss,
path: iss.path.slice()
} : { ...iss });
}
/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */
function isRecursive(inst, stack, resolve) {
const cached = recursive.get(inst);
if (cached !== void 0) return cached ? PROVEN : NONE;
if (stack.has(inst)) return PROVEN;
stack.add(inst);
let result = NONE;
const check = (child) => {
if (result !== PROVEN && child?._zod) {
const answer = isRecursive(child, stack, resolve);
if (answer > result) result = answer;
}
};
const shape = (sh, spread) => {
let answer = NONE;
for (const key of Reflect.ownKeys(sh)) {
const desc = Object.getOwnPropertyDescriptor(sh, key);
if (spread && !desc.enumerable) continue;
const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve) : NONE;
if (child > answer) answer = child;
}
return answer;
};
const merge = (answer) => {
if (answer > result) result = answer;
};
const def = inst._zod.def;
switch (def.type) {
case "object": {
const raw = rawShape(def);
merge(raw ? shape(raw, true) : ASSUMED);
check(def.catchall);
break;
}
case "array":
check(def.element);
break;
case "tuple":
for (const el of def.items) check(el);
check(def.rest);
break;
case "record":
case "map":
check(def.keyType);
check(def.valueType);
break;
case "set":
check(def.valueType);
break;
case "union":
for (const el of def.options) check(el);
break;
case "intersection":
check(def.left);
check(def.right);
break;
case "optional":
case "nullable":
case "default":
case "prefault":
case "catch":
case "readonly":
case "nonoptional":
case "promise":
case "success":
check(def.innerType);
break;
case "pipe":
check(def.in);
check(def.out);
break;
case "function":
check(def.input);
check(def.output);
break;
case "lazy": {
const inner = def._cachedInner ?? (resolve ? inst._zod.innerType : void 0);
merge(inner ? isRecursive(inner, stack, false) : ASSUMED);
break;
}
case "template_literal":
case "string":
case "number":
case "int":
case "boolean":
case "bigint":
case "symbol":
case "undefined":
case "null":
case "void":
case "never":
case "any":
case "unknown":
case "date":
case "nan":
case "enum":
case "literal":
case "file":
case "transform":
case "custom": break;
default: for (const key in def) {
const desc = Object.getOwnPropertyDescriptor(def, key);
if (!desc || desc.get) continue;
const value = desc.value;
if (!value || typeof value !== "object") continue;
if (value._zod) check(value);
else if (Array.isArray(value)) for (const el of value) check(el);
}
}
stack.delete(inst);
return settle(inst, result);
}
/** An assumed answer must not outlive the resolution that settles it, so only a certain one is cached. */
function settle(inst, answer) {
if (answer !== ASSUMED) recursive.set(inst, answer === PROVEN);
return answer;
}
function bucketFor(state, inst) {
let bucket = state.buckets.get(inst);
if (!bucket) {
bucket = /* @__PURE__ */ new WeakMap();
state.buckets.set(inst, bucket);
}
return bucket;
}
/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */
function memoizer() {
return memo;
}
/** Whether this value is a node a back-edge resolved to before it finished. */
function isBackEdge(ctx, value) {
const backEdges = ctx[STATE]?.backEdges;
return backEdges !== void 0 && isRef(value) && backEdges.has(value);
}
var $ZodCyclicError, STATE, NO_ISSUES, recursive, NONE, ASSUMED, PROVEN, handoff, open, memo;
var init_memoizer = __esmMin((() => {
init_util();
$ZodCyclicError = class extends Error {
constructor() {
super(`Cannot parse a reference cycle that closes through a transform`);
this.name = "ZodCyclicError";
}
};
STATE = "~memo";
NO_ISSUES = [];
recursive = /*@__PURE__*/ new WeakMap();
NONE = 0;
ASSUMED = 1;
PROVEN = 2;
open = [];
memo = {
alloc(_inst, payload, empty) {
const bucket = handoff;
if (!bucket) return empty;
handoff = void 0;
const entry = {
value: empty,
issues: null
};
bucket.set(payload.value, entry);
open.push(entry);
return empty;
},
guard(inst) {
var _a;
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred.push(() => {
const base = inst._zod.parse;
const wrapped = (payload, ctx) => {
if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) throw new $ZodCyclicError();
return base(payload, ctx);
};
inst._zod.parse = wrapped;
if (inst._zod.run === base) inst._zod.run = wrapped;
});
},
attach(inst) {
var _a;
let isRecursiveInst;
let rechecked = false;
let lastCtx;
let lastBucket;
(_a = inst._zod).deferred ?? (_a.deferred = []);
inst._zod.deferred.push(() => {
const base = inst._zod.parse;
const wrapped = (payload, ctx) => {
if (isRecursiveInst === void 0) {
const walked = isRecursive(inst, /* @__PURE__ */ new Set(), false);
if (walked === NONE) {
inst._zod.parse = base;
if (inst._zod.run === wrapped) inst._zod.run = base;
return base(payload, ctx);
}
if (walked === PROVEN || rechecked) isRecursiveInst = true;
else rechecked = true;
}
const input = payload.value;
if (!isRef(input)) return base(payload, ctx);
let state = ctx[STATE];
if (!state) {
state = {
buckets: /* @__PURE__ */ new WeakMap(),
backEdges: void 0
};
ctx[STATE] = state;
}
let bucket;
if (lastCtx === ctx) bucket = lastBucket;
else {
bucket = bucketFor(state, inst);
lastCtx = ctx;
lastBucket = bucket;
}
const hit = bucket.get(input);
if (hit) {
payload.value = hit.value;
if (hit.issues) {
if (hit.issues.length) payload.issues.push(...cloneIssues(hit.issues));
} else {
payload.memo = true;
state.backEdges ?? (state.backEdges = /* @__PURE__ */ new WeakSet());
state.backEdges.add(hit.value);
}
return payload;
}
handoff = bucket;
const depth = open.length;
const result = base(payload, ctx);
handoff = void 0;
const entry = open.length > depth ? open.pop() : void 0;
if (result instanceof Promise) return result.then((r) => {
if (entry) entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;
return r;
});
if (entry) entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES;
return result;
};
inst._zod.parse = wrapped;
if (inst._zod.run === base) inst._zod.run = wrapped;
});
}
};
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/locales/en.js
function en_default() {
return { localeError: error() };
}
var error;
var init_en = __esmMin((() => {
init_util();
error = () => {
const Sizable = {
string: {
unit: "characters",
verb: "to have"
},
file: {
unit: "bytes",
verb: "to have"
},
array: {
unit: "items",
verb: "to have"
},
set: {
unit: "items",
verb: "to have"
},
map: {
unit: "entries",
verb: "to have"
}
};
function getSizing(origin) {
return Sizable[origin] ?? null;
}
const FormatDictionary = {
regex: "input",
email: "email address",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "ISO datetime",
date: "ISO date",
time: "ISO time",
duration: "ISO duration",
ipv4: "IPv4 address",
ipv6: "IPv6 address",
mac: "MAC address",
cidrv4: "IPv4 range",
cidrv6: "IPv6 range",
base64: "base64-encoded string",
base64url: "base64url-encoded string",
json_string: "JSON string",
e164: "E.164 number",
currency_code: "currency code",
credit_card: "credit card number",
iban: "IBAN",
jwt: "JWT",
template_literal: "input"
};
const TypeDictionary = { nan: "NaN" };
function getTypeName(type, input) {
if (type === "number" && typeof input === "number" && !Number.isFinite(input)) return String(input);
return TypeDictionary[type] ?? type;
}
return (issue) => {
switch (issue.code) {
case "invalid_type": return `Invalid input: expected ${getTypeName(issue.expected)}, received ${getTypeName(parsedType(issue.input), issue.input)}`;
case "invalid_value":
if (issue.values.length === 1) return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`;
return `Invalid option: expected one of ${joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing) return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`;
return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`;
return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue;
if (_issue.format === "starts_with") return `Invalid string: must start with "${_issue.prefix}"`;
if (_issue.format === "ends_with") return `Invalid string: must end with "${_issue.suffix}"`;
if (_issue.format === "includes") return `Invalid string: must include "${_issue.includes}"`;
if (_issue.format === "regex") return `Invalid string: must match pattern ${_issue.pattern}`;
return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`;
}
case "not_multiple_of": return `Invalid number: must be a multiple of ${issue.divisor}`;
case "unrecognized_keys": return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`;
case "invalid_key": return `Invalid key in ${issue.origin}`;
case "invalid_union":
if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) return `Invalid discriminator value. Expected ${issue.options.map((o) => `'${o}'`).join(" | ")}`;
if (issue.inclusive === false) return "Invalid input: more than one option matched";
return "Invalid input";
case "invalid_element": return `Invalid value in ${issue.origin}`;
default: return `Invalid input`;
}
};
};
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/registries.js
function registry() {
return new $ZodRegistry();
}
var _a, $ZodRegistry, globalRegistry;
var init_registries = __esmMin((() => {
$ZodRegistry = class {
constructor() {
this._map = /* @__PURE__ */ new WeakMap();
this._idmap = /* @__PURE__ */ new Map();
}
add(schema, ..._meta) {
const meta = _meta[0];
this._map.set(schema, meta);
if (meta && typeof meta === "object" && "id" in meta) this._idmap.set(meta.id, schema);
return this;
}
clear() {
this._map = /* @__PURE__ */ new WeakMap();
this._idmap = /* @__PURE__ */ new Map();
return this;
}
remove(schema) {
const meta = this._map.get(schema);
if (meta && typeof meta === "object" && "id" in meta) this._idmap.delete(meta.id);
this._map.delete(schema);
return this;
}
get(schema) {
const p = schema._zod.parent;
if (p) {
const pm = { ...this.get(p) ?? {} };
delete pm.id;
const f = {
...pm,
...this._map.get(schema)
};
return Object.keys(f).length ? f : void 0;
}
return this._map.get(schema);
}
has(schema) {
return this._map.has(schema);
}
};
(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
globalRegistry = globalThis.__zod_globalRegistry;
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/compile.js
var init_compile = __esmMin((() => {}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/api.js
function snapshotChecks(def) {
if (def.checks) def.checks = [...def.checks];
return def;
}
// @__NO_SIDE_EFFECTS__
function _string(Class, params) {
return new Class(snapshotChecks({
type: "string",
...normalizeParams(params)
}));
}
// @__NO_SIDE_EFFECTS__
function _email(Class, params) {
return new Class({
type: "string",
format: "email",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _guid(Class, params) {
return new Class({
type: "string",
format: "guid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _uuid(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _uuidv4(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v4",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _uuidv6(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v6",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _uuidv7(Class, params) {
return new Class({
type: "string",
format: "uuid",
check: "string_format",
abort: false,
version: "v7",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _url(Class, params) {
return new Class({
type: "string",
format: "url",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _emoji(Class, params) {
return new Class({
type: "string",
format: "emoji",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _nanoid(Class, params) {
return new Class({
type: "string",
format: "nanoid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
/**
* @deprecated CUID v1 is deprecated by its authors due to information leakage
* (timestamps embedded in the id). Use {@link _cuid2} instead.
* See https://github.com/paralleldrive/cuid.
*/
// @__NO_SIDE_EFFECTS__
function _cuid(Class, params) {
return new Class({
type: "string",
format: "cuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _cuid2(Class, params) {
return new Class({
type: "string",
format: "cuid2",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _ulid(Class, params) {
return new Class({
type: "string",
format: "ulid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _xid(Class, params) {
return new Class({
type: "string",
format: "xid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _ksuid(Class, params) {
return new Class({
type: "string",
format: "ksuid",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _ipv4(Class, params) {
return new Class({
type: "string",
format: "ipv4",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _ipv6(Class, params) {
return new Class({
type: "string",
format: "ipv6",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _cidrv4(Class, params) {
return new Class({
type: "string",
format: "cidrv4",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _cidrv6(Class, params) {
return new Class({
type: "string",
format: "cidrv6",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _base64(Class, params) {
return new Class({
type: "string",
format: "base64",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _base64url(Class, params) {
return new Class({
type: "string",
format: "base64url",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _e164(Class, params) {
return new Class({
type: "string",
format: "e164",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _jwt(Class, params) {
return new Class({
type: "string",
format: "jwt",
check: "string_format",
abort: false,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _isoDateTime(Class, params) {
return new Class({
type: "string",
format: "datetime",
check: "string_format",
offset: false,
local: false,
precision: null,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _isoDate(Class, params) {
return new Class({
type: "string",
format: "date",
check: "string_format",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _isoTime(Class, params) {
return new Class({
type: "string",
format: "time",
check: "string_format",
precision: null,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _isoDuration(Class, params) {
return new Class({
type: "string",
format: "duration",
check: "string_format",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _number(Class, params) {
return new Class(snapshotChecks({
type: "number",
checks: [],
...normalizeParams(params)
}));
}
// @__NO_SIDE_EFFECTS__
function _int(Class, params) {
return new Class({
type: "number",
check: "number_format",
abort: false,
format: "safeint",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _boolean(Class, params) {
return new Class({
type: "boolean",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _unknown(Class) {
return new Class({ type: "unknown" });
}
// @__NO_SIDE_EFFECTS__
function _never(Class, params) {
return new Class({
type: "never",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _lt(value, params) {
return new $ZodCheckLessThan({
check: "less_than",
...normalizeParams(params),
value,
inclusive: false
});
}
// @__NO_SIDE_EFFECTS__
function _lte(value, params) {
return new $ZodCheckLessThan({
check: "less_than",
...normalizeParams(params),
value,
inclusive: true
});
}
// @__NO_SIDE_EFFECTS__
function _gt(value, params) {
return new $ZodCheckGreaterThan({
check: "greater_than",
...normalizeParams(params),
value,
inclusive: false
});
}
// @__NO_SIDE_EFFECTS__
function _gte(value, params) {
return new $ZodCheckGreaterThan({
check: "greater_than",
...normalizeParams(params),
value,
inclusive: true
});
}
// @__NO_SIDE_EFFECTS__
function _multipleOf(value, params) {
return new $ZodCheckMultipleOf({
check: "multiple_of",
...normalizeParams(params),
value
});
}
// @__NO_SIDE_EFFECTS__
function _maxLength(maximum, params) {
return new $ZodCheckMaxLength({
check: "max_length",
...normalizeParams(params),
maximum
});
}
// @__NO_SIDE_EFFECTS__
function _minLength(minimum, params) {
return new $ZodCheckMinLength({
check: "min_length",
...normalizeParams(params),
minimum
});
}
// @__NO_SIDE_EFFECTS__
function _length(length, params) {
return new $ZodCheckLengthEquals({
check: "length_equals",
...normalizeParams(params),
length
});
}
// @__NO_SIDE_EFFECTS__
function _regex(pattern, params) {
return new $ZodCheckRegex({
check: "string_format",
format: "regex",
...normalizeParams(params),
pattern
});
}
// @__NO_SIDE_EFFECTS__
function _lowercase(params) {
return new $ZodCheckLowerCase({
check: "string_format",
format: "lowercase",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _uppercase(params) {
return new $ZodCheckUpperCase({
check: "string_format",
format: "uppercase",
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _includes(includes, params) {
return new $ZodCheckIncludes({
check: "string_format",
format: "includes",
...normalizeParams(params),
includes
});
}
// @__NO_SIDE_EFFECTS__
function _startsWith(prefix, params) {
return new $ZodCheckStartsWith({
check: "string_format",
format: "starts_with",
...normalizeParams(params),
prefix
});
}
// @__NO_SIDE_EFFECTS__
function _endsWith(suffix, params) {
return new $ZodCheckEndsWith({
check: "string_format",
format: "ends_with",
...normalizeParams(params),
suffix
});
}
// @__NO_SIDE_EFFECTS__
function _overwrite(tx) {
return new $ZodCheckOverwrite({
check: "overwrite",
tx
});
}
// @__NO_SIDE_EFFECTS__
function _normalize(form) {
return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
}
// @__NO_SIDE_EFFECTS__
function _trim() {
return /* @__PURE__ */ _overwrite((input) => input.trim());
}
// @__NO_SIDE_EFFECTS__
function _toLowerCase() {
return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
}
// @__NO_SIDE_EFFECTS__
function _toUpperCase() {
return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
}
// @__NO_SIDE_EFFECTS__
function _slugify() {
return /* @__PURE__ */ _overwrite((input) => slugify(input));
}
// @__NO_SIDE_EFFECTS__
function _array(Class, element, params) {
return new Class({
type: "array",
element,
...normalizeParams(params)
});
}
// @__NO_SIDE_EFFECTS__
function _custom(Class, fn, _params) {
const norm = normalizeParams(_params);
norm.abort ?? (norm.abort = true);
return new Class({
type: "custom",
check: "custom",
fn,
...norm
});
}
// @__NO_SIDE_EFFECTS__
function _refine(Class, fn, _params) {
return new Class({
type: "custom",
check: "custom",
fn,
...normalizeParams(_params)
});
}
// @__NO_SIDE_EFFECTS__
function _superRefine(fn, params) {
const ch = /* @__PURE__ */ _check((payload) => {
payload.addIssue = (issue$2) => {
if (typeof issue$2 === "string") payload.issues.push(issue(issue$2, payload.value, ch._zod.def));
else {
const _issue = issue$2;
if (_issue.fatal) _issue.continue = false;
_issue.code ?? (_issue.code = "custom");
if (!("input" in _issue)) _issue.input = payload.value;
_issue.inst ?? (_issue.inst = ch);
_issue.continue ?? (_issue.continue = !ch._zod.def.abort);
payload.issues.push(issue(_issue));
}
};
return fn(payload.value, payload);
}, params);
return ch;
}
// @__NO_SIDE_EFFECTS__
function _check(fn, params) {
const ch = new $ZodCheck({
check: "custom",
...normalizeParams(params)
});
ch._zod.check = fn;
return ch;
}
var init_api = __esmMin((() => {
init_checks$1();
init_util();
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/to-json-schema.js
function assignProps(target, ...sources) {
for (const source of sources) for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProp(target, key, source[key]);
return target;
}
function initializeContext(params) {
let target = params?.target ?? "draft-2020-12";
if (target === "draft-4") target = "draft-04";
if (target === "draft-7") target = "draft-07";
return {
processors: params.processors ?? {},
metadataRegistry: params?.metadata ?? globalRegistry,
target,
unrepresentable: params?.unrepresentable ?? "throw",
override: params?.override ?? (() => {}),
io: params?.io ?? "output",
counter: 0,
seen: /* @__PURE__ */ new Map(),
sharedDefsExtractedFor: void 0,
sharedEmitDoneFor: void 0,
cycles: params?.cycles ?? "ref",
reused: params?.reused ?? "inline",
intersections: [],
deferred: [],
external: params?.external ?? void 0
};
}
/**
* Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws
* `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a
* custom JSON Schema was written into `json`, in which case the caller must not write its own.
*/
function handleUnrepresentable(schema, ctx, json, params, message) {
const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({
zodSchema: schema,
path: params.path,
message
}) : ctx.unrepresentable;
if (result === "any") return false;
if (result === void 0 || result === "throw") throw new Error(message);
Object.assign(json, result);
return true;
}
function processSchema(schema, ctx, _params = {
path: [],
schemaPath: []
}) {
var _a;
const def = schema._zod.def;
const seen = ctx.seen.get(schema);
if (seen) {
seen.count++;
if (_params.schemaPath.includes(schema)) seen.cycle = _params.path;
return seen.schema;
}
const result = {
schema: {},
count: 1,
cycle: void 0,
path: _params.path
};
ctx.seen.set(schema, result);
ctx.sharedDefsExtractedFor = void 0;
ctx.sharedEmitDoneFor = void 0;
const overrideSchema = schema._zod.toJSONSchema?.();
if (overrideSchema) result.schema = overrideSchema;
else {
const params = {
..._params,
schemaPath: [..._params.schemaPath, schema],
path: _params.path
};
if (schema._zod.processJSONSchema) schema._zod.processJSONSchema(ctx, result.schema, params);
else {
const _json = result.schema;
const processor = ctx.processors[def.type];
if (!processor) throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
processor(schema, ctx, _json, params);
}
const parent = schema._zod.parent;
if (parent) {
if (!result.ref) result.ref = parent;
processSchema(parent, ctx, params);
ctx.seen.get(parent).isParent = true;
}
}
const meta = ctx.metadataRegistry.get(schema);
if (meta) assignProps(result.schema, meta);
if (ctx.io === "input" && isTransforming(schema)) {
delete result.schema.examples;
delete result.schema.default;
}
if (ctx.io === "input" && "_prefault" in result.schema) (_a = result.schema).default ?? (_a.default = result.schema._prefault);
delete result.schema._prefault;
return ctx.seen.get(schema).schema;
}
function encodeJSONPointerSegment(segment) {
return segment.replace(/~/g, "~0").replace(/\//g, "~1");
}
function extractDefs(ctx, schema) {
const root = ctx.seen.get(schema);
if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) return;
const idToSchema = /* @__PURE__ */ new Map();
for (const entry of ctx.seen.entries()) {
const id = ctx.metadataRegistry.get(entry[0])?.id;
if (id) {
const existing = idToSchema.get(id);
if (existing && existing !== entry[0]) throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
idToSchema.set(id, entry[0]);
}
}
const makeURI = (entry) => {
const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
if (ctx.external) {
const externalId = ctx.external.registry.get(entry[0])?.id;
const uriGenerator = ctx.external.uri ?? ((id) => id);
if (externalId) return { ref: uriGenerator(externalId) };
const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;
entry[1].defId = id;
return {
defId: id,
ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}`
};
}
const uriPrefix = `#`;
const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
if (entry[1] === root && !entry[1].schema.id) return { ref: uriPrefix };
const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;
return {
defId,
ref: defUriPrefix + encodeJSONPointerSegment(defId)
};
};
const extractToDef = (entry) => {
if (entry[1].schema.$ref) return;
const seen = entry[1];
const { ref, defId } = makeURI(entry);
seen.def = { ...seen.schema };
if (defId) seen.defId = defId;
const schema = seen.schema;
for (const key in schema) delete schema[key];
schema.$ref = ref;
};
if (ctx.cycles === "throw") for (const entry of ctx.seen.entries()) {
const seen = entry[1];
if (seen.cycle) throw new Error(`Cycle detected: #/${seen.cycle?.join("/")}/<root>
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
}
for (const entry of ctx.seen.entries()) {
const seen = entry[1];
if (schema === entry[0]) {
extractToDef(entry);
continue;
}
if (ctx.external) {
const ext = ctx.external.registry.get(entry[0])?.id;
if (schema !== entry[0] && ext) {
extractToDef(entry);
continue;
}
}
if (ctx.metadataRegistry.get(entry[0])?.id) {
extractToDef(entry);
continue;
}
if (seen.cycle) {
extractToDef(entry);
continue;
}
if (seen.count > 1) {
if (ctx.reused === "ref") extractToDef(entry);
}
}
if (ctx.external) ctx.sharedDefsExtractedFor = ctx.external;
}
/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */
function compactTypeUnion(schema) {
const options = schema.anyOf;
if (!Array.isArray(options) || options.length === 0 || schema.type !== void 0) return;
const types = [];
for (const option of options) {
if (!option || typeof option !== "object") return;
compactTypeUnion(option);
const keys = Object.keys(option);
if (keys.length !== 1 || keys[0] !== "type") return;
const type = option.type;
for (const member of Array.isArray(type) ? type : [type]) {
if (typeof member !== "string") return;
if (!types.includes(member)) types.push(member);
}
}
delete schema.anyOf;
schema.type = types.length === 1 ? types[0] : types;
}
/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */
function undeclaredConstraint(member) {
const extra = member.additionalProperties;
if (extra === void 0 || extra === false || typeof extra !== "object" || extra === null) return null;
return Object.keys(extra).length ? extra : null;
}
/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */
function foldObjects(members) {
const objects = [];
for (const member of members) {
if (typeof member !== "object" || member.type !== "object") return null;
for (const key in member) if (!FOLDABLE_KEYS.has(key)) return null;
objects.push(member);
}
const properties = {};
const required = /* @__PURE__ */ new Set();
for (const object of objects) {
for (const key in object.properties) {
if (Object.prototype.hasOwnProperty.call(properties, key)) continue;
const parts = [];
for (const other of objects) {
const part = other.properties?.[key] ?? undeclaredConstraint(other);
if (part === null || part === void 0) continue;
if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) parts.push(part);
}
assignProp(properties, key, parts.length === 1 ? parts[0] : foldObjects(parts) ?? { allOf: parts });
}
for (const key of object.required ?? []) required.add(key);
}
const folded = {
type: "object",
properties
};
if (required.size) folded.required = [...required];
if (objects.every((object) => object.additionalProperties === false)) folded.additionalProperties = false;
else {
const constraints = [];
for (const object of objects) {
const constraint = undeclaredConstraint(object);
if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) constraints.push(constraint);
}
if (constraints.length === 1) folded.additionalProperties = constraints[0];
else if (constraints.length > 1) folded.additionalProperties = { allOf: constraints };
}
return folded;
}
/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two
* closed object members reject each other's keys and the schema validates nothing. Zod's parser
* pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when
* *every* side rejects it — so the emitted schema has to pool them too, and folding the members
* into one object is the encoding that says so on every target.
*
* This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref`
* machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it
* keeps its reference and its own closedness rather than being inlined as a stale copy. */
function foldIntersection(json) {
const allOf = json.allOf;
if (!Array.isArray(allOf) || allOf.length < 2) return;
for (const key of FOLDABLE_KEYS) if (key in json) return;
const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k])));
let folded = null;
if (!unions.length) folded = foldObjects(allOf);
else {
const union = unions[0];
const keyword = UNION_KEYS.find((k) => Array.isArray(union[k]));
if (Object.keys(union).length !== 1) return;
const rest = allOf.filter((m) => m !== union);
const branches = union[keyword].map((branch) => foldObjects([...rest, branch]));
if (branches.some((b) => !b)) return;
folded = { [keyword]: branches };
}
if (!folded) return;
delete json.allOf;
assignProps(json, folded);
}
function finalize(ctx, schema) {
const root = ctx.seen.get(schema);
if (!root) throw new Error("Unprocessed schema. This is a bug in Zod.");
const flattenRef = (zodSchema) => {
const seen = ctx.seen.get(zodSchema);
if (seen.ref === null) return;
const schema = seen.def ?? seen.schema;
const _cached = { ...schema };
const ref = seen.ref;
seen.ref = null;
if (ref) {
flattenRef(ref);
const refSeen = ctx.seen.get(ref);
const refSchema = refSeen.schema;
if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
schema.allOf = schema.allOf ?? [];
schema.allOf.push(refSchema);
} else assignProps(schema, refSchema);
assignProps(schema, _cached);
if (zodSchema._zod.parent === ref) for (const key in schema) {
if (key === "$ref" || key === "allOf") continue;
if (!(key in _cached)) delete schema[key];
}
if (refSchema.$ref && refSeen.def) for (const key in schema) {
if (key === "$ref" || key === "allOf") continue;
if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) delete schema[key];
}
}
const parent = zodSchema._zod.parent;
if (parent && parent !== ref) {
flattenRef(parent);
const parentSeen = ctx.seen.get(parent);
if (parentSeen?.schema.$ref) {
schema.$ref = parentSeen.schema.$ref;
if (parentSeen.def) for (const key in schema) {
if (key === "$ref" || key === "allOf") continue;
if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) delete schema[key];
}
}
}
ctx.override({
zodSchema,
jsonSchema: schema,
path: seen.path ?? []
});
};
if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) {
for (const entry of [...ctx.seen.entries()].reverse()) flattenRef(entry[0]);
if (ctx.target !== "openapi-3.0") for (const entry of ctx.seen.entries()) compactTypeUnion(entry[1].def ?? entry[1].schema);
for (const rewrite of ctx.deferred) rewrite();
if (ctx.intersections.length) {
const carriers = /* @__PURE__ */ new Map();
for (const seen of ctx.seen.values()) for (const json of [seen.schema, seen.def]) {
const allOf = json?.allOf;
if (!Array.isArray(allOf)) continue;
const existing = carriers.get(allOf);
if (existing) existing.push(json);
else carriers.set(allOf, [json]);
}
for (const allOf of ctx.intersections) for (const json of carriers.get(allOf) ?? []) foldIntersection(json);
}
}
const result = {};
if (ctx.target === "draft-2020-12") result.$schema = "https://json-schema.org/draft/2020-12/schema";
else if (ctx.target === "draft-07") result.$schema = "http://json-schema.org/draft-07/schema#";
else if (ctx.target === "draft-04") result.$schema = "http://json-schema.org/draft-04/schema#";
else if (ctx.target === "openapi-3.0") {}
if (ctx.external?.uri) {
const id = ctx.external.registry.get(schema)?.id;
if (!id) throw new Error("Schema is missing an `id` property");
result.$id = ctx.external.uri(id);
}
assignProps(result, root.defId ? root.schema : root.def ?? root.schema);
const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
if (rootMetaId !== void 0 && result.id === rootMetaId) delete result.id;
const defs = ctx.external?.defs ?? {};
if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) for (const entry of ctx.seen.entries()) {
const seen = entry[1];
if (seen.def && seen.defId) {
if (seen.def.id === seen.defId) delete seen.def.id;
assignProp(defs, seen.defId, seen.def);
}
}
if (ctx.external) ctx.sharedEmitDoneFor = ctx.external;
if (ctx.external) {} else if (Object.keys(defs).length > 0) {
if (ctx.target === "draft-2020-12") result.$defs = defs;
else result.definitions = defs;
}
try {
const finalized = JSON.parse(JSON.stringify(result));
Object.defineProperty(finalized, "~standard", {
value: {
...schema["~standard"],
jsonSchema: {
input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
}
},
enumerable: false,
writable: false
});
return finalized;
} catch (_err) {
throw new Error("Error converting schema to JSON.");
}
}
function isTransforming(_schema, _ctx) {
const ctx = _ctx ?? { seen: /* @__PURE__ */ new Set() };
if (ctx.seen.has(_schema)) return false;
ctx.seen.add(_schema);
const def = _schema._zod.def;
if (def.type === "transform") return true;
if (def.type === "array") return isTransforming(def.element, ctx);
if (def.type === "set") return isTransforming(def.valueType, ctx);
if (def.type === "lazy") return isTransforming(def.getter(), ctx);
if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault" || def.type === "catch") return isTransforming(def.innerType, ctx);
if (def.type === "intersection") return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
if (def.type === "record" || def.type === "map") return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
if (def.type === "pipe") {
if (_schema._zod.traits.has("$ZodCodec")) return true;
return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
}
if (def.type === "object") {
for (const key in def.shape) if (isTransforming(def.shape[key], ctx)) return true;
return false;
}
if (def.type === "union") {
for (const option of def.options) if (isTransforming(option, ctx)) return true;
return false;
}
if (def.type === "tuple") {
for (const item of def.items) if (isTransforming(item, ctx)) return true;
if (def.rest && isTransforming(def.rest, ctx)) return true;
return false;
}
return false;
}
var FOLDABLE_KEYS, UNION_KEYS, createToJSONSchemaMethod, createStandardJSONSchemaMethod;
var init_to_json_schema = __esmMin((() => {
init_registries();
init_util();
FOLDABLE_KEYS = /* @__PURE__ */ new Set([
"type",
"properties",
"required",
"additionalProperties"
]);
UNION_KEYS = ["oneOf", "anyOf"];
createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
const ctx = initializeContext({
...params,
processors
});
processSchema(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
};
createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
const { libraryOptions, target } = params ?? {};
const ctx = initializeContext({
...libraryOptions ?? {},
target,
io,
processors
});
processSchema(schema, ctx);
extractDefs(ctx, schema);
return finalize(ctx, schema);
};
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/json-schema-processors.js
function aggregateChecks(schema) {
const agg = {};
const def = schema._zod.def;
const list = schema._zod.traits.has("$ZodCheck") ? [schema, ...def.checks ?? []] : def.checks ?? [];
for (const ch of list) contributors[ch._zod.def.check]?.(agg, ch._zod.def);
const bag = schema._zod.bag;
if (bag.minimum !== void 0) narrowMin(agg, "minimum", bag.minimum);
if (bag.exclusiveMinimum !== void 0) narrowMin(agg, "exclusiveMinimum", bag.exclusiveMinimum);
if (bag.maximum !== void 0) narrowMax(agg, "maximum", bag.maximum);
if (bag.exclusiveMaximum !== void 0) narrowMax(agg, "exclusiveMaximum", bag.exclusiveMaximum);
if (bag.multipleOf !== void 0) addDivisor(agg, bag.multipleOf);
if (bag.format !== void 0) {
agg.format ?? (agg.format = bag.format);
if (bag.format.includes("int")) agg.isInt = true;
}
if (bag.mime) intersectMime(agg, bag.mime);
for (const pattern of bag.patterns ?? []) addPattern(agg, pattern);
return agg;
}
function inputOptin(schema) {
const def = schema._zod.def;
if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) return inputOptin(def.out);
if (def.type === "catch") return inputOptin(def.innerType);
return schema._zod.optin;
}
function serializeDefaultValue(value, schema, ctx, json, params) {
let unrepresentable = false;
const serialized = JSON.stringify(value, (_, val) => {
if (typeof val !== "bigint") return val;
unrepresentable = true;
return null;
});
if (!unrepresentable) return JSON.parse(serialized);
handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema");
return UNREPRESENTABLE_DEFAULT;
}
var narrowMin, narrowMax, narrowBoth, addDivisor, addPattern, intersectMime, setFormat, minContributor, maxContributor, formatContributor, contributors, formatMap, exactPatterns, exactPattern, stringProcessor, numberProcessor, booleanProcessor, neverProcessor, unknownProcessor, enumProcessor, literalProcessor, customProcessor, transformProcessor, arrayProcessor, objectProcessor, unionProcessor, intersectionProcessor, nullableProcessor, nonoptionalProcessor, UNREPRESENTABLE_DEFAULT, defaultProcessor, prefaultProcessor, catchProcessor, pipeProcessor, readonlyProcessor, optionalProcessor;
var init_json_schema_processors = __esmMin((() => {
init_regexes();
init_schemas$1();
init_to_json_schema();
init_util();
narrowMin = (agg, key, value) => {
if (agg[key] === void 0 || value > agg[key]) agg[key] = value;
};
narrowMax = (agg, key, value) => {
if (agg[key] === void 0 || value < agg[key]) agg[key] = value;
};
narrowBoth = (agg, value) => {
narrowMin(agg, "minimum", value);
narrowMax(agg, "maximum", value);
};
addDivisor = (agg, value) => {
agg.multipleOf ?? (agg.multipleOf = []);
if (!agg.multipleOf.includes(value)) agg.multipleOf.push(value);
};
addPattern = (agg, pattern) => {
agg.patterns ?? (agg.patterns = /* @__PURE__ */ new Set());
agg.patterns.add(pattern);
};
intersectMime = (agg, mime) => {
agg.mime = agg.mime ? agg.mime.filter((m) => mime.includes(m)) : [...mime];
};
setFormat = (agg, format) => {
agg.format = format;
if (format.includes("int")) agg.isInt = true;
};
minContributor = (agg, def) => narrowMin(agg, "minimum", def.minimum);
maxContributor = (agg, def) => narrowMax(agg, "maximum", def.maximum);
formatContributor = (ranges) => (agg, def) => {
setFormat(agg, def.format);
const [minimum, maximum] = ranges[def.format];
narrowMin(agg, "minimum", minimum);
narrowMax(agg, "maximum", maximum);
};
contributors = {
greater_than: (agg, def) => narrowMin(agg, def.inclusive ? "minimum" : "exclusiveMinimum", def.value),
less_than: (agg, def) => narrowMax(agg, def.inclusive ? "maximum" : "exclusiveMaximum", def.value),
multiple_of: (agg, def) => addDivisor(agg, def.value),
number_format: formatContributor(NUMBER_FORMAT_RANGES),
bigint_format: formatContributor(BIGINT_FORMAT_RANGES),
min_length: minContributor,
max_length: maxContributor,
length_equals: (agg, def) => narrowBoth(agg, def.length),
min_size: minContributor,
max_size: maxContributor,
size_equals: (agg, def) => narrowBoth(agg, def.size),
string_format: (agg, def) => {
setFormat(agg, def.format);
if (def.pattern) addPattern(agg, def.pattern);
if (def.format === "base64" || def.format === "base64url") agg.contentEncoding = def.format;
if (def.local || def.precision === -1) agg.laxFormat = true;
},
mime_type: (agg, def) => intersectMime(agg, def.mime)
};
formatMap = {
guid: "uuid",
url: "uri",
datetime: "date-time",
json_string: "json-string",
regex: ""
};
exactPatterns = /* @__PURE__ */ new Map([[base64Charset, base64], [base64urlCharset, base64url]]);
exactPattern = (p) => exactPatterns.get(p) ?? p;
stringProcessor = (schema, ctx, _json, _params) => {
const json = _json;
json.type = "string";
const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = aggregateChecks(schema);
if (typeof minimum === "number") json.minLength = minimum;
if (typeof maximum === "number") json.maxLength = maximum;
if (format) {
json.format = formatMap[format] ?? format;
if (json.format === "") delete json.format;
if (format === "time" || laxFormat) delete json.format;
}
if (contentEncoding) json.contentEncoding = contentEncoding;
if (patterns && patterns.size > 0) {
const patternList = [...patterns].map(exactPattern);
if (patternList.length === 1) json.pattern = patternList[0].source;
else if (patternList.length > 1) json.allOf = [...patternList.map((regex) => ({
...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
pattern: regex.source
}))];
}
};
numberProcessor = (schema, ctx, _json, params) => {
const json = _json;
const { minimum, maximum, multipleOf, exclusiveMaximum, exclusiveMinimum, isInt } = aggregateChecks(schema);
json.type = isInt ? "integer" : "number";
const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
if (exMin) {
if (legacy) {
json.minimum = exclusiveMinimum;
json.exclusiveMinimum = true;
} else json.exclusiveMinimum = exclusiveMinimum;
} else if (typeof minimum === "number") json.minimum = minimum;
if (exMax) {
if (legacy) {
json.maximum = exclusiveMaximum;
json.exclusiveMaximum = true;
} else json.exclusiveMaximum = exclusiveMaximum;
} else if (typeof maximum === "number") json.maximum = maximum;
if (multipleOf) {
const divisors = /* @__PURE__ */ new Set();
for (const divisor of multipleOf) if (Number.isFinite(divisor) && divisor !== 0) divisors.add(Math.abs(divisor));
else handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${divisor} cannot be represented in JSON Schema`);
const [first, ...rest] = divisors;
if (first !== void 0) json.multipleOf = first;
if (rest.length) json.allOf = [...json.allOf ?? [], ...rest.map((m) => ({ multipleOf: m }))];
}
};
booleanProcessor = (_schema, _ctx, json, _params) => {
json.type = "boolean";
};
neverProcessor = (_schema, _ctx, json, _params) => {
json.not = {};
};
unknownProcessor = (_schema, _ctx, _json, _params) => {};
enumProcessor = (schema, _ctx, json, _params) => {
const def = schema._zod.def;
const values = getEnumValues(def.entries);
if (values.length === 0) {
json.not = {};
return;
}
if (values.every((v) => typeof v === "number")) json.type = "number";
if (values.every((v) => typeof v === "string")) json.type = "string";
json.enum = values;
};
literalProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
if (def.values.length === 0) {
json.not = {};
return;
}
const vals = [];
for (const val of def.values) if (val === void 0) {
if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) return;
} else if (typeof val === "bigint") {
if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) return;
vals.push(Number(val));
} else vals.push(val);
if (vals.length === 0) {} else if (vals.length === 1) {
const val = vals[0];
json.type = val === null ? "null" : typeof val;
if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") json.enum = [val];
else json.const = val;
} else {
if (vals.every((v) => typeof v === "number")) json.type = "number";
if (vals.every((v) => typeof v === "string")) json.type = "string";
if (vals.every((v) => typeof v === "boolean")) json.type = "boolean";
if (vals.every((v) => v === null)) json.type = "null";
json.enum = vals;
}
};
customProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema");
};
transformProcessor = (schema, ctx, json, params) => {
handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema");
};
arrayProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
const { minimum, maximum } = aggregateChecks(schema);
if (typeof minimum === "number") json.minItems = minimum;
if (typeof maximum === "number") json.maxItems = maximum;
json.type = "array";
json.items = processSchema(def.element, ctx, {
...params,
path: [...params.path, "items"]
});
};
objectProcessor = (schema, ctx, _json, params) => {
const json = _json;
const def = schema._zod.def;
const shape = def.shape;
if (Object.getOwnPropertySymbols(shape).length && handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) return;
json.type = "object";
json.properties = {};
for (const key in shape) assignProp(json.properties, key, processSchema(shape[key], ctx, {
...params,
path: [
...params.path,
"properties",
key
]
}));
const requiredKeys = [];
for (const key of Object.keys(shape)) {
const field = def.shape[key];
if (ctx.io === "input" ? inputOptin(field) === void 0 : field._zod.optout === void 0) requiredKeys.push(key);
}
if (requiredKeys.length > 0) json.required = requiredKeys;
if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
else if (!def.catchall) {
if (ctx.io === "output") json.additionalProperties = false;
} else if (def.catchall) json.additionalProperties = processSchema(def.catchall, ctx, {
...params,
path: [...params.path, "additionalProperties"]
});
};
unionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const isExclusive = def.inclusive === false;
const options = def.options.map((x, i) => processSchema(x, ctx, {
...params,
path: [
...params.path,
isExclusive ? "oneOf" : "anyOf",
i
]
}));
if (isExclusive) json.oneOf = options;
else json.anyOf = options;
};
intersectionProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const a = processSchema(def.left, ctx, {
...params,
path: [
...params.path,
"allOf",
0
]
});
const b = processSchema(def.right, ctx, {
...params,
path: [
...params.path,
"allOf",
1
]
});
const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
const allOf = [...isSimpleIntersection(a) ? a.allOf : [a], ...isSimpleIntersection(b) ? b.allOf : [b]];
json.allOf = allOf;
ctx.intersections.push(allOf);
};
nullableProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
const inner = processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
if (ctx.target === "openapi-3.0") {
seen.ref = def.innerType;
json.nullable = true;
} else json.anyOf = [inner, { type: "null" }];
};
nonoptionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
UNREPRESENTABLE_DEFAULT = Symbol();
defaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
if (value !== UNREPRESENTABLE_DEFAULT) json.default = value;
};
prefaultProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
if (ctx.io !== "input") return;
const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params);
if (value !== UNREPRESENTABLE_DEFAULT) json._prefault = value;
};
catchProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
let catchValue;
try {
catchValue = def.catchValue(void 0);
} catch {
handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema");
return;
}
json.default = catchValue;
};
pipeProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
const inIsTransform = def.in._zod.traits.has("$ZodTransform");
const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
processSchema(innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = innerType;
};
readonlyProcessor = (schema, ctx, json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
json.readOnly = true;
};
optionalProcessor = (schema, ctx, _json, params) => {
const def = schema._zod.def;
processSchema(def.innerType, ctx, params);
const seen = ctx.seen.get(schema);
seen.ref = def.innerType;
};
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/index.js
var init_core = __esmMin((() => {
init_core$1();
init_parse$1();
init_errors$1();
init_schemas$1();
init_memoizer();
init_checks$1();
init_versions();
init_util();
init_regexes();
init_en();
init_registries();
init_doc();
init_compile();
init_api();
init_to_json_schema();
init_json_schema_processors();
init_to_json_schema();
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/checks.js
var init_checks = __esmMin((() => {
init_core();
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/errors.js
function _lazyMethod(proto, key, make) {
Object.defineProperty(proto, key, {
configurable: true,
enumerable: false,
get() {
const value = make(this);
Object.defineProperty(this, key, {
value,
configurable: true,
writable: true
});
return value;
},
set(value) {
Object.defineProperty(this, key, {
value,
configurable: true,
writable: true
});
}
});
}
var _installedErrorProtos, initializer, ZodRealError;
var init_errors = __esmMin((() => {
init_core();
init_util();
_installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
initializer = (inst, issues) => {
$ZodError.init(inst, issues);
inst.name = "ZodError";
const proto = Object.getPrototypeOf(inst);
if (_installedErrorProtos.has(proto)) return;
_installedErrorProtos.add(proto);
_lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper));
_lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper));
_lazyMethod(proto, "addIssue", (self) => (issue) => {
self.issues.push(issue);
self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
});
_lazyMethod(proto, "addIssues", (self) => (issues) => {
self.issues.push(...issues);
self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2);
});
Object.defineProperty(proto, "isEmpty", {
configurable: true,
enumerable: false,
get() {
return this.issues.length === 0;
}
});
};
ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, void 0, { Parent: Error });
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/parse.js
var parse$1, parseAsync, safeParse, safeParseAsync, encode, decode, encodeAsync, decodeAsync, safeEncode, safeDecode, safeEncodeAsync, safeDecodeAsync;
var init_parse = __esmMin((() => {
init_core();
init_errors();
parse$1 = /* @__PURE__ */ _parse(ZodRealError);
parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError);
encode = /* @__PURE__ */ _encode(ZodRealError);
decode = /* @__PURE__ */ _decode(ZodRealError);
encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError);
decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError);
safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError);
safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/schemas.js
function _ensureDefaultLocale() {
if (!globalConfig.localeError) config(en_default());
}
function _ensureDefaultMemoizer() {
if (!globalConfig.memoizer) config({ memoizer: memoizer() });
}
function string(params) {
return /* @__PURE__ */ _string(ZodString, params);
}
function number(params) {
return /* @__PURE__ */ _number(ZodNumber, params);
}
function int(params) {
return /* @__PURE__ */ _int(ZodNumberFormat, params);
}
function boolean(params) {
return /* @__PURE__ */ _boolean(ZodBoolean, params);
}
function unknown() {
return /* @__PURE__ */ _unknown(ZodUnknown);
}
function never(params) {
return /* @__PURE__ */ _never(ZodNever, params);
}
function array(element, params) {
return /* @__PURE__ */ _array(ZodArray, element, params);
}
function object(shape, params) {
const def = {
type: "object",
shape: shape ?? {},
...normalizeParams(params)
};
return new ZodObject(def);
}
function looseObject(shape, params) {
return new ZodObject({
type: "object",
shape,
catchall: unknown(),
...normalizeParams(params)
});
}
function union(options, params) {
return new ZodUnion({
type: "union",
options,
...normalizeParams(params)
});
}
function intersection(left, right) {
return new ZodIntersection({
type: "intersection",
left,
right
});
}
function _enum(values, params) {
const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
return new ZodEnum({
type: "enum",
entries,
...normalizeParams(params)
});
}
function literal(value, params) {
return new ZodLiteral({
type: "literal",
values: Array.isArray(value) ? value : [value],
...normalizeParams(params)
});
}
function transform(fn) {
return new ZodTransform({
type: "transform",
transform: fn
});
}
function optional(innerType) {
return new ZodOptional({
type: "optional",
innerType
});
}
function exactOptional(innerType) {
return new ZodExactOptional({
type: "optional",
innerType
});
}
function nullable(innerType) {
return new ZodNullable({
type: "nullable",
innerType
});
}
function _default(innerType, defaultValue) {
return new ZodDefault({
type: "default",
innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
}
});
}
function prefault(innerType, defaultValue) {
return new ZodPrefault({
type: "prefault",
innerType,
get defaultValue() {
return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
}
});
}
function nonoptional(innerType, params) {
return new ZodNonOptional({
type: "nonoptional",
innerType,
...normalizeParams(params)
});
}
function _catch(innerType, catchValue) {
return new ZodCatch({
type: "catch",
innerType,
catchValue: typeof catchValue === "function" ? catchValue : constantCatch(catchValue)
});
}
function pipe(in_, out) {
return new ZodPipe({
type: "pipe",
in: in_,
out
});
}
function readonly(innerType) {
return new ZodReadonly({
type: "readonly",
innerType
});
}
function custom(fn, _params) {
return /* @__PURE__ */ _custom(ZodCustom, fn ?? (() => true), _params);
}
function refine(fn, _params = {}) {
return /* @__PURE__ */ _refine(ZodCustom, fn, _params);
}
function superRefine(fn, params) {
return /* @__PURE__ */ _superRefine(fn, params);
}
var ZodType, _ZodString, ZodString, ZodStringFormat, ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration, ZodEmail, ZodGUID, ZodUUID, ZodURL, ZodEmoji, ZodNanoID, ZodCUID, ZodCUID2, ZodULID, ZodXID, ZodKSUID, ZodIPv4, ZodIPv6, ZodCIDRv4, ZodCIDRv6, ZodBase64, ZodBase64URL, ZodE164, ZodJWT, ZodNumber, ZodNumberFormat, ZodBoolean, ZodUnknown, ZodNever, ZodArray, ZodObject, ZodUnion, ZodIntersection, ZodEnum, ZodLiteral, ZodTransform, ZodOptional, ZodExactOptional, ZodNullable, ZodDefault, ZodPrefault, ZodNonOptional, ZodCatch, ZodPipe, ZodReadonly, ZodCustom;
var init_schemas = __esmMin((() => {
init_core();
init_json_schema_processors();
init_to_json_schema();
init_en();
init_checks();
init_parse();
ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => {
_ensureDefaultLocale();
$ZodType.init(inst, def);
inst.def = def;
inst.type = def.type;
return inst;
}, {
check(...chks) {
const def = this.def;
return this.clone(mergeDefs(def, { checks: [...def.checks ?? [], ...chks.map((ch) => typeof ch === "function" ? { _zod: {
check: ch,
def: { check: "custom" },
onattach: []
} } : ch)] }), { parent: true });
},
with(...chks) {
return this.check(...chks);
},
clone(def, params) {
return clone(this, def, params);
},
brand() {
return this;
},
register(reg, meta) {
reg.add(this, meta);
return this;
},
refine(check, params) {
return this.check(refine(check, params));
},
superRefine(refinement, params) {
return this.check(superRefine(refinement, params));
},
overwrite(fn) {
return this.check(/* @__PURE__ */ _overwrite(fn));
},
optional() {
return optional(this);
},
exactOptional() {
return exactOptional(this);
},
nullable() {
return nullable(this);
},
nullish() {
return optional(nullable(this));
},
nonoptional(params) {
return nonoptional(this, params);
},
array() {
return array(this);
},
or(arg) {
return union([this, arg]);
},
and(arg) {
return intersection(this, arg);
},
transform(tx) {
return pipe(this, transform(tx));
},
default(d) {
return _default(this, d);
},
prefault(d) {
return prefault(this, d);
},
catch(params) {
return _catch(this, params);
},
pipe(target) {
return pipe(this, target);
},
readonly() {
return readonly(this);
},
describe(description) {
const cl = this.clone();
globalRegistry.add(cl, { description });
return cl;
},
meta(...args) {
if (args.length === 0) return globalRegistry.get(this);
const cl = this.clone();
globalRegistry.add(cl, args[0]);
return cl;
},
isOptional() {
return this.safeParse(void 0).success;
},
isNullable() {
return this.safeParse(null).success;
},
apply(fn, ...args) {
return args.length === 0 ? fn(this) : fn(this, ...args);
},
get "~standard"() {
return hide(this, "~standard", {
...standardProps(this),
jsonSchema: {
input: createStandardJSONSchemaMethod(this, "input"),
output: createStandardJSONSchemaMethod(this, "output")
}
});
},
set "~standard"(value) {
own(this, "~standard", value);
},
parse: function _parse(data, params) {
return parse$1(this, data, params, { callee: _parse });
},
parseAsync: async function _parseAsync(data, params) {
return await parseAsync(this, data, params, { callee: _parseAsync });
},
safeParse(data, params) {
return safeParse(this, data, params);
},
async safeParseAsync(data, params) {
return safeParseAsync(this, data, params);
},
get spa() {
return this?.safeParseAsync;
},
set spa(value) {
own(this, "spa", value);
},
validate(data, params) {
return validate(this, data, params);
},
validateAsync(data, params) {
return validateAsync$1(this, data, params);
},
encode: function _encode(data, params) {
return encode(this, data, params, { callee: _encode });
},
decode: function _decode(data, params) {
return decode(this, data, params, { callee: _decode });
},
encodeAsync: async function _encodeAsync(data, params) {
return await encodeAsync(this, data, params, { callee: _encodeAsync });
},
decodeAsync: async function _decodeAsync(data, params) {
return await decodeAsync(this, data, params, { callee: _decodeAsync });
},
safeEncode(data, params) {
return safeEncode(this, data, params);
},
safeDecode(data, params) {
return safeDecode(this, data, params);
},
async safeEncodeAsync(data, params) {
return safeEncodeAsync(this, data, params);
},
async safeDecodeAsync(data, params) {
return safeDecodeAsync(this, data, params);
},
toJSONSchema(params) {
return createToJSONSchemaMethod(this, {})(params);
},
get description() {
return globalRegistry.get(this)?.description;
},
get _def() {
return this._zod.def;
}
});
_ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => {
$ZodString.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
}, /*@__PURE__*/ derived({
format: (inst) => aggregateChecks(inst).format ?? null,
minLength: (inst) => aggregateChecks(inst).minimum ?? null,
maxLength: (inst) => aggregateChecks(inst).maximum ?? null
}, {
regex(...args) {
return this.check(/* @__PURE__ */ _regex(...args));
},
includes(...args) {
return this.check(/* @__PURE__ */ _includes(...args));
},
startsWith(...args) {
return this.check(/* @__PURE__ */ _startsWith(...args));
},
endsWith(...args) {
return this.check(/* @__PURE__ */ _endsWith(...args));
},
min(...args) {
return this.check(/* @__PURE__ */ _minLength(...args));
},
max(...args) {
return this.check(/* @__PURE__ */ _maxLength(...args));
},
length(...args) {
return this.check(/* @__PURE__ */ _length(...args));
},
nonempty(...args) {
return this.check(/* @__PURE__ */ _minLength(1, ...args));
},
lowercase(params) {
return this.check(/* @__PURE__ */ _lowercase(params));
},
uppercase(params) {
return this.check(/* @__PURE__ */ _uppercase(params));
},
trim() {
return this.check(/* @__PURE__ */ _trim());
},
normalize(...args) {
return this.check(/* @__PURE__ */ _normalize(...args));
},
toLowerCase() {
return this.check(/* @__PURE__ */ _toLowerCase());
},
toUpperCase() {
return this.check(/* @__PURE__ */ _toUpperCase());
},
slugify() {
return this.check(/* @__PURE__ */ _slugify());
}
}));
ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => {
$ZodString.init(inst, def);
_ZodString.init(inst, def);
}, {
email(params) {
return this.check(/* @__PURE__ */ _email(ZodEmail, params));
},
url(params) {
return this.check(/* @__PURE__ */ _url(ZodURL, params));
},
jwt(params) {
return this.check(/* @__PURE__ */ _jwt(ZodJWT, params));
},
emoji(params) {
return this.check(/* @__PURE__ */ _emoji(ZodEmoji, params));
},
guid(params) {
return this.check(/* @__PURE__ */ _guid(ZodGUID, params));
},
uuid(params) {
return this.check(/* @__PURE__ */ _uuid(ZodUUID, params));
},
uuidv4(params) {
return this.check(/* @__PURE__ */ _uuidv4(ZodUUID, params));
},
uuidv6(params) {
return this.check(/* @__PURE__ */ _uuidv6(ZodUUID, params));
},
uuidv7(params) {
return this.check(/* @__PURE__ */ _uuidv7(ZodUUID, params));
},
nanoid(params) {
return this.check(/* @__PURE__ */ _nanoid(ZodNanoID, params));
},
cuid(params) {
return this.check(/* @__PURE__ */ _cuid(ZodCUID, params));
},
cuid2(params) {
return this.check(/* @__PURE__ */ _cuid2(ZodCUID2, params));
},
ulid(params) {
return this.check(/* @__PURE__ */ _ulid(ZodULID, params));
},
base64(params) {
return this.check(/* @__PURE__ */ _base64(ZodBase64, params));
},
base64url(params) {
return this.check(/* @__PURE__ */ _base64url(ZodBase64URL, params));
},
xid(params) {
return this.check(/* @__PURE__ */ _xid(ZodXID, params));
},
ksuid(params) {
return this.check(/* @__PURE__ */ _ksuid(ZodKSUID, params));
},
ipv4(params) {
return this.check(/* @__PURE__ */ _ipv4(ZodIPv4, params));
},
ipv6(params) {
return this.check(/* @__PURE__ */ _ipv6(ZodIPv6, params));
},
cidrv4(params) {
return this.check(/* @__PURE__ */ _cidrv4(ZodCIDRv4, params));
},
cidrv6(params) {
return this.check(/* @__PURE__ */ _cidrv6(ZodCIDRv6, params));
},
e164(params) {
return this.check(/* @__PURE__ */ _e164(ZodE164, params));
},
datetime(params) {
return this.check(/* @__PURE__ */ _isoDateTime(ZodISODateTime, params));
},
date(params) {
return this.check(/* @__PURE__ */ _isoDate(ZodISODate, params));
},
time(params) {
return this.check(/* @__PURE__ */ _isoTime(ZodISOTime, params));
},
duration(params) {
return this.check(/* @__PURE__ */ _isoDuration(ZodISODuration, params));
}
});
ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => {
$ZodStringFormat.init(inst, def);
_ZodString.init(inst, def);
});
ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
$ZodISODateTime.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => {
$ZodISODate.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => {
$ZodISOTime.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => {
$ZodISODuration.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => {
$ZodEmail.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => {
$ZodGUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => {
$ZodUUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
$ZodURL.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
$ZodEmoji.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => {
$ZodNanoID.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => {
$ZodCUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => {
$ZodCUID2.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => {
$ZodULID.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => {
$ZodXID.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => {
$ZodKSUID.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => {
$ZodIPv4.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => {
$ZodIPv6.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => {
$ZodCIDRv4.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => {
$ZodCIDRv6.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => {
$ZodBase64.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => {
$ZodBase64URL.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => {
$ZodE164.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => {
$ZodJWT.init(inst, def);
ZodStringFormat.init(inst, def);
});
ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => {
$ZodNumber.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
inst.isFinite = true;
}, /*@__PURE__*/ derived({
minValue: (inst) => {
const { minimum, exclusiveMinimum } = aggregateChecks(inst);
return Math.max(minimum ?? Number.NEGATIVE_INFINITY, exclusiveMinimum ?? Number.NEGATIVE_INFINITY);
},
maxValue: (inst) => {
const { maximum, exclusiveMaximum } = aggregateChecks(inst);
return Math.min(maximum ?? Number.POSITIVE_INFINITY, exclusiveMaximum ?? Number.POSITIVE_INFINITY);
},
isInt: (inst) => {
const { isInt, multipleOf } = aggregateChecks(inst);
return !!isInt || !!multipleOf?.some(Number.isSafeInteger);
},
format: (inst) => aggregateChecks(inst).format ?? null
}, {
gt(value, params) {
return this.check(/* @__PURE__ */ _gt(value, params));
},
gte(value, params) {
return this.check(/* @__PURE__ */ _gte(value, params));
},
min(value, params) {
return this.check(/* @__PURE__ */ _gte(value, params));
},
lt(value, params) {
return this.check(/* @__PURE__ */ _lt(value, params));
},
lte(value, params) {
return this.check(/* @__PURE__ */ _lte(value, params));
},
max(value, params) {
return this.check(/* @__PURE__ */ _lte(value, params));
},
int(params) {
return this.check(int(params));
},
safe(params) {
return this.check(int(params));
},
positive(params) {
return this.check(/* @__PURE__ */ _gt(0, params));
},
nonnegative(params) {
return this.check(/* @__PURE__ */ _gte(0, params));
},
negative(params) {
return this.check(/* @__PURE__ */ _lt(0, params));
},
nonpositive(params) {
return this.check(/* @__PURE__ */ _lte(0, params));
},
multipleOf(value, params) {
return this.check(/* @__PURE__ */ _multipleOf(value, params));
},
step(value, params) {
return this.check(/* @__PURE__ */ _multipleOf(value, params));
},
finite() {
return this;
}
}));
ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => {
$ZodNumberFormat.init(inst, def);
ZodNumber.init(inst, def);
});
ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => {
$ZodBoolean.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params);
});
ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => {
$ZodUnknown.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params);
});
ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => {
$ZodNever.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
});
ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => {
_ensureDefaultMemoizer();
$ZodArray.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
inst.element = def.element;
}, {
min(n, params) {
return this.check(/* @__PURE__ */ _minLength(n, params));
},
nonempty(params) {
return this.check(/* @__PURE__ */ _minLength(1, params));
},
max(n, params) {
return this.check(/* @__PURE__ */ _maxLength(n, params));
},
length(n, params) {
return this.check(/* @__PURE__ */ _length(n, params));
},
unwrap() {
return this.element;
}
});
ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => {
_ensureDefaultMemoizer();
$ZodObjectJIT.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
installLazyProp(inst, "shape", (self) => self._zod.def.shape, false);
}, {
keyof() {
return _enum(Object.keys(this._zod.def.shape));
},
catchall(catchall) {
return this.clone(mergeDefs(this._zod.def, { catchall }));
},
passthrough() {
return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
},
loose() {
return this.clone(mergeDefs(this._zod.def, { catchall: unknown() }));
},
strict() {
return this.clone(mergeDefs(this._zod.def, { catchall: never() }));
},
strip() {
return this.clone(mergeDefs(this._zod.def, { catchall: void 0 }));
},
extend(incoming) {
return extend(this, incoming);
},
safeExtend(incoming) {
return safeExtend(this, incoming);
},
merge(other) {
return merge(this, other);
},
pick(mask) {
return pick(this, mask);
},
omit(mask) {
return omit(this, mask);
},
partial(...args) {
return partial(ZodOptional, this, args[0]);
},
exactPartial(...args) {
return partial(ZodExactOptional, this, args[0], "exactPartial");
},
required(...args) {
return required(ZodNonOptional, this, args[0]);
}
});
ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => {
$ZodUnion.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
inst.options = def.options;
});
ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => {
$ZodIntersection.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
});
ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => {
$ZodEnum.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params);
inst.enum = def.entries;
inst.options = [...inst._zod.values];
const keys = new Set(Object.keys(def.entries));
inst.extract = (values, params) => {
const newEntries = {};
for (const value of values) if (keys.has(value)) newEntries[value] = def.entries[value];
else throw new Error(`Key ${value} not found in enum`);
return new ZodEnum({
...def,
checks: [],
...normalizeParams(params),
entries: newEntries
});
};
inst.exclude = (values, params) => {
const newEntries = { ...def.entries };
for (const value of values) if (keys.has(value)) delete newEntries[value];
else throw new Error(`Key ${value} not found in enum`);
return new ZodEnum({
...def,
checks: [],
...normalizeParams(params),
entries: newEntries
});
};
});
ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => {
$ZodLiteral.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params);
inst.values = new Set(def.values);
Object.defineProperty(inst, "value", { get() {
if (def.values.length > 1) throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
return def.values[0];
} });
});
ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => {
_ensureDefaultMemoizer();
$ZodTransform.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
inst._zod.parse = (payload, _ctx) => {
if (_ctx.direction === "backward") throw new $ZodEncodeError(inst.constructor.name);
payload.addIssue = (issue$1) => {
if (typeof issue$1 === "string") payload.issues.push(issue(issue$1, payload.value, def));
else {
const _issue = issue$1;
if (_issue.fatal) _issue.continue = false;
_issue.code ?? (_issue.code = "custom");
if (!("input" in _issue)) _issue.input = payload.value;
_issue.inst ?? (_issue.inst = inst);
payload.issues.push(issue(_issue));
}
};
const output = def.transform(payload.value, payload);
if (output instanceof Promise) return output.then((output) => {
payload.value = output;
return payload;
});
payload.value = output;
return payload;
};
});
ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => {
$ZodOptional.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => {
$ZodExactOptional.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => {
$ZodNullable.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => {
$ZodDefault.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
inst.removeDefault = inst.unwrap;
});
ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => {
$ZodPrefault.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => {
$ZodNonOptional.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => {
$ZodCatch.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
inst.removeCatch = inst.unwrap;
});
ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => {
$ZodPipe.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params);
inst.in = def.in;
inst.out = def.out;
});
ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => {
$ZodReadonly.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
inst.unwrap = () => inst._zod.def.innerType;
});
ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => {
$ZodCustom.init(inst, def);
ZodType.init(inst, def);
inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
});
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/compat.js
var init_compat = __esmMin((() => {
init_core();
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/external.js
var init_external = __esmMin((() => {
init_core();
init_schemas();
init_checks();
init_errors();
init_parse();
init_compat();
init_json_schema_processors();
init_registries();
init_util();
init_checks();
init_schemas();
init_schemas$1();
init_en();
}));
//#endregion
//#region node_modules/.pnpm/zod@4.6.5/node_modules/zod/index.js
var init_zod = __esmMin((() => {
init_external();
init_external();
}));
//#endregion
//#region src/utils/zod-parse.ts
/**
* Null-returning Zod parse helpers for plugin and runtime boundaries.
*
* Callers use these where invalid external payloads should be ignored or
* recovered from without constructing and catching validation errors.
*/
/** Safely validates an unknown value with a Zod schema, returning null on validation failure. */
function safeParseWithSchema(schema, value) {
const parsed = schema.safeParse(value);
return parsed.success ? parsed.data : null;
}
/** Parses JSON, then safely validates it with a Zod schema, returning null for parse or schema failures. */
function safeParseJsonWithSchema(schema, raw) {
try {
return safeParseWithSchema(schema, JSON.parse(raw));
} catch {
return null;
}
}
var init_zod_parse = __esmMin((() => {}));
//#endregion
//#region src/infra/gateway-lock-payload.ts
function parseGatewayLockPayload(raw) {
return safeParseJsonWithSchema(LockPayloadSchema, raw);
}
var LockPayloadSchema;
var init_gateway_lock_payload = __esmMin((() => {
init_zod();
init_zod_parse();
LockPayloadSchema = object({
pid: number(),
ownerId: string().min(1).optional(),
/** A cold opener may wait for this transient owner, never enter while it is held. */
stateOwnerKind: literal("schema").optional(),
/** Present when Gateway cron writes use the dynamic-default ownership projection. */
cronOwnerProjection: literal("dynamic-default-v1").optional(),
createdAt: string(),
configPath: string(),
port: number().int().min(1).max(65535).optional(),
role: _enum([
"gateway",
"agent-embedded",
"skill-workshop-apply",
"sqlite-maintenance"
]).optional(),
stateDir: string().optional(),
startTime: number().optional()
});
}));
//#endregion
//#region src/infra/private-mode.ts
function hasRestrictivePermissions(target) {
try {
return (statSync(target).mode & 63) === 0;
} catch {
return false;
}
}
function filesystemRejectsChmod(target) {
let probePath;
try {
const probeDir = statSync(target).isDirectory() ? target : path.dirname(target);
probePath = path.join(probeDir, `.openclaw-chmod-probe-${randomUUID()}`);
writeFileSync(probePath, "", {
flag: "wx",
mode: PRIVATE_PROBE_FILE_MODE
});
} catch {
return false;
}
try {
chmodSync(probePath, PRIVATE_PROBE_FILE_MODE);
return false;
} catch (err) {
return err.code === "EPERM";
} finally {
try {
unlinkSync(probePath);
} catch {}
}
}
function canIgnorePrivateChmodError(target, code) {
if (code && CHMOD_UNSUPPORTED_CODES.has(code)) return true;
if (code === "EROFS") return hasRestrictivePermissions(target);
if (code !== "EPERM") return false;
return hasRestrictivePermissions(target) || filesystemRejectsChmod(target);
}
/**
* Applies a private POSIX mode, reporting unsupported filesystems without
* weakening real permission failures.
*/
function applyPrivateModeSync(target, mode) {
try {
chmodSync(target, mode);
return { applied: true };
} catch (err) {
if (!canIgnorePrivateChmodError(target, err.code)) throw err;
return {
applied: false,
error: err
};
}
}
var CHMOD_UNSUPPORTED_CODES, PRIVATE_PROBE_FILE_MODE;
var init_private_mode = __esmMin((() => {
CHMOD_UNSUPPORTED_CODES = /* @__PURE__ */ new Set([
"ENOTSUP",
"EOPNOTSUPP",
"EINVAL"
]);
PRIVATE_PROBE_FILE_MODE = 384;
}));
//#endregion
//#region src/infra/gateway-state-owner-directory.ts
function ensureOwnerDirectory(directory, created) {
const firstCreated = fs.mkdirSync(directory, {
recursive: true,
mode: 448
});
if (firstCreated && created) {
const boundary = path.toNamespacedPath(firstCreated);
const directories = [];
for (let current = directory;;) {
const { dev, ino } = fs.lstatSync(current, { bigint: true });
directories.push({
path: current,
dev,
ino
});
if (path.toNamespacedPath(current) === boundary) break;
const parent = path.dirname(current);
if (parent === current) throw new Error("Created state ownership directory is outside its expected ancestry");
current = parent;
}
for (const entry of directories) {
const previous = created.findIndex((candidate) => candidate.path === entry.path);
if (previous < 0) created.push(entry);
else created[previous] = entry;
}
}
const observed = fs.lstatSync(directory);
const uid = process.getuid?.();
if (!observed.isDirectory() || uid !== void 0 && observed.uid !== uid) throw new Error("State ownership directory must be a user-owned real directory");
if (process.platform !== "win32" && (observed.mode & 4095) !== 448) {
applyPrivateModeSync(directory, 448);
if ((fs.lstatSync(directory).mode & 63) !== 0) throw new Error("State ownership directory permissions are not private");
}
}
function removeCreatedProjectionDirectories(directories) {
let directory = directories[0];
while (directory) {
try {
const observed = fs.lstatSync(directory.path, { bigint: true });
if (observed.isDirectory() && observed.dev === directory.dev && observed.ino === directory.ino) fs.rmdirSync(directory.path);
} catch (error) {
const code = extractErrorCode(error);
if (code !== "ENOENT" && code !== "ENOTEMPTY" && code !== "EEXIST") throw error;
}
directories.shift();
directory = directories[0];
}
}
var init_gateway_state_owner_directory = __esmMin((() => {
init_error_coercion();
init_private_mode();
}));
//#endregion
//#region src/infra/stale-lock-file.ts
function readLockFileOwnerPayload(payload) {
if (!payload) return null;
return {
pid: typeof payload.pid === "number" && Number.isInteger(payload.pid) && payload.pid > 0 ? payload.pid : void 0,
createdAt: typeof payload.createdAt === "string" ? payload.createdAt : void 0,
starttime: typeof payload.starttime === "number" && Number.isInteger(payload.starttime) && payload.starttime >= 0 ? payload.starttime : void 0
};
}
/** Capture only the bounded facts used by this exact stale decision. Never
* resample the owner after failure or copy arbitrary sidecar payload fields. */
function inspectStaleLockOwner(params) {
const payload = readLockFileOwnerPayload(params.payload);
if (!payload?.pid) return null;
const observedStarttime = payload.starttime === void 0 ? null : (params.getProcessStartTime ?? getFileLockProcessStartTime)(payload.pid);
const identity = {
pid: payload.pid,
recordedStarttime: payload.starttime ?? null,
observedStarttime
};
const normalizedStored = process.platform === "darwin" && payload.starttime !== void 0 && payload.starttime > 1e10 ? Math.floor(payload.starttime / 1e6) : payload.starttime;
if (observedStarttime !== null && observedStarttime !== normalizedStored) return {
reason: "owner-starttime-changed",
...identity
};
return (params.isPidDefinitelyDead ?? isPidDefinitelyDead)(payload.pid) ? {
reason: "owner-process-exited",
...identity
} : null;
}
function isLockOwnerDefinitelyStale(params) {
return inspectStaleLockOwner(params) !== null;
}
var init_stale_lock_file = __esmMin((() => {
init_pid_alive();
}));
//#endregion
//#region src/infra/gateway-state-owner.ts
function hasPhysicalOwnership(owner) {
return verifyOwnerLock(owner, owner.locks.values().next().value);
}
function verifyOwnerLock(owner, lock) {
owner.verifiedAt = void 0;
if (!lock?.verifyStillHeld()) return false;
owner.verifiedAt = performance.now();
return true;
}
/** The synchronous lexical owner is live authority, not the existence of its sidecar. */
function getStateDatabaseSchemaLease(databasePath) {
const entry = schemaOwners.getStore()?.get(resolveGatewayStateOwnerPath(databasePath));
if (!entry) return;
if (!entry.active) throw new Error("State schema maintenance scope is no longer current");
entry.lease.assertCurrent();
return entry.lease;
}
/** State cleanup preserves this owner until destructive work and native handles settle. */
function resolveGatewayStateOwnerPath(databasePath) {
const canonical = resolveIdentityPathViaExistingAncestorSync(databasePath);
const uid = process.getuid?.();
const directory = process.platform === "win32" ? path.join(os.homedir(), "AppData", "Local", "OpenClaw", "locks", uid === void 0 ? "openclaw-state-owners" : `openclaw-state-owners-${uid}`) : resolveGatewayLockDirForCanonicalStateDir(resolveOpenClawStateDirForDatabasePath(canonical));
return path.join(resolveIdentityPathViaExistingAncestorSync(directory), `state.${sha256HexPrefixCore(canonical, 16)}.lock`);
}
function defaultPayload(databasePath, role = "sqlite-maintenance") {
const stateDir = resolveOpenClawStateDirForDatabasePath(databasePath);
const startTime = getFileLockProcessStartTime(process.pid);
return {
pid: process.pid,
ownerId: randomUUID(),
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
stateDir,
configPath: path.join(stateDir, "openclaw.json"),
role,
...startTime === null ? {} : { startTime }
};
}
function acquireOwnerFile(databasePath, pathname, payload, busyTimeoutMs = 0, createdDirectories) {
const deadline = performance.now() + busyTimeoutMs;
ensureOwnerDirectory(path.dirname(pathname), createdDirectories);
const stale = ({ payload: value }) => {
return isLockOwnerDefinitelyStale({ payload: isRecord(value) ? {
pid: value.pid,
starttime: value.startTime
} : null });
};
if (busyTimeoutMs > 0) try {
const previous = parseGatewayLockPayload(fs.readFileSync(pathname, "utf8"));
if (previous && !stale({ payload: previous }) && (previous.pid === process.pid || (previous.role ?? "gateway") === "gateway" && isPidAlive(previous.pid))) throw new GatewayStateOwnerContentionError(databasePath);
} catch (error) {
if (extractErrorCode(error) !== "ENOENT") throw error;
}
for (let retriedMissingParent = false;;) try {
return acquireFileLockSync(pathname, {
lockPath: pathname,
retry: busyTimeoutMs > 0 ? {
factor: 1.25,
minTimeout: 10,
maxTimeout: 25,
randomize: false
} : { retries: 0 },
timeoutMs: Math.max(0, Math.ceil(deadline - performance.now())),
staleMs: Infinity,
staleRecovery: "remove-if-unchanged",
reentrantOwner: payload.ownerId,
payload: () => payload,
parsePayload: parseGatewayLockPayload,
shouldReclaim: stale,
shouldRemoveStaleLock: stale
});
} catch (error) {
const code = extractErrorCode(error);
if (code === "ENOENT" && !retriedMissingParent) {
retriedMissingParent = true;
ensureOwnerDirectory(path.dirname(pathname), createdDirectories);
continue;
}
if (code === "file_lock_timeout" || code === "file_lock_stale") throw new GatewayStateOwnerContentionError(databasePath, error);
throw error;
}
}
function leaseForFile(pathname, lock, owner, projection) {
let released = false;
const lease = {
path: pathname,
assertCurrent() {
if (released || !verifyOwnerLock(owner, lock) || projection && !projection.verifyStillHeld()) throw new Error("OpenClaw state ownership is no longer current");
},
assertDatabaseAccess(databasePath) {
if (released || owners.get(pathname) !== owner || resolveGatewayStateOwnerPath(databasePath) !== pathname || !verifyOwnerLock(owner, lock) || projection && !projection.verifyStillHeld()) throw new Error("OpenClaw state maintenance does not own this database");
},
run(operation) {
lease.assertCurrent();
readOwnerPaths.clear();
const inherited = new Map(schemaOwners.getStore());
const entry = {
lease,
active: true
};
inherited.set(pathname, entry);
try {
return schemaOwners.run(inherited, operation);
} finally {
entry.active = false;
readOwnerPaths.clear();
}
},
release() {
readOwnerPaths.clear();
if (!released) {
projection?.release();
lock.release();
released = true;
owner.locks.delete(lock);
if (owner.locks.size === 0 && owners.get(pathname) === owner) {
owner.accepting = false;
owners.delete(pathname);
}
}
if (owner.locks.size === 0) removeCreatedProjectionDirectories(owner.projectionDirectories);
}
};
return lease;
}
/** Accepted schema work retains the sidecar even when its process owner stops lending. */
function acquireStateDatabaseSchemaLease(databasePath, options = {}) {
readOwnerPaths.clear();
const pathname = resolveGatewayStateOwnerPath(databasePath);
let owner = owners.get(pathname);
if (owner && (!owner.accepting || !hasPhysicalOwnership(owner))) throw new GatewayStateOwnerContentionError(databasePath);
if (owner) assertStateDatabaseAccessAllowed(databasePath);
const payload = owner?.payload ?? {
...defaultPayload(databasePath),
stateOwnerKind: "schema"
};
let lock;
const projectionDirectories = [];
try {
lock = acquireOwnerFile(databasePath, pathname, payload, owner ? 0 : options.busyTimeoutMs ?? 5e3, projectionDirectories);
} catch (error) {
if (error instanceof GatewayStateOwnerContentionError) try {
assertStateDatabaseAccessAllowed(databasePath);
} catch (currentOwnerError) {
if (currentOwnerError instanceof StateDatabaseAdmissionPendingError) throw currentOwnerError;
}
throw error;
}
const projectionPath = owner?.projectionPath ?? path.join(resolveGatewayLockDir(resolveOpenClawStateDirForDatabasePath(resolveIdentityPathViaExistingAncestorSync(databasePath))), "gateway.state.lock");
let projection;
try {
projection = owner?.getProjection?.()?.retain() ?? acquireOwnerFile(databasePath, projectionPath, {
...payload,
role: payload.role === "gateway" ? "gateway" : "agent-embedded"
}, 0, projectionDirectories);
} catch (error) {
return runWithSqliteCleanup({ release() {
lock.release();
removeCreatedProjectionDirectories(projectionDirectories);
} }, "state schema projection admission", () => {
throw error;
});
}
if (owner) {
owner.locks.add(lock);
owner.projectionDirectories.push(...projectionDirectories);
} else {
owner = {
kind: "schema",
payload,
projectionPath,
locks: /* @__PURE__ */ new Set([lock]),
projectionDirectories,
accepting: true
};
owners.set(pathname, owner);
}
const lease = leaseForFile(pathname, lock, owner, projection);
try {
lease.assertCurrent();
return lease;
} catch (error) {
return runWithSqliteCleanup(lease, "state schema ownership verification", () => {
throw error;
});
}
}
function hasRecentVerification(verifiedAt, now) {
return verifiedAt !== void 0 && now - verifiedAt < READ_OWNERSHIP_MAX_AGE_MS;
}
/** Only explicit reads reuse recent physical verification; mutations always check freshly. */
function assertStateDatabaseReadAllowed(databasePath) {
if (owners.size === 0) {
assertStateDatabaseAccessAllowed(databasePath);
return;
}
const key = path.resolve(databasePath);
const now = performance.now();
const cached = readOwnerPaths.get(key);
const projection = cached?.owner.getProjection?.();
if (cached && now < cached.expiresAt && owners.get(cached.pathname) === cached.owner && cached.owner.accepting && hasRecentVerification(cached.owner.verifiedAt, now) && (!cached.owner.getProjection || projection && hasRecentVerification(projection.verifiedAt, now))) return;
readOwnerPaths.delete(key);
const pathname = resolveGatewayStateOwnerPath(databasePath);
const owner = owners.get(pathname);
const role = owner?.payload.role ?? "gateway";
if (!owner || owner.kind !== "process" || !owner.accepting || role !== "gateway" && role !== "agent-embedded") {
assertStateDatabaseAccessAllowed(databasePath);
return;
}
if (!hasPhysicalOwnership(owner) || owner.getProjection && !owner.getProjection()?.verifyStillHeld()) throw new Error(`OpenClaw state ownership at ${databasePath} could not be verified; retry after maintenance finishes.`);
readOwnerPaths.set(key, {
pathname,
owner,
expiresAt: now + READ_OWNERSHIP_MAX_AGE_MS
});
}
/** Ordinary SQLite access observes maintenance; it never borrows schema authority. */
function assertStateDatabaseAccessAllowed(databasePath, captured) {
const assertMaintenance = () => {
const schemaLease = captured ? captured.schemaLease : getStateDatabaseSchemaLease(databasePath);
if (schemaLease) {
schemaLease.assertDatabaseAccess(databasePath);
return;
}
const scope = captured ? captured.maintenanceScope : getOpenClawDatabaseMaintenanceScope();
if (!scope) throw new Error(`OpenClaw state at ${databasePath} is undergoing offline maintenance; retry when it finishes.`);
scope.assertDatabaseAccess(databasePath);
};
const pathname = resolveGatewayStateOwnerPath(databasePath);
const local = owners.get(pathname);
const unavailable = `OpenClaw state ownership at ${databasePath} could not be verified; retry after maintenance finishes.`;
if (local) {
if (!hasPhysicalOwnership(local)) throw new Error(unavailable);
const role = local.payload.role ?? "gateway";
if (!local.accepting || role !== "gateway" && role !== "agent-embedded") assertMaintenance();
return;
}
let raw;
try {
raw = fs.readFileSync(pathname, "utf8");
} catch (error) {
if (extractErrorCode(error) === "ENOENT") return;
throw new Error(unavailable, { cause: error });
}
const owner = parseGatewayLockPayload(raw);
if (!owner) throw new StateDatabaseAdmissionPendingError(databasePath, unavailable);
if (!Number.isSafeInteger(owner.pid) || owner.pid <= 0) throw new Error(unavailable);
if (isLockOwnerDefinitelyStale({ payload: {
pid: owner.pid,
starttime: owner.startTime
} })) return;
if (owner.pid === process.pid && !isMainThread) return;
if (!isPidAlive(owner.pid)) throw new Error(unavailable);
const role = owner.role ?? "gateway";
if (role === "gateway" || role === "agent-embedded") return;
if (owner.pid === process.pid) {
assertMaintenance();
return;
}
if (owner.stateOwnerKind === "schema" && owner.role === "sqlite-maintenance") throw new StateDatabaseAdmissionPendingError(databasePath, `OpenClaw state at ${databasePath} is undergoing offline maintenance; retry when it finishes.`);
throw new Error(`OpenClaw state at ${databasePath} is undergoing offline maintenance; retry when it finishes.`);
}
var READ_OWNERSHIP_MAX_AGE_MS, readOwnerPaths, owners, schemaOwners, GatewayStateOwnerContentionError, StateDatabaseAdmissionPendingError;
var init_gateway_state_owner = __esmMin((() => {
init_error_coercion();
init_record_coerce();
init_paths$1();
init_global_singleton();
init_pid_alive();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_contract();
init_openclaw_state_db_paths();
init_boundary_path();
init_crypto_digest();
init_file_lock_manager();
init_gateway_lock_payload();
init_gateway_state_owner_directory();
init_sqlite_lifecycle_errors();
init_stale_lock_file();
READ_OWNERSHIP_MAX_AGE_MS = 1e3;
readOwnerPaths = resolveGlobalSingleton(Symbol.for("openclaw.gatewayStateReadOwnerPaths"), () => /* @__PURE__ */ new Map());
owners = resolveGlobalSingleton(Symbol.for("openclaw.gatewayStateOwners"), () => /* @__PURE__ */ new Map());
schemaOwners = resolveGlobalSingleton(Symbol.for("openclaw.stateDatabaseSchemaOwners"), () => new AsyncLocalStorage());
GatewayStateOwnerContentionError = resolveGlobalSingleton(Symbol.for("openclaw.gatewayStateOwnerContentionError"), () => class StateOwnerContentionError extends Error {
constructor(databasePath, cause) {
super(`OpenClaw state database is busy at ${databasePath}. Wait for the other OpenClaw process to finish, then retry. If it persists, run \`openclaw gateway status\` and check for other OpenClaw processes using the same state directory. A running Gateway can hold this ownership until it stops; stop it through its service manager or original terminal before retrying.`);
this.databasePath = databasePath;
this.cause = cause;
this.name = "GatewayStateOwnerContentionError";
}
});
StateDatabaseAdmissionPendingError = resolveGlobalSingleton(Symbol.for("openclaw.stateDatabaseAdmissionPendingError"), () => class extends Error {
constructor(databasePath, message) {
super(message);
this.databasePath = databasePath;
}
});
}));
//#endregion
//#region src/infra/sqlite-post-commit.ts
/** A lost transaction invalidates every savepoint's staged state and observers. */
function discardSqliteTransactionState(db, error) {
pendingPublications.get(db)?.splice(0);
const rolledBackState = pendingTransactionState.get(db)?.splice(0) ?? [];
pendingPublications.delete(db);
pendingTransactionState.delete(db);
for (const state of rolledBackState.toReversed()) state.rollback(error);
}
/** Nested rollback restores staged state and discards observers; savepoints wait for outer commit. */
function withSqlitePostCommitPublications(db, transaction) {
const nested = db.isTransaction;
const publications = nested ? pendingPublications.get(db) : [];
const transactionState = nested ? pendingTransactionState.get(db) : [];
const publicationStart = publications?.length ?? 0;
const stateStart = transactionState?.length ?? 0;
if (!nested && publications && transactionState) {
pendingPublications.set(db, publications);
pendingTransactionState.set(db, transactionState);
}
let result;
try {
result = transaction();
} catch (error) {
publications?.splice(publicationStart);
const rolledBackState = transactionState?.splice(stateStart) ?? [];
for (const state of rolledBackState.toReversed()) state.rollback(error);
throw error;
} finally {
if (!nested) {
pendingPublications.delete(db);
pendingTransactionState.delete(db);
}
}
if (!nested) {
for (const state of transactionState ?? []) state.commit();
for (const state of transactionState ?? []) state.prepareObservers?.();
for (const publish of publications ?? []) publish();
}
return result;
}
var pendingPublications, pendingTransactionState;
var init_sqlite_post_commit = __esmMin((() => {
init_global_singleton();
pendingPublications = resolveGlobalSingleton(Symbol.for("openclaw.sqlitePostCommitPublications"), () => /* @__PURE__ */ new WeakMap());
pendingTransactionState = resolveGlobalSingleton(Symbol.for("openclaw.sqliteTransactionState"), () => /* @__PURE__ */ new WeakMap());
}));
//#endregion
//#region src/infra/sqlite-worker-contract.ts
/** Carry only canonical worker classification through a local cleanup aggregate. */
function retainSqliteWorkerErrorCode(error, source) {
let code;
try {
code = Object.getOwnPropertyDescriptor(source, retainedWorkerErrorCode)?.value;
} catch {
return error;
}
if (code === "closed" || code === "overloaded" || code === "unavailable" || code === "outcome-unknown") {
Object.defineProperty(error, retainedWorkerErrorCode, { value: code });
Object.assign(error, { code });
}
return error;
}
var SQLITE_WORKER_MAX_MESSAGE_BYTES, retainedWorkerErrorCode, SqliteWorkerAdmissionTimeoutError, SqliteWorkerError;
var init_sqlite_worker_contract = __esmMin((() => {
init_global_singleton();
SQLITE_WORKER_MAX_MESSAGE_BYTES = 33554432;
retainedWorkerErrorCode = Symbol.for("openclaw.sqliteWorkerErrorCode");
SqliteWorkerAdmissionTimeoutError = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerAdmissionTimeoutError"), () => class AdmissionTimeoutError extends Error {
constructor() {
super("SQLite host admission timed out; retry after transaction rollback");
this.code = "admission-timeout";
this.name = "SqliteWorkerAdmissionTimeoutError";
}
});
SqliteWorkerError = class extends Error {
constructor(message, code) {
super(message);
this.code = code;
this.name = "SqliteWorkerError";
Object.defineProperty(this, retainedWorkerErrorCode, { value: code });
}
};
}));
//#endregion
//#region src/infra/sqlite-worker-operation-admission.ts
/** The caller retains real source custody before invoking the synchronous grant. */
function createSqliteWorkerOperationAdmission(admit, attachment) {
const { port1, port2 } = new MessageChannel();
if (attachment !== void 0) try {
port1.postMessage({
kind: "sqlite-operation-attachment",
value: attachment
}, []);
} catch (error) {
port1.close();
port2.close();
throw error;
}
const inOwnerContext = AsyncLocalStorage.snapshot();
const decisions = /* @__PURE__ */ new Set();
const cleanupFailures = [];
let closed = false;
let failure;
let committed;
let settlement;
let databaseAuthority;
const waiting = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
const recordFailure = (error, source) => {
if (!failure || failure.source === "domain" && source !== "domain") failure = {
error,
source
};
};
const refuse = (decision, error, source) => {
if (Atomics.compareExchange(decision, 0, REQUESTED, REFUSED) === REQUESTED) {
recordFailure(error, source);
Atomics.notify(decision, 0);
} else if (Atomics.load(decision, 0) === GRANTED) cleanupFailures.push(error);
};
const receive = (message) => {
if (isRecord(message) && message.kind === "native-commit") {
if (!isRecord(message.committed) || settlement) {
recordFailure(new SqliteWorkerError("SQLite worker commit receipt is invalid", "outcome-unknown"), "protocol");
return;
}
committed = { facts: message.committed.facts };
return;
}
if (isRecord(message) && message.kind === "native-settlement") {
const value = message.settlement;
if (!isRecord(value) || value.kind !== "completed" && value.kind !== "unknown" || value.committed !== void 0 && !isRecord(value.committed) || settlement) {
recordFailure(new SqliteWorkerError("SQLite worker native settlement is invalid", "outcome-unknown"), "protocol");
return;
}
if (isRecord(value.committed)) committed = { facts: value.committed.facts };
settlement = {
kind: value.kind,
...committed ? { committed } : {}
};
return;
}
if (!isRecord(message) || !(message.decision instanceof SharedArrayBuffer) || message.decision.byteLength !== Int32Array.BYTES_PER_ELEMENT || message.stage !== "open" && message.stage !== "prepare" && message.stage !== "transaction" && message.stage !== "commit") {
recordFailure(new SqliteWorkerError("SQLite worker admission request is invalid", "unavailable"), "protocol");
return;
}
const decision = new Int32Array(message.decision);
const expired = () => {
if (typeof message.deadlineNs === "bigint" && process.hrtime.bigint() >= message.deadlineNs) {
if (Atomics.compareExchange(decision, 0, REQUESTED, TIMED_OUT) === REQUESTED) Atomics.notify(decision, 0);
}
if (Atomics.load(decision, 0) !== TIMED_OUT) return false;
if (Array.isArray(message.ports)) {
for (const port of message.ports) if (port instanceof MessagePort) port.close();
}
return true;
};
if (expired()) return;
decisions.add(decision);
if (closed) {
refuse(decision, new SqliteWorkerError("SQLite worker admission is closed", "closed"), "authority");
return;
}
const request = {
stage: message.stage,
facts: message.facts
};
const grant = () => {
if (closed || expired() || Atomics.load(decision, 0) !== REQUESTED) return false;
try {
inOwnerContext(() => databaseAuthority?.assertAccess());
} catch (error) {
refuse(decision, error, "authority");
return false;
}
if (closed || expired() || Atomics.load(decision, 0) !== REQUESTED) return false;
const granted = Atomics.compareExchange(decision, 0, REQUESTED, GRANTED) === REQUESTED;
if (granted) Atomics.notify(decision, 0);
return granted;
};
let source = "authority";
try {
inOwnerContext(() => {
databaseAuthority?.assertRequest?.();
databaseAuthority?.assertAccess();
});
if (request.stage === "prepare" && isRecord(request.facts) && request.facts.kind === "schema-maintenance") {
const authority = databaseAuthority;
if (!authority || typeof request.facts.databasePath !== "string" || resolveIdentityPathViaExistingAncestorSync(request.facts.databasePath) !== authority.databasePath) throw new SqliteWorkerError("SQLite schema maintenance target differs from its admitted database", "closed");
inOwnerContext(() => {
authority.lease ??= authority.acquireSchema();
authority.lease.assertCurrent();
grant();
});
} else {
source = "domain";
inOwnerContext(admit, request, grant);
}
} catch (error) {
refuse(decision, error, source);
return;
} finally {
decisions.delete(decision);
}
if (Atomics.load(decision, 0) === REQUESTED) refuse(decision, new SqliteWorkerError("SQLite worker admission was not granted", "closed"), "domain");
};
port1.on("message", receive);
port1.unref();
const service = () => {
for (let queued = receiveMessageOnPort(port1); queued; queued = receiveMessageOnPort(port1)) receive(queued.message);
};
return {
port: port2,
bindDatabaseAuthority(authority) {
if (closed || databaseAuthority) throw new SqliteWorkerError("SQLite database authority is already bound or closed", "closed");
databaseAuthority = {
...authority,
databasePath: resolveIdentityPathViaExistingAncestorSync(authority.databasePath)
};
},
get failure() {
return failure?.error;
},
get failureSource() {
return failure?.source;
},
get cleanupFailures() {
return cleanupFailures;
},
get committed() {
service();
return committed;
},
get settlement() {
return settlement;
},
waitForSettlement(deadlineMs) {
while (true) {
service();
if (failure !== void 0) throw toErrorObject(failure.error, "SQLite worker admission failed");
if (settlement?.kind === "completed") return settlement;
const remaining = deadlineMs - performance.now();
if (settlement?.kind === "unknown" || closed || remaining <= 0) throw new SqliteWorkerError("SQLite worker native settlement is unknown", "outcome-unknown");
Atomics.wait(waiting, 0, 0, Math.min(5, remaining));
}
},
service,
finish() {
closed = true;
service();
for (const decision of decisions) if (Atomics.load(decision, 0) === REQUESTED) refuse(decision, new SqliteWorkerError("SQLite worker admission is closed", "closed"), "authority");
port1.close();
port2.close();
if (databaseAuthority?.lease) try {
databaseAuthority.lease.release();
databaseAuthority.lease = void 0;
} catch (error) {
cleanupFailures.push(error);
}
}
};
}
/** Called on the SQLite worker, after transaction entry and before its row mutation. */
function requestSqliteWorkerOperationAdmission(request, transferList = []) {
const scope = currentAdmission.getStore();
if (!scope?.active) throw new SqliteWorkerError("SQLite operation requires its retained admission", "unavailable");
const decision = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
const deadlineNs = request.deadlineMs === void 0 ? void 0 : process.hrtime.bigint() + BigInt(request.deadlineMs) * 1000000n;
scope.port.postMessage({
...request,
decision: decision.buffer,
deadlineNs,
ports: transferList.filter((value) => value instanceof MessagePort)
}, transferList);
while (Atomics.load(decision, 0) === REQUESTED) {
const remainingMs = deadlineNs === void 0 ? void 0 : Number(deadlineNs - process.hrtime.bigint()) / 1e6;
if (remainingMs !== void 0 && remainingMs <= 0) Atomics.compareExchange(decision, 0, REQUESTED, TIMED_OUT);
else Atomics.wait(decision, 0, REQUESTED, remainingMs);
}
if (Atomics.load(decision, 0) !== GRANTED) {
const refusal = Atomics.load(decision, 0) === TIMED_OUT ? new SqliteWorkerAdmissionTimeoutError() : new SqliteWorkerError("SQLite transaction admission was refused", "closed");
scope.owner.refusal = refusal;
throw refusal;
}
}
/** Schema work borrows live host authority through the same retained job port. */
function requestSqliteWorkerSchemaMaintenance(databasePath) {
if (!currentAdmission.getStore()) return false;
requestSqliteWorkerOperationAdmission({
stage: "prepare",
facts: {
kind: "schema-maintenance",
databasePath
}
});
return true;
}
var REQUESTED, GRANTED, REFUSED, TIMED_OUT, currentAdmission;
var init_sqlite_worker_operation_admission = __esmMin((() => {
init_error_coercion();
init_record_coerce();
init_global_singleton();
init_boundary_path();
init_sqlite_post_commit();
init_sqlite_worker_contract();
REQUESTED = 0;
GRANTED = 1;
REFUSED = 2;
TIMED_OUT = 3;
resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerOpenRefusedError"), () => class OpenRefusedError extends Error {
constructor(originalError) {
super("SQLite worker admission was refused before agent open", { cause: originalError });
this.originalError = originalError;
this.name = "SqliteWorkerOpenRefusedError";
}
});
currentAdmission = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerOperationAdmission"), () => new AsyncLocalStorage());
}));
//#endregion
//#region src/infra/state-database-maintenance.ts
/** Ordinary transactions use SQLite; schema changes retain the installation's process owner. */
function withStateDatabaseSchemaMaintenance({ databasePath, busyTimeoutMs }, operation) {
if (requestSqliteWorkerSchemaMaintenance(databasePath)) return operation();
const canonical = resolveIdentityPathViaExistingAncestorSync(databasePath);
const inherited = getStateDatabaseSchemaLease(canonical);
if (inherited) {
inherited.assertCurrent();
return operation();
}
let lease;
try {
lease = acquireStateDatabaseSchemaLease(canonical, { busyTimeoutMs });
} catch (error) {
if (error instanceof GatewayStateOwnerContentionError) throw new StateSchemaMutationConflictError(canonical, error);
throw error;
}
return runWithSqliteCleanup(lease, "state schema mutation", () => lease.run(operation));
}
var StateSchemaMutationConflictError;
var init_state_database_maintenance = __esmMin((() => {
init_global_singleton();
init_boundary_path();
init_gateway_state_owner();
init_sqlite_lifecycle_errors();
init_sqlite_worker_operation_admission();
StateSchemaMutationConflictError = resolveGlobalSingleton(Symbol.for("openclaw.stateSchemaMutationConflictError"), () => class SchemaMutationConflictError extends Error {
constructor(databasePath, cause) {
super(`OpenClaw refused shared state schema mutation at ${databasePath} because another Gateway owns that state directory. Stop that Gateway or perform the update through its managed restart path, then retry.`, { cause });
this.name = "StateSchemaMutationConflictError";
}
});
}));
//#endregion
//#region src/infra/sqlite-terminal-open-latch.ts
function generationMatchesPath(pathname, expected) {
try {
return sameSqliteFileGeneration(expected, readStableSqliteFileGeneration(pathname));
} catch {
return false;
}
}
/**
* Per-path latch for terminal database-open failures (newer schema, proven
* corruption). Recording quarantines the path: any live handle is closed and
* every later open fails fast until doctor repairs the file and clears it.
*/
function createSqliteTerminalOpenLatch(options) {
const failures = /* @__PURE__ */ new Map();
return {
/** Read the owner's recorded fact without running filesystem or database inspection. */
peek: (pathname) => failures.get(path.resolve(pathname))?.error,
get: (pathname) => {
const resolvedPath = path.resolve(pathname);
const failure = failures.get(resolvedPath);
if (!failure) return;
if (failure.generation && !generationMatchesPath(resolvedPath, failure.generation)) {
failures.delete(resolvedPath);
return;
}
return failure.error;
},
async getAsync(pathname, isCurrentGeneration) {
const resolvedPath = path.resolve(pathname);
for (;;) {
const failure = failures.get(resolvedPath);
if (!failure?.generation) return failure?.error;
const current = await isCurrentGeneration(resolvedPath, failure.generation);
if (failures.get(resolvedPath) !== failure) continue;
if (!current) {
failures.delete(resolvedPath);
return;
}
return failure.error;
}
},
record: (pathname, error, generation) => {
const resolvedPath = path.resolve(pathname);
if (generation && !generationMatchesPath(resolvedPath, generation)) return false;
failures.set(resolvedPath, {
error,
...generation ? { generation } : {}
});
options.closeByPath(resolvedPath, error);
if (generation && !generationMatchesPath(resolvedPath, generation)) {
failures.delete(resolvedPath);
return false;
}
return true;
},
clear: (pathname) => {
failures.delete(path.resolve(pathname));
},
clearAll: (rootPath) => {
for (const pathname of failures.keys()) if (rootPath === void 0 || isPathInside$1(rootPath, pathname)) failures.delete(pathname);
}
};
}
var init_sqlite_terminal_open_latch = __esmMin((() => {
init_path_guards();
init_sqlite_file_generation();
}));
//#endregion
//#region packages/terminal-core/src/progress-line.ts
/** Clear the active progress line when it is attached to a TTY stream. */
function clearActiveProgressLine() {
if (!activeStream?.isTTY) return;
activeStream.write("\r\x1B[2K");
}
var activeStream;
var init_progress_line = __esmMin((() => {
activeStream = null;
}));
//#endregion
//#region src/global-state.ts
function isVerbose() {
return globalVerbose;
}
var globalVerbose;
var init_global_state = __esmMin((() => {
globalVerbose = false;
}));
//#endregion
//#region src/infra/diagnostic-event-listener-presence.ts
function getDiagnosticEventListenerPresence() {
const existing = globalThis[DIAGNOSTIC_EVENT_LISTENER_PRESENCE_KEY];
if (existing && typeof existing === "object" && existing.marker === DIAGNOSTIC_EVENT_LISTENER_PRESENCE_KEY) {
const state = existing;
state.broadInterestCount ??= 0;
state.eventInterestDeltas ??= /* @__PURE__ */ new Map();
return state;
}
const state = {
broadInterestCount: 0,
eventInterestDeltas: /* @__PURE__ */ new Map(),
marker: DIAGNOSTIC_EVENT_LISTENER_PRESENCE_KEY,
internalCount: 0,
trustedCount: 0
};
Object.defineProperty(globalThis, DIAGNOSTIC_EVENT_LISTENER_PRESENCE_KEY, {
configurable: true,
enumerable: false,
value: state,
writable: false
});
return state;
}
function isInternalDiagnosticEventInterested(interest, type, trusted) {
return (!interest?.include || interest.include.includes(type)) && !interest?.exclude?.includes(type) && (!trusted || !interest?.includeTrusted || interest.includeTrusted.includes(type));
}
function hasInternalDiagnosticEventInterest(type) {
const state = getDiagnosticEventListenerPresence();
return state.broadInterestCount + (state.eventInterestDeltas.get(type) ?? 0) > 0;
}
var DIAGNOSTIC_EVENT_LISTENER_PRESENCE_KEY;
var init_diagnostic_event_listener_presence = __esmMin((() => {
DIAGNOSTIC_EVENT_LISTENER_PRESENCE_KEY = Symbol.for("openclaw.diagnosticEventListenerPresence.v1");
}));
//#endregion
//#region src/infra/diagnostic-event-snapshot.ts
function createDiagnosticMetadataForListener(metadata) {
return Object.freeze({ ...metadata });
}
function cloneDiagnosticValueForListener(value) {
return deepFreezeDiagnosticValue(structuredClone(value));
}
function deepFreezeDiagnosticValue(value, seen = /* @__PURE__ */ new WeakSet()) {
if (!value || typeof value !== "object") return value;
if (seen.has(value)) return value;
seen.add(value);
if (Array.isArray(value)) {
for (const item of value) deepFreezeDiagnosticValue(item, seen);
return Object.freeze(value);
}
for (const nested of Object.values(value)) deepFreezeDiagnosticValue(nested, seen);
return Object.freeze(value);
}
var init_diagnostic_event_snapshot = __esmMin((() => {}));
//#endregion
//#region src/infra/diagnostic-model-request-provenance.ts
var CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY;
var init_diagnostic_model_request_provenance = __esmMin((() => {
CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY = "coreModelRequestLifecycle";
}));
//#endregion
//#region src/infra/diagnostic-otel-listener-provenance.ts
function isTrustedOtelDiagnosticListener(listener) {
return trustedOtelDiagnosticListeners.has(listener);
}
var trustedOtelDiagnosticListeners;
var init_diagnostic_otel_listener_provenance = __esmMin((() => {
trustedOtelDiagnosticListeners = /* @__PURE__ */ new WeakSet();
}));
//#endregion
//#region src/infra/diagnostic-semantic-run-progress-provenance.ts
var CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY;
var init_diagnostic_semantic_run_progress_provenance = __esmMin((() => {
CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY = "coreSemanticRunProgress";
})), TOOL_EXECUTION_LIVENESS_METADATA_KEY;
var init_diagnostic_tool_execution_liveness = __esmMin((() => {
init_global_singleton();
TOOL_EXECUTION_LIVENESS_METADATA_KEY = "toolExecutionLiveness";
resolveGlobalSingleton(Symbol.for("openclaw.diagnosticToolExecutionLiveness"), () => ({
context: new AsyncLocalStorage(),
events: /* @__PURE__ */ new WeakMap()
}));
}));
//#endregion
//#region src/infra/diagnostic-trace-context.ts
function isNonZeroHex(value) {
return !/^0+$/.test(value);
}
function createDiagnosticTraceScopeState() {
return {
marker: DIAGNOSTIC_TRACE_SCOPE_STATE_KEY,
storage: new AsyncLocalStorage()
};
}
function isDiagnosticTraceScopeState(value) {
if (!value || typeof value !== "object") return false;
const candidate = value;
return candidate.marker === DIAGNOSTIC_TRACE_SCOPE_STATE_KEY && candidate.storage instanceof AsyncLocalStorage;
}
function getDiagnosticTraceScopeState() {
const existing = globalThis[DIAGNOSTIC_TRACE_SCOPE_STATE_KEY];
if (isDiagnosticTraceScopeState(existing)) return existing;
const state = createDiagnosticTraceScopeState();
Object.defineProperty(globalThis, DIAGNOSTIC_TRACE_SCOPE_STATE_KEY, {
configurable: true,
enumerable: false,
value: state,
writable: false
});
return state;
}
/** Returns whether a value is a non-zero W3C trace id. */
function isValidDiagnosticTraceId(value) {
return typeof value === "string" && TRACE_ID_RE.test(value) && isNonZeroHex(value);
}
/** Returns whether a value is a non-zero W3C span id. */
function isValidDiagnosticSpanId(value) {
return typeof value === "string" && SPAN_ID_RE.test(value) && isNonZeroHex(value);
}
/** Returns whether a value is a valid W3C trace-flags byte. */
function isValidDiagnosticTraceFlags(value) {
return typeof value === "string" && TRACE_FLAGS_RE.test(value);
}
/** Returns the trace context bound to the current async scope. */
function getActiveDiagnosticTraceContext() {
return getDiagnosticTraceScopeState().storage.getStore();
}
var TRACE_ID_RE, SPAN_ID_RE, TRACE_FLAGS_RE, DIAGNOSTIC_TRACE_SCOPE_STATE_KEY;
var init_diagnostic_trace_context = __esmMin((() => {
init_src$2();
TRACE_ID_RE = /^[0-9a-f]{32}$/;
SPAN_ID_RE = /^[0-9a-f]{16}$/;
TRACE_FLAGS_RE = /^[0-9a-f]{2}$/;
DIAGNOSTIC_TRACE_SCOPE_STATE_KEY = Symbol.for("openclaw.diagnosticTraceScope.state.v1");
}));
//#endregion
//#region src/infra/diagnostic-trace-propagation.ts
function createDiagnosticTracePropagationState() {
return {
marker: DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY,
bridges: /* @__PURE__ */ new Set()
};
}
function isDiagnosticTracePropagationState(value) {
if (!value || typeof value !== "object") return false;
const candidate = value;
return candidate.marker === DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY && candidate.bridges instanceof Set;
}
function getDiagnosticTracePropagationState() {
const existing = globalThis[DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY];
if (isDiagnosticTracePropagationState(existing)) return existing;
const state = createDiagnosticTracePropagationState();
Object.defineProperty(globalThis, DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY, {
configurable: true,
enumerable: false,
value: state,
writable: false
});
return state;
}
function activeDiagnosticTracePropagationBridge() {
let active;
for (const bridge of getDiagnosticTracePropagationState().bridges) active = bridge;
return active;
}
function shouldPrepareDiagnosticTracePropagation(event) {
const bridge = activeDiagnosticTracePropagationBridge();
if (!bridge?.prepareEvent) return false;
if (!bridge.shouldPrepareEvent) return true;
try {
return bridge.shouldPrepareEvent(event);
} catch (error) {
console.error(`[diagnostic-trace-propagation] prepare filter error: ${String(error)}`);
return false;
}
}
function prepareDiagnosticTracePropagation(event, metadata) {
const bridge = activeDiagnosticTracePropagationBridge();
if (!bridge?.prepareEvent) return;
try {
bridge.prepareEvent(event, metadata);
} catch (error) {
console.error(`[diagnostic-trace-propagation] prepare error type=${event.type} seq=${event.seq}: ${String(error)}`);
}
}
var DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY;
var init_diagnostic_trace_propagation = __esmMin((() => {
init_diagnostic_trace_context();
DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY = Symbol.for("openclaw.diagnosticTracePropagation.state.v1");
}));
//#endregion
//#region src/infra/diagnostic-events.ts
function createDiagnosticEventsState() {
return {
marker: DIAGNOSTIC_EVENTS_STATE_KEY,
enabled: true,
seq: 0,
listeners: /* @__PURE__ */ new Map(),
trustedListeners: /* @__PURE__ */ new Map(),
toolExecutionListeners: /* @__PURE__ */ new Set(),
toolExecutionSeq: 0,
dispatchDepth: 0,
asyncQueue: [],
asyncDrainScheduled: false,
asyncDroppedEvents: 0,
asyncDroppedTrustedEvents: 0,
asyncDroppedUntrustedEvents: 0,
asyncDroppedPriorityEvents: 0
};
}
function isDiagnosticEventsState(value) {
if (!value || typeof value !== "object") return false;
const candidate = value;
return candidate.marker === DIAGNOSTIC_EVENTS_STATE_KEY && typeof candidate.enabled === "boolean" && typeof candidate.seq === "number" && candidate.listeners instanceof Map && candidate.trustedListeners instanceof Map && (candidate.toolExecutionListeners === void 0 || candidate.toolExecutionListeners instanceof Set) && typeof candidate.dispatchDepth === "number" && Array.isArray(candidate.asyncQueue) && typeof candidate.asyncDrainScheduled === "boolean";
}
function getDiagnosticEventsState() {
const existing = globalThis[DIAGNOSTIC_EVENTS_STATE_KEY];
if (isDiagnosticEventsState(existing)) {
existing.asyncDroppedEvents ??= 0;
existing.asyncDroppedTrustedEvents ??= 0;
existing.asyncDroppedUntrustedEvents ??= 0;
existing.asyncDroppedPriorityEvents ??= 0;
existing.toolExecutionListeners ??= /* @__PURE__ */ new Set();
existing.toolExecutionSeq ??= 0;
return existing;
}
const state = createDiagnosticEventsState();
Object.defineProperty(globalThis, DIAGNOSTIC_EVENTS_STATE_KEY, {
configurable: true,
enumerable: false,
value: state,
writable: false
});
return state;
}
/** Returns the current process-wide diagnostic dispatcher enable flag. */
function areDiagnosticsEnabledForProcess() {
return getDiagnosticEventsState().enabled;
}
function dispatchDiagnosticEvent(state, enriched, metadata, privateData, options = {}) {
if (state.dispatchDepth > 100) {
console.error(`[diagnostic-events] recursion guard tripped at depth=${state.dispatchDepth}, dropping type=${enriched.type}`);
return;
}
state.dispatchDepth += 1;
try {
if (!options.trustedListenersOnly) for (const [listener, interest] of state.listeners) {
if (!isInternalDiagnosticEventInterested(interest, enriched.type, metadata.trusted)) continue;
try {
listener(cloneDiagnosticValueForListener(enriched), createDiagnosticMetadataForListener(metadata));
} catch (err) {
const errorMessage = err instanceof Error ? err.stack ?? err.message : String(err);
console.error(`[diagnostic-events] listener error type=${enriched.type} seq=${enriched.seq}: ${errorMessage}`);
}
}
for (const [listener, interest] of state.trustedListeners) {
if (!isInternalDiagnosticEventInterested(interest, enriched.type, metadata.trusted)) continue;
try {
const eventForListener = cloneDiagnosticValueForListener(enriched);
const metadataForListener = createDiagnosticMetadataForListener(metadata);
if (interest?.includePrivateData === false) listener(eventForListener, metadataForListener, EMPTY_DIAGNOSTIC_PRIVATE_DATA);
else if (isTrustedOtelDiagnosticListener(listener)) {
const cloned = structuredClone(privateData ?? {});
Reflect.deleteProperty(cloned, "hostPluginId");
listener(eventForListener, metadataForListener, deepFreezeDiagnosticValue(options.hostPluginId ? Object.assign(cloned, { hostPluginId: options.hostPluginId }) : cloned));
} else listener(eventForListener, metadataForListener, privateData ? cloneDiagnosticValueForListener(privateData) : Object.freeze({}));
} catch (err) {
const errorMessage = err instanceof Error ? err.stack ?? err.message : String(err);
console.error(`[diagnostic-events] trusted listener error type=${enriched.type} seq=${enriched.seq}: ${errorMessage}`);
}
}
} finally {
state.dispatchDepth -= 1;
}
}
function isPriorityAsyncDiagnosticEvent(entry) {
return entry.metadata.trusted && PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES.has(entry.event.type);
}
function noteAsyncDiagnosticDrop(state, entry) {
state.asyncDroppedEvents += 1;
if (entry.metadata.trusted) state.asyncDroppedTrustedEvents += 1;
else state.asyncDroppedUntrustedEvents += 1;
if (isPriorityAsyncDiagnosticEvent(entry)) state.asyncDroppedPriorityEvents += 1;
}
function makeRoomForPriorityAsyncDiagnosticEvent(state) {
const nonPriorityIndex = state.asyncQueue.findIndex((entry) => !isPriorityAsyncDiagnosticEvent(entry));
if (nonPriorityIndex >= 0) return state.asyncQueue.splice(nonPriorityIndex, 1)[0];
return state.asyncQueue.shift();
}
function scheduleAsyncDiagnosticDrain(state) {
if (state.asyncDrainScheduled) return;
state.asyncDrainScheduled = true;
setImmediate(() => {
state.asyncDrainScheduled = false;
const batch = state.asyncQueue.splice(0, MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN);
for (const entry of batch) dispatchDiagnosticEvent(state, entry.event, entry.metadata, entry.privateData, {
hostPluginId: entry.hostPluginId,
trustedListenersOnly: entry.trustedListenersOnly
});
if (state.asyncQueue.length > 0) {
scheduleAsyncDiagnosticDrain(state);
return;
}
dispatchAsyncDiagnosticDropSummary(state);
});
}
function dispatchAsyncDiagnosticDropSummary(state) {
if (state.asyncDroppedEvents <= 0) return;
const droppedEvents = state.asyncDroppedEvents;
const droppedTrustedEvents = state.asyncDroppedTrustedEvents;
const droppedUntrustedEvents = state.asyncDroppedUntrustedEvents;
const droppedPriorityEvents = state.asyncDroppedPriorityEvents;
state.asyncDroppedEvents = 0;
state.asyncDroppedTrustedEvents = 0;
state.asyncDroppedUntrustedEvents = 0;
state.asyncDroppedPriorityEvents = 0;
dispatchDiagnosticEvent(state, enrichDiagnosticEvent(state, {
type: "diagnostic.async_queue.dropped",
droppedEvents,
...droppedTrustedEvents > 0 ? { droppedTrustedEvents } : {},
...droppedUntrustedEvents > 0 ? { droppedUntrustedEvents } : {},
...droppedPriorityEvents > 0 ? { droppedPriorityEvents } : {},
queueLength: state.asyncQueue.length,
maxQueueLength: MAX_ASYNC_DIAGNOSTIC_EVENTS,
drainBatchSize: MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN
}), createInternalDiagnosticMetadata(false));
}
function enrichDiagnosticEvent(state, event) {
const enriched = {};
for (const [key, value] of Object.entries(event)) {
if (isBlockedObjectKey(key)) continue;
enriched[key] = value;
}
enriched.trace ??= getActiveDiagnosticTraceContext();
state.seq += 1;
enriched.seq = state.seq;
enriched.ts = Date.now();
return enriched;
}
function createInternalDiagnosticMetadata(trusted) {
return {
internal: true,
trusted
};
}
function emitDiagnosticEventWithTrust(event, trusted, options = {}) {
const state = getDiagnosticEventsState();
if (trusted && isToolExecutionEventInput(event)) dispatchTrustedToolExecutionEvent(state, event);
if (!state.enabled) return;
if (event.type === "security.event" && options.allowSecurityEvent !== true) return;
const enriched = enrichDiagnosticEvent(state, event);
const { hostPluginId, internal = false, privateData } = options;
const trustedTraceContext = options.trustedTraceContext === true;
const metadata = {
...internal ? createInternalDiagnosticMetadata(trusted) : { trusted },
...options.toolExecutionLiveness ? { [TOOL_EXECUTION_LIVENESS_METADATA_KEY]: options.toolExecutionLiveness } : {},
...options.coreModelRequestLifecycle ? { [CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY]: options.coreModelRequestLifecycle } : {},
...options.coreSemanticRunProgress === true ? { [CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY]: true } : {},
...trustedTraceContext ? { trustedTraceContext } : {}
};
const prepareTracePropagation = trusted && !options.queuedPhase && shouldPrepareDiagnosticTracePropagation(enriched);
const queued = options.queuedPhase || ASYNC_DIAGNOSTIC_EVENT_TYPES.has(enriched.type);
if (queued) {
if (state.asyncQueue.length >= MAX_ASYNC_DIAGNOSTIC_EVENTS) {
if (!trusted || !PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES.has(enriched.type)) {
noteAsyncDiagnosticDrop(state, {
event: enriched,
metadata,
privateData,
hostPluginId
});
return;
}
const droppedEntry = makeRoomForPriorityAsyncDiagnosticEvent(state);
if (droppedEntry) noteAsyncDiagnosticDrop(state, droppedEntry);
}
state.asyncQueue.push({
event: enriched,
metadata,
privateData,
hostPluginId
});
}
if (prepareTracePropagation) prepareDiagnosticTracePropagation(cloneDiagnosticValueForListener(enriched), createDiagnosticMetadataForListener(metadata));
if (queued) scheduleAsyncDiagnosticDrain(state);
else dispatchDiagnosticEvent(state, enriched, metadata, privateData, { hostPluginId });
}
function isToolExecutionEventInput(event) {
return event.type === "tool.execution.started" || event.type === "tool.execution.completed" || event.type === "tool.execution.error" || event.type === "tool.execution.blocked";
}
function dispatchTrustedToolExecutionEvent(state, event) {
state.toolExecutionSeq += 1;
let enriched;
try {
enriched = cloneDiagnosticValueForListener({
...event,
seq: state.toolExecutionSeq,
ts: Date.now()
});
} catch (error) {
console.error(`[diagnostic-events] tool execution clone error type=${event.type}: ${String(error)}`);
return;
}
for (const listener of state.toolExecutionListeners) try {
listener(enriched);
} catch (error) {
console.error(`[diagnostic-events] tool execution listener error type=${enriched.type} seq=${enriched.seq}: ${String(error)}`);
}
}
/** Emits an untrusted diagnostic event from external/plugin-facing code. */
function emitDiagnosticEvent(event) {
emitDiagnosticEventWithTrust(event, false);
}
/** Emits an untrusted event whose trace context came from OpenClaw-owned scope. */
function emitDiagnosticEventWithTrustedTraceContext(event) {
emitDiagnosticEventWithTrust(event, false, { trustedTraceContext: true });
}
var EMPTY_DIAGNOSTIC_PRIVATE_DATA, MAX_ASYNC_DIAGNOSTIC_EVENTS, MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN, DIAGNOSTIC_EVENTS_STATE_KEY, ASYNC_DIAGNOSTIC_EVENT_TYPES, PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES;
var init_diagnostic_events = __esmMin((() => {
init_diagnostic_event_listener_presence();
init_diagnostic_event_snapshot();
init_diagnostic_model_request_provenance();
init_diagnostic_otel_listener_provenance();
init_diagnostic_semantic_run_progress_provenance();
init_diagnostic_tool_execution_liveness();
init_diagnostic_trace_context();
init_diagnostic_trace_propagation();
init_prototype_keys();
EMPTY_DIAGNOSTIC_PRIVATE_DATA = Object.freeze({});
MAX_ASYNC_DIAGNOSTIC_EVENTS = 1e4;
MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN = 100;
DIAGNOSTIC_EVENTS_STATE_KEY = Symbol.for("openclaw.diagnosticEvents.state.v1");
ASYNC_DIAGNOSTIC_EVENT_TYPES = /* @__PURE__ */ new Set([
"diagnostic.gc",
"gateway.event_loop.sample",
"gateway.rpc",
"tool.execution.started",
"tool.execution.completed",
"tool.execution.error",
"tool.execution.blocked",
"skill.used",
"exec.process.completed",
"exec.approval.followup_suppressed",
"message.delivery.started",
"message.delivery.completed",
"message.delivery.error",
"talk.event",
"model.call.started",
"model.call.completed",
"model.call.error",
"run.progress",
"run.execution_phase",
"agent.commentary",
"harness.run.completed",
"harness.run.error",
"context.assembled",
"log.record"
]);
PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES = /* @__PURE__ */ new Set([
"tool.execution.completed",
"tool.execution.error",
"tool.execution.blocked",
"model.call.completed",
"model.call.error",
"harness.run.completed",
"harness.run.error"
]);
}));
//#endregion
//#region packages/terminal-core/src/restore.ts
function reportRestoreFailure(scope, err, reason) {
const suffix = reason ? ` (${reason})` : "";
const message = `[terminal] restore ${scope} failed${suffix}: ${String(err)}`;
try {
process.stderr.write(`${message}\n`);
} catch (writeErr) {
console.error(`[terminal] restore reporting failed${suffix}: ${String(writeErr)}`);
}
}
function restoreTerminalState(reason, options = {}) {
const resumeStdin = options.resumeStdinIfPaused ?? options.resumeStdin ?? false;
const resetStream = options.resetStream ?? process.stdout;
try {
clearActiveProgressLine();
} catch (err) {
reportRestoreFailure("progress line", err, reason);
}
const stdin = process.stdin;
if (stdin.isTTY && typeof stdin.setRawMode === "function") {
try {
stdin.setRawMode(false);
} catch (err) {
reportRestoreFailure("raw mode", err, reason);
}
if (resumeStdin && typeof stdin.isPaused === "function" && stdin.isPaused()) try {
stdin.resume();
} catch (err) {
reportRestoreFailure("stdin resume", err, reason);
}
}
if (resetStream.isTTY) try {
resetStream.write(RESET_SEQUENCE);
} catch (err) {
reportRestoreFailure("terminal reset", err, reason);
}
}
var RESET_SEQUENCE;
var init_restore = __esmMin((() => {
init_progress_line();
RESET_SEQUENCE = "\x1B[0m\x1B[?25h\x1B[?1000l\x1B[?1002l\x1B[?1003l\x1B[?1006l\x1B[?2004l\x1B[<u\x1B[>4;0m";
}));
//#endregion
//#region src/runtime.ts
function shouldEmitRuntimeLog(env = process.env) {
if (env.VITEST !== "true") return true;
if (env.OPENCLAW_TEST_RUNTIME_LOG === "1") return true;
return typeof console.log.mock === "object";
}
function shouldEmitRuntimeStdout(env = process.env) {
if (env.VITEST !== "true") return true;
if (env.OPENCLAW_TEST_RUNTIME_LOG === "1") return true;
return typeof process.stdout.write.mock === "object";
}
function isPipeClosedError(err) {
const code = err?.code;
return code === "EPIPE" || code === "EIO";
}
function writeStdout(value) {
if (!shouldEmitRuntimeStdout()) return;
clearActiveProgressLine();
const line = value.endsWith("\n") ? value : `${value}\n`;
try {
process.stdout.write(line);
} catch (err) {
if (isPipeClosedError(err)) return;
throw err;
}
}
function createRuntimeIo() {
return {
log: (...args) => {
if (!shouldEmitRuntimeLog()) return;
clearActiveProgressLine();
console.log(...args);
},
error: (...args) => {
clearActiveProgressLine();
console.error(...args);
},
writeStdout,
writeJson: (value, space = 2) => {
writeStdout(JSON.stringify(value, void 0, space > 0 ? space : void 0));
}
};
}
/** Keep terminal reset bytes off stdout when the invocation owns machine-readable output. */
function restoreRuntimeTerminalState(reason, options = {}) {
const resetStream = options.resetStream ?? (loggingState.forceConsoleToStderr ? process.stderr : void 0);
restoreTerminalState(reason, {
...options,
...resetStream ? { resetStream } : {}
});
}
var defaultRuntime;
var init_runtime = __esmMin((() => {
init_progress_line();
init_restore();
init_state();
defaultRuntime = {
...createRuntimeIo(),
exit: (code, opts) => {
restoreRuntimeTerminalState("runtime exit", {
resumeStdinIfPaused: false,
...opts?.resetStream ? { resetStream: opts.resetStream } : {}
});
process.exit(code);
throw new Error("unreachable");
}
};
})), ANSI_OSC_INTRODUCER_PATTERN, ANSI_STRING_TERMINATOR_PATTERN, ANSI_OSC_PATTERN, ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN;
var init_ansi_sequences = __esmMin((() => {
ANSI_OSC_INTRODUCER_PATTERN = "(?:\\x1b\\]|\\x9d)";
ANSI_STRING_TERMINATOR_PATTERN = "(?:\\x1b\\\\|\\x07|\\x9c)";
ANSI_OSC_PATTERN = `${ANSI_OSC_INTRODUCER_PATTERN}[^\\x07\\x1b\\x9c]*${ANSI_STRING_TERMINATOR_PATTERN}`;
ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
new RegExp(ANSI_OSC_PATTERN, "y");
})), ANSI_OSC_SEQUENCE_PATTERN;
var init_ansi = __esmMin((() => {
init_ansi_sequences();
ANSI_OSC_SEQUENCE_PATTERN = `${ANSI_OSC_INTRODUCER_PATTERN}[\\s\\S]*?${ANSI_STRING_TERMINATOR_PATTERN}`;
new RegExp(`${ANSI_OSC_SEQUENCE_PATTERN}|${ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN}`, "y");
new Intl.Segmenter(void 0, { granularity: "grapheme" });
new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}${String.fromCharCode(127)}-${String.fromCharCode(159)}]`, "g");
}));
//#endregion
//#region src/cli/signal-exit-barrier.ts
/** Temporary artifacts remain available until other shutdown owners have drained. */
function registerSignalExitFinalizer(finalizer) {
activeFinalizers.add(finalizer);
return () => activeFinalizers.delete(finalizer);
}
var activeFinalizers;
var init_signal_exit_barrier = __esmMin((() => {
init_global_singleton();
resolveGlobalSet(Symbol.for("openclaw.signalExitBarriers"), "close-and-restart");
resolveGlobalSet(Symbol.for("openclaw.signalExitGates"), "close-and-restart");
activeFinalizers = resolveGlobalSet(Symbol.for("openclaw.signalExitFinalizers"), "close-and-restart");
}));
//#endregion
//#region src/logging/timestamps.ts
function isValidTimeZone(tz) {
const cached = validTimeZoneCache.get(tz);
if (cached !== void 0) return cached;
let valid;
try {
new Intl.DateTimeFormat("en", { timeZone: tz }).format();
valid = true;
} catch {
valid = false;
}
validTimeZoneCache.set(tz, valid);
return valid;
}
function resolveEffectiveTimeZone(timeZone) {
const explicit = timeZone ?? process.env.TZ;
return explicit && isValidTimeZone(explicit) ? explicit : hostTimeZone ??= Intl.DateTimeFormat().resolvedOptions().timeZone;
}
function formatOffset(offsetRaw) {
return offsetRaw === "GMT" ? "+00:00" : offsetRaw.slice(3);
}
function getTimestampParts(date, timeZone) {
const effectiveTimeZone = resolveEffectiveTimeZone(timeZone);
const second = Math.floor(date.getTime() / 1e3);
if (lastTimestampParts?.second === second && lastTimestampParts.timeZone === effectiveTimeZone) return lastTimestampParts.parts;
let fmt = timestampFormatterCache.get(effectiveTimeZone);
if (!fmt) {
fmt = new Intl.DateTimeFormat("en", {
timeZone: effectiveTimeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
fractionalSecondDigits: 3,
timeZoneName: "longOffset"
});
timestampFormatterCache.set(effectiveTimeZone, fmt);
}
const parts = {};
for (const part of fmt.formatToParts(date)) parts[part.type] = part.value;
lastTimestampParts = {
second,
timeZone: effectiveTimeZone,
parts
};
return parts;
}
function formatTimestamp(date, options) {
const style = options?.style ?? "medium";
const parts = getTimestampParts(date, options?.timeZone);
const offset = formatOffset(parts.timeZoneName ?? "GMT");
const milliseconds = String(date.getUTCMilliseconds()).padStart(3, "0");
switch (style) {
case "short": return `${parts.hour}:${parts.minute}:${parts.second}${offset}`;
case "medium": return `${parts.hour}:${parts.minute}:${parts.second}.${milliseconds}${offset}`;
case "long": return `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}.${milliseconds}${offset}`;
}
throw new Error("Unsupported timestamp style");
}
var validTimeZoneCache, timestampFormatterCache, hostTimeZone, lastTimestampParts;
var init_timestamps = __esmMin((() => {
validTimeZoneCache = /* @__PURE__ */ new Map();
timestampFormatterCache = /* @__PURE__ */ new Map();
}));
//#endregion
//#region src/logging/json-console-line.ts
function formatJsonConsoleLine(params) {
const envelope = {
...params.meta,
time: formatTimestamp(/* @__PURE__ */ new Date(), { style: "long" }),
level: params.level,
...params.subsystem ? { subsystem: params.subsystem } : {},
message: params.message
};
return JSON.stringify(redactLogRecordForTransport(envelope, { format: "console" }));
}
/** Formats diagnostics that must bypass console capture without bypassing JSON console style. */
function formatConsoleDiagnosticLine(params) {
return (loggingState.overrideSettings?.consoleStyle ?? readLoggingConfig()?.consoleStyle) === "json" ? formatJsonConsoleLine(params) : params.message;
}
var init_json_console_line = __esmMin((() => {
init_config();
init_redact();
init_state();
init_timestamps();
}));
//#endregion
//#region src/logging/levels.ts
function tryParseLogLevel(level) {
if (typeof level !== "string") return;
const candidate = level.trim();
return ALLOWED_LOG_LEVELS.includes(candidate) ? candidate : void 0;
}
function normalizeLogLevel(level, fallback = "info") {
return tryParseLogLevel(level) ?? fallback;
}
function levelToMinLevel(level) {
return MIN_LEVEL_BY_LOG_LEVEL[level];
}
function isLogLevelEnabled(level, minimum) {
return level !== "silent" && minimum !== "silent" && levelToMinLevel(level) >= levelToMinLevel(minimum);
}
var ALLOWED_LOG_LEVELS, MIN_LEVEL_BY_LOG_LEVEL;
var init_levels = __esmMin((() => {
ALLOWED_LOG_LEVELS = [
"silent",
"fatal",
"error",
"warn",
"info",
"debug",
"trace"
];
MIN_LEVEL_BY_LOG_LEVEL = {
trace: 1,
debug: 2,
info: 3,
warn: 4,
error: 5,
fatal: 6,
silent: Number.POSITIVE_INFINITY
};
}));
//#endregion
//#region src/logging/env-log-level.ts
/** Resolves OPENCLAW_LOG_LEVEL once per value, warning only when the invalid value changes. */
function resolveEnvLogLevelOverride() {
const trimmed = normalizeOptionalString(process.env.OPENCLAW_LOG_LEVEL) ?? "";
if (!trimmed) {
loggingState.invalidEnvLogLevelValue = null;
return;
}
const parsed = tryParseLogLevel(trimmed);
if (parsed) {
loggingState.invalidEnvLogLevelValue = null;
return parsed;
}
if (loggingState.invalidEnvLogLevelValue !== trimmed) {
loggingState.invalidEnvLogLevelValue = trimmed;
const message = `[openclaw] Ignoring invalid OPENCLAW_LOG_LEVEL="${trimmed}" (allowed: ${ALLOWED_LOG_LEVELS.join("|")}).`;
process.stderr.write(`${formatConsoleDiagnosticLine({
level: "warn",
message
})}\n`);
}
}
var init_env_log_level = __esmMin((() => {
init_string_coerce();
init_json_console_line();
init_levels();
init_state();
}));
//#endregion
//#region src/infra/tmp-openclaw-dir.ts
function loadResolveSecureTempRoot() {
if (resolveSecureTempRootRuntime) return resolveSecureTempRootRuntime;
const injected = getSealedRuntimeSecureTempRoot();
if (injected) {
resolveSecureTempRootRuntime = injected;
return injected;
}
if (typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) throw new Error("sealed temp-root runtime was not registered before use");
const getBuiltinModule = process.getBuiltinModule;
if (typeof getBuiltinModule !== "function") throw new Error("Node module loading is unavailable for secure temp-root resolution");
const moduleNamespace = getBuiltinModule("module");
if (typeof moduleNamespace.createRequire !== "function") throw new Error("Node createRequire is unavailable for secure temp-root resolution");
resolveSecureTempRootRuntime = moduleNamespace.createRequire(import.meta.url)("@openclaw/fs-safe/temp").resolveSecureTempRoot;
return resolveSecureTempRootRuntime;
}
/** Resolves a safe OpenClaw temp root, falling back to user-scoped os.tmpdir paths when needed. */
function resolvePreferredOpenClawTmpDir(options = {}) {
return loadResolveSecureTempRoot()({
...options,
preferredDir: options.preferredDir ?? "/tmp/openclaw",
fallbackPrefix: "openclaw",
warningPrefix: "[openclaw]",
unsafeFallbackLabel: "OpenClaw temp dir",
skipPreferredOnWindows: true
});
}
var DEFAULT_POSIX_TMP_ROOT, resolveSecureTempRootRuntime;
var init_tmp_openclaw_dir = __esmMin((() => {
init_sealed_runtime_registry();
DEFAULT_POSIX_TMP_ROOT = "/tmp/openclaw";
}));
//#endregion
//#region src/logging/log-file-shared.ts
function canUseNodeFs() {
const getBuiltinModule = process.getBuiltinModule;
if (typeof getBuiltinModule !== "function") return false;
try {
return getBuiltinModule("fs") !== void 0;
} catch {
return false;
}
}
function formatLocalDate(date) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
}
var LOG_PREFIX, LOG_SUFFIX;
var init_log_file_shared = __esmMin((() => {
LOG_PREFIX = "openclaw";
LOG_SUFFIX = ".log";
}));
//#endregion
//#region src/logging/log-file-path.ts
function encodeLogProfileSegment(profile) {
let encoded = "";
for (const char of profile) if (/^[a-z0-9]$/u.test(char)) encoded += char;
else if (char === "-") encoded += "--";
else if (char === "_") encoded += "-0";
else if (/^[A-Z]$/u.test(char)) encoded += `-1${char.toLowerCase()}`;
else encoded += `-2${char.codePointAt(0)?.toString(16) ?? "0"}-`;
return encoded;
}
function resolveLogProfileSegment(env) {
const profile = env.OPENCLAW_PROFILE?.trim();
if (!profile || profile.toLowerCase() === "default") return null;
const encoded = encodeLogProfileSegment(profile);
if (encoded.length <= MAX_LOG_PROFILE_SEGMENT_LENGTH) return encoded;
return `-3${createHash("sha256").update(profile).digest("hex")}`;
}
/** Resolves today's default rolling log path for the active CLI profile. */
function resolveDefaultRollingLogFile(options) {
const date = options?.date ?? /* @__PURE__ */ new Date();
const env = options?.env ?? process.env;
const logDir = options?.logDir ?? (canUseNodeFs() ? resolvePreferredOpenClawTmpDir() : "/tmp/openclaw");
const profileSegment = resolveLogProfileSegment(env);
const profileSuffix = profileSegment ? `-${profileSegment}` : "";
return path.join(logDir, `${LOG_PREFIX}${profileSuffix}-${formatLocalDate(date)}${LOG_SUFFIX}`);
}
/** Returns whether a configured path had the legacy default rolling filename shape. */
function isLegacyRollingLogFilePath(file) {
const base = path.basename(file);
return base === `openclaw-YYYY-MM-DD.log` || ROLLING_LOG_FILE_RE.exec(base)?.[1] === "openclaw";
}
/** Advances a rolling log path to the requested date while preserving its profile family. */
function resolveRollingLogFilePathForDate(file, date) {
const match = ROLLING_LOG_FILE_RE.exec(path.basename(file));
if (!match) return isLegacyRollingLogFilePath(file) ? path.join(path.dirname(file), `${LOG_PREFIX}-${formatLocalDate(date)}${LOG_SUFFIX}`) : file;
return path.join(path.dirname(file), `${match[1]}-${formatLocalDate(date)}${LOG_SUFFIX}`);
}
var ROLLING_LOG_FILE_RE, MAX_LOG_PROFILE_SEGMENT_LENGTH;
var init_log_file_path = __esmMin((() => {
init_tmp_openclaw_dir();
init_log_file_shared();
ROLLING_LOG_FILE_RE = /^(openclaw(?:-[a-z0-9-]+)?)-(\d{4}-\d{2}-\d{2})\.log$/u;
MAX_LOG_PROFILE_SEGMENT_LENGTH = 220;
}));
//#endregion
//#region src/logging/logger-file-message.ts
function clampMessage(text) {
return text.length > MAX_FILE_LOG_MESSAGE_CHARS ? `${truncateUtf16Safe(text, MAX_FILE_LOG_MESSAGE_CHARS)}...(truncated)` : text;
}
function stringifyFileLogMessagePart(value, json) {
if (json) return JSON.stringify(value);
if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return String(value);
if (isRecord(value) && typeof value.message === "string") return value.message;
}
function buildFileLogMessage(record, parts) {
const text = [];
const spans = [];
let length = 0;
for (const { key, json, primitiveText } of parts) {
const value = record[key];
const part = primitiveText ?? stringifyFileLogMessagePart(value, json);
if (!part?.trim()) continue;
if (text.length > 0) length += 1;
spans.push({
key,
json,
messageField: !json && isRecord(value),
start: length,
...primitiveText === void 0 ? {} : { primitiveLength: primitiveText.length }
});
text.push(part);
length += part.length;
}
if (text.length === 0) return;
const joined = text.join(" ");
const prefix = truncateUtf16Safe(joined, MAX_FILE_LOG_MESSAGE_CHARS);
const textValue = clampMessage(joined);
return {
text: textValue,
contentLength: prefix.length,
finish: (value) => value === textValue ? value : clampMessage(value),
parts: spans
};
}
var MAX_FILE_LOG_MESSAGE_CHARS;
var init_logger_file_message = __esmMin((() => {
init_record_coerce();
init_utf16_slice();
MAX_FILE_LOG_MESSAGE_CHARS = 4096;
}));
//#endregion
//#region src/logging/logger-file-transport.ts
function rotatedLogPath(file, index) {
const ext = path.extname(file);
return `${file.slice(0, file.length - ext.length)}.${index}${ext}`;
}
function rotateLogFile(file) {
try {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.rmSync(rotatedLogPath(file, MAX_ROTATED_LOG_FILES), { force: true });
for (let index = 4; index >= 1; index -= 1) {
const from = rotatedLogPath(file, index);
if (fs.existsSync(from)) fs.renameSync(from, rotatedLogPath(file, index + 1));
}
if (fs.existsSync(file)) fs.renameSync(file, rotatedLogPath(file, 1));
return true;
} catch {
return false;
}
}
async function getCurrentLogFileBytes(file) {
try {
return (await fsPromises.stat(file)).size;
} catch {
return 0;
}
}
function getCurrentLogFileBytesSync(file) {
try {
return fs.statSync(file).size;
} catch {
return 0;
}
}
function buildDroppedMarker(target, count) {
const date = /* @__PURE__ */ new Date();
const message = `[openclaw] file log queue overflow; dropped ${count} oldest record${count === 1 ? "" : "s"}`;
const record = {
0: message,
_meta: {
date,
hostname: target.hostname,
logLevelName: "WARN",
name: "openclaw"
},
time: formatTimestamp(date, { style: "long" }),
hostname: target.hostname,
message,
dropped: count
};
return {
...target,
payload: `${serializeRedactedFileLogRecord(record)}\n`
};
}
function writeFileTransportWarning(message, synchronous) {
try {
const line = `${formatConsoleDiagnosticLine({
level: "warn",
message: redactSensitiveText(message)
})}\n`;
if (synchronous) fs.writeSync(process.stderr.fd, line);
else process.stderr.write(line);
return true;
} catch {
return false;
}
}
function warnAboutRotationFailure(entry, synchronous) {
if (warnedRotationFiles.get(entry.file) === entry.maxFileBytes) return;
warnedRotationFiles.set(entry.file, entry.maxFileBytes);
writeFileTransportWarning(`[openclaw] log file rotation failed; continuing writes file=${entry.file} maxFileBytes=${entry.maxFileBytes}`, synchronous);
}
function warnAboutAppendFailure(entry, synchronous) {
if (warnedAppendFiles.has(entry.file)) return;
const saturated = warnedAppendFiles.size >= MAX_TRACKED_APPEND_FAILURE_FILES;
if (saturated && appendFailureTrackingSaturated) return;
if (!writeFileTransportWarning(saturated ? "[openclaw] log file append failure diagnostics saturated; suppressing new file targets" : `[openclaw] log file append failed; records dropped; check that the path is a writable regular file; file=${entry.file}`, synchronous)) return;
if (saturated) appendFailureTrackingSaturated = true;
else warnedAppendFiles.add(entry.file);
}
function clearAppendFailure(entry) {
if (warnedAppendFiles.delete(entry.file)) appendFailureTrackingSaturated = false;
}
function claimQueuedEntries() {
const entries = queueStart === 0 ? queue : [...queue.slice(queueStart), ...queue.slice(0, queueStart)];
queue = [];
queueStart = 0;
if (droppedCount > 0 && droppedTarget) entries.unshift(buildDroppedMarker(droppedTarget, droppedCount));
droppedCount = 0;
droppedTarget = null;
return entries;
}
function prepareWrite(entry, cursor, synchronous, entries, index) {
let payloadBytes = Buffer.byteLength(entry.payload, "utf8");
if (cursor.bytes > 0 && cursor.bytes + payloadBytes > entry.maxFileBytes) {
if (rotateLogFile(entry.file)) {
cursor.bytes = 0;
warnedRotationFiles.delete(entry.file);
} else warnAboutRotationFailure(entry, synchronous);
}
let nextIndex = index + 1;
if (synchronous) return {
payload: entry.payload,
payloadBytes,
nextIndex
};
const payloads = [entry.payload];
for (; nextIndex < entries.length; nextIndex += 1) {
const next = entries[nextIndex];
if (!next || next.file !== entry.file || next.maxFileBytes !== entry.maxFileBytes) break;
const nextBytes = Buffer.byteLength(next.payload, "utf8");
if (payloadBytes + nextBytes > MAX_APPEND_BATCH_BYTES || cursor.bytes + payloadBytes + nextBytes > entry.maxFileBytes) break;
payloads.push(next.payload);
payloadBytes += nextBytes;
}
return {
payload: payloads.join(""),
payloadBytes,
nextIndex
};
}
async function writeEntries(entries, generation) {
const cursors = /* @__PURE__ */ new Map();
for (let index = 0; index < entries.length;) {
if (generation !== drainGeneration || processExiting) return;
const entry = entries[index];
if (!entry) return;
let cursor = cursors.get(entry.file);
if (!cursor) {
cursor = { bytes: await getCurrentLogFileBytes(entry.file) };
if (generation !== drainGeneration || processExiting) return;
cursors.set(entry.file, cursor);
}
const batch = prepareWrite(entry, cursor, false, entries, index);
activeIndex = batch.nextIndex;
try {
await appendFile({
filePath: entry.file,
content: batch.payload
});
cursor.bytes += batch.payloadBytes;
clearAppendFailure(entry);
} catch {
warnAboutAppendFailure(entry, false);
} finally {
for (const written of entries.slice(index, batch.nextIndex)) written.payload = "";
index = batch.nextIndex;
}
}
}
function writeEntriesSync(entries) {
const cursors = /* @__PURE__ */ new Map();
for (let index = 0; index < entries.length;) {
const entry = entries[index];
if (!entry) return;
let cursor = cursors.get(entry.file);
if (!cursor) {
cursor = { bytes: getCurrentLogFileBytesSync(entry.file) };
cursors.set(entry.file, cursor);
}
const batch = prepareWrite(entry, cursor, true, entries, index);
try {
appendRegularFileSync({
filePath: entry.file,
content: batch.payload
});
cursor.bytes += batch.payloadBytes;
clearAppendFailure(entry);
} catch {
warnAboutAppendFailure(entry, true);
}
entry.payload = "";
index = batch.nextIndex;
}
}
async function runFlushLoop() {
const generation = drainGeneration;
for (;;) {
if (generation !== drainGeneration || processExiting) return;
const entries = claimQueuedEntries();
if (entries.length === 0) return;
activeBatch = entries;
activeIndex = 0;
await writeEntries(entries, generation);
if (generation !== drainGeneration) return;
activeBatch = null;
activeIndex = 0;
}
}
function startFlush() {
if (flushPromise || processExiting) return;
const running = runFlushLoop().catch(() => void 0);
flushPromise = running;
running.then(() => {
if (flushPromise === running) flushPromise = null;
if (queue.length > 0 || droppedCount > 0) scheduleFlush();
});
}
function scheduleFlush() {
if (scheduledFlush || flushPromise || processExiting) return;
scheduledFlush = setImmediate(() => {
scheduledFlush = null;
startFlush();
});
}
function handleProcessBeforeExit() {
flushFileLogQueue();
}
function handleProcessExit() {
processExiting = true;
drainFileLogQueueSync();
}
function installProcessHooks() {
if (processHooksInstalled) return;
processHooksInstalled = true;
process.on("beforeExit", handleProcessBeforeExit);
process.on("exit", handleProcessExit);
}
function removeProcessHooks() {
if (!processHooksInstalled) return;
process.removeListener("beforeExit", handleProcessBeforeExit);
process.removeListener("exit", handleProcessExit);
processHooksInstalled = false;
}
/** Enqueues one serialized record without waiting for filesystem I/O. */
function enqueueFileLog(entry) {
if (processExiting) {
writeEntriesSync([entry]);
return;
}
installProcessHooks();
if (queue.length >= maxQueuedRecords) {
const dropped = queue[queueStart];
if (dropped) {
dropped.payload = "";
droppedTarget ??= dropped;
droppedCount += 1;
}
queue[queueStart] = entry;
queueStart = (queueStart + 1) % queue.length;
} else queue.push(entry);
scheduleFlush();
}
/** Waits until every record currently queued for the async transport has settled. */
async function flushFileLogQueue() {
for (;;) {
if (scheduledFlush) {
clearImmediate(scheduledFlush);
scheduledFlush = null;
}
if (!flushPromise && (queue.length > 0 || droppedCount > 0)) startFlush();
const running = flushPromise;
if (!running) return;
await running;
}
}
/** Synchronously rescues pending records for process.exit() and crash-adjacent paths. */
function drainFileLogQueueSync() {
if (scheduledFlush) {
clearImmediate(scheduledFlush);
scheduledFlush = null;
}
drainGeneration += 1;
const entries = activeBatch ? activeBatch.slice(activeIndex) : [];
activeBatch = null;
activeIndex = 0;
entries.push(...claimQueuedEntries());
writeEntriesSync(entries);
}
function setFileLogQueueMaxRecordsForTests(value) {
maxQueuedRecords = Math.max(1, value ?? DEFAULT_MAX_QUEUED_RECORDS);
}
function setFileLogAppenderForTests(value) {
appendFile = value ?? appendRegularFile;
}
function resetFileLogTransportForTests() {
drainFileLogQueueSync();
removeProcessHooks();
processExiting = false;
appendFile = appendRegularFile;
maxQueuedRecords = DEFAULT_MAX_QUEUED_RECORDS;
warnedRotationFiles.clear();
warnedAppendFiles.clear();
appendFailureTrackingSaturated = false;
}
var DEFAULT_MAX_QUEUED_RECORDS, MAX_APPEND_BATCH_BYTES, MAX_ROTATED_LOG_FILES, MAX_TRACKED_APPEND_FAILURE_FILES, queue, queueStart, activeBatch, activeIndex, droppedCount, droppedTarget, maxQueuedRecords, scheduledFlush, flushPromise, drainGeneration, processExiting, processHooksInstalled, appendFile, warnedRotationFiles, warnedAppendFiles, appendFailureTrackingSaturated, fileLogTransport;
var init_logger_file_transport = __esmMin((() => {
init_json_console_line();
init_redact();
init_timestamps();
DEFAULT_MAX_QUEUED_RECORDS = 4096;
MAX_APPEND_BATCH_BYTES = 65536;
MAX_ROTATED_LOG_FILES = 5;
MAX_TRACKED_APPEND_FAILURE_FILES = 64;
queue = [];
queueStart = 0;
activeBatch = null;
activeIndex = 0;
droppedCount = 0;
droppedTarget = null;
maxQueuedRecords = DEFAULT_MAX_QUEUED_RECORDS;
scheduledFlush = null;
flushPromise = null;
drainGeneration = 0;
processExiting = false;
processHooksInstalled = false;
appendFile = appendRegularFile;
warnedRotationFiles = /* @__PURE__ */ new Map();
warnedAppendFiles = /* @__PURE__ */ new Set();
appendFailureTrackingSaturated = false;
if (process.env.VITEST !== "true") installProcessHooks();
fileLogTransport = {
drainSync: drainFileLogQueueSync,
enqueue: enqueueFileLog,
flush: flushFileLogQueue,
resetForTests: resetFileLogTransportForTests,
setAppenderForTests: setFileLogAppenderForTests,
setMaxQueuedRecordsForTests: setFileLogQueueMaxRecordsForTests
};
}));
//#endregion
//#region src/logging/logger-hostname-state.ts
var defaultLoggerHostnameResolver, loggerHostnameState;
var init_logger_hostname_state = __esmMin((() => {
defaultLoggerHostnameResolver = () => os.hostname();
loggerHostnameState = {
cached: null,
resolver: defaultLoggerHostnameResolver
};
}));
//#endregion
//#region src/logging/logger-settings-internal.ts
function setLoggerFileTargetResolver(resolver) {
resolveLoggerFileTarget = resolver;
}
var resolveLoggerFileTarget;
var init_logger_settings_internal = __esmMin((() => {}));
//#endregion
//#region src/logging/logger.ts
function clampLogText(value, maxChars) {
return value.length > maxChars ? `${truncateUtf16Safe(value, maxChars)}...(truncated)` : value;
}
function sanitizeDiagnosticLogText(value, maxChars) {
return clampLogText(redactSensitiveText(clampLogText(value, maxChars)), maxChars);
}
function normalizeDiagnosticLogName(value) {
if (!value || value.trim().startsWith("{")) return;
const sanitized = sanitizeDiagnosticLogText(value.trim(), MAX_DIAGNOSTIC_LOG_NAME_CHARS);
return DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE.test(sanitized) ? sanitized : void 0;
}
function assignDiagnosticLogAttribute(attributes, state, key, value) {
if (state.count >= MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT) return;
const normalizedKey = key.trim();
if (isBlockedObjectKey(normalizedKey)) return;
if (redactSensitiveText(normalizedKey) !== normalizedKey) return;
if (!DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE.test(normalizedKey)) return;
if (typeof value === "string") {
attributes[normalizedKey] = sanitizeDiagnosticLogText(value, MAX_DIAGNOSTIC_LOG_ATTRIBUTE_VALUE_CHARS);
state.count += 1;
return;
}
if (typeof value === "number" && Number.isFinite(value)) {
attributes[normalizedKey] = value;
state.count += 1;
return;
}
if (typeof value === "boolean") {
attributes[normalizedKey] = value;
state.count += 1;
}
}
function addDiagnosticLogAttributesFrom(attributes, state, source) {
if (!source) return;
for (const key in source) {
if (state.count >= MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT) break;
if (!Object.hasOwn(source, key) || key === "trace") continue;
assignDiagnosticLogAttribute(attributes, state, key, source[key]);
}
}
function isPlainLogRecordObject(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
const prototype = Object.getPrototypeOf(value);
return prototype === Object.prototype || prototype === null;
}
function normalizeTraceContext(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return;
const candidate = value;
if (!isValidDiagnosticTraceId(candidate.traceId)) return;
if (candidate.spanId !== void 0 && !isValidDiagnosticSpanId(candidate.spanId)) return;
if (candidate.parentSpanId !== void 0 && !isValidDiagnosticSpanId(candidate.parentSpanId)) return;
if (candidate.traceFlags !== void 0 && !isValidDiagnosticTraceFlags(candidate.traceFlags)) return;
return {
traceId: candidate.traceId,
...candidate.spanId ? { spanId: candidate.spanId } : {},
...candidate.parentSpanId ? { parentSpanId: candidate.parentSpanId } : {},
...candidate.traceFlags ? { traceFlags: candidate.traceFlags } : {}
};
}
function extractTraceContext(value) {
const direct = normalizeTraceContext(value);
if (direct) return direct;
if (!value || typeof value !== "object" || Array.isArray(value)) return;
return normalizeTraceContext(value.trace);
}
function getSortedNumericLogEntries(logObj) {
return Object.entries(logObj).filter(([key]) => /^\d+$/.test(key)).toSorted((a, b) => Number(a[0]) - Number(b[0]));
}
function normalizeFileLogContextValue(value) {
if (typeof value === "string") {
const normalized = value.trim();
return normalized ? clampLogText(normalized, MAX_FILE_LOG_CONTEXT_VALUE_CHARS) : void 0;
}
if (typeof value === "number" && Number.isFinite(value)) return String(value);
if (typeof value === "boolean") return String(value);
}
function readFirstContextString(sources, keys) {
for (const source of sources) {
if (!source) continue;
for (const key of keys) {
const value = normalizeFileLogContextValue(source[key]);
if (value) return value;
}
}
}
function resolveLogHostname() {
if (loggerHostnameState.cached) return loggerHostnameState.cached;
const hostname = loggerHostnameState.resolver().trim();
if (!hostname) return "unknown";
loggerHostnameState.cached = hostname;
return hostname;
}
function withResolvedLogMetaHostname(meta, hostname) {
if (!meta || typeof meta !== "object" || Array.isArray(meta)) return meta;
return {
...meta,
hostname
};
}
function extractLogBindingPrefix(numericArgs) {
if (typeof numericArgs[0] === "string" && numericArgs[0].length <= MAX_DIAGNOSTIC_LOG_BINDINGS_JSON_CHARS && numericArgs[0].trim().startsWith("{")) try {
const parsed = JSON.parse(numericArgs[0]);
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return {
bindings: parsed,
args: numericArgs.slice(1)
};
} catch {}
return { args: numericArgs };
}
function findLogTraceContext(bindings, numericArgs) {
const fromBindings = extractTraceContext(bindings);
if (fromBindings) return fromBindings;
for (const arg of numericArgs) {
const fromArg = extractTraceContext(arg);
if (fromArg) return fromArg;
}
}
function resolveLogTraceContext(bindings, numericArgs) {
const explicitTrace = findLogTraceContext(bindings, numericArgs);
if (explicitTrace) return {
trace: explicitTrace,
trustedTraceContext: false
};
const activeTrace = getActiveDiagnosticTraceContext();
return activeTrace ? {
trace: activeTrace,
trustedTraceContext: true
} : { trustedTraceContext: false };
}
function prepareFileLogRecord(logObj) {
const entries = getSortedNumericLogEntries(logObj);
const { bindings, args } = extractLogBindingPrefix(entries.map(([, value]) => value));
const { trace } = resolveLogTraceContext(bindings, args);
const structuredArg = isPlainLogRecordObject(args[0]) ? args[0] : void 0;
const sources = [
structuredArg,
bindings,
logObj
];
const metadataCount = structuredArg && typeof structuredArg.message !== "string" ? 1 : 0;
const messageParts = entries.slice(entries.length - args.length + metadataCount).map(([key, value]) => {
const part = {
key,
json: value != null && ![
"string",
"number",
"boolean",
"bigint"
].includes(typeof value) && !(value instanceof Error) && !(isPlainLogRecordObject(value) && typeof value.message === "string")
};
if (typeof value === "number" && !Number.isFinite(value)) part.primitiveText = String(value);
return part;
});
const agentId = readFirstContextString(sources, ["agent_id", "agentId"]);
const sessionId = readFirstContextString(sources, [
"session_id",
"sessionId",
"sessionKey"
]);
const channel = readFirstContextString(sources, ["channel", "messageProvider"]);
return {
fields: {
hostname: resolveLogHostname(),
...agentId ? { agent_id: agentId } : {},
...sessionId ? { session_id: sessionId } : {},
...channel ? { channel } : {},
...trace
},
messageParts
};
}
function buildDiagnosticLogRecord(logObj) {
const meta = logObj["_meta"];
const { bindings, args: numericArgs } = extractLogBindingPrefix(getSortedNumericLogEntries(logObj).map(([, value]) => value));
const { trace, trustedTraceContext } = resolveLogTraceContext(bindings, numericArgs);
const structuredArg = numericArgs[0];
const structuredBindings = isPlainLogRecordObject(structuredArg) ? structuredArg : void 0;
if (structuredBindings) numericArgs.shift();
let message = "";
if (numericArgs.length > 0 && typeof numericArgs[numericArgs.length - 1] === "string") message = sanitizeDiagnosticLogText(String(numericArgs.pop()), MAX_DIAGNOSTIC_LOG_MESSAGE_CHARS);
else if (numericArgs.length === 1 && (typeof numericArgs[0] === "number" || typeof numericArgs[0] === "boolean")) {
message = String(numericArgs[0]);
numericArgs.length = 0;
}
if (!message) message = "log";
const attributes = Object.create(null);
const attributeState = { count: 0 };
addDiagnosticLogAttributesFrom(attributes, attributeState, bindings);
addDiagnosticLogAttributesFrom(attributes, attributeState, structuredBindings);
const code = {};
if (meta?.path?.fileLine) {
const line = Number(meta.path.fileLine);
if (Number.isFinite(line)) code.line = line;
}
if (meta?.path?.method) code.functionName = sanitizeDiagnosticLogText(meta.path.method, MAX_DIAGNOSTIC_LOG_NAME_CHARS);
const loggerName = normalizeDiagnosticLogName(meta?.name);
const loggerParents = meta?.parentNames?.map(normalizeDiagnosticLogName).filter((name) => Boolean(name));
return {
event: {
type: "log.record",
level: meta?.logLevelName ?? "INFO",
message,
...loggerName ? { loggerName } : {},
...loggerParents?.length ? { loggerParents } : {},
...Object.keys(attributes).length > 0 ? { attributes } : {},
...Object.keys(code).length > 0 ? { code } : {},
...trace ? { trace } : {}
},
trustedTraceContext
};
}
function attachDiagnosticEventTransport(logger) {
logger.attachTransport({
format: () => "",
write: (logObj) => {
if (!areDiagnosticsEnabledForProcess() || !hasInternalDiagnosticEventInterest("log.record")) return;
try {
const record = buildDiagnosticLogRecord(redactSecrets(logObj));
(record.trustedTraceContext ? emitDiagnosticEventWithTrustedTraceContext : emitDiagnosticEvent)(record.event);
} catch {}
}
});
}
function canUseSilentVitestFileLogFastPath(envLevel) {
return process.env.VITEST === "true" && process.env.OPENCLAW_TEST_FILE_LOG !== "1" && !envLevel && !loggingState.overrideSettings;
}
function resolveDefaultActiveLogFile() {
if (process.env.VITEST === "true" && process.env.OPENCLAW_TEST_FILE_LOG === "1") return path.join(process.cwd(), ".artifacts", "test-logs", `${LOG_PREFIX}-vitest-${process.pid}-${formatLocalDate(/* @__PURE__ */ new Date())}${LOG_SUFFIX}`);
return resolveDefaultRollingLogFile();
}
function resolveSettings() {
if (!canUseNodeFs()) return {
level: "silent",
file: DEFAULT_LOG_FILE,
maxFileBytes: DEFAULT_MAX_LOG_FILE_BYTES,
rolling: false
};
const envLevel = resolveEnvLogLevelOverride();
if (canUseSilentVitestFileLogFastPath(envLevel)) return {
level: "silent",
file: resolveDefaultRollingLogFile(),
maxFileBytes: DEFAULT_MAX_LOG_FILE_BYTES,
rolling: true
};
const cfg = loggingState.overrideSettings ?? readLoggingConfig();
const defaultLevel = process.env.VITEST === "true" && process.env.OPENCLAW_TEST_FILE_LOG !== "1" ? "silent" : "info";
const fromConfig = normalizeLogLevel(cfg?.level, defaultLevel);
const level = envLevel ?? fromConfig;
const rolling = cfg?.file ? isLegacyRollingLogFilePath(cfg.file) : true;
return {
level,
file: resolveActiveLogFileWithMode(cfg?.file ?? resolveDefaultActiveLogFile(), rolling),
maxFileBytes: resolveMaxLogFileBytes(cfg?.maxFileBytes),
rolling
};
}
function getRuntimeSettings() {
const settings = loggingState.cachedSettings ?? resolveSettings();
loggingState.cachedSettings = settings;
return settings;
}
function isFileLogLevelEnabled(level) {
return isLogLevelEnabled(level, getRuntimeSettings().level);
}
function inheritLogLevel(logger, getLevel) {
let resolveLevel = getLevel;
Object.defineProperty(logger.settings, "minLevel", {
configurable: true,
enumerable: true,
get: () => resolveLevel(),
set: (level) => {
resolveLevel = () => level;
}
});
}
function buildLogger() {
const logger = new RuntimeLogger({
name: "openclaw",
mask: { keys: [] },
meta: { property: "_meta" },
minLevel: levelToMinLevel("fatal"),
type: "hidden"
});
inheritLogLevel(logger, () => levelToMinLevel(getRuntimeSettings().level));
let activeFile;
logger.attachTransport({
format: () => "",
write: (logObj) => {
try {
const settings = getRuntimeSettings();
if (settings.level === "silent") return;
const nextActiveFile = resolveActiveLogFileWithMode(settings.file, settings.rolling);
if (nextActiveFile !== activeFile) {
activeFile = nextActiveFile;
fs.mkdirSync(path.dirname(activeFile), { recursive: true });
if (settings.rolling) pruneOldRollingLogs(path.dirname(activeFile));
}
const time = formatTimestamp(logObj.date ?? /* @__PURE__ */ new Date(), { style: "long" });
const { fields, messageParts } = prepareFileLogRecord(logObj);
const line = serializeRedactedFileLogRecord({
...logObj,
_meta: withResolvedLogMetaHostname(logObj["_meta"], expectDefined(fields.hostname, "structured log hostname")),
time,
...fields
}, {
deriveMessage: (materialized) => buildFileLogMessage(materialized, messageParts),
decodedOptions: resolveFileLogRedactOptions()
});
fileLogTransport.enqueue({
file: activeFile,
hostname: expectDefined(fields.hostname, "structured log hostname"),
maxFileBytes: settings.maxFileBytes,
payload: `${line}\n`
});
} catch {}
}
});
attachDiagnosticEventTransport(logger);
return logger;
}
function resolveMaxLogFileBytes(raw) {
if (typeof raw === "number" && Number.isFinite(raw) && raw > 0) return Math.floor(raw);
return DEFAULT_MAX_LOG_FILE_BYTES;
}
function getLogger() {
const cachedLogger = loggingState.cachedLogger;
if (cachedLogger) return cachedLogger;
getRuntimeSettings();
const logger = buildLogger();
loggingState.cachedLogger = logger;
return logger;
}
function getChildLogger(bindings, opts) {
const base = getLogger();
const name = bindings ? JSON.stringify(bindings) : void 0;
return base.getSubLogger({
name,
prefix: bindings ? [name ?? ""] : [],
...opts?.level ? { minLevel: levelToMinLevel(opts.level) } : {}
});
}
function resolveActiveLogFileWithMode(file, rolling) {
const expandedFile = expandHomePrefix(file);
return rolling ? resolveRollingLogFilePathForDate(expandedFile, /* @__PURE__ */ new Date()) : expandedFile;
}
function pruneOldRollingLogs(dir) {
try {
const entries = fs.readdirSync(dir, { withFileTypes: true });
const cutoff = Date.now() - MAX_LOG_AGE_MS;
for (const entry of entries) {
if (!entry.isFile()) continue;
if (!entry.name.startsWith(`openclaw-`) || !entry.name.endsWith(".log")) continue;
const fullPath = path.join(dir, entry.name);
try {
if (fs.statSync(fullPath).mtimeMs < cutoff) fs.rmSync(fullPath, { force: true });
} catch {}
}
} catch {}
}
var DEFAULT_LOG_FILE, MAX_LOG_AGE_MS, DEFAULT_MAX_LOG_FILE_BYTES, MAX_DIAGNOSTIC_LOG_BINDINGS_JSON_CHARS, MAX_DIAGNOSTIC_LOG_MESSAGE_CHARS, MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT, MAX_DIAGNOSTIC_LOG_ATTRIBUTE_VALUE_CHARS, MAX_DIAGNOSTIC_LOG_NAME_CHARS, MAX_FILE_LOG_CONTEXT_VALUE_CHARS, DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE, RuntimeLogger;
var init_logger = __esmMin((() => {
init_src$2();
init_utf16_slice();
init_diagnostic_event_listener_presence();
init_diagnostic_events();
init_diagnostic_trace_context();
init_home_dir();
init_prototype_keys();
init_tmp_openclaw_dir();
init_config();
init_env_log_level();
init_levels();
init_log_file_path();
init_log_file_shared();
init_logger_file_message();
init_logger_file_transport();
init_logger_hostname_state();
init_logger_settings_internal();
init_redact();
init_state();
init_timestamps();
DEFAULT_LOG_FILE = `${DEFAULT_POSIX_TMP_ROOT}/openclaw.log`;
MAX_LOG_AGE_MS = 864e5;
DEFAULT_MAX_LOG_FILE_BYTES = 104857600;
MAX_DIAGNOSTIC_LOG_BINDINGS_JSON_CHARS = 8192;
MAX_DIAGNOSTIC_LOG_MESSAGE_CHARS = 4096;
MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT = 32;
MAX_DIAGNOSTIC_LOG_ATTRIBUTE_VALUE_CHARS = 2048;
MAX_DIAGNOSTIC_LOG_NAME_CHARS = 120;
MAX_FILE_LOG_CONTEXT_VALUE_CHARS = 512;
DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE = /^[A-Za-z0-9_.:-]{1,64}$/u;
setLoggerFileTargetResolver(() => {
const { file, rolling } = resolveSettings();
return {
file,
rolling
};
});
RuntimeLogger = class extends Logger {
getSubLogger(settings, logObj) {
const minLevel = settings?.minLevel ?? this.settings.minLevel;
const child = super.getSubLogger({
...settings,
minLevel: minLevel === Infinity ? levelToMinLevel("fatal") : minLevel
}, logObj);
if (settings?.minLevel == null) inheritLogLevel(child, () => this.settings.minLevel);
else if (minLevel === Infinity) child.settings.minLevel = minLevel;
return child;
}
};
}));
//#endregion
//#region src/logging/console.ts
function normalizeConsoleLevel(level) {
if (isVerbose()) return "debug";
if (!level && process.env.VITEST === "true" && process.env.OPENCLAW_TEST_CONSOLE !== "1") return "silent";
return normalizeLogLevel(level, "info");
}
function normalizeConsoleStyle(style) {
if (style === "compact" || style === "json" || style === "pretty") return style;
if (!process.stdout.isTTY) return "compact";
return "pretty";
}
function resolveConsoleSettings() {
const envLevel = resolveEnvLogLevelOverride();
if (process.env.VITEST === "true" && process.env.OPENCLAW_TEST_CONSOLE !== "1" && !isVerbose() && !envLevel && !loggingState.overrideSettings) return {
level: "silent",
style: normalizeConsoleStyle(void 0)
};
const cfg = loggingState.overrideSettings ?? readLoggingConfig();
return {
level: envLevel ?? normalizeConsoleLevel(cfg?.consoleLevel),
style: normalizeConsoleStyle(cfg?.consoleStyle)
};
}
function getConsoleSettings() {
const cached = loggingState.cachedConsoleSettings;
if (cached) return cached;
const settings = resolveConsoleSettings();
loggingState.cachedConsoleSettings = settings;
return loggingState.cachedConsoleSettings;
}
function normalizeConsoleSubsystem(subsystem) {
if (typeof subsystem !== "string") return null;
const normalized = subsystem.trim();
return normalized.length > 0 ? normalized : null;
}
function shouldLogSubsystemToConsole(subsystem) {
const filter = loggingState.consoleSubsystemFilter;
if (!filter || filter.length === 0) return true;
const normalizedSubsystem = normalizeConsoleSubsystem(subsystem);
if (!normalizedSubsystem) return false;
return filter.some((prefix) => normalizedSubsystem === prefix || normalizedSubsystem.startsWith(`${prefix}/`));
}
function formatConsoleTimestamp(style) {
const now = /* @__PURE__ */ new Date();
if (style === "pretty") return formatTimestamp(now, { style: "short" }).replace(/[+-]\d{2}:\d{2}$/, "");
return formatTimestamp(now, { style: "long" });
}
var init_console = __esmMin((() => {
init_ansi();
init_signal_exit_barrier();
init_global_state();
init_config();
init_env_log_level();
init_json_console_line();
init_levels();
init_logger();
init_redact();
init_state();
init_timestamps();
`${process.release.name}${process.pid}`;
}));
//#endregion
//#region src/logging/subsystem.ts
var subsystem_exports = /* @__PURE__ */ __exportAll({
createSubsystemLogger: () => createSubsystemLogger,
runtimeForLogger: () => runtimeForLogger,
stripRedundantSubsystemPrefixForConsole: () => stripRedundantSubsystemPrefixForConsole
});
function normalizeSubsystemLabel(subsystem) {
if (typeof subsystem !== "string") return "unknown";
const normalized = subsystem.trim();
return normalized.length > 0 ? normalized : "unknown";
}
function formatRuntimeArg(arg) {
if (typeof arg === "string") return arg;
if (inspectValue) return inspectValue(arg);
try {
return JSON.stringify(arg);
} catch {
return String(arg);
}
}
function isRichConsoleEnv() {
const term = normalizeLowercaseStringOrEmpty(process.env.TERM);
if (process.env.COLORTERM || process.env.TERM_PROGRAM) return true;
return term.length > 0 && term !== "dumb";
}
function getColorForConsole() {
const level = typeof process.env.FORCE_COLOR === "string" && process.env.FORCE_COLOR.trim().length > 0 && process.env.FORCE_COLOR.trim() !== "0" || !process.env.NO_COLOR && (process.stdout.isTTY || process.stderr.isTTY || isRichConsoleEnv()) ? 1 : 0;
return consoleColors[level] ??= new Chalk({ level });
}
function isChannelSubsystemPrefix(value) {
const normalized = normalizeLowercaseStringOrEmpty(value);
if (!normalized) return false;
return CHANNEL_SUBSYSTEM_PREFIXES.has(normalized);
}
function pickSubsystemColor(subsystem) {
const override = SUBSYSTEM_COLOR_OVERRIDES.get(subsystem);
if (override) return override;
let hash = 0;
for (let i = 0; i < subsystem.length; i += 1) hash = hash * 31 + subsystem.charCodeAt(i) | 0;
const idx = Math.abs(hash) % SUBSYSTEM_COLORS.length;
return expectDefined(SUBSYSTEM_COLORS[idx], "subsystem colors entry at idx");
}
function formatSubsystemForConsole(subsystem) {
const parts = subsystem.split("/").filter(Boolean);
const original = parts.join("/") || subsystem;
while (parts.length > 0) {
const first = parts.at(0);
if (first === void 0 || !SUBSYSTEM_PREFIXES_TO_DROP.includes(first)) break;
parts.shift();
}
const first = parts.at(0);
if (first === void 0) return original;
if (isChannelSubsystemPrefix(first)) return first;
if (parts.length > SUBSYSTEM_MAX_SEGMENTS) return parts.slice(-2).join("/");
return parts.join("/");
}
function stripRedundantSubsystemPrefixForConsole(message, displaySubsystem) {
if (!displaySubsystem) return message;
if (message.startsWith("[")) {
const closeIdx = message.indexOf("]");
if (closeIdx > 1) {
if (normalizeLowercaseStringOrEmpty(message.slice(1, closeIdx)) === normalizeLowercaseStringOrEmpty(displaySubsystem)) {
let i = closeIdx + 1;
while (message[i] === " ") i += 1;
return message.slice(i);
}
}
}
if (normalizeLowercaseStringOrEmpty(message.slice(0, displaySubsystem.length)) !== normalizeLowercaseStringOrEmpty(displaySubsystem)) return message;
const next = message.slice(displaySubsystem.length, displaySubsystem.length + 1);
if (next !== ":" && next !== " ") return message;
let i = displaySubsystem.length;
while (message[i] === " ") i += 1;
if (message[i] === ":") i += 1;
while (message[i] === " ") i += 1;
return message.slice(i);
}
function createConsoleLineFormatter(subsystem) {
const displaySubsystem = formatSubsystemForConsole(subsystem);
const prefix = `[${displaySubsystem}]`;
const prefixColor = pickSubsystemColor(displaySubsystem);
return (level, message, style) => {
const color = getColorForConsole();
const levelColor = level === "error" || level === "fatal" ? color.red : level === "warn" ? color.yellow : level === "debug" || level === "trace" ? color.gray : color.cyan;
const displayMessage = stripRedundantSubsystemPrefixForConsole(redactSensitiveText(message), displaySubsystem);
const time = style === "pretty" || loggingState.consoleTimestampPrefix ? color.gray(formatConsoleTimestamp(style)) : "";
const prefixToken = color[prefixColor](prefix);
return `${time ? `${time} ${prefixToken}` : prefixToken} ${levelColor(displayMessage)}`;
};
}
function writeConsoleLine(level, line, opts = {}) {
clearActiveProgressLine();
const sanitized = process.platform === "win32" && process.env.GITHUB_ACTIONS === "true" ? line.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "?").replace(/[\uD800-\uDFFF]/g, "?") : line;
const redacted = opts.redacted ? sanitized : redactSensitiveText(sanitized);
const sink = loggingState.rawConsole ?? console;
if (loggingState.forceConsoleToStderr || level === "error" || level === "fatal") (sink.error ?? console.error)(redacted);
else if (level === "warn") (sink.warn ?? console.warn)(redacted);
else (sink.log ?? console.log)(redacted);
}
function shouldSuppressProbeConsoleLine(params) {
if (isVerbose()) return false;
if (params.level === "error" || params.level === "fatal") return false;
const message = typeof params.message === "string" ? params.message : "";
if (!params.suppressProbeMessages) return false;
if ((typeof params.meta?.runId === "string" ? params.meta.runId : typeof params.meta?.sessionId === "string" ? params.meta.sessionId : void 0)?.startsWith("probe-")) return true;
return /(sessionId|runId)=probe-/.test(message);
}
function formatConsoleMetaValue(value) {
if (value === void 0) return;
if (typeof value === "string") return /\s|=/.test(value) || value.length === 0 ? JSON.stringify(value) : value;
if (value === null || typeof value === "number" || typeof value === "boolean") return String(value);
return JSON.stringify(value);
}
/** Keeps an Error's message, which a JSON round-trip would otherwise reduce to `{}`. */
function prepareConsoleMetaRecord(meta) {
let prepared;
for (const [key, value] of Object.entries(meta)) if (value instanceof Error) {
prepared ??= { ...meta };
prepared[key] = value.message;
}
return prepared ?? meta;
}
/**
* Renders structured fields as one compact `key=value` tail so warn/error/fatal
* records keep their diagnostics in plain-text sinks such as journald, which only
* see the console line. The JSON console style and the file sink carry the same
* fields natively, so only plain styles call this.
*
* Fields pass through the shared console transport redactor before flattening, so
* key-aware protection such as `apiToken` survives the loss of structure and the
* length cap can only clip text that is already masked. That redactor also owns
* circular references, bigints, and values with no JSON form, and returns parsed
* data, so rendering a value here cannot re-enter a stateful `toJSON`.
*/
function formatConsoleMeta(meta) {
let redacted;
try {
redacted = redactLogRecordForTransport(prepareConsoleMetaRecord(meta), { format: "console" });
} catch {
return "";
}
const parts = [];
for (const [key, value] of Object.entries(redacted)) {
const rendered = formatConsoleMetaValue(value);
if (rendered !== void 0) parts.push(`${key}=${rendered}`);
}
const joined = parts.join(" ");
return joined.length > CONSOLE_META_MAX_CHARS ? `${joined.slice(0, CONSOLE_META_MAX_CHARS)}...(truncated)` : joined;
}
function logToFile(fileLogger, level, message, meta) {
if (level === "silent") return;
if (meta && Object.keys(meta).length > 0) fileLogger[level](meta, message);
else fileLogger[level](message);
}
function createSubsystemLogger(subsystem) {
const resolvedSubsystem = normalizeSubsystemLabel(subsystem);
const suppressProbeMessages = resolvedSubsystem === "agent/embedded" || resolvedSubsystem.startsWith("agent/embedded/") || resolvedSubsystem === "model-fallback" || resolvedSubsystem.startsWith("model-fallback/");
let fileChild;
let fileChildWithoutStack;
let formatConsoleLine;
const getFileLogger = (level) => {
fileChild ??= getChildLogger({ subsystem: resolvedSubsystem });
if (level === "error" || level === "fatal" || areDiagnosticsEnabledForProcess() && hasInternalDiagnosticEventInterest("log.record")) return fileChild;
if (!fileChildWithoutStack) {
fileChildWithoutStack = fileChild.getSubLogger({ stack: { capture: "off" } });
fileChildWithoutStack.settings.parentNames = fileChild.settings.parentNames;
}
return fileChildWithoutStack;
};
const emitLog = (level, message, meta) => {
const consoleSettings = getConsoleSettings();
const consoleEnabled = isLogLevelEnabled(level, consoleSettings.level) && shouldLogSubsystemToConsole(resolvedSubsystem);
const fileEnabled = isFileLogLevelEnabled(level);
if (!consoleEnabled && !fileEnabled) return;
let consoleMessageOverride;
let fileMeta = meta;
if (meta && Object.keys(meta).length > 0) {
const { consoleMessage, ...rest } = meta;
if (typeof consoleMessage === "string") consoleMessageOverride = consoleMessage;
fileMeta = Object.keys(rest).length > 0 ? rest : void 0;
}
if (fileEnabled) logToFile(getFileLogger(level), level, message, fileMeta);
if (!consoleEnabled) return;
const consoleMeta = consoleSettings.style !== "json" && consoleMessageOverride === void 0 && fileMeta && CONSOLE_META_LEVELS.has(level) ? formatConsoleMeta(fileMeta) : "";
const consoleMessage = consoleMessageOverride ?? (consoleMeta ? `${message} ${consoleMeta}` : message);
if (shouldSuppressProbeConsoleLine({
level,
suppressProbeMessages,
message: consoleMessage,
meta: fileMeta
})) return;
writeConsoleLine(level, consoleSettings.style === "json" ? formatJsonConsoleLine({
level,
subsystem: resolvedSubsystem,
message,
meta: fileMeta
}) : (formatConsoleLine ??= createConsoleLineFormatter(resolvedSubsystem))(level, consoleMessage, consoleSettings.style), { redacted: true });
};
return {
subsystem: resolvedSubsystem,
isEnabled(level, target = "any") {
const isConsoleEnabled = isLogLevelEnabled(level, getConsoleSettings().level) && shouldLogSubsystemToConsole(resolvedSubsystem);
const isFileEnabled = isFileLogLevelEnabled(level);
if (target === "console") return isConsoleEnabled;
if (target === "file") return isFileEnabled;
return isConsoleEnabled || isFileEnabled;
},
trace(message, meta) {
emitLog("trace", message, meta);
},
debug(message, meta) {
emitLog("debug", message, meta);
},
info(message, meta) {
emitLog("info", message, meta);
},
warn(message, meta) {
emitLog("warn", message, meta);
},
error(message, meta) {
emitLog("error", message, meta);
},
fatal(message, meta) {
emitLog("fatal", message, meta);
},
raw(message) {
if (isFileLogLevelEnabled("info")) logToFile(getFileLogger("info"), "info", message, { raw: true });
const consoleSettings = getConsoleSettings();
if (isLogLevelEnabled("info", consoleSettings.level) && shouldLogSubsystemToConsole(resolvedSubsystem)) {
if (shouldSuppressProbeConsoleLine({
level: "info",
suppressProbeMessages,
message
})) return;
writeConsoleLine("info", consoleSettings.style === "json" ? formatJsonConsoleLine({
level: "info",
subsystem: resolvedSubsystem,
message
}) : message, { redacted: consoleSettings.style === "json" });
}
},
child(name) {
return createSubsystemLogger(`${resolvedSubsystem}/${name}`);
}
};
}
function runtimeForLogger(logger, exit = defaultRuntime.exit) {
return {
log(...args) {
logger.info(args.map((arg) => formatRuntimeArg(arg)).join(" ").trim());
},
error(...args) {
logger.error(args.map((arg) => formatRuntimeArg(arg)).join(" ").trim());
},
writeStdout(value) {
logger.info(value);
},
writeJson(value, space = 2) {
logger.info(JSON.stringify(value, void 0, space > 0 ? space : void 0));
},
exit
};
}
var inspectValue, consoleColors, SUBSYSTEM_COLORS, SUBSYSTEM_COLOR_OVERRIDES, SUBSYSTEM_PREFIXES_TO_DROP, SUBSYSTEM_MAX_SEGMENTS, CHANNEL_SUBSYSTEM_PREFIXES, CONSOLE_META_LEVELS, CONSOLE_META_MAX_CHARS;
var init_subsystem = __esmMin((() => {
init_src$2();
init_string_coerce();
init_progress_line();
init_global_state();
init_diagnostic_event_listener_presence();
init_diagnostic_events();
init_runtime();
init_console();
init_levels();
init_logger();
init_redact();
init_state();
inspectValue = (() => {
const getBuiltinModule = process.getBuiltinModule;
if (typeof getBuiltinModule !== "function") return null;
try {
const utilNamespace = getBuiltinModule("util");
return typeof utilNamespace.inspect === "function" ? utilNamespace.inspect : null;
} catch {
return null;
}
})();
consoleColors = [];
SUBSYSTEM_COLORS = [
"cyan",
"green",
"yellow",
"blue",
"magenta",
"red"
];
SUBSYSTEM_COLOR_OVERRIDES = /* @__PURE__ */ new Map([["gmail-watcher", "blue"]]);
SUBSYSTEM_PREFIXES_TO_DROP = [
"gateway",
"channels",
"providers"
];
SUBSYSTEM_MAX_SEGMENTS = 2;
CHANNEL_SUBSYSTEM_PREFIXES = /* @__PURE__ */ new Set([
"clickclack",
"discord",
"feishu",
"googlechat",
"imessage",
"irc",
"line",
"matrix",
"mattermost",
"msteams",
"nextcloud-talk",
"nostr",
"openclaw-weixin",
"qqbot",
"signal",
"slack",
"synology-chat",
"telegram",
"tlon",
"twitch",
"webchat",
"wecom",
"whatsapp",
"yuanbao",
"zalo",
"zalouser"
]);
CONSOLE_META_LEVELS = /* @__PURE__ */ new Set([
"warn",
"error",
"fatal"
]);
CONSOLE_META_MAX_CHARS = 2048;
}));
//#endregion
//#region src/infra/sqlite-transaction.ts
function assertTransactionUsable(db) {
const aborted = db[abortedTransactionSymbol];
if (aborted) throw aborted.error;
}
function writeAdmissionLocation(database) {
const cached = writeAdmissionLocations.get(database);
if (cached !== void 0) return cached;
const location = database.location();
const canonical = location === null ? null : normalizeDatabasePath(location);
writeAdmissionLocations.set(database, canonical);
return canonical;
}
/** Locations come from the retained native owner; registration grants no write authority. */
function retainSqliteWriteAdmissionService(nativeLocations, service) {
const registrations = [...new Set(nativeLocations.map(normalizeDatabasePath))].map((location) => {
const services = writeAdmissionServices.get(location) ?? /* @__PURE__ */ new Set();
const retained = () => service();
services.add(retained);
writeAdmissionServices.set(location, services);
return {
location,
services,
retained
};
});
return () => {
for (const { location, services, retained } of registrations) {
services.delete(retained);
if (services.size === 0 && writeAdmissionServices.get(location) === services) writeAdmissionServices.delete(location);
}
};
}
function execNativeBegin(db, diagnostics) {
const startedAt = Date.now();
diagnostics.nativeAttempts += 1;
try {
db.exec("BEGIN IMMEDIATE");
} finally {
diagnostics.nativeMs += Date.now() - startedAt;
}
}
function beginImmediateTransaction(db, diagnostics) {
const location = writeAdmissionServices.size > 0 ? writeAdmissionLocation(db) : null;
const services = location === null ? void 0 : writeAdmissionServices.get(location);
if (!services) {
execNativeBegin(db, diagnostics);
return;
}
const deadline = performance.now() + readSqliteBusyTimeout(db);
while (true) try {
runWithSqliteBusyTimeout(db, Math.min(25, Math.max(0, Math.ceil(deadline - performance.now()))), () => execNativeBegin(db, diagnostics));
return;
} catch (error) {
if (!isSqliteLockError(error) || performance.now() >= deadline) throw error;
for (const service of services) {
const startedAt = Date.now();
diagnostics.serviceCalls += 1;
try {
service();
} finally {
diagnostics.serviceMs += Date.now() - startedAt;
}
}
if (performance.now() >= deadline) throw error;
}
}
function assertSyncTransactionResult(value) {
if (isPromiseLike(value)) throw new Error("SQLite write transactions must be synchronous; Promise returns are not supported.");
}
function slowBusyWaitThresholdMs(options) {
if (options?.busyTimeoutMs === void 0 || options.busyTimeoutMs <= 0) return DEFAULT_SLOW_BUSY_WAIT_MS;
return Math.min(DEFAULT_SLOW_BUSY_WAIT_MS, options.busyTimeoutMs);
}
function slowTransactionHoldThresholdMs(options) {
return options?.slowTransactionHoldMs ?? DEFAULT_SLOW_TRANSACTION_HOLD_MS;
}
function transactionLogger(options) {
return options?.logger ?? transactionLog;
}
function transactionDiagnosticLabels(db, options) {
let database = options?.databaseLabel;
if (!database) try {
database = db ? db.location() ?? ":memory:" : "unavailable";
} catch {
database = "unavailable";
}
return {
database,
operation: options?.operationLabel || captureSqliteReaderOwner()?.operation || "unlabeled"
};
}
function logSlowTransactionHold(params) {
if (params.elapsedMs < slowTransactionHoldThresholdMs(params.options)) return;
transactionLogger(params.options).warn("slow SQLite transaction hold", {
async: false,
...transactionDiagnosticLabels(params.db, params.options),
elapsedMs: params.elapsedMs,
isMainThread,
mode: params.mode,
pid: process.pid,
threadId,
thresholdMs: slowTransactionHoldThresholdMs(params.options)
});
}
function logSlowTransactionStep(params) {
if (params.elapsedMs < slowBusyWaitThresholdMs(params.options)) return;
transactionLogger(params.options).warn("slow SQLite transaction step", {
async: false,
...params.options?.busyTimeoutMs !== void 0 ? { busyTimeoutMs: params.options.busyTimeoutMs } : {},
...transactionDiagnosticLabels(params.db, params.options),
elapsedMs: params.elapsedMs,
isMainThread,
pid: process.pid,
step: params.step,
threadId,
...params.beginAdmission ? { beginAdmission: { ...params.beginAdmission } } : {}
});
}
function execTimedTransactionStep(params) {
const startedAt = Date.now();
const beginAdmission = params.sql === "BEGIN IMMEDIATE" ? {
nativeAttempts: 0,
nativeMs: 0,
serviceCalls: 0,
serviceMs: 0
} : void 0;
try {
if (beginAdmission) beginImmediateTransaction(params.db, beginAdmission);
else params.db.exec(params.sql);
const elapsedMs = Date.now() - startedAt;
logSlowTransactionStep({
beginAdmission,
db: params.db,
elapsedMs,
options: params.options,
step: params.step
});
return elapsedMs;
} catch (error) {
const elapsedMs = Date.now() - startedAt;
if (isSqliteLockError(error) && shouldReportSqliteLockFailure(params.db)) {
const sqliteErrcode = sqliteExtendedResultCode(error);
const sqlitePrimaryCode = sqlitePrimaryResultCode(error);
transactionLogger(params.options).warn("SQLite transaction lock wait failed", {
async: false,
...params.options?.busyTimeoutMs !== void 0 ? { busyTimeoutMs: params.options.busyTimeoutMs } : {},
...transactionDiagnosticLabels(params.db, params.options),
code: sqliteErrorCode(error),
elapsedMs,
failureKind: "lock-contention",
isMainThread,
pid: process.pid,
...sqliteErrcode !== void 0 ? { sqliteErrcode } : {},
...sqlitePrimaryCode !== void 0 ? { sqlitePrimaryCode } : {},
step: params.step,
threadId,
...beginAdmission ? { beginAdmission: { ...beginAdmission } } : {}
});
}
throw error;
}
}
function beginTransaction(db, options, mode) {
execTimedTransactionStep({
db,
options,
sql: mode === "immediate" ? "BEGIN IMMEDIATE" : "BEGIN",
step: "begin"
});
}
function commitImmediateTransaction(db, options) {
execTimedTransactionStep({
db,
options,
sql: "COMMIT",
step: "commit"
});
}
function discardUnsafeConnection(db, error) {
db[abortedTransactionSymbol] ??= { error };
discardSqliteTransactionState(db, error);
clearNodeSqliteKyselyCacheForDatabase(db);
try {
db.close();
} catch {}
}
function abortImmediateTransaction(db, error, commitStarted) {
if (db[abortedTransactionSymbol]) return;
try {
if (!commitStarted && db.isOpen && !db.isTransaction) {
discardSqliteTransactionState(db, error);
return;
}
db.exec("ROLLBACK");
} catch {
discardUnsafeConnection(db, error);
}
}
function runSqliteTransactionSync(db, operation, mode, options) {
assertTransactionUsable(db);
if (db.isTransaction) {
db.exec("SAVEPOINT openclaw_tx_nested");
try {
const result = operation();
assertSyncTransactionResult(result);
assertTransactionUsable(db);
db.exec("RELEASE SAVEPOINT openclaw_tx_nested");
return result;
} catch (error) {
const failure = db[abortedTransactionSymbol];
if (failure) throw failure.error;
try {
db.exec("ROLLBACK TO SAVEPOINT openclaw_tx_nested");
db.exec("RELEASE SAVEPOINT openclaw_tx_nested");
} catch {
discardUnsafeConnection(db, error);
}
throw error;
}
}
beginTransaction(db, options, mode);
const transactionStartedAt = Date.now();
let commitStarted = false;
try {
const result = operation();
assertSyncTransactionResult(result);
assertTransactionUsable(db);
commitStarted = true;
if (options?.withCommit) assertSyncTransactionResult(options.withCommit(() => commitImmediateTransaction(db, options)));
else commitImmediateTransaction(db, options);
return result;
} catch (error) {
abortImmediateTransaction(db, error, commitStarted);
assertTransactionUsable(db);
throw error;
} finally {
try {
logSlowTransactionHold({
db,
elapsedMs: Date.now() - transactionStartedAt,
mode,
options
});
} catch {}
}
}
/** Run synchronous reads against one deferred SQLite snapshot. */
function runSqliteDeferredTransactionSync(db, operation, options) {
return runSqliteTransactionSync(db, operation, "deferred", options);
}
function runSqliteImmediateTransactionSync(db, operation, options) {
return runSqliteTransactionSync(db, operation, "immediate", options);
}
var DEFAULT_SLOW_BUSY_WAIT_MS, DEFAULT_SLOW_TRANSACTION_HOLD_MS, abortedTransactionSymbol, transactionLog, writeAdmissionServices, writeAdmissionLocations;
var init_sqlite_transaction = __esmMin((() => {
init_promise_like();
init_subsystem();
init_global_singleton();
init_kysely_sync_cache_state();
init_sqlite_busy_timeout();
init_sqlite_error_diagnostics();
init_sqlite_post_commit();
init_sqlite_reader_lifecycle();
init_sqlite_worker_identity();
DEFAULT_SLOW_BUSY_WAIT_MS = 1e3;
DEFAULT_SLOW_TRANSACTION_HOLD_MS = 1e3;
abortedTransactionSymbol = Symbol.for("openclaw.sqliteAbortedTransaction");
transactionLog = createSubsystemLogger("sqlite/transaction");
writeAdmissionServices = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWriteAdmissionServices"), () => /* @__PURE__ */ new Map());
writeAdmissionLocations = /* @__PURE__ */ new WeakMap();
}));
//#endregion
//#region src/infra/sqlite-wal-write-admission.ts
function registerSqliteWalWorkerMaintenance(database, execute, cancel) {
admissions.set(database, {
execute,
cancel
});
}
function cancelSqliteWalWriteAdmission(database) {
return admissions.get(database)?.cancel?.();
}
var admissions;
var init_sqlite_wal_write_admission = __esmMin((() => {
init_global_singleton();
init_sqlite_transaction();
admissions = resolveGlobalSingleton(Symbol.for("openclaw.sqliteWalWriteAdmissions"), () => /* @__PURE__ */ new WeakMap());
}));
var init_sqlite_number = __esmMin((() => {
BigInt(Number.MAX_SAFE_INTEGER);
}));
var init_sqlite_wal_checkpoint = __esmMin((() => {
init_global_singleton();
init_errno();
init_errors$2();
init_sqlite_number();
init_sqlite_reader_lifecycle();
resolveGlobalSingleton(Symbol.for("openclaw.sqliteWalCheckpointListeners"), () => /* @__PURE__ */ new Set());
}));
//#endregion
//#region src/infra/sqlite-wal-reclamation.ts
var init_sqlite_wal_reclamation = __esmMin((() => {
init_sqlite_error_diagnostics();
init_sqlite_transaction();
}));
//#endregion
//#region src/infra/sqlite-wal-split-brain.ts
var init_sqlite_wal_split_brain = __esmMin((() => {
init_errno();
}));
//#endregion
//#region src/infra/sqlite-wal.ts
function detachEmptySqliteExitGroup(group) {
if (group.pending.size > 0) return;
if (lastSqliteExitGroup === group) lastSqliteExitGroup = void 0;
process.removeListener("exit", group.dispatch);
}
/**
* Register a best-effort exit-time close for a SQLite handle cache. Returns an
* unregister callback the cache's orderly close path must invoke, so tests and
* runtime shutdowns do not accumulate listeners on shared worker processes.
*/
function registerSqliteCacheExitClose(closeAll) {
const registration = {
close: closeAll,
fired: false
};
let group = lastSqliteExitGroup;
if (!group || process.listeners("exit").at(-1) !== group.dispatch) {
const pending = /* @__PURE__ */ new Set([registration]);
const created = {
pending,
dispatch: () => {
const snapshot = [...pending];
for (const entry of snapshot) {
if (entry.fired) continue;
entry.fired = true;
pending.delete(entry);
detachEmptySqliteExitGroup(created);
try {
entry.close();
} catch {}
}
}
};
process.on("exit", created.dispatch);
lastSqliteExitGroup = group = created;
} else group.pending.add(registration);
const owner = group;
return () => {
owner.pending.delete(registration);
detachEmptySqliteExitGroup(owner);
};
}
var runInSqliteMaintenanceContext, lastSqliteExitGroup;
var init_sqlite_wal = __esmMin((() => {
init_number_coercion();
init_subsystem();
init_sqlite_error_diagnostics();
init_sqlite_lifecycle_errors();
init_sqlite_wal_checkpoint();
init_sqlite_wal_reclamation();
init_sqlite_wal_split_brain();
init_sqlite_wal_write_admission();
new Int32Array(new SharedArrayBuffer(4));
createSubsystemLogger("infra/sqlite-wal");
runInSqliteMaintenanceContext = AsyncLocalStorage.snapshot();
}));
//#endregion
//#region src/state/openclaw-quarantine-error.ts
var DATABASE_QUARANTINE_READ_CLEANUP_ERROR_NAME, OpenClawQuarantineReadCleanupError;
var init_openclaw_quarantine_error = __esmMin((() => {
init_global_singleton();
DATABASE_QUARANTINE_READ_CLEANUP_ERROR_NAME = "OpenClawQuarantineReadCleanupError";
OpenClawQuarantineReadCleanupError = resolveGlobalSingleton(Symbol.for("openclaw.quarantineReadCleanupError"), () => class QuarantineReadCleanupError extends AggregateError {
constructor(errors, quarantine) {
super(errors, "OpenClaw quarantine reader cleanup failed.", { cause: errors[0] });
this.quarantine = quarantine;
this.name = DATABASE_QUARANTINE_READ_CLEANUP_ERROR_NAME;
}
});
}));
//#endregion
//#region src/infra/sqlite-strict.ts
var init_sqlite_strict = __esmMin((() => {
init_node_sqlite();
init_sqlite_integrity();
init_sqlite_transaction();
}));
//#endregion
//#region packages/memory-host-sdk/src/host/openclaw-runtime-sqlite.ts
var init_openclaw_runtime_sqlite = __esmMin((() => {
init_sqlite_strict();
init_sqlite_schema_contract();
init_sqlite_transaction();
})), MEMORY_INDEX_CHUNK_PROVENANCE_TABLE;
var init_memory_schema_provenance = __esmMin((() => {
init_openclaw_runtime_sqlite();
MEMORY_INDEX_CHUNK_PROVENANCE_TABLE = "memory_index_chunk_provenance";
`${MEMORY_INDEX_CHUNK_PROVENANCE_TABLE}`;
`${MEMORY_INDEX_CHUNK_PROVENANCE_TABLE}`;
})), MEMORY_INDEX_CHUNKS_TABLE$1, MEMORY_INDEX_CHUNK_RECALL_METADATA_TABLE;
var init_memory_schema_recall = __esmMin((() => {
init_openclaw_runtime_sqlite();
MEMORY_INDEX_CHUNKS_TABLE$1 = "memory_index_chunks";
MEMORY_INDEX_CHUNK_RECALL_METADATA_TABLE = "memory_index_chunk_recall_metadata";
`${MEMORY_INDEX_CHUNK_RECALL_METADATA_TABLE}${MEMORY_INDEX_CHUNKS_TABLE$1}`;
}));
//#endregion
//#region packages/memory-host-sdk/src/host/error-utils.ts
var init_error_utils = __esmMin((() => {
init_redact();
})), MEMORY_INDEX_SOURCES_TABLE, MEMORY_INDEX_CHUNKS_TABLE, MEMORY_INDEX_FTS_TABLE, MEMORY_INDEX_PATHS_FTS_TABLE;
var init_memory_schema_fts = __esmMin((() => {
MEMORY_INDEX_SOURCES_TABLE = "memory_index_sources";
MEMORY_INDEX_CHUNKS_TABLE = "memory_index_chunks";
MEMORY_INDEX_FTS_TABLE = "memory_index_chunks_fts";
MEMORY_INDEX_PATHS_FTS_TABLE = "memory_index_paths_fts";
`${MEMORY_INDEX_SOURCES_TABLE}${MEMORY_INDEX_PATHS_FTS_TABLE}`, `${MEMORY_INDEX_SOURCES_TABLE}${MEMORY_INDEX_PATHS_FTS_TABLE}${MEMORY_INDEX_PATHS_FTS_TABLE}`, `${MEMORY_INDEX_SOURCES_TABLE}${MEMORY_INDEX_PATHS_FTS_TABLE}`;
`${MEMORY_INDEX_CHUNKS_TABLE}${MEMORY_INDEX_FTS_TABLE}`, `${MEMORY_INDEX_CHUNKS_TABLE}${MEMORY_INDEX_FTS_TABLE}${MEMORY_INDEX_FTS_TABLE}`, `${MEMORY_INDEX_CHUNKS_TABLE}${MEMORY_INDEX_FTS_TABLE}`;
}));
var init_memory_schema_base = __esmMin((() => {
init_memory_schema_fts();
init_memory_schema_provenance();
init_memory_schema_recall();
`${MEMORY_INDEX_CHUNKS_TABLE}`;
}));
var init_memory_schema_storage_migration = __esmMin((() => {
init_memory_schema_base();
init_memory_schema_fts();
init_memory_schema_recall();
init_openclaw_runtime_sqlite();
[
"insert",
"update",
"delete"
].map((event) => ({
name: `memory_index_chunks_revision_after_${event}`,
sql: `CREATE TRIGGER IF NOT EXISTS memory_index_chunks_revision_after_${event}
AFTER ${event.toUpperCase()} ON memory_index_chunks
BEGIN UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1; END;`
}));
})), LEGACY_MEMORY_INDEX_SOURCE_COLUMNS;
var init_memory_schema = __esmMin((() => {
init_error_utils();
init_memory_schema_base();
init_memory_schema_fts();
init_memory_schema_provenance();
init_memory_schema_recall();
init_memory_schema_storage_migration();
init_openclaw_runtime_sqlite();
LEGACY_MEMORY_INDEX_SOURCE_COLUMNS = [
"path",
"source",
"hash",
"mtime",
"size"
];
[...LEGACY_MEMORY_INDEX_SOURCE_COLUMNS];
}));
//#endregion
//#region src/state/openclaw-agent-schema.ts
var OPENCLAW_AGENT_SCHEMA_SQL;
var init_openclaw_agent_schema = __esmMin((() => {
OPENCLAW_AGENT_SCHEMA_SQL = "-- Session storage doctrine: session_nodes.entry_json owns hot logical-session facts;\n-- session_entry_snapshots owns keyed cold values. Promoted node columns are query\n-- indexes; session_windows and their children own transcript generations.\n-- Legacy ACP provenance is private import evidence carried with its logical session.\n\nCREATE TABLE IF NOT EXISTS schema_meta (\n meta_key TEXT NOT NULL PRIMARY KEY,\n role TEXT NOT NULL,\n schema_version INTEGER NOT NULL,\n agent_id TEXT,\n app_version TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_nodes (\n session_key TEXT NOT NULL PRIMARY KEY,\n current_session_id TEXT NOT NULL,\n entry_json TEXT NOT NULL,\n snapshot_revision INTEGER NOT NULL DEFAULT 0,\n legacy_acp_migration_json TEXT,\n entry_valid INTEGER NOT NULL DEFAULT 0 CHECK (entry_valid IN (-1, 0, 1)),\n updated_at INTEGER NOT NULL,\n status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),\n created_at INTEGER,\n created_via TEXT CHECK (created_via IS NULL OR created_via IN ('operator', 'spawn', 'channel', 'cron', 'talk', 'run', 'plugin', 'internal')),\n created_actor_type TEXT CHECK (created_actor_type IS NULL OR created_actor_type IN ('human', 'agent', 'system')),\n created_actor_id TEXT,\n owner_actor_type TEXT,\n owner_actor_id TEXT,\n owner_assigned_by_type TEXT,\n owner_assigned_by_id TEXT,\n owner_assigned_at INTEGER,\n project_id TEXT,\n parent_session_key TEXT,\n spawned_by TEXT,\n fork_source_session_key TEXT,\n fork_source_session_id TEXT,\n fork_source_entry_id TEXT,\n label TEXT,\n display_name TEXT,\n category TEXT,\n icon TEXT,\n pinned_at INTEGER,\n archived_at INTEGER,\n last_read_at INTEGER,\n last_interaction_at INTEGER,\n last_activity_at INTEGER\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_entry_snapshots (\n session_key TEXT NOT NULL,\n field TEXT NOT NULL CHECK (field IN ('sessionDiffBaseline', 'skillsSnapshot', 'systemPromptReport')),\n value_json TEXT NOT NULL,\n PRIMARY KEY (session_key, field),\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT, WITHOUT ROWID;\n\nCREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_insert\nAFTER INSERT ON session_entry_snapshots\nBEGIN\n UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1\n WHERE session_key = NEW.session_key;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_update\nAFTER UPDATE OF session_key, field, value_json ON session_entry_snapshots\nWHEN NEW.session_key IS NOT OLD.session_key\n OR NEW.field IS NOT OLD.field OR NEW.value_json IS NOT OLD.value_json\nBEGIN\n UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1\n WHERE session_key IN (OLD.session_key, NEW.session_key);\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_entry_snapshots_after_delete\nAFTER DELETE ON session_entry_snapshots\nBEGIN\n UPDATE session_nodes SET snapshot_revision = snapshot_revision + 1\n WHERE session_key = OLD.session_key;\nEND;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_updated_at\n ON session_nodes(updated_at DESC, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_last_interaction_at\n ON session_nodes(last_interaction_at DESC, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_label\n ON session_nodes(label, session_key)\n WHERE label IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_parent_session_key\n ON session_nodes(parent_session_key, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_spawned_by\n ON session_nodes(spawned_by, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_status\n ON session_nodes(status, session_key)\n WHERE status IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_archived_at\n ON session_nodes(archived_at, session_key)\n WHERE archived_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_active\n ON session_nodes(session_key)\n WHERE archived_at IS NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_current_session_id\n ON session_nodes(current_session_id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_valid_pending\n ON session_nodes(session_key)\n WHERE entry_valid = 0;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_nodes_entry_not_valid\n ON session_nodes(session_key)\n WHERE entry_valid != 1;\n\nCREATE TABLE IF NOT EXISTS session_participants (\n session_key TEXT NOT NULL,\n identity_namespace TEXT NOT NULL,\n actor_id TEXT NOT NULL,\n contribution_count INTEGER NOT NULL,\n first_prompted_at INTEGER,\n last_prompted_at INTEGER,\n PRIMARY KEY (session_key, identity_namespace, actor_id),\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_key_contract (\n id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),\n main_key TEXT NOT NULL,\n canonical_ready TEXT,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nINSERT OR IGNORE INTO session_key_contract (id, main_key, updated_at) VALUES (1, 'main', 0);\n\nCREATE TRIGGER IF NOT EXISTS session_nodes_entry_valid_after_insert\nAFTER INSERT ON session_nodes\nBEGIN\n UPDATE session_nodes SET entry_valid = 0 WHERE session_key = NEW.session_key;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_nodes_entry_valid_after_entry_update\nAFTER UPDATE OF entry_json ON session_nodes\nBEGIN\n UPDATE session_nodes SET entry_valid = 0 WHERE session_key = NEW.session_key;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_nodes_entry_valid_after_identity_update\nAFTER UPDATE OF current_session_id, updated_at ON session_nodes\nBEGIN\n UPDATE session_nodes SET entry_valid = 0 WHERE session_key = NEW.session_key;\nEND;\n\nCREATE TABLE IF NOT EXISTS session_windows (\n session_id TEXT NOT NULL PRIMARY KEY,\n session_key TEXT NOT NULL,\n previous_session_id TEXT,\n reason TEXT CHECK (reason IS NULL OR reason IN ('initial', 'reset', 'rollover', 'fork', 'rewind', 'switch', 'recovery', 'compaction')),\n session_scope TEXT NOT NULL DEFAULT 'conversation' CHECK (session_scope IN ('conversation', 'shared-main', 'group', 'channel')),\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n transcript_updated_at INTEGER DEFAULT NULL,\n transcript_observed_at INTEGER DEFAULT NULL,\n session_entry_provenance INTEGER NOT NULL DEFAULT 0 CHECK (session_entry_provenance IN (0, 1)),\n acp_owned INTEGER NOT NULL DEFAULT 0 CHECK (acp_owned IN (0, 1)),\n plugin_owner_id TEXT,\n hook_external_content_source TEXT CHECK (hook_external_content_source IS NULL OR hook_external_content_source IN ('gmail', 'webhook')),\n started_at INTEGER,\n ended_at INTEGER,\n status TEXT CHECK (status IS NULL OR status IN ('running', 'done', 'failed', 'killed', 'timeout')),\n chat_type TEXT CHECK (chat_type IS NULL OR chat_type IN ('direct', 'group', 'channel')),\n channel TEXT,\n account_id TEXT,\n primary_conversation_id TEXT,\n model_provider TEXT,\n model TEXT,\n agent_harness_id TEXT,\n parent_session_key TEXT,\n spawned_by TEXT,\n display_name TEXT,\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,\n FOREIGN KEY (primary_conversation_id) REFERENCES conversations(conversation_id) ON DELETE SET NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_windows_updated_at\n ON session_windows(updated_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_windows_session_key\n ON session_windows(session_key, updated_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_windows_created_at\n ON session_windows(created_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_windows_conversation\n ON session_windows(primary_conversation_id, updated_at DESC, session_id)\n WHERE primary_conversation_id IS NOT NULL;\n\n-- No foreign key: node triggers settle key renames and deletion even while a\n-- maintenance owner has disabled foreign-key enforcement.\nCREATE TABLE IF NOT EXISTS session_canonical_validation_pending (\n session_key TEXT NOT NULL PRIMARY KEY\n) STRICT;\n\n-- Avoid trigger-local conflict clauses: SQLite inherits the outer writer's\n-- conflict policy, including writers that predate this validation projection.\nCREATE TRIGGER IF NOT EXISTS session_nodes_canonical_pending_after_insert\nAFTER INSERT ON session_nodes\nBEGIN\n INSERT INTO session_canonical_validation_pending (session_key)\n SELECT NEW.session_key\n WHERE NOT EXISTS (\n SELECT 1 FROM session_canonical_validation_pending WHERE session_key = NEW.session_key\n );\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_nodes_canonical_pending_after_update\nAFTER UPDATE OF session_key, current_session_id, entry_json, entry_valid,\n parent_session_key, spawned_by, fork_source_session_key ON session_nodes\nWHEN OLD.session_key IS NOT NEW.session_key\n OR OLD.current_session_id IS NOT NEW.current_session_id\n OR OLD.entry_json IS NOT NEW.entry_json\n OR OLD.entry_valid IS NOT NEW.entry_valid\n OR OLD.parent_session_key IS NOT NEW.parent_session_key\n OR OLD.spawned_by IS NOT NEW.spawned_by\n OR OLD.fork_source_session_key IS NOT NEW.fork_source_session_key\nBEGIN\n DELETE FROM session_canonical_validation_pending\n WHERE session_key = OLD.session_key AND OLD.session_key IS NOT NEW.session_key;\n INSERT INTO session_canonical_validation_pending (session_key)\n SELECT NEW.session_key\n WHERE NOT EXISTS (\n SELECT 1 FROM session_canonical_validation_pending WHERE session_key = NEW.session_key\n );\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_nodes_canonical_pending_after_delete\nAFTER DELETE ON session_nodes\nBEGIN\n DELETE FROM session_canonical_validation_pending WHERE session_key = OLD.session_key;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_windows_canonical_pending_after_insert\nAFTER INSERT ON session_windows\nBEGIN\n INSERT INTO session_canonical_validation_pending (session_key)\n SELECT node.session_key FROM session_nodes AS node\n WHERE node.current_session_id = NEW.session_id\n AND NOT EXISTS (\n SELECT 1 FROM session_canonical_validation_pending AS pending\n WHERE pending.session_key = node.session_key\n );\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_windows_canonical_pending_after_update\nAFTER UPDATE OF session_id, session_key ON session_windows\nWHEN OLD.session_id IS NOT NEW.session_id OR OLD.session_key IS NOT NEW.session_key\nBEGIN\n INSERT INTO session_canonical_validation_pending (session_key)\n SELECT node.session_key FROM session_nodes AS node\n WHERE node.current_session_id IN (OLD.session_id, NEW.session_id)\n AND NOT EXISTS (\n SELECT 1 FROM session_canonical_validation_pending AS pending\n WHERE pending.session_key = node.session_key\n );\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_windows_canonical_pending_after_delete\nAFTER DELETE ON session_windows\nBEGIN\n INSERT INTO session_canonical_validation_pending (session_key)\n SELECT node.session_key FROM session_nodes AS node\n WHERE node.current_session_id = OLD.session_id\n AND NOT EXISTS (\n SELECT 1 FROM session_canonical_validation_pending AS pending\n WHERE pending.session_key = node.session_key\n );\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_key_contract_canonical_pending_after_insert\nAFTER INSERT ON session_key_contract\nBEGIN\n INSERT INTO session_canonical_validation_pending (session_key)\n SELECT node.session_key FROM session_nodes AS node\n WHERE NOT EXISTS (\n SELECT 1 FROM session_canonical_validation_pending AS pending\n WHERE pending.session_key = node.session_key\n );\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_key_contract_canonical_pending_after_update\nAFTER UPDATE OF main_key ON session_key_contract\nWHEN OLD.main_key IS NOT NEW.main_key\nBEGIN\n INSERT INTO session_canonical_validation_pending (session_key)\n SELECT node.session_key FROM session_nodes AS node\n WHERE NOT EXISTS (\n SELECT 1 FROM session_canonical_validation_pending AS pending\n WHERE pending.session_key = node.session_key\n );\nEND;\n\nCREATE TRIGGER IF NOT EXISTS session_key_contract_canonical_pending_after_delete\nAFTER DELETE ON session_key_contract\nBEGIN\n INSERT INTO session_canonical_validation_pending (session_key)\n SELECT node.session_key FROM session_nodes AS node\n WHERE NOT EXISTS (\n SELECT 1 FROM session_canonical_validation_pending AS pending\n WHERE pending.session_key = node.session_key\n );\nEND;\n\nCREATE TABLE IF NOT EXISTS conversations (\n conversation_id TEXT NOT NULL PRIMARY KEY,\n channel TEXT NOT NULL,\n account_id TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('direct', 'group', 'channel')),\n peer_id TEXT NOT NULL,\n delivery_target TEXT NOT NULL,\n parent_conversation_id TEXT,\n thread_id TEXT,\n native_channel_id TEXT,\n native_direct_user_id TEXT,\n label TEXT,\n metadata_json TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_conversations_lookup\n ON conversations(channel, account_id, kind, peer_id, thread_id);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_conversations_identity\n ON conversations(\n channel,\n account_id,\n kind,\n peer_id,\n IFNULL(parent_conversation_id, ''),\n IFNULL(thread_id, '')\n );\n\nCREATE INDEX IF NOT EXISTS idx_agent_conversations_updated\n ON conversations(updated_at DESC, conversation_id);\n\nCREATE TABLE IF NOT EXISTS conversation_deliveries (\n operation_id TEXT NOT NULL PRIMARY KEY,\n operation_kind TEXT NOT NULL CHECK (operation_kind IN ('send', 'turn')),\n conversation_id TEXT NOT NULL,\n source_session_key TEXT,\n message_hash TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('created', 'queued', 'sent', 'suppressed', 'rejected', 'unknown', 'replied')),\n prepared_message_id TEXT,\n platform_message_id TEXT,\n queue_id TEXT,\n rejection_error TEXT,\n reply_message_id TEXT,\n reply_to_id TEXT,\n reply_thread_id TEXT,\n reply_text TEXT,\n reply_timestamp INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n CHECK (\n (status = 'rejected' AND rejection_error IS NOT NULL) OR\n (status != 'rejected' AND rejection_error IS NULL)\n ),\n FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_reply\n ON conversation_deliveries(conversation_id, platform_message_id, prepared_message_id)\n WHERE status IN ('queued', 'sent', 'replied');\n\nCREATE INDEX IF NOT EXISTS idx_agent_conversation_deliveries_updated\n ON conversation_deliveries(updated_at DESC, operation_id);\n\nCREATE TABLE IF NOT EXISTS session_conversations (\n session_id TEXT NOT NULL,\n conversation_id TEXT NOT NULL,\n role TEXT NOT NULL DEFAULT 'primary' CHECK (role IN ('primary', 'participant', 'related')),\n route_context_json TEXT,\n first_seen_at INTEGER NOT NULL,\n last_seen_at INTEGER NOT NULL,\n PRIMARY KEY (session_id, conversation_id, role),\n FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE,\n FOREIGN KEY (conversation_id) REFERENCES conversations(conversation_id) ON DELETE CASCADE\n) STRICT;\n\n-- Older same-version writers preserve the envelope while updating the association.\nCREATE TRIGGER IF NOT EXISTS session_conversations_route_context_invalidate_after_update\nAFTER UPDATE OF role, last_seen_at ON session_conversations\nWHEN NEW.route_context_json IS OLD.route_context_json\nBEGIN\n UPDATE session_conversations\n SET route_context_json = NULL\n WHERE session_id = NEW.session_id\n AND conversation_id = NEW.conversation_id\n AND role = NEW.role;\nEND;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_conversations_conversation\n ON session_conversations(conversation_id, last_seen_at DESC, session_id);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_session_conversations_primary\n ON session_conversations(session_id)\n WHERE role = 'primary';\n\nCREATE TABLE IF NOT EXISTS session_members (\n session_key TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n added_by TEXT NOT NULL,\n added_at INTEGER NOT NULL,\n PRIMARY KEY (session_key, identity_id),\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_members_identity\n ON session_members(identity_id, session_key);\n\nCREATE TABLE IF NOT EXISTS session_suggestions (\n id TEXT PRIMARY KEY,\n session_key TEXT NOT NULL,\n author_id TEXT NOT NULL,\n author_label TEXT,\n text TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('pending', 'accepted', 'dismissed')),\n dispatch_token TEXT,\n dispatch_started_at INTEGER,\n dispatch_resolution TEXT CHECK (dispatch_resolution IN ('send', 'queue', 'edit', 'dismiss')),\n CHECK (\n (dispatch_token IS NULL AND dispatch_started_at IS NULL AND dispatch_resolution IS NULL)\n OR (dispatch_token IS NOT NULL AND dispatch_started_at IS NOT NULL AND dispatch_resolution IS NOT NULL)\n ),\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_session_state_created\n ON session_suggestions(session_key, state, created_at, id);\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_suggestions_author_created\n ON session_suggestions(author_id, created_at, id);\n\nCREATE TABLE IF NOT EXISTS board_tabs (\n session_key TEXT NOT NULL,\n tab_id TEXT NOT NULL,\n title TEXT NOT NULL,\n position INTEGER NOT NULL CHECK (position >= 0),\n chat_dock TEXT NOT NULL DEFAULT 'right' CHECK (chat_dock IN ('left', 'right', 'bottom', 'hidden')),\n created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),\n revision INTEGER NOT NULL CHECK (revision >= 0),\n PRIMARY KEY (session_key, tab_id),\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS board_widgets (\n session_key TEXT NOT NULL,\n name TEXT NOT NULL,\n tab_id TEXT NOT NULL,\n title TEXT,\n content_kind TEXT NOT NULL CHECK (content_kind IN ('html', 'mcp-app', 'plugin')),\n html BLOB,\n descriptor_json TEXT,\n sha256 TEXT NOT NULL,\n view_generation TEXT,\n revision INTEGER NOT NULL CHECK (revision >= 1),\n size_w INTEGER NOT NULL CHECK (size_w BETWEEN 1 AND 12),\n size_h INTEGER NOT NULL CHECK (size_h BETWEEN 1 AND 20),\n position INTEGER NOT NULL CHECK (position >= 0),\n manifest TEXT NOT NULL DEFAULT '{}',\n grant_state TEXT NOT NULL DEFAULT 'none' CHECK (grant_state IN ('none', 'pending', 'granted', 'rejected')),\n granted_sha TEXT,\n created_by TEXT NOT NULL CHECK (created_by IN ('user', 'agent')),\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (session_key, name),\n FOREIGN KEY (session_key, tab_id) REFERENCES board_tabs(session_key, tab_id) ON DELETE CASCADE,\n CHECK (\n (content_kind = 'html' AND html IS NOT NULL AND descriptor_json IS NULL AND view_generation IS NOT NULL) OR\n (content_kind = 'mcp-app' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL) OR\n (content_kind = 'plugin' AND html IS NULL AND descriptor_json IS NOT NULL AND view_generation IS NULL)\n )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_board_widgets_tab_position\n ON board_widgets(session_key, tab_id, position);\n\nCREATE TABLE IF NOT EXISTS session_progress_cards (\n session_key TEXT NOT NULL PRIMARY KEY,\n markdown TEXT,\n steps_json TEXT,\n revision INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS heartbeat_outcomes (\n session_key TEXT NOT NULL PRIMARY KEY,\n run_session_key TEXT NOT NULL,\n outcome TEXT NOT NULL CHECK (outcome IN ('progress', 'done', 'blocked', 'needs_attention')),\n summary TEXT NOT NULL,\n response_reason TEXT,\n priority TEXT CHECK (priority IS NULL OR priority IN ('low', 'normal', 'high')),\n next_check TEXT,\n task_names_json TEXT,\n wake_source TEXT,\n wake_reason TEXT,\n occurred_at INTEGER NOT NULL,\n context_run_id TEXT,\n context_claimed_at INTEGER,\n updated_at INTEGER NOT NULL,\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS message_tool_run_outcomes (\n id INTEGER PRIMARY KEY,\n run_id TEXT NOT NULL,\n session_key TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n provider TEXT NOT NULL,\n model TEXT NOT NULL,\n outcome TEXT NOT NULL CHECK (outcome IN ('tool_delivered', 'mute')),\n run_status TEXT NOT NULL CHECK (run_status IN ('completed', 'errored', 'aborted')),\n occurred_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_message_tool_run_outcomes_occurred\n ON message_tool_run_outcomes(occurred_at DESC, id DESC);\n\n-- Receipts outlive Goal clear and session reset so a delayed retry cannot recreate a Goal.\n-- They intentionally have no session FK; bounded retention belongs to the operation owner.\nCREATE TABLE IF NOT EXISTS session_goal_operations (\n session_key TEXT NOT NULL,\n operation_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n request_fingerprint TEXT NOT NULL,\n result_json TEXT NOT NULL,\n expires_at INTEGER NOT NULL,\n PRIMARY KEY (session_key, operation_id)\n) STRICT;\nCREATE INDEX IF NOT EXISTS idx_agent_session_goal_operations_expiry\n ON session_goal_operations(expires_at);\n\nCREATE TABLE IF NOT EXISTS transcript_events (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n event_json TEXT,\n created_at INTEGER NOT NULL,\n event_zstd BLOB,\n event_utf8_bytes INTEGER CHECK (event_utf8_bytes IS NULL OR event_utf8_bytes >= 0),\n navigation_json TEXT,\n PRIMARY KEY (session_id, seq),\n FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE,\n CHECK (\n (event_json IS NOT NULL AND event_zstd IS NULL)\n OR (\n event_json IS NULL AND event_zstd IS NOT NULL\n AND event_utf8_bytes IS NOT NULL\n AND event_utf8_bytes BETWEEN 1 AND 4194304\n AND length(event_zstd) BETWEEN 1 AND 4194304\n AND navigation_json IS NOT NULL\n )\n ),\n CHECK (\n navigation_json IS NULL OR CASE WHEN json_valid(navigation_json) THEN coalesce(\n octet_length(navigation_json) <= 16384\n AND json_type(navigation_json, '$.version') = 'integer'\n AND json_extract(navigation_json, '$.version') = 1\n AND json_type(navigation_json, '$.report') = 'object'\n AND json_extract(navigation_json, '$.report.kind') IN ('canonical', 'leaf', 'link', 'ignored')\n AND json_type(navigation_json, '$.navigation') = 'object'\n AND json_type(navigation_json, '$.reset') = 'object'\n AND json_type(navigation_json, '$.model') = 'object'\n AND json_type(navigation_json, '$.modelBytes') = 'integer'\n AND json_extract(navigation_json, '$.modelBytes') BETWEEN 0 AND 4194304\n AND json_type(navigation_json, '$.modelWithoutCheckpointBytes') = 'integer'\n AND json_extract(navigation_json, '$.modelWithoutCheckpointBytes') BETWEEN 0 AND 4194304\n AND json_type(navigation_json, '$.withoutCustomDataBytes') = 'integer'\n AND json_extract(navigation_json, '$.withoutCustomDataBytes') BETWEEN 0 AND 4194304,\n 0) ELSE 0 END\n )\n) STRICT;\n\n-- Canonical cold-tier owner for reclaimed transcript generations. The derived\n-- .deleted/.reset file may be recreated from this row after a crash.\nCREATE TABLE IF NOT EXISTS session_transcript_archives (\n session_id TEXT NOT NULL,\n generation TEXT NOT NULL,\n session_key TEXT NOT NULL,\n reason TEXT NOT NULL CHECK (reason IN ('deleted', 'reset')),\n encoding TEXT NOT NULL CHECK (encoding IN ('identity', 'zstd')),\n archive_blob BLOB NOT NULL,\n archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),\n archive_name TEXT NOT NULL UNIQUE,\n created_at INTEGER NOT NULL,\n published_at INTEGER,\n publish_attempts INTEGER NOT NULL DEFAULT 0 CHECK (publish_attempts >= 0),\n last_publish_attempt_at INTEGER,\n last_publish_error TEXT,\n PRIMARY KEY (session_id, generation),\n CHECK (archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%')\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_pending\n ON session_transcript_archives(created_at, session_id, generation)\n WHERE published_at IS NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_transcript_archives_retention\n ON session_transcript_archives(created_at, session_id, generation);\n\nCREATE TABLE IF NOT EXISTS session_transcript_cold_archives (\n session_id TEXT NOT NULL PRIMARY KEY,\n generation TEXT NOT NULL,\n archive_name TEXT NOT NULL UNIQUE,\n archive_sha256 TEXT NOT NULL CHECK (length(archive_sha256) = 64),\n event_count INTEGER NOT NULL CHECK (event_count >= 1),\n raw_bytes INTEGER NOT NULL CHECK (raw_bytes >= 0),\n archive_bytes INTEGER NOT NULL CHECK (archive_bytes >= 0),\n last_seq INTEGER NOT NULL,\n archived_at INTEGER NOT NULL,\n storage TEXT NOT NULL CHECK (storage IN ('file', 'sqlite')),\n archive_blob BLOB,\n FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE,\n CHECK (length(archive_name) > 0 AND archive_name NOT IN ('.', '..') AND archive_name NOT LIKE '%/%' AND archive_name NOT LIKE '%\\%'),\n CHECK ((storage = 'file' AND archive_blob IS NULL) OR (storage = 'sqlite' AND archive_blob IS NOT NULL))\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS transcript_rewrite_watermarks (\n session_id TEXT NOT NULL PRIMARY KEY,\n generation TEXT NOT NULL,\n updated_at INTEGER NOT NULL,\n FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS trajectory_runtime_events (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n run_id TEXT,\n event_json TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n PRIMARY KEY (session_id, seq),\n FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_trajectory_runtime_run\n ON trajectory_runtime_events(session_id, run_id, seq)\n WHERE run_id IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS acp_parent_stream_events (\n session_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n event_json TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n PRIMARY KEY (session_id, run_id, seq),\n FOREIGN KEY (session_id) REFERENCES \"session_windows\"(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_acp_parent_stream_run\n ON acp_parent_stream_events(run_id, seq);\n\nCREATE TABLE IF NOT EXISTS transcript_event_identities (\n session_id TEXT NOT NULL,\n event_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n event_type TEXT,\n parent_id TEXT,\n message_idempotency_key TEXT,\n created_at INTEGER NOT NULL,\n PRIMARY KEY (session_id, event_id),\n FOREIGN KEY (session_id, seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_message_idempotency\n ON transcript_event_identities(session_id, message_idempotency_key)\n WHERE message_idempotency_key IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_transcript_event_identity_sequence\n ON transcript_event_identities(session_id, seq);\n\nCREATE INDEX IF NOT EXISTS idx_agent_transcript_event_parent\n ON transcript_event_identities(session_id, parent_id)\n WHERE parent_id IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_transcript_event_sequence\n ON transcript_event_identities(session_id, event_type, seq DESC);\n\nCREATE TABLE IF NOT EXISTS context_engine_turn_outbox (\n advancement_key TEXT NOT NULL PRIMARY KEY,\n engine_id TEXT NOT NULL,\n owner_plugin_id TEXT,\n session_id TEXT NOT NULL,\n payload_json TEXT NOT NULL,\n attempt_count INTEGER NOT NULL DEFAULT 0,\n last_attempt_at INTEGER,\n last_error TEXT,\n created_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_context_engine_turn_outbox_engine\n ON context_engine_turn_outbox(engine_id, created_at);\n\nCREATE TABLE IF NOT EXISTS cache_entries (\n scope TEXT NOT NULL,\n key TEXT NOT NULL,\n value_json TEXT,\n blob BLOB,\n expires_at INTEGER,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (scope, key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_cache_expiry\n ON cache_entries(scope, expires_at, key)\n WHERE expires_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_cache_updated\n ON cache_entries(scope, updated_at DESC, key);\n\nCREATE TABLE IF NOT EXISTS auth_profile_store (\n store_key TEXT NOT NULL PRIMARY KEY,\n store_json TEXT NOT NULL,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS auth_profile_state (\n state_key TEXT NOT NULL PRIMARY KEY,\n state_json TEXT NOT NULL,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_sources (\n id INTEGER PRIMARY KEY,\n path TEXT NOT NULL,\n source TEXT NOT NULL DEFAULT 'memory',\n hash TEXT NOT NULL,\n mtime REAL NOT NULL,\n size INTEGER NOT NULL,\n UNIQUE (path, source)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_chunks (\n chunk_rowid INTEGER PRIMARY KEY,\n id TEXT NOT NULL UNIQUE,\n path TEXT NOT NULL,\n source TEXT NOT NULL DEFAULT 'memory',\n start_line INTEGER NOT NULL,\n end_line INTEGER NOT NULL,\n hash TEXT NOT NULL,\n model TEXT NOT NULL,\n text TEXT NOT NULL,\n embedding BLOB NOT NULL,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_chunk_recall_metadata (\n chunk_id TEXT PRIMARY KEY,\n importance INTEGER CHECK (importance IS NULL OR importance BETWEEN 1 AND 10),\n triggers TEXT,\n project_key TEXT,\n FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_chunk_provenance (\n chunk_id TEXT PRIMARY KEY,\n origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),\n session_kind TEXT NOT NULL CHECK (session_kind IN ('interactive', 'cron', 'heartbeat', 'subagent', 'unknown')),\n observed_at INTEGER NOT NULL,\n supersedes_key TEXT,\n FOREIGN KEY (chunk_id) REFERENCES memory_index_chunks(id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_entry_origins (\n entry_key TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n session_id TEXT NOT NULL,\n session_key TEXT,\n origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),\n observed_at INTEGER NOT NULL,\n PRIMARY KEY (entry_key, agent_id, session_id)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_session_tombstones (\n session_id TEXT NOT NULL PRIMARY KEY,\n agent_id TEXT NOT NULL,\n reason TEXT NOT NULL,\n created_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_embedding_cache (\n provider TEXT NOT NULL,\n model TEXT NOT NULL,\n provider_key TEXT NOT NULL,\n hash TEXT NOT NULL,\n embedding BLOB NOT NULL,\n dims INTEGER,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (provider, model, provider_key, hash)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS memory_index_state (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n revision INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS standing_intents (\n intent_key INTEGER PRIMARY KEY,\n id TEXT NOT NULL UNIQUE,\n description TEXT NOT NULL,\n trigger_keywords TEXT NOT NULL,\n trigger_embedding TEXT,\n channel_scope TEXT,\n sender_scope TEXT,\n creator_sender TEXT CHECK (creator_sender IS NULL OR length(trim(creator_sender)) > 0),\n status TEXT NOT NULL CHECK (status IN ('pending', 'armed', 'fired', 'done', 'cancelled', 'expired')),\n expires_at INTEGER NOT NULL,\n max_fires INTEGER NOT NULL CHECK (max_fires > 0),\n fire_count INTEGER NOT NULL DEFAULT 0 CHECK (fire_count >= 0),\n cooldown_seconds INTEGER NOT NULL DEFAULT 86400 CHECK (cooldown_seconds >= 0),\n last_fired_at INTEGER,\n created_at INTEGER NOT NULL,\n source_session_id TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_standing_intents_lifecycle\n ON standing_intents(status, expires_at, last_fired_at);\n\nCREATE INDEX IF NOT EXISTS idx_standing_intents_scope\n ON standing_intents(status, channel_scope, sender_scope);\n\nCREATE VIRTUAL TABLE IF NOT EXISTS standing_intents_fts USING fts5(\n trigger_keywords,\n content = 'standing_intents',\n content_rowid = 'intent_key',\n tokenize = 'unicode61 remove_diacritics 2'\n);\n\nCREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_insert\nAFTER INSERT ON standing_intents\nBEGIN\n INSERT INTO standing_intents_fts(rowid, trigger_keywords)\n VALUES (new.intent_key, new.trigger_keywords);\nEND;\n\nCREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_delete\nAFTER DELETE ON standing_intents\nBEGIN\n INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)\n VALUES ('delete', old.intent_key, old.trigger_keywords);\nEND;\n\nCREATE TRIGGER IF NOT EXISTS standing_intents_fts_after_update\nAFTER UPDATE OF trigger_keywords ON standing_intents\nBEGIN\n INSERT INTO standing_intents_fts(standing_intents_fts, rowid, trigger_keywords)\n VALUES ('delete', old.intent_key, old.trigger_keywords);\n INSERT INTO standing_intents_fts(rowid, trigger_keywords)\n VALUES (new.intent_key, new.trigger_keywords);\nEND;\n\nCREATE TABLE IF NOT EXISTS session_transcript_index_state (\n session_id TEXT NOT NULL PRIMARY KEY,\n indexed_seq INTEGER NOT NULL,\n leaf_event_id TEXT,\n needs_rebuild INTEGER NOT NULL DEFAULT 0,\n active_event_count INTEGER NOT NULL DEFAULT 0,\n active_message_count INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL,\n FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_transcript_active_events (\n session_id TEXT NOT NULL,\n active_position INTEGER NOT NULL CHECK (active_position >= 0),\n event_seq INTEGER NOT NULL,\n message_position INTEGER CHECK (message_position IS NULL OR message_position >= 0),\n context_eligible INTEGER,\n PRIMARY KEY (session_id, active_position),\n FOREIGN KEY (session_id, event_seq) REFERENCES transcript_events(session_id, seq) ON DELETE CASCADE\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_event_seq\n ON session_transcript_active_events(session_id, event_seq);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_agent_transcript_active_messages\n ON session_transcript_active_events(session_id, message_position)\n WHERE message_position IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_agent_transcript_context_pending\n ON session_transcript_active_events(session_id)\n WHERE context_eligible IS NULL;\n\nCREATE VIRTUAL TABLE IF NOT EXISTS session_transcript_fts USING fts5(\n text,\n session_id UNINDEXED,\n message_id UNINDEXED,\n role UNINDEXED,\n timestamp UNINDEXED,\n tokenize = 'unicode61 remove_diacritics 2'\n);\n\nCREATE TABLE IF NOT EXISTS session_transcript_fts_rows (\n id INTEGER PRIMARY KEY,\n session_id TEXT NOT NULL,\n message_id TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_session_transcript_fts_rows_session_message\n ON session_transcript_fts_rows(session_id, message_id);\n\nCREATE TRIGGER IF NOT EXISTS session_transcript_fts_rows_after_delete\nAFTER DELETE ON session_transcript_fts_rows\nBEGIN\n DELETE FROM session_transcript_fts WHERE rowid = OLD.id;\nEND;\n\nINSERT OR IGNORE INTO memory_index_state (id, revision) VALUES (1, 0);\n\nCREATE TRIGGER IF NOT EXISTS memory_index_sources_revision_after_insert\nAFTER INSERT ON memory_index_sources\nBEGIN\n UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS memory_index_sources_revision_after_update\nAFTER UPDATE ON memory_index_sources\nBEGIN\n UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS memory_index_sources_revision_after_delete\nAFTER DELETE ON memory_index_sources\nBEGIN\n UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS memory_index_chunks_revision_after_insert\nAFTER INSERT ON memory_index_chunks\nBEGIN\n UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS memory_index_chunks_revision_after_update\nAFTER UPDATE ON memory_index_chunks\nBEGIN\n UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1;\nEND;\n\nCREATE TRIGGER IF NOT EXISTS memory_index_chunks_revision_after_delete\nAFTER DELETE ON memory_index_chunks\nBEGIN\n UPDATE memory_index_state SET revision = revision + 1 WHERE id = 1;\nEND;\n\nCREATE INDEX IF NOT EXISTS idx_memory_embedding_cache_updated_at\n ON memory_embedding_cache(updated_at);\n\nCREATE INDEX IF NOT EXISTS idx_memory_index_sources_source\n ON memory_index_sources(source);\n\nCREATE INDEX IF NOT EXISTS idx_memory_index_chunks_path_source\n ON memory_index_chunks(path, source);\n\nCREATE INDEX IF NOT EXISTS idx_memory_index_chunks_path\n ON memory_index_chunks(path);\n\nCREATE INDEX IF NOT EXISTS idx_memory_index_chunks_source\n ON memory_index_chunks(source);\n\n-- Accepted input stays outside the active transcript until its exact turn owns execution.\nCREATE TABLE IF NOT EXISTS session_pending_inputs (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n input_id TEXT NOT NULL UNIQUE,\n session_key TEXT NOT NULL,\n session_id TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n run_id TEXT NOT NULL,\n request_hash TEXT NOT NULL,\n message_json TEXT NOT NULL,\n lifecycle_generation TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('queued', 'interrupted', 'cancelled')),\n accepted_at INTEGER NOT NULL,\n consumed_event_id TEXT,\n UNIQUE (session_id, idempotency_key),\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,\n FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_agent_session_pending_inputs_session\n ON session_pending_inputs(session_key, session_id, seq DESC);\n\n-- Processing completion is separate from input consumption; neither schedules replay.\nCREATE TABLE IF NOT EXISTS session_input_completions (\n session_key TEXT NOT NULL,\n session_id TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n run_id TEXT NOT NULL,\n request_hash TEXT NOT NULL,\n outcome_json TEXT NOT NULL,\n succeeded INTEGER NOT NULL CHECK (succeeded IN (0, 1)),\n completed_at INTEGER NOT NULL,\n PRIMARY KEY (session_id, idempotency_key),\n FOREIGN KEY (session_key) REFERENCES session_nodes(session_key) ON DELETE CASCADE,\n FOREIGN KEY (session_id) REFERENCES session_windows(session_id) ON DELETE CASCADE\n) STRICT;\n";
}));
var init_openclaw_agent_context_engine_turn_outbox_schema = __esmMin((() => {
init_sqlite_transaction();
}));
//#endregion
//#region src/state/openclaw-agent-db-additive-columns.ts
var SESSION_OWNER_COLUMN_DEFINITIONS, LEGACY_ACP_MIGRATION_COLUMN_DEFINITION, CANONICAL_READY_COLUMN_DEFINITION, FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS;
var init_openclaw_agent_db_additive_columns = __esmMin((() => {
SESSION_OWNER_COLUMN_DEFINITIONS = [
{
columnName: "owner_actor_type",
dataType: "TEXT",
tableName: "session_nodes"
},
{
columnName: "owner_actor_id",
dataType: "TEXT",
tableName: "session_nodes"
},
{
columnName: "owner_assigned_by_type",
dataType: "TEXT",
tableName: "session_nodes"
},
{
columnName: "owner_assigned_by_id",
dataType: "TEXT",
tableName: "session_nodes"
},
{
columnName: "owner_assigned_at",
dataType: "INTEGER",
tableName: "session_nodes"
}
];
LEGACY_ACP_MIGRATION_COLUMN_DEFINITION = {
columnName: "legacy_acp_migration_json",
dataType: "TEXT",
tableName: "session_nodes"
};
CANONICAL_READY_COLUMN_DEFINITION = {
columnName: "canonical_ready",
dataType: "TEXT",
tableName: "session_key_contract"
};
FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS = [
...SESSION_OWNER_COLUMN_DEFINITIONS,
LEGACY_ACP_MIGRATION_COLUMN_DEFINITION,
CANONICAL_READY_COLUMN_DEFINITION
];
}));
var init_openclaw_agent_db_contract = __esmMin((() => {}));
var init_openclaw_agent_goal_operations_schema = __esmMin((() => {
init_sqlite_transaction();
}));
var init_openclaw_agent_message_tool_outcome_schema = __esmMin((() => {
init_sqlite_transaction();
}));
//#endregion
//#region src/state/openclaw-state-db-schema-helpers.ts
function tableHasColumn(db, tableName, columnName) {
return tableHasColumns(db, tableName, [columnName]);
}
function tableHasColumns(db, tableName, columnNames) {
const existing = readTableColumns(db, tableName);
return columnNames.every((columnName) => existing.has(columnName));
}
function readTableColumns(db, tableName) {
const rows = db.prepare(`PRAGMA table_info(${tableName})`).all();
return new Set(rows.flatMap((row) => typeof row.name === "string" ? [row.name] : []));
}
/** Inspect only failed queries; native unavailability must not become a schema refusal. */
function classifySqliteTableReadError(db, tableName, columnNames, error) {
if (sqlitePrimaryResultCode(error) !== 1) return error;
try {
const existing = readTableColumns(db, tableName);
if (existing.size > 0 && columnNames.some((column) => !existing.has(column))) return new SqliteSchemaMismatchError(`SQLite table ${tableName} is missing required columns; run openclaw doctor --fix to repair it.`, { cause: error });
} catch {}
return error;
}
function tablePrimaryKeyColumns(db, tableName) {
return db.prepare(`PRAGMA table_info(${tableName})`).all().filter((row) => Number(row.pk ?? 0) > 0 && typeof row.name === "string").toSorted((left, right) => Number(left.pk ?? 0) - Number(right.pk ?? 0)).map((row) => row.name);
}
function tableExists(db, tableName) {
const schema = getAdmittedSqliteSchemaFacts(db);
if (schema) return schema.tables.has(tableName);
return executeWithCachedStatement(db, "SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?", [tableName], (statement) => statement.get(tableName))?.ok === 1;
}
var init_openclaw_state_db_schema_helpers = __esmMin((() => {
init_kysely_sync_cache_state();
init_sqlite_error_diagnostics();
init_sqlite_schema_facts();
init_sqlite_schema_issues();
}));
var init_openclaw_agent_pending_inputs_schema = __esmMin((() => {
init_sqlite_transaction();
init_openclaw_state_db_schema_helpers();
}));
//#endregion
//#region src/state/openclaw-agent-board-schema.ts
var OPENCLAW_AGENT_BOARD_SCHEMA_SQL, OPENCLAW_AGENT_SCHEMA_WITHOUT_BOARD_SQL;
var init_openclaw_agent_board_schema = __esmMin((() => {
init_sqlite_schema_sql();
init_openclaw_agent_schema();
OPENCLAW_AGENT_BOARD_SCHEMA_SQL = extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_SQL, "board_tabs", {
endMarker: "CREATE TABLE IF NOT EXISTS session_progress_cards (",
includeEndMarker: false,
errorMessage: "OpenClaw agent board schema markers are missing from the canonical schema."
});
OPENCLAW_AGENT_SCHEMA_WITHOUT_BOARD_SQL = OPENCLAW_AGENT_SCHEMA_SQL.replace(OPENCLAW_AGENT_BOARD_SCHEMA_SQL, "");
})), SESSION_PROGRESS_CARDS_TABLE, AGENT_PROGRESS_CARD_SCHEMA_SQL;
var init_openclaw_agent_progress_card_schema = __esmMin((() => {
init_sqlite_schema_sql();
init_openclaw_agent_board_schema();
SESSION_PROGRESS_CARDS_TABLE = "session_progress_cards";
AGENT_PROGRESS_CARD_SCHEMA_SQL = extractSqliteTableSchema(OPENCLAW_AGENT_SCHEMA_WITHOUT_BOARD_SQL, SESSION_PROGRESS_CARDS_TABLE, {
endMarker: "CREATE TABLE IF NOT EXISTS heartbeat_outcomes (",
includeEndMarker: false,
errorMessage: "OpenClaw agent progress-card schema markers are missing."
});
OPENCLAW_AGENT_SCHEMA_WITHOUT_BOARD_SQL.replace(AGENT_PROGRESS_CARD_SCHEMA_SQL, "");
}));
var init_openclaw_agent_session_transcript_archive_schema = __esmMin((() => {
init_sqlite_transaction();
})), STANDING_INTENTS_FTS_SHADOW_TABLES;
var init_openclaw_agent_standing_intents_schema = __esmMin((() => {
init_sqlite_transaction();
STANDING_INTENTS_FTS_SHADOW_TABLES = [
"standing_intents_fts_config",
"standing_intents_fts_data",
"standing_intents_fts_docsize",
"standing_intents_fts_idx"
];
}));
var init_openclaw_agent_db_schema_compatibility = __esmMin((() => {
init_memory_schema_provenance();
init_memory_schema_recall();
init_memory_schema();
init_openclaw_agent_context_engine_turn_outbox_schema();
init_openclaw_agent_db_additive_columns();
init_openclaw_agent_db_contract();
init_openclaw_agent_goal_operations_schema();
init_openclaw_agent_message_tool_outcome_schema();
init_openclaw_agent_pending_inputs_schema();
init_openclaw_agent_progress_card_schema();
init_openclaw_agent_session_transcript_archive_schema();
init_openclaw_agent_standing_intents_schema();
[...STANDING_INTENTS_FTS_SHADOW_TABLES], [...FIRST_USE_ADDITIVE_AGENT_COLUMN_DEFINITIONS.map(({ columnName, tableName }) => `${tableName}.${columnName}`)];
}));
//#endregion
//#region src/state/session-metadata-unavailable-error.ts
var SessionMetadataUnavailableError;
var init_session_metadata_unavailable_error = __esmMin((() => {
SessionMetadataUnavailableError = class extends Error {
constructor(reason, options, missingTables = []) {
super(`Session metadata unavailable (${[reason, ...missingTables].join(": ")}); retry after the agent store is ready.`, options);
this.reason = reason;
this.missingTables = missingTables;
this.name = "SessionMetadataUnavailableError";
}
};
}));
var init_openclaw_agent_db_read_error = __esmMin((() => {
init_sqlite_error_diagnostics();
init_sqlite_schema_contract();
init_global_singleton();
init_openclaw_agent_db_schema_compatibility();
resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseSettledReadOpenFailures"), () => /* @__PURE__ */ new WeakSet());
}));
var init_openclaw_agent_canonical_validation_schema = __esmMin((() => {
init_kysely_sync_cache_state();
init_node_sqlite();
init_sqlite_schema_contract();
init_sqlite_schema_facts();
init_global_singleton();
init_openclaw_agent_db_read_error();
resolveGlobalSingleton(Symbol.for("openclaw.agentCanonicalValidationSchemas"), () => /* @__PURE__ */ new WeakMap());
}));
var init_openclaw_agent_db_identity = __esmMin((() => {
init_sqlite_worker_identity();
init_global_singleton();
resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseIdentities"), () => /* @__PURE__ */ new WeakMap());
}));
//#endregion
//#region src/state/openclaw-agent-canonical-validation-receipt.ts
var init_openclaw_agent_canonical_validation_receipt = __esmMin((() => {
init_kysely_sync();
init_sqlite_post_commit();
init_openclaw_agent_canonical_validation_schema();
init_openclaw_agent_db_additive_columns();
init_openclaw_agent_db_identity();
init_openclaw_state_db_schema_helpers();
}));
var init_openclaw_agent_db_resources = __esmMin((() => {
init_path_guards();
init_global_singleton();
init_openclaw_state_db_async_lifecycle();
resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseAsyncResources"), () => ({
active: /* @__PURE__ */ new Set(),
closing: /* @__PURE__ */ new Map(),
selections: /* @__PURE__ */ new Map()
}));
}));
//#endregion
//#region src/state/openclaw-agent-db-validation-cache.ts
function invalidateOpenClawAgentDatabaseValidation(pathname, identity) {
const resolved = resolveDatabasePathKey(pathname);
const currentIdentity = identity ?? validatedPaths.get(resolved)?.validation?.identity;
const paths = /* @__PURE__ */ new Set([resolved]);
if (currentIdentity) {
for (const [candidate, entry] of validatedPaths) if (entry.validation?.identity === currentIdentity) paths.add(candidate);
}
for (const candidate of paths) {
const entry = validatedPaths.get(candidate);
const validation = entry?.validation;
if (validation) Atomics.store(new Int32Array(validation.valid), 0, 0);
validatedPaths.set(candidate, {
agentId: entry?.agentId,
validation,
integrityVerified: false,
revoked: true
});
}
}
function clearOpenClawAgentDatabaseValidationCache(rootPath) {
const rootKey = rootPath === void 0 ? void 0 : resolveDatabasePathKey(rootPath);
for (const pathname of validatedPaths.keys()) if (rootKey === void 0 || isPathInside$1(rootKey, pathname)) {
invalidateOpenClawAgentDatabaseValidation(pathname);
validatedPaths.delete(pathname);
}
}
var validatedPaths;
var init_openclaw_agent_db_validation_cache = __esmMin((() => {
init_kysely_sync_cache_state();
init_path_guards();
init_sqlite_post_commit();
init_sqlite_user_version();
init_sqlite_worker_identity();
init_global_singleton();
init_openclaw_agent_canonical_validation_receipt();
init_openclaw_agent_canonical_validation_schema();
init_openclaw_agent_db_identity();
init_openclaw_agent_db_resources();
validatedPaths = resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseValidatedPaths"), () => /* @__PURE__ */ new Map(), () => clearOpenClawAgentDatabaseValidationCache());
resolveGlobalSingleton(Symbol.for("openclaw.agentDatabaseValidationBindings"), () => /* @__PURE__ */ new WeakMap());
}));
//#endregion
//#region src/state/openclaw-quarantine-store.ts
function createOpenClawDatabaseVerificationError(kind, pathname, storedError) {
const error = /* @__PURE__ */ new Error(`OpenClaw ${kind} database ${pathname} is quarantined after integrity verification failed: ${storedError ?? "unknown integrity error"}. Restore the database from a backup or repair it, then run openclaw doctor --fix to clear the quarantine. See ${OPENCLAW_DATABASE_SCHEMA_DOCS_URL}.`);
error.name = "SqliteIntegrityError";
return error;
}
function readQuarantineSchemaVersion(database, storePath) {
const userVersion = database.prepare("PRAGMA user_version").get()?.user_version;
if (typeof userVersion !== "number" || !Number.isInteger(userVersion)) throw new Error(`OpenClaw quarantine store ${storePath} has an invalid schema version.`);
return userVersion;
}
/** Read one authoritative quarantine decision without creating the store. */
function readOpenClawDatabaseQuarantine(pathname, options = {}) {
const storePath = resolveQuarantineStorePath(options.env ?? process.env);
if (!existsSync(storePath)) return;
const database = openNodeSqliteDatabase(storePath);
let outcome;
try {
outcome = { value: readQuarantineDecision(database, pathname, storePath) };
} catch (error) {
outcome = { error };
}
try {
database.close();
} catch (closeError) {
throw new OpenClawQuarantineReadCleanupError("error" in outcome ? [outcome.error, closeError] : [closeError], "value" in outcome ? outcome.value : void 0);
}
if ("error" in outcome) throw outcome.error;
return outcome.value;
}
function readQuarantineDecision(database, pathname, storePath) {
database.exec(`PRAGMA busy_timeout = ${OPENCLAW_QUARANTINE_BUSY_TIMEOUT_MS};`);
const userVersion = readQuarantineSchemaVersion(database, storePath);
if (userVersion === 0) return;
if (userVersion > OPENCLAW_QUARANTINE_SCHEMA_VERSION) throw new Error(`OpenClaw quarantine store ${storePath} uses newer schema version ${userVersion}.`);
const generationColumn = userVersion >= 2 ? ", verified_generation" : "";
const row = database.prepare(`SELECT kind, reason, quarantined_at${generationColumn} FROM quarantined_databases WHERE path = ? LIMIT 1`).get(path.resolve(pathname));
if (!row) return;
if (row.kind !== "agent" && row.kind !== "state" || typeof row.reason !== "string" || typeof row.quarantined_at !== "number" || !Number.isInteger(row.quarantined_at) || row.verified_generation !== void 0 && row.verified_generation !== null && typeof row.verified_generation !== "string") throw new Error(`OpenClaw quarantine store ${storePath} contains an invalid row.`);
if (typeof row.verified_generation === "string") {
let verifiedGeneration;
try {
verifiedGeneration = parseSqliteFileGeneration(row.verified_generation);
} catch {
throw new Error(`OpenClaw quarantine store ${storePath} contains an invalid row.`);
}
try {
const currentGeneration = readStableSqliteFileGeneration(path.resolve(pathname));
if (!sameSqliteFileGeneration(verifiedGeneration, currentGeneration)) return;
} catch {
return;
}
}
return {
kind: row.kind,
quarantinedAt: row.quarantined_at,
reason: row.reason
};
}
/** Runtime opens refuse recorded damage while tolerating a broken quarantine index. */
function readOpenClawDatabaseQuarantineFailure(kind, pathname, options = {}) {
let quarantine;
let cleanupFailure;
try {
quarantine = readOpenClawDatabaseQuarantine(pathname, options);
} catch (error) {
if (!(error instanceof OpenClawQuarantineReadCleanupError)) return;
if (!error.quarantine) throw error;
quarantine = error.quarantine;
cleanupFailure = error;
}
if (!quarantine) return;
const failure = createOpenClawDatabaseVerificationError(kind, pathname, quarantine.reason);
if (cleanupFailure) failure.cause = cleanupFailure;
return failure;
}
var OPENCLAW_QUARANTINE_SCHEMA_VERSION, OPENCLAW_QUARANTINE_BUSY_TIMEOUT_MS;
var init_openclaw_quarantine_store = __esmMin((() => {
init_errno();
init_kysely_sync();
init_node_sqlite();
init_sqlite_file_generation();
init_sqlite_transaction();
init_version$1();
init_openclaw_agent_db_validation_cache();
init_openclaw_quarantine_error();
init_openclaw_state_db_contract();
init_openclaw_state_db_paths();
OPENCLAW_QUARANTINE_SCHEMA_VERSION = 2;
OPENCLAW_QUARANTINE_BUSY_TIMEOUT_MS = 5e3;
}));
//#endregion
//#region src/state/openclaw-state-db-borrow.ts
/** The canonical cache supplies identity and custody; this owner manages its native references. */
function createStateDatabaseRetainer(state, operations) {
const admit = (pathname, ownership) => {
const scope = getOpenClawDatabaseMaintenanceScope();
if (ownership === "cached-read") scope?.assertReadAdmission();
else scope?.assertAdmission();
operations.assertOpen(pathname, ownership);
return scope;
};
const retain = (database, scope, readOnly = false) => {
operations.capture(database.path).assertCurrent();
if (state.cachedDatabases.get(database.path) !== database || !database.db.isOpen) throw new Error("OpenClaw state database borrow requires its current canonical handle");
const owner = state.borrowers.get(database.db) ?? {
references: /* @__PURE__ */ new Set(),
retiring: false,
cleanupComplete: false
};
if (owner.retiring) throw new Error("OpenClaw state database native owner is retiring");
if (!readOnly) observeOpenClawDatabaseMaintenanceResource(database.db);
state.borrowers.set(database.db, owner);
const isCurrent = () => !scope || isOpenClawDatabaseMaintenanceResourceOwned(database.db, scope);
const reference = retainStateDatabaseReference({
owner,
retirement: readOnly ? void 0 : {
ordinary: scope === void 0,
isCurrent,
retire: () => {
if (!isCurrent()) {
owner.retiring = false;
return;
}
operations.retire(database, scope === void 0);
}
},
retainFailedClose: () => operations.retainFailed(database)
});
scope?.own(reference, "shared-references", () => reference.release());
return reference;
};
const findReadDatabase = (pathname, ownership) => {
const scope = admit(pathname, ownership);
const database = state.cachedDatabases.get(path.resolve(pathname));
return {
database: database?.db.isOpen ? database : void 0,
scope
};
};
const retainReadReference = (database, scope) => {
const reference = retain(database, scope, true);
const assertCurrent = () => {
if (state.cachedDatabases.get(database.path) !== database || !database.db.isOpen) throw new Error("Shared-state read lost its original native owner");
};
return {
assertCurrent,
observe() {
assertCurrent();
observeOpenClawDatabaseMaintenanceResource(database.db);
},
release() {
reference.release();
operations.touch(database);
}
};
};
return {
retain: (database) => retain(database, admit(database.path)),
retainForIndependentRead(pathname, ownership) {
const { database, scope } = findReadDatabase(pathname, ownership);
return database ? retainReadReference(database, scope) : void 0;
},
borrowForRead(pathname, ownership) {
const { database, scope } = findReadDatabase(pathname, ownership);
if (!database) return;
if (database.db.isTransaction) throw new Error("Asynchronous shared-state reads cannot run inside a native transaction");
return {
database,
...retainReadReference(database, scope)
};
}
};
}
function assertStateDatabaseBorrowersReleased(owner, pathname) {
if (owner?.references.size) throw new Error(`OpenClaw state database still has active native borrowers: ${pathname}`);
}
/** Preserve the requesting owner's retirement when the last reference is only a read pin. */
function retainStateDatabaseReference(params) {
const { owner } = params;
const reference = {};
owner.references.add(reference);
let released = false;
return { release() {
if (released || owner.cleanupComplete) {
released = true;
return;
}
owner.references.delete(reference);
if (owner.retirement && !owner.retirement.isCurrent()) {
owner.retirement = void 0;
owner.retiring = false;
}
if (params.retirement?.isCurrent() && !owner.retirement?.ordinary) owner.retirement = params.retirement;
if (owner.references.size > 0 || !owner.retirement) {
released = true;
return;
}
owner.retiring = true;
try {
owner.retirement.retire();
} catch (error) {
params.retainFailedClose();
throw error;
}
owner.retirement = void 0;
released = true;
} };
}
var init_openclaw_state_db_borrow = __esmMin((() => {
init_openclaw_state_db_async_lifecycle();
}));
//#endregion
//#region src/infra/sqlite-handle-lifecycle.ts
var SQLITE_IDLE_HANDLE_TTL_MS;
var init_sqlite_handle_lifecycle = __esmMin((() => {
SQLITE_IDLE_HANDLE_TTL_MS = 18e5;
}));
//#endregion
//#region src/state/openclaw-state-db-cache.idle.ts
/** Schedule native retirement against the canonical cache's handles and borrow pins. */
function createStateDatabaseIdleRetirement({ cachedDatabases, retainedDatabaseHandles, idleTimers, idleReferences, borrowers }, retire) {
const touch = (database) => {
if (!(cachedDatabases.get(database.path) === database && database.db.isOpen) && retainedDatabaseHandles.get(database.db) !== database) return;
const previous = idleTimers.get(database.db);
if (previous) {
previous.refresh();
return;
}
const timer = runInSqliteMaintenanceContext(() => setTimeout(() => {
idleTimers.delete(database.db);
try {
if (database.db.isOpen && (database.db.isTransaction || borrowers.get(database.db)?.references.size || idleReferences.get(database.db)?.size)) {
touch(database);
return;
}
retire(database, false, {
busyTimeoutMs: 0,
checkpointMode: "PASSIVE"
});
} catch (error) {
log$2.warn("Idle shared-state database cleanup failed", {
path: database.path,
error
});
touch(database);
}
}, SQLITE_IDLE_HANDLE_TTL_MS));
timer.unref();
idleTimers.set(database.db, timer);
};
return {
touch,
/** Retained consumers postpone idle eviction without blocking explicit retirement. */
retain(database) {
if (cachedDatabases.get(database.path) !== database || !database.db.isOpen || borrowers.get(database.db)?.retiring) throw new Error("OpenClaw state database idle retention requires its current canonical handle");
const references = idleReferences.get(database.db) ?? /* @__PURE__ */ new Set();
const reference = {};
references.add(reference);
idleReferences.set(database.db, references);
return () => {
if (!references.delete(reference)) return;
if (cachedDatabases.get(database.path) === database && database.db.isOpen) touch(database);
};
}
};
}
var log$2;
var init_openclaw_state_db_cache_idle = __esmMin((() => {
init_sqlite_handle_lifecycle();
init_sqlite_wal();
init_subsystem();
log$2 = createSubsystemLogger("state/db");
}));
//#endregion
//#region src/shared/lazy-promise.ts
/**
* Creates a small promise cache that dedupes concurrent loads and can be cleared manually.
*
* Rejections are evicted by default so transient dynamic-import/runtime failures can recover.
*/
function createLazyPromiseLoader(load, options = {}) {
let promise;
const createPromise = () => {
const loaded = Promise.resolve().then(load);
if (options.cacheRejections !== true) loaded.catch(() => {
if (promise === loaded) promise = void 0;
});
return loaded;
};
return {
load() {
promise ??= createPromise();
return promise;
},
peek() {
return promise;
},
clear() {
promise = void 0;
}
};
}
/** Creates a reusable function that resolves one cached promise at a time. */
function createLazyPromise(load, options) {
const loader = createLazyPromiseLoader(load, options);
return () => loader.load();
}
var init_lazy_promise = __esmMin((() => {}));
//#endregion
//#region src/shared/lazy-runtime.ts
var init_lazy_runtime = __esmMin((() => {
init_lazy_promise();
})), DEFAULT_TRUTHY, DEFAULT_FALSY;
var init_boolean = __esmMin((() => {
DEFAULT_TRUTHY = [
"true",
"1",
"yes",
"on"
];
DEFAULT_FALSY = [
"false",
"0",
"no",
"off"
];
new Set(DEFAULT_TRUTHY);
new Set(DEFAULT_FALSY);
}));
var init_env = __esmMin((() => {
init_lazy_runtime();
init_boolean();
createLazyPromise(() => Promise.resolve().then(() => (init_subsystem(), subsystem_exports)).then(({ createSubsystemLogger }) => createSubsystemLogger("env")), { cacheRejections: true });
}));
//#endregion
//#region src/infra/host-env-security-policy.json
var host_env_security_policy_default = {
blockedEverywhereKeys: [
"NODE_OPTIONS",
"NODE_PATH",
"NODE_REDIRECT_WARNINGS",
"NODE_REPL_EXTERNAL_MODULE",
"NODE_REPL_HISTORY",
"NODE_V8_COVERAGE",
"PYTHONHOME",
"PYTHONPATH",
"PERL5LIB",
"PERL5OPT",
"RUBYLIB",
"RUBYOPT",
"BASHOPTS",
"BASH_ENV",
"ENV",
"KSH_ENV",
"BROWSER",
"GIT_ALLOW_PROTOCOL",
"GIT_EDITOR",
"GIT_EXTERNAL_DIFF",
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_COMMON_DIR",
"GIT_EXEC_PATH",
"GIT_INDEX_FILE",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_NAMESPACE",
"GIT_PROTOCOL_FROM_USER",
"GIT_SEQUENCE_EDITOR",
"GIT_TEMPLATE_DIR",
"GIT_SSL_NO_VERIFY",
"GIT_SSL_CAINFO",
"GIT_SSL_CAPATH",
"CC",
"CPP",
"CXX",
"CXXCPP",
"CARGO_BUILD_RUSTC",
"CARGO_BUILD_RUSTC_WRAPPER",
"CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER",
"CARGO_BUILD_RUSTDOC",
"RUSTC",
"RUSTC_WRAPPER",
"RUSTC_WORKSPACE_WRAPPER",
"RUSTDOC",
"CMAKE_C_COMPILER",
"CMAKE_CXX_COMPILER",
"SHELL",
"SHELLOPTS",
"PS4",
"GCONV_PATH",
"IFS",
"SSLKEYLOGFILE",
"JAVA_OPTS",
"JAVA_TOOL_OPTIONS",
"_JAVA_OPTIONS",
"JDK_JAVA_OPTIONS",
"PYTHONBREAKPOINT",
"DOTNET_STARTUP_HOOKS",
"DOTNET_ADDITIONAL_DEPS",
"FPATH",
"GLIBC_TUNABLES",
"MAVEN_OPTS",
"MAKE",
"MAKEFLAGS",
"MFLAGS",
"SBT_OPTS",
"GRADLE_OPTS",
"ANT_OPTS",
"HGRCPATH",
"HGEDITOR",
"HGMERGE",
"EXINIT",
"VIMINIT",
"MYVIMRC",
"GVIMINIT",
"LUA_INIT",
"LUA_INIT_5_1",
"LUA_INIT_5_2",
"LUA_INIT_5_3",
"LUA_INIT_5_4",
"EMACSLOADPATH",
"RUBYSHELL",
"GIT_HOOK_PATH",
"SVN_EDITOR",
"SVN_SSH",
"BZR_EDITOR",
"BZR_SSH",
"BZR_PLUGIN_PATH",
"SUDO_ASKPASS",
"JULIA_EDITOR",
"CONFIG_SITE",
"CONFIG_SHELL",
"CMAKE_TOOLCHAIN_FILE",
"CATALINA_OPTS",
"CORECLR_PROFILER",
"HELM_PLUGINS",
"PACKER_PLUGIN_PATH",
"VAGRANT_VAGRANTFILE",
"ERL_AFLAGS",
"ERL_FLAGS",
"ERL_ZFLAGS",
"ELIXIR_ERL_OPTIONS",
"R_ENVIRON",
"R_PROFILE",
"R_ENVIRON_USER",
"R_PROFILE_USER",
"TCLLIBPATH",
"HOSTALIASES"
],
blockedOverrideOnlyKeys: [
"HOME",
"GRADLE_USER_HOME",
"ZDOTDIR",
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_COMMON_DIR",
"GIT_INDEX_FILE",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_NAMESPACE",
"GIT_SSH_COMMAND",
"GIT_SSH",
"GIT_PROXY_COMMAND",
"GIT_ASKPASS",
"GIT_SSL_NO_VERIFY",
"GIT_SSL_CAINFO",
"GIT_SSL_CAPATH",
"SSH_ASKPASS",
"LESSOPEN",
"LESSCLOSE",
"PAGER",
"MANPAGER",
"GIT_PAGER",
"EDITOR",
"VISUAL",
"FCEDIT",
"SUDO_EDITOR",
"PROMPT_COMMAND",
"HISTFILE",
"PERL5DB",
"PERL5DBCMD",
"OPENSSL_CONF",
"OPENSSL_ENGINES",
"PYTHONSTARTUP",
"WGETRC",
"CURL_HOME",
"CLASSPATH",
"CFLAGS",
"CGO_CFLAGS",
"CGO_LDFLAGS",
"GOFLAGS",
"MAKEFLAGS",
"MFLAGS",
"CORECLR_PROFILER_PATH",
"PHPRC",
"PHP_INI_SCAN_DIR",
"DENO_DIR",
"BUN_CONFIG_REGISTRY",
"YARN_RC_FILENAME",
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"NO_PROXY",
"NODE_TLS_REJECT_UNAUTHORIZED",
"NODE_EXTRA_CA_CERTS",
"SSL_CERT_FILE",
"SSL_CERT_DIR",
"REQUESTS_CA_BUNDLE",
"CURL_CA_BUNDLE",
"DOCKER_HOST",
"DOCKER_TLS_VERIFY",
"DOCKER_CERT_PATH",
"PIP_INDEX_URL",
"PIP_PYPI_URL",
"PIP_EXTRA_INDEX_URL",
"PIP_CONFIG_FILE",
"PIP_FIND_LINKS",
"PIP_TRUSTED_HOST",
"UV_INDEX",
"UV_INDEX_URL",
"UV_PYTHON",
"UV_EXTRA_INDEX_URL",
"UV_DEFAULT_INDEX",
"DOCKER_CONTEXT",
"LIBRARY_PATH",
"LDFLAGS",
"CPATH",
"C_INCLUDE_PATH",
"CPLUS_INCLUDE_PATH",
"OBJC_INCLUDE_PATH",
"GOPROXY",
"GONOSUMCHECK",
"GONOSUMDB",
"GONOPROXY",
"GOPRIVATE",
"GOENV",
"GOPATH",
"HGRCPATH",
"PYTHONUSERBASE",
"RUSTC_WRAPPER",
"RUSTFLAGS",
"RUSTUP_DIST_ROOT",
"RUSTUP_DIST_SERVER",
"RUSTUP_HOME",
"RUSTUP_TOOLCHAIN",
"RUSTUP_UPDATE_ROOT",
"CARGO_HOME",
"VIRTUAL_ENV",
"LUA_PATH",
"LUA_CPATH",
"GEM_HOME",
"GEM_PATH",
"BUNDLE_GEMFILE",
"COMPOSER_HOME",
"CONDA_DEFAULT_ENV",
"CONDA_PREFIX",
"CARGO_BUILD_RUSTC_WRAPPER",
"XDG_CACHE_HOME",
"XDG_CONFIG_DIRS",
"XDG_CONFIG_HOME",
"XDG_DATA_DIRS",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"XDG_STATE_HOME",
"AWS_CONFIG_FILE",
"KUBECONFIG",
"GOOGLE_APPLICATION_CREDENTIALS",
"AWS_SHARED_CREDENTIALS_FILE",
"AWS_WEB_IDENTITY_TOKEN_FILE",
"AZURE_AUTH_LOCATION",
"HELM_HOME",
"ANSIBLE_CONFIG",
"ANSIBLE_LIBRARY",
"ANSIBLE_CALLBACK_PLUGINS",
"ANSIBLE_COLLECTIONS_PATH",
"ANSIBLE_CONNECTION_PLUGINS",
"ANSIBLE_FILTER_PLUGINS",
"ANSIBLE_INVENTORY_PLUGINS",
"ANSIBLE_LOOKUP_PLUGINS",
"ANSIBLE_MODULE_UTILS",
"ANSIBLE_REMOTE_TEMP",
"ANSIBLE_ROLES_PATH",
"ANSIBLE_STRATEGY_PLUGINS",
"R_LIBS_USER",
"TF_CLI_CONFIG_FILE",
"TF_PLUGIN_CACHE_DIR",
"AMQP_URL",
"AWS_ACCESS_KEY_ID",
"AWS_CONTAINER_CREDENTIALS_FULL_URI",
"AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
"AWS_SECRET_ACCESS_KEY",
"AWS_SECURITY_TOKEN",
"AWS_SESSION_TOKEN",
"AZURE_CLIENT_ID",
"AZURE_CLIENT_SECRET",
"DATABASE_URL",
"GH_TOKEN",
"GITHUB_TOKEN",
"GITLAB_TOKEN",
"MONGODB_URI",
"NODE_AUTH_TOKEN",
"NPM_TOKEN",
"REDIS_URL",
"SSH_AUTH_SOCK",
"SYSTEMROOT",
"WINDIR"
],
allowedInheritedOverrideOnlyKeys: [
"ALL_PROXY",
"AWS_CONFIG_FILE",
"AWS_SHARED_CREDENTIALS_FILE",
"AWS_WEB_IDENTITY_TOKEN_FILE",
"AZURE_AUTH_LOCATION",
"CURL_CA_BUNDLE",
"DOCKER_CERT_PATH",
"DOCKER_CONTEXT",
"DOCKER_HOST",
"DOCKER_TLS_VERIFY",
"GIT_PAGER",
"GOOGLE_APPLICATION_CREDENTIALS",
"GRADLE_USER_HOME",
"HISTFILE",
"HOME",
"HTTPS_PROXY",
"HTTP_PROXY",
"KUBECONFIG",
"MANPAGER",
"NODE_EXTRA_CA_CERTS",
"NODE_TLS_REJECT_UNAUTHORIZED",
"NO_PROXY",
"PAGER",
"REQUESTS_CA_BUNDLE",
"RUSTUP_DIST_ROOT",
"RUSTUP_DIST_SERVER",
"RUSTUP_HOME",
"RUSTUP_TOOLCHAIN",
"RUSTUP_UPDATE_ROOT",
"SSH_AUTH_SOCK",
"SSL_CERT_DIR",
"SSL_CERT_FILE",
"SYSTEMROOT",
"WINDIR",
"XDG_CACHE_HOME",
"XDG_CONFIG_DIRS",
"XDG_CONFIG_HOME",
"XDG_DATA_DIRS",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"XDG_STATE_HOME",
"ZDOTDIR"
],
blockedOverridePrefixes: [
"GIT_CONFIG_",
"NPM_CONFIG_",
"CARGO_REGISTRIES_",
"TF_VAR_"
],
blockedPrefixes: [
"DYLD_",
"LD_",
"BASH_FUNC_"
]
};
//#endregion
//#region src/infra/host-env-security-policy.js
function sortUniqueUppercase(values) {
return Object.freeze(Array.from(new Set(values.map((value) => value.toUpperCase()))).toSorted((left, right) => left < right ? -1 : left > right ? 1 : 0));
}
function derivePolicyArrays(policy) {
const blockedEverywhereKeys = policy.blockedEverywhereKeys ?? [];
const blockedOverrideOnlyKeys = policy.blockedOverrideOnlyKeys ?? [];
const allowedInheritedOverrideOnlyKeys = policy.allowedInheritedOverrideOnlyKeys ?? [];
const allowedInheritedOverrideOnlyUpper = new Set(allowedInheritedOverrideOnlyKeys.map((value) => value.toUpperCase()));
const blockedPrefixes = policy.blockedPrefixes ?? [];
const blockedOverridePrefixes = policy.blockedOverridePrefixes ?? [];
const blockedInheritedPrefixes = policy.blockedInheritedPrefixes ?? blockedPrefixes;
return {
blockedInheritedKeys: sortUniqueUppercase([...blockedEverywhereKeys, ...blockedOverrideOnlyKeys.filter((value) => !allowedInheritedOverrideOnlyUpper.has(value.toUpperCase()))]),
blockedInheritedPrefixes: sortUniqueUppercase(blockedInheritedPrefixes),
blockedKeys: sortUniqueUppercase(blockedEverywhereKeys),
blockedOverrideKeys: sortUniqueUppercase(blockedOverrideOnlyKeys),
blockedPrefixes: sortUniqueUppercase(blockedPrefixes),
blockedOverridePrefixes: sortUniqueUppercase(blockedOverridePrefixes)
};
}
/**
* Normalizes raw host environment policy JSON into immutable lookup arrays.
*/
function loadHostEnvSecurityPolicy(rawPolicy = host_env_security_policy_default) {
const derived = derivePolicyArrays(rawPolicy);
return Object.freeze({
blockedEverywhereKeys: Object.freeze(rawPolicy.blockedEverywhereKeys ?? []),
blockedOverrideOnlyKeys: Object.freeze(rawPolicy.blockedOverrideOnlyKeys ?? []),
allowedInheritedOverrideOnlyKeys: Object.freeze(rawPolicy.allowedInheritedOverrideOnlyKeys ?? []),
blockedInheritedKeys: derived.blockedInheritedKeys,
blockedInheritedPrefixes: derived.blockedInheritedPrefixes,
blockedPrefixes: derived.blockedPrefixes,
blockedOverridePrefixes: derived.blockedOverridePrefixes,
blockedKeys: derived.blockedKeys,
blockedOverrideKeys: derived.blockedOverrideKeys
});
}
var HOST_ENV_SECURITY_POLICY;
var init_host_env_security_policy = __esmMin((() => {
HOST_ENV_SECURITY_POLICY = loadHostEnvSecurityPolicy();
}));
var init_host_env_security = __esmMin((() => {
init_host_env_security_policy();
new Set(HOST_ENV_SECURITY_POLICY.blockedKeys);
new Set(HOST_ENV_SECURITY_POLICY.blockedInheritedKeys);
new Set(HOST_ENV_SECURITY_POLICY.blockedOverrideKeys);
new AsyncLocalStorage();
}));
//#endregion
//#region src/config/version.ts
var init_version = __esmMin((() => {
init_semver();
}));
//#endregion
//#region src/config/future-version-guard.ts
var init_future_version_guard = __esmMin((() => {
init_version$1();
init_version();
}));
//#endregion
//#region src/config/config-env-values.ts
function findCaseInsensitiveEnvKey(env, key) {
if (Object.hasOwn(env, key)) return key;
const upperKey = key.toUpperCase();
return Object.keys(env).find((candidate) => candidate.toUpperCase() === upperKey);
}
var init_config_env_values = __esmMin((() => {
init_env();
init_host_env_security();
init_env_substitution();
init_future_version_guard();
}));
//#endregion
//#region src/config/config-env-vars.ts
function resolveAppliedConfigEnvOwnership(env) {
return {
...appliedConfigEnvOwnership.get(env),
...env === process.env ? publishedConfigRuntimeEnvState.ownedEnv : {}
};
}
function cloneEnvWithPlatformSemantics(env) {
const cloned = { ...env };
const ownedEnv = resolveAppliedConfigEnvOwnership(env);
if (process.platform !== "win32") {
appliedConfigEnvOwnership.set(cloned, ownedEnv);
return cloned;
}
const proxy = new Proxy(cloned, {
deleteProperty(target, property) {
if (typeof property !== "string") return Reflect.deleteProperty(target, property);
const key = findCaseInsensitiveEnvKey(target, property);
return key ? Reflect.deleteProperty(target, key) : true;
},
get(target, property, receiver) {
if (typeof property !== "string") return Reflect.get(target, property, receiver);
const key = findCaseInsensitiveEnvKey(target, property);
return key ? target[key] : Reflect.get(target, property, receiver);
},
getOwnPropertyDescriptor(target, property) {
if (typeof property !== "string") return Reflect.getOwnPropertyDescriptor(target, property);
const key = findCaseInsensitiveEnvKey(target, property);
if (!key) return;
return {
configurable: true,
enumerable: true,
value: target[key],
writable: true
};
},
has(target, property) {
return typeof property === "string" ? findCaseInsensitiveEnvKey(target, property) !== void 0 : Reflect.has(target, property);
},
set(target, property, value) {
if (typeof property !== "string") return Reflect.set(target, property, value);
target[findCaseInsensitiveEnvKey(target, property) ?? property] = value;
return true;
}
});
appliedConfigEnvOwnership.set(proxy, ownedEnv);
return proxy;
}
var appliedConfigEnvOwnership, publishedConfigRuntimeEnvState;
var init_config_env_vars = __esmMin((() => {
init_env();
init_config_env_values();
appliedConfigEnvOwnership = /* @__PURE__ */ new WeakMap();
new AsyncLocalStorage();
publishedConfigRuntimeEnvState = {
generation: 0,
ownedEnv: {},
sourceConfig: null
};
}));
//#endregion
//#region src/infra/gateway-supervision.ts
function isGatewayExternallySupervised(env = process.env) {
return env[GATEWAY_SUPERVISOR_MODE_ENV]?.trim().toLowerCase() === "external";
}
var GATEWAY_SUPERVISOR_MODE_ENV;
var init_gateway_supervision = __esmMin((() => {
init_paths$1();
GATEWAY_SUPERVISOR_MODE_ENV = "OPENCLAW_SUPERVISOR_MODE";
}));
//#endregion
//#region src/state/openclaw-state-db-schema-policy.ts
function canonicalPath(pathname) {
const resolved = path.resolve(pathname);
try {
return realpathSync.native(resolved);
} catch (error) {
if (hasErrnoCode(error, "ENOENT")) return resolved;
throw error;
}
}
function assertSchemaScopeActive(scope) {
if (scope && !scope.active) throw new Error("Existing shared-state schema admission has ended.");
}
function getExistingOpenClawStateSchemaPath() {
const scope = schemaPolicies.scopes.getStore();
assertSchemaScopeActive(scope);
return scope?.path;
}
/** Admit this source once; retained reads only need the original scope's live lifetime. */
function captureOpenClawStateSchemaReadAdmission(pathname) {
const scope = schemaPolicies.scopes.getStore();
if (!scope) return;
isExistingOpenClawStateSchema(pathname);
return {
path: scope.path,
assertCurrent: () => assertSchemaScopeActive(scope)
};
}
/** Check supplied and cached handles before exposing them to another admission policy. */
function isExistingOpenClawStateSchema(pathname, database) {
const scopedPath = getExistingOpenClawStateSchemaPath();
const scope = schemaPolicies.scopes.getStore();
const admittedPath = database && schemaPolicies.existingDatabases.get(database);
const resolvedPath = path.resolve(pathname);
const existing = scopedPath !== void 0 && (scopedPath === resolvedPath || scope?.canonicalPath === resolvedPath || scope?.canonicalPath === canonicalPath(resolvedPath));
if (scopedPath && !existing) throw new Error(`Existing shared-state schema admission is bound to ${scopedPath}, not ${pathname}.`);
if (admittedPath && (!existing || admittedPath !== scope?.canonicalPath)) throw new Error(`Shared-state database ${pathname} was admitted without schema repair; close its existing handle before ordinary admission.`);
return existing;
}
/** The cache owns the handle inventory, including owners retained after failed cleanup. */
function assertExistingOpenClawStateSchemaCacheAdmission(pathname, cache) {
const scopedPath = getExistingOpenClawStateSchemaPath();
const scope = schemaPolicies.scopes.getStore();
const requested = path.resolve(pathname);
let resolved = scope && (scopedPath === requested || scope.canonicalPath === requested) ? scope.canonicalPath : void 0;
for (const databases of [cache.cachedDatabases, cache.retainedDatabaseHandles]) for (const { db } of databases.values()) {
const admittedPath = schemaPolicies.existingDatabases.get(db);
if (admittedPath && db.isOpen) {
resolved ??= canonicalPath(pathname);
if (admittedPath === resolved) isExistingOpenClawStateSchema(pathname, db);
}
}
}
function assertOpenClawStateSchemaRepairAllowed(pathname) {
if (isExistingOpenClawStateSchema(pathname)) throw new Error(`Shared-state schema repair is owned by the existing installation at ${pathname}; update that installation before retrying the managed node.`);
}
var schemaPolicies;
var init_openclaw_state_db_schema_policy = __esmMin((() => {
init_errno();
init_global_singleton();
schemaPolicies = resolveGlobalSingleton(Symbol.for("openclaw.stateDatabaseSchemaPolicies"), () => ({
scopes: new AsyncLocalStorage(),
existingDatabases: /* @__PURE__ */ new WeakMap()
}));
}));
//#endregion
//#region src/state/openclaw-state-worker-context.capture.ts
/** Capture read authority without constructing a worker environment. */
function captureOpenClawStateReadContextWithAdmission(pathname, captureAdmission) {
const schema = captureOpenClawStateSchemaReadAdmission(pathname);
const capturedAdmission = captureAdmission(pathname);
let admission = capturedAdmission;
let runInCapturedSchemaScope;
if (schema) {
const inCapturedScope = AsyncLocalStorage.snapshot();
admission = {
databasePath: capturedAdmission.databasePath,
coordinationKey: capturedAdmission.coordinationKey,
get identity() {
return capturedAdmission.identity;
},
assertCurrent() {
capturedAdmission.assertCurrent();
schema.assertCurrent();
}
};
runInCapturedSchemaScope = (operation) => inCapturedScope(() => {
admission.assertCurrent();
return operation();
});
}
return {
maintenanceScope: getOpenClawDatabaseMaintenanceScope(),
admission,
existingSchemaPath: schema?.path,
runInCapturedSchemaScope
};
}
/** Read-only workers need resolved runtime facts, not the initialization environment. */
function captureOpenClawStateReadWorkerContextWithAdmission(options, captureAdmission) {
const source = options.env ?? process.env;
const env = process.platform === "win32" ? cloneEnvWithPlatformSemantics(source) : source;
const environment = {
OPENCLAW_STATE_DIR: resolveStateDir(env),
...isGatewayExternallySupervised(env) ? { OPENCLAW_SUPERVISOR_MODE: "external" } : {}
};
return {
...captureOpenClawStateReadContextWithAdmission(options.path ?? resolveOpenClawStateSqlitePath(environment), captureAdmission),
environment
};
}
/** Capture host facts before asynchronous work, without opening SQLite. */
function captureOpenClawStateWorkerContextWithAdmission(options, captureAdmission) {
const context = captureOpenClawStateReadWorkerContextWithAdmission(options, captureAdmission);
return {
...context,
initializationEnvironment: mergeProcessEnv([
options.env ?? process.env,
{
OPENCLAW_STATE_DIR: void 0,
OPENCLAW_SUPERVISOR_MODE: void 0
},
context.environment
]),
...options.initializationAgentPaths ? { initializationAgentPaths: options.initializationAgentPaths.map((agentPath) => path.resolve(agentPath)) } : {}
};
}
var init_openclaw_state_worker_context_capture = __esmMin((() => {
init_config_env_vars();
init_state_dir();
init_gateway_supervision();
init_process_env();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_paths();
}));
//#endregion
//#region src/state/openclaw-state-db-failure.ts
/** Preserve the terminal admission owner's path through worker error transport. */
function markOpenClawStateDatabaseFailure(error, pathname) {
failurePaths.set(error, pathname);
}
/** Cleanup aggregates must retain the original refusal without attributing unrelated errors. */
function findOpenClawStateDatabaseFailure(error, pathname) {
const pending = [error];
const seen = /* @__PURE__ */ new Set();
for (const current of pending) {
if (!(current instanceof Error) || seen.has(current)) continue;
seen.add(current);
if (failurePaths.get(current) === pathname) return current;
pending.push(current.cause);
if (current instanceof AggregateError) pending.push(...current.errors);
}
}
var failurePaths;
var init_openclaw_state_db_failure = __esmMin((() => {
init_global_singleton();
failurePaths = resolveGlobalSingleton(Symbol.for("openclaw.stateDatabaseFailurePaths"), () => /* @__PURE__ */ new WeakMap());
}));
//#endregion
//#region src/agents/mcp-oauth-store-error.ts
var McpOAuthStoreCorruptionError;
var init_mcp_oauth_store_error = __esmMin((() => {
McpOAuthStoreCorruptionError = class extends Error {
constructor(storeKey, detail, options) {
super(`MCP OAuth store ${storeKey} is invalid: ${detail}`, options);
this.name = "McpOAuthStoreCorruptionError";
}
};
}));
//#endregion
//#region src/agents/workspace-state-identity.ts
var WORKSPACE_ALIAS_REPOINTED_ERROR_CODE, WorkspaceAliasRepointedError;
var init_workspace_state_identity = __esmMin((() => {
init_utils();
WORKSPACE_ALIAS_REPOINTED_ERROR_CODE = "WORKSPACE_ALIAS_REPOINTED";
WorkspaceAliasRepointedError = class extends Error {
constructor(params) {
super(`workspace path alias points to a different current target: ${params.aliasPath} now resolves to ${params.currentWorkspacePath}, but its stored workspace state belongs to ${params.storedWorkspacePath}. Run \`openclaw doctor --fix\` and confirm the move, or use \`openclaw doctor --fix --force\`.`);
this.code = WORKSPACE_ALIAS_REPOINTED_ERROR_CODE;
this.name = "WorkspaceAliasRepointedError";
this.aliasPath = params.aliasPath;
this.storedWorkspacePath = params.storedWorkspacePath;
this.currentWorkspacePath = params.currentWorkspacePath;
}
};
}));
//#endregion
//#region src/gateway/worker-environments/session-attachment.ts
var WorkerSessionAlreadyAttachedError;
var init_session_attachment = __esmMin((() => {
WorkerSessionAlreadyAttachedError = class extends Error {
constructor(sessionId, environmentId) {
super(`Session ${sessionId} is already attached to worker environment ${environmentId}`);
this.sessionId = sessionId;
this.environmentId = environmentId;
}
};
}));
//#endregion
//#region src/plugin-state/plugin-blob-store.types.ts
var PluginBlobStoreError;
var init_plugin_blob_store_types = __esmMin((() => {
PluginBlobStoreError = class extends Error {
constructor(message, options) {
super(message, { cause: options.cause });
this.name = "PluginBlobStoreError";
this.code = options.code;
this.operation = options.operation;
if (options.path) this.path = options.path;
}
};
}));
//#endregion
//#region src/skills/lifecycle/upload-store-error.ts
var SkillUploadRequestError;
var init_upload_store_error = __esmMin((() => {
SkillUploadRequestError = class extends Error {
constructor(message) {
super(message);
this.name = "SkillUploadRequestError";
}
};
}));
//#endregion
//#region src/state/openclaw-agent-db-migration-required.ts
var OpenClawAgentDatabaseMediaMigrationRequiredError;
var init_openclaw_agent_db_migration_required = __esmMin((() => {
init_startup_maintenance_required();
OpenClawAgentDatabaseMediaMigrationRequiredError = class extends StartupMaintenanceRequiredError {
constructor(pathname, schemaVersion) {
super("agent-media", `OpenClaw agent database ${pathname} uses schema version ${schemaVersion}; run openclaw doctor --fix to migrate persisted media before using it.`);
this.pathname = pathname;
this.schemaVersion = schemaVersion;
this.name = "OpenClawAgentDatabaseMediaMigrationRequiredError";
}
};
}));
//#endregion
//#region src/state/openclaw-state-db-schema-migration-required.ts
/** Runtime readers report malformed legacy state without entering repair mode. */
function normalizeOpenClawStateSchemaReadError(error, pathname) {
if (error instanceof Error && error.message.startsWith(`malformed database schema (idx_skill_workshop_collection_reviews_workspace_time)`)) {
const required = new OpenClawStateDatabaseSchemaMigrationRequiredError("legacy-workshop-review-index", pathname);
required.cause = error;
return required;
}
return error;
}
var OpenClawStateDatabaseSchemaMigrationRequiredError;
var init_openclaw_state_db_schema_migration_required = __esmMin((() => {
init_startup_maintenance_required();
OpenClawStateDatabaseSchemaMigrationRequiredError = class extends StartupMaintenanceRequiredError {
constructor(kind, pathname) {
super(kind, `OpenClaw state database schema migration required (${kind}) at ${pathname}; run openclaw doctor --fix to migrate it.`);
this.kind = kind;
this.pathname = pathname;
this.name = "OpenClawStateDatabaseSchemaMigrationRequiredError";
}
};
}));
//#endregion
//#region src/state/openclaw-state-lease-error.ts
function isOpenClawStateLeaseErrorCode(value) {
return leaseErrorCodes.some((code) => code === value);
}
var leaseErrorCodes, OpenClawStateLeaseError;
var init_openclaw_state_lease_error = __esmMin((() => {
leaseErrorCodes = [
"OPENCLAW_STATE_LEASE_INVALID_INPUT",
"OPENCLAW_STATE_LEASE_HELD",
"OPENCLAW_STATE_LEASE_ABORTED",
"OPENCLAW_STATE_LEASE_LOST",
"OPENCLAW_STATE_LEASE_STORAGE_FAILED"
];
OpenClawStateLeaseError = class extends Error {
constructor(message, options) {
super(message, { cause: options.cause });
this.name = "OpenClawStateLeaseError";
this.code = options.code;
}
};
}));
//#endregion
//#region src/state/openclaw-state-worker-error-identity.ts
function identifyError(error) {
if (error instanceof WorkerSessionAlreadyAttachedError) return {
type: "worker-session-already-attached",
sessionId: error.sessionId,
environmentId: error.environmentId
};
if (error instanceof PluginBlobStoreError) return {
type: "plugin-blob",
blobCode: error.code,
operation: error.operation,
...error.path === void 0 ? {} : { path: error.path }
};
if (error instanceof WorkspaceAliasRepointedError) return {
type: "workspace-alias-repointed",
aliasPath: error.aliasPath,
storedWorkspacePath: error.storedWorkspacePath,
currentWorkspacePath: error.currentWorkspacePath
};
if (error instanceof McpOAuthStoreCorruptionError) return { type: "mcp-oauth-corruption" };
if (error instanceof SessionMetadataUnavailableError) return {
type: "session-metadata",
reason: error.reason,
missingTables: [...error.missingTables]
};
if (error instanceof SkillUploadRequestError) return { type: "skill-upload-request" };
if (error instanceof GatewayStateOwnerContentionError) return {
type: "state-owner-contention",
databasePath: error.databasePath
};
if (error instanceof SqliteCoordinatorError) return { type: "coordinator" };
if (error instanceof OpenClawStateLeaseError) return {
type: "state-lease",
leaseCode: error.code
};
if (error instanceof OpenClawStateOwnershipMetadataError) return {
type: "ownership-metadata",
databasePath: error.databasePath
};
if (error instanceof OpenClawStateExternalOwnershipError) return {
type: "external-ownership",
databasePath: error.databasePath,
managerId: error.managerId
};
if (error instanceof OpenClawStateOwnershipError) return { type: "ownership" };
if (error instanceof SqliteSchemaVersionError) return { type: "newer-schema" };
if (error instanceof OpenClawStateDatabaseSchemaMigrationRequiredError) return {
type: "state-migration",
kind: error.kind,
pathname: error.pathname
};
if (error instanceof OpenClawAgentDatabaseMediaMigrationRequiredError) return {
type: "agent-media-migration",
pathname: error.pathname,
schemaVersion: error.schemaVersion
};
if (error instanceof StartupMaintenanceRequiredError) return {
type: "maintenance",
kind: error.kind
};
if (error instanceof RangeError) return { type: "range-error" };
if (error instanceof SyntaxError) return { type: "syntax-error" };
if (error instanceof TypeError) return { type: "type-error" };
return { type: error instanceof AggregateError ? "aggregate" : "error" };
}
function isBlobCode(value) {
return value === "PLUGIN_BLOB_OPEN_FAILED" || value === "PLUGIN_BLOB_WRITE_FAILED" || value === "PLUGIN_BLOB_READ_FAILED" || value === "PLUGIN_BLOB_CORRUPT" || value === "PLUGIN_BLOB_LIMIT_EXCEEDED" || value === "PLUGIN_BLOB_INVALID_INPUT";
}
function isBlobOperation(value) {
return value === "open" || value === "register" || value === "lookup" || value === "delete" || value === "entries" || value === "clear" || value === "sweep";
}
function parseIdentity(node) {
switch (node.type) {
case "worker-session-already-attached": return typeof node.sessionId === "string" && typeof node.environmentId === "string" ? {
type: node.type,
sessionId: node.sessionId,
environmentId: node.environmentId
} : void 0;
case "workspace-alias-repointed": return typeof node.aliasPath === "string" && typeof node.storedWorkspacePath === "string" && typeof node.currentWorkspacePath === "string" ? {
type: node.type,
aliasPath: node.aliasPath,
storedWorkspacePath: node.storedWorkspacePath,
currentWorkspacePath: node.currentWorkspacePath
} : void 0;
case "error":
case "aggregate":
case "ownership":
case "newer-schema":
case "coordinator":
case "range-error":
case "syntax-error":
case "type-error":
case "skill-upload-request":
case "mcp-oauth-corruption": return { type: node.type };
case "session-metadata": return (node.reason === "schema-missing" || node.reason === "table-missing") && Array.isArray(node.missingTables) && node.missingTables.every((table) => typeof table === "string") ? {
type: node.type,
reason: node.reason,
missingTables: [...node.missingTables]
} : void 0;
case "state-owner-contention": return typeof node.databasePath === "string" ? {
type: node.type,
databasePath: node.databasePath
} : void 0;
case "ownership-metadata": return typeof node.databasePath === "string" ? {
type: node.type,
databasePath: node.databasePath
} : void 0;
case "external-ownership": return typeof node.databasePath === "string" && typeof node.managerId === "string" ? {
type: node.type,
databasePath: node.databasePath,
managerId: node.managerId
} : void 0;
case "plugin-blob": return isBlobCode(node.blobCode) && node.code === node.blobCode && isBlobOperation(node.operation) && (node.path === void 0 || typeof node.path === "string") ? {
type: node.type,
blobCode: node.blobCode,
operation: node.operation,
...typeof node.path === "string" ? { path: node.path } : {}
} : void 0;
case "state-lease": return isOpenClawStateLeaseErrorCode(node.leaseCode) && node.code === node.leaseCode ? {
type: node.type,
leaseCode: node.leaseCode
} : void 0;
case "maintenance": return isStartupMaintenanceKind(node.kind) ? {
type: node.type,
kind: node.kind
} : void 0;
case "state-migration": return (node.kind === "agent-databases-composite-primary-key" || node.kind === "audit-events-v2" || node.kind === "legacy-cron-run-logs" || node.kind === "legacy-workshop-review-index") && typeof node.pathname === "string" ? {
type: node.type,
kind: node.kind,
pathname: node.pathname
} : void 0;
case "agent-media-migration": return typeof node.pathname === "string" && typeof node.schemaVersion === "number" && Number.isSafeInteger(node.schemaVersion) && node.schemaVersion >= 0 ? {
type: node.type,
pathname: node.pathname,
schemaVersion: node.schemaVersion
} : void 0;
default: return;
}
}
function unreachableErrorNode(node) {
throw new Error(`Unexpected shared-state worker error node: ${String(node)}`);
}
function createError(node) {
switch (node.type) {
case "worker-session-already-attached": return new WorkerSessionAlreadyAttachedError(node.sessionId, node.environmentId);
case "workspace-alias-repointed": return new WorkspaceAliasRepointedError(node);
case "session-metadata": return new SessionMetadataUnavailableError(node.reason, void 0, node.missingTables);
case "error": return new Error(node.message);
case "range-error": return new RangeError(node.message);
case "syntax-error": return new SyntaxError(node.message);
case "type-error": return new TypeError(node.message);
case "skill-upload-request": return new SkillUploadRequestError(node.message);
case "mcp-oauth-corruption": return new McpOAuthStoreCorruptionError("", "");
case "aggregate": return new AggregateError([], node.message);
case "coordinator": return new SqliteCoordinatorError(node.message);
case "state-owner-contention": return new GatewayStateOwnerContentionError(node.databasePath);
case "ownership": return new OpenClawStateOwnershipError(node.message);
case "ownership-metadata": return new OpenClawStateOwnershipMetadataError(node.databasePath, "");
case "external-ownership": return new OpenClawStateExternalOwnershipError(node.databasePath, node.managerId);
case "newer-schema": return new SqliteSchemaVersionError(node.message);
case "plugin-blob": return new PluginBlobStoreError(node.message, {
code: node.blobCode,
operation: node.operation,
...node.path === void 0 ? {} : { path: node.path }
});
case "state-lease": return new OpenClawStateLeaseError(node.message, { code: node.leaseCode });
case "maintenance": return new StartupMaintenanceRequiredError(node.kind, node.message);
case "state-migration": return new OpenClawStateDatabaseSchemaMigrationRequiredError(node.kind, node.pathname);
case "agent-media-migration": return new OpenClawAgentDatabaseMediaMigrationRequiredError(node.pathname, node.schemaVersion);
}
return unreachableErrorNode(node);
}
var init_openclaw_state_worker_error_identity = __esmMin((() => {
init_mcp_oauth_store_error();
init_workspace_state_identity();
init_session_attachment();
init_gateway_state_owner();
init_sqlite_lifecycle_errors();
init_sqlite_user_version();
init_startup_maintenance_required();
init_plugin_blob_store_types();
init_upload_store_error();
init_openclaw_agent_db_migration_required();
init_openclaw_state_db_schema_migration_required();
init_openclaw_state_lease_error();
init_session_metadata_unavailable_error();
}));
//#endregion
//#region src/state/openclaw-state-worker-error.ts
function isScalar(value) {
return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
}
function isNativeErrorCode(value) {
return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 2147483647;
}
function isErrorValue(value, count) {
if (!isRecord(value) || Object.keys(value).length !== 1) return false;
if ("ref" in value) return typeof value.ref === "number" && Number.isSafeInteger(value.ref) && value.ref >= 0 && value.ref < count;
return "value" in value ? isScalar(value.value) : value.undefined === true;
}
function parseNode(value, count) {
if (!isRecord(value) || typeof value.name !== "string" || typeof value.message !== "string") return;
const identity = parseIdentity(value);
if (!identity) return;
const allowed = /* @__PURE__ */ new Set([
...Object.keys(identity),
"name",
"message",
"code",
"errcode",
"errno",
"nativeOpen",
"stateDatabasePath",
"cause"
]);
const errors = [];
if (identity.type === "aggregate") {
allowed.add("errors");
if (!Array.isArray(value.errors)) return;
for (const entry of value.errors) {
if (!isErrorValue(entry, count)) return;
errors.push(entry);
}
}
if (Object.keys(value).some((key) => !allowed.has(key)) || "code" in value && typeof value.code !== "string" && !(typeof value.code === "number" && Number.isFinite(value.code)) || "errcode" in value && !isNativeErrorCode(value.errcode) || "errno" in value && (typeof value.errno !== "number" || !Number.isInteger(value.errno)) || "nativeOpen" in value && value.nativeOpen !== true || "stateDatabasePath" in value && typeof value.stateDatabasePath !== "string" || "cause" in value && !isErrorValue(value.cause, count)) return;
return {
...identity,
name: value.name,
message: value.message,
...typeof value.code === "string" || typeof value.code === "number" ? { code: value.code } : {},
...isNativeErrorCode(value.errcode) ? { errcode: value.errcode } : {},
...typeof value.errno === "number" ? { errno: value.errno } : {},
...value.nativeOpen === true ? { nativeOpen: true } : {},
...typeof value.stateDatabasePath === "string" ? { stateDatabasePath: value.stateDatabasePath } : {},
...isErrorValue(value.cause, count) ? { cause: value.cause } : {},
...identity.type === "aggregate" ? { errors } : {}
};
}
function decodeErrorGraph(value, options) {
try {
if (!isRecord(value) || Object.keys(value).some((key) => ![
"version",
"root",
"nodes"
].includes(key)) || value.version !== 1 || !Array.isArray(value.nodes) || typeof value.root !== "number" || !Number.isSafeInteger(value.root) || value.root < 0 || value.root >= value.nodes.length) return;
const nodes = [];
for (const valueNode of value.nodes) {
const node = parseNode(valueNode, value.nodes.length);
if (!node) return;
nodes.push(node);
}
const visited = /* @__PURE__ */ new Set();
const pending = [value.root];
let canonical = false;
for (const ref of pending) {
if (visited.has(ref)) continue;
visited.add(ref);
const node = nodes[ref];
canonical ||= node.stateDatabasePath !== void 0 || node.nativeOpen === true || node.type === "aggregate" && node.name === "OpenClawQuarantineReadCleanupError" || node.type !== "error" && node.type !== "aggregate";
for (const edge of [...node.cause ? [node.cause] : [], ...node.errors ?? []]) if ("ref" in edge) pending.push(edge.ref);
}
if (!canonical && options.includeOrdinary !== true || visited.size !== nodes.length) return;
const errors = nodes.map(createError);
const decodeValue = (entry) => "ref" in entry ? errors[entry.ref] : "value" in entry ? entry.value : void 0;
for (const [index, node] of nodes.entries()) {
const error = errors[index];
error.name = node.name;
error.message = node.message;
if (node.nativeOpen) markSqliteNativeOpenFailure(error);
if (node.stateDatabasePath !== void 0) markOpenClawStateDatabaseFailure(error, node.stateDatabasePath);
for (const [key, propertyValue] of Object.entries({
...node.code !== void 0 ? { code: node.code } : {},
...node.errcode !== void 0 ? { errcode: node.errcode } : {},
...node.errno !== void 0 ? { errno: node.errno } : {},
...node.cause ? { cause: decodeValue(node.cause) } : {}
})) Object.defineProperty(error, key, {
value: propertyValue,
configurable: true,
writable: true
});
if (error instanceof AggregateError) error.errors = (node.errors ?? []).map(decodeValue);
}
const group = Object.freeze({});
for (const [index, error] of errors.entries()) retainPayload(error, value, index, true, group);
return {
errors,
nodes,
root: value.root
};
} catch {
return;
}
}
function retainPayload(error, payload, node, materialized, group) {
Object.defineProperty(error, retainedPayloadKey, { value: Object.freeze({
payload,
node,
materialized,
group
}) });
}
/** Keep the closed wire graph without binding it to a process-global broker's classes. */
function retainOpenClawStateWorkerErrorPayload(error, payload) {
retainPayload(error, payload, 0, false, Object.freeze({}));
}
function hydrateOpenClawStateWorkerError(value, options = {}) {
if (!(value instanceof Error)) return value;
const groups = /* @__PURE__ */ new Map();
const nodes = /* @__PURE__ */ new Map();
const queue = [];
const add = (error) => {
const previous = nodes.get(error);
if (previous) return previous;
const node = {
source: error,
replacement: error,
parents: /* @__PURE__ */ new Set(),
changed: false,
opaque: false
};
nodes.set(error, node);
queue.push(node);
const retained = Object.getOwnPropertyDescriptor(error, retainedPayloadKey)?.value;
if (isRecord(retained) && typeof retained.node === "number" && Number.isSafeInteger(retained.node) && retained.node >= 0 && typeof retained.materialized === "boolean" && isRecord(retained.group)) {
if (!groups.has(retained.group)) groups.set(retained.group, decodeErrorGraph(retained.payload, options));
const graph = groups.get(retained.group);
const index = retained.materialized ? retained.node : graph?.root;
const replacement = index === void 0 ? void 0 : graph?.errors[index];
const identity = index === void 0 ? void 0 : graph?.nodes[index];
if (replacement && identity) {
node.replacement = replacement;
node.opaque = !retained.materialized;
node.changed = node.opaque || identifyError(error).type !== identity.type;
}
}
return node;
};
const root = add(value);
for (const node of queue) {
if (node.opaque) continue;
const edge = (child) => {
if (child instanceof Error) add(child).parents.add(node);
};
if ("cause" in node.source) {
node.cause = { value: node.source.cause };
edge(node.cause.value);
}
if (node.source instanceof AggregateError) {
node.errors = [...node.source.errors];
node.errors.forEach(edge);
}
}
const affected = queue.filter((node) => node.changed);
for (const node of affected) for (const parent of node.parents) if (!parent.changed) {
parent.changed = true;
affected.push(parent);
}
if (!root.changed) return value;
for (const node of affected) if (node.replacement === node.source) {
node.replacement = node.source instanceof AggregateError ? new AggregateError([], node.source.message) : new Error(node.source.message);
Object.setPrototypeOf(node.replacement, Object.getPrototypeOf(node.source));
}
const replace = (child) => {
const node = child instanceof Error ? nodes.get(child) : void 0;
return node?.changed ? node.replacement : child;
};
for (const node of affected) {
if (node.opaque) continue;
const descriptors = Object.getOwnPropertyDescriptors(node.source);
Reflect.deleteProperty(descriptors, retainedPayloadKey);
if (node.cause) descriptors.cause = {
configurable: descriptors.cause?.configurable ?? true,
enumerable: descriptors.cause?.enumerable ?? false,
writable: descriptors.cause?.writable ?? true,
value: replace(node.cause.value)
};
if (node.errors) descriptors.errors = {
configurable: descriptors.errors?.configurable ?? true,
enumerable: descriptors.errors?.enumerable ?? false,
writable: descriptors.errors?.writable ?? true,
value: node.errors.map(replace)
};
Object.defineProperties(node.replacement, descriptors);
}
return root.replacement;
}
var retainedPayloadKey;
var init_openclaw_state_worker_error = __esmMin((() => {
init_record_coerce();
init_sqlite_error_diagnostics();
init_openclaw_quarantine_error();
init_openclaw_state_db_failure();
init_openclaw_state_worker_error_identity();
retainedPayloadKey = Symbol.for("openclaw.sharedStateWorkerErrorPayload");
}));
//#endregion
//#region src/daemon/runtime-binary.ts
function normalizeRuntimeBasename(execPath) {
const trimmed = execPath.trim().replace(/^["']|["']$/g, "");
const lastSlash = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
return (lastSlash === -1 ? trimmed : trimmed.slice(lastSlash + 1)).trim().toLowerCase();
}
/** Returns whether an executable path names a Bun runtime binary. */
function isBunRuntime(execPath) {
const base = normalizeRuntimeBasename(execPath);
return base === "bun" || base === "bun.exe";
}
var init_runtime_binary = __esmMin((() => {}));
//#endregion
//#region src/infra/runtime-worker-url.ts
/** Resolve an explicit installed root, source sibling, or stable packaged worker path. */
function resolveRuntimeWorkerUrl(params) {
if (params.root !== void 0) return pathToFileURL(path.join(params.root, "dist", params.distWorkerPath));
const currentPath = fileURLToPath(params.currentModuleUrl);
const distIndex = currentPath.replaceAll(path.sep, "/").lastIndexOf("/dist/");
if (distIndex >= 0) {
const distRoot = currentPath.slice(0, distIndex + 6);
let workerPath = params.distWorkerPath;
if (params.package) {
const packageRoot = path.resolve(distRoot, "..");
const manifest = readRootJsonObjectSync({
rootDir: packageRoot,
relativePath: "package.json",
boundaryLabel: "runtime worker package",
rejectHardlinks: false
});
if (!manifest.ok) throw new Error(`Cannot resolve runtime worker package: ${packageRoot}/package.json`);
if (manifest.value.name === params.package.name) workerPath = params.package.distWorkerPath;
}
return pathToFileURL(path.join(distRoot, workerPath));
}
const extension = path.extname(currentPath) || ".js";
return new URL(`./${params.sourceWorkerName}${extension}`, params.currentModuleUrl);
}
function isBunWorkerRuntime(execPath) {
return execPath === process.execPath ? Boolean(process.versions.bun) : isBunRuntime(execPath);
}
/** Whether a source TypeScript module needs Node's tsx loader; Bun runs TypeScript natively. */
function runtimeNeedsTypeScriptLoader(modulePath, execPath = process.execPath) {
return /\.[cm]?ts$/.test(modulePath) && !isBunWorkerRuntime(execPath);
}
function resolveRuntimeWorkerArgv(url, execPath = process.execPath) {
const entry = fileURLToPath(url);
return runtimeNeedsTypeScriptLoader(entry, execPath) ? [
"--import",
import.meta.resolve("tsx"),
entry
] : [entry];
}
/** Select the source Worker preload without feeding Node's TypeScript loader to Bun. */
function resolveRuntimeWorkerThreadExecArgv(url, execPath = process.execPath) {
return url.protocol === "file:" && runtimeNeedsTypeScriptLoader(fileURLToPath(url), execPath) ? ["--import", import.meta.resolve("tsx/esm")] : [];
}
var init_runtime_worker_url = __esmMin((() => {
init_runtime_binary();
}));
//#endregion
//#region packages/session-url-contract/src/focus.ts
var init_focus = __esmMin((() => {}));
var init_share = __esmMin((() => {
Object.freeze([
"activity",
"agents",
"ai-agents",
"appearance",
"approve",
"apps",
"ask",
"automation",
"automations",
"channels",
"chat",
"communications",
"config",
"cron",
"custodian",
"dashboard",
"dashboards",
"debug",
"focus",
"infrastructure",
"lobsterdex",
"logs",
"mcp",
"meetings",
"memory-import",
"model-providers",
"model-setup",
"new",
"nodes",
"plugin",
"plugins",
"portals",
"profile",
"sessions",
"settings",
"share",
"skills",
"systems",
"terminal",
"usage",
"workboard",
"worktrees"
]);
}));
//#endregion
//#region packages/session-url-contract/src/index.ts
var init_src = __esmMin((() => {
init_focus();
init_share();
}));
//#endregion
//#region src/routing/session-key.ts
var init_session_key = __esmMin((() => {
init_src();
init_prototype_keys();
})), agentSqlitePaths;
var init_openclaw_agent_db_paths = __esmMin((() => {
init_paths$1();
init_errno();
init_path_guards();
init_session_key();
agentSqlitePaths = /* @__PURE__ */ new Map();
agentSqlitePaths.keys();
}));
//#endregion
//#region src/infra/runtime-process-entrypoints.ts
function runtimeProcessEntrypoint(modulePath) {
return {
currentModuleUrl: import.meta.url,
sourceWorkerName: modulePath.startsWith("infra/") ? modulePath.slice(6) : `../${modulePath}`,
distWorkerPath: `${modulePath}.js`
};
}
var SQLITE_READONLY_CHILD_ARG, runtimeProcessEntrypoints;
var init_runtime_process_entrypoints = __esmMin((() => {
SQLITE_READONLY_CHILD_ARG = "--openclaw-sqlite-readonly-child";
runtimeProcessEntrypoints = {
secretEgressProxy: runtimeProcessEntrypoint("secrets/egress-proxy/proxy.worker"),
codeModeNode: runtimeProcessEntrypoint("agents/code-mode-node.worker"),
cronReadOnly: runtimeProcessEntrypoint("cron/store/read-only.worker"),
stateRead: runtimeProcessEntrypoint("state/openclaw-state-read.worker"),
spawnBroker: runtimeProcessEntrypoint("process/spawn-broker/worker"),
cronStreamMatcher: runtimeProcessEntrypoint("gateway/cron-stream-matcher.worker"),
controlUiFile: runtimeProcessEntrypoint("gateway/control-ui-file.worker"),
nativeHookRelayClient: runtimeProcessEntrypoint("agents/harness/native-hook-relay-client.worker"),
computerHost: runtimeProcessEntrypoint("gateway/desktop/computer.worker"),
imageProcessor: runtimeProcessEntrypoint("media/image-processor.worker"),
fileToolPlanning: runtimeProcessEntrypoint("agents/sessions/tools/file-tool-planning.worker"),
attachmentProcessor: runtimeProcessEntrypoint("media/attachment-processor.worker"),
gitOperations: runtimeProcessEntrypoint("infra/git-operation.worker"),
fsSafeCopy: runtimeProcessEntrypoint("infra/fs-safe-copy.worker"),
sharedStateStore: runtimeProcessEntrypoint("state/openclaw-state.worker"),
authProfileInlineUsage: runtimeProcessEntrypoint("agents/auth-profiles/inline-usage.worker"),
agentDatabaseExecution: runtimeProcessEntrypoint("state/openclaw-agent-execution.worker"),
workspaceMemory: runtimeProcessEntrypoint("worker/memory-worker-entry"),
localAgentAvatar: runtimeProcessEntrypoint("agents/identity-avatar-file.worker"),
identityFile: runtimeProcessEntrypoint("agents/identity-file.worker"),
workspaceSkills: runtimeProcessEntrypoint("worker/skills-worker-entry"),
boardStore: runtimeProcessEntrypoint("boards/sqlite-board-store.worker"),
sessionSharingStore: runtimeProcessEntrypoint("config/sessions/session-sharing-store.worker"),
heartbeatOutcomeStore: runtimeProcessEntrypoint("infra/heartbeat-outcome-store.worker"),
contextEngineTurnOutbox: runtimeProcessEntrypoint("agents/harness/context-engine-turn-outbox.worker"),
sqliteStore: runtimeProcessEntrypoint("infra/sqlite-store.worker"),
agentSchemaInspection: runtimeProcessEntrypoint("state/openclaw-agent-schema-inspection.worker"),
stateMigrationSnapshot: runtimeProcessEntrypoint("infra/state-migrations.snapshot.worker"),
githubExec: runtimeProcessEntrypoint("agents/github-exec-launcher"),
sqliteReadOnly: runtimeProcessEntrypoint("infra/sqlite-readonly-location.worker"),
sqliteSourceRevision: runtimeProcessEntrypoint("infra/sqlite-source-revision.worker"),
sqliteIntegrity: runtimeProcessEntrypoint("infra/sqlite-integrity.worker"),
preparedModelCatalog: runtimeProcessEntrypoint("agents/prepared-model-catalog.worker"),
providerPromptState: runtimeProcessEntrypoint("agents/embedded-agent-runner/provider-prompt-state.worker"),
updateRepair: runtimeProcessEntrypoint("infra/update-repair.worker"),
updateMigratedFinalize: runtimeProcessEntrypoint("infra/update-migrated-finalize.worker"),
updateCandidateState: runtimeProcessEntrypoint("infra/update-candidate-state.worker"),
doctorLint: runtimeProcessEntrypoint("commands/doctor-lint.worker"),
doctor: runtimeProcessEntrypoint("commands/doctor.worker"),
databaseVerify: runtimeProcessEntrypoint("state/openclaw-database-verify.worker"),
stateOwnership: runtimeProcessEntrypoint("state/openclaw-state-ownership.worker"),
stateLeaseHeartbeat: runtimeProcessEntrypoint("state/openclaw-state-lease-heartbeat.worker"),
sessionTranscriptArchive: runtimeProcessEntrypoint("config/sessions/session-accessor.sqlite-archive.worker"),
sessionTranscript: runtimeProcessEntrypoint("config/sessions/session-transcript.worker"),
sessionManagerMetadata: runtimeProcessEntrypoint("agents/sessions/session-manager-metadata.worker"),
sessionTranscriptProjectionPublication: runtimeProcessEntrypoint("config/sessions/session-transcript-projection-publication.worker"),
sessionTranscriptReports: runtimeProcessEntrypoint("config/sessions/session-accessor.sqlite-transcript-reports.worker"),
sessionTranscriptReconcile: runtimeProcessEntrypoint("config/sessions/session-transcript-reconcile.worker"),
tailscaleRouteOwner: runtimeProcessEntrypoint("infra/tailscale-route-owner.worker"),
serviceChildRelay: runtimeProcessEntrypoint("process/supervisor/service-child-relay"),
terminalPty: runtimeProcessEntrypoint("process/terminal-pty-worker"),
serviceChildGroupAnchor: runtimeProcessEntrypoint("process/supervisor/service-child-group-anchor"),
serviceChildWindowsJobAnchor: runtimeProcessEntrypoint("process/supervisor/service-child-windows-job-anchor"),
bunSqliteLibrary: runtimeProcessEntrypoint("infra/bun-sqlite-library")
};
}));
//#endregion
//#region src/infra/runtime-process-url.ts
function resolveRuntimeProcessEntrypointUrl(name) {
return sealedEntrypoints.get(name) ?? resolveRuntimeWorkerUrl(runtimeProcessEntrypoints[name]);
}
var sealedEntrypoints;
var init_runtime_process_url = __esmMin((() => {
init_runtime_process_entrypoints();
init_runtime_worker_url();
sealedEntrypoints = /* @__PURE__ */ new Map();
}));
//#endregion
//#region src/infra/sqlite-worker-state-context.ts
function captureSqliteWorkerStateContext(context) {
return {
environment: { ...context.environment },
...context.initializationEnvironment ? { initializationEnvironment: { ...context.initializationEnvironment } } : {},
...context.initializationAgentPaths ? { initializationAgentPaths: [...context.initializationAgentPaths] } : {},
existingSchemaPath: context.existingSchemaPath
};
}
/** Charge captured initialization facts together with the request bytes retained by admission. */
function sqliteWorkerRequestBytes(input, context, preparation) {
const agentPathBytes = context?.initializationAgentPaths?.reduce((bytes, agentPath) => bytes + Buffer.byteLength(agentPath, "utf8"), 0) ?? 0;
return [context?.environment, context?.initializationEnvironment].reduce((bytes, environment) => Object.entries(environment ?? {}).reduce((total, [key, value]) => total + Buffer.byteLength(key, "utf8") + Buffer.byteLength(value ?? "", "utf8"), bytes), input.byteLength + (preparation?.byteLength ?? 0) + agentPathBytes);
}
var init_sqlite_worker_state_context = __esmMin((() => {
init_global_singleton();
init_openclaw_state_db_schema_policy();
resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerStateContext"), () => new AsyncLocalStorage());
}));
//#endregion
//#region src/infra/sqlite-worker-broker-admission.ts
function validateSqliteWorkerDatabaseLocator(databasePath) {
const basename = path.basename(databasePath);
if (!databasePath || databasePath.startsWith("file:") || basename === ":memory:" || basename === "incognito-openclaw-agent.sqlite") throw new Error("SQLite worker stores require a file-backed filesystem path; in-memory and incognito databases are not supported");
}
function captureSqliteWorkerOpen(options, stateContext, assertCurrent, custody = {}) {
const { createAdmission, preparation, ...native } = custody;
const inCaller = createAdmission ? AsyncLocalStorage.snapshot() : void 0;
const ownedAdmission = options.admission;
const assertOpening = ownedAdmission ? () => {
assertCurrent?.();
ownedAdmission.assertCurrent();
} : assertCurrent;
const databasePath = path.resolve(options.databasePath);
if (options.admission && (!options.existingOnly || !options.admission.identity.startsWith("file:"))) throw new Error("Owned SQLite Worker admission requires an existing physical identity");
assertOpening?.();
const carrier = resolveRuntimeProcessEntrypointUrl("sqliteStore");
const carrierUrl = options.runtimeGeneration?.resolve(carrier) ?? carrier;
return {
...native,
maintenanceScope: custody.maintenanceScope ?? getOpenClawDatabaseMaintenanceScope(),
...preparation !== void 0 ? { preparation: serialize(preparation) } : {},
runtimeGeneration: options.runtimeGeneration,
carrierUrl,
createAdmission: createAdmission && inCaller ? (operation) => inCaller(createAdmission, operation) : void 0,
assertCurrent: assertOpening,
...options.admission ? {
expectedIdentity: options.admission.identity,
createOpenAdmission: () => {
let granted = false;
return {
nativeLocations: [databasePath],
admission: createSqliteWorkerOperationAdmission((request, grant) => {
if (granted || request.stage !== "open") throw new Error("SQLite Worker open admission requested out of order");
assertOpening();
if (!grant()) throw new Error("SQLite Worker open admission expired");
granted = true;
})
};
}
} : {},
moduleUrl: new URL(options.moduleUrl),
databasePath,
input: serialize(options.input),
existingOnly: options.existingOnly === true,
...stateContext ? { stateContext: captureSqliteWorkerStateContext(stateContext) } : {}
};
}
function validateSqliteWorkerModuleUrl(moduleUrl) {
if (moduleUrl.protocol !== "file:" || moduleUrl.search || moduleUrl.hash) throw new Error("SQLite worker backend must be a static local module URL");
}
async function prepareSqliteWorkerDatabaseAdmission(options) {
validateSqliteWorkerModuleUrl(options.moduleUrl);
const databasePath = path.resolve(options.databasePath);
const inputHash = createHash("sha256").update(options.input).digest("hex");
const identity = await readDatabasePathIdentity(databasePath);
options.assertCurrent?.();
if (options.expectedIdentity && identity.key !== options.expectedIdentity) throw new Error("SQLite Worker path no longer matches its borrowed native owner");
return {
databasePath,
inputHash,
identity
};
}
function captureSqliteWorkerAdmissionPaths(databasePath, identity, actors) {
const admittedPaths = /* @__PURE__ */ new Set([databasePath, identity.canonicalPath]);
if ([...actors].some((entry) => entry.key !== identity.key && [...admittedPaths].some((pathname) => entry.pathReferences.has(pathname)))) throw new Error("SQLite database pathname changed while its worker owner is active; close the existing store first");
return admittedPaths;
}
function retainSqliteWorkerAdmissionCleanup(actor, retain, close) {
retain?.({
get pending() {
return actor.references === 0 && actor.cleanupState === "pending";
},
close: () => actor.references === 0 ? close() : Promise.resolve()
});
}
function retainSqliteWorkerAdmissionPathReferences(actor, paths) {
for (const pathname of paths) actor.pathReferences.set(pathname, (actor.pathReferences.get(pathname) ?? 0) + 1);
return () => {
for (const pathname of paths) {
const references = actor.pathReferences.get(pathname) ?? 0;
if (references > 1) actor.pathReferences.set(pathname, references - 1);
else actor.pathReferences.delete(pathname);
}
};
}
async function resolveOpenedSqliteWorkerIdentity(databasePath, previous, isOwnedElsewhere) {
const openedIdentity = await readDatabasePathIdentity(databasePath);
const physical = openedIdentity.key;
if (openedIdentity.canonicalPath !== previous.canonicalPath) throw new Error("SQLite database canonical pathname changed during open");
if (!physical.startsWith("file:")) throw new Error("SQLite worker backend did not establish its database file");
if (isOwnedElsewhere(physical)) throw new Error("SQLite database identity collided with an existing worker owner during open");
if (previous.key.startsWith("file:") && physical !== previous.key) throw new Error("SQLite database file identity changed during open");
return physical;
}
function findUnclaimedSharedStateActors(actors, databasePath) {
const pathname = path.resolve(databasePath);
return [...actors].filter((actor) => actor.stateContext !== void 0 && actor.references === 0 && actor.cleanupState === "pending" && actor.databasePath === pathname);
}
async function closeUnclaimedSharedStateActors(actors, databasePath, close) {
const errors = (await Promise.allSettled(findUnclaimedSharedStateActors(actors, databasePath).map(close))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
if (errors.length) throw new AggregateError(errors, "SQLite worker unclaimed cleanup failed", { cause: errors[0] });
}
async function resolveSqliteWorkerModuleUrl(sourceUrl) {
const modulePath = await realpath(fileURLToPath(sourceUrl));
const moduleUrl = pathToFileURL(modulePath).href;
if (!/\.[cm]?[jt]s$/.test(modulePath) || !(await stat(modulePath)).isFile()) throw new Error("SQLite worker backend must identify a JavaScript or TypeScript file");
return {
modulePath,
moduleUrl
};
}
function assertSqliteWorkerActorStateContext(actor, stateContext) {
if (actor.stateContext?.existingSchemaPath !== stateContext?.existingSchemaPath) throw new Error("Shared-state worker schema policy changed; close its actor first");
}
function assertSqliteWorkerActorReusable(actor, moduleUrl, inputHash, stateContext) {
if (actor.slot.failed) throw actor.slot.failed;
if (actor.moduleUrl !== moduleUrl || actor.inputHash !== inputHash) throw new Error("SQLite database already belongs to another worker backend");
assertSqliteWorkerActorStateContext(actor, stateContext);
}
function prepareSqliteWorkerActorContext(actor, job) {
const { request } = job;
const stateContext = request.stateContext ?? actor?.stateContext;
if (actor && request.type !== "close") assertStateDatabaseAccessAllowed(actor.stateDatabasePath ?? actor.databasePath, { maintenanceScope: job.maintenanceScope });
if (actor && stateContext) {
assertSqliteWorkerActorStateContext(actor, stateContext);
request.stateDatabasePath = actor.stateDatabasePath ?? actor.databasePath;
request.stateContext = stateContext;
}
}
var init_sqlite_worker_broker_admission = __esmMin((() => {
init_openclaw_agent_db_paths();
init_openclaw_state_db_async_lifecycle();
init_gateway_state_owner();
init_runtime_process_url();
init_sqlite_worker_identity();
init_sqlite_worker_operation_admission();
init_sqlite_worker_state_context();
}));
//#endregion
//#region node-compile-cache.mjs
function resolveSafeNodeCompileCacheDirectory(directory) {
if (process.platform === "win32" && path.resolve(directory).length > 200) {
process.stderr.write("[openclaw] Compile cache disabled: Windows cache path exceeds 200 characters.\n");
return;
}
return directory;
}
async function maintain(directory) {
const root = path.dirname(path.dirname(directory));
const version = path.basename(path.dirname(directory));
if (path.basename(root) !== "openclaw" || sanitize(version) !== version || !BUILD_MARKER_RE.test(path.basename(directory))) return;
const now = Date.now();
const previous = await fsPromises.lstat(root).catch(() => void 0);
for (const target of [
root,
path.dirname(directory),
directory
]) {
const stat = target === root ? previous : await fsPromises.lstat(target).catch(() => void 0);
if (stat && !stat.isDirectory()) return;
}
await fsPromises.mkdir(directory, { recursive: true });
let retired = false;
for (const entry of await fsPromises.readdir(root, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const versionRoot = path.join(root, entry.name);
for (const build of await fsPromises.readdir(versionRoot, { withFileTypes: true })) {
const candidate = path.join(versionRoot, build.name);
if (build.isDirectory() && candidate !== directory) {
await fsPromises.rm(candidate, {
recursive: true,
force: true
});
retired = true;
}
}
if (versionRoot !== path.dirname(directory)) await fsPromises.rmdir(versionRoot).catch(() => {});
}
if (!retired && previous && now - previous.mtimeMs < MAINTENANCE_INTERVAL_MS) return;
await fsPromises.utimes(root, new Date(now), new Date(now));
const files = [];
let bytes = 0;
async function visit(dir) {
for (const entry of await fsPromises.readdir(dir, { withFileTypes: true })) {
const file = path.join(dir, entry.name);
if (entry.isDirectory()) await visit(file);
else if (entry.isFile()) {
const stat = await fsPromises.lstat(file);
bytes += stat.size;
files.push({
file,
size: stat.size,
mtimeMs: stat.mtimeMs
});
}
}
}
await visit(directory);
files.sort((left, right) => left.mtimeMs - right.mtimeMs);
for (const file of files) if (bytes > MAX_BYTES || now - file.mtimeMs > MAX_AGE_MS) {
await fsPromises.unlink(file.file);
bytes -= file.size;
}
}
var MAX_BYTES, MAX_AGE_MS, MAINTENANCE_INTERVAL_MS, BUILD_MARKER_RE, sanitize;
var init_node_compile_cache = __esmMin((() => {
MAX_BYTES = 536870912;
MAX_AGE_MS = 6048e5;
MAINTENANCE_INTERVAL_MS = 36e5;
BUILD_MARKER_RE = /^(?:[a-f0-9]{16}|\d+-\d+|no-package-json|build-[A-Za-z0-9._-]+)$/;
sanitize = (value) => {
const segment = value.replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^_+|_+$/g, "");
return segment && segment !== "." && segment !== ".." ? segment : "unknown";
};
if (!isMainThread && typeof workerData?.openclawCompileCacheDirectory === "string") maintain(workerData.openclawCompileCacheDirectory).catch(() => {});
}));
//#endregion
//#region src/infra/node-compile-cache-env.ts
function compileCacheOwner() {
return resolveGlobalSingleton(COMPILE_CACHE_BASE_KEY, () => ({}));
}
function resolveNodeCompileCacheEnv(env = process.env) {
if (env.NODE_DISABLE_COMPILE_CACHE !== void 0) return env;
const directory = env.NODE_COMPILE_CACHE ?? compileCacheOwner().baseDirectory;
if (directory && !resolveSafeNodeCompileCacheDirectory(directory)) {
const disabled = {
...env,
NODE_DISABLE_COMPILE_CACHE: "1"
};
delete disabled.NODE_COMPILE_CACHE;
return disabled;
}
if (env.NODE_COMPILE_CACHE !== void 0) return env;
return directory ? {
...env,
NODE_COMPILE_CACHE: directory
} : env;
}
var COMPILE_CACHE_BASE_KEY;
var init_node_compile_cache_env = __esmMin((() => {
init_node_compile_cache();
init_global_singleton();
COMPILE_CACHE_BASE_KEY = Symbol.for("openclaw.nodeCompileCacheBase");
}));
//#endregion
//#region src/infra/sqlite-worker-transfer.ts
/** One owned result cursor; callers supply records and any associated cleanup. */
function createSqliteWorkerTransferOwner() {
let nextId = 0;
let current;
const cleanup = (transfer) => {
const errors = [];
if (!transfer.iteratorClosed) try {
transfer.iterator.return?.();
transfer.iteratorClosed = true;
} catch (error) {
errors.push(error);
}
if (!transfer.cleaned) try {
transfer.cleanup?.();
transfer.cleaned = true;
} catch (error) {
errors.push(error);
}
if (errors.length === 1) throw errors[0];
if (errors.length) throw new AggregateError(errors, "SQLite read transfer cleanup failed", { cause: errors[0] });
};
const cancel = () => {
if (current) {
cleanup(current);
current = void 0;
}
};
const requireTransfer = (id) => {
if (!current || current.id !== id) throw new Error("SQLite read transfer is no longer active");
return current;
};
return {
start(iterator, options) {
if (current) throw new Error("The preceding SQLite read transfer was not released");
current = {
id: ++nextId,
iterator,
cleanup: options.cleanup,
iteratorClosed: false,
cleaned: false,
counts: new Map(options.kinds.map((kind) => [kind, 0])),
sequence: 0,
finished: false
};
return {
id: current.id,
kinds: [...current.counts.keys()]
};
},
next(id) {
const transfer = requireTransfer(id);
if (transfer.finished) throw new Error("SQLite read transfer has already reached its end");
if (transfer.record && transfer.record.offset === transfer.record.bytes.byteLength) transfer.record = void 0;
if (!transfer.record) {
const next = transfer.iterator.next();
if (next.done) {
cleanup(transfer);
transfer.finished = true;
return {
id,
sequence: transfer.sequence++,
done: true,
counts: [...transfer.counts]
};
}
const { kind } = next.value;
const count = transfer.counts.get(kind);
if (count === void 0) throw new Error("SQLite read transfer returned an unexpected record kind");
transfer.record = {
kind,
bytes: "serialized" in next.value ? next.value.serialized : serialize(next.value.value),
offset: 0
};
transfer.counts.set(kind, count + 1);
}
const record = transfer.record;
const offset = record.offset;
const end = Math.min(record.bytes.byteLength, offset + SQLITE_WORKER_TRANSFER_FRAME_BYTES);
record.offset = end;
return {
id,
sequence: transfer.sequence++,
done: false,
kind: record.kind,
recordBytes: record.bytes.byteLength,
offset,
recordDone: end === record.bytes.byteLength,
bytes: new Uint8Array(record.bytes.subarray(offset, end))
};
},
end(id) {
if (!requireTransfer(id).finished) throw new Error("SQLite read transfer ended before its complete result");
cancel();
},
cancel,
close: cancel
};
}
/** Reassembles one transfer; its caller owns transport completion and cancellation. */
function createSqliteWorkerTransferReceiver(handle, consume) {
const counts = new Map(handle.kinds.map((kind) => [kind, 0]));
let sequence = 0;
let finished = false;
let record;
return { accept(frame) {
try {
if (finished || frame.id !== handle.id || frame.sequence !== sequence++) throw new Error("SQLite read transfer frame is out of order");
if (frame.done) {
if (record || frame.counts.length !== counts.size || frame.counts.some(([kind, count]) => counts.get(kind) !== count) || new Set(frame.counts.map(([kind]) => kind)).size !== counts.size) throw new Error("SQLite read transfer ended with an incomplete result");
finished = true;
return frame.counts;
}
const count = counts.get(frame.kind);
if (count === void 0 || !Number.isSafeInteger(frame.recordBytes) || frame.recordBytes < 1 || !Number.isSafeInteger(frame.offset) || frame.offset < 0 || frame.bytes.byteLength < 1 || frame.bytes.byteLength > 8388608) throw new Error("SQLite read transfer returned an invalid frame");
if (!record) {
if (frame.offset !== 0) throw new Error("SQLite read transfer omitted the start of a record");
record = {
kind: frame.kind,
bytes: new Uint8Array(frame.recordBytes),
offset: 0
};
}
const end = frame.offset + frame.bytes.byteLength;
if (record.kind !== frame.kind || record.bytes.byteLength !== frame.recordBytes || record.offset !== frame.offset || end > frame.recordBytes || frame.recordDone !== (end === frame.recordBytes)) throw new Error("SQLite read transfer returned a discontinuous record");
record.bytes.set(frame.bytes, frame.offset);
record.offset = end;
if (frame.recordDone) {
const value = deserialize(record.bytes);
const kind = record.kind;
record = void 0;
consume({
kind,
value
});
counts.set(kind, count + 1);
}
return;
} catch (error) {
record = void 0;
finished = true;
throw error;
}
} };
}
var SQLITE_WORKER_TRANSFER_FRAME_BYTES;
var init_sqlite_worker_transfer = __esmMin((() => {
SQLITE_WORKER_TRANSFER_FRAME_BYTES = 8388608;
}));
//#endregion
//#region src/infra/sqlite-worker-broker-reply.ts
function dispatchSqliteWorkerJob(slot, job, onRejected) {
const actor = [...slot.actors].find((candidate) => candidate.id === job.request.actor);
const assertCurrentJob = () => {
if (slot.failed || slot.current !== job) throw slot.failed ?? new SqliteWorkerError("SQLite worker job is no longer current", "closed");
};
const assertDispatchable = () => {
if (!job.nativeDispatched) job.signal?.throwIfAborted();
job.assertCurrent?.();
assertCurrentJob();
};
try {
assertDispatchable();
prepareSqliteWorkerActorContext(actor, job);
job.request.operationAdmission = prepareSqliteWorkerOperationAdmission(job, actor, assertDispatchable, assertCurrentJob);
const request = prepareSqliteWorkerRequest(job);
assertDispatchable();
job.nativeDispatched = true;
job.detach();
if (job.dispatchState) job.dispatchState.dispatched = true;
job.requestPosted = true;
slot.worker.postMessage(request, request.operationAdmission ? [request.operationAdmission] : []);
} catch (error) {
onRejected(error, job.requestPosted === true);
}
}
function prepareSqliteWorkerOperationAdmission(job, actor, assertDispatchable, assertCurrentJob) {
const databasePath = job.request.stateDatabasePath ?? actor?.databasePath;
if (!job.createAdmission && !databasePath) return;
const settlement = createDeferredCore();
job.settleNative = settlement.resolve;
const retained = job.createAdmission ? job.createAdmission({ settled: settlement.promise }) : {
admission: createSqliteWorkerOperationAdmission(() => {
throw new SqliteWorkerError("SQLite domain operation requires its own admission", "closed");
}),
nativeLocations: databasePath ? [databasePath] : []
};
try {
if (databasePath) {
let schemaLease;
const assertAccess = () => {
assertCurrentJob();
job.maintenanceScope?.assertAdmission();
assertStateDatabaseAccessAllowed(databasePath, {
maintenanceScope: job.maintenanceScope,
schemaLease
});
};
retained.admission.bindDatabaseAuthority({
databasePath,
assertRequest: assertDispatchable,
assertAccess,
acquireSchema() {
assertAccess();
const acquire = () => acquireStateDatabaseSchemaLease(databasePath);
const lease = job.maintenanceScope ? job.maintenanceScope.run(acquire) : acquire();
schemaLease = lease;
job.maintenanceScope?.own(lease, "shared-resources", () => lease.release());
return {
assertCurrent() {
assertAccess();
lease.assertCurrent();
},
release: () => lease.release()
};
}
});
}
} catch (error) {
retained.admission.finish();
throw error;
}
job.operationAdmission = {
admission: retained.admission,
releaseService: retainSqliteWriteAdmissionService([
...retained.nativeLocations,
...databasePath ? [databasePath] : [],
...actor?.pathReferences.keys() ?? []
], () => retained.admission.service())
};
return retained.admission.port;
}
function prepareSqliteWorkerRequest(job) {
if (job.request.type !== "execute" || job.request.input.byteLength <= 33554432) return job.request;
const { input, ...request } = job.request;
const producer = createSqliteWorkerTransferOwner();
const transfer = producer.start([{
kind: "command",
serialized: input
}].values(), { kinds: ["command"] });
job.inputTransfer = {
id: transfer.id,
producer
};
job.request.input = /* @__PURE__ */ new Uint8Array();
return {
...request,
type: "execute-start",
transfer
};
}
function decodeSqliteWorkerReplyValue(job, reply) {
if (reply.input === "next") {
const transfer = job.inputTransfer;
if (!transfer || reply.transfer) throw new Error("SQLite worker requested unexpected command input");
const frame = transfer.producer.next(transfer.id);
const input = serialize(frame);
if (input.byteLength > 33554432) throw new Error("SQLite worker input frame exceeds the transport byte limit");
if (frame.done) {
transfer.producer.end(transfer.id);
job.inputTransfer = void 0;
}
return {
type: "continue",
request: {
type: "execute-frame",
id: job.request.id,
actor: job.request.actor,
input
}
};
}
if (job.inputTransfer) throw new Error("SQLite worker completed before receiving its command input");
let value;
if (reply.transfer === "start") {
const handle = deserialize(reply.value);
if (job.request.type !== "execute" || job.transfer || handle.kinds.length !== 1 || handle.kinds[0] !== "result") throw new Error("SQLite worker returned an unexpected result transfer");
const transfer = {
id: handle.id,
value: void 0,
receiver: createSqliteWorkerTransferReceiver(handle, (record) => {
transfer.value = record.value;
})
};
job.transfer = transfer;
} else if (reply.transfer === "frame") {
const transfer = job.transfer;
if (!transfer) throw new Error("SQLite worker returned an unexpected result frame");
const frame = deserialize(reply.value);
const counts = transfer.receiver.accept(frame);
if (counts) {
if (counts.length !== 1 || counts[0]?.[1] !== 1) throw new Error("SQLite worker returned an incomplete result transfer");
value = transfer.value;
job.transfer = void 0;
}
} else {
if (job.transfer) throw new Error("SQLite worker ended its result transfer without completion");
value = deserialize(reply.value);
}
return job.transfer ? {
type: "continue",
request: {
type: "result-next",
id: job.request.id,
actor: job.request.actor,
transferId: job.transfer.id
}
} : {
type: "complete",
value
};
}
function decodeSqliteWorkerReplyError(job, error) {
if (error.name === "SqliteWorkerAdmissionTimeoutError" && error.code === "admission-timeout") return new SqliteWorkerAdmissionTimeoutError();
const failure = Object.assign(new Error(error.message), {
name: error.name,
...error.code === void 0 ? {} : { code: error.code }
});
if (job.request.stateContext && error.code !== "outcome-unknown" && error.sharedState) retainOpenClawStateWorkerErrorPayload(failure, error.sharedState);
return failure;
}
function decodeSqliteWorkerCleanupError(payload) {
const failure = /* @__PURE__ */ new Error("SQLite worker native cleanup failed");
retainOpenClawStateWorkerErrorPayload(failure, payload);
return hydrateOpenClawStateWorkerError(failure, { includeOrdinary: true });
}
function receiveSqliteWorkerReply(slot, reply, owner) {
const job = slot.current;
if (!job || reply.id !== job.request.id) {
owner.fail(/* @__PURE__ */ new Error("SQLite worker returned an unexpected response"));
return;
}
if (!reply.ok) {
if (reply.cleanupFailure && job.nativeDispatched && !reply.retire) {
const admission = job.operationAdmission?.admission;
const original = (admission?.failureSource === "domain" && !reply.admissionRefused ? void 0 : admission?.failure) ?? decodeSqliteWorkerReplyError(job, reply.error);
owner.fail(decodeSqliteWorkerCleanupError(reply.cleanupFailure), void 0, void 0, { error: original });
return;
}
if (reply.openNotEntered && job.request.type === "open" && job.dispatchState) job.dispatchState.openNotEntered = true;
const error = decodeSqliteWorkerReplyError(job, reply.error);
if (job.request.type === "open" && reply.openNotEntered && !reply.retire) {
slot.current = void 0;
const refusal = job.operationAdmission?.admission.failure ?? error;
owner.finish(job, refusal, void 0, {
kind: "not-entered",
error: refusal
});
owner.dispatch();
return;
}
if (job.request.type !== "execute" || reply.retire) {
const refusedOpen = job.request.type === "open" && reply.openOutcome === "refused-before-agent-open";
const failure = refusedOpen || job.request.type === "open" && reply.admissionRefused ? toErrorObject(job.operationAdmission?.admission.failure ?? error, error.message) : error;
owner.fail(failure, job.request.type !== "execute" ? failure : void 0, refusedOpen ? "refused-before-agent-open" : void 0);
return;
}
slot.current = void 0;
owner.finish(job, job.operationAdmission?.admission.failure ?? error);
owner.dispatch();
return;
}
let value;
try {
const result = decodeSqliteWorkerReplyValue(job, reply);
if (result.type === "continue") {
slot.worker.postMessage(result.request, []);
return;
}
value = result.value;
} catch (error) {
owner.fail(error);
return;
}
if (reply.cleanupFailure) {
const admission = job.operationAdmission?.admission;
const failure = admission?.failureSource === "domain" ? void 0 : admission?.failure;
owner.fail(decodeSqliteWorkerCleanupError(reply.cleanupFailure), void 0, void 0, failure === void 0 ? { value } : { error: failure });
return;
}
slot.current = void 0;
if (job.request.type === "close") owner.finish(job, void 0, value, void 0, reply.closeReceipt);
else {
const admission = job.operationAdmission?.admission;
owner.finish(job, admission?.failureSource === "domain" ? void 0 : admission?.failure, value);
}
owner.dispatch();
}
/** Keep the original failure and outcome classification when retirement also fails. */
function withSqliteWorkerCleanupFailure(failure, cleanupError) {
if (cleanupError === void 0) return failure;
return retainSqliteWorkerErrorCode(new AggregateError([failure, cleanupError], "SQLite worker failure and cleanup failed", { cause: failure }), failure);
}
function settleFailedSqliteWorkerJobs({ queuedError, current, queued, error, currentError, completed, openOutcome, retire, finish }) {
const retirement = retire();
const finishFailed = (retired, cleanupError) => {
if (current && completed) {
process.emitWarning(new Error("SQLite worker operation completed before native cleanup failed", { cause: withSqliteWorkerCleanupFailure(error, cleanupError) }));
finish(current, "error" in completed ? completed.error : void 0, "value" in completed ? completed.value : void 0, retired ? { kind: "completed" } : {
kind: "unknown",
error: cleanupError ?? error
});
} else if (current) {
const failure = currentError ?? new SqliteWorkerError(`SQLite worker stopped before its result was received: ${error.message}`, current.request.type === "execute" && current.nativeDispatched ? "outcome-unknown" : "unavailable");
if (!currentError) failure.cause = error;
finish(current, withSqliteWorkerCleanupFailure(failure, cleanupError), void 0, current.nativeDispatched ? retired && openOutcome === "refused-before-agent-open" ? { kind: "completed" } : {
kind: "unknown",
error: currentError ?? error
} : {
kind: "not-entered",
error
});
}
for (const job of queued) finish(job, withSqliteWorkerCleanupFailure(queuedError, cleanupError));
};
retirement.then(() => finishFailed(!current?.operationAdmission?.admission.cleanupFailures.length), (cleanupError) => finishFailed(false, cleanupError));
}
function settleSqliteWorkerJob(job, error, value, settlement) {
job.settleNative?.(settlement ?? (job.nativeDispatched ? { kind: "completed" } : {
kind: "not-entered",
error
}));
job.operationAdmission?.admission.finish();
job.operationAdmission?.releaseService();
let failure = error;
const admissionCleanupFailures = job.operationAdmission?.admission.cleanupFailures ?? [];
if (admissionCleanupFailures.length > 0) {
const cleanupError = new AggregateError(admissionCleanupFailures, "SQLite worker admission cleanup failed");
if (error === void 0 && job.request.type === "execute") process.emitWarning(cleanupError);
else failure = error === void 0 ? cleanupError : withSqliteWorkerCleanupFailure(toErrorObject(error, "SQLite worker failed"), cleanupError);
}
job.inputTransfer?.producer.cancel();
job.inputTransfer = void 0;
job.transfer = void 0;
job.detach();
if (failure !== void 0) job.reject(failure);
else job.resolve(value);
}
var init_sqlite_worker_broker_reply = __esmMin((() => {
init_error_coercion();
init_deferred$1();
init_openclaw_state_worker_error();
init_gateway_state_owner();
init_sqlite_transaction();
init_sqlite_worker_broker_admission();
init_sqlite_worker_contract();
init_sqlite_worker_operation_admission();
init_sqlite_worker_transfer();
}));
//#endregion
//#region src/infra/worker-diagnostic-script.ts
/** Imported diagnostics may contain arbitrary paths or names. Preserve only known scripts. */
function normalizeDiagnosticWorkerScript(value) {
return typeof value === "string" && workerScriptNames.has(value) ? value : "other";
}
var workerScriptNames;
var init_worker_diagnostic_script = __esmMin((() => {
init_runtime_process_entrypoints();
workerScriptNames = /* @__PURE__ */ new Set([
...Object.values(runtimeProcessEntrypoints).map((entry) => basename(entry.distWorkerPath)),
"catalog-page.worker.js",
"code-mode.worker.js",
"compaction-planning.worker.js",
"disk-budget.worker.js",
"document-extractor.worker.js",
"manager-index.worker.js",
"manager-search.worker.js",
"memory-index.worker.js",
"memory-search.worker.js",
"session-history.worker.js",
"audio-worker.runtime.js",
"realtime-quicksilver-audio.worker.js",
"realtime-quicksilver-socket.worker.js",
"telegram-ingress-worker.runtime.js"
]);
}));
//#endregion
//#region src/infra/worker-cpu.ts
function workerScriptName(filename, evalSource = false) {
if (evalSource || filename instanceof URL && filename.protocol !== "file:") return "other";
return normalizeDiagnosticWorkerScript(basename(filename instanceof URL ? fileURLToPath(filename) : filename).replace(/\.[cm]?ts$/u, ".js"));
}
function createCpuTrackedWorker(...args) {
const worker = new Worker(...args);
trackWorker(worker);
trackedWorkers.workers.get(worker).script = workerScriptName(args[0], args[1]?.eval);
return worker;
}
function forgetWorker(worker) {
const source = trackedWorkers.workers.get(worker);
if (!source) return;
const counts = countWorkerStart(source);
const reason = source.retirementReason ?? "exit";
counts.retired.set(reason, (counts.retired.get(reason) ?? 0) + 1);
source.memoryPort?.close();
trackedWorkers.workers.delete(worker);
trackedWorkers.revision++;
}
function countWorkerStart(source) {
let counts = trackedWorkers.lifecycle.get(source.script);
if (!counts) {
counts = {
started: 0,
retired: /* @__PURE__ */ new Map()
};
trackedWorkers.lifecycle.set(source.script, counts);
}
if (!source.started) {
source.started = true;
counts.started++;
}
return counts;
}
function trackWorker(worker) {
if (trackedWorkers.workers.has(worker)) return;
let pending = false;
const source = {
script: "other",
async cpuUsage() {
if (pending) return;
pending = true;
try {
return await worker.cpuUsage();
} catch {
return;
} finally {
pending = false;
}
}
};
trackedWorkers.workers.set(worker, source);
queueMicrotask(() => countWorkerStart(source));
trackedWorkers.revision++;
worker.once("exit", () => forgetWorker(worker));
}
var trackedWorkers;
var init_worker_cpu = __esmMin((() => {
init_number_coercion();
init_global_singleton();
init_worker_diagnostic_script();
trackedWorkers = resolveGlobalSingleton(Symbol.for("openclaw.workerCpuSources"), () => {
process.on("worker", trackWorker);
return {
revision: 0,
nextPoolId: 0,
poolIds: /* @__PURE__ */ new WeakMap(),
workers: /* @__PURE__ */ new Map(),
lifecycle: /* @__PURE__ */ new Map()
};
});
}));
//#endregion
//#region src/infra/sqlite-worker-broker-lifecycle.ts
/** The broker retains these maps; this owner drains clients before native close custody. */
function createSqliteWorkerLifecycle({ actors, slots, stores, enqueueClose, fail }) {
function createSlot(options, borrowedGenerationSlot, createReplyOwner) {
if (process.versions.bun && process.platform === "darwin") ensureSqliteLibrarySelected();
options.assertCurrent?.();
const worker = runOutsideCaller(() => createCpuTrackedWorker(options.carrierUrl, {
resourceLimits: { maxOldGenerationSizeMb: 512 },
env: resolveNodeCompileCacheEnv(),
execArgv: resolveRuntimeWorkerThreadExecArgv(options.carrierUrl)
}));
const exited = createDeferredCore();
const slot = {
runtimeGeneration: options.runtimeGeneration,
...borrowedGenerationSlot ? { borrowedGenerationSlot: true } : {},
worker,
receiveReply: (reply) => receiveSqliteWorkerReply(slot, reply, replyOwner),
actors: /* @__PURE__ */ new Set(),
queue: [],
exit: exited.promise,
exited: false,
pendingOpens: 1
};
const replyOwner = createReplyOwner(slot);
slots.add(slot);
worker.on("message", (reply) => slot.receiveReply(reply));
worker.on("error", (error) => fail(slot, error));
worker.on("messageerror", (error) => fail(slot, error));
worker.once("exit", (code) => {
slot.exited = true;
for (const actor of slot.actors) {
actor.backendClosed = true;
actor.markNativeStopped();
}
fail(slot, /* @__PURE__ */ new Error(`SQLite worker exited with code ${code}`));
slots.delete(slot);
exited.resolve();
});
worker.unref();
return slot;
}
async function settleGeneration(generation) {
const retained = [...actors.values()].filter((actor) => actor.runtimeGeneration === generation);
const retirement = Promise.allSettled(retained.map((actor) => retireActor(actor)));
await Promise.all(retained.map(async (actor) => await actor.settlement));
return async () => {
throwSqliteLifecycleErrors((await retirement).flatMap((result) => result.status === "rejected" ? [result.reason] : []), "Retained SQLite worker cleanup failed");
await Promise.all([...slots].filter((slot) => slot.runtimeGeneration === generation).map((slot) => retireEmpty(slot)));
};
}
function releaseActorReference(actor) {
actor.references -= 1;
if (!actor.references) actor.onReferencesDrained?.();
}
async function rejectSlotAdmission(slot, error) {
slot.pendingOpens -= 1;
try {
await retireEmpty(slot);
} catch (cleanupError) {
throw createSqliteLifecycleAggregateError([error, cleanupError], "SQLite slot admission and cleanup failed", error);
}
throw error;
}
function retireActor(identity) {
const actor = [...actors.values()].find((entry) => entry === identity);
if (!actor) return Promise.resolve();
if (actor.retirement) return actor.retirement;
actor.retirementRequested = true;
const drained = createDeferredCore();
actor.onReferencesDrained = drained.resolve;
if (!actor.references) drained.resolve();
actor.settlement = drained.promise;
const clients = [...stores.values()].filter((client) => client.actor === actor);
actor.retirement = (async () => {
const results = await Promise.allSettled(clients.map((client) => client.close()));
await actor.settlement;
const errors = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
if (!errors.length) try {
await closeActor(actor);
} catch (error) {
errors.push(error);
}
if (errors.length) throw new AggregateError(errors, "SQLite actor retirement failed", { cause: errors[0] });
})().finally(() => {
actor.retirement = void 0;
actor.onReferencesDrained = void 0;
});
return actor.retirement;
}
function closeActor(actor, maintenanceScope) {
if (actor.cleanupState === "complete") return Promise.resolve();
if (actor.closing) return actor.closing;
actor.cleanupState = "pending";
actor.closing = (async () => {
const errors = [];
if (!actor.backendClosed) try {
await enqueueClose(actor, maintenanceScope);
actor.backendClosed = true;
if (!process.versions.bun) actor.markNativeStopped();
} catch (error) {
errors.push(error);
fail(actor.slot, error instanceof Error ? error : new Error(String(error)));
await actor.slot.exit;
}
try {
if (process.versions.bun || actor.slot.failed || !actor.slot.pendingOpens && [...actor.slot.actors].every((entry) => entry.backendClosed)) await retire(actor.slot);
} catch (error) {
errors.push(error);
} finally {
forget(actor);
}
throwSqliteLifecycleErrors(errors, "SQLite worker actor cleanup failed");
})().finally(() => {
actor.closing = void 0;
});
return actor.closing;
}
function forget(actor) {
if (actors.get(actor.key) === actor) actors.delete(actor.key);
actor.slot.actors.delete(actor);
actor.cleanupState = "complete";
}
async function retireEmpty(slot) {
if (!slot.actors.size && !slot.pendingOpens) await retire(slot);
}
function retire(slot) {
slot.retiring ??= (async () => {
const errors = [];
if (!slot.exited) try {
await slot.worker.terminate();
} catch (error) {
errors.push(error);
}
await slot.exit;
throwSqliteLifecycleErrors(errors, "SQLite worker retirement cleanup failed");
})().finally(() => {
slot.retiring = void 0;
});
return slot.retiring;
}
return {
createSlot,
settleGeneration,
releaseActorReference,
rejectSlotAdmission,
retireActor,
closeActor,
forget,
retireEmpty,
retire
};
}
var runOutsideCaller;
var init_sqlite_worker_broker_lifecycle = __esmMin((() => {
init_deferred$1();
init_bun_sqlite_library();
init_node_compile_cache_env();
init_runtime_worker_url();
init_sqlite_lifecycle_errors();
init_sqlite_worker_broker_reply();
init_worker_cpu();
runOutsideCaller = AsyncLocalStorage.snapshot();
}));
//#endregion
//#region src/infra/sqlite-worker-client.ts
function runSqliteWorkerClientOperation(client, operation, stateContext, track, assertCurrent, createAdmission) {
if (!client || client.sealed) return Promise.reject(new SqliteWorkerError("SQLite worker store is closed", "closed"));
const scope = {
maintenanceScope: getOpenClawDatabaseMaintenanceScope(),
createAdmission,
assertCurrent,
active: true,
pending: /* @__PURE__ */ new Set(),
...stateContext ? { stateContext: captureSqliteWorkerStateContext(stateContext) } : {}
};
const released = createDeferredCore();
client.scopes.add(released.promise);
const untrack = track(released.promise);
return (async () => {
try {
const result = operation({ execute: (command, options = {}) => client.execute(command, options, scope) });
return isPromise(result) ? await result : result;
} finally {
scope.active = false;
await Promise.allSettled(scope.pending);
client.scopes.delete(released.promise);
untrack();
released.resolve();
}
})();
}
function createSqliteWorkerClient(owner) {
let closed;
const pending = /* @__PURE__ */ new Set();
const client = {
actor: owner.actor,
close: () => store.close(),
sealed: owner.isDraining(),
isAvailable: owner.isAvailable,
scopes: /* @__PURE__ */ new Set(),
execute: (command, options, scope) => {
if (scope ? !scope.active : closed || client.sealed || owner.isDraining()) return Promise.reject(new SqliteWorkerError("SQLite worker store is closed", "closed"));
if (options.signal?.aborted) return Promise.reject(toErrorObject(options.signal.reason, "SQLite worker operation canceled"));
let payload;
let assertCurrent;
const admission = scope?.assertCurrent;
const createAdmission = scope?.createAdmission;
const inCaller = admission || createAdmission ? AsyncLocalStorage.snapshot() : void 0;
try {
const commandType = command.type;
assertCurrent = admission && inCaller ? () => inCaller(admission, commandType) : void 0;
assertCurrent?.();
payload = serialize({
type: commandType,
input: command.input
});
} catch (error) {
return Promise.reject(toErrorObject(error, "SQLite worker command could not be serialized"));
}
const operation = owner.dispatch(payload, options.signal, scope, assertCurrent, createAdmission && inCaller ? (admissionOperation) => inCaller(createAdmission, admissionOperation) : void 0);
pending.add(operation);
scope?.pending.add(operation);
const settled = () => {
pending.delete(operation);
scope?.pending.delete(operation);
};
operation.then(settled, settled);
return operation;
}
};
const store = {
execute: (command, options = {}) => client.execute(command, options),
close: () => {
if (!closed) {
client.sealed = true;
closed = (async () => {
await Promise.allSettled(client.scopes);
await Promise.allSettled(pending);
await owner.release();
})().catch((error) => {
closed = void 0;
throw error;
});
}
return closed;
}
};
return {
store,
client
};
}
var init_sqlite_worker_client = __esmMin((() => {
init_error_coercion();
init_deferred$1();
init_openclaw_state_db_async_lifecycle();
init_sqlite_worker_contract();
init_sqlite_worker_state_context();
}));
//#endregion
//#region src/infra/sqlite-worker-input-admission.ts
var SqliteWorkerInputAdmission;
var init_sqlite_worker_input_admission = __esmMin((() => {
init_deferred$1();
init_sqlite_worker_contract();
SqliteWorkerInputAdmission = class {
constructor(owner) {
this.owner = owner;
this.bytes = 0;
this.inputPreparationGeneration = {};
this.inputPreparations = /* @__PURE__ */ new Set();
this.openTail = Promise.resolve();
}
get retainedBytes() {
return this.bytes;
}
retain(bytes) {
this.bytes += bytes;
let released = false;
return () => {
if (!released) {
released = true;
this.bytes -= bytes;
}
};
}
open(bytes, dispatch) {
if (bytes > this.owner.maxMessageBytes || this.owner.queuedBytes() + this.bytes + bytes > this.owner.maxQueuedBytes) return Promise.reject(new SqliteWorkerError("SQLite worker open input capacity reached", "overloaded"));
const previous = this.openTail;
const settled = createDeferredCore();
this.openTail = settled.promise;
const release = this.retain(bytes);
return previous.then(dispatch).finally(() => {
release();
settled.resolve();
});
}
joinOpens() {
return this.openTail;
}
invalidatePreparations() {
this.inputPreparationGeneration = {};
}
async joinPreparations() {
await Promise.allSettled(this.inputPreparations);
}
reserveInputPreparation(inputBytes, retention = "stream") {
if (!Number.isSafeInteger(inputBytes) || inputBytes < 0) throw new RangeError("SQLite worker input bytes must be a non-negative safe integer");
if (this.owner.isClosing()) throw new SqliteWorkerError("SQLite worker host is closing", "closed");
const bytes = retention === "stream" && inputBytes > this.owner.maxQueuedInputBytes ? this.owner.maxMessageBytes : inputBytes;
if (this.owner.queuedBytes() + this.bytes + bytes > this.owner.maxQueuedBytes) throw new SqliteWorkerError("SQLite worker input preparation capacity reached", "overloaded");
const generation = this.inputPreparationGeneration;
this.bytes += bytes;
const settled = createDeferredCore();
this.inputPreparations.add(settled.promise);
let released = false;
let handedOff = false;
const release = () => {
if (!released) {
released = true;
this.bytes -= bytes;
this.inputPreparations.delete(settled.promise);
settled.resolve();
}
};
const assertCurrent = () => {
if (!handedOff && (released || this.owner.isClosing() || generation !== this.inputPreparationGeneration)) throw new SqliteWorkerError("SQLite worker input preparation is closed", "closed");
};
return {
assertCurrent,
handoff: (dispatch) => {
try {
if (released) throw new SqliteWorkerError("SQLite worker input preparation is closed", "closed");
assertCurrent();
} catch (error) {
release();
throw error;
}
handedOff = true;
release();
return dispatch();
},
release
};
}
};
})), ADMISSION_TIMEOUT_MS, MAX_STORES, MAX_QUEUED_COMMAND_BYTES, SQLITE_WORKER_MAX_QUEUED_BYTES, SqliteWorkerBroker;
var init_sqlite_worker_broker = __esmMin((() => {
init_error_coercion();
init_logger();
init_deferred$1();
init_openclaw_state_db_async_lifecycle();
init_gateway_state_owner();
init_runtime_worker_url();
init_sqlite_worker_broker_admission();
init_sqlite_worker_broker_lifecycle();
init_sqlite_worker_broker_reply();
init_sqlite_worker_client();
init_sqlite_worker_contract();
init_sqlite_worker_input_admission();
init_sqlite_worker_state_context();
ADMISSION_TIMEOUT_MS = 1e4;
MAX_STORES = 64;
MAX_QUEUED_COMMAND_BYTES = 67108864;
SQLITE_WORKER_MAX_QUEUED_BYTES = 268435456;
SqliteWorkerBroker = class {
constructor() {
this.maxWorkers = Math.min(8, Math.max(2, Math.floor(availableParallelism() / 8)));
this.waiters = /* @__PURE__ */ new Map();
this.resuming = /* @__PURE__ */ new Set();
this.nextAdmissionWarning = 0;
this.actors = /* @__PURE__ */ new Map();
this.slots = /* @__PURE__ */ new Set();
this.clients = /* @__PURE__ */ new Set();
this.stores = /* @__PURE__ */ new Map();
this.operations = /* @__PURE__ */ new Set();
this.lifecycle = createSqliteWorkerLifecycle({
actors: this.actors,
slots: this.slots,
stores: this.stores,
enqueueClose: (actor, maintenanceScope) => this.enqueue(actor.slot, {
type: "close",
actor: actor.id
}, 0, { maintenanceScope }),
fail: (slot, error) => this.fail(slot, error)
});
this.nextActor = 0;
this.nextRequest = 0;
this.requests = /* @__PURE__ */ new WeakMap();
this.bytes = 0;
this.inputAdmission = new SqliteWorkerInputAdmission({
queuedBytes: () => this.bytes,
isClosing: () => this.draining !== void 0,
maxQueuedBytes: SQLITE_WORKER_MAX_QUEUED_BYTES,
maxQueuedInputBytes: MAX_QUEUED_COMMAND_BYTES,
maxMessageBytes: SQLITE_WORKER_MAX_MESSAGE_BYTES
});
}
reserveInputPreparation(inputBytes, retention = "stream") {
return this.inputAdmission.reserveInputPreparation(inputBytes, retention);
}
open(options, stateContext, assertCurrent, custody = {}) {
try {
validateSqliteWorkerDatabaseLocator(options.databasePath);
} catch (error) {
return Promise.reject(toErrorObject(error, "SQLite worker database locator is invalid"));
}
if (this.draining) return Promise.reject(new SqliteWorkerError("SQLite worker host is closing", "closed"));
if (this.clients.size >= MAX_STORES) return Promise.reject(new SqliteWorkerError("SQLite worker store capacity reached", "overloaded"));
const client = {};
this.clients.add(client);
let snapshot;
try {
snapshot = captureSqliteWorkerOpen(options, stateContext, assertCurrent, custody);
const generation = options.runtimeGeneration;
generation?.retain(this, async () => {
await this.inputAdmission.joinOpens();
return await this.lifecycle.settleGeneration(generation);
});
} catch (error) {
this.clients.delete(client);
return Promise.reject(toErrorObject(error, "SQLite worker input could not be serialized"));
}
return this.inputAdmission.open(sqliteWorkerRequestBytes(snapshot.input, snapshot.stateContext, snapshot.preparation), () => this.openAdmitted(snapshot, client)).catch((error) => {
this.clients.delete(client);
throw error;
});
}
async openAdmitted(options, client) {
options.assertCurrent?.();
const { databasePath, inputHash, identity } = await prepareSqliteWorkerDatabaseAdmission(options);
options.assertCurrent?.();
assertStateDatabaseAccessAllowed(options.stateDatabasePath ?? databasePath, { maintenanceScope: options.maintenanceScope });
const input = options.input;
const { key } = identity;
const admittedPaths = captureSqliteWorkerAdmissionPaths(databasePath, identity, this.actors.values());
if (options.existingOnly && !key.startsWith("file:")) {
this.clients.delete(client);
return;
}
const { modulePath, moduleUrl } = await resolveSqliteWorkerModuleUrl(options.moduleUrl);
options.assertCurrent?.();
let actor = this.actors.get(key);
if (actor?.retirementRequested) {
if (actor.retirement) {
await actor.retirement;
return this.openAdmitted(options, client);
}
throw new SqliteWorkerError("SQLite actor retirement must finish before reopening", "closed");
}
if (actor?.cleanupState === "pending") {
if (actor.closing) {
await actor.closing;
return this.openAdmitted(options, client);
}
throw new SqliteWorkerError("SQLite worker cleanup is pending; retry close before reopening", "closed");
}
if (actor) {
assertSqliteWorkerActorReusable(actor, moduleUrl, inputHash, options.stateContext);
actor.references += 1;
} else {
const slot = await this.acquireSlot(options);
try {
options.assertCurrent?.();
} catch (error) {
return this.lifecycle.rejectSlotAdmission(slot, error);
}
const nativeStopped = createDeferredCore();
actor = {
runtimeGeneration: options.runtimeGeneration,
nativeStopped: nativeStopped.promise,
markNativeStopped: nativeStopped.resolve,
id: ++this.nextActor,
key,
pathReferences: new Map([...admittedPaths].map((pathname) => [pathname, 1])),
moduleUrl,
inputHash,
slot,
references: 1,
opened: Promise.resolve(),
openDispatch: { dispatched: false },
initialized: false,
backendClosed: false,
databasePath,
stateContext: options.stateContext,
stateDatabasePath: options.stateDatabasePath
};
this.actors.set(key, actor);
slot.actors.add(actor);
slot.pendingOpens -= 1;
const opening = actor;
opening.opened = this.enqueue(slot, {
type: "open",
actor: actor.id,
moduleUrl,
databasePath,
...options.createAdmission ? { openAdmission: "input" } : options.createOpenAdmission ? { openAdmission: "identity" } : {},
...options.existingOnly ? { existingIdentity: key } : {},
input,
...options.preparation ? { preparation: options.preparation } : {},
...runtimeNeedsTypeScriptLoader(modulePath) ? { sourceLoaderUrl: import.meta.resolve("tsx/esm/api") } : {}
}, sqliteWorkerRequestBytes(input, options.stateContext, options.preparation), {
dispatchState: opening.openDispatch,
signal: options.signal,
assertCurrent: options.assertCurrent,
maintenanceScope: options.maintenanceScope,
createAdmission: options.createAdmission ?? options.createOpenAdmission
}).then(async () => {
opening.initialized = true;
const physical = await resolveOpenedSqliteWorkerIdentity(databasePath, identity, (id) => {
const existing = this.actors.get(id);
return existing !== void 0 && existing !== opening;
});
if (physical !== key) {
this.actors.delete(key);
opening.key = physical;
this.actors.set(physical, opening);
}
});
}
const admittedActor = actor;
try {
retainSqliteWorkerAdmissionCleanup(admittedActor, options.retainCleanup, () => this.lifecycle.closeActor(admittedActor, options.maintenanceScope));
options.onNativeStopped?.(actor.nativeStopped, () => admittedActor.closeReceipt);
await actor.opened;
options.assertCurrent?.();
if (actor.retirementRequested) throw new SqliteWorkerError("SQLite actor retired during client admission", "closed");
if (actor.slot.failed) throw actor.slot.failed;
} catch (error) {
this.lifecycle.releaseActorReference(actor);
if (!actor.references) {
const errors = [error];
try {
if (actor.initialized) await this.lifecycle.closeActor(actor, options.maintenanceScope);
else {
if ((!actor.openDispatch.dispatched || actor.openDispatch.openNotEntered) && !actor.slot.failed) {
actor.backendClosed = true;
actor.markNativeStopped();
actor.cleanupState = "pending";
}
if (actor.openDispatch.dispatched && !actor.openDispatch.openNotEntered) {
this.fail(actor.slot, error);
await actor.slot.exit;
}
this.lifecycle.forget(actor);
await this.lifecycle.retireEmpty(actor.slot);
}
} catch (cleanupError) {
errors.push(cleanupError);
}
if (errors.length > 1) throw new AggregateError(errors, "SQLite worker admission and cleanup failed", { cause: error });
}
throw error;
}
const owned = actor;
const releasePaths = retainSqliteWorkerAdmissionPathReferences(owned, admittedPaths);
let referenceReleased = false;
const { store, client: storeClient } = createSqliteWorkerClient({
actor: owned,
isDraining: () => this.draining !== void 0,
isAvailable: () => !owned.slot.failed && !owned.cleanupState && !owned.retirementRequested,
dispatch: (payload, signal, scope, assertCurrent, createAdmission) => this.enqueue(owned.slot, {
type: "execute",
actor: owned.id,
input: payload,
...scope?.stateContext ? { stateContext: scope.stateContext } : {}
}, sqliteWorkerRequestBytes(payload, scope?.stateContext), {
signal,
scope,
assertCurrent,
createAdmission,
maintenanceScope: scope ? scope.maintenanceScope : getOpenClawDatabaseMaintenanceScope()
}),
release: async () => {
if (!referenceReleased) {
referenceReleased = true;
this.lifecycle.releaseActorReference(owned);
this.stores.delete(store);
this.clients.delete(client);
releasePaths();
}
if (this.draining) await this.draining;
else if (owned.slot.failed) await owned.slot.exit;
if (!owned.references) await this.lifecycle.closeActor(owned, options.maintenanceScope);
}
});
this.stores.set(store, storeClient);
return store;
}
runOperation(store, operation, stateContext, assertCurrent, createAdmission) {
return runSqliteWorkerClientOperation(this.draining ? void 0 : this.stores.get(store), operation, stateContext, (pending) => {
this.operations.add(pending);
return () => this.operations.delete(pending);
}, assertCurrent, createAdmission);
}
isAvailable(store) {
return this.stores.get(store)?.isAvailable() ?? false;
}
retireActor(identity) {
return this.lifecycle.retireActor(identity);
}
getActorIdentity(store) {
const client = this.stores.get(store);
if (!client || client.sealed || !client.actor.stateContext) throw new SqliteWorkerError("SQLite shared actor binding is unavailable", "closed");
return client.actor;
}
hasUnclaimedSharedStateCleanup(databasePath) {
return findUnclaimedSharedStateActors(this.actors.values(), databasePath).length > 0;
}
async closeUnclaimedSharedState(databasePath) {
await this.inputAdmission.joinOpens();
await closeUnclaimedSharedStateActors(this.actors.values(), databasePath, (actor) => this.lifecycle.closeActor(actor));
}
async acquireSlot(options) {
options.assertCurrent?.();
const available = [...this.slots].filter((slot) => !slot.failed && !slot.retiring && slot.runtimeGeneration === options.runtimeGeneration);
const borrowedGenerationSlot = !process.versions.bun && options.runtimeGeneration !== void 0 && available.length === 0 && this.slots.size >= this.maxWorkers && ![...this.slots].some((slot) => slot.borrowedGenerationSlot);
if (!borrowedGenerationSlot && this.slots.size >= (process.versions.bun ? MAX_STORES : this.maxWorkers)) {
if (!available.length || process.versions.bun) {
const retiring = [...this.slots].filter((slot) => Boolean(slot.failed || slot.retiring));
if (retiring.length > 0) {
await Promise.race(retiring.map(({ exit }) => exit));
return this.acquireSlot(options);
}
if (process.versions.bun) throw new SqliteWorkerError("SQLite worker store capacity reached", "overloaded");
if (!available.length) throw new SqliteWorkerError("SQLite worker runtime capacity reached", "overloaded");
}
const selected = available.reduce((left, right) => left.actors.size <= right.actors.size ? left : right);
selected.pendingOpens += 1;
return selected;
}
return this.lifecycle.createSlot(options, borrowedGenerationSlot, (slot) => ({
fail: (reason, currentError, openOutcome, completed) => this.fail(slot, reason, currentError, openOutcome, completed),
finish: (job, error, value, settlement, closeReceipt) => {
if (job.request.type === "close" && closeReceipt) {
const actor = [...slot.actors].find((candidate) => candidate.id === job.request.actor);
if (actor) actor.closeReceipt = closeReceipt;
}
this.finish(slot, job, error, value, settlement);
},
dispatch: () => this.dispatch(slot)
}));
}
enqueue(slot, body, bytes, options = {}, admitted = false) {
const { signal, dispatchState, scope, assertCurrent, createAdmission, maintenanceScope } = options;
if (this.draining && body.type !== "close" && !scope?.active) return Promise.reject(new SqliteWorkerError("SQLite worker host is closing", "closed"));
if (slot.failed) return Promise.reject(slot.failed);
const activeInput = body.type === "execute" && bytes > MAX_QUEUED_COMMAND_BYTES;
const reservedBytes = activeInput ? SQLITE_WORKER_MAX_MESSAGE_BYTES : bytes;
if (body.type !== "close" && (body.type !== "execute" && bytes > 33554432 || activeInput && (slot.current || slot.queue.length > 0 || slot.pendingOpens > 0) || this.bytes + this.inputAdmission.retainedBytes + reservedBytes > SQLITE_WORKER_MAX_QUEUED_BYTES)) return Promise.reject(new SqliteWorkerError("SQLite worker queue capacity reached", "overloaded"));
if (body.type !== "close" && ((this.requests.get(slot) ?? 0) >= 128 || !admitted && this.waiters.has(slot))) {
if (activeInput || this.draining) return Promise.reject(new SqliteWorkerError("SQLite worker queue capacity reached", "overloaded"));
return this.waitForCapacity(slot, body, bytes, options);
}
const result = createDeferredCore();
const job = {
signal,
maintenanceScope,
createAdmission,
assertCurrent,
dispatchState,
request: {
...body,
id: ++this.nextRequest
},
bytes: reservedBytes,
resolve: result.resolve,
reject: result.reject,
detach: () => signal?.removeEventListener("abort", abort)
};
const abort = () => {
const index = slot.queue.indexOf(job);
if (index >= 0) {
slot.queue.splice(index, 1);
this.finish(slot, job, signal?.reason ?? /* @__PURE__ */ new Error("SQLite worker operation canceled"));
}
};
this.requests.set(slot, (this.requests.get(slot) ?? 0) + 1);
this.bytes += reservedBytes;
if (activeInput) {
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) this.finish(slot, job, signal.reason ?? /* @__PURE__ */ new Error("SQLite worker operation canceled"));
else this.dispatchJob(slot, job);
return result.promise;
}
slot.queue.push(job);
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) abort();
this.dispatch(slot);
return result.promise;
}
waitForCapacity(slot, body, bytes, options) {
return new Promise((resolve, reject) => {
const started = Date.now();
const signal = options.signal;
const waiters = this.waiters.get(slot) ?? /* @__PURE__ */ new Set();
const resume = (error) => {
if (!waiters.delete(resume)) return;
if (!waiters.size) this.waiters.delete(slot);
clearTimeout(timer);
signal?.removeEventListener("abort", abort);
releaseInput();
let failure = error;
if (failure === void 0 && Date.now() - started >= ADMISSION_TIMEOUT_MS) {
this.warnAdmission(slot, Date.now() - started);
failure = new SqliteWorkerError("SQLite worker queue capacity reached", "overloaded");
}
if (failure !== void 0) reject(toErrorObject(failure, "SQLite worker admission failed"));
else resolve(this.enqueue(slot, body, bytes, options, true));
};
const abort = () => resume(signal?.reason ?? /* @__PURE__ */ new Error("SQLite worker operation canceled"));
const timer = setTimeout(() => {
this.warnAdmission(slot, Date.now() - started);
resume(new SqliteWorkerError("SQLite worker queue capacity reached", "overloaded"));
}, ADMISSION_TIMEOUT_MS);
const releaseInput = this.inputAdmission.retain(bytes);
waiters.add(resume);
this.waiters.set(slot, waiters);
signal?.addEventListener("abort", abort, { once: true });
if (signal?.aborted) abort();
else if (waiters.size >= 128) this.warnAdmission(slot, 0);
});
}
warnAdmission(slot, waitMs) {
const now = Date.now();
if (now >= this.nextAdmissionWarning) {
this.nextAdmissionWarning = now + ADMISSION_TIMEOUT_MS;
getChildLogger({ subsystem: "infra/sqlite-worker" }).warn("SQLite worker admission delayed", {
queueDepth: this.waiters.get(slot)?.size ?? 0,
waitMs
});
}
}
dispatch(slot) {
if (slot.current || slot.failed) return;
const job = slot.queue.shift();
if (!job) {
slot.worker.unref();
return;
}
this.dispatchJob(slot, job);
}
dispatchJob(slot, job) {
slot.current = job;
slot.worker.ref();
dispatchSqliteWorkerJob(slot, job, (error, retire) => {
if (slot.current !== job) return;
if (retire) this.fail(slot, error, toErrorObject(error, "SQLite worker transfer failed"));
else {
slot.current = void 0;
this.finish(slot, job, error);
this.dispatch(slot);
}
});
}
finish(slot, job, error, value, settlement) {
this.requests.set(slot, (this.requests.get(slot) ?? 0) - 1);
this.bytes -= job.bytes;
settleSqliteWorkerJob(job, error, value, settlement);
if (!this.resuming.has(slot)) {
this.resuming.add(slot);
while ((this.requests.get(slot) ?? 0) < 128) {
const resume = this.waiters.get(slot)?.values().next().value;
if (!resume) break;
resume();
}
this.resuming.delete(slot);
}
}
fail(slot, reason, currentError, openOutcome, completed) {
if (slot.failed) return;
const error = toErrorObject(reason, "SQLite worker failed");
slot.failed = new SqliteWorkerError(error.message, "unavailable");
for (const resume of this.waiters.get(slot) ?? []) resume(slot.failed);
const current = slot.current;
slot.current = void 0;
if (current) {
current.inputTransfer?.producer.cancel();
current.inputTransfer = void 0;
current.transfer = void 0;
}
const queued = slot.queue.splice(0);
settleFailedSqliteWorkerJobs({
queuedError: slot.failed,
current,
queued,
error,
currentError,
completed,
openOutcome,
retire: () => this.lifecycle.retire(slot),
finish: (job, failure, value, settlement) => this.finish(slot, job, failure, value, settlement)
});
}
close() {
this.draining ??= (async () => {
this.inputAdmission.invalidatePreparations();
for (const waiters of this.waiters.values()) for (const resume of waiters) resume(new SqliteWorkerError("SQLite worker host is closing", "overloaded"));
for (const client of this.stores.values()) client.sealed = true;
await this.inputAdmission.joinOpens();
await Promise.allSettled(this.operations);
const errors = (await Promise.allSettled([...this.actors.values()].map((actor) => this.lifecycle.closeActor(actor)))).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
await this.inputAdmission.joinPreparations();
if (errors.length) throw new AggregateError(errors, "SQLite worker host cleanup failed");
})().finally(() => {
this.clients.clear();
this.stores.clear();
this.draining = void 0;
});
return this.draining;
}
};
}));
//#endregion
//#region src/infra/sqlite-worker-store.ts
function withCallerErrors(result) {
return result.catch((error) => {
if (error instanceof Error) throw hydrateOpenClawStateWorkerError(error);
throw error;
});
}
function bindCallerExecute(scope) {
return { execute: (command, options) => {
const result = withCallerErrors(scope.execute(command, options));
result.catch(() => void 0);
return result;
} };
}
/** Retain one actor through local reconciliation; the callback must not await its own close. */
function runSqliteWorkerStoreOperation(store, operation, stateContext, assertCurrent, createAdmission) {
return withCallerErrors(resolveSqliteWorkerBroker().runOperation(store, (scope) => operation(bindCallerExecute(scope)), stateContext, assertCurrent, createAdmission));
}
function resolveSqliteWorkerBroker() {
return resolveGlobalSingleton(Symbol.for("openclaw.sqliteWorkerBroker"), () => new SqliteWorkerBroker(), (broker) => withCallerErrors(broker.close()));
}
/** Read the broker's recorded lifecycle state without probing native storage. */
function isSqliteWorkerStoreAvailable(store) {
return resolveSqliteWorkerBroker().isAvailable(store);
}
/** Internal identity for the existing canonical actor, never a transferable authority. */
function getSqliteWorkerActorIdentity(store) {
return resolveSqliteWorkerBroker().getActorIdentity(store);
}
function retireSqliteWorkerActor(identity) {
return withCallerErrors(resolveSqliteWorkerBroker().retireActor(identity));
}
/** Recorded orphan custody at its original shared-state opening path. */
function hasUnclaimedSharedStateSqliteCleanup(databasePath) {
return resolveSqliteWorkerBroker().hasUnclaimedSharedStateCleanup(databasePath);
}
/** Explicit cleanup only; referenced actors and other opening scopes are untouched. */
function closeUnclaimedSharedStateSqliteWorkers(databasePath) {
return withCallerErrors(resolveSqliteWorkerBroker().closeUnclaimedSharedState(databasePath));
}
/** Host-internal admission for the canonical shared-state actor. */
function openSharedStateSqliteWorkerStore(options, stateContext, assertCurrent, lifecycle) {
if (!isMainThread) return Promise.reject(new SqliteWorkerError("Shared-state admission requires the host broker", "unavailable"));
return withCallerErrors(resolveSqliteWorkerBroker().open({
...options,
input: void 0
}, stateContext, assertCurrent, lifecycle)).then((store) => {
if (store) {
const execute = store.execute.bind(store);
const close = store.close.bind(store);
store.execute = bindCallerExecute({ execute }).execute;
store.close = () => withCallerErrors(close());
}
return store;
});
}
var init_sqlite_worker_store = __esmMin((() => {
init_global_singleton();
init_openclaw_state_worker_error();
init_sqlite_worker_broker();
init_sqlite_worker_contract();
init_sqlite_worker_operation_admission();
}));
//#endregion
//#region src/state/openclaw-state-worker-operation.ts
/** A live alias cannot authorize a worker still bound to a vanished opening path. */
function assertOpenClawStateWorkerActorPath(actor) {
if (openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(actor.databasePath)?.key !== actor.key) throw new StateDatabaseReadAdmissionInvalidatedError("Shared-state worker opening path changed");
}
function runWithCapturedWorkerContext(context, operation) {
const maintenance = context.maintenanceScope;
const run = () => maintenance ? maintenance.run(() => maintenance.track(operation())) : operation();
return context.runInCapturedSchemaScope ? context.runInCapturedSchemaScope(run) : run();
}
function runWithOpenClawStateWorkerStore(store, context, operation, assertCurrent, createAdmission) {
const { admission } = context;
const actor = getSqliteWorkerActorIdentity(store);
return runSqliteWorkerStoreOperation(store, operation, context, (commandType) => {
admission.assertCurrent();
assertOpenClawStateWorkerActorPath(actor);
assertCurrent?.(commandType);
}, createAdmission);
}
/** Only native opening owns the caller scope; a cached actor must not retain it. */
function captureOpenClawStateWorkerOpeningGuard(context, assertCurrent) {
const admission = { assertCurrent };
let captured = AsyncLocalStorage.bind(() => {
context.admission.assertCurrent();
try {
assertCurrent?.();
} catch (error) {
admission.refusal = { error };
throw error;
}
});
return {
admission,
assertCurrent: () => {
if (!captured) throw new Error("Shared-state worker opening admission is closed");
captured();
},
releaseContext() {
captured = void 0;
}
};
}
var init_openclaw_state_worker_operation = __esmMin((() => {
init_sqlite_worker_store();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_cache();
}));
//#endregion
//#region src/state/openclaw-state-worker-lease.ts
/** Retain a logical actor resource while tracking only acquisition and individual commands. */
function retainOpenClawStateWorkerLease(context, owner, finalize) {
const maintenance = context.maintenanceScope;
context.admission.assertCurrent();
maintenance?.assertAdmission();
const ready = createDeferredCore();
const admitted = createDeferredCore();
const released = createDeferredCore();
const invocations = /* @__PURE__ */ new Set();
const operations = /* @__PURE__ */ new Set();
let retained;
let releaseOperation;
let retirement;
let closing;
let sealed = false;
let invalidated = false;
let store;
let scope;
let acquisitionReady = false;
ready.promise.catch(() => void 0);
const assertResourceCurrent = () => resource?.assertCurrent();
const assertInvocation = (invocation) => {
if (invocation.phase === "closed" || invalidated) throw new SqliteWorkerError("Shared-state worker operation is closed", "closed");
context.admission.assertCurrent();
assertResourceCurrent();
};
const assertCommandAdmission = (invocation) => {
assertInvocation(invocation);
if (invocation.phase !== "accepting") throw new SqliteWorkerError("Shared-state worker operation is closed", "closed");
};
const assertNewOperation = () => {
if (sealed) throw new SqliteWorkerError("Shared-state worker lease is closed", "closed");
context.admission.assertCurrent();
maintenance?.assertAdmission();
};
const retireNative = () => {
retirement ??= (async () => {
await admitted.promise.catch(() => void 0);
released.resolve();
const errors = [];
try {
await retained;
} catch (error) {
errors.push(error);
}
try {
await releaseOperation?.();
} catch (error) {
errors.push(error);
}
throwSqliteLifecycleErrors(errors, "Shared-state worker lease retirement failed");
})();
retirement.catch(() => void 0);
return retirement;
};
const retire = () => {
sealed = true;
invalidated = true;
for (const invocation of invocations) invocation.phase = "closed";
return retireNative();
};
const createOperationScope = (invocation) => ({ execute: (command, options) => {
try {
assertCommandAdmission(invocation);
} catch (error) {
const rejected = createDeferredCore();
rejected.reject(error);
rejected.promise.catch(() => void 0);
return rejected.promise;
}
const run = async () => {
if (!acquisitionReady) await ready.promise;
assertInvocation(invocation);
if (!scope) throw new SqliteWorkerError("Shared-state worker lease is not ready", "closed");
return scope.execute(command, options);
};
const result = (resource ? resource.run(run) : run()).catch(async (error) => {
if (store && !sealed && !isSqliteWorkerStoreAvailable(store)) try {
await retire();
} catch (cleanupError) {
throw new AggregateError([error, cleanupError], "Shared-state operation and retirement failed", { cause: cleanupError });
}
throw error;
});
invocation.pending.add(result);
const settled = () => invocation.pending.delete(result);
result.then(settled, settled);
return maintenance ? maintenance.track(result) : result;
} });
const runOperation = (operation) => {
try {
assertNewOperation();
} catch (error) {
const rejected = createDeferredCore();
rejected.reject(error);
rejected.promise.catch(() => void 0);
return rejected.promise;
}
const invocation = {
phase: "accepting",
pending: /* @__PURE__ */ new Set()
};
invocations.add(invocation);
const completion = createDeferredCore();
operations.add(completion.promise);
completion.promise.catch(() => void 0);
const run = async () => {
try {
return await operation(createOperationScope(invocation));
} finally {
if (invocation.phase === "accepting") invocation.phase = "draining";
await Promise.allSettled(invocation.pending);
invocation.phase = "closed";
invocations.delete(invocation);
}
};
run().then((value) => {
operations.delete(completion.promise);
completion.resolve(value);
}, (error) => {
operations.delete(completion.promise);
completion.reject(error);
});
return completion.promise;
};
const release = () => {
if (invalidated) return retireNative();
if (closing) return closing;
sealed = true;
closing = (async () => {
const errors = [];
const terminal = {
phase: "accepting",
pending: /* @__PURE__ */ new Set()
};
invocations.add(terminal);
try {
await ready.promise;
await finalize?.(createOperationScope(terminal));
} catch (error) {
errors.push(error);
} finally {
if (terminal.phase === "accepting") terminal.phase = "draining";
await Promise.allSettled(terminal.pending);
terminal.phase = "closed";
invocations.delete(terminal);
}
const results = await Promise.allSettled(operations);
errors.push(...results.flatMap((result) => result.status === "rejected" ? [result.reason] : []));
try {
await retireNative();
} catch (error) {
errors.push(error);
}
throwSqliteLifecycleErrors(errors, "Shared-state worker lease cleanup failed");
})();
closing.catch(() => void 0);
return closing;
};
const lease = {
ready: ready.promise,
execute: (command, options) => runOperation((operationScope) => operationScope.execute(command, options)),
runOperation,
release,
retire
};
maintenance?.own(lease, "shared-resources", release);
const resource = maintenance ? captureOpenClawDatabaseMaintenanceResource(lease, maintenance) : void 0;
const acquire = async () => {
try {
const failure = await getOpenClawStateDatabaseTerminalFailureAsync(context);
if (failure) throw failure;
context.admission.assertCurrent();
store = await owner.open(context);
context.admission.assertCurrent();
if (!store) throw new Error("Canonical shared-state worker did not open its database");
releaseOperation = owner.retainOperation(store);
retained = runWithOpenClawStateWorkerStore(store, context, async (operationScope) => {
scope = operationScope;
admitted.resolve();
await released.promise;
}, assertResourceCurrent);
retained.catch(admitted.reject);
await admitted.promise;
context.admission.assertCurrent();
if (invalidated) throw new SqliteWorkerError("Shared-state worker lease is closed", "closed");
} catch (error) {
const failure = error instanceof Error ? hydrateOpenClawStateWorkerError(error) : error;
admitted.reject(failure);
try {
await retire();
} catch (cleanupError) {
if (cleanupError !== failure) throw new AggregateError([failure, cleanupError], "Shared-state lease acquisition failed", { cause: cleanupError });
}
throw failure;
}
};
runWithCapturedWorkerContext(context, acquire).then(() => {
acquisitionReady = true;
ready.resolve();
}, ready.reject);
return lease;
}
var init_openclaw_state_worker_lease = __esmMin((() => {
init_sqlite_lifecycle_errors();
init_sqlite_worker_store();
init_deferred$1();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_cache();
init_openclaw_state_worker_error();
init_openclaw_state_worker_operation();
}));
//#endregion
//#region src/infra/runtime-worker-generation.ts
/** Capture before queues or detached pool contexts discard the caller's scope. */
function captureRuntimeWorkerSource(url) {
const generation = scope.getStore()?.generation;
const bound = generation?.resolve(url);
return bound && bound.href !== url.href ? {
moduleUrl: bound,
runtimeGeneration: generation
} : { moduleUrl: url };
}
var scope;
var init_runtime_worker_generation = __esmMin((() => {
init_signal_exit_barrier();
init_global_singleton();
scope = resolveGlobalSingleton(Symbol.for("openclaw.runtimeWorkerGeneration"), () => new AsyncLocalStorage());
}));
//#endregion
//#region src/state/openclaw-state-worker-owner.ts
function createSharedStateWorkerOwner() {
const moduleUrl = resolveRuntimeProcessEntrypointUrl("sharedStateStore");
const stores = /* @__PURE__ */ new Set();
const activeEntries = /* @__PURE__ */ new Set();
const retiring = /* @__PURE__ */ new Map();
const retiringActors = /* @__PURE__ */ new Map();
const memoryPressure = channel("openclaw.memory.critical");
let pressureSubscribed = false;
const refreshPressureSubscription = () => {
const hasCustody = stores.size > 0 || retiring.size > 0 || retiringActors.size > 0 || activeEntries.size > 0;
if (hasCustody === pressureSubscribed) return;
pressureSubscribed = hasCustody;
if (hasCustody) memoryPressure.subscribe(retireIdleWorkers);
else memoryPressure.unsubscribe(retireIdleWorkers);
};
const matches = (entry, identity) => identity === void 0 || entry.context.admission.identity.key === identity.key;
const hasActiveActorOperations = (entry) => [...activeEntries].some((active) => entry.actor ? active.actor === entry.actor : active === entry);
const clearIdleRetirement = (entry) => {
if (entry.idleTimer) {
clearTimeout(entry.idleTimer);
entry.idleTimer = void 0;
}
};
const hasPendingCleanup = (entry) => entry.cleanup?.pending ?? (!entry.context.maintenanceScope && hasUnclaimedSharedStateSqliteCleanup(entry.context.admission.databasePath));
const retire = (entry) => {
clearIdleRetirement(entry);
stores.delete(entry);
let attempt = retiring.get(entry);
if (!attempt) {
attempt = {};
retiring.set(entry, attempt);
}
refreshPressureSubscription();
if (attempt.pending) return attempt.pending;
if (entry.actor && retiringActors.has(entry.actor)) return retireActor(entry.actor, entry.context.admission.identity);
const pending = (entry.store ? entry.store.close() : entry.opening.then((store) => store?.close(), () => entry.cleanup ? entry.cleanup.close() : entry.context.maintenanceScope ? void 0 : closeUnclaimedSharedStateSqliteWorkers(entry.context.admission.databasePath))).catch(async (error) => {
if (!attempt.actorSettlement) throw error;
await attempt.actorSettlement;
});
attempt.pending = pending;
const settled = () => {
attempt.pending = void 0;
if (!hasPendingCleanup(entry)) retiring.delete(entry);
refreshPressureSubscription();
};
pending.then(settled, settled);
return pending;
};
const scheduleIdleRetirement = (entry) => {
if (entry.activeOperations !== 0 || entry.idleTimer || entry.context.maintenanceScope || !entry.store || !stores.has(entry)) return;
const store = entry.store;
const generation = entry.operationGeneration;
const deadline = performance$1.now() + SQLITE_IDLE_HANDLE_TTL_MS;
const arm = (delay, inspect) => {
const isCurrentIdle = () => entry.idleTimer === timer && entry.operationGeneration === generation && entry.activeOperations === 0 && stores.has(entry);
const settle = async () => {
if (!isCurrentIdle()) return;
let healthy = false;
if (inspect) try {
healthy = await runWithCapturedWorkerContext(entry.context, () => runSqliteWorkerStoreOperation(store, (scope) => scope.execute({
type: "database.inspectIdle",
input: void 0
}), entry.context, () => {
entry.context.admission.assertCurrent();
if (!isCurrentIdle()) throw new Error("Shared-state worker resumed before idle inspection");
})) === "healthy" && isSqliteWorkerStoreAvailable(store);
entry.context.admission.assertCurrent();
} catch {
healthy = false;
}
if (!isCurrentIdle()) return;
entry.idleTimer = void 0;
const remaining = deadline - performance$1.now();
if (healthy && remaining > 0) arm(remaining, false);
else await retire(entry);
};
const timer = runInDetachedAsyncContext(() => setTimeout(() => {
settle().catch((error) => {
log$1.warn("Idle shared-state worker retirement failed", {
path: entry.context.admission.databasePath,
error
});
});
}, delay));
entry.idleTimer = timer;
timer.unref?.();
};
arm(SHARED_STATE_WORKER_IDLE_INSPECT_MS, true);
};
const retainOperation = (store) => {
const entry = [...stores].find((candidate) => candidate.store === store);
if (!entry) throw new Error("Shared-state worker operation lost its actor owner");
clearIdleRetirement(entry);
entry.operationGeneration += 1;
entry.activeOperations += 1;
activeEntries.add(entry);
let released = false;
return () => {
if (released) return;
released = true;
entry.activeOperations -= 1;
if (entry.activeOperations === 0) activeEntries.delete(entry);
refreshPressureSubscription();
if (stores.has(entry) && !isSqliteWorkerStoreAvailable(store) && !hasActiveActorOperations(entry)) {
const pending = entry.actor ? retireActor(entry.actor, entry.context.admission.identity) : retire(entry);
pending.catch((error) => {
log$1.warn("Shared-state worker retirement failed", {
path: entry.context.admission.databasePath,
error
});
});
return pending;
}
scheduleIdleRetirement(entry);
};
};
const retainActorSettlement = (attempt, pending) => {
for (const entry of attempt.entries) {
const closing = retiring.get(entry);
if (closing) closing.actorSettlement = pending;
}
return pending;
};
const retireActor = (actor, identity) => {
let attempt = retiringActors.get(actor);
if (!attempt) {
attempt = {
identity,
entries: /* @__PURE__ */ new Set()
};
retiringActors.set(actor, attempt);
}
for (const entry of [...stores, ...retiring.keys()]) if (entry.actor === actor) {
attempt.entries.add(entry);
clearIdleRetirement(entry);
stores.delete(entry);
}
refreshPressureSubscription();
if (attempt.pending) return retainActorSettlement(attempt, attempt.pending);
const current = attempt;
const complete = () => {
for (const entry of current.entries) {
clearIdleRetirement(entry);
stores.delete(entry);
retiring.delete(entry);
}
retiringActors.delete(actor);
refreshPressureSubscription();
};
const pending = retireSqliteWorkerActor(actor).then(complete, (error) => {
current.pending = void 0;
if (current.entries.size > 0 && [...current.entries].every((entry) => entry.cleanup?.pending === false)) {
complete();
return;
}
throw error;
});
current.pending = pending;
return retainActorSettlement(current, pending);
};
const joinActorRetirement = async (attempt) => {
if (!attempt.pending) throw new Error("Shared-state actor cleanup is pending; close the database before reopening");
await attempt.pending;
};
const inspectInvalidEntry = (entry) => {
const actor = entry.actor;
let kind = "actor";
try {
if (entry.bound && actor) {
assertOpenClawStateWorkerActorPath(actor);
if (entry.store && isSqliteWorkerStoreAvailable(entry.store)) kind = "client";
}
entry.databaseAdmission.assertCurrent();
} catch (error) {
if (!isStateDatabaseReadAdmissionInvalidatedError(error)) throw error;
if (kind === "client" && openClawStateDatabaseCache.getKnownOpenClawStateDatabaseIdentity(entry.context.admission.databasePath)?.key === actor?.key) kind = "actor";
return {
kind,
error
};
}
};
const retireInvalidEntry = (entry) => {
const invalid = inspectInvalidEntry(entry);
if (!invalid) return;
if (invalid.kind === "actor") {
if (hasActiveActorOperations(entry)) throw invalid.error;
return { pending: entry.opening.then(() => {
if (hasActiveActorOperations(entry)) throw invalid.error;
return entry.actor ? retireActor(entry.actor, entry.context.admission.identity) : retire(entry);
}, () => retire(entry)) };
}
if (!stores.has(entry)) return;
const closing = retire(entry);
return { pending: entry.activeOperations === 0 ? closing : void 0 };
};
async function close(identity) {
for (const entry of stores.values()) if (matches(entry, identity)) retire(entry);
const errors = (await Promise.allSettled([...[...retiring.keys()].filter((entry) => matches(entry, identity)).map(retire), ...[...retiringActors].filter(([, attempt]) => !identity || attempt.identity.key === identity.key).map(([actor, attempt]) => retireActor(actor, attempt.identity))])).flatMap((result) => result.status === "rejected" ? [result.reason] : []);
refreshPressureSubscription();
if (errors.length) throw new AggregateError(errors, "Failed to close shared-state SQLite workers");
}
registerOpenClawStateDatabaseAsyncResource({ close });
registerOpenClawStateDatabaseLifecycleListener((event) => {
if (event.kind !== "opened") {
if (!event.identity) return;
close(event.identity).catch((error) => {
log$1.warn("Shared-state worker retirement failed", {
path: event.path,
error
});
});
}
});
function retireIdleWorkers() {
for (const entry of stores) if (entry.idleTimer && entry.store && !entry.context.maintenanceScope && !hasActiveActorOperations(entry)) runInDetachedAsyncContext(() => retire(entry)).catch((error) => {
log$1.warn("Idle shared-state worker retirement failed", {
path: entry.context.admission.databasePath,
error
});
});
}
return {
close,
retainOperation,
openCleanup(databasePath, context, assertOwned) {
return openSharedStateSqliteWorkerStore({
...captureRuntimeWorkerSource(moduleUrl),
databasePath,
existingOnly: true
}, context, assertOwned);
},
async open(context, options = {}) {
const { existingOnly = false, assertCurrent, preparation } = options;
const { admission } = context;
const source = captureRuntimeWorkerSource(moduleUrl);
const assertAdmission = () => {
admission.assertCurrent();
assertCurrent?.();
};
assertAdmission();
isExistingOpenClawStateSchema(admission.databasePath);
if (getExistingOpenClawStateSchemaPath() !== context.existingSchemaPath) throw new Error("Shared-state worker schema context does not match its caller");
let entry;
for (;;) {
for (const candidate of /* @__PURE__ */ new Set([...stores, ...retiring.keys()])) {
if (!matches(candidate, admission.identity)) continue;
const retirement = retireInvalidEntry(candidate);
if (retirement) {
if (retirement.pending) await retirement.pending;
return this.open(context, options);
}
if (stores.has(candidate) && (candidate.context.existingSchemaPath !== context.existingSchemaPath || candidate.source.moduleUrl.href !== source.moduleUrl.href)) {
await retire(candidate);
assertAdmission();
}
}
for (const attempt of retiringActors.values()) if (attempt.identity.key === admission.identity.key) {
await joinActorRetirement(attempt);
assertAdmission();
}
for (const [retiringEntry, attempt] of retiring) if (matches(retiringEntry, admission.identity) && retiringEntry.context.maintenanceScope === context.maintenanceScope) {
if (inspectInvalidEntry(retiringEntry)?.kind === "client") continue;
if (!attempt.pending) {
if (!hasPendingCleanup(retiringEntry)) {
retiring.delete(retiringEntry);
refreshPressureSubscription();
continue;
}
throw new Error("Shared-state SQLite cleanup is pending; close the database before reopening");
}
try {
await attempt.pending;
} catch (error) {
if (retiring.get(retiringEntry) === attempt) throw error;
}
assertAdmission();
}
assertAdmission();
entry = [...stores].find((candidate) => matches(candidate, admission.identity) && candidate.context.maintenanceScope === context.maintenanceScope && candidate.context.existingSchemaPath === context.existingSchemaPath);
if (!entry || entry.store || entry.openingAdmission.assertCurrent === assertCurrent) break;
let rejected;
try {
await entry.opening;
} catch (error) {
rejected = { error };
}
assertAdmission();
if (rejected && (!entry.openingAdmission.refusal || !Object.is(rejected.error, entry.openingAdmission.refusal.error))) throw rejected.error;
}
if (!entry) {
assertAdmission();
const databaseAdmission = captureOpenClawStateDatabaseReadAdmission(admission.databasePath);
assertAdmission();
const openingGuard = captureOpenClawStateWorkerOpeningGuard(context, assertCurrent);
const open = async () => {
try {
return await openSharedStateSqliteWorkerStore({
...source,
databasePath: admission.databasePath,
existingOnly
}, context, openingGuard.assertCurrent, {
maintenanceScope: context.maintenanceScope,
preparation,
retainCleanup: (cleanup) => {
admitted.cleanup = cleanup;
}
});
} finally {
openingGuard.releaseContext();
}
};
const admitted = {
source,
context,
databaseAdmission,
openingAdmission: openingGuard.admission,
existingOnly,
activeOperations: 0,
operationGeneration: 0,
opening: context.maintenanceScope ? open() : runInDetachedAsyncContext(open)
};
entry = admitted;
admitted.opening = admitted.opening.then((store) => {
if (store) {
admitted.store = store;
admitted.actor = getSqliteWorkerActorIdentity(store);
} else {
stores.delete(admitted);
refreshPressureSubscription();
}
return store;
});
stores.add(entry);
refreshPressureSubscription();
context.maintenanceScope?.own(entry, "shared-resources", () => retire(admitted));
entry.opening.catch(() => {
stores.delete(admitted);
if (hasPendingCleanup(admitted) && !retiring.has(admitted)) retiring.set(admitted, {});
refreshPressureSubscription();
});
}
const store = await entry.opening;
try {
admission.assertCurrent();
} catch (error) {
try {
await retire(entry);
} catch (cleanupError) {
throw new AggregateError([error, cleanupError], "Shared-state worker admission and cleanup failed", { cause: cleanupError });
}
throw error;
}
assertCurrent?.();
if (!store) return !existingOnly && entry.existingOnly ? this.open(context, {
...options,
existingOnly: false
}) : void 0;
if (!stores.has(entry)) return this.open(context, options);
clearIdleRetirement(entry);
const actorRetirement = entry.actor ? retiringActors.get(entry.actor) : void 0;
if (entry.actor && actorRetirement) {
actorRetirement.entries.add(entry);
stores.delete(entry);
refreshPressureSubscription();
await joinActorRetirement(actorRetirement);
return this.open(context, options);
}
if (!isSqliteWorkerStoreAvailable(store) && !hasActiveActorOperations(entry)) {
await (entry.actor ? retireActor(entry.actor, admission.identity) : retire(entry));
return this.open(context, options);
}
try {
if (!entry.bound) {
publishOpenClawStateDatabaseWorkerAdmission(entry.context.admission);
entry.bound = true;
}
} catch (error) {
try {
await retire(entry);
} catch (cleanupError) {
throw new AggregateError([error, cleanupError], "Shared-state worker binding and cleanup failed", { cause: cleanupError });
}
throw error;
}
const retirement = retireInvalidEntry(entry);
if (retirement) {
if (retirement.pending) await retirement.pending;
return this.open(context, options);
}
stores.delete(entry);
stores.add(entry);
return store;
}
};
}
function getOpenClawStateWorkerOwner() {
return resolveGlobalSingleton(Symbol.for("openclaw.sharedStateWorkerOwner"), createSharedStateWorkerOwner, (sharedOwner) => sharedOwner.close());
}
var log$1, SHARED_STATE_WORKER_IDLE_INSPECT_MS;
var init_openclaw_state_worker_owner = __esmMin((() => {
init_runtime_process_url();
init_runtime_worker_generation();
init_sqlite_handle_lifecycle();
init_sqlite_worker_store();
init_subsystem();
init_async_work_scope();
init_global_singleton();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_cache();
init_openclaw_state_db_schema_policy();
init_openclaw_state_worker_operation();
log$1 = createSubsystemLogger("state/worker");
SHARED_STATE_WORKER_IDLE_INSPECT_MS = 6e4;
}));
//#endregion
//#region src/state/openclaw-state-worker-store.ts
var openclaw_state_worker_store_exports = /* @__PURE__ */ __exportAll({
createOpenClawStateWorkerLease: () => createOpenClawStateWorkerLease,
executeOpenClawStateWorker: () => executeOpenClawStateWorker,
inspectOpenClawStateDatabase: () => inspectOpenClawStateDatabase,
openOpenClawStateWorkerCleanupStore: () => openOpenClawStateWorkerCleanupStore,
runOpenClawStateWorkerOperation: () => runOpenClawStateWorkerOperation
});
/** Retired cleanup uses the retained owner's backend without renewing read admission. */
function openOpenClawStateWorkerCleanupStore(databasePath, context, assertOwned) {
return getOpenClawStateWorkerOwner().openCleanup(databasePath, context, assertOwned);
}
async function executeOpenClawStateWorker(context, command) {
const result = await runOpenClawStateWorkerOperation(context, (scope) => scope.execute(command));
context.admission.assertCurrent();
return result;
}
/** Retain the canonical actor for capture callbacks and their terminal writes. */
function createOpenClawStateWorkerLease(context, finalize) {
return retainOpenClawStateWorkerLease(context, {
open: (captured) => getOpenClawStateWorkerOwner().open(captured),
retainOperation: (store) => getOpenClawStateWorkerOwner().retainOperation(store)
}, finalize);
}
async function runOpenClawStateWorkerOperation(context, operation, options) {
return runWithCapturedWorkerContext(context, () => runAdmittedOpenClawStateWorkerOperation(context, operation, options));
}
async function runAdmittedOpenClawStateWorkerOperation(context, operation, options) {
try {
context.admission.assertCurrent();
options?.assertCurrent?.();
const failure = await getOpenClawStateDatabaseTerminalFailureAsync(context);
if (failure) throw failure;
context.admission.assertCurrent();
options?.assertCurrent?.();
const store = await getOpenClawStateWorkerOwner().open(context, options);
context.admission.assertCurrent();
if (!store) {
if (options?.existingOnly) return;
throw new Error("Canonical shared-state worker did not open its database");
}
const releaseOperation = getOpenClawStateWorkerOwner().retainOperation(store);
try {
context.admission.assertCurrent();
options?.assertCurrent?.();
return await runWithOpenClawStateWorkerStore(store, context, operation, options?.assertCurrent, options?.createAdmission);
} finally {
releaseOperation();
}
} catch (error) {
const hydrated = hydrateOpenClawStateWorkerError(error);
const failure = findOpenClawStateDatabaseFailure(hydrated, context.admission.databasePath);
if (failure && !openClawStateDatabaseCache.getOpenClawStateDatabaseRecordedFailure(context.admission.databasePath)) {
try {
context.admission.assertCurrent();
} catch {
throw hydrated;
}
recordOpenClawStateDatabaseOpenFailure(context.admission.databasePath, failure);
}
throw hydrated;
}
}
/** Inspect the existing file without recursively admitting a domain operation. */
async function inspectOpenClawStateDatabase(context, command) {
return runWithCapturedWorkerContext(context, () => inspectAdmittedOpenClawStateDatabase(context, command));
}
async function inspectAdmittedOpenClawStateDatabase(context, command) {
try {
const store = await getOpenClawStateWorkerOwner().open(context, { existingOnly: true });
context.admission.assertCurrent();
if (!store) return;
const releaseOperation = getOpenClawStateWorkerOwner().retainOperation(store);
try {
context.admission.assertCurrent();
return await runWithOpenClawStateWorkerStore(store, context, (scope) => scope.execute(command));
} finally {
releaseOperation();
}
} catch (error) {
throw hydrateOpenClawStateWorkerError(error);
}
}
var init_openclaw_state_worker_store = __esmMin((() => {
init_openclaw_state_db_cache();
init_openclaw_state_db_failure();
init_openclaw_state_worker_error();
init_openclaw_state_worker_lease();
init_openclaw_state_worker_operation();
init_openclaw_state_worker_owner();
}));
//#endregion
//#region src/state/openclaw-state-db-cache.wal.ts
/** Bind periodic maintenance and its observations to the cache's exact native owner. */
function createStateDatabaseWalOwner({ cachedDatabases, asyncResources }, retainForIdle) {
return {
register(database, identity, admission, env) {
if (!isMainThread) return;
const capturedContext = captureOpenClawStateWorkerContextWithAdmission({
path: database.path,
env
}, () => admission);
const controller = new AbortController();
let pending;
const cancel = () => {
controller.abort();
if (!pending) {
unregister();
return;
}
return pending.then(() => void 0, () => void 0);
};
const unregister = asyncResources.register({ async close(selected) {
if (selected && selected.key !== identity.key) return;
cancel();
await pending?.catch(() => {});
unregister();
} });
const run = async (request) => {
const maintenanceScope = getOpenClawDatabaseMaintenanceResourceScope(database.db);
const context = {
...capturedContext,
maintenanceScope
};
const assertCurrent = () => {
controller.signal.throwIfAborted();
context.admission.assertCurrent();
maintenanceScope?.assertAdmission();
if (getOpenClawDatabaseMaintenanceResourceScope(database.db) !== maintenanceScope || cachedDatabases.get(database.path) !== database || !database.db.isOpen) throw new StateDatabaseReadAdmissionInvalidatedError("Shared-state WAL maintenance owner changed");
assertExistingDatabaseIdentity(database.path, identity.key, identity.birthtime);
};
let releaseIdle;
let operationStarted = false;
try {
assertCurrent();
releaseIdle = retainForIdle(database);
const { runOpenClawStateWorkerOperation } = await Promise.resolve().then(() => (init_openclaw_state_worker_store(), openclaw_state_worker_store_exports));
assertCurrent();
const result = await runOpenClawStateWorkerOperation(context, (worker) => worker.execute({
type: "database.walMaintenance",
input: request
}, { signal: controller.signal }), {
existingOnly: true,
assertCurrent,
createAdmission: () => ({
nativeLocations: [database.path, identity.canonicalPath],
admission: createSqliteWorkerOperationAdmission((_request, grant) => {
assertCurrent();
if (!grant()) throw new StateDatabaseReadAdmissionInvalidatedError("Shared-state WAL maintenance authority expired");
operationStarted = true;
})
})
});
assertCurrent();
return result;
} catch (error) {
if (!operationStarted && (isStateDatabaseReadAdmissionInvalidatedError(error) || controller.signal.aborted && isAbortError(error))) return;
throw error;
} finally {
releaseIdle?.();
}
};
registerSqliteWalWorkerMaintenance(database.db, (operation) => {
if (controller.signal.aborted) return Promise.resolve(void 0);
const active = run(operation);
pending = active;
return active.finally(() => {
if (pending === active) pending = void 0;
if (controller.signal.aborted) unregister();
});
}, cancel);
},
/** Report the last observation without opening or querying SQLite. */
readHealth() {
const database = cachedDatabases.get(path.resolve(resolveOpenClawStateSqlitePath()));
return database?.db.isOpen ? database.walMaintenance.health : void 0;
}
};
}
var init_openclaw_state_db_cache_wal = __esmMin((() => {
init_abort_signal();
init_sqlite_wal_write_admission();
init_sqlite_worker_identity();
init_sqlite_worker_operation_admission();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_paths();
init_openclaw_state_worker_context_capture();
}));
//#endregion
//#region src/state/openclaw-state-db-handle.ts
function openTrackedStateDatabase(pathname, options) {
const result = openTrackedStateDatabaseResult(pathname, options);
if (result.status === "unavailable") throw result.error;
return result.database;
}
/** Native open failure is an ordinary read failure; admitted handles retain their own cleanup. */
function openTrackedStateDatabaseResult(pathname, options) {
assertStateDatabaseAccessAllowed(pathname);
try {
if (options?.expectedIdentity !== void 0) assertExistingDatabaseIdentity(pathname, options.expectedIdentity);
const location = options?.existingOnly || options?.expectedIdentity !== void 0 ? resolveExistingSqliteFileUri(pathname) : pathname;
const nativeOptions = options?.readOnly ? {
readOnly: true,
timeout: options.timeout
} : { enableForeignKeyConstraints: options?.enableForeignKeyConstraints };
const database = withSqliteNativeOpen(() => openNodeSqliteDatabase(location, nativeOptions));
try {
assertStateDatabaseAccessAllowed(pathname);
} catch (error) {
database.close();
throw error;
}
return {
status: "available",
database
};
} catch (error) {
return {
status: "unavailable",
error
};
}
}
function closeTrackedStateDatabase(database) {
if (database.isOpen) database.close();
}
var init_openclaw_state_db_handle = __esmMin((() => {
init_gateway_state_owner();
init_node_sqlite();
init_sqlite_error_diagnostics();
init_sqlite_worker_identity();
}));
//#endregion
//#region src/state/openclaw-state-db-schema-version.ts
/** Content and its marker commit together, even while older readers retain their version floor. */
function readStateSchemaContentVersion(db) {
const schema = getAdmittedSqliteSchemaFacts(db);
const cached = schema && contentVersions.get(schema);
if (cached !== void 0) return cached;
const version = readContentVersion(db, schema?.userVersion ?? readSqliteUserVersion(db));
if (schema) contentVersions.set(schema, version);
return version;
}
function readContentVersion(db, published) {
if (!tableExists(db, "config_machine_state")) return published;
let query = contentVersionQueries.get(db);
if (!query) {
query = prepareSqliteQuerySync(db, () => getNodeSqliteKysely(db).selectFrom("config_machine_state").select("value_json").where("state_key", "=", CONTENT_VERSION_KEY));
contentVersionQueries.set(db, query);
}
const row = query().rows[0];
if (!row) return published;
let contentVersion;
try {
contentVersion = JSON.parse(row.value_json);
} catch (cause) {
throw new SqliteSchemaMismatchError(`Invalid shared state schema content version in ${CONTENT_VERSION_KEY}.`, { cause });
}
if (typeof contentVersion !== "number" || !Number.isSafeInteger(contentVersion) || contentVersion < 0) throw new SqliteSchemaMismatchError(`Invalid shared state schema content version in ${CONTENT_VERSION_KEY}.`);
return Math.max(published, contentVersion);
}
/** Cold migration planning checks physical content; admission still uses the recorded version. */
function readStateSchemaMigrationVersion(db) {
const version = readStateSchemaContentVersion(db);
if (version !== 16) return version;
const reviewWorkspace = tableHasColumn(db, "skill_workshop_collection_reviews", "workspace_dir");
const proposalWorkspace = tableHasColumn(db, "skill_workshop_proposals", "workspace_dir");
const releasedClaim = tableHasColumn(db, "skill_workshop_proposals", "claim_released_time");
if (!reviewWorkspace && !proposalWorkspace && !releasedClaim) return version;
const missingAttribution = reviewWorkspace && !proposalWorkspace;
const issues = collectSqliteSchemaIssues(db, `
CREATE TABLE skill_workshop_collection_reviews (
review_id TEXT NOT NULL PRIMARY KEY,
${reviewWorkspace ? "workspace_dir" : "owner_agent_id"} TEXT NOT NULL,
backup_id TEXT NOT NULL,
create_time INTEGER NOT NULL,
kept_names_json TEXT NOT NULL,
written_names_json TEXT NOT NULL,
dropped_json TEXT NOT NULL
) STRICT;
CREATE TABLE skill_workshop_proposals (
proposal_id TEXT NOT NULL PRIMARY KEY,
record_json TEXT NOT NULL,
owner_agent_id TEXT,
${proposalWorkspace ? "workspace_dir TEXT NOT NULL," : ""}
kind TEXT NOT NULL CHECK (kind IN ('create', 'update')),
status TEXT NOT NULL CHECK (status IN ('pending', 'applied', 'rejected', 'quarantined', 'stale')),
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
draft_hash TEXT NOT NULL,
origin_agent_id TEXT,
origin_session_key TEXT,
origin_run_id TEXT,
origin_message_id TEXT,
applied_at TEXT,
rejected_at TEXT,
quarantined_at TEXT,
stale_at TEXT,
status_reason TEXT
${releasedClaim ? ", claim_released_time INTEGER" : ""}
) STRICT;
`, {
allowedMissingTables: ["skill_workshop_collection_reviews"],
allowedColumnDefinitions: {
"skill_workshop_collection_reviews.workspace_dir": ["workspace_dir TEXT NOT NULL DEFAULT ''"],
"skill_workshop_proposals.workspace_dir": ["workspace_dir TEXT NOT NULL DEFAULT ''"]
}
});
if (!missingAttribution && issues.length === 0) return 15;
throw new SqliteSchemaMismatchError("Unrecognized Skill Workshop ownership schema; cannot apply the schema 16 migration.");
}
function assertSupportedStateSchemaVersion(db, pathname) {
try {
const userVersion = getAdmittedSqliteSchemaFacts(db)?.userVersion ?? readSqliteUserVersion(db);
const contentVersion = userVersion > 19 ? userVersion : readStateSchemaContentVersion(db);
if (contentVersion > 19) throw createNewerSqliteSchemaVersionError("OpenClaw state database", pathname, contentVersion, 19);
return userVersion;
} catch (error) {
throw normalizeOpenClawStateSchemaReadError(error, pathname);
}
}
var CONTENT_VERSION_KEY, contentVersions, contentVersionQueries;
var init_openclaw_state_db_schema_version = __esmMin((() => {
init_kysely_sync();
init_sqlite_schema_contract();
init_sqlite_schema_facts();
init_sqlite_schema_issues();
init_sqlite_user_version();
init_openclaw_state_db_contract();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_migration_required();
CONTENT_VERSION_KEY = "state.schema.contentVersion";
contentVersions = /* @__PURE__ */ new WeakMap();
contentVersionQueries = /* @__PURE__ */ new WeakMap();
}));
//#endregion
//#region src/state/openclaw-state-db-runtime-failure.ts
/** Runtime validation uses the cache's existing handles, version counters, and terminal latch. */
function createOpenClawStateDatabaseRuntimeFailureOwner(owner) {
return {
closeTerminalFailure(pathname, error) {
markOpenClawStateDatabaseFailure(error, pathname);
owner.invalidate(pathname);
const cached = owner.cachedDatabases.get(pathname);
const errors = [];
try {
if (cached) owner.evict(cached);
} catch (cleanupError) {
errors.push(cleanupError);
}
try {
owner.notifyTerminalFailure(pathname, error);
} catch (notificationError) {
errors.push(notificationError);
}
throwSqliteLifecycleErrors(errors, "Terminal shared-state failure cleanup failed");
},
get: (pathname) => {
const resolvedPath = path.resolve(pathname);
const latched = owner.latch.get(resolvedPath);
if (latched) return latched;
const cached = owner.cachedDatabases.get(resolvedPath);
if (!cached?.db.isOpen) return;
try {
assertSupportedStateSchemaVersion(cached.db, resolvedPath);
return;
} catch (error) {
const failure = error instanceof Error ? error : new Error(String(error));
if (isSqliteCorruptionError(failure)) {
owner.evict(cached);
return;
}
if (isSqliteSchemaVersionError(failure)) owner.recordSchemaFailure(resolvedPath, failure);
return failure;
}
}
};
}
var init_openclaw_state_db_runtime_failure = __esmMin((() => {
init_sqlite_error_diagnostics();
init_sqlite_lifecycle_errors();
init_sqlite_user_version();
init_openclaw_state_db_failure();
init_openclaw_state_db_schema_version();
}));
//#endregion
//#region src/infra/sqlite-backup.ts
var init_sqlite_backup = __esmMin((() => {
init_node_sqlite();
}));
//#endregion
//#region src/infra/windows-private-directory.ts
function loadPrivatePathCreators() {
const koffi = require("koffi");
const kernel32 = koffi.load("kernel32.dll");
const advapi32 = koffi.load("advapi32.dll");
const attributes = koffi.struct({
length: "uint32_t",
descriptor: "void *",
inheritHandle: "int32_t"
});
const getLastError = kernel32.func("uint32_t __stdcall GetLastError()");
const getCurrentProcess = kernel32.func("void * __stdcall GetCurrentProcess()");
const closeHandle = kernel32.func("int32_t __stdcall CloseHandle(void *handle)");
const localFree = kernel32.func("void * __stdcall LocalFree(void *memory)");
const openToken = advapi32.func("int32_t __stdcall OpenProcessToken(void *process, uint32_t access, _Out_ void **token)");
const getTokenInformation = advapi32.func("int32_t __stdcall GetTokenInformation(void *token, int32_t informationClass, _Out_ void *information, uint32_t length, _Out_ uint32_t *required)");
const convertSid = advapi32.func("int32_t __stdcall ConvertSidToStringSidW(void *sid, _Out_ void **text)");
const convertDescriptor = advapi32.func("int32_t __stdcall ConvertStringSecurityDescriptorToSecurityDescriptorW(str16 text, uint32_t revision, _Out_ void **descriptor, void *size)");
const createDirectory = kernel32.func("__stdcall", "CreateDirectoryW", "int32_t", ["str16", koffi.pointer(attributes)]);
const createFile = kernel32.func("__stdcall", "CreateFileW", "void *", [
"str16",
"uint32_t",
"uint32_t",
koffi.pointer(attributes),
"uint32_t",
"uint32_t",
"void *"
]);
const failure = (operation) => {
const errorCode = getLastError();
return Object.assign(/* @__PURE__ */ new Error(`${operation} failed (Win32 error ${errorCode})`), {
code: errorCode === 80 || errorCode === 183 ? "EEXIST" : "EIO",
errno: errorCode
});
};
const withPrivateAttributes = (inherit, operation) => {
const token = [null];
const sidText = [null];
const descriptor = [null];
if (!openToken(getCurrentProcess(), 8, token)) throw failure("OpenProcessToken");
try {
const required = [0];
getTokenInformation(token[0], 1, null, 0, required);
if (getLastError() !== 122 || required[0] === 0) throw failure("GetTokenInformation(size)");
const user = Buffer.alloc(required[0]);
if (!getTokenInformation(token[0], 1, user, user.length, required)) throw failure("GetTokenInformation");
if (!convertSid(koffi.decode(user, "void *"), sidText)) throw failure("ConvertSidToStringSidW");
const sid = koffi.decode(sidText[0], "char16_t", -1);
const flags = inherit ? "OICI" : "";
const sddl = `O:${sid}D:P(A;${flags};FA;;;${sid})(A;${flags};FA;;;SY)(A;${flags};FA;;;BA)`;
if (!convertDescriptor(sddl, 1, descriptor, null)) throw failure("ConvertStringSecurityDescriptorToSecurityDescriptorW");
return operation({
length: koffi.sizeof(attributes),
descriptor: descriptor[0],
inheritHandle: 0
});
} finally {
if (descriptor[0] !== null) localFree(descriptor[0]);
if (sidText[0] !== null) localFree(sidText[0]);
closeHandle(token[0]);
}
};
return {
directory: (directoryPath) => withPrivateAttributes(true, (security) => {
if (!createDirectory(path.toNamespacedPath(path.resolve(directoryPath)), security)) throw failure(`CreateDirectoryW(${directoryPath})`);
}),
file: (filePath) => withPrivateAttributes(false, (security) => {
const resolved = path.toNamespacedPath(path.resolve(filePath));
const handle = createFile(resolved, 3221225472, 3, security, 1, 128, null);
if (handle === null || BigInt.asIntN(64, koffi.address(handle)) === -1n) throw failure(`CreateFileW(${filePath})`);
try {
return fs.openSync(resolved, fs.constants.O_RDWR | (fs.constants.O_NOFOLLOW ?? 0));
} finally {
closeHandle(handle);
}
})
};
}
function createPrivateWindowsDirectory(directoryPath) {
creators ??= loadPrivatePathCreators();
creators.directory(directoryPath);
}
var require, creators;
var init_windows_private_directory = __esmMin((() => {
require = createRequire(import.meta.url);
}));
//#endregion
//#region src/infra/sqlite-private-directory.ts
function resolvePrivateSqliteSnapshotStagingRoot(env = process.env) {
const appData = process.platform === "win32" ? env.LOCALAPPDATA?.trim() : void 0;
const defaultRoot = process.platform === "win32" ? "AppData/Local" : ".cache";
const platformRoot = process.platform === "darwin" ? "Library/Caches" : defaultRoot;
const cacheRoot = [env.XDG_CACHE_HOME?.trim(), appData].find((root) => root && path.isAbsolute(root)) ?? path.join(resolveRequiredOsHomeDir(env), platformRoot);
return resolvePreferredOpenClawTmpDir({
preferredDir: path.join(cacheRoot, "openclaw"),
tmpdir: () => cacheRoot
});
}
function createPrivateSqliteTempDirectorySync(rootPath, prefix) {
if (process.platform !== "win32") return fs.mkdtempSync(path.join(rootPath, prefix));
const directoryPath = path.join(rootPath, `${prefix}${randomUUID()}`);
createPrivateWindowsDirectory(directoryPath);
return directoryPath;
}
var init_sqlite_private_directory = __esmMin((() => {
init_home_dir();
init_tmp_openclaw_dir();
init_windows_private_directory();
}));
//#endregion
//#region src/infra/sqlite-staging-token.ts
/** Native transactions fence private staging admission and committed retirement. */
function acquireSqliteStagingToken(directory, mode, options = {}) {
const location = path.join(directory, SQLITE_STAGING_TOKEN_FILES[0]);
const readIdentity = (pathname, kind) => {
const stat = fs.lstatSync(pathname, { bigint: true });
if (!(kind === "directory" ? stat.isDirectory() : stat.isFile()) || process.platform === "win32" && (stat.dev === 0n || stat.ino === 0n)) throw new Error("SQLite staging ownership is unknown");
return stat;
};
const directoryIdentity = readIdentity(directory, "directory");
const family = SQLITE_STAGING_TOKEN_FILES.map((file) => fs.lstatSync(path.join(directory, file), { throwIfNoEntry: false }));
const existing = family[0];
if (family.some((file) => file && (!file.isFile() || process.getuid && file.uid !== process.getuid())) || !existing && mode !== "create" && !options.allowMissing) throw new Error("SQLite snapshot token ownership is unknown");
const existingIdentity = existing ? readIdentity(location, "file") : void 0;
const db = withSqliteNativeOpen(() => openNodeSqliteDatabase(existing ? resolveExistingSqliteFileUri(location) : location));
let tokenIdentity;
const kysely = getNodeSqliteKysely(db);
const execute = (statement) => executeSqliteQueryTakeFirstSync(db, { compile: () => statement.compile(kysely) });
let exclusive = mode === "reclaim";
let retired = false;
const assertIdentity = () => {
const currentDirectory = readIdentity(directory, "directory");
if (directoryIdentity.dev !== currentDirectory.dev || directoryIdentity.ino !== currentDirectory.ino) throw new Error("SQLite staging ownership changed before retirement");
const currentToken = readIdentity(location, "file");
if (tokenIdentity.dev !== currentToken.dev || tokenIdentity.ino !== currentToken.ino) throw new Error("SQLite staging ownership changed before retirement");
};
const readVersion = () => {
const row = execute(sql`PRAGMA user_version`);
return isRecord(row) ? row.user_version : void 0;
};
const beginRetirement = () => {
assertIdentity();
if (!db.isOpen) return acquireSqliteStagingToken(directory, "reclaim");
if (!db.isTransaction || !exclusive) {
if (db.isTransaction) execute(sql`ROLLBACK`);
execute(sql`BEGIN EXCLUSIVE`);
exclusive = true;
}
assertIdentity();
const version = readVersion();
if (version !== (retired ? 1 : 0)) {
retired = version === 1;
throw new SqliteStagingRetiredError();
}
return token;
};
const release = (retiring = false) => {
if (!db.isOpen) return;
if (retiring) {
beginRetirement();
if (!retired) execute(sql`PRAGMA user_version=1`);
execute(sql`COMMIT`);
retired = true;
} else if (db.isTransaction) execute(sql`ROLLBACK`);
db.close();
};
const token = Object.assign(release, { beginRetirement });
try {
tokenIdentity = existingIdentity ?? readIdentity(location, "file");
execute(sql`PRAGMA busy_timeout=0`);
if (mode === "create") execute(sql`BEGIN IMMEDIATE`);
else if (mode === "reclaim") execute(sql`BEGIN EXCLUSIVE`);
else {
execute(sql`BEGIN`);
execute(sql`SELECT rootpage FROM sqlite_schema LIMIT 1`);
}
const journalMode = execute(sql`PRAGMA journal_mode`);
if (!isRecord(journalMode) || journalMode.journal_mode !== "delete") throw new Error("SQLite snapshot token journal mode is unknown");
const version = readVersion();
if (version !== 0 && (mode !== "reclaim" || version !== 1)) throw new SqliteStagingRetiredError();
retired = version === 1;
assertIdentity();
return token;
} catch (error) {
release();
throw error;
}
}
var SQLITE_STAGING_TOKEN_FILES, SqliteStagingRetiredError;
var init_sqlite_staging_token = __esmMin((() => {
init_record_coerce();
init_dist();
init_kysely_sync();
init_node_sqlite();
init_sqlite_error_diagnostics();
SQLITE_STAGING_TOKEN_FILES = [
"owner.sqlite",
"owner.sqlite-journal",
"owner.sqlite-wal",
"owner.sqlite-shm"
];
SqliteStagingRetiredError = class extends Error {
constructor() {
super("SQLite snapshot parent retired; aborting snapshot allocation");
}
};
}));
//#endregion
//#region src/infra/sqlite-snapshot-retirement.ts
function releaseTokens(directory, tokens) {
const pending = pendingTokenReleases.get(directory) ?? /* @__PURE__ */ new Set();
const failures = [];
for (const token of tokens) try {
token();
pending.delete(token);
} catch (error) {
pending.add(token);
failures.push(error);
}
if (pending.size) pendingTokenReleases.set(directory, pending);
else pendingTokenReleases.delete(directory);
if (failures.length) throw new AggregateError(failures, "SQLite snapshot retirement token release failed");
}
/** A failed native close retains its actual handle until retry, even after commit or unlink. */
function drainPendingSqliteSnapshotTokens(directory) {
releaseTokens(directory, pendingTokenReleases.get(directory) ?? []);
}
function acquireSqliteSnapshotToken(directory, mode) {
return acquireSqliteStagingToken(directory, mode, { allowMissing: SQLITE_SNAPSHOT_LEGACY_MARKER.test(path.basename(directory)) });
}
/** Hold every nested lifetime before selecting payload; a parent lock alone cannot fence children. */
function beginSqliteSnapshotRetirement(directory, options = {}) {
drainPendingSqliteSnapshotTokens(directory);
const tokens = [];
const payload = [];
const release = () => releaseTokens(directory, tokens.filter((token) => token !== options.token));
if (!fs.existsSync(directory)) {
options.token?.();
return {
bytes: 0,
payload,
release,
retire: () => {}
};
}
function inspect(current, inheritedCutoff, layout = "", lock = true, parentFenced = false) {
const stat = fs.lstatSync(current);
if (!stat.isDirectory() || process.getuid && stat.uid !== process.getuid()) throw new Error("Snapshot directory ownership is unknown");
const legacy = !layout && SQLITE_SNAPSHOT_LEGACY_MARKER.test(path.basename(current));
const cutoff = options.cutoff !== void 0 && legacy ? Math.min(inheritedCutoff, Date.now() - SQLITE_SNAPSHOT_LEGACY_AGE_MS) : inheritedCutoff;
if (legacy && lock && options.cutoff !== void 0) inspect(current, cutoff, layout, false);
if (!layout && lock) {
const unfinishedAllocation = parentFenced && tokenMarker.test(path.basename(current)) && fs.readdirSync(current).length === 0;
tokens.push(current === directory && options.token ? options.token.beginRetirement() : unfinishedAllocation ? acquireSqliteStagingToken(current, "reclaim", { allowMissing: true }) : acquireSqliteSnapshotToken(current, "reclaim"));
}
let bytes = 0;
let newest = stat.mtimeMs;
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
const location = path.join(current, entry.name);
const item = fs.lstatSync(location);
if (process.getuid && item.uid !== process.getuid()) throw new Error("Snapshot file ownership is unknown");
if ((!layout || options.cutoff === void 0) && item.isFile() && SQLITE_STAGING_TOKEN_FILES.some((file) => file === entry.name)) continue;
newest = Math.max(newest, item.mtimeMs);
if (item.isDirectory()) {
const nested = isSqliteSnapshotStagingName(entry.name);
const childLayout = nested ? "" : [layout, entry.name].filter(Boolean).join("/");
if (options.cutoff !== void 0 && (!nested && ![
"openclaw",
"openclaw-state",
"openclaw-state/state"
].includes(childLayout) || nested && layout !== "" && layout !== "openclaw")) throw new Error("Unrecognized snapshot directory");
const allocationParent = layout === "openclaw" ? path.dirname(current) : current;
const child = inspect(location, cutoff, childLayout, lock, nested && (layout === "" || layout === "openclaw") && isSqliteSnapshotStagingName(path.basename(allocationParent)));
bytes += child.bytes;
newest = Math.max(newest, child.newest);
} else if (options.cutoff === void 0 || item.isFile() && (layout === "openclaw-state/state" ? /^openclaw\.sqlite(?:-wal|-shm|-journal)?$/u.test(entry.name) : !layout && /^(?:first|database\.sqlite(?:\.partial)?(?:-wal|-shm|-journal)?)$/u.test(entry.name))) {
bytes += item.size;
if (lock) payload.push(location);
} else throw new Error("Unrecognized snapshot artifact");
}
if (newest >= cutoff) throw new Error(legacy ? "Legacy snapshot contains activity newer than 24 hours" : "Snapshot contains activity within the reclamation grace period");
return {
bytes,
newest
};
}
try {
const { bytes } = inspect(directory, options.cutoff ?? Number.POSITIVE_INFINITY);
return {
bytes,
payload,
release,
retire: () => {
for (const token of tokens) token(true);
}
};
} catch (error) {
release();
throw error;
}
}
var SQLITE_SNAPSHOT_PREFIX, suffix, SQLITE_SNAPSHOT_LEGACY_MARKER, tokenMarker, SQLITE_SNAPSHOT_LEGACY_AGE_MS, pendingTokenReleases, isSqliteSnapshotStagingName;
var init_sqlite_snapshot_retirement = __esmMin((() => {
init_sqlite_staging_token();
SQLITE_SNAPSHOT_PREFIX = "openclaw-sqlite-readonly-v2-";
suffix = "(?:[A-Za-z0-9]{6}|[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12})$";
SQLITE_SNAPSHOT_LEGACY_MARKER = new RegExp(`^openclaw-sqlite-readonly-[1-9]\\d*-${suffix}`, "u");
tokenMarker = new RegExp(`^${SQLITE_SNAPSHOT_PREFIX}${suffix}`, "u");
SQLITE_SNAPSHOT_LEGACY_AGE_MS = 864e5;
pendingTokenReleases = /* @__PURE__ */ new Map();
isSqliteSnapshotStagingName = (name) => SQLITE_SNAPSHOT_LEGACY_MARKER.test(name) || tokenMarker.test(name);
}));
//#endregion
//#region src/infra/sqlite-readonly-location-cleanup.ts
function snapshotDirectory(directory) {
let owner = pendingTempDirectoryCleanup.get(directory);
if (!owner) {
owner = { readers: /* @__PURE__ */ new Set() };
pendingTempDirectoryCleanup.set(directory, owner);
}
return owner;
}
function cleanupSnapshotOperations() {
pendingSignalCleanup ??= (async () => {
const directories = pendingTempDirectoryCleanup.keys();
while (true) {
while (activeSnapshotWork.size > 0) {
for (const stop of activeSnapshotWork.values()) stop();
await Promise.allSettled(activeSnapshotWork.keys());
}
const next = directories.next();
if (next.done) break;
const directory = next.value;
await removeTempDirectoryAsync(directory, (error) => emitSnapshotCleanupFailure({
cleanupRoot: directory,
operation: "rm",
code: extractErrorCode(error)
}));
}
})().finally(() => {
pendingSignalCleanup = void 0;
});
return pendingSignalCleanup;
}
/** Join native backup work or a terminated child before removing its private bytes. */
function retainSnapshotWork(work, stop = () => {}) {
registerSignalExitFinalizer(cleanupSnapshotOperations);
activeSnapshotWork.set(work, stop);
const release = () => activeSnapshotWork.delete(work);
work.then(release, release);
return work;
}
function registerSnapshotTempDirectory(directory, release) {
const owner = snapshotDirectory(directory);
owner.release = release ?? owner.release;
if (!cleanupExitHandlerInstalled) {
cleanupExitHandlerInstalled = true;
process.once("exit", () => {
for (const stop of activeSnapshotWork.values()) stop();
if (activeSnapshotWork.size === 0) for (const pendingDir of pendingTempDirectoryCleanup.keys()) removeTempDirectory(pendingDir);
});
}
registerSignalExitFinalizer(cleanupSnapshotOperations);
}
function emitSnapshotCleanupFailure(report, onCleanupFailure) {
if (onCleanupFailure) try {
onCleanupFailure(report);
return;
} catch {}
try {
getChildLogger({ subsystem: "infra/sqlite-snapshot" }).warn({
path: report.cleanupRoot,
operation: report.operation,
errorCode: report.code
}, "SQLite read-only snapshot cleanup failed. Check directory permissions and available storage before retrying.");
} catch {}
}
function assertSnapshotReadersRetired(owner) {
if (owner?.readers.size) throw new SqliteSnapshotCleanupError("SQLite snapshot still belongs to an active reader");
}
function prepareSnapshotRetirement(directory) {
drainPendingSqliteSnapshotTokens(directory);
const owner = pendingTempDirectoryCleanup.get(directory);
assertSnapshotReadersRetired(owner);
if (owner?.releaseAsync) throw new SqliteSnapshotCleanupError("SQLite snapshot requires asynchronous cleanup");
if (owner?.retired || !owner?.release && !fs.existsSync(path.join(directory, SQLITE_STAGING_TOKEN_FILES[0]))) return;
if (owner) owner.retirementStarted = true;
return beginSqliteSnapshotRetirement(directory, { token: owner?.release });
}
/** Delete in the token process: owner death must stop unlinking when its locks disappear. */
function retireSqliteSnapshotPayload(retirement) {
for (const file of retirement.payload) fs.rmSync(file, tempDirectoryRemovalOptions);
retirement.retire();
}
function removeTempDirectory(tempDir, onFailure) {
try {
const retirement = prepareSnapshotRetirement(tempDir);
try {
if (retirement) {
retireSqliteSnapshotPayload(retirement);
const owner = snapshotDirectory(tempDir);
owner.release = void 0;
owner.retired = true;
}
fs.rmSync(tempDir, tempDirectoryRemovalOptions);
} finally {
retirement?.release();
}
pendingTempDirectoryCleanup.delete(tempDir);
return true;
} catch (error) {
onFailure?.(error);
registerSnapshotTempDirectory(tempDir);
return false;
}
}
async function removeTempDirectoryAsync(tempDir, onFailure) {
try {
const owner = pendingTempDirectoryCleanup.get(tempDir);
assertSnapshotReadersRetired(owner);
if (owner?.releaseAsync) {
owner.retirementStarted = true;
await (owner.retiring ??= owner.releaseAsync().then(() => {
owner.releaseAsync = void 0;
owner.retired = true;
}).finally(() => {
owner.retiring = void 0;
}));
}
const retirement = prepareSnapshotRetirement(tempDir);
try {
for (const file of retirement?.payload ?? []) await retainSnapshotWork(fs.promises.rm(file, tempDirectoryRemovalOptions));
if (retirement) {
retirement.retire();
const current = snapshotDirectory(tempDir);
current.release = void 0;
current.retired = true;
}
await retainSnapshotWork(fs.promises.rm(tempDir, tempDirectoryRemovalOptions));
} finally {
retirement?.release();
}
pendingTempDirectoryCleanup.delete(tempDir);
return true;
} catch (error) {
onFailure?.(error);
registerSnapshotTempDirectory(tempDir);
return false;
}
}
function adoptPreparedLocation(location, ownedRoot, requireCleanup = false, onCleanupFailure) {
const tempDir = ownedRoot ?? path.dirname(location);
registerSnapshotTempDirectory(tempDir);
let active = true;
let pending;
let reported = false;
const reportFailure = (error) => {
if (!requireCleanup && !reported) {
reported = true;
emitSnapshotCleanupFailure({
cleanupRoot: tempDir,
operation: "rm",
code: extractErrorCode(error)
}, onCleanupFailure);
}
};
const complete = (removed) => {
if (removed) active = false;
else if (requireCleanup) throw new Error(`SQLite read-only worker snapshot cleanup failed: ${tempDir}`);
return removed;
};
return {
location,
cleanupRoot: tempDir,
cleanup: () => {
if (pending) return requireCleanup ? complete(false) : false;
if (!active) return true;
return complete(removeTempDirectory(tempDir, reportFailure));
},
cleanupAsync: () => {
if (pending) return pending;
if (!active) return Promise.resolve(true);
pending = Promise.resolve().then(() => removeTempDirectoryAsync(tempDir, reportFailure)).then(complete).finally(() => {
pending = void 0;
});
return pending;
}
};
}
var SqliteSnapshotCleanupError, pendingTempDirectoryCleanup, cleanupExitHandlerInstalled, activeSnapshotWork, pendingSignalCleanup, tempDirectoryRemovalOptions;
var init_sqlite_readonly_location_cleanup = __esmMin((() => {
init_error_coercion();
init_signal_exit_barrier();
init_logger();
init_sqlite_snapshot_retirement();
init_sqlite_staging_token();
SqliteSnapshotCleanupError = class extends Error {};
pendingTempDirectoryCleanup = /* @__PURE__ */ new Map();
cleanupExitHandlerInstalled = false;
activeSnapshotWork = /* @__PURE__ */ new Map();
tempDirectoryRemovalOptions = {
force: true,
maxRetries: 3,
recursive: true,
retryDelay: 20
};
}));
//#endregion
//#region src/state/openclaw-agent-db-metadata.ts
var init_openclaw_agent_db_metadata = __esmMin((() => {
init_openclaw_state_db_schema_helpers();
}));
//#endregion
//#region src/infra/sqlite-schema-header.ts
var init_sqlite_schema_header = __esmMin((() => {
init_openclaw_agent_db_metadata();
init_openclaw_state_db_contract();
init_kysely_sync();
init_node_sqlite();
init_sqlite_lifecycle_errors();
init_sqlite_transaction();
init_sqlite_user_version();
init_sqlite_wal();
}));
//#endregion
//#region src/infra/sqlite-snapshot-policy.ts
var init_sqlite_snapshot_policy = __esmMin((() => {
init_logger();
init_errno();
}));
var init_context = __esmMin((() => {
init_runtime_process_entrypoints();
new AsyncLocalStorage();
}));
var init_sqlite_readonly_worker_context = __esmMin((() => {
new AsyncLocalStorage();
}));
//#endregion
//#region src/infra/sqlite-readonly-worker-protocol.ts
function isSqliteSnapshotStagingMode(mode) {
return mode === "staging-create" || mode === "staging-create-legacy" || mode === "staging-reconcile" || mode === "staging-retire";
}
function isSqliteReadOnlyWorkerResult(value) {
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
if (Object.keys(value).length !== 2 || !("ok" in value)) return false;
return value.ok === true && "location" in value && typeof value.location === "string" || value.ok === true && "contentVersion" in value && typeof value.contentVersion === "string" && /^(?:[a-f0-9]{64})?$/.test(value.contentVersion) || value.ok === true && "warnings" in value && Array.isArray(value.warnings) && value.warnings.every((warning) => typeof warning === "string") || value.ok === false && "message" in value && typeof value.message === "string";
}
function createSqliteReadOnlyWorkerError(message, stderr) {
const stderrTail = toUSVString(sliceUtf16Safe(stderr.trim(), -4e3));
return /* @__PURE__ */ new Error(`SQLite read-only worker ${message}${stderrTail ? `\nstderr (tail): ${stderrTail}` : ""}`);
}
function parseSqliteReadOnlyWorkerResult(stdout, stderr) {
if (!stdout.trim()) throw createSqliteReadOnlyWorkerError("returned no JSON result", stderr);
let message;
try {
message = JSON.parse(stdout);
} catch {
throw createSqliteReadOnlyWorkerError("returned invalid JSON", stderr);
}
if (!isSqliteReadOnlyWorkerResult(message)) throw createSqliteReadOnlyWorkerError("returned an invalid result", stderr);
return message;
}
function readSqliteReadOnlyWorkerValue(params, mode) {
let result;
try {
result = parseSqliteReadOnlyWorkerResult(params.stdout, params.stderr);
} catch (error) {
if (params.failure) throw createSqliteReadOnlyWorkerError(params.failure, params.stderr);
throw error;
}
if (params.failure || !result.ok) {
const contention = !result.ok && result.message.startsWith("Retryable SQLite inspection contention: ");
const error = createSqliteReadOnlyWorkerError(!result.ok ? contention ? result.message.slice(40) : result.message : params.failure ?? "failed", params.stderr);
if (contention) throw new SqliteReadOnlyInspectionContentionError(error.message);
throw error;
}
if ((mode === "sync" || mode === "async" || mode === "consolidated" || isSqliteSnapshotStagingMode(mode)) && "location" in result) return result.location;
if (mode === "content-version" && "contentVersion" in result) return result.contentVersion;
if (mode === "reclaim" && "warnings" in result) return result.warnings;
throw createSqliteReadOnlyWorkerError("returned a result for a different operation", params.stderr);
}
var SQLITE_READONLY_WORKER_MAX_BUFFER, SqliteReadOnlyInspectionContentionError;
var init_sqlite_readonly_worker_protocol = __esmMin((() => {
init_utf16_slice();
SQLITE_READONLY_WORKER_MAX_BUFFER = 1048576;
SqliteReadOnlyInspectionContentionError = class extends Error {};
}));
var init_spawn_diagnostics = __esmMin((() => {
init_diagnostic_events();
init_subsystem();
init_global_singleton();
resolveGlobalSingleton(Symbol.for("openclaw.childProcessSpawnCounts"), () => ({
counts: /* @__PURE__ */ new Map(),
sampledAt: performance.now()
}));
}));
//#endregion
//#region src/infra/sqlite-readonly-worker-session.ts
var init_sqlite_readonly_worker_session = __esmMin((() => {
init_spawn_diagnostics();
init_sqlite_readonly_location_cleanup();
}));
//#endregion
//#region src/infra/sqlite-readonly-worker.ts
function resolveSqliteInspectionBudget(operation, pathname, sizeBytes) {
const timeoutMs = resolveTimerTimeoutMs(SQLITE_INSPECTION_TIMEOUT_MS + Math.ceil(40 * Number(sizeBytes ?? 0) / SQLITE_INSPECTION_BYTES_PER_SECOND) * 1e3, SQLITE_INSPECTION_TIMEOUT_MS);
const size = sizeBytes === void 0 ? "unknown size" : formatByteSize(Number(sizeBytes), {
style: "iec",
maxUnit: "giga",
separator: " ",
fractionDigits: sizeBytes < 1024n ? 0 : 1
});
if (timeoutMs > SQLITE_INSPECTION_TIMEOUT_MS) log.debug(`SQLite ${operation} for ${pathname}: ${size}, budget ${timeoutMs / 1e3} seconds`);
return {
timeoutMs,
size
};
}
function readSqliteInspectionBudget(operation, pathname, mainSizeBytes) {
let sizeBytes = mainSizeBytes;
try {
sizeBytes ??= fs.statSync(pathname, { bigint: true }).size;
for (const suffix of [
"-wal",
"-shm",
"-journal"
]) try {
sizeBytes += fs.statSync(pathname + suffix, { bigint: true }).size;
} catch (error) {
if (!hasErrnoCode(error, "ENOENT")) throw error;
}
} catch {}
return resolveSqliteInspectionBudget(operation, pathname, sizeBytes);
}
function sqliteInspectionTimeoutError(operation, pathname, timeoutMs, size) {
return /* @__PURE__ */ new Error(`SQLite ${operation} timed out after ${timeoutMs / 1e3} seconds (budget for ${size}) for ${pathname}. Stop the Gateway service and other OpenClaw processes using this database, then retry; if already stopped, check storage performance.`);
}
function sqliteReadOnlyWorkerRequestArgs(pathname, options) {
return [
options.mode,
path.resolve(pathname),
...options.stagingRoot ? [options.stagingRoot] : []
];
}
function sqliteReadOnlyWorkerArgv(pathname, options) {
const { moduleUrl, runtimeGeneration } = captureRuntimeWorkerSource(resolveRuntimeWorkerUrl(options.mode === "content-version" ? runtimeProcessEntrypoints.sqliteSourceRevision : runtimeProcessEntrypoints.sqliteReadOnly));
return {
runtimeGeneration,
argv: [
...resolveRuntimeWorkerArgv(moduleUrl),
SQLITE_READONLY_CHILD_ARG,
...sqliteReadOnlyWorkerRequestArgs(pathname, options)
]
};
}
function runSqliteReadOnlyWorkerSync(pathname, stagingRoot, mode = "sync") {
const { timeoutMs, size } = readSqliteInspectionBudget("read-only snapshot", pathname);
const started = log.isEnabled("trace") ? performance$1.now() : void 0;
const result = spawnSync(process.execPath, sqliteReadOnlyWorkerArgv(pathname, {
mode,
stagingRoot
}).argv, {
encoding: "utf8",
env: resolveNodeCompileCacheEnv(),
maxBuffer: SQLITE_READONLY_WORKER_MAX_BUFFER,
timeout: timeoutMs,
killSignal: "SIGKILL"
});
if (started !== void 0) log.trace(`SQLite read-only snapshot child durationMs=${performance$1.now() - started}`);
return readSqliteReadOnlyWorkerValue({
failure: result.error ? hasErrnoCode(result.error, "ETIMEDOUT") ? sqliteInspectionTimeoutError("read-only snapshot", pathname, timeoutMs, size).message : `failed to start: ${result.error.message}` : result.status === 0 ? void 0 : `exited with ${result.signal ? `signal ${result.signal}` : `code ${result.status}`}`,
stderr: result.stderr,
stdout: result.stdout
}, mode);
}
var SQLITE_INSPECTION_TIMEOUT_MS, SQLITE_INSPECTION_BYTES_PER_SECOND, log;
var init_sqlite_readonly_worker = __esmMin((() => {
init_src$2();
init_number_coercion();
init_subsystem();
init_context();
init_errno();
init_node_compile_cache_env();
init_runtime_process_entrypoints();
init_runtime_worker_generation();
init_runtime_worker_url();
init_sqlite_readonly_location_cleanup();
init_sqlite_readonly_worker_context();
init_sqlite_readonly_worker_protocol();
init_sqlite_readonly_worker_session();
SQLITE_INSPECTION_TIMEOUT_MS = 3e5;
SQLITE_INSPECTION_BYTES_PER_SECOND = 33554432;
log = createSubsystemLogger("state/sqlite");
}));
//#endregion
//#region src/infra/sqlite-snapshot-staging.ts
function stagingParent(root) {
const parent = path.basename(root) === "openclaw" ? path.dirname(root) : root;
return isSqliteSnapshotStagingName(path.basename(parent)) ? parent : void 0;
}
function sqliteSnapshotStagingError(tempDir, cause, allocation = false) {
markSqliteInspectionOperation(cause, "snapshot");
let destination = allocation;
let capacity = false;
let sqliteErrcode;
for (let depth = 0, error = cause; depth < 8 && error instanceof Error; depth += 1) {
const { code, errcode, path: errorPath } = error;
capacity ||= ["ENOSPC", "EDQUOT"].includes(code ?? "") || errcode === 13;
if (capacity || typeof errcode === "number" && [
13,
778,
1034,
1290
].includes(errcode) || `${errorPath ?? ""}${path.sep}`.startsWith(`${tempDir}${path.sep}`)) {
destination = true;
if (typeof errcode === "number") sqliteErrcode = errcode;
}
error = error.cause;
}
if (!destination) return cause;
const guidance = capacity ? "free disk space/quota" : "check filesystem health and write permissions";
const message = `${cause instanceof Error ? cause.message : String(cause)}${sqliteErrcode !== void 0 ? ` (SQLite errcode=${sqliteErrcode})` : ""}; snapshot staging root ${allocation ? tempDir : path.dirname(tempDir)}: ${guidance} or set XDG_CACHE_HOME to a writable filesystem`;
return new Error(message, { cause });
}
function createSqliteSnapshotStagingDirectorySync(root = resolvePrivateSqliteSnapshotStagingRoot(), allowLegacyWorker = false) {
const owned = createSqliteSnapshotStagingTokenSync(root, allowLegacyWorker);
registerSnapshotTempDirectory(owned.directory, owned.release);
return owned.directory;
}
/** Token workers remove disposable payload under their own native retirement fences. */
function createSqliteSnapshotStagingTokenSync(root = resolvePrivateSqliteSnapshotStagingRoot(), allowLegacyWorker = false) {
const parentDirectory = stagingParent(root);
const parent = parentDirectory ? acquireSqliteSnapshotToken(parentDirectory, "read") : void 0;
let directory;
try {
try {
directory = createPrivateSqliteTempDirectorySync(root, allowLegacyWorker ? `openclaw-sqlite-readonly-${process.pid}-` : SQLITE_SNAPSHOT_PREFIX);
} catch (error) {
throw sqliteSnapshotStagingError(root, error, true);
}
return {
directory,
release: acquireSqliteSnapshotToken(directory, "create")
};
} catch (error) {
if (directory) removeTempDirectory(directory);
throw error;
} finally {
parent?.();
}
}
var init_sqlite_snapshot_staging = __esmMin((() => {
init_logger();
init_errors$2();
init_sqlite_error_diagnostics();
init_sqlite_private_directory();
init_sqlite_readonly_location_cleanup();
init_sqlite_snapshot_retirement();
}));
//#endregion
//#region src/infra/sqlite-snapshot-wal-prefix.ts
var init_sqlite_snapshot_wal_prefix = __esmMin((() => {}));
//#endregion
//#region src/infra/sqlite-source-handle.ts
var init_sqlite_source_handle = __esmMin((() => {
init_gateway_state_owner();
init_node_sqlite();
init_sqlite_error_diagnostics();
}));
var init_sqlite_readonly_location = __esmMin((() => {
init_node_sqlite();
init_sqlite_backup();
init_sqlite_error_diagnostics();
init_sqlite_lifecycle_errors();
init_sqlite_private_directory();
init_sqlite_readonly_location_cleanup();
init_sqlite_schema_header();
init_sqlite_snapshot_policy();
init_sqlite_snapshot_staging();
init_sqlite_snapshot_wal_prefix();
init_sqlite_source_handle();
Buffer.from([
217,
213,
5,
249,
32,
161,
99,
215
]);
}));
var init_sqlite_snapshot_single_flight = __esmMin((() => {
init_logger();
init_global_singleton();
init_sqlite_readonly_location_cleanup();
init_sqlite_worker_identity();
resolveGlobalSingleton(Symbol.for("openclaw.sqliteSnapshotFlights"), () => /* @__PURE__ */ new Map());
}));
//#endregion
//#region src/infra/sqlite-live-snapshot.ts
function registerLiveSqliteSnapshotOwner(options) {
const identity = readDatabasePathIdentitySync(options.databasePath);
const registration = {
assertCurrent: options.assertCurrent,
database: options.database,
owner: options.owner
};
liveOwners.set(identity.key, registration);
return () => {
if (liveOwners.get(identity.key) === registration) liveOwners.delete(identity.key);
};
}
var liveOwners;
var init_sqlite_live_snapshot = __esmMin((() => {
init_logger();
init_global_singleton();
init_errno();
init_sqlite_readonly_location();
init_sqlite_snapshot_single_flight();
init_sqlite_worker_identity();
liveOwners = resolveGlobalSingleton(Symbol.for("openclaw.sqliteLiveSnapshotOwners"), () => /* @__PURE__ */ new Map());
}));
//#endregion
//#region src/state/openclaw-state-db-snapshot-owner.ts
function createOpenClawStateSnapshotOwnerRegistry() {
const releases = /* @__PURE__ */ new WeakMap();
return {
register(database, getCurrent) {
releases.set(database.db, registerLiveSqliteSnapshotOwner({
database: database.db,
databasePath: database.path,
owner: "openclaw-state",
assertCurrent: () => {
if (getCurrent() !== database || !database.db.isOpen) throw new Error("OpenClaw state snapshot owner is no longer current");
}
}));
},
release(database) {
releases.get(database)?.();
releases.delete(database);
}
};
}
var openClawStateSnapshotOwners;
var init_openclaw_state_db_snapshot_owner = __esmMin((() => {
init_sqlite_live_snapshot();
init_global_singleton();
openClawStateSnapshotOwners = resolveGlobalSingleton(Symbol.for("openclaw.stateSnapshotOwners"), createOpenClawStateSnapshotOwnerRegistry);
}));
//#endregion
//#region src/state/openclaw-state-db-cache.ts
function notifyOpenClawStateDatabaseLifecycle(event) {
const notification = event.kind === "open-error" ? {
...event,
identity: event.identity ?? asyncResources.knownIdentity(event.path)
} : event;
for (const listener of databaseLifecycleListeners) listener(notification);
}
function notifyOpenClawStateDatabaseClosed(database) {
notifyOpenClawStateDatabaseLifecycle({
kind: "closed",
path: database.path,
identity: requireOpenClawStateDatabaseIdentity(database)
});
}
function requireOpenClawStateDatabaseIdentity(database) {
const identity = databaseIdentities.get(database.db);
if (!identity) throw new Error("Published shared-state owner has no recorded database identity");
return identity;
}
function registerOpenClawStateDatabaseLifecycleListener(listener) {
databaseLifecycleListeners.add(listener);
for (const database of cachedDatabases.values()) if (database.db.isOpen) listener({
kind: "opened",
database,
identity: requireOpenClawStateDatabaseIdentity(database)
});
return () => databaseLifecycleListeners.delete(listener);
}
function retainStateDatabaseClose(database) {
retainedDatabaseHandles.set(database.db, database);
stateDatabaseLifecycle.unregisterRetainedExitClose ??= registerSqliteCacheExitClose(closeOpenClawStateDatabase);
}
function ownMaintenanceStateDatabaseHandle(database) {
getOpenClawDatabaseMaintenanceScope()?.own(database.db, "shared-handles", async () => {
const closingScope = getOpenClawDatabaseMaintenanceScope();
if (!closingScope || !isOpenClawDatabaseMaintenanceResourceOwned(database.db, closingScope)) return;
if (cachedDatabases.get(database.path) === database || retainedDatabaseHandles.get(database.db) === database) {
await cancelSqliteWalWriteAdmission(database.db);
if (isOpenClawDatabaseMaintenanceResourceOwned(database.db, closingScope) && (cachedDatabases.get(database.path) === database || retainedDatabaseHandles.get(database.db) === database)) retireOpenClawStateDatabaseHandle(database, false);
}
});
}
function closeUnpublishedOpenClawStateDatabaseHandle(database) {
const errors = closeOpenClawStateDatabaseHandle(database);
if (retainedDatabaseHandles.get(database.db) === database) ownMaintenanceStateDatabaseHandle(database);
return errors;
}
/** Close both physical-handle owners while retaining every cleanup failure. */
function closeOpenClawStateDatabaseHandle(database, options) {
clearTimeout(idleTimers.get(database.db));
idleTimers.delete(database.db);
try {
assertStateDatabaseBorrowersReleased(borrowers.get(database.db), database.path);
} catch (error) {
const owner = borrowers.get(database.db);
if (owner) {
owner.retiring = true;
owner.retirement = {
ordinary: true,
isCurrent: () => true,
retire: () => {
throwSqliteLifecycleErrors(closeOpenClawStateDatabaseHandle(database, options), `OpenClaw state database cleanup failed for ${database.path}.`);
owner.cleanupComplete = true;
borrowers.delete(database.db);
}
};
}
retainStateDatabaseClose(database);
return [error];
}
idleReferences.delete(database.db);
const errors = [];
openClawStateSnapshotOwners.release(database.db);
try {
cancelSqliteWalWriteAdmission(database.db);
database.walMaintenance?.close(options);
} catch (error) {
errors.push(error);
}
try {
clearNodeSqliteKyselyCacheForDatabase(database.db);
} catch (error) {
errors.push(error);
}
try {
closeTrackedStateDatabase(database.db);
} catch (error) {
errors.push(error);
}
let cleanupPending = false;
if (!database.db.isOpen) try {
database.afterClose?.();
} catch (error) {
errors.push(error);
cleanupPending = true;
}
if (database.db.isOpen || cleanupPending) retainStateDatabaseClose(database);
else retainedDatabaseHandles.delete(database.db);
if (cachedDatabases.get(database.path)?.db === database.db) cachedDatabases.delete(database.path);
if (retainedDatabaseHandles.size === 0) {
stateDatabaseLifecycle.unregisterRetainedExitClose?.();
stateDatabaseLifecycle.unregisterRetainedExitClose = void 0;
}
return errors;
}
function evictCachedOpenClawStateDatabase(database) {
if (cachedDatabases.get(database.path) !== database) return false;
asyncResources.invalidate(database.path);
cachedDatabases.delete(database.path);
notifyOpenClawStateDatabaseClosed(database);
closeOpenClawStateDatabaseHandle(database, { checkpointMode: "PASSIVE" });
return true;
}
/** Evict an exact cached shared-state owner after a proven corruption read. */
function evictOpenClawStateDatabaseAfterCorruption(database, error) {
return isSqliteCorruptionError(error) && evictCachedOpenClawStateDatabase(database);
}
/** Publish a fully opened handle and bind query corruption to its exact cache owner. */
function publishOpenClawStateDatabase(database, env) {
const { db, path: pathname } = database;
admitSqliteSchema(db);
assertSupportedStateSchemaVersion(db, pathname);
const { identity, admission } = asyncResources.publish(pathname);
databaseIdentities.set(db, identity);
cachedDatabases.set(pathname, database);
registerStateDatabaseWalAdmission(database, identity, admission, env);
touchStateDatabase(database);
openClawStateSnapshotOwners.register(database, () => cachedDatabases.get(pathname));
ownMaintenanceStateDatabaseHandle(database);
notifyOpenClawStateDatabaseLifecycle({
kind: "opened",
database,
identity
});
registerNodeSqliteKyselyQueryErrorHandler(db, (error) => {
if (!db.isTransaction && isSqliteCorruptionError(error)) evictCachedOpenClawStateDatabase(database);
});
terminalOpenLatch.clear(pathname);
return database;
}
function getCachedOpenClawStateDatabase(pathname, options) {
const maintenance = getOpenClawDatabaseMaintenanceScope();
if (options?.readOnly) maintenance?.assertReadAdmission();
else maintenance?.assertAdmission();
assertExistingOpenClawStateSchemaCacheAdmission(pathname, stateDatabaseLifecycle);
const runtimeFailure = runtimeFailures.get(pathname);
if (runtimeFailure) throw runtimeFailure;
const database = cachedDatabases.get(path.resolve(pathname));
if (database && borrowers.get(database.db)?.retiring) throw new Error(`OpenClaw state database native borrower cleanup is pending: ${pathname}`);
if (database) touchStateDatabase(database);
return database;
}
function getOpenClawStateDatabaseIfOpenAtPath(pathname) {
const cached = getCachedOpenClawStateDatabase(pathname);
observeOpenClawDatabaseMaintenanceResource(cached?.db.isOpen ? cached.db : void 0);
return cached?.db.isOpen ? cached : void 0;
}
/** Remove a closed cached owner while fresh-open access is held. */
function closeStaleCachedOpenClawStateDatabase(database) {
if (cachedDatabases.get(database.path) !== database) return;
asyncResources.invalidate(database.path);
const errors = closeOpenClawStateDatabaseHandle(database);
notifyOpenClawStateDatabaseClosed(database);
throwSqliteLifecycleErrors(errors, `Stale OpenClaw state database cleanup failed for ${database.path}.`);
}
/** Latch background verification damage so later opens fail without rescanning. */
function recordOpenClawStateDatabaseOpenFailure(pathname, error, generation) {
return terminalOpenLatch.record(pathname, error, generation);
}
/** Clear a terminal open failure after doctor rewrites the database file. */
function clearOpenClawStateDatabaseOpenFailure(pathname) {
const resolvedPath = path.resolve(pathname);
terminalOpenLatch.clear(resolvedPath);
asyncResources.invalidate(resolvedPath);
notifyOpenClawStateDatabaseLifecycle({
kind: "failure-cleared",
path: resolvedPath,
identity: asyncResources.knownIdentity(resolvedPath)
});
}
/** Validate the canonical terminal fact before acquiring a domain-operation lease. */
async function getOpenClawStateDatabaseTerminalFailureAsync(context) {
context.admission.assertCurrent();
const failure = await terminalOpenLatch.getAsync(context.admission.databasePath, async (_path, generation) => {
const { inspectOpenClawStateDatabase } = await Promise.resolve().then(() => (init_openclaw_state_worker_store(), openclaw_state_worker_store_exports));
const matches = await inspectOpenClawStateDatabase(context, {
type: "database.generationMatches",
input: { generation }
});
if (matches === void 0) throw new Error("Recorded shared-state database generation is unavailable");
return matches;
});
context.admission.assertCurrent();
return failure;
}
/** Reject shared-state access after a process-local terminal failure. */
function assertOpenClawStateDatabaseOpenAllowed(pathname, ownership) {
if (ownership === "cached-read") assertStateDatabaseReadAllowed(pathname);
else assertStateDatabaseAccessAllowed(pathname);
const { identity } = asyncResources.capture(pathname);
const terminalFailure = terminalOpenLatch.get(pathname);
if (terminalFailure) throw terminalFailure;
const resolvedPath = path.resolve(pathname);
for (const database of retainedDatabaseHandles.values()) if (borrowers.get(database.db)?.retiring && (database.path === resolvedPath || databaseIdentities.get(database.db)?.key === identity.key)) throw new Error(`OpenClaw state database native borrower cleanup is pending: ${pathname}`);
}
function recordOpenClawStateDatabaseLifecycleOpenError(pathname, error) {
notifyOpenClawStateDatabaseLifecycle({
kind: "open-error",
path: path.resolve(pathname),
error
});
}
/** Reject a fresh shared-state open after known corruption until repair clears it. */
function assertOpenClawStateDatabaseFreshOpenAllowedAtPath(pathname, env, onNativeCleanupFailure) {
assertOpenClawStateDatabaseOpenAllowed(pathname);
let quarantineFailure;
try {
quarantineFailure = readOpenClawDatabaseQuarantineFailure("state", pathname, { env });
} catch (error) {
if (!(error instanceof OpenClawQuarantineReadCleanupError)) throw error;
onNativeCleanupFailure?.(error);
return;
}
if (quarantineFailure?.cause instanceof OpenClawQuarantineReadCleanupError) onNativeCleanupFailure?.(quarantineFailure.cause);
if (quarantineFailure) {
runtimeFailures.closeTerminalFailure(pathname, quarantineFailure);
throw quarantineFailure;
}
}
/** SQLite owns checkpoint exclusion; retirement joins the actual native handle. */
function retireOpenClawStateDatabaseHandle(database, retireAdmission = true, options) {
assertStateDatabaseBorrowersReleased(borrowers.get(database.db), database.path);
const borrowedOwner = borrowers.get(database.db);
try {
const wasCached = cachedDatabases.get(database.path)?.db === database.db;
if (retireAdmission) asyncResources.invalidate(database.path);
const errors = closeOpenClawStateDatabaseHandle(database, options);
if (wasCached && retireAdmission) try {
notifyOpenClawStateDatabaseClosed(database);
} catch (error) {
errors.push(error);
}
throwSqliteLifecycleErrors(errors, `OpenClaw state database cleanup failed for ${database.path}.`);
} catch (error) {
if (borrowedOwner) retainStateDatabaseClose(database);
throw error;
}
if (borrowedOwner) {
borrowedOwner.cleanupComplete = true;
borrowers.delete(database.db);
}
}
/** Close cached and disposal-only handles, preserving independent cleanup failures. */
function retireOpenClawStateDatabaseHandles(pathname, options, identity) {
const databases = /* @__PURE__ */ new Set([...retainedDatabaseHandles.values(), ...cachedDatabases.values()]);
const errors = [];
let found = false;
for (const database of databases) {
if (pathname !== void 0 && database.path !== pathname && (identity === void 0 || databaseIdentities.get(database.db)?.key !== identity.key)) continue;
found = true;
try {
retireOpenClawStateDatabaseHandle(database, true, options);
} catch (error) {
errors.push(error);
}
}
throwSqliteLifecycleErrors(errors, "OpenClaw state database cleanup failed.");
return found;
}
/** Close one cached shared state database handle by exact pathname. */
function closeOpenClawStateDatabaseByPath(pathname, options) {
return retireOpenClawStateDatabaseHandles(path.resolve(pathname), options, asyncResources.identity(pathname));
}
/** Close all cached shared state database handles. */
function closeOpenClawStateDatabase(options) {
retireOpenClawStateDatabaseHandles(void 0, options);
}
/** Register a resource owner before it can admit any shared-state worker opens. */
function registerOpenClawStateDatabaseAsyncResource(resource) {
return asyncResources.register(resource);
}
/** Bind worker-created storage to its captured admission without publishing a native handle. */
function publishOpenClawStateDatabaseWorkerAdmission(admission) {
admission.assertCurrent();
asyncResources.publish(admission.databasePath);
admission.assertCurrent();
}
/** Orderly lifecycle close; synchronous close remains native/exit cleanup only. */
async function closeOpenClawStateDatabaseAsync(options) {
await asyncResources.close(void 0, () => retireOpenClawStateDatabaseHandles(void 0, options));
}
/** Test whether a cached shared state database handle is still open, optionally at one path. */
function isOpenClawStateDatabaseOpen(pathname) {
if (pathname !== void 0) return cachedDatabases.get(path.resolve(pathname))?.db.isOpen === true;
return Array.from(cachedDatabases.values()).some((database) => database.db.isOpen);
}
/**
* Close shared state handles and clear terminal failure latches for test isolation.
* Worker retirement continues after return; await closeOpenClawStateDatabaseAsync()
* before raw SQLite or file access to a database that workers have used.
*/
function closeOpenClawStateDatabaseForTest() {
closeOpenClawStateDatabase();
terminalOpenLatch.clearAll();
}
var stateDatabaseLifecycle, cachedDatabases, retainedDatabaseHandles, idleTimers, idleReferences, databaseIdentities, borrowers, databaseLifecycleListeners, terminalOpenLatch, asyncResources, touchStateDatabase, retainOpenClawStateDatabaseForIdle, registerStateDatabaseWalAdmission, readOpenClawStateWalHealth, runtimeFailures, retainOpenClawStateDatabase, borrowOpenClawStateDatabaseForAsyncRead, retainOpenClawStateDatabaseForIndependentRead, captureOpenClawStateDatabaseReadAdmission, openClawStateDatabaseCache;
var init_openclaw_state_db_cache = __esmMin((() => {
init_gateway_state_owner();
init_kysely_sync_cache_state();
init_node_sqlite();
init_sqlite_error_diagnostics();
init_sqlite_integrity();
init_sqlite_lifecycle_errors();
init_sqlite_schema_facts();
init_sqlite_terminal_open_latch();
init_sqlite_wal_write_admission();
init_sqlite_wal();
init_global_singleton();
init_openclaw_quarantine_error();
init_openclaw_quarantine_store();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_borrow();
init_openclaw_state_db_cache_idle();
init_openclaw_state_db_cache_wal();
init_openclaw_state_db_handle();
init_openclaw_state_db_runtime_failure();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_schema_version();
init_openclaw_state_db_snapshot_owner();
stateDatabaseLifecycle = resolveGlobalSingleton(Symbol.for("openclaw.stateDatabaseLifecycle"), () => ({
cachedDatabases: /* @__PURE__ */ new Map(),
retainedDatabaseHandles: /* @__PURE__ */ new Map(),
idleTimers: /* @__PURE__ */ new WeakMap(),
idleReferences: /* @__PURE__ */ new WeakMap(),
unregisterRetainedExitClose: void 0,
databaseIdentities: /* @__PURE__ */ new WeakMap(),
borrowers: /* @__PURE__ */ new WeakMap(),
databaseLifecycleListeners: /* @__PURE__ */ new Set(),
terminalOpenLatch: createSqliteTerminalOpenLatch({ closeByPath: (pathname, error) => runtimeFailures.closeTerminalFailure(pathname, error) }),
asyncResources: createOpenClawStateDatabaseAsyncLifecycle()
}), () => closeOpenClawStateDatabaseAsync());
({cachedDatabases, retainedDatabaseHandles, idleTimers, idleReferences, databaseIdentities, borrowers, databaseLifecycleListeners, terminalOpenLatch, asyncResources} = stateDatabaseLifecycle);
({touch: touchStateDatabase, retain: retainOpenClawStateDatabaseForIdle} = createStateDatabaseIdleRetirement(stateDatabaseLifecycle, retireOpenClawStateDatabaseHandle));
({register: registerStateDatabaseWalAdmission, readHealth: readOpenClawStateWalHealth} = createStateDatabaseWalOwner(stateDatabaseLifecycle, retainOpenClawStateDatabaseForIdle));
runtimeFailures = createOpenClawStateDatabaseRuntimeFailureOwner({
cachedDatabases,
latch: terminalOpenLatch,
evict: evictCachedOpenClawStateDatabase,
invalidate: (pathname) => asyncResources.invalidate(pathname),
notifyTerminalFailure: (pathname, error) => notifyOpenClawStateDatabaseLifecycle({
kind: "terminal-failure",
path: pathname,
error,
identity: asyncResources.knownIdentity(pathname)
}),
recordSchemaFailure: (pathname, error) => {
terminalOpenLatch.record(pathname, error);
notifyOpenClawStateDatabaseLifecycle({
kind: "open-error",
path: pathname,
error
});
}
});
({retain: retainOpenClawStateDatabase, borrowForRead: borrowOpenClawStateDatabaseForAsyncRead, retainForIndependentRead: retainOpenClawStateDatabaseForIndependentRead} = createStateDatabaseRetainer(stateDatabaseLifecycle, {
assertOpen(pathname, ownership) {
assertOpenClawStateDatabaseOpenAllowed(pathname, ownership);
assertExistingOpenClawStateSchemaCacheAdmission(pathname, stateDatabaseLifecycle);
},
capture: (pathname) => asyncResources.capture(pathname),
retire: retireOpenClawStateDatabaseHandle,
retainFailed: retainStateDatabaseClose,
touch: touchStateDatabase
}));
captureOpenClawStateDatabaseReadAdmission = asyncResources.capture;
openClawStateDatabaseCache = {
assertOpenClawStateDatabaseFreshOpenAllowedAtPath,
assertOpenClawStateDatabaseOpenAllowed,
clearOpenClawStateDatabaseOpenFailure,
closeOpenClawStateDatabase,
closeOpenClawStateDatabaseByPath,
closeOpenClawStateDatabaseForTest,
closeOpenClawStateDatabaseHandle,
closeUnpublishedOpenClawStateDatabaseHandle,
closeStaleCachedOpenClawStateDatabase,
evictCachedOpenClawStateDatabase,
evictOpenClawStateDatabaseAfterCorruption,
getCachedOpenClawStateDatabase,
getOpenClawStateDatabaseRuntimeFailure: runtimeFailures.get,
getOpenClawStateDatabaseRecordedFailure: terminalOpenLatch.peek,
getOpenClawStateDatabaseIfOpenAtPath,
getKnownOpenClawStateDatabaseIdentity: asyncResources.knownIdentity,
isOpenClawStateDatabaseOpen,
publishOpenClawStateDatabase,
recordOpenClawStateDatabaseOpenFailure,
recordOpenClawStateDatabaseLifecycleOpenError,
touchStateDatabase
};
}));
//#endregion
//#region packages/gateway-protocol/src/failover-reasons.ts
var FAILOVER_REASONS;
var init_failover_reasons = __esmMin((() => {
FAILOVER_REASONS = [
"auth",
"auth_permanent",
"format",
"rate_limit",
"overloaded",
"billing",
"server_error",
"timeout",
"tls_certificate",
"context_overflow",
"model_not_found",
"session_expired",
"empty_response",
"no_error_details",
"unclassified",
"unknown"
];
}));
//#endregion
//#region src/cron/run-diagnostics-normalize.ts
var init_run_diagnostics_normalize = __esmMin((() => {
init_number_coercion();
}));
//#endregion
//#region src/cron/run-history-detail.ts
function isJsonObject(value) {
return isRecord(value);
}
function normalizeTimestamp(value) {
return asSafeIntegerInRange(value, {
min: 0,
max: MAX_DATE_TIMESTAMP_MS
});
}
var cronRunStatusSchema, cronCompletionStatusSchema, cronDeliveryStatusSchema, optionalCronStringSchema, optionalNonBlankCronStringSchema, optionalCronTimestampSchema, optionalCronNonnegativeIntegerSchema, cronUsageSchema, cronFailureNotificationDeliverySchema;
var init_run_history_detail = __esmMin((() => {
init_number_coercion();
init_record_coerce();
init_zod();
init_failover_reasons();
init_run_diagnostics_normalize();
cronRunStatusSchema = _enum([
"ok",
"error",
"skipped"
]);
cronCompletionStatusSchema = _enum([
"succeeded",
"failed",
"unknown"
]);
cronDeliveryStatusSchema = _enum([
"delivered",
"not-delivered",
"unknown",
"not-requested"
]);
optionalCronStringSchema = string().optional().catch(void 0);
optionalNonBlankCronStringSchema = string().refine((value) => value.trim().length > 0).optional().catch(void 0);
optionalCronTimestampSchema = unknown().optional().transform((value) => normalizeTimestamp(value));
optionalCronNonnegativeIntegerSchema = unknown().optional().transform((value) => asSafeIntegerInRange(value, { min: 0 }));
cronUsageSchema = object({
input_tokens: optionalCronNonnegativeIntegerSchema,
output_tokens: optionalCronNonnegativeIntegerSchema,
total_tokens: optionalCronNonnegativeIntegerSchema,
cache_read_tokens: optionalCronNonnegativeIntegerSchema,
cache_write_tokens: optionalCronNonnegativeIntegerSchema
}).transform((usage) => Object.values(usage).some((tokenCount) => tokenCount !== void 0) ? usage : void 0).optional().catch(void 0);
cronFailureNotificationDeliverySchema = looseObject({
status: cronDeliveryStatusSchema,
delivered: boolean().optional().catch(void 0),
error: optionalCronStringSchema
}).transform(({ status, delivered, error }) => ({
status,
...delivered !== void 0 ? { delivered } : {},
...error !== void 0 ? { error } : {}
})).optional().catch(void 0);
looseObject({
action: literal("finished"),
jobId: string().refine((value) => value.trim().length > 0),
ts: unknown().transform((value) => normalizeTimestamp(value)).pipe(number()),
status: cronRunStatusSchema.optional().catch(void 0),
completionStatus: cronCompletionStatusSchema.optional().catch(void 0),
error: optionalCronStringSchema,
errorReason: _enum(FAILOVER_REASONS).optional().catch(void 0),
summary: optionalCronStringSchema,
runId: optionalNonBlankCronStringSchema,
diagnostics: unknown().optional(),
runAtMs: optionalCronTimestampSchema,
durationMs: optionalCronNonnegativeIntegerSchema,
nextRunAtMs: optionalCronTimestampSchema,
triggerFired: unknown().optional().transform((value) => value === true ? true : void 0),
model: optionalNonBlankCronStringSchema,
provider: optionalNonBlankCronStringSchema,
usage: cronUsageSchema,
delivered: boolean().optional().catch(void 0),
deliveryStatus: cronDeliveryStatusSchema.optional().catch(void 0),
deliveryError: optionalCronStringSchema,
deliverySuppressionReason: _enum([
"empty",
"silent",
"heartbeat",
"channel_transform"
]).optional().catch(void 0),
failureNotificationDelivery: cronFailureNotificationDeliverySchema,
delivery: custom(isJsonObject).optional().catch(void 0),
sessionId: optionalNonBlankCronStringSchema,
sessionKey: optionalNonBlankCronStringSchema
});
}));
//#endregion
//#region src/infra/state-migrations.cron-run-logs.ts
function hasLegacyCronRunLogs(db) {
return Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'cron_run_logs' LIMIT 1").get());
}
var init_state_migrations_cron_run_logs = __esmMin((() => {
init_src$2();
init_run_history_detail();
init_sqlite_number();
}));
//#endregion
//#region src/infra/sqlite-audit-record.kernel.ts
var init_sqlite_audit_record_kernel = __esmMin((() => {
init_kysely_sync();
init_sqlite_number();
}));
//#endregion
//#region src/state/openclaw-state-db-additive-columns.ts
function lazyColumnDefinitions(firstUseOnly) {
return lazyColumns.filter((definition) => firstUseOnly === void 0 || Boolean(definition[3]) === firstUseOnly).map(([tableName, columnName, dataType]) => ({
columnName,
dataType,
tableName
}));
}
var lazyColumns, CLAW_LAZY_ADDITIVE_STATE_COLUMN_DEFINITIONS, CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS, CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS, ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS;
var init_openclaw_state_db_additive_columns = __esmMin((() => {
lazyColumns = [
[
"user_profile_identities",
"authorization_id",
"TEXT"
],
[
"user_profile_identities",
"authorization_basis_json",
"TEXT"
],
[
"claw_installs",
"bootstrap_content_digest",
"TEXT"
],
[
"claw_installs",
"bootstrap_source_path",
"TEXT"
],
[
"worker_environments",
"desktop_json",
"TEXT"
],
[
"worker_environments",
"bootstrap_install_kind",
"TEXT"
],
[
"worker_environments",
"preparation_purpose",
"TEXT"
],
[
"claw_package_refs",
"extension_adapter_identity",
"TEXT"
],
[
"claw_package_refs",
"extension_detected_format",
"TEXT"
],
[
"claw_package_refs",
"extension_format",
"TEXT"
],
[
"claw_package_refs",
"extension_id",
"TEXT"
],
[
"claw_package_refs",
"extension_mapped_json",
"TEXT"
],
[
"claw_package_refs",
"extension_unavailable_json",
"TEXT"
],
[
"worker_environments",
"shared_host",
"INTEGER"
],
[
"worker_environments",
"node_setup_id",
"TEXT"
],
[
"worker_environments",
"node_device_id",
"TEXT"
],
[
"worker_session_placements",
"terminal_reason",
"TEXT"
],
[
"worker_session_placements",
"terminal_at_ms",
"INTEGER"
],
[
"worker_workspace_pending_results",
"repository_workspace_id",
"TEXT",
true
],
[
"worker_session_placement_moves",
"abandon_source",
"INTEGER",
true
],
[
"worker_session_placement_moves",
"target_machine_class",
"TEXT",
true
],
[
"worker_session_placement_moves",
"target_os",
"TEXT",
true
],
[
"worktrees",
"run_end_cleanup_json",
"TEXT"
],
[
"worktrees",
"gc_protection_json",
"TEXT"
],
[
"device_bootstrap_tokens",
"setup_id",
"TEXT",
true
],
[
"session_groups",
"cwd",
"TEXT",
true
],
[
"session_groups",
"worktree",
"INTEGER",
true
],
[
"secret_store_entries",
"allowed_hosts",
"TEXT"
],
[
"web_push_subscriptions",
"device_id",
"TEXT",
true
],
[
"web_push_subscriptions",
"user_profile_id",
"TEXT",
true
],
[
"web_push_subscriptions",
"preferences_json",
"TEXT",
true
],
[
"task_runs",
"execution_owner_host",
"TEXT",
true
],
[
"task_runs",
"execution_owner_pid",
"INTEGER",
true
],
[
"task_runs",
"execution_owner_start_identity",
"INTEGER",
true
],
[
"session_watch_cursors",
"watcher_store_path",
"TEXT",
true
],
[
"subagent_runs",
"requester_store_path",
"TEXT",
true
],
[
"subagent_runs",
"controller_store_path",
"TEXT",
true
],
[
"cron_jobs",
"grant_definition_revision",
"TEXT"
],
[
"cron_jobs",
"grant_definition_generation",
"INTEGER"
],
[
"cron_jobs",
"grant_definition_updated_at",
"INTEGER"
]
];
CLAW_LAZY_ADDITIVE_STATE_COLUMN_DEFINITIONS = lazyColumnDefinitions();
CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS = lazyColumnDefinitions(false);
CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS = lazyColumnDefinitions(true);
ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS = {
packageUpdatedAt: [["claw_package_refs", "updated_at_ms INTEGER NOT NULL DEFAULT 0"]],
packageIntegrity: [["claw_package_refs", "package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'"]],
diagnosticSequence: [["diagnostic_events", "sequence INTEGER NOT NULL DEFAULT 0"]],
cronRunLogs: [
["worktrees", "provisioned_paths_json TEXT"],
["apns_registrations", "relay_origin TEXT"],
["device_pairing_pending", "refreshed_at_ms INTEGER"],
["device_pairing_pending", "browser_origin TEXT"],
["device_pairing_paired", "approved_via TEXT"],
["device_pairing_paired", "browser_origin TEXT"],
["device_pairing_paired", "operator_label TEXT"],
["device_pairing_paired", "node_surface_json TEXT"],
["device_pairing_paired", "pending_node_surface_json TEXT"],
["cron_run_logs", "status TEXT"],
["cron_run_logs", "error TEXT"],
["cron_run_logs", "summary TEXT"],
["cron_run_logs", "diagnostics_summary TEXT"],
["cron_run_logs", "delivery_status TEXT"],
["cron_run_logs", "delivery_error TEXT"],
["cron_run_logs", "delivered INTEGER"],
["cron_run_logs", "session_id TEXT"],
["cron_run_logs", "session_key TEXT"],
["cron_run_logs", "run_id TEXT"],
["cron_run_logs", "run_at_ms INTEGER"],
["cron_run_logs", "duration_ms INTEGER"],
["cron_run_logs", "next_run_at_ms INTEGER"],
["cron_run_logs", "model TEXT"],
["cron_run_logs", "provider TEXT"],
["cron_run_logs", "total_tokens INTEGER"],
["cron_run_logs", "entry_json TEXT NOT NULL DEFAULT '{}'"],
["cron_run_logs", "created_at INTEGER NOT NULL DEFAULT 0"]
],
acpReplay: [["acp_replay_events", "estimated_bytes INTEGER NOT NULL DEFAULT 0"], ["acp_replay_sessions", "estimated_bytes INTEGER NOT NULL DEFAULT 0"]],
cronJobs: [
["cron_jobs", "description TEXT"],
["cron_jobs", "declaration_key TEXT"],
["cron_jobs", "owner_agent_id TEXT"],
["cron_jobs", "name TEXT NOT NULL DEFAULT ''"],
["cron_jobs", "enabled INTEGER NOT NULL DEFAULT 1"],
["cron_jobs", "agent_id TEXT"],
["cron_jobs", "payload_kind TEXT NOT NULL DEFAULT 'message'"],
["cron_jobs", "state_json TEXT NOT NULL DEFAULT '{}'"],
["cron_jobs", "runtime_updated_at_ms INTEGER"],
["cron_jobs", "schedule_identity TEXT"],
["cron_jobs", "sort_order INTEGER NOT NULL DEFAULT 0"]
],
deliveryQueue: [
["sandbox_registry_entries", "session_key TEXT"],
["sandbox_registry_entries", "backend_id TEXT"],
["sandbox_registry_entries", "runtime_label TEXT"],
["sandbox_registry_entries", "image TEXT"],
["sandbox_registry_entries", "created_at_ms INTEGER"],
["sandbox_registry_entries", "last_used_at_ms INTEGER"],
["sandbox_registry_entries", "config_label_kind TEXT"],
["sandbox_registry_entries", "config_hash TEXT"],
["sandbox_registry_entries", "cdp_port INTEGER"],
["sandbox_registry_entries", "no_vnc_port INTEGER"],
["delivery_queue_entries", "entry_kind TEXT"],
["delivery_queue_entries", "session_key TEXT"],
["delivery_queue_entries", "channel TEXT"],
["delivery_queue_entries", "target TEXT"],
["delivery_queue_entries", "account_id TEXT"],
["delivery_queue_entries", "retry_count INTEGER NOT NULL DEFAULT 0"],
["delivery_queue_entries", "last_attempt_at INTEGER"],
["delivery_queue_entries", "last_error TEXT"],
["delivery_queue_entries", "recovery_state TEXT"],
["delivery_queue_entries", "platform_send_started_at INTEGER"]
],
originalMediaRoot: [["managed_outgoing_image_records", "original_media_root TEXT NOT NULL DEFAULT ''"]],
beforeTaskAttribution: [
["managed_outgoing_image_records", "agent_id TEXT"],
["managed_outgoing_image_records", "cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))"],
["current_conversation_bindings", "conversation_kind TEXT NOT NULL DEFAULT 'channel'"],
["device_bootstrap_tokens", "pending_profile_json TEXT"],
["gateway_restart_handoff", "restart_trace_started_at INTEGER"],
["gateway_restart_handoff", "restart_trace_last_at INTEGER"],
["gateway_restart_intent", "reason TEXT"],
["gateway_restart_sentinel", "delivery_channel TEXT"],
["gateway_restart_sentinel", "delivery_to TEXT"],
["gateway_restart_sentinel", "delivery_account_id TEXT"],
["gateway_restart_sentinel", "message TEXT"],
["gateway_restart_sentinel", "continuation_json TEXT"],
["gateway_restart_sentinel", "doctor_hint TEXT"],
["gateway_restart_sentinel", "stats_json TEXT"],
["gateway_boot_lifecycle", "startup_reason TEXT"],
["official_external_plugin_catalog_snapshots", "trust_mode TEXT"],
["official_external_plugin_catalog_snapshots", "trust_key_id TEXT"],
["official_external_plugin_catalog_snapshots", "trust_signature_count INTEGER"],
["official_external_plugin_catalog_snapshots", "trust_threshold INTEGER"],
["official_external_plugin_catalog_snapshots", "trust_verified_at TEXT"]
],
taskRequester: [["task_runs", "requester_agent_id TEXT"]],
taskRunDetails: [
["task_runs", "tool_use_count INTEGER"],
["task_runs", "last_tool_name TEXT"],
["task_runs", "detail_json TEXT"]
],
workerEnvironments: [
["worker_environments", "bootstrap_bundle_hash TEXT"],
["worker_environments", "bootstrap_openclaw_version TEXT"],
["worker_environments", "bootstrap_protocol_features_json TEXT"],
["worker_environments", "bootstrap_install_kind TEXT"],
["worker_environments", "owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0)"],
["worker_environments", "ssh_host_key TEXT"],
["worker_workspace_pending_results", "staged_result_ref TEXT"],
["worker_environments", "teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed'))"]
]
};
}));
//#endregion
//#region src/cron/definition-hash.ts
var init_definition_hash = __esmMin((() => {
init_src$2();
init_crypto_digest();
}));
//#endregion
//#region src/infra/delivery-queue-sqlite-bound.ts
var init_delivery_queue_sqlite_bound = __esmMin((() => {
init_kysely_sync();
init_sqlite_number();
}));
//#endregion
//#region src/infra/delivery-queue-sqlite.types.ts
var init_delivery_queue_sqlite_types = __esmMin((() => {
init_number_coercion();
}));
//#endregion
//#region src/state/openclaw-state-db-delivery-queue-backfill.ts
var init_openclaw_state_db_delivery_queue_backfill = __esmMin((() => {
init_src$2();
init_delivery_queue_sqlite_bound();
init_delivery_queue_sqlite_types();
}));
//#endregion
//#region src/state/openclaw-state-schema.ts
var OPENCLAW_STATE_SCHEMA_SQL;
var init_openclaw_state_schema = __esmMin((() => {
OPENCLAW_STATE_SCHEMA_SQL = "\n\nCREATE TABLE IF NOT EXISTS mcp_oauth_stores (\n store_key TEXT NOT NULL PRIMARY KEY,\n format_version INTEGER NOT NULL CHECK (format_version = 1),\n store_json TEXT NOT NULL,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS mcp_oauth_pending_authorizations (\n state TEXT NOT NULL PRIMARY KEY,\n store_key TEXT NOT NULL,\n create_time INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS diagnostic_events (\n scope TEXT NOT NULL,\n event_key TEXT NOT NULL,\n payload_json TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n sequence INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (scope, event_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_diagnostic_events_scope_sequence\n ON diagnostic_events(scope, sequence, event_key);\n\nCREATE TABLE IF NOT EXISTS skill_usage (\n skill_file TEXT NOT NULL PRIMARY KEY,\n skill_key TEXT NOT NULL,\n skill_name TEXT NOT NULL,\n skill_source TEXT NOT NULL,\n first_used_at_ms INTEGER NOT NULL,\n last_used_at_ms INTEGER NOT NULL,\n use_count INTEGER NOT NULL,\n last_agent_id TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_skill_usage_key\n ON skill_usage(skill_key, skill_file);\n\n-- Profile-owned skill library: additive, absent until first publication/import.\nCREATE TABLE IF NOT EXISTS skill_library_entries (\n skill_id TEXT NOT NULL PRIMARY KEY,\n owner_profile_id TEXT,\n author_profile_id TEXT NOT NULL,\n slug TEXT NOT NULL,\n current_revision TEXT NOT NULL,\n shared INT NOT NULL,\n enabled INT NOT NULL,\n removed INT NOT NULL,\n created_at INT NOT NULL,\n updated_at INT NOT NULL\n) STRICT;\nCREATE TABLE IF NOT EXISTS skill_library_revisions (\n skill_id TEXT NOT NULL,\n revision TEXT NOT NULL,\n description TEXT NOT NULL,\n files_json TEXT NOT NULL,\n created_at INT NOT NULL,\n PRIMARY KEY (skill_id, revision)\n) STRICT;\nCREATE TABLE IF NOT EXISTS skill_library_events (\n event_id TEXT NOT NULL PRIMARY KEY,\n skill_id TEXT NOT NULL,\n revision TEXT NOT NULL,\n action TEXT NOT NULL,\n actor_profile_id TEXT NOT NULL,\n created_at INT NOT NULL\n) STRICT;\nCREATE TABLE IF NOT EXISTS skill_library_uploads (\n upload_id TEXT NOT NULL PRIMARY KEY,\n owner_profile_id TEXT NOT NULL,\n slug TEXT NOT NULL,\n size_bytes INT NOT NULL,\n sha256 TEXT NOT NULL,\n archive_blob BLOB NOT NULL,\n expires_at INT NOT NULL,\n published_skill_id TEXT\n) STRICT;\n-- End profile-owned skill library.\n\nCREATE TABLE IF NOT EXISTS skill_workshop_proposals (\n proposal_id TEXT NOT NULL PRIMARY KEY,\n record_json TEXT NOT NULL,\n owner_agent_id TEXT,\n kind TEXT NOT NULL CHECK (kind IN ('create', 'update')),\n status TEXT NOT NULL CHECK (status IN ('pending', 'applied', 'rejected', 'quarantined', 'stale')),\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n draft_hash TEXT NOT NULL,\n origin_agent_id TEXT,\n origin_session_key TEXT,\n origin_run_id TEXT,\n origin_message_id TEXT,\n applied_at TEXT,\n rejected_at TEXT,\n quarantined_at TEXT,\n stale_at TEXT,\n status_reason TEXT\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS skill_workshop_collection_reviews (\n review_id TEXT NOT NULL PRIMARY KEY,\n owner_agent_id TEXT NOT NULL,\n backup_id TEXT NOT NULL,\n create_time INTEGER NOT NULL,\n kept_names_json TEXT NOT NULL,\n written_names_json TEXT NOT NULL,\n dropped_json TEXT NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_skill_workshop_collection_reviews_owner_time\n ON skill_workshop_collection_reviews(owner_agent_id, create_time DESC, review_id);\n\nCREATE TABLE IF NOT EXISTS skill_workshop_proposal_rollbacks (\n proposal_id TEXT NOT NULL PRIMARY KEY,\n written_at TEXT NOT NULL,\n target_skill_file TEXT NOT NULL,\n action TEXT NOT NULL CHECK (action IN ('create', 'update')),\n previous_content_hash TEXT,\n previous_content TEXT,\n support_files_json TEXT,\n FOREIGN KEY (proposal_id) REFERENCES skill_workshop_proposals(proposal_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS skill_workshop_proposal_events (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n event_id TEXT NOT NULL UNIQUE,\n proposal_id TEXT NOT NULL,\n proposed_version TEXT NOT NULL,\n revision_hash TEXT NOT NULL,\n event_type TEXT NOT NULL CHECK (event_type IN (\n 'created',\n 'revised',\n 'evaluation_completed',\n 'applied',\n 'rejected',\n 'quarantined',\n 'stale'\n )),\n occurred_at TEXT NOT NULL,\n actor_json TEXT NOT NULL,\n correlation_id TEXT,\n payload_json TEXT,\n FOREIGN KEY (proposal_id) REFERENCES skill_workshop_proposals(proposal_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS audit_events (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n event_id TEXT NOT NULL UNIQUE,\n source_id TEXT NOT NULL UNIQUE,\n schema_version INTEGER NOT NULL DEFAULT 1,\n source_sequence INTEGER NOT NULL,\n occurred_at INTEGER NOT NULL,\n kind TEXT NOT NULL,\n action TEXT NOT NULL,\n status TEXT NOT NULL,\n error_code TEXT,\n actor_type TEXT NOT NULL,\n actor_id TEXT NOT NULL,\n agent_id TEXT,\n session_key TEXT,\n session_id TEXT,\n run_id TEXT,\n tool_call_id TEXT,\n tool_name TEXT,\n direction TEXT,\n channel TEXT,\n conversation_kind TEXT,\n message_outcome TEXT,\n reason_code TEXT,\n delivery_kind TEXT,\n failure_stage TEXT,\n duration_ms INTEGER,\n result_count INTEGER,\n account_ref TEXT,\n conversation_ref TEXT,\n message_ref TEXT,\n target_ref TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_time\n ON audit_events(occurred_at DESC, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_agent_sequence\n ON audit_events(agent_id, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_session_sequence\n ON audit_events(session_key, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_run_sequence\n ON audit_events(run_id, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_kind_sequence\n ON audit_events(kind, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_status_sequence\n ON audit_events(status, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_channel_sequence\n ON audit_events(channel, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_audit_events_direction_sequence\n ON audit_events(direction, sequence DESC);\n\nCREATE TABLE IF NOT EXISTS outbound_message_execution_bindings (\n event_id TEXT NOT NULL PRIMARY KEY,\n context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),\n execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),\n run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),\n FOREIGN KEY (event_id) REFERENCES audit_events(event_id) ON DELETE CASCADE\n) STRICT;\nCREATE INDEX IF NOT EXISTS outbound_message_execution_bindings_execution_event_idx\n ON outbound_message_execution_bindings (context_id, execution_id, run_id, event_id);\n\nCREATE TABLE IF NOT EXISTS outbound_message_progress (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n progress_id TEXT NOT NULL UNIQUE CHECK (length(progress_id) BETWEEN 1 AND 256),\n source_id TEXT NOT NULL UNIQUE CHECK (length(source_id) BETWEEN 1 AND 512),\n source_sequence INTEGER NOT NULL CHECK (source_sequence >= 1),\n schema_version INTEGER NOT NULL CHECK (schema_version = 1),\n occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),\n action TEXT NOT NULL CHECK (\n action IN ('message.outbound.queued', 'message.outbound.platform-started')\n ),\n outcome TEXT NOT NULL CHECK (outcome IN ('queued', 'platform_started')),\n actor_type TEXT NOT NULL CHECK (actor_type IN ('agent', 'system')),\n actor_id TEXT NOT NULL CHECK (length(actor_id) BETWEEN 1 AND 256),\n agent_id TEXT CHECK (agent_id IS NULL OR length(agent_id) BETWEEN 1 AND 256),\n run_id TEXT CHECK (run_id IS NULL OR length(run_id) BETWEEN 1 AND 256),\n context_id TEXT,\n execution_id TEXT,\n channel TEXT NOT NULL CHECK (length(channel) BETWEEN 1 AND 256),\n conversation_kind TEXT NOT NULL CHECK (\n conversation_kind IN ('direct', 'group', 'channel', 'unknown')\n ),\n duration_ms INTEGER CHECK (duration_ms IS NULL OR duration_ms >= 0),\n account_ref TEXT,\n conversation_ref TEXT,\n target_ref TEXT,\n UNIQUE (occurred_at, progress_id)\n) STRICT;\nCREATE INDEX IF NOT EXISTS outbound_message_progress_occurred_idx\n ON outbound_message_progress (occurred_at, sequence);\nCREATE INDEX IF NOT EXISTS outbound_message_progress_run_occurred_idx\n ON outbound_message_progress (run_id, occurred_at, sequence);\n\nCREATE TABLE IF NOT EXISTS audit_identity_keys (\n id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),\n key_id TEXT NOT NULL,\n key BLOB NOT NULL,\n created_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS config_revision_keys (\n id INTEGER NOT NULL PRIMARY KEY CHECK (id = 1),\n hmac_key BLOB NOT NULL CHECK (length(hmac_key) = 32)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS execution_identity_contexts (\n context_id TEXT NOT NULL PRIMARY KEY CHECK (length(context_id) BETWEEN 1 AND 256),\n execution_id TEXT NOT NULL UNIQUE CHECK (length(execution_id) BETWEEN 1 AND 256),\n run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),\n created_at INTEGER NOT NULL CHECK (created_at >= 0),\n coverage_state TEXT NOT NULL CHECK (\n coverage_state IN ('attribution-only', 'unattributed', 'unknown', 'unsupported')\n ),\n context_bytes INTEGER NOT NULL CHECK (context_bytes BETWEEN 1 AND 16384),\n context_json TEXT NOT NULL CHECK (length(context_json) > 0),\n UNIQUE (created_at, context_id)\n) STRICT;\nCREATE INDEX IF NOT EXISTS execution_identity_contexts_run_created_idx\n ON execution_identity_contexts (run_id, created_at, execution_id);\n\nCREATE TABLE IF NOT EXISTS execution_decision_facts (\n receipt_id TEXT NOT NULL PRIMARY KEY CHECK (length(receipt_id) BETWEEN 1 AND 256),\n context_id TEXT NOT NULL CHECK (length(context_id) BETWEEN 1 AND 256),\n execution_id TEXT NOT NULL CHECK (length(execution_id) BETWEEN 1 AND 256),\n run_id TEXT NOT NULL CHECK (length(run_id) BETWEEN 1 AND 256),\n action_id TEXT CHECK (action_id IS NULL OR length(action_id) BETWEEN 1 AND 256),\n action_family TEXT NOT NULL CHECK (length(action_family) BETWEEN 1 AND 256),\n decision_outcome TEXT NOT NULL CHECK (\n decision_outcome IN ('allowed', 'denied', 'not-applicable', 'unknown')\n ),\n coverage_state TEXT NOT NULL CHECK (\n coverage_state IN ('enforced', 'attribution-only', 'unattributed', 'unknown', 'unsupported')\n ),\n reason_code TEXT NOT NULL CHECK (length(reason_code) BETWEEN 1 AND 256),\n owner TEXT NOT NULL CHECK (length(owner) BETWEEN 1 AND 256),\n source_ref TEXT NOT NULL CHECK (length(source_ref) BETWEEN 1 AND 256),\n occurred_at INTEGER NOT NULL CHECK (occurred_at >= 0),\n receipt_bytes INTEGER NOT NULL CHECK (receipt_bytes BETWEEN 1 AND 16384),\n receipt_json TEXT NOT NULL CHECK (length(receipt_json) > 0),\n UNIQUE (occurred_at, receipt_id)\n) STRICT;\nCREATE INDEX IF NOT EXISTS execution_decision_facts_context_occurred_idx\n ON execution_decision_facts (context_id, occurred_at, receipt_id);\nCREATE INDEX IF NOT EXISTS execution_decision_facts_run_occurred_idx\n ON execution_decision_facts (run_id, occurred_at, receipt_id);\n\n-- Exact admission identity stays separate from owner-native lifecycle rows so\n-- older readers retain byte-compatible cron/task/flow table definitions.\nCREATE TABLE IF NOT EXISTS execution_owner_lifecycle_bindings (\n owner_kind TEXT NOT NULL,\n owner_id TEXT NOT NULL,\n context_id TEXT NOT NULL,\n execution_id TEXT NOT NULL,\n PRIMARY KEY (owner_kind, owner_id)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS session_state_events (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n dedupe_key TEXT UNIQUE,\n session_key TEXT NOT NULL,\n session_id TEXT,\n agent_id TEXT NOT NULL,\n kind TEXT NOT NULL,\n actor_type TEXT NOT NULL,\n actor_id TEXT,\n run_id TEXT,\n occurred_at INTEGER NOT NULL,\n summary TEXT NOT NULL,\n payload_json TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_session_state_events_session_sequence\n ON session_state_events(session_key, sequence DESC);\n\nCREATE INDEX IF NOT EXISTS idx_session_state_events_time\n ON session_state_events(occurred_at DESC, sequence DESC);\n\nCREATE TABLE IF NOT EXISTS session_state_heads (\n session_key TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n last_sequence INTEGER NOT NULL,\n pruned_max_sequence INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (session_key, agent_id)\n) STRICT;\n\n-- Notifiable watcher identity is the bare session key, matching the process-local\n-- system-event queue it feeds. Provenance distinguishes explicit immediate-wake\n-- watches from ambient queue-only group watches. Other bare keys\n-- (session.scope=\"global\") are ambiguous across agents and excluded until watcher\n-- identity is agent-scoped end-to-end.\nCREATE TABLE IF NOT EXISTS session_watch_cursors (\n watcher_session_key TEXT NOT NULL,\n watcher_store_path TEXT,\n target_session_key TEXT NOT NULL,\n last_seen_sequence INTEGER NOT NULL DEFAULT 0,\n notified_sequence INTEGER NOT NULL DEFAULT 0,\n material_sequence INTEGER NOT NULL DEFAULT 0,\n provenance TEXT NOT NULL DEFAULT 'explicit' CHECK (provenance IN ('explicit', 'ambient-group')),\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (watcher_session_key, target_session_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_session_watch_cursors_target\n ON session_watch_cursors(target_session_key);\n\nCREATE TABLE IF NOT EXISTS session_upstream_links (\n session_key TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n catalog_id TEXT NOT NULL,\n host_id TEXT NOT NULL,\n thread_id TEXT NOT NULL,\n upstream_kind TEXT NOT NULL,\n upstream_ref_json TEXT,\n last_marker_json TEXT,\n last_scanned_at INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n -- (session_key, agent_id) composite identity: under session.scope=\"global\" agents\n -- share bare keys; a key-only row would let one agent overwrite another's upstream.\n PRIMARY KEY (session_key, agent_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_session_upstream_links_catalog_id\n ON session_upstream_links(catalog_id);\n\nCREATE TABLE IF NOT EXISTS state_leases (\n scope TEXT NOT NULL,\n lease_key TEXT NOT NULL,\n owner TEXT NOT NULL,\n expires_at INTEGER,\n heartbeat_at INTEGER,\n payload_json TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (scope, lease_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_state_leases_expiry\n ON state_leases(expires_at, scope, lease_key)\n WHERE expires_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_state_leases_owner\n ON state_leases(owner, updated_at DESC);\n\nCREATE TABLE IF NOT EXISTS exec_approvals_config (\n config_key TEXT NOT NULL PRIMARY KEY,\n raw_json TEXT NOT NULL,\n socket_path TEXT,\n has_socket_token INTEGER NOT NULL,\n default_security TEXT,\n default_ask TEXT,\n default_ask_fallback TEXT,\n auto_allow_skills INTEGER,\n agent_count INTEGER NOT NULL,\n allowlist_count INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS operator_approvals (\n approval_id TEXT NOT NULL PRIMARY KEY CHECK (\n length(approval_id) > 0 AND approval_id NOT IN ('.', '..')\n ),\n resolution_ref TEXT NOT NULL CHECK (\n length(resolution_ref) = 43 AND resolution_ref NOT GLOB '*[^A-Za-z0-9_-]*'\n ),\n kind TEXT NOT NULL CHECK (kind IN ('exec', 'plugin', 'system-agent')),\n status TEXT NOT NULL CHECK (status IN ('pending', 'allowed', 'denied', 'expired', 'cancelled')),\n presentation_json TEXT NOT NULL,\n requested_by_device_id TEXT,\n requested_by_client_id TEXT,\n requested_by_device_token_auth INTEGER NOT NULL DEFAULT 0,\n reviewer_device_ids_json TEXT NOT NULL,\n source_agent_id TEXT,\n source_session_key TEXT,\n source_session_id TEXT,\n source_run_id TEXT,\n source_tool_call_id TEXT,\n source_tool_name TEXT,\n audience_session_keys_json TEXT NOT NULL,\n runtime_epoch TEXT NOT NULL,\n created_at_ms INTEGER NOT NULL,\n expires_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n decision TEXT CHECK (decision IN ('allow-once', 'allow-always', 'deny')),\n terminal_reason TEXT CHECK (\n terminal_reason IN (\n 'user',\n 'timeout',\n 'malformed-verdict',\n 'no-route',\n 'run-aborted',\n 'gateway-restart',\n 'storage-corrupt'\n )\n ),\n resolved_at_ms INTEGER,\n resolver_kind TEXT CHECK (resolver_kind IN ('device', 'channel', 'runtime', 'system')),\n resolver_id TEXT,\n consumed_at_ms INTEGER,\n consumed_by TEXT,\n CHECK (expires_at_ms >= created_at_ms),\n CHECK (updated_at_ms >= created_at_ms),\n CHECK (resolved_at_ms IS NULL OR resolved_at_ms >= created_at_ms),\n CHECK (resolved_at_ms IS NULL OR resolved_at_ms <= updated_at_ms),\n CHECK (consumed_at_ms IS NULL OR consumed_at_ms >= resolved_at_ms),\n CHECK (consumed_at_ms IS NULL OR consumed_at_ms <= updated_at_ms),\n CHECK (requested_by_device_token_auth IN (0, 1)),\n CHECK (\n (\n status = 'pending'\n AND decision IS NULL\n AND terminal_reason IS NULL\n AND resolved_at_ms IS NULL\n AND resolver_kind IS NULL\n AND resolver_id IS NULL\n AND consumed_at_ms IS NULL\n AND consumed_by IS NULL\n )\n OR (\n status = 'allowed'\n AND decision IN ('allow-once', 'allow-always')\n AND terminal_reason = 'user'\n AND resolved_at_ms IS NOT NULL\n AND resolver_kind IS NOT NULL\n )\n OR (\n status = 'denied'\n AND decision = 'deny'\n AND terminal_reason IN ('user', 'malformed-verdict', 'no-route', 'storage-corrupt')\n AND resolved_at_ms IS NOT NULL\n AND resolver_kind IS NOT NULL\n AND consumed_at_ms IS NULL\n AND consumed_by IS NULL\n )\n OR (\n status = 'expired'\n AND decision = 'deny'\n AND terminal_reason = 'timeout'\n AND resolved_at_ms IS NOT NULL\n AND resolver_kind IS NOT NULL\n AND consumed_at_ms IS NULL\n AND consumed_by IS NULL\n )\n OR (\n status = 'cancelled'\n AND decision = 'deny'\n AND terminal_reason IN ('run-aborted', 'gateway-restart')\n AND resolved_at_ms IS NOT NULL\n AND resolver_kind IS NOT NULL\n AND consumed_at_ms IS NULL\n AND consumed_by IS NULL\n )\n ),\n CHECK (\n (consumed_at_ms IS NULL AND consumed_by IS NULL)\n OR (\n status = 'allowed'\n AND decision = 'allow-once'\n AND consumed_at_ms IS NOT NULL\n AND consumed_by IS NOT NULL\n )\n )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_status_expiry\n ON operator_approvals(status, expires_at_ms, approval_id);\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_operator_approvals_resolution_ref\n ON operator_approvals(resolution_ref);\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_source_session_created\n ON operator_approvals(source_session_key, created_at_ms DESC, approval_id);\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_source_run_resolved\n ON operator_approvals(source_run_id, resolved_at_ms, approval_id)\n WHERE source_run_id IS NOT NULL AND resolved_at_ms IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_resolved\n ON operator_approvals(resolved_at_ms, approval_id)\n WHERE resolved_at_ms IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_operator_approvals_runtime_pending\n ON operator_approvals(runtime_epoch, approval_id)\n WHERE status = 'pending';\n\nCREATE TABLE IF NOT EXISTS operator_approval_execution_identities (\n approval_id TEXT NOT NULL PRIMARY KEY\n REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,\n source_context_id TEXT NOT NULL CHECK (\n length(source_context_id) BETWEEN 1 AND 256 AND source_context_id = trim(source_context_id)\n ),\n source_execution_id TEXT NOT NULL CHECK (\n length(source_execution_id) BETWEEN 1 AND 256 AND source_execution_id = trim(source_execution_id)\n )\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS operator_approval_standing_grants (\n grant_id TEXT NOT NULL PRIMARY KEY CHECK (length(grant_id) > 0),\n minted_by_approval_id TEXT NOT NULL\n REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,\n agent_id TEXT NOT NULL CHECK (length(agent_id) > 0),\n cron_job_id TEXT NOT NULL CHECK (length(cron_job_id) > 0),\n job_config_revision TEXT NOT NULL CHECK (length(job_config_revision) > 0),\n operation_binding TEXT NOT NULL CHECK (length(operation_binding) > 0),\n created_at_ms INTEGER NOT NULL,\n expires_at_ms INTEGER CHECK (expires_at_ms IS NULL OR expires_at_ms >= created_at_ms),\n revoked_at_ms INTEGER,\n revoked_by TEXT,\n last_used_at_ms INTEGER,\n use_count INTEGER NOT NULL DEFAULT 0\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_operator_approval_standing_grants_binding\n ON operator_approval_standing_grants(agent_id, cron_job_id, operation_binding, created_at_ms DESC);\n\nCREATE TABLE IF NOT EXISTS operator_approval_standing_grant_generations (\n grant_id TEXT NOT NULL PRIMARY KEY\n REFERENCES operator_approval_standing_grants(grant_id) ON DELETE CASCADE,\n job_definition_generation INTEGER NOT NULL CHECK (job_definition_generation >= 1)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS schema_meta (\n meta_key TEXT NOT NULL PRIMARY KEY,\n role TEXT NOT NULL,\n schema_version INTEGER NOT NULL,\n agent_id TEXT,\n app_version TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS config_machine_state (\n state_key TEXT NOT NULL PRIMARY KEY,\n value_json TEXT NOT NULL,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS device_pairing_pending (\n request_id TEXT NOT NULL PRIMARY KEY,\n device_id TEXT NOT NULL,\n public_key TEXT NOT NULL,\n display_name TEXT,\n platform TEXT,\n device_family TEXT,\n client_id TEXT,\n client_mode TEXT,\n browser_origin TEXT,\n role TEXT,\n roles_json TEXT,\n scopes_json TEXT,\n remote_ip TEXT,\n silent INTEGER,\n is_repair INTEGER,\n ts INTEGER NOT NULL,\n refreshed_at_ms INTEGER\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_device_pairing_pending_device\n ON device_pairing_pending(device_id, ts DESC);\n\nCREATE TABLE IF NOT EXISTS device_pairing_paired (\n device_id TEXT NOT NULL PRIMARY KEY,\n public_key TEXT NOT NULL,\n display_name TEXT,\n operator_label TEXT,\n platform TEXT,\n device_family TEXT,\n client_id TEXT,\n client_mode TEXT,\n browser_origin TEXT,\n role TEXT,\n roles_json TEXT,\n scopes_json TEXT,\n approved_scopes_json TEXT,\n remote_ip TEXT,\n tokens_json TEXT,\n approved_via TEXT,\n node_surface_json TEXT,\n pending_node_surface_json TEXT,\n created_at_ms INTEGER NOT NULL,\n approved_at_ms INTEGER NOT NULL,\n last_seen_at_ms INTEGER,\n last_seen_reason TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_device_pairing_paired_approved\n ON device_pairing_paired(approved_at_ms DESC, device_id);\n\nCREATE TABLE IF NOT EXISTS device_bootstrap_tokens (\n token_key TEXT NOT NULL PRIMARY KEY,\n token TEXT NOT NULL,\n setup_id TEXT,\n ts INTEGER NOT NULL,\n device_id TEXT,\n public_key TEXT,\n profile_json TEXT,\n redeemed_profile_json TEXT,\n pending_profile_json TEXT,\n issued_at_ms INTEGER NOT NULL,\n last_used_at_ms INTEGER\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_device_bootstrap_tokens_ts\n ON device_bootstrap_tokens(ts);\n\n-- Terminal outcome of a redeemed setup credential. The bootstrap row is deleted\n-- on redemption, so this is the only durable proof a setup code succeeded; the\n-- presenting client reconciles it when the completion broadcast is missed.\n-- Non-secret only: never the bootstrap token or anything derived from it.\n-- Bounded by retention to a handful of live rows, so the primary key is the\n-- only access path worth having.\nCREATE TABLE IF NOT EXISTS device_pair_setup_completions (\n setup_id TEXT NOT NULL PRIMARY KEY,\n device_id TEXT NOT NULL,\n device_name TEXT,\n access TEXT NOT NULL,\n completed_at_ms INTEGER NOT NULL,\n delivery_state TEXT NOT NULL CHECK (delivery_state IN ('uncertain', 'confirmed')),\n retain_until_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS device_pairing_join_codes (\n shortcode TEXT,\n payload_json TEXT,\n created_at_ms INTEGER,\n expires_at_ms INTEGER\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS device_identities (\n identity_key TEXT NOT NULL PRIMARY KEY,\n device_id TEXT NOT NULL,\n public_key_pem TEXT NOT NULL,\n private_key_pem TEXT NOT NULL,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_device_identities_device\n ON device_identities(device_id, updated_at_ms DESC);\n\nCREATE TABLE IF NOT EXISTS device_auth_tokens (\n device_id TEXT NOT NULL,\n role TEXT NOT NULL,\n token TEXT NOT NULL,\n scopes_json TEXT NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY (device_id, role)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_device_auth_tokens_updated\n ON device_auth_tokens(updated_at_ms DESC, device_id, role);\n\nCREATE TABLE IF NOT EXISTS gateway_origin_device_tokens (\n gateway_scope TEXT NOT NULL,\n device_id TEXT NOT NULL,\n role TEXT NOT NULL,\n token TEXT NOT NULL,\n scopes_json TEXT NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY (gateway_scope, device_id, role)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS macos_port_guardian_records (\n pid INTEGER NOT NULL PRIMARY KEY,\n port INTEGER NOT NULL,\n command TEXT NOT NULL,\n mode TEXT NOT NULL,\n timestamp REAL NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_macos_port_guardian_records_port\n ON macos_port_guardian_records(port, timestamp DESC);\n\nCREATE TABLE IF NOT EXISTS workspace_setup_state (\n workspace_key TEXT NOT NULL PRIMARY KEY,\n -- NULL only for attestation-only rows whose legacy source never recorded a\n -- path (orphan hashed-key attestations); setup rows always carry one.\n workspace_path TEXT,\n -- NULL setup columns mean an attestation-only row: replaceWorkspaceAttestation\n -- may record hashes before any setup milestone exists for the workspace.\n version INTEGER,\n bootstrap_seeded_at TEXT,\n setup_completed_at TEXT,\n updated_at INTEGER,\n attested_at_ms INTEGER,\n attestation_updated_at_ms INTEGER,\n CHECK (version IS NULL OR workspace_path IS NOT NULL)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_workspace_setup_state_path\n ON workspace_setup_state(workspace_path);\n\nCREATE TABLE IF NOT EXISTS workspace_path_aliases (\n alias_key TEXT NOT NULL PRIMARY KEY,\n alias_path TEXT NOT NULL,\n workspace_key TEXT NOT NULL,\n workspace_path TEXT NOT NULL,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_workspace_path_aliases_workspace\n ON workspace_path_aliases(workspace_key);\n\n\n\nCREATE TABLE IF NOT EXISTS workspace_generated_bootstrap_hashes (\n workspace_key TEXT NOT NULL,\n filename TEXT NOT NULL,\n sha256 TEXT NOT NULL,\n PRIMARY KEY (workspace_key, filename),\n FOREIGN KEY (workspace_key) REFERENCES workspace_setup_state(workspace_key) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS native_hook_relay_bridges (\n relay_id TEXT NOT NULL PRIMARY KEY,\n pid INTEGER NOT NULL,\n hostname TEXT NOT NULL,\n port INTEGER NOT NULL,\n token TEXT NOT NULL,\n expires_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_native_hook_relay_bridges_expires\n ON native_hook_relay_bridges(expires_at_ms, relay_id);\n\nCREATE TABLE IF NOT EXISTS managed_outgoing_image_records (\n attachment_id TEXT NOT NULL PRIMARY KEY,\n session_key TEXT NOT NULL,\n agent_id TEXT,\n message_id TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT,\n retention_class TEXT,\n alt TEXT NOT NULL,\n original_media_root TEXT NOT NULL,\n original_media_id TEXT NOT NULL,\n original_media_subdir TEXT NOT NULL,\n original_content_type TEXT NOT NULL,\n original_width INTEGER,\n original_height INTEGER,\n original_size_bytes INTEGER,\n original_filename TEXT,\n record_json TEXT NOT NULL,\n cleanup_pending INTEGER NOT NULL DEFAULT 0 CHECK (cleanup_pending IN (0, 1))\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_session\n ON managed_outgoing_image_records(session_key, created_at DESC, attachment_id);\n\nCREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_message\n ON managed_outgoing_image_records(session_key, message_id, attachment_id)\n WHERE message_id IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_session\n ON managed_outgoing_image_records(session_key, agent_id, created_at DESC, attachment_id);\n\nCREATE INDEX IF NOT EXISTS idx_managed_outgoing_images_agent_message\n ON managed_outgoing_image_records(session_key, agent_id, message_id, attachment_id)\n WHERE message_id IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS channel_pairing_requests (\n channel_key TEXT NOT NULL,\n account_id TEXT NOT NULL,\n request_id TEXT NOT NULL,\n code TEXT NOT NULL,\n created_at TEXT NOT NULL,\n last_seen_at TEXT NOT NULL,\n meta_json TEXT,\n PRIMARY KEY (channel_key, account_id, request_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_code\n ON channel_pairing_requests(channel_key, code);\n\nCREATE INDEX IF NOT EXISTS idx_channel_pairing_requests_created\n ON channel_pairing_requests(channel_key, created_at, request_id);\n\nCREATE TABLE IF NOT EXISTS channel_pairing_allow_entries (\n channel_key TEXT NOT NULL,\n account_id TEXT NOT NULL,\n entry TEXT NOT NULL,\n sort_order INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (channel_key, account_id, entry)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_channel_pairing_allow_account\n ON channel_pairing_allow_entries(channel_key, account_id, sort_order, entry);\n\nCREATE TABLE IF NOT EXISTS web_push_subscriptions (\n endpoint_hash TEXT NOT NULL PRIMARY KEY,\n subscription_id TEXT NOT NULL UNIQUE,\n endpoint TEXT NOT NULL,\n p256dh TEXT NOT NULL,\n auth TEXT NOT NULL,\n device_id TEXT,\n user_profile_id TEXT,\n preferences_json TEXT,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_web_push_subscriptions_updated\n ON web_push_subscriptions(updated_at_ms DESC, subscription_id);\n\nCREATE TABLE IF NOT EXISTS web_push_approval_deliveries (\n approval_id TEXT NOT NULL\n REFERENCES operator_approvals(approval_id) ON DELETE CASCADE,\n subscription_id TEXT NOT NULL\n REFERENCES web_push_subscriptions(subscription_id) ON DELETE CASCADE,\n device_id TEXT NOT NULL,\n user_profile_id TEXT,\n prepared_at_ms INTEGER NOT NULL,\n PRIMARY KEY (approval_id, subscription_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_web_push_approval_deliveries_subscription\n ON web_push_approval_deliveries(subscription_id, approval_id);\n\nCREATE TABLE IF NOT EXISTS apns_registrations (\n node_id TEXT NOT NULL PRIMARY KEY,\n transport TEXT NOT NULL,\n token TEXT,\n relay_handle TEXT,\n send_grant TEXT,\n installation_id TEXT,\n relay_origin TEXT,\n topic TEXT NOT NULL,\n environment TEXT NOT NULL,\n distribution TEXT,\n token_debug_suffix TEXT,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_apns_registrations_updated\n ON apns_registrations(updated_at_ms DESC, node_id);\n\nCREATE TABLE IF NOT EXISTS apns_registration_tombstones (\n node_id TEXT NOT NULL PRIMARY KEY,\n deleted_at_ms INTEGER NOT NULL\n) STRICT;\n\n-- Node-host-owned launch journal. The descriptor and its credential remain\n-- process memory only; this table records bounded supervision facts.\nCREATE TABLE IF NOT EXISTS node_worker_launches (\n launch_id TEXT NOT NULL PRIMARY KEY\n CHECK (length(launch_id) BETWEEN 1 AND 256 AND instr(launch_id, char(0)) = 0),\n plan_hash TEXT NOT NULL\n CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),\n gateway_namespace TEXT NOT NULL\n CHECK (\n length(gateway_namespace) BETWEEN 1 AND 128\n AND gateway_namespace NOT GLOB '*[^A-Za-z0-9._-]*'\n AND gateway_namespace GLOB '[A-Za-z0-9]*'\n ),\n environment_id TEXT NOT NULL\n CHECK (length(environment_id) BETWEEN 1 AND 256 AND instr(environment_id, char(0)) = 0),\n session_id TEXT NOT NULL\n CHECK (length(session_id) BETWEEN 1 AND 256 AND instr(session_id, char(0)) = 0),\n owner_epoch INTEGER NOT NULL CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),\n placement_generation INTEGER NOT NULL\n CHECK (placement_generation BETWEEN 0 AND 9007199254740991),\n run_id TEXT NOT NULL\n CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),\n state TEXT NOT NULL\n CHECK (state IN ('pending', 'running', 'completed', 'failed', 'interrupted', 'cancelled')),\n supervisor_pid INTEGER NOT NULL CHECK (supervisor_pid BETWEEN 1 AND 2147483647),\n supervisor_start_time INTEGER NOT NULL\n CHECK (supervisor_start_time BETWEEN 0 AND 9007199254740991),\n worker_pid INTEGER CHECK (worker_pid IS NULL OR worker_pid BETWEEN 1 AND 2147483647),\n worker_start_time INTEGER CHECK (\n worker_start_time IS NULL OR worker_start_time BETWEEN 0 AND 9007199254740991\n ),\n result_json TEXT CHECK (\n result_json IS NULL\n OR (\n length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536\n AND instr(result_json, char(0)) = 0\n AND json_valid(result_json)\n )\n ),\n error_text TEXT CHECK (\n error_text IS NULL\n OR (\n length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096\n AND instr(error_text, char(0)) = 0\n AND instr(error_text, char(10)) = 0\n AND instr(error_text, char(13)) = 0\n )\n ),\n completed_at_ms INTEGER CHECK (\n completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991\n ),\n created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),\n updated_at_ms INTEGER NOT NULL CHECK (\n updated_at_ms BETWEEN created_at_ms AND 9007199254740991\n ),\n CHECK ((worker_pid IS NULL) = (worker_start_time IS NULL)),\n CHECK (\n (state = 'pending'\n AND worker_pid IS NULL AND result_json IS NULL AND error_text IS NULL\n AND completed_at_ms IS NULL)\n OR\n (state = 'running'\n AND worker_pid IS NOT NULL AND result_json IS NULL AND error_text IS NULL\n AND completed_at_ms IS NULL)\n OR\n (state = 'completed'\n AND result_json IS NOT NULL AND error_text IS NULL\n AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)\n OR\n (state IN ('failed', 'interrupted', 'cancelled')\n AND result_json IS NULL AND error_text IS NOT NULL\n AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)\n )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_node_worker_launches_terminal_completed\n ON node_worker_launches(completed_at_ms, launch_id)\n WHERE completed_at_ms IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS node_worker_launch_containers (\n launch_id TEXT PRIMARY KEY,\n container_json TEXT\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS node_worker_launch_cleanup (\n launch_id TEXT NOT NULL PRIMARY KEY\n REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,\n cleanup_mode TEXT NOT NULL CHECK (cleanup_mode IN ('process-group', 'owned-anchor')),\n lineage_settled INTEGER CHECK (lineage_settled IS NULL OR lineage_settled = 1)\n) STRICT;\n\n-- Turn receipts have a shorter lifetime than their physical worker owner.\n-- Keeping the launch running preserves capacity and predecessor cleanup semantics.\nCREATE TABLE IF NOT EXISTS node_worker_turns (\n turn_id TEXT NOT NULL PRIMARY KEY\n CHECK (length(turn_id) BETWEEN 1 AND 256 AND instr(turn_id, char(0)) = 0),\n owner_launch_id TEXT NOT NULL\n REFERENCES node_worker_launches(launch_id) ON DELETE CASCADE,\n plan_hash TEXT NOT NULL\n CHECK (length(plan_hash) = 64 AND plan_hash NOT GLOB '*[^0-9a-f]*'),\n run_id TEXT NOT NULL\n CHECK (length(run_id) BETWEEN 1 AND 256 AND instr(run_id, char(0)) = 0),\n state TEXT NOT NULL\n CHECK (state IN ('running', 'completed', 'failed', 'interrupted', 'cancelled')),\n result_json TEXT CHECK (\n result_json IS NULL\n OR (\n length(CAST(result_json AS BLOB)) BETWEEN 1 AND 65536\n AND instr(result_json, char(0)) = 0\n AND json_valid(result_json)\n )\n ),\n error_text TEXT CHECK (\n error_text IS NULL\n OR (\n length(CAST(error_text AS BLOB)) BETWEEN 1 AND 4096\n AND instr(error_text, char(0)) = 0\n AND instr(error_text, char(10)) = 0\n AND instr(error_text, char(13)) = 0\n )\n ),\n completed_at_ms INTEGER CHECK (\n completed_at_ms IS NULL OR completed_at_ms BETWEEN 0 AND 9007199254740991\n ),\n created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),\n updated_at_ms INTEGER NOT NULL CHECK (\n updated_at_ms BETWEEN created_at_ms AND 9007199254740991\n ),\n CHECK (\n (state = 'running'\n AND result_json IS NULL AND error_text IS NULL AND completed_at_ms IS NULL)\n OR\n (state = 'completed'\n AND result_json IS NOT NULL AND error_text IS NULL\n AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)\n OR\n (state IN ('failed', 'interrupted', 'cancelled')\n AND result_json IS NULL AND error_text IS NOT NULL\n AND completed_at_ms BETWEEN created_at_ms AND updated_at_ms)\n )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_node_worker_turns_terminal_completed\n ON node_worker_turns(completed_at_ms, turn_id)\n WHERE completed_at_ms IS NOT NULL;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_node_worker_turns_active_owner\n ON node_worker_turns(owner_launch_id)\n WHERE state = 'running';\n\nCREATE TABLE IF NOT EXISTS config_health_entries (\n config_path TEXT NOT NULL PRIMARY KEY,\n last_known_good_json TEXT,\n last_promoted_good_json TEXT,\n last_observed_suspicious_signature TEXT,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS clawhub_promotion_claims (\n slug TEXT NOT NULL PRIMARY KEY,\n provider TEXT,\n model_keys_json TEXT NOT NULL,\n ends_at_ms INTEGER NOT NULL,\n claimed_at_ms INTEGER NOT NULL\n) STRICT;\n\n\n\nCREATE TABLE IF NOT EXISTS official_external_plugin_catalog_snapshots (\n feed_url TEXT NOT NULL PRIMARY KEY,\n body TEXT NOT NULL,\n status INTEGER NOT NULL,\n etag TEXT,\n last_modified TEXT,\n checksum TEXT NOT NULL,\n saved_at TEXT NOT NULL,\n trust_mode TEXT,\n trust_key_id TEXT,\n trust_signature_count INTEGER,\n trust_threshold INTEGER,\n trust_verified_at TEXT,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_official_external_plugin_catalog_snapshots_updated\n ON official_external_plugin_catalog_snapshots(updated_at_ms DESC, feed_url);\n\nCREATE TABLE IF NOT EXISTS update_runs (\n run_id TEXT PRIMARY KEY NOT NULL,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n trigger TEXT NOT NULL CHECK (trigger IN ('chat', 'control-ui', 'cli', 'campaign', 'mac-app', 'api')),\n phase TEXT NOT NULL CHECK (phase IN ('requested', 'staging', 'validating', 'repairing', 'activating', 'restarting', 'verifying', 'finished')),\n status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'rolled-back', 'skipped')),\n reason TEXT,\n origin_json TEXT NOT NULL CHECK (length(CAST(origin_json AS BLOB)) <= 16384),\n target_json TEXT NOT NULL CHECK (length(CAST(target_json AS BLOB)) <= 16384),\n before_json TEXT NOT NULL CHECK (length(CAST(before_json AS BLOB)) <= 16384),\n after_json TEXT NOT NULL CHECK (length(CAST(after_json AS BLOB)) <= 16384),\n steps_json TEXT NOT NULL CHECK (length(CAST(steps_json AS BLOB)) <= 16384),\n verification_json TEXT NOT NULL CHECK (length(CAST(verification_json AS BLOB)) <= 16384),\n repair_json TEXT NOT NULL CHECK (length(CAST(repair_json AS BLOB)) <= 16384),\n confirmed_at_ms INTEGER,\n finished_at_ms INTEGER,\n downtime_ms INTEGER,\n CHECK ((status = 'running' AND phase != 'finished' AND finished_at_ms IS NULL) OR\n (status != 'running' AND phase = 'finished' AND finished_at_ms IS NOT NULL))\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_update_runs_created\n ON update_runs(created_at_ms DESC, run_id);\nCREATE INDEX IF NOT EXISTS idx_update_runs_active\n ON update_runs(status, created_at_ms DESC, run_id);\n\nCREATE TABLE IF NOT EXISTS gateway_restart_sentinel (\n sentinel_key TEXT NOT NULL PRIMARY KEY,\n version INTEGER NOT NULL,\n kind TEXT NOT NULL,\n status TEXT NOT NULL,\n ts INTEGER NOT NULL,\n session_key TEXT,\n thread_id TEXT,\n delivery_channel TEXT,\n delivery_to TEXT,\n delivery_account_id TEXT,\n message TEXT,\n continuation_json TEXT,\n doctor_hint TEXT,\n stats_json TEXT,\n payload_json TEXT NOT NULL,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_gateway_restart_sentinel_ts\n ON gateway_restart_sentinel(ts DESC, sentinel_key);\n\nCREATE TABLE IF NOT EXISTS gateway_restart_intent (\n intent_key TEXT NOT NULL PRIMARY KEY,\n kind TEXT NOT NULL,\n pid INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n reason TEXT,\n force INTEGER,\n wait_ms INTEGER,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS gateway_restart_handoff (\n handoff_key TEXT NOT NULL PRIMARY KEY,\n kind TEXT NOT NULL,\n version INTEGER NOT NULL,\n intent_id TEXT NOT NULL,\n pid INTEGER NOT NULL,\n process_instance_id TEXT,\n created_at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL,\n reason TEXT,\n restart_trace_started_at INTEGER,\n restart_trace_last_at INTEGER,\n source TEXT NOT NULL,\n restart_kind TEXT NOT NULL,\n supervisor_mode TEXT NOT NULL,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_gateway_restart_handoff_expiry\n ON gateway_restart_handoff(expires_at, pid);\n\nCREATE TABLE IF NOT EXISTS gateway_boot_lifecycle (\n boot_id TEXT NOT NULL PRIMARY KEY,\n pid INTEGER NOT NULL,\n started_at_ms INTEGER NOT NULL,\n completed_at_ms INTEGER,\n outcome TEXT,\n startup_reason TEXT,\n reason TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_gateway_boot_lifecycle_started\n ON gateway_boot_lifecycle(started_at_ms);\n\nCREATE TABLE IF NOT EXISTS acp_sessions (\n session_key TEXT NOT NULL PRIMARY KEY,\n session_id TEXT,\n backend TEXT NOT NULL,\n agent TEXT NOT NULL,\n runtime_session_name TEXT NOT NULL,\n identity_json TEXT,\n mode TEXT NOT NULL,\n runtime_options_json TEXT,\n cwd TEXT,\n state TEXT NOT NULL,\n last_activity_at INTEGER NOT NULL,\n last_error TEXT,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_acp_sessions_state_activity\n ON acp_sessions(state, last_activity_at DESC, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_acp_sessions_agent_activity\n ON acp_sessions(agent, last_activity_at DESC, session_key);\n\nCREATE TABLE IF NOT EXISTS acp_replay_sessions (\n session_id TEXT NOT NULL PRIMARY KEY,\n session_key TEXT NOT NULL,\n cwd TEXT NOT NULL,\n complete INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n next_seq INTEGER NOT NULL,\n -- Running estimate of this session's ledger footprint (row overhead plus\n -- all event rows), maintained at insert/trim so budget checks never scan\n -- acp_replay_events (#100622).\n estimated_bytes INTEGER NOT NULL DEFAULT 0\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_key_updated\n ON acp_replay_sessions(session_key, complete, updated_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_acp_replay_sessions_updated\n ON acp_replay_sessions(updated_at DESC, session_id);\n\nCREATE TABLE IF NOT EXISTS acp_replay_events (\n session_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n at INTEGER NOT NULL,\n session_key TEXT NOT NULL,\n run_id TEXT,\n update_json TEXT NOT NULL,\n estimated_bytes INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (session_id, seq),\n FOREIGN KEY (session_id) REFERENCES acp_replay_sessions(session_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_acp_replay_events_session_seq\n ON acp_replay_events(session_id, seq);\n\nCREATE TABLE IF NOT EXISTS agent_databases (\n agent_id TEXT NOT NULL,\n path TEXT NOT NULL,\n schema_version INTEGER NOT NULL,\n last_seen_at INTEGER NOT NULL,\n size_bytes INTEGER,\n PRIMARY KEY (agent_id, path)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS agent_deletion_journal (\n agent_id TEXT PRIMARY KEY,\n operation_id TEXT NOT NULL DEFAULT '',\n agent_dir TEXT NOT NULL,\n workspace_dir TEXT NOT NULL,\n sessions_dir TEXT NOT NULL,\n database_paths_json TEXT NOT NULL DEFAULT '[]',\n cleanup_paths_json TEXT NOT NULL DEFAULT '[]',\n created_at INTEGER NOT NULL,\n cleanup_completed INTEGER NOT NULL DEFAULT 0,\n delete_files INTEGER NOT NULL DEFAULT 1\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS agent_provenance (\n agent_id TEXT PRIMARY KEY,\n created_via TEXT NOT NULL CHECK (created_via IN ('operator', 'agent', 'claw')),\n creator_agent_id TEXT,\n created_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS agent_database_leases (\n lease_id TEXT PRIMARY KEY,\n agent_id TEXT NOT NULL,\n path TEXT NOT NULL,\n owner_pid INTEGER NOT NULL,\n owner_start_time INTEGER,\n opened_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS plugin_state_entries (\n plugin_id TEXT NOT NULL,\n namespace TEXT NOT NULL,\n entry_key TEXT NOT NULL,\n value_json TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n expires_at INTEGER,\n PRIMARY KEY (plugin_id, namespace, entry_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_state_expiry\n ON plugin_state_entries(expires_at)\n WHERE expires_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_state_listing\n ON plugin_state_entries(plugin_id, namespace, created_at, entry_key, expires_at);\n\nCREATE TABLE IF NOT EXISTS channel_ingress_events (\n queue_name TEXT NOT NULL,\n event_id TEXT NOT NULL,\n channel_id TEXT NOT NULL,\n account_id TEXT NOT NULL,\n status TEXT NOT NULL,\n lane_key TEXT,\n payload_json TEXT NOT NULL,\n metadata_json TEXT,\n received_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n claim_token TEXT,\n claim_owner TEXT,\n claimed_at INTEGER,\n attempts INTEGER NOT NULL DEFAULT 0,\n last_attempt_at INTEGER,\n last_error TEXT,\n failed_reason TEXT,\n failed_at INTEGER,\n completed_at INTEGER,\n completed_metadata_json TEXT,\n PRIMARY KEY (queue_name, event_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_channel_ingress_pending\n ON channel_ingress_events(queue_name, status, received_at, event_id);\n\nCREATE INDEX IF NOT EXISTS idx_channel_ingress_claims\n ON channel_ingress_events(queue_name, status, claimed_at);\n\nCREATE INDEX IF NOT EXISTS idx_channel_ingress_lane\n ON channel_ingress_events(queue_name, status, lane_key);\n\nCREATE TABLE IF NOT EXISTS plugin_blob_entries (\n plugin_id TEXT NOT NULL,\n namespace TEXT NOT NULL,\n entry_key TEXT NOT NULL,\n metadata_json TEXT NOT NULL,\n blob BLOB NOT NULL,\n created_at INTEGER NOT NULL,\n expires_at INTEGER,\n PRIMARY KEY (plugin_id, namespace, entry_key)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_blob_expiry\n ON plugin_blob_entries(expires_at)\n WHERE expires_at IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_blob_listing\n ON plugin_blob_entries(plugin_id, namespace, created_at, entry_key);\n\nCREATE TABLE IF NOT EXISTS skill_uploads (\n upload_id TEXT NOT NULL PRIMARY KEY,\n kind TEXT NOT NULL,\n slug TEXT NOT NULL,\n force INTEGER NOT NULL,\n size_bytes INTEGER NOT NULL,\n sha256 TEXT,\n actual_sha256 TEXT,\n received_bytes INTEGER NOT NULL,\n archive_blob BLOB NOT NULL,\n created_at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL,\n committed INTEGER NOT NULL,\n committed_at INTEGER,\n idempotency_key_hash TEXT UNIQUE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_skill_uploads_expiry\n ON skill_uploads(expires_at);\n\nCREATE INDEX IF NOT EXISTS idx_skill_uploads_idempotency\n ON skill_uploads(idempotency_key_hash)\n WHERE idempotency_key_hash IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS skill_upload_chunks (\n upload_id TEXT NOT NULL,\n byte_offset INTEGER NOT NULL CHECK (byte_offset >= 0),\n size_bytes INTEGER NOT NULL CHECK (size_bytes > 0),\n chunk_blob BLOB NOT NULL,\n PRIMARY KEY (upload_id, byte_offset),\n FOREIGN KEY (upload_id) REFERENCES skill_uploads(upload_id) ON DELETE CASCADE,\n CHECK (length(chunk_blob) = size_bytes)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS capture_sessions (\n id TEXT NOT NULL PRIMARY KEY,\n started_at INTEGER NOT NULL,\n ended_at INTEGER,\n mode TEXT NOT NULL,\n source_scope TEXT NOT NULL,\n source_process TEXT NOT NULL,\n proxy_url TEXT\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS capture_blobs (\n blob_id TEXT NOT NULL PRIMARY KEY,\n content_type TEXT,\n encoding TEXT NOT NULL,\n size_bytes INTEGER NOT NULL,\n sha256 TEXT NOT NULL,\n data BLOB NOT NULL,\n created_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS capture_events (\n id INTEGER NOT NULL PRIMARY KEY,\n session_id TEXT NOT NULL,\n ts INTEGER NOT NULL,\n source_scope TEXT NOT NULL,\n source_process TEXT NOT NULL,\n protocol TEXT NOT NULL,\n direction TEXT NOT NULL,\n kind TEXT NOT NULL,\n flow_id TEXT NOT NULL,\n method TEXT,\n host TEXT,\n path TEXT,\n status INTEGER,\n close_code INTEGER,\n content_type TEXT,\n headers_json TEXT,\n data_text TEXT,\n data_blob_id TEXT,\n data_sha256 TEXT,\n error_text TEXT,\n meta_json TEXT,\n FOREIGN KEY (session_id) REFERENCES capture_sessions(id) ON DELETE CASCADE,\n FOREIGN KEY (data_blob_id) REFERENCES capture_blobs(blob_id) ON DELETE SET NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS capture_events_session_ts_idx\n ON capture_events(session_id, ts);\n\nCREATE INDEX IF NOT EXISTS capture_events_flow_idx\n ON capture_events(flow_id, ts);\n\nCREATE TABLE IF NOT EXISTS sandbox_registry_entries (\n registry_kind TEXT NOT NULL,\n container_name TEXT NOT NULL,\n session_key TEXT,\n backend_id TEXT,\n runtime_label TEXT,\n image TEXT,\n created_at_ms INTEGER,\n last_used_at_ms INTEGER,\n config_label_kind TEXT,\n config_hash TEXT,\n cdp_port INTEGER,\n no_vnc_port INTEGER,\n entry_json TEXT NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (registry_kind, container_name)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_sandbox_registry_updated\n ON sandbox_registry_entries(registry_kind, updated_at DESC, container_name);\n\nCREATE INDEX IF NOT EXISTS idx_sandbox_registry_session\n ON sandbox_registry_entries(registry_kind, session_key, last_used_at_ms DESC, container_name)\n WHERE session_key IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_sandbox_registry_last_used\n ON sandbox_registry_entries(registry_kind, last_used_at_ms DESC, container_name)\n WHERE last_used_at_ms IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS cron_jobs (\n store_key TEXT NOT NULL,\n job_id TEXT NOT NULL,\n declaration_key TEXT,\n owner_agent_id TEXT,\n name TEXT NOT NULL,\n description TEXT,\n enabled INTEGER NOT NULL,\n agent_id TEXT,\n payload_kind TEXT NOT NULL,\n job_json TEXT NOT NULL,\n grant_definition_revision TEXT,\n grant_definition_generation INTEGER,\n grant_definition_updated_at INTEGER,\n state_json TEXT NOT NULL DEFAULT '{}',\n runtime_updated_at_ms INTEGER,\n schedule_identity TEXT,\n sort_order INTEGER NOT NULL DEFAULT 0,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (store_key, job_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_cron_jobs_store_order\n ON cron_jobs(store_key, sort_order ASC, updated_at ASC, job_id);\n\n-- One owner-native receipt is also the durable execution fence. Receipts\n-- survive job deletion so operators can distinguish a run from log inference.\nCREATE TABLE IF NOT EXISTS cron_run_receipts (\n receipt_id TEXT PRIMARY KEY,\n store_key TEXT NOT NULL,\n job_id TEXT NOT NULL,\n config_revision TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n request_run_id TEXT,\n status TEXT NOT NULL,\n owner_pid INTEGER NOT NULL,\n owner_start_time INTEGER,\n started_at_ms INTEGER NOT NULL,\n finished_at_ms INTEGER,\n error_text TEXT,\n CHECK (status IN ('running', 'ok', 'error', 'skipped', 'interrupted', 'superseded')),\n CHECK (\n (status = 'running' AND finished_at_ms IS NULL)\n OR\n (status != 'running' AND finished_at_ms IS NOT NULL)\n )\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_cron_run_receipts_active_job\n ON cron_run_receipts(store_key, job_id)\n WHERE status = 'running';\n\nCREATE INDEX IF NOT EXISTS idx_cron_run_receipts_job_history\n ON cron_run_receipts(store_key, job_id, started_at_ms DESC, receipt_id DESC);\n\n-- Retirement follows the receipt's retention without changing its released shape.\nCREATE TABLE IF NOT EXISTS cron_run_trigger_state_retirements (\n receipt_id TEXT PRIMARY KEY\n REFERENCES cron_run_receipts(receipt_id) ON DELETE CASCADE\n) STRICT;\n\n-- Runtime-private authority is independent of job_json so downgraded writers\n-- can rewrite recognized job config without erasing or silently widening it.\nCREATE TABLE IF NOT EXISTS cron_job_runtime_authorities (\n store_key TEXT NOT NULL,\n job_id TEXT NOT NULL,\n authority_json TEXT,\n authority_input_fingerprint TEXT,\n recovery_required INTEGER NOT NULL,\n PRIMARY KEY (store_key, job_id),\n FOREIGN KEY (store_key, job_id)\n REFERENCES cron_jobs(store_key, job_id) ON DELETE CASCADE,\n CHECK (recovery_required IN (0, 1)),\n CHECK (\n (recovery_required = 0 AND authority_json IS NOT NULL AND authority_input_fingerprint IS NOT NULL)\n OR\n (recovery_required = 1 AND authority_json IS NULL AND authority_input_fingerprint IS NULL)\n )\n) STRICT;\n\n-- Scratch is separate from cron_jobs so scheduler state writes and downgraded\n-- full-row replacement preserve it. New builds prune rows explicitly on job removal.\n-- content NULL is a tombstone: it keeps the revision lineage monotonic across\n-- unset/recreate so stale compare-and-swap writes cannot resurrect old content.\nCREATE TABLE IF NOT EXISTS cron_job_scratch (\n store_key TEXT NOT NULL,\n job_id TEXT NOT NULL,\n content TEXT,\n revision INTEGER NOT NULL,\n source_sha256 TEXT,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY (store_key, job_id),\n CHECK (revision >= 1),\n CHECK (content IS NULL OR length(CAST(content AS BLOB)) <= 262144)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_cron_job_scratch_store_updated\n ON cron_job_scratch(store_key, updated_at_ms DESC, job_id);\n\nCREATE TABLE IF NOT EXISTS delivery_queue_entries (\n queue_name TEXT NOT NULL,\n id TEXT NOT NULL,\n status TEXT NOT NULL,\n entry_kind TEXT,\n session_key TEXT,\n channel TEXT,\n target TEXT,\n account_id TEXT,\n retry_count INTEGER NOT NULL DEFAULT 0,\n last_attempt_at INTEGER,\n last_error TEXT,\n recovery_state TEXT,\n platform_send_started_at INTEGER,\n entry_json TEXT NOT NULL,\n enqueued_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n failed_at INTEGER,\n PRIMARY KEY (queue_name, id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_delivery_queue_pending\n ON delivery_queue_entries(queue_name, status, enqueued_at, id);\n\nCREATE INDEX IF NOT EXISTS idx_delivery_queue_failed\n ON delivery_queue_entries(queue_name, status, failed_at, id);\n\nCREATE INDEX IF NOT EXISTS idx_delivery_queue_session\n ON delivery_queue_entries(queue_name, status, session_key, enqueued_at, id)\n WHERE session_key IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_delivery_queue_target\n ON delivery_queue_entries(queue_name, status, channel, target, enqueued_at, id)\n WHERE channel IS NOT NULL AND target IS NOT NULL;\n\nCREATE TABLE IF NOT EXISTS task_runs (\n task_id TEXT NOT NULL PRIMARY KEY,\n runtime TEXT NOT NULL,\n task_kind TEXT,\n source_id TEXT,\n requester_session_key TEXT,\n owner_key TEXT NOT NULL,\n scope_kind TEXT NOT NULL,\n child_session_key TEXT,\n parent_flow_id TEXT,\n parent_task_id TEXT,\n agent_id TEXT,\n requester_agent_id TEXT,\n run_id TEXT,\n execution_owner_host TEXT,\n execution_owner_pid INTEGER,\n execution_owner_start_identity INTEGER,\n label TEXT,\n task TEXT NOT NULL,\n status TEXT NOT NULL,\n delivery_status TEXT NOT NULL,\n notify_policy TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n started_at INTEGER,\n ended_at INTEGER,\n last_event_at INTEGER,\n cleanup_after INTEGER,\n tool_use_count INTEGER,\n last_tool_name TEXT,\n error TEXT,\n progress_summary TEXT,\n terminal_summary TEXT,\n terminal_outcome TEXT,\n detail_json TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_task_runs_run_id ON task_runs(run_id);\nCREATE INDEX IF NOT EXISTS idx_task_runs_status ON task_runs(status);\nCREATE INDEX IF NOT EXISTS idx_task_runs_runtime_status ON task_runs(runtime, status);\nCREATE INDEX IF NOT EXISTS idx_task_runs_cleanup_after ON task_runs(cleanup_after);\nCREATE INDEX IF NOT EXISTS idx_task_runs_last_event_at ON task_runs(last_event_at);\nCREATE INDEX IF NOT EXISTS idx_task_runs_owner_key ON task_runs(owner_key);\nCREATE INDEX IF NOT EXISTS idx_task_runs_parent_flow_id ON task_runs(parent_flow_id);\nCREATE INDEX IF NOT EXISTS idx_task_runs_child_session_key ON task_runs(child_session_key);\nCREATE INDEX IF NOT EXISTS idx_task_runs_requester_session_key ON task_runs(requester_session_key);\nCREATE INDEX IF NOT EXISTS idx_task_runs_runtime_source_ended\n ON task_runs(runtime, source_id, ended_at, created_at, task_id);\nCREATE INDEX IF NOT EXISTS idx_task_runs_runtime_ended\n ON task_runs(runtime, ended_at, created_at, task_id);\n\nCREATE TABLE IF NOT EXISTS subagent_runs (\n run_id TEXT NOT NULL PRIMARY KEY,\n child_session_key TEXT NOT NULL,\n controller_session_key TEXT,\n controller_store_path TEXT,\n requester_session_key TEXT NOT NULL,\n requester_store_path TEXT,\n created_at INTEGER NOT NULL,\n payload_json TEXT NOT NULL DEFAULT '{}'\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_subagent_runs_child_session_key\n ON subagent_runs(child_session_key, created_at DESC, run_id);\nCREATE INDEX IF NOT EXISTS idx_subagent_runs_requester_session_key\n ON subagent_runs(requester_session_key, created_at DESC, run_id);\nCREATE INDEX IF NOT EXISTS idx_subagent_runs_controller_session_key\n ON subagent_runs(controller_session_key, created_at DESC, run_id);\n\nCREATE TABLE IF NOT EXISTS current_conversation_bindings (\n binding_key TEXT NOT NULL PRIMARY KEY,\n binding_id TEXT NOT NULL,\n target_session_key TEXT NOT NULL,\n channel TEXT NOT NULL,\n account_id TEXT NOT NULL,\n conversation_kind TEXT NOT NULL,\n parent_conversation_id TEXT,\n conversation_id TEXT NOT NULL,\n target_kind TEXT NOT NULL,\n status TEXT NOT NULL,\n bound_at INTEGER NOT NULL,\n expires_at INTEGER,\n metadata_json TEXT,\n record_json TEXT NOT NULL,\n updated_at INTEGER NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_target\n ON current_conversation_bindings(target_session_key, updated_at DESC, binding_key);\nCREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_conversation\n ON current_conversation_bindings(channel, account_id, conversation_kind, conversation_id);\nCREATE INDEX IF NOT EXISTS idx_current_conversation_bindings_expires\n ON current_conversation_bindings(expires_at, binding_key);\n\nCREATE TABLE IF NOT EXISTS plugin_binding_approvals (\n plugin_root TEXT NOT NULL,\n channel TEXT NOT NULL,\n account_id TEXT NOT NULL,\n plugin_id TEXT NOT NULL,\n plugin_name TEXT,\n approved_at INTEGER NOT NULL,\n PRIMARY KEY (plugin_root, channel, account_id)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_plugin_binding_approvals_plugin\n ON plugin_binding_approvals(plugin_id, approved_at DESC);\n\nCREATE TABLE IF NOT EXISTS task_delivery_state (\n task_id TEXT NOT NULL PRIMARY KEY,\n requester_origin_json TEXT,\n last_notified_event_at INTEGER,\n FOREIGN KEY (task_id) REFERENCES task_runs(task_id) ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS flow_runs (\n flow_id TEXT NOT NULL PRIMARY KEY,\n shape TEXT,\n sync_mode TEXT NOT NULL DEFAULT 'managed',\n owner_key TEXT NOT NULL,\n requester_origin_json TEXT,\n controller_id TEXT,\n revision INTEGER NOT NULL DEFAULT 0,\n status TEXT NOT NULL,\n notify_policy TEXT NOT NULL,\n goal TEXT NOT NULL,\n current_step TEXT,\n blocked_task_id TEXT,\n blocked_summary TEXT,\n state_json TEXT,\n wait_json TEXT,\n cancel_requested_at INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n ended_at INTEGER\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_flow_runs_status ON flow_runs(status);\nCREATE INDEX IF NOT EXISTS idx_flow_runs_owner_key ON flow_runs(owner_key);\nCREATE INDEX IF NOT EXISTS idx_flow_runs_updated_at ON flow_runs(updated_at);\n\n-- Durable meeting-capture sessions are gateway-global rather than agent-session\n-- transcripts. JSON/JSONL files are doctor import inputs or explicit CLI exports.\nCREATE TABLE IF NOT EXISTS meeting_transcript_sessions (\n session_id TEXT NOT NULL,\n started_at TEXT NOT NULL,\n selector TEXT NOT NULL UNIQUE,\n export_key TEXT NOT NULL,\n session_slug TEXT NOT NULL,\n provider_id TEXT NOT NULL,\n title TEXT,\n source_json TEXT NOT NULL,\n stopped_at TEXT,\n metadata_json TEXT,\n export_manifest_json TEXT NOT NULL DEFAULT '{}',\n export_pending_json TEXT NOT NULL DEFAULT '[]',\n next_utterance_seq INTEGER NOT NULL DEFAULT 0 CHECK (next_utterance_seq >= 0),\n created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n PRIMARY KEY (session_id, started_at)\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_started\n ON meeting_transcript_sessions(started_at DESC, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_id\n ON meeting_transcript_sessions(session_id, started_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_slug\n ON meeting_transcript_sessions(session_slug, started_at DESC);\n\nCREATE INDEX IF NOT EXISTS idx_meeting_transcript_sessions_export_key\n ON meeting_transcript_sessions(export_key);\n\nCREATE TABLE IF NOT EXISTS meeting_transcript_utterances (\n session_id TEXT NOT NULL,\n session_started_at TEXT NOT NULL,\n sequence INTEGER NOT NULL CHECK (sequence >= 0),\n utterance_id TEXT,\n started_at TEXT,\n ended_at TEXT,\n speaker_id TEXT,\n speaker_label TEXT,\n text TEXT NOT NULL,\n final INTEGER CHECK (final IN (0, 1)),\n metadata_json TEXT,\n PRIMARY KEY (session_id, session_started_at, sequence),\n FOREIGN KEY (session_id, session_started_at)\n REFERENCES meeting_transcript_sessions(session_id, started_at)\n ON DELETE CASCADE\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS meeting_transcript_summaries (\n session_id TEXT NOT NULL,\n session_started_at TEXT NOT NULL,\n generated_at TEXT,\n summary_json TEXT,\n markdown TEXT,\n utterance_count INTEGER NOT NULL CHECK (utterance_count >= 0),\n PRIMARY KEY (session_id, session_started_at),\n FOREIGN KEY (session_id, session_started_at)\n REFERENCES meeting_transcript_sessions(session_id, started_at)\n ON DELETE CASCADE,\n CHECK (summary_json IS NOT NULL OR markdown IS NOT NULL)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS migration_runs (\n id TEXT NOT NULL PRIMARY KEY,\n started_at INTEGER NOT NULL,\n finished_at INTEGER,\n status TEXT NOT NULL,\n report_json TEXT NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_migration_runs_started\n ON migration_runs(started_at DESC, id);\n\nCREATE TABLE IF NOT EXISTS migration_sources (\n source_key TEXT NOT NULL PRIMARY KEY,\n migration_kind TEXT NOT NULL,\n source_path TEXT NOT NULL,\n target_table TEXT NOT NULL,\n source_sha256 TEXT,\n source_size_bytes INTEGER,\n source_record_count INTEGER,\n last_run_id TEXT NOT NULL,\n status TEXT NOT NULL,\n imported_at INTEGER NOT NULL,\n removed_source INTEGER NOT NULL DEFAULT 0,\n report_json TEXT NOT NULL,\n FOREIGN KEY (last_run_id) REFERENCES migration_runs(id) ON DELETE CASCADE\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_migration_sources_path\n ON migration_sources(source_path, migration_kind, target_table);\n\nCREATE INDEX IF NOT EXISTS idx_migration_sources_run\n ON migration_sources(last_run_id, source_path);\n\nCREATE TABLE IF NOT EXISTS backup_runs (\n id TEXT NOT NULL PRIMARY KEY,\n created_at INTEGER NOT NULL,\n archive_path TEXT NOT NULL,\n status TEXT NOT NULL,\n manifest_json TEXT NOT NULL\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_backup_runs_created\n ON backup_runs(created_at DESC, id);\n\nCREATE TABLE IF NOT EXISTS worktrees (\n id TEXT NOT NULL PRIMARY KEY,\n repo_fingerprint TEXT NOT NULL,\n repo_root TEXT NOT NULL,\n path TEXT NOT NULL,\n branch TEXT NOT NULL,\n base_ref TEXT NOT NULL,\n owner_kind TEXT NOT NULL CHECK (owner_kind IN ('manual', 'workboard', 'session')),\n owner_id TEXT,\n snapshot_ref TEXT,\n provisioned_paths_json TEXT,\n created_at INTEGER NOT NULL,\n last_active_at INTEGER NOT NULL,\n removed_at INTEGER,\n run_end_cleanup_json TEXT,\n gc_protection_json TEXT\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_worktrees_repo_fingerprint\n ON worktrees(repo_fingerprint);\n\nCREATE INDEX IF NOT EXISTS idx_worktrees_removed_at\n ON worktrees(removed_at);\n\nCREATE TABLE IF NOT EXISTS worktree_provisioned_file_chunks (\n worktree_id TEXT NOT NULL,\n path TEXT NOT NULL,\n chunk_index INTEGER NOT NULL CHECK (chunk_index >= 0),\n data BLOB NOT NULL,\n PRIMARY KEY (worktree_id, path, chunk_index)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS worktree_templates (\n cache_key TEXT NOT NULL PRIMARY KEY,\n id TEXT NOT NULL UNIQUE,\n repo_root TEXT NOT NULL,\n common_dir TEXT NOT NULL,\n worktree_root TEXT NOT NULL,\n path TEXT NOT NULL,\n backend TEXT NOT NULL,\n source_commit TEXT NOT NULL,\n content_key TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('preparing', 'ready')),\n created_at INTEGER NOT NULL,\n last_used_at INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS projects (\n id TEXT NOT NULL PRIMARY KEY,\n display_name TEXT NOT NULL,\n repo_root TEXT NOT NULL,\n origin_url TEXT,\n source TEXT NOT NULL CHECK (source IN ('registered', 'cloned')),\n created_at_ms INT NOT NULL,\n updated_at_ms INT NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS user_preferences (\n profile_id TEXT NOT NULL,\n pref_key TEXT NOT NULL,\n value_json TEXT NOT NULL,\n updated_at_ms INT NOT NULL,\n PRIMARY KEY (profile_id, pref_key)\n) STRICT;\n\n-- Gateway-owned custom session group catalog (names + display order).\n-- Membership stays on each session entry's category field; this table only\n-- owns which groups exist and how operator UIs order them.\nCREATE TABLE IF NOT EXISTS session_groups (\n name TEXT NOT NULL PRIMARY KEY,\n position INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n cwd TEXT,\n worktree INTEGER\n) STRICT;\n\n-- Gateway-owned durable cloud worker lifecycle. Provider-specific execution\n-- stays in plugins; this table records only core reconciliation facts.\nCREATE TABLE IF NOT EXISTS worker_environments (\n environment_id TEXT NOT NULL PRIMARY KEY,\n provider_id TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n profile_snapshot_json TEXT NOT NULL,\n last_activated_at_ms INTEGER,\n preparation_key TEXT,\n preparation_purpose TEXT,\n preparation_demand_at_ms INTEGER,\n preparation_expires_at_ms INTEGER,\n preparation_consumed_at_ms INTEGER CHECK (\n (preparation_key IS NULL AND preparation_demand_at_ms IS NULL\n AND preparation_expires_at_ms IS NULL AND preparation_consumed_at_ms IS NULL)\n OR\n (preparation_key IS NOT NULL AND length(preparation_key) = 64\n AND preparation_key NOT GLOB '*[^0-9a-f]*'\n AND preparation_demand_at_ms IS NOT NULL\n AND preparation_demand_at_ms BETWEEN 0 AND 9007199254740991\n AND preparation_expires_at_ms IS NOT NULL\n AND preparation_expires_at_ms > preparation_demand_at_ms\n AND preparation_expires_at_ms <= 9007199254740991\n AND (preparation_consumed_at_ms IS NULL\n OR (preparation_consumed_at_ms >= preparation_demand_at_ms\n AND preparation_consumed_at_ms < preparation_expires_at_ms)))\n ),\n provision_operation_id TEXT NOT NULL UNIQUE,\n lease_id TEXT,\n node_setup_id TEXT,\n node_device_id TEXT,\n ssh_host TEXT,\n ssh_port INTEGER CHECK (ssh_port IS NULL OR (ssh_port >= 1 AND ssh_port <= 65535)),\n ssh_user TEXT,\n ssh_host_key TEXT,\n ssh_key_ref_json TEXT,\n desktop_json TEXT,\n state TEXT NOT NULL CHECK (\n state IN (\n 'requested',\n 'provisioning',\n 'bootstrapping',\n 'ready',\n 'attached',\n 'idle',\n 'draining',\n 'destroying',\n 'destroyed',\n 'failed',\n 'orphaned'\n )\n ),\n bootstrap_bundle_hash TEXT,\n bootstrap_openclaw_version TEXT,\n bootstrap_protocol_features_json TEXT,\n bootstrap_install_kind TEXT,\n owner_epoch INTEGER NOT NULL DEFAULT 0 CHECK (owner_epoch >= 0),\n teardown_terminal_state TEXT CHECK (teardown_terminal_state IN ('destroyed', 'failed')),\n attached_session_ids_json TEXT NOT NULL DEFAULT '[]',\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n state_changed_at_ms INTEGER NOT NULL,\n idle_since_at_ms INTEGER,\n destroy_requested_at_ms INTEGER,\n last_error TEXT,\n shared_host INTEGER\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_worker_environments_provider_lease\n ON worker_environments(provider_id, lease_id)\n WHERE lease_id IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS idx_worker_environments_terminal_changed\n ON worker_environments(state_changed_at_ms, environment_id);\n\n-- A dedicated node registers its fixed build paths before ready, then binds\n-- them once. The environment belongs to the Gateway's separate database.\nCREATE TABLE IF NOT EXISTS node_worker_prepared_workspaces (\n preparation_key TEXT NOT NULL PRIMARY KEY CHECK (\n length(preparation_key) = 64 AND preparation_key NOT GLOB '*[^0-9a-f]*'\n ),\n cache_key TEXT NOT NULL CHECK (\n length(cache_key) = 64 AND cache_key NOT GLOB '*[^0-9a-f]*'\n ),\n gateway_namespace TEXT NOT NULL CHECK (length(gateway_namespace) > 0),\n workspace_dir TEXT NOT NULL UNIQUE CHECK (length(workspace_dir) > 0),\n home_dir TEXT NOT NULL CHECK (length(home_dir) > 0),\n source_manifest_ref TEXT NOT NULL CHECK (\n length(source_manifest_ref) = 71 AND substr(source_manifest_ref, 1, 7) = 'sha256:'\n AND substr(source_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'\n ),\n prepared_manifest_ref TEXT NOT NULL CHECK (\n length(prepared_manifest_ref) = 71 AND substr(prepared_manifest_ref, 1, 7) = 'sha256:'\n AND substr(prepared_manifest_ref, 8) NOT GLOB '*[^0-9a-f]*'\n ),\n state TEXT NOT NULL CHECK (state IN ('available', 'bound', 'retiring', 'retired')),\n environment_id TEXT NOT NULL CHECK (length(environment_id) > 0),\n session_id TEXT,\n session_key TEXT,\n owner_epoch INTEGER CHECK (owner_epoch BETWEEN 1 AND 9007199254740991),\n created_at_ms INTEGER NOT NULL CHECK (created_at_ms BETWEEN 0 AND 9007199254740991),\n bound_at_ms INTEGER CHECK (bound_at_ms BETWEEN created_at_ms AND 9007199254740991),\n retired_at_ms INTEGER CHECK (\n retired_at_ms BETWEEN coalesce(bound_at_ms, created_at_ms) AND 9007199254740991\n ),\n CHECK (\n (session_id IS NULL AND session_key IS NULL AND owner_epoch IS NULL AND bound_at_ms IS NULL)\n OR\n (session_id IS NOT NULL AND length(session_id) > 0\n AND session_key IS NOT NULL AND length(session_key) > 0\n AND owner_epoch IS NOT NULL AND bound_at_ms IS NOT NULL)\n ),\n CHECK (\n (state = 'available' AND bound_at_ms IS NULL AND retired_at_ms IS NULL)\n OR (state = 'bound' AND bound_at_ms IS NOT NULL AND retired_at_ms IS NULL)\n OR (state = 'retiring' AND retired_at_ms IS NULL)\n OR (state = 'retired' AND retired_at_ms IS NOT NULL)\n )\n) STRICT;\n\n-- Provider-advertised fallback ports preserve stable retry order separately\n-- from the downgrade-sensitive canonical worker environment row.\nCREATE TABLE IF NOT EXISTS worker_environment_ssh_fallback_ports (\n environment_id TEXT NOT NULL,\n position INTEGER NOT NULL CHECK (position >= 0 AND position <= 9),\n port INTEGER NOT NULL CHECK (port >= 1 AND port <= 65535),\n PRIMARY KEY (environment_id, position),\n UNIQUE (environment_id, port),\n FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE\n) STRICT;\n\n-- Logical sessions own repository intent and accepted artifact references,\n-- independently of the worker or rotating transcript session id.\nCREATE TABLE IF NOT EXISTS session_repository_workspaces (\n workspace_id TEXT NOT NULL PRIMARY KEY CHECK (length(workspace_id) = 36),\n agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),\n session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),\n url TEXT NOT NULL CHECK (length(url) BETWEEN 1 AND 4096),\n requested_ref TEXT CHECK (requested_ref IS NULL OR length(requested_ref) BETWEEN 1 AND 1024),\n run_setup_script INTEGER NOT NULL DEFAULT 0 CHECK (run_setup_script IN (0, 1)),\n base_commit TEXT CHECK (base_commit IS NULL OR length(base_commit) IN (40, 64)),\n base_manifest_hash TEXT,\n branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),\n checkpoint_ref TEXT,\n manifest_hash TEXT,\n revision INTEGER NOT NULL CHECK (revision >= 0),\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n UNIQUE (agent_id, session_key),\n CHECK (base_manifest_hash IS NULL OR base_commit IS NOT NULL),\n CHECK ((checkpoint_ref IS NULL AND manifest_hash IS NULL)\n OR (checkpoint_ref IS NOT NULL AND manifest_hash IS NOT NULL AND base_manifest_hash IS NOT NULL))\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS github_repository_publication_requests (\n request_id TEXT NOT NULL PRIMARY KEY,\n owner_profile_id TEXT,\n connection_generation TEXT,\n idempotency_key TEXT NOT NULL,\n request_digest TEXT NOT NULL,\n session_id TEXT NOT NULL,\n session_lifecycle_revision TEXT,\n requester_authority_json TEXT,\n session_key TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n checkpoint_ref TEXT,\n checkpoint_digest TEXT,\n claim_id TEXT,\n run_id TEXT,\n environment_id TEXT,\n owner_epoch INTEGER,\n placement_generation INTEGER,\n identity_source TEXT NOT NULL CHECK (identity_source IN ('system-detected', 'system-configured', 'agent-override', 'personal')),\n identity_profile_id TEXT,\n identity_account_id INTEGER NOT NULL,\n identity_login TEXT NOT NULL,\n title TEXT,\n body TEXT,\n status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),\n gateway_instance_id TEXT,\n execution_id TEXT,\n last_effect TEXT CHECK (last_effect IN ('push', 'pull_request')),\n effect_state TEXT CHECK (effect_state IN ('dispatched', 'observed')),\n push_repository TEXT,\n repository TEXT,\n branch TEXT NOT NULL,\n base_branch TEXT,\n source_head_commit TEXT,\n source_index_tree TEXT,\n workspace_tree TEXT,\n previous_head_commit TEXT,\n pushed_head_commit TEXT,\n head_commit TEXT,\n pull_request_url TEXT,\n error_code TEXT,\n next_action TEXT,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n reported_at_ms INTEGER,\n CHECK ((identity_source = 'personal' AND owner_profile_id IS NOT NULL AND connection_generation IS NOT NULL)\n OR (identity_source <> 'personal' AND owner_profile_id IS NULL AND connection_generation IS NULL)),\n CHECK ((checkpoint_ref IS NULL AND checkpoint_digest IS NULL) OR (checkpoint_ref IS NOT NULL AND checkpoint_digest IS NOT NULL)),\n CHECK ((last_effect IS NULL AND effect_state IS NULL) OR (last_effect IS NOT NULL AND effect_state IS NOT NULL))\n) STRICT;\nCREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_shared_request\n ON github_repository_publication_requests(session_id, idempotency_key) WHERE owner_profile_id IS NULL;\nCREATE UNIQUE INDEX IF NOT EXISTS idx_github_repository_publication_personal_request\n ON github_repository_publication_requests(owner_profile_id, session_id, idempotency_key) WHERE owner_profile_id IS NOT NULL;\n\n-- Session placement lives in the shared state database so local admission,\n-- worker admission, and environment attachment use one durable authority.\nCREATE TABLE IF NOT EXISTS worker_session_placements (\n session_id TEXT NOT NULL PRIMARY KEY,\n agent_id TEXT NOT NULL,\n session_key TEXT NOT NULL,\n execution_mode TEXT CHECK (execution_mode IN ('worker-turn', 'remote-exec')),\n state TEXT NOT NULL CHECK (\n state IN (\n 'local',\n 'requested',\n 'provisioning',\n 'syncing',\n 'starting',\n 'active',\n 'draining',\n 'reconciling',\n 'reclaimed',\n 'failed'\n )\n ),\n environment_id TEXT,\n transition_generation INTEGER NOT NULL DEFAULT 0 CHECK (transition_generation >= 0),\n active_owner_epoch INTEGER CHECK (active_owner_epoch IS NULL OR active_owner_epoch >= 1),\n workspace_base_manifest_ref TEXT,\n remote_workspace_dir TEXT,\n worker_bundle_hash TEXT,\n last_transcript_ack_cursor INTEGER CHECK (\n last_transcript_ack_cursor IS NULL OR last_transcript_ack_cursor >= 0\n ),\n last_live_event_ack_cursor INTEGER CHECK (\n last_live_event_ack_cursor IS NULL OR last_live_event_ack_cursor >= 0\n ),\n recovery_error TEXT,\n turn_claim_owner TEXT CHECK (turn_claim_owner IN ('local', 'worker')),\n turn_claim_id TEXT,\n turn_claim_run_id TEXT,\n turn_claim_generation INTEGER CHECK (\n turn_claim_generation IS NULL OR turn_claim_generation >= 0\n ),\n turn_claim_owner_epoch INTEGER CHECK (\n turn_claim_owner_epoch IS NULL OR turn_claim_owner_epoch >= 1\n ),\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n state_changed_at_ms INTEGER NOT NULL,\n terminal_reason TEXT,\n terminal_at_ms INTEGER,\n CHECK (\n (state IN ('local', 'requested')\n AND environment_id IS NULL AND active_owner_epoch IS NULL\n AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL\n AND worker_bundle_hash IS NULL\n AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL\n AND recovery_error IS NULL)\n OR\n (state IS 'provisioning'\n AND active_owner_epoch IS NULL\n AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL\n AND worker_bundle_hash IS NULL\n AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL\n AND recovery_error IS NULL)\n OR\n (state IS 'syncing'\n AND environment_id IS NOT NULL AND active_owner_epoch IS NULL\n AND workspace_base_manifest_ref IS NULL AND remote_workspace_dir IS NULL\n AND worker_bundle_hash IS NOT NULL\n AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL\n AND recovery_error IS NULL)\n OR\n (state IS 'starting'\n AND environment_id IS NOT NULL AND active_owner_epoch IS NULL\n AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL\n AND worker_bundle_hash IS NOT NULL\n AND last_transcript_ack_cursor IS NULL AND last_live_event_ack_cursor IS NULL\n AND recovery_error IS NULL)\n OR\n (state IN ('active', 'draining', 'reconciling')\n AND environment_id IS NOT NULL AND active_owner_epoch IS NOT NULL\n AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL\n AND worker_bundle_hash IS NOT NULL AND recovery_error IS NULL)\n OR\n (state IS 'reclaimed'\n AND environment_id IS NOT NULL AND active_owner_epoch IS NOT NULL\n AND workspace_base_manifest_ref IS NOT NULL AND remote_workspace_dir IS NOT NULL\n AND worker_bundle_hash IS NOT NULL AND recovery_error IS NULL\n AND turn_claim_owner IS NULL AND turn_claim_id IS NULL AND turn_claim_run_id IS NULL\n AND turn_claim_generation IS NULL AND turn_claim_owner_epoch IS NULL)\n OR\n (state IS 'failed' AND recovery_error IS NOT NULL)\n ),\n CHECK (\n (turn_claim_owner IS NULL AND turn_claim_id IS NULL AND turn_claim_run_id IS NULL\n AND turn_claim_generation IS NULL AND turn_claim_owner_epoch IS NULL)\n OR\n (turn_claim_owner IS 'local' AND turn_claim_id IS NOT NULL\n AND turn_claim_run_id IS NOT NULL AND turn_claim_generation IS NOT NULL\n AND turn_claim_owner_epoch IS NULL)\n OR\n (turn_claim_owner IS 'worker' AND turn_claim_id IS NOT NULL\n AND turn_claim_run_id IS NOT NULL AND turn_claim_generation IS NOT NULL\n AND turn_claim_owner_epoch IS NOT NULL)\n ),\n CHECK (\n turn_claim_owner IS NULL\n OR\n (turn_claim_owner IS 'local' AND (\n state IN ('local', 'requested', 'failed')\n OR (state IN ('active', 'draining') AND execution_mode IS 'remote-exec')\n ))\n OR\n (turn_claim_owner IS 'worker' AND state IN ('active', 'draining')\n AND (execution_mode IS NULL OR execution_mode IS 'worker-turn')\n AND turn_claim_owner_epoch IS active_owner_epoch)\n )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_worker_session_placements_session_key\n ON worker_session_placements(agent_id, session_key);\n\nCREATE INDEX IF NOT EXISTS idx_worker_session_placements_reconcile\n ON worker_session_placements(updated_at_ms, session_id);\n\nCREATE INDEX IF NOT EXISTS idx_worker_session_placements_environment\n ON worker_session_placements(environment_id)\n WHERE environment_id IS NOT NULL;\n\n-- Planned placement moves retain their exact source CAS and bounded target\n-- without widening the stable placement-state vocabulary. The opaque operation\n-- id fences stale asynchronous completion; it is correlation, never authority.\nCREATE TABLE IF NOT EXISTS worker_session_placement_moves (\n operation_id TEXT NOT NULL PRIMARY KEY,\n session_id TEXT NOT NULL UNIQUE\n REFERENCES worker_session_placements(session_id) ON DELETE CASCADE,\n source_generation INTEGER NOT NULL CHECK (source_generation >= 0),\n source_environment_id TEXT NOT NULL CHECK (\n length(source_environment_id) BETWEEN 1 AND 256\n AND source_environment_id = trim(source_environment_id)\n ),\n source_owner_epoch INTEGER NOT NULL CHECK (source_owner_epoch >= 1),\n target_kind TEXT NOT NULL CHECK (target_kind IN ('gateway', 'profile', 'device')),\n target_id TEXT,\n -- Keep these nullable columns constraint-free so lazy ALTER TABLE produces the\n -- same shape as fresh databases; placement-move code validates their values.\n target_machine_class TEXT,\n target_os TEXT,\n -- Explicit source abandonment is a durable operator decision. Keep the bit\n -- bare and nullable so same-version older readers can safely omit it.\n abandon_source INTEGER,\n last_error TEXT,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n CHECK (\n (target_kind IS 'gateway' AND target_id IS NULL)\n OR\n (target_kind IN ('profile', 'device')\n AND target_id IS NOT NULL\n AND length(target_id) BETWEEN 1 AND 256\n AND target_id = trim(target_id))\n )\n) STRICT;\n\n-- Worker-visible session RPC authority is persisted against the exact turn\n-- claim. The launch descriptor is informative only; Gateway dispatch always\n-- revalidates this record and the live placement claim before executing.\nCREATE TABLE IF NOT EXISTS worker_turn_tool_authorities (\n session_id TEXT NOT NULL PRIMARY KEY,\n environment_id TEXT NOT NULL,\n owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),\n placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),\n claim_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n tool_names_json TEXT NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE\n) STRICT;\n\n-- Tool-call ids are idempotency keys only within one exact source turn claim.\n-- A running operation from another Gateway instance is ambiguous and is never\n-- replayed. A persisted random seed separates durable downstream identities\n-- from Gateway authentication keys and survives ordinary process restarts.\nCREATE TABLE IF NOT EXISTS worker_session_tool_operations (\n source_session_id TEXT NOT NULL,\n source_claim_id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n tool_name TEXT NOT NULL CHECK (tool_name IN ('sessions_spawn', 'sessions_send')),\n request_digest TEXT NOT NULL,\n operation_seed TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('running', 'succeeded', 'failed', 'unknown')),\n child_session_key TEXT,\n result_json TEXT,\n gateway_instance_id TEXT NOT NULL,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY (source_session_id, source_claim_id, tool_call_id),\n FOREIGN KEY (source_session_id)\n REFERENCES worker_session_placements(session_id) ON DELETE CASCADE\n) STRICT;\n\n-- Local sandbox execution is a projection of a session-owned managed worktree.\n-- No cascade: an older binary must not discard pending edits with a session row.\nCREATE TABLE IF NOT EXISTS local_workspace_projections (\n worktree_id TEXT NOT NULL PRIMARY KEY,\n agent_id TEXT NOT NULL,\n session_key TEXT NOT NULL,\n session_id TEXT NOT NULL,\n lifecycle_revision TEXT,\n projection_path TEXT NOT NULL UNIQUE,\n base_commit TEXT NOT NULL,\n source_paths_json TEXT NOT NULL,\n baseline_json TEXT,\n baseline_ref TEXT,\n pending_ref TEXT,\n pending_target TEXT CHECK (pending_target IN ('canonical', 'projection')),\n paused_runtimes_json TEXT,\n journal_json TEXT,\n journal_pack BLOB CHECK (journal_pack IS NULL OR length(journal_pack) <= 268435456),\n revision INTEGER NOT NULL DEFAULT 0 CHECK (revision >= 0),\n created_at_ms INTEGER NOT NULL,\n CHECK ((baseline_json IS NULL) = (baseline_ref IS NULL)),\n CHECK ((journal_json IS NULL) = (journal_pack IS NULL))\n) STRICT;\n\n-- A reconciliation journal is written before managed-worktree mutation. The\n-- bounded Git base snapshot repairs any subset left by an interrupted apply.\nCREATE TABLE IF NOT EXISTS worker_workspace_reconciliations (\n session_id TEXT NOT NULL PRIMARY KEY,\n environment_id TEXT NOT NULL,\n owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),\n placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),\n base_manifest_ref TEXT NOT NULL,\n current_manifest_ref TEXT NOT NULL,\n plan_json TEXT NOT NULL,\n base_pack BLOB NOT NULL CHECK (length(base_pack) <= 268435456),\n created_at_ms INTEGER NOT NULL,\n FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE\n) STRICT;\n\n-- A completed remote turn is fenced from stale-claim teardown until its\n-- workspace result is durably reconciled into the managed worktree.\nCREATE TABLE IF NOT EXISTS worker_workspace_pending_results (\n session_id TEXT NOT NULL PRIMARY KEY,\n environment_id TEXT NOT NULL,\n owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 1),\n placement_generation INTEGER NOT NULL CHECK (placement_generation >= 0),\n claim_id TEXT NOT NULL,\n run_id TEXT NOT NULL,\n gateway_instance_id TEXT NOT NULL,\n recovery_requested_at_ms INTEGER,\n workspace_accepted_at_ms INTEGER,\n staged_result_ref TEXT,\n repository_workspace_id TEXT,\n created_at_ms INTEGER NOT NULL,\n FOREIGN KEY (session_id) REFERENCES worker_session_placements(session_id) ON DELETE CASCADE\n) STRICT;\n\n-- GitHub publication intent records the authoritative session worktree. Cloud\n-- requests execute only after the exact turn claim's result is accepted locally.\n-- Secrets stay in the effective Gateway-owned GitHub profile and never enter\n-- this row or the worker protocol.\nCREATE TABLE IF NOT EXISTS github_publication_requests (\n request_id TEXT NOT NULL PRIMARY KEY,\n idempotency_key TEXT NOT NULL,\n request_digest TEXT NOT NULL,\n session_id TEXT NOT NULL,\n session_key TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n worktree_id TEXT NOT NULL,\n repository_fingerprint TEXT NOT NULL,\n claim_id TEXT,\n run_id TEXT,\n environment_id TEXT,\n owner_epoch INTEGER CHECK (owner_epoch IS NULL OR owner_epoch >= 1),\n placement_generation INTEGER CHECK (\n placement_generation IS NULL OR placement_generation >= 0\n ),\n identity_source TEXT NOT NULL CHECK (\n identity_source IN ('system-detected', 'system-configured', 'agent-override')\n ),\n identity_profile_id TEXT,\n identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),\n identity_login TEXT NOT NULL,\n title TEXT,\n body TEXT,\n status TEXT NOT NULL CHECK (\n status IN ('requested', 'publishing', 'published', 'failed')\n ),\n gateway_instance_id TEXT,\n repository TEXT,\n branch TEXT NOT NULL,\n base_branch TEXT,\n source_head_commit TEXT,\n source_index_tree TEXT,\n workspace_tree TEXT,\n head_commit TEXT,\n pull_request_url TEXT,\n error_code TEXT,\n next_action TEXT,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n reported_at_ms INTEGER,\n UNIQUE (session_id, idempotency_key),\n CHECK (\n (claim_id IS NULL AND run_id IS NULL AND environment_id IS NULL\n AND owner_epoch IS NULL AND placement_generation IS NULL)\n OR\n (claim_id IS NOT NULL AND run_id IS NOT NULL AND placement_generation IS NOT NULL\n AND ((environment_id IS NULL AND owner_epoch IS NULL)\n OR (environment_id IS NOT NULL AND owner_epoch IS NOT NULL)))\n ),\n CHECK (\n (identity_source IS 'system-detected' AND identity_profile_id IS NULL)\n OR\n (identity_source IN ('system-configured', 'agent-override')\n AND identity_profile_id IS NOT NULL)\n ),\n CHECK (\n (source_head_commit IS NULL AND source_index_tree IS NULL AND workspace_tree IS NULL)\n OR\n (source_head_commit IS NOT NULL AND workspace_tree IS NOT NULL)\n ),\n CHECK (\n (status IS 'published' AND pull_request_url IS NOT NULL AND error_code IS NULL\n AND next_action IS NULL)\n OR\n (status IS 'failed' AND pull_request_url IS NULL AND error_code IS NOT NULL\n AND next_action IS NOT NULL)\n OR\n (status IN ('requested', 'publishing') AND pull_request_url IS NULL\n AND error_code IS NULL AND next_action IS NULL)\n )\n) STRICT;\n\nCREATE INDEX IF NOT EXISTS idx_github_publication_requests_pending\n ON github_publication_requests(status, updated_at_ms, request_id);\n\n-- Personal requests cannot be interpreted or resumed by older shared publishers.\nCREATE TABLE IF NOT EXISTS github_personal_publication_requests (\n request_id TEXT NOT NULL PRIMARY KEY CHECK (length(request_id) = 36),\n owner_profile_id TEXT NOT NULL CHECK (length(owner_profile_id) BETWEEN 1 AND 128),\n connection_generation TEXT NOT NULL CHECK (length(connection_generation) = 36),\n idempotency_key TEXT NOT NULL CHECK (length(idempotency_key) BETWEEN 1 AND 128),\n request_digest TEXT NOT NULL CHECK (length(request_digest) = 64),\n session_id TEXT NOT NULL CHECK (length(session_id) BETWEEN 1 AND 128),\n session_key TEXT NOT NULL CHECK (length(session_key) BETWEEN 1 AND 1024),\n agent_id TEXT NOT NULL CHECK (length(agent_id) BETWEEN 1 AND 128),\n worktree_id TEXT NOT NULL CHECK (length(worktree_id) BETWEEN 1 AND 128),\n repository_fingerprint TEXT NOT NULL CHECK (length(repository_fingerprint) BETWEEN 1 AND 256),\n identity_source TEXT NOT NULL CHECK (identity_source = 'personal'),\n identity_profile_id TEXT NOT NULL CHECK (length(identity_profile_id) = 36),\n identity_account_id INTEGER NOT NULL CHECK (identity_account_id >= 1),\n identity_login TEXT NOT NULL CHECK (length(identity_login) BETWEEN 1 AND 39),\n title TEXT CHECK (title IS NULL OR length(title) BETWEEN 1 AND 256),\n body TEXT CHECK (body IS NULL OR length(body) BETWEEN 1 AND 8192),\n status TEXT NOT NULL CHECK (status IN ('requested', 'publishing', 'needs_confirmation', 'published', 'failed')),\n gateway_instance_id TEXT CHECK (gateway_instance_id IS NULL OR length(gateway_instance_id) BETWEEN 1 AND 128),\n execution_id TEXT CHECK (execution_id IS NULL OR length(execution_id) = 36),\n last_effect TEXT CHECK (last_effect IS NULL OR last_effect IN ('push', 'pull_request')),\n effect_state TEXT CHECK (effect_state IS NULL OR effect_state IN ('dispatched', 'observed')),\n push_repository TEXT NOT NULL CHECK (length(push_repository) BETWEEN 3 AND 256),\n repository TEXT NOT NULL CHECK (length(repository) BETWEEN 3 AND 256),\n branch TEXT NOT NULL CHECK (length(branch) BETWEEN 1 AND 256),\n base_branch TEXT NOT NULL CHECK (length(base_branch) BETWEEN 1 AND 256),\n source_head_commit TEXT NOT NULL CHECK (length(source_head_commit) IN (40, 64)),\n source_index_tree TEXT NOT NULL CHECK (length(source_index_tree) IN (40, 64)),\n workspace_tree TEXT NOT NULL CHECK (length(workspace_tree) IN (40, 64)),\n head_commit TEXT CHECK (head_commit IS NULL OR length(head_commit) IN (40, 64)),\n pull_request_url TEXT CHECK (pull_request_url IS NULL OR length(pull_request_url) BETWEEN 1 AND 2048),\n error_code TEXT CHECK (error_code IS NULL OR length(error_code) BETWEEN 1 AND 64),\n next_action TEXT CHECK (next_action IS NULL OR length(next_action) BETWEEN 1 AND 1024),\n created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= created_at_ms),\n reported_at_ms INTEGER,\n UNIQUE (owner_profile_id, session_id, idempotency_key),\n CHECK ((status = 'publishing' AND gateway_instance_id IS NOT NULL AND execution_id IS NOT NULL) OR status <> 'publishing'),\n CHECK ((last_effect IS NULL AND effect_state IS NULL) OR (last_effect IS NOT NULL AND effect_state IS NOT NULL)),\n CHECK ((status = 'published' AND pull_request_url IS NOT NULL AND head_commit IS NOT NULL AND error_code IS NULL AND next_action IS NULL)\n OR (status = 'failed' AND error_code IS NOT NULL AND next_action IS NOT NULL)\n OR (status IN ('requested', 'publishing', 'needs_confirmation') AND error_code IS NULL AND next_action IS NULL))\n) STRICT;\nCREATE INDEX IF NOT EXISTS idx_github_personal_publication_owner_session\n ON github_personal_publication_requests(owner_profile_id, session_id, created_at_ms);\nCREATE INDEX IF NOT EXISTS idx_github_personal_publication_pending\n ON github_personal_publication_requests(status, updated_at_ms, request_id);\n\n-- Older readers validate both local receipt tables exactly. Their immutable\n-- lifecycle binding stays in a first-use companion so those schemas remain readable.\nCREATE TABLE IF NOT EXISTS github_publication_session_lifecycles (\n publication_kind TEXT NOT NULL CHECK (publication_kind IN ('shared', 'personal')),\n request_id TEXT NOT NULL,\n lifecycle_revision TEXT,\n requester_authority_json TEXT,\n PRIMARY KEY (publication_kind, request_id)\n) STRICT;\n\n-- One active, opaque admission credential per worker environment. Plaintext\n-- may be retried until delivery acknowledgement but never enters durable state.\nCREATE TABLE IF NOT EXISTS worker_environment_credentials (\n environment_id TEXT NOT NULL PRIMARY KEY,\n credential_hash TEXT NOT NULL UNIQUE,\n bundle_hash TEXT NOT NULL,\n session_id TEXT,\n rpc_set_version INTEGER NOT NULL CHECK (rpc_set_version >= 1),\n owner_epoch INTEGER NOT NULL CHECK (owner_epoch >= 0),\n expires_at_ms INTEGER NOT NULL CHECK (expires_at_ms >= 0),\n delivered_at_ms INTEGER CHECK (delivered_at_ms >= 0),\n FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE\n) STRICT;\n\n-- One durable sequence cursor per attached session owner epoch. The environment\n-- binding prevents independent workers with coincident epochs from sharing replay state.\nCREATE TABLE IF NOT EXISTS worker_transcript_commit_heads (\n session_id TEXT NOT NULL,\n run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),\n environment_id TEXT NOT NULL,\n next_seq INTEGER NOT NULL CHECK (next_seq >= 1),\n updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n PRIMARY KEY (session_id, run_epoch)\n) STRICT;\n\n-- Pending rows preserve a claimed request across gateway restarts. Terminal rows\n-- cache the exact result returned for deterministic at-least-once replay.\nCREATE TABLE IF NOT EXISTS worker_transcript_commits (\n session_id TEXT NOT NULL,\n run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),\n seq INTEGER NOT NULL CHECK (seq >= 1),\n request_hash TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),\n result_json TEXT,\n created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n PRIMARY KEY (session_id, run_epoch, seq),\n FOREIGN KEY (session_id, run_epoch)\n REFERENCES worker_transcript_commit_heads(session_id, run_epoch)\n ON DELETE CASCADE,\n CHECK (\n (state = 'pending' AND result_json IS NULL) OR\n (state = 'terminal' AND result_json IS NOT NULL)\n )\n) STRICT;\n\n-- Pending rows preserve a claimed inference turn across gateway restarts.\n-- Terminal rows cache the exact outcome returned for deterministic replay.\nCREATE TABLE IF NOT EXISTS worker_inference_turns (\n session_id TEXT NOT NULL,\n run_epoch INTEGER NOT NULL CHECK (run_epoch >= 0),\n run_id TEXT NOT NULL,\n turn_id TEXT NOT NULL,\n environment_id TEXT NOT NULL,\n request_hash TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('pending', 'terminal')),\n terminal_json TEXT,\n created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n PRIMARY KEY (session_id, run_epoch, run_id, turn_id),\n FOREIGN KEY (environment_id) REFERENCES worker_environments(environment_id) ON DELETE CASCADE,\n CHECK (\n (state = 'pending' AND terminal_json IS NULL) OR\n (state = 'terminal' AND terminal_json IS NOT NULL)\n )\n) STRICT;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_worker_inference_turns_pending_run\n ON worker_inference_turns(session_id, run_epoch, run_id)\n WHERE state = 'pending';\n\nCREATE TABLE IF NOT EXISTS fleet_cells (\n tenant_id TEXT NOT NULL PRIMARY KEY,\n created_at_ms INTEGER NOT NULL,\n image TEXT NOT NULL,\n runtime TEXT NOT NULL,\n host_port INTEGER NOT NULL,\n container_name TEXT NOT NULL,\n data_dir TEXT NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS claw_installs (\n agent_id TEXT NOT NULL PRIMARY KEY,\n schema_version TEXT NOT NULL,\n source_kind TEXT NOT NULL,\n claw_name TEXT NOT NULL,\n claw_version TEXT NOT NULL,\n package_root TEXT NOT NULL,\n manifest_path TEXT NOT NULL,\n integrity_kind TEXT NOT NULL,\n integrity TEXT NOT NULL,\n source_byte_length INTEGER NOT NULL,\n manifest_schema_version INTEGER NOT NULL,\n plan_integrity TEXT NOT NULL,\n workspace TEXT NOT NULL UNIQUE,\n agent_config_digest TEXT NOT NULL,\n agent_owned_paths_json TEXT NOT NULL,\n bootstrap_source_path TEXT,\n bootstrap_content_digest TEXT,\n status TEXT NOT NULL CHECK (\n status IN ('pending', 'workspace_ready', 'config_committed', 'complete', 'partial')\n ),\n added_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS claw_workspace_files (\n agent_id TEXT NOT NULL,\n target_path TEXT NOT NULL,\n schema_version TEXT NOT NULL,\n workspace TEXT NOT NULL,\n source_path TEXT NOT NULL,\n content_digest TEXT NOT NULL,\n status TEXT NOT NULL,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY (agent_id, target_path)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS claw_package_refs (\n agent_id TEXT NOT NULL,\n package_kind TEXT NOT NULL,\n package_source TEXT NOT NULL,\n package_ref TEXT NOT NULL,\n package_version TEXT NOT NULL,\n package_integrity TEXT NOT NULL,\n schema_version TEXT NOT NULL,\n claw_name TEXT NOT NULL,\n package_status TEXT NOT NULL,\n relationship TEXT NOT NULL CHECK (relationship IN ('managed', 'referenced')),\n origin TEXT NOT NULL CHECK (origin IN ('claw-introduced', 'pre-existing')),\n independent_owner INTEGER NOT NULL CHECK (independent_owner IN (0, 1)),\n extension_id TEXT,\n extension_format TEXT,\n extension_detected_format TEXT,\n extension_mapped_json TEXT,\n extension_unavailable_json TEXT,\n extension_adapter_identity TEXT,\n installed_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY (agent_id, package_kind, package_source, package_ref, package_version)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS claw_cron_refs (\n agent_id TEXT NOT NULL,\n manifest_id TEXT NOT NULL,\n schema_version TEXT NOT NULL,\n declaration_key TEXT NOT NULL UNIQUE,\n scheduler_job_id TEXT UNIQUE,\n status TEXT NOT NULL,\n job_json TEXT NOT NULL,\n error TEXT,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY (agent_id, manifest_id)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS claw_mcp_server_refs (\n agent_id TEXT NOT NULL,\n name TEXT NOT NULL,\n schema_version TEXT NOT NULL,\n config_digest TEXT NOT NULL,\n relationship TEXT NOT NULL CHECK (relationship IN ('managed', 'referenced')),\n origin TEXT NOT NULL CHECK (origin IN ('claw-introduced', 'pre-existing')),\n independent_owner INTEGER NOT NULL DEFAULT 0 CHECK (independent_owner IN (0, 1)),\n status TEXT NOT NULL,\n error TEXT,\n created_at_ms INTEGER NOT NULL,\n updated_at_ms INTEGER NOT NULL,\n PRIMARY KEY (agent_id, name)\n) STRICT;\n\nCREATE TABLE IF NOT EXISTS user_profile_identities (\n provider TEXT NOT NULL,\n subject TEXT NOT NULL,\n profile_id TEXT NOT NULL,\n canonical_login TEXT,\n created_at INTEGER NOT NULL,\n authorization_id TEXT,\n authorization_basis_json TEXT,\n PRIMARY KEY (provider, subject)\n) STRICT;\nCREATE INDEX IF NOT EXISTS idx_user_profile_identities_profile_id\n ON user_profile_identities(profile_id);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_user_profile_identities_authorization\n ON user_profile_identities(authorization_id);\n\nCREATE TABLE IF NOT EXISTS outbound_media_provenance (\n realpath TEXT NOT NULL PRIMARY KEY,\n kind TEXT NOT NULL,\n version INTEGER NOT NULL,\n sha256 TEXT NOT NULL,\n size_bytes INTEGER NOT NULL,\n created_at_ms INTEGER NOT NULL\n) STRICT;\n\n-- scope_id is non-null because SQLite treats NULLs as distinct in unique indexes/PKs,\n-- which would allow duplicate team rows. This PK also avoids a rebuild for identity scope.\nCREATE TABLE IF NOT EXISTS secret_store_entries (\n scope_kind TEXT NOT NULL CHECK (scope_kind IN ('team', 'identity')),\n scope_id TEXT NOT NULL,\n name TEXT NOT NULL,\n value TEXT NOT NULL,\n kind TEXT NOT NULL CHECK (kind IN ('secret', 'env')),\n created_at_ms INTEGER NOT NULL CHECK (created_at_ms >= 0),\n updated_at_ms INTEGER NOT NULL CHECK (updated_at_ms >= 0),\n updated_by TEXT,\n deleted_at_ms INTEGER,\n allowed_hosts TEXT,\n CHECK ((scope_kind = 'team' AND scope_id = '') OR (scope_kind = 'identity' AND length(scope_id) > 0)),\n PRIMARY KEY (scope_kind, scope_id, name)\n) STRICT;\nCREATE INDEX IF NOT EXISTS secret_store_entries_live_idx\n ON secret_store_entries (scope_kind, scope_id, name) WHERE deleted_at_ms IS NULL;\n";
}));
//#endregion
//#region src/state/openclaw-state-db-operator-approval-migration.ts
function tableSql$1(db) {
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'operator_approvals'").get();
return typeof row?.sql === "string" ? row.sql : void 0;
}
function hasCanonicalOperatorApprovalKinds(db) {
if (!tableExists(db, "operator_approvals")) return true;
return /kind\s+text\s+not\s+null\s+check\s*\(\s*kind\s+in\s*\(\s*'exec'\s*,\s*'plugin'\s*,\s*'system-agent'\s*\)\s*\)/.test(tableSql$1(db)?.toLowerCase() ?? "");
}
function assertCanonicalOperatorApprovalKinds(db, pathname) {
if (!hasCanonicalOperatorApprovalKinds(db)) throw new SqliteSchemaMismatchError(`OpenClaw state database ${pathname} has a legacy operator approval schema; run openclaw doctor --fix to migrate it.`);
}
var init_openclaw_state_db_operator_approval_migration = __esmMin((() => {
init_sqlite_schema_issues();
init_sqlite_transaction();
init_openclaw_state_db_schema_helpers();
}));
//#endregion
//#region src/state/openclaw-state-db-legacy-backfills.ts
var init_openclaw_state_db_legacy_backfills = __esmMin((() => {
init_src$2();
init_number_coercion();
init_definition_hash();
init_kysely_sync();
init_sqlite_number();
init_sqlite_transaction();
init_openclaw_state_db_delivery_queue_backfill();
init_openclaw_state_db_operator_approval_migration();
init_openclaw_state_db_schema_helpers();
}));
//#endregion
//#region src/state/openclaw-state-db-schema-v13-widerow.ts
var init_openclaw_state_db_schema_v13_widerow = __esmMin((() => {
init_src$2();
init_sqlite_audit_record_kernel();
init_sqlite_post_commit();
init_subsystem();
init_openclaw_state_db_additive_columns();
init_openclaw_state_db_legacy_backfills();
init_openclaw_state_db_schema_helpers();
})), SQLITE_DATABASE_FILE_SUFFIXES;
var init_sqlite_files = __esmMin((() => {
init_subsystem();
init_boundary_file_read();
init_crypto_digest();
SQLITE_DATABASE_FILE_SUFFIXES = [
"",
"-wal",
"-shm",
"-journal"
];
SQLITE_DATABASE_FILE_SUFFIXES.slice(1);
Buffer.from([
0,
5,
22,
7
]);
createSubsystemLogger("state/sqlite");
}));
//#endregion
//#region src/infra/sqlite-snapshot-source.ts
function prepareSqliteReadOnlyLocationSync(pathname) {
const stagingRoot = createSqliteSnapshotStagingDirectorySync();
try {
return adoptPreparedLocation(runSqliteReadOnlyWorkerSync(pathname, stagingRoot), stagingRoot);
} catch (error) {
if (!removeTempDirectory(stagingRoot)) throw new SqliteSnapshotCleanupError(`${coerceErrorMessage(error)}; SQLite snapshot cleanup failed: ${stagingRoot}`, { cause: error });
throw error;
}
}
var init_sqlite_snapshot_source = __esmMin((() => {
init_error_coercion();
init_sqlite_live_snapshot();
init_sqlite_readonly_location_cleanup();
init_sqlite_readonly_worker();
init_sqlite_snapshot_single_flight();
init_sqlite_snapshot_staging();
}));
//#endregion
//#region src/state/openclaw-state-ownership-worker.ts
var init_openclaw_state_ownership_worker = __esmMin((() => {
init_runtime_process_url();
init_runtime_worker_generation();
init_runtime_worker_url();
init_sqlite_readonly_worker();
init_openclaw_state_worker_error();
}));
//#endregion
//#region src/state/openclaw-state-ownership.ts
function parseExternalOwnership(valueJson, databasePath) {
let value;
try {
value = JSON.parse(valueJson);
} catch {
throw new OpenClawStateOwnershipMetadataError(databasePath, "reserved value is not valid JSON");
}
const record = isRecord(value) ? value : void 0;
const keys = record ? Object.keys(record).toSorted().join(",") : "";
const managerId = record?.managerId;
const claimedAt = record?.claimedAt;
if (keys !== "claimedAt,managerId,mode,version" || record?.version !== 1 || record?.mode !== "external" || typeof managerId !== "string" || !MANAGER_ID_PATTERN.test(managerId) || typeof claimedAt !== "number" || !Number.isSafeInteger(claimedAt) || claimedAt < 0 || claimedAt > MAX_OWNERSHIP_TIMESTAMP_MS) throw new OpenClawStateOwnershipMetadataError(databasePath, "reserved value does not match the version 1 external ownership contract");
return {
version: 1,
mode: "external",
managerId,
claimedAt
};
}
/** Inspect the reserved ownership row without entering the shared-state lifecycle. */
function inspectOpenClawStateOwnershipFromDatabase(database, databasePath, configMachineStateTableReady = false) {
try {
if (!configMachineStateTableReady && !tableExists(database, "config_machine_state")) return null;
const ownershipSql = configMachineStateTableReady ? "SELECT value_json FROM config_machine_state WHERE state_key = ? LIMIT 1" : "SELECT value_json FROM config_machine_state NOT INDEXED WHERE state_key = ? LIMIT 1";
const row = database.prepare(ownershipSql).get(STATE_SUPERVISION_KEY);
if (!row) return null;
if (typeof row.value_json !== "string") throw new OpenClawStateOwnershipMetadataError(databasePath, "reserved value is not text");
return parseExternalOwnership(row.value_json, databasePath);
} catch (error) {
throw normalizeOpenClawStateSchemaReadError(error, databasePath);
}
}
function assertOwnershipAllowsWrite(status, databasePath, env) {
if (status && !isGatewayExternallySupervised(env)) throw new OpenClawStateExternalOwnershipError(databasePath, status.managerId);
}
/** Fence shared-state writes once an external manager has claimed ownership. */
function assertOpenClawStateWriteAllowed(options) {
const resolvedPath = path.resolve(options.databasePath);
assertStateDatabaseAccessAllowed(resolvedPath);
assertOwnershipAllowsWrite(inspectOpenClawStateOwnershipFromDatabase(options.database, resolvedPath, options.schemaReady), resolvedPath, options.env ?? process.env);
}
var STATE_SUPERVISION_KEY, MAX_OWNERSHIP_TIMESTAMP_MS, MANAGER_ID_PATTERN;
var init_openclaw_state_ownership = __esmMin((() => {
init_record_coerce();
init_gateway_state_owner();
init_gateway_supervision();
init_node_sqlite();
init_sqlite_error_diagnostics();
init_sqlite_files();
init_sqlite_lifecycle_errors();
init_sqlite_readonly_location();
init_sqlite_snapshot_source();
init_sqlite_source_handle();
init_sqlite_transaction();
init_state_database_maintenance();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_contract();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_migration_required();
init_openclaw_state_ownership_worker();
STATE_SUPERVISION_KEY = "gateway.supervision";
MAX_OWNERSHIP_TIMESTAMP_MS = 864e13;
MANAGER_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;
}));
//#endregion
//#region src/state/openclaw-state-schema-compatibility.ts
/** Project canonical SQL to the tables the shared runtime may create during this open. */
function getOpenClawStateRuntimeSchema(options) {
const { includeVersionLazyAdditiveTables, includeAgentDeletionJournal = true } = options;
const key = `${includeVersionLazyAdditiveTables}:${includeAgentDeletionJournal}`;
const cached = runtimeSchemaCache.get(key);
if (cached !== void 0) return cached;
let schema = OPENCLAW_STATE_SCHEMA_SQL;
const omittedTables = [...includeVersionLazyAdditiveTables ? FIRST_USE_STATE_TABLES : LAZY_ADDITIVE_STATE_TABLES, ...includeAgentDeletionJournal ? [] : DOCTOR_OWNED_STATE_TABLES];
const omittedIndexes = includeVersionLazyAdditiveTables ? FIRST_USE_STATE_INDEXES : LAZY_ADDITIVE_STATE_INDEXES;
for (const tableName of omittedTables) {
const start = schema.indexOf(`CREATE TABLE IF NOT EXISTS ${tableName} (`);
const end = start >= 0 ? schema.indexOf("\n) STRICT;", start) : -1;
if (start < 0 || end < 0) throw new Error(`lazy additive state schema block is missing for ${tableName}`);
schema = `${schema.slice(0, start)}${schema.slice(end + 10)}`;
}
for (const indexName of omittedIndexes) {
const plainStart = schema.indexOf(`CREATE INDEX IF NOT EXISTS ${indexName}`);
const uniqueStart = schema.indexOf(`CREATE UNIQUE INDEX IF NOT EXISTS ${indexName}`);
const start = plainStart >= 0 ? plainStart : uniqueStart;
const end = start >= 0 ? schema.indexOf(";", start) : -1;
if (start < 0 || end < 0) throw new Error(`lazy additive state schema index is missing for ${indexName}`);
schema = `${schema.slice(0, start)}${schema.slice(end + 1)}`;
}
runtimeSchemaCache.set(key, schema);
return schema;
}
var CLAW_LAZY_ADDITIVE_STATE_COLUMNS, CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS, CLAW_STARTUP_ADDITIVE_STATE_TABLES, CLAW_READONLY_OPTIONAL_STATE_INDEXES, runtimeSchemaCache, STATE_PERSISTENT_SCHEMA_COMPATIBILITY, OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY;
var init_openclaw_state_schema_compatibility = __esmMin((() => {
init_sqlite_schema_contract();
init_openclaw_state_db_additive_columns();
init_openclaw_state_db_contract();
init_openclaw_state_schema();
CLAW_LAZY_ADDITIVE_STATE_COLUMNS = CLAW_LAZY_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ columnName, tableName }) => `${tableName}.${columnName}`);
CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS = CLAW_FIRST_USE_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ columnName, tableName }) => `${tableName}.${columnName}`);
new Set(CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS);
[...CLAW_STARTUP_ADDITIVE_STATE_COLUMN_DEFINITIONS.map(({ columnName, tableName }) => `${tableName}.${columnName}`), ...Object.values(ORDERED_STARTUP_ADDITIVE_STATE_COLUMNS).flat().map(([tableName, definition]) => `${tableName}.${definition.split(" ", 1)[0]}`)];
CLAW_STARTUP_ADDITIVE_STATE_TABLES = ["worker_session_tool_operations", "worker_turn_tool_authorities"];
new Set(CLAW_STARTUP_ADDITIVE_STATE_TABLES);
CLAW_READONLY_OPTIONAL_STATE_INDEXES = [
"idx_operator_approvals_source_run_resolved",
"idx_task_runs_requester_session_key",
"idx_worker_session_placements_environment"
];
runtimeSchemaCache = /* @__PURE__ */ new Map();
STATE_PERSISTENT_SCHEMA_COMPATIBILITY = {
allowCompatibleAdditiveColumns: true,
allowedMissingTables: DOCTOR_OWNED_STATE_TABLES,
allowedMissingColumns: CLAW_FIRST_USE_ADDITIVE_STATE_COLUMNS,
allowedColumnDefinitions: {
"diagnostic_events.sequence": ["sequence INTEGER NOT NULL DEFAULT 0"],
"claw_package_refs.package_integrity": ["package_integrity TEXT NOT NULL DEFAULT 'sha256:0000000000000000000000000000000000000000000000000000000000000000'"],
"claw_package_refs.updated_at_ms": ["updated_at_ms INTEGER NOT NULL DEFAULT 0"],
"cron_jobs.enabled": ["enabled INTEGER NOT NULL DEFAULT 1"],
"cron_jobs.name": ["name TEXT NOT NULL DEFAULT ''"],
"cron_jobs.payload_kind": ["payload_kind TEXT NOT NULL DEFAULT 'message'"],
"current_conversation_bindings.conversation_kind": ["conversation_kind TEXT NOT NULL DEFAULT 'channel'"],
"operator_approvals.resolution_ref": ["resolution_ref TEXT"],
"worker_environments.desktop_json": ["desktop_json TEXT"],
"worker_environments.bootstrap_install_kind": ["bootstrap_install_kind TEXT"],
"worker_environments.shared_host": ["shared_host INTEGER CHECK (shared_host IN (0, 1))"],
"worker_environments.node_setup_id": ["node_setup_id TEXT"],
"worker_environments.node_device_id": ["node_device_id TEXT"],
"worker_session_placements.terminal_reason": ["terminal_reason TEXT"],
"worker_session_placements.terminal_at_ms": ["terminal_at_ms INTEGER"]
}
};
OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY = {
...STATE_PERSISTENT_SCHEMA_COMPATIBILITY,
allowedMissingTables: [
...LAZY_ADDITIVE_STATE_TABLES,
...CLAW_STARTUP_ADDITIVE_STATE_TABLES,
...DOCTOR_OWNED_STATE_TABLES
],
allowedMissingIndexes: CLAW_READONLY_OPTIONAL_STATE_INDEXES,
allowedMissingColumns: CLAW_LAZY_ADDITIVE_STATE_COLUMNS
};
}));
//#endregion
//#region src/state/openclaw-state-schema-publication.ts
var init_openclaw_state_schema_publication = __esmMin((() => {
init_kysely_sync();
init_sqlite_schema_facts();
init_sqlite_user_version();
init_openclaw_state_db_contract();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_version();
}));
//#endregion
//#region src/state/openclaw-update-schema-refusal.ts
var init_openclaw_update_schema_refusal = __esmMin((() => {
init_errors$2();
}));
//#endregion
//#region src/state/openclaw-state-db-maintenance.ts
/** Require canonical shared-state ownership without requiring the latest schema. */
function assertOpenClawStateDatabaseOwner(database, options) {
const hasMetadataTable = database.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'schema_meta' LIMIT 1").get();
let metadata;
try {
metadata = hasMetadataTable ? database.prepare("SELECT role, schema_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1").get() : void 0;
} catch (error) {
throw classifySqliteTableReadError(database, "schema_meta", [
"meta_key",
"role",
"schema_version"
], error);
}
if (metadata?.role !== "global") {
const role = typeof metadata?.role === "string" ? metadata.role : "missing";
throw new SqliteSchemaMismatchError(`OpenClaw state database ${options.pathname} has schema role ${role}; expected global. Run openclaw doctor --fix to inspect and repair its ownership.`);
}
return metadata;
}
/** Require the canonical shared-state owner and schema before offline file maintenance. */
function assertOpenClawStateDatabaseForMaintenance(database, options, readTable) {
const userVersion = assertSupportedStateSchemaVersion(database, options.pathname);
if (readStateSchemaContentVersion(database) !== 19) throw new SqliteSchemaMismatchError(`OpenClaw state database ${options.pathname} uses schema version ${userVersion}; run openclaw doctor --fix before compacting it.`);
const metadata = assertOpenClawStateDatabaseOwner(database, options);
if (metadata?.schema_version !== userVersion) {
const schemaVersion = typeof metadata?.schema_version === "number" ? metadata.schema_version : "invalid";
throw new SqliteSchemaMismatchError(`OpenClaw state database ${options.pathname} metadata schema version ${schemaVersion} does not match ${userVersion}; run openclaw doctor --fix before compacting it.`);
}
assertSqliteSchemaContains(database, options.pathname, OPENCLAW_STATE_SCHEMA_SQL, OPENCLAW_STATE_MAINTENANCE_SCHEMA_COMPATIBILITY, readTable);
}
function assertOpenClawStateDatabaseVersionForMigration(database, options) {
const userVersion = readSqliteUserVersion(database);
if (readStateSchemaMigrationVersion(database) !== options.version) throw new SqliteSchemaMismatchError(`OpenClaw state database ${options.pathname} uses schema version ${userVersion}; expected ${options.version} before migrating it.`);
const metadata = assertOpenClawStateDatabaseOwner(database, options);
if (metadata?.schema_version !== userVersion) {
const schemaVersion = typeof metadata?.schema_version === "number" ? metadata.schema_version : "invalid";
throw new SqliteSchemaMismatchError(`OpenClaw state database ${options.pathname} metadata schema version ${schemaVersion} does not match ${userVersion}; repair the ownership metadata before migrating it.`);
}
assertSqliteSchemaTablesPresent(database, options.pathname, OPENCLAW_STATE_SCHEMA_SQL, { allowedMissingTables: [...STATE_MIGRATION_ALLOWED_MISSING_TABLES[options.version], ...DOCTOR_OWNED_STATE_TABLES] });
}
var STATE_V6_ADDITIVE_TABLES, STATE_MIGRATION_ALLOWED_MISSING_TABLES;
var init_openclaw_state_db_maintenance = __esmMin((() => {
init_kysely_sync();
init_sqlite_lifecycle_errors();
init_sqlite_schema_contract();
init_sqlite_schema_issues();
init_sqlite_transaction();
init_sqlite_user_version();
init_version$1();
init_openclaw_state_db_contract();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_v13_widerow();
init_openclaw_state_db_schema_version();
init_openclaw_state_db_paths();
init_openclaw_state_ownership();
init_openclaw_state_schema_compatibility();
init_openclaw_state_schema_publication();
init_openclaw_state_schema();
init_openclaw_update_schema_refusal();
STATE_V6_ADDITIVE_TABLES = [
"gateway_origin_device_tokens",
...LAZY_ADDITIVE_STATE_TABLES,
"worker_session_tool_operations",
"worker_turn_tool_authorities"
];
STATE_MIGRATION_ALLOWED_MISSING_TABLES = {
5: [
"agent_database_leases",
"agent_deletion_journal",
"claw_cron_refs",
"claw_installs",
"claw_mcp_server_refs",
"claw_package_refs",
"claw_workspace_files",
"config_machine_state",
"cron_job_scratch",
"meeting_transcript_sessions",
"meeting_transcript_summaries",
"meeting_transcript_utterances",
"outbound_media_provenance",
"worker_environment_credentials",
"worker_transcript_commit_heads",
"worker_transcript_commits",
...STATE_V6_ADDITIVE_TABLES
],
6: STATE_V6_ADDITIVE_TABLES,
7: STATE_V6_ADDITIVE_TABLES,
8: STATE_V6_ADDITIVE_TABLES,
9: STATE_V6_ADDITIVE_TABLES,
10: STATE_V6_ADDITIVE_TABLES,
11: STATE_V6_ADDITIVE_TABLES,
12: STATE_V6_ADDITIVE_TABLES,
13: LAZY_ADDITIVE_STATE_TABLES,
14: LAZY_ADDITIVE_STATE_TABLES,
15: LAZY_ADDITIVE_STATE_TABLES,
16: LAZY_ADDITIVE_STATE_TABLES,
17: LAZY_ADDITIVE_STATE_TABLES
};
new Map([
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17
].map((version) => [version, (database, options) => assertOpenClawStateDatabaseVersionForMigration(database, {
...options,
version
})]));
}));
//#endregion
//#region src/state/openclaw-state-db-audit-migration.ts
function tableColumnInfo(db, tableName) {
return db.prepare(`PRAGMA table_info(${tableName})`).all();
}
function tableHasExactColumns(db, tableName, expected) {
const names = tableColumnInfo(db, tableName).map((column) => column.name);
return names.length === expected.length && names.every((name, index) => name === expected[index]);
}
function tableHasRequiredColumns(db, tableName, required) {
const columns = new Map(tableColumnInfo(db, tableName).map((column) => [column.name, column]));
return required.every((name) => Number(columns.get(name)?.notnull ?? 0) === 1);
}
function tableSql(db, tableName) {
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(tableName);
return typeof row?.sql === "string" ? row.sql : void 0;
}
function tableHasUniqueColumn(db, tableName, columnName) {
return db.prepare(`PRAGMA index_list(${tableName})`).all().some((index) => {
if (Number(index.unique ?? 0) !== 1 || typeof index.name !== "string") return false;
const escaped = index.name.replaceAll("'", "''");
const columns = db.prepare(`PRAGMA index_info('${escaped}')`).all();
return columns.length === 1 && columns[0]?.name === columnName;
});
}
function hasCanonicalAuditEventTable(db, expectedColumns, requiredColumns) {
const sql = tableSql(db, "audit_events")?.toLowerCase();
return tableHasExactColumns(db, "audit_events", expectedColumns) && tablePrimaryKeyColumns(db, "audit_events").join(",") === "sequence" && tableHasRequiredColumns(db, "audit_events", requiredColumns) && typeof sql === "string" && /\bsequence\s+integer\s+primary\s+key\s+autoincrement\b/.test(sql) && tableHasUniqueColumn(db, "audit_events", "event_id") && tableHasUniqueColumn(db, "audit_events", "source_id");
}
function hasCanonicalAuditIdentityKeyTable(db) {
if (!tableExists(db, "audit_identity_keys")) return false;
const sql = tableSql(db, "audit_identity_keys")?.toLowerCase();
return tableHasExactColumns(db, "audit_identity_keys", [
"id",
"key_id",
"key",
"created_at"
]) && tablePrimaryKeyColumns(db, "audit_identity_keys").join(",") === "id" && tableHasRequiredColumns(db, "audit_identity_keys", [
"id",
"key_id",
"key",
"created_at"
]) && typeof sql === "string" && /\bcheck\s*\(\s*id\s*=\s*1\s*\)/.test(sql);
}
function hasCanonicalAuditEventsSchema(db) {
if (!tableExists(db, "audit_events")) return readSqliteUserVersion(db) < AUDIT_EVENT_STATE_SCHEMA_VERSION && !tableExists(db, "audit_identity_keys");
return hasCanonicalAuditEventTable(db, AUDIT_EVENT_V2_COLUMNS, [
"event_id",
"source_id",
"schema_version",
"source_sequence",
"occurred_at",
"kind",
"action",
"status",
"actor_type",
"actor_id"
]) && hasCanonicalAuditIdentityKeyTable(db);
}
function canRepairLegacyAuditEventsSchema(db) {
if (!tableExists(db, "audit_events") || tableExists(db, "audit_events_migration_new") || tableHasColumn(db, "audit_events", "schema_version")) return false;
return (!tableExists(db, "audit_identity_keys") || hasCanonicalAuditIdentityKeyTable(db)) && hasCanonicalAuditEventTable(db, AUDIT_EVENT_LEGACY_COLUMNS, [
"event_id",
"source_id",
"source_sequence",
"occurred_at",
"kind",
"action",
"status",
"actor_type",
"actor_id",
"agent_id",
"run_id"
]);
}
var AUDIT_EVENT_STATE_SCHEMA_VERSION, AUDIT_EVENT_LEGACY_COLUMNS, AUDIT_EVENT_V2_COLUMNS;
var init_openclaw_state_db_audit_migration = __esmMin((() => {
init_sqlite_user_version();
init_openclaw_state_db_schema_helpers();
AUDIT_EVENT_STATE_SCHEMA_VERSION = 2;
AUDIT_EVENT_LEGACY_COLUMNS = [
"sequence",
"event_id",
"source_id",
"source_sequence",
"occurred_at",
"kind",
"action",
"status",
"error_code",
"actor_type",
"actor_id",
"agent_id",
"session_key",
"session_id",
"run_id",
"tool_call_id",
"tool_name"
];
AUDIT_EVENT_V2_COLUMNS = [
"sequence",
"event_id",
"source_id",
"schema_version",
"source_sequence",
"occurred_at",
"kind",
"action",
"status",
"error_code",
"actor_type",
"actor_id",
"agent_id",
"session_key",
"session_id",
"run_id",
"tool_call_id",
"tool_name",
"direction",
"channel",
"conversation_kind",
"message_outcome",
"reason_code",
"delivery_kind",
"failure_stage",
"duration_ms",
"result_count",
"account_ref",
"conversation_ref",
"message_ref",
"target_ref"
];
}));
//#endregion
//#region src/state/openclaw-state-db-schema-v12-foldin.ts
var init_openclaw_state_db_schema_v12_foldin = __esmMin((() => {
init_openclaw_state_db_schema_helpers();
}));
//#endregion
//#region src/state/session-watch-cursor-provenance.ts
var SESSION_WATCH_PROVENANCE_EXPLICIT, SESSION_WATCH_PROVENANCE_AMBIENT_GROUP;
var init_session_watch_cursor_provenance = __esmMin((() => {
SESSION_WATCH_PROVENANCE_EXPLICIT = "explicit";
SESSION_WATCH_PROVENANCE_AMBIENT_GROUP = "ambient-group";
}));
var init_openclaw_state_db_session_watch_migration = __esmMin((() => {
init_kysely_sync();
init_openclaw_state_db_schema_helpers();
init_session_watch_cursor_provenance();
`${SESSION_WATCH_PROVENANCE_EXPLICIT}${SESSION_WATCH_PROVENANCE_EXPLICIT}${SESSION_WATCH_PROVENANCE_AMBIENT_GROUP}`;
})), RETIRED_COMMITMENTS_COLUMNS_SQL, RETIRED_COMMITMENTS_BASE_INDEXES_SQL;
var init_openclaw_state_db_table_retirements = __esmMin((() => {
init_sqlite_schema_contract();
init_subsystem();
init_openclaw_state_db_schema_helpers();
createSubsystemLogger("state/db");
RETIRED_COMMITMENTS_COLUMNS_SQL = `
id TEXT NOT NULL PRIMARY KEY,
agent_id TEXT NOT NULL,
session_key TEXT NOT NULL,
channel TEXT NOT NULL,
account_id TEXT,
recipient_id TEXT,
thread_id TEXT,
sender_id TEXT,
kind TEXT NOT NULL,
sensitivity TEXT NOT NULL,
source TEXT NOT NULL,
status TEXT NOT NULL,
reason TEXT NOT NULL,
suggested_text TEXT NOT NULL,
dedupe_key TEXT NOT NULL,
confidence REAL NOT NULL,
due_earliest_ms INTEGER NOT NULL,
due_latest_ms INTEGER NOT NULL,
due_timezone TEXT NOT NULL,
source_message_id TEXT,
source_run_id TEXT,
created_at_ms INTEGER NOT NULL,
updated_at_ms INTEGER NOT NULL,
attempts INTEGER NOT NULL,
last_attempt_at_ms INTEGER,
sent_at_ms INTEGER,
dismissed_at_ms INTEGER,
snoozed_until_ms INTEGER,
expired_at_ms INTEGER,
record_json TEXT NOT NULL
`;
RETIRED_COMMITMENTS_BASE_INDEXES_SQL = `CREATE INDEX idx_commitments_scope_due
ON commitments(agent_id, session_key, status, due_earliest_ms, due_latest_ms);
CREATE INDEX idx_commitments_status_due
ON commitments(status, due_earliest_ms, due_latest_ms);
CREATE INDEX idx_commitments_scope_dedupe
ON commitments(agent_id, session_key, channel, dedupe_key, status);`;
`${RETIRED_COMMITMENTS_COLUMNS_SQL.slice(1, -1)}${RETIRED_COMMITMENTS_BASE_INDEXES_SQL}`;
`${RETIRED_COMMITMENTS_COLUMNS_SQL.slice(1, -1)}${RETIRED_COMMITMENTS_BASE_INDEXES_SQL}`;
}));
//#endregion
//#region src/state/openclaw-state-db-schema-repair.ts
function hasCanonicalAgentDatabasesPrimaryKey(db) {
if (!tableExists(db, "agent_databases")) return true;
const primaryKey = tablePrimaryKeyColumns(db, "agent_databases");
return primaryKey.length === 2 && primaryKey[0] === "agent_id" && primaryKey[1] === "path";
}
function canRepairAgentDatabasesPrimaryKey(db) {
if (!tableExists(db, "agent_databases")) return false;
return [
"agent_id",
"path",
"schema_version",
"last_seen_at",
"size_bytes"
].every((column) => tableHasColumn(db, "agent_databases", column));
}
function assertCanonicalStateSchemaShape(db, pathname) {
assertCanonicalOperatorApprovalKinds(db, pathname);
if (!hasCanonicalAgentDatabasesPrimaryKey(db)) {
if (canRepairAgentDatabasesPrimaryKey(db)) throw new OpenClawStateDatabaseSchemaMigrationRequiredError("agent-databases-composite-primary-key", pathname);
throw new SqliteSchemaMismatchError(`OpenClaw state database ${pathname} has a noncanonical agent database registry schema that cannot be repaired automatically; restore the canonical agent_databases shape before retrying.`);
}
if (!hasCanonicalAuditEventsSchema(db)) {
if (canRepairLegacyAuditEventsSchema(db)) throw new OpenClawStateDatabaseSchemaMigrationRequiredError("audit-events-v2", pathname);
throw new SqliteSchemaMismatchError(`OpenClaw state database ${pathname} has a noncanonical audit event schema that cannot be repaired automatically; restore the canonical audit_events shape before retrying.`);
}
}
var init_openclaw_state_db_schema_repair = __esmMin((() => {
init_node_sqlite();
init_sqlite_schema_issues();
init_openclaw_state_db_audit_migration();
init_openclaw_state_db_contract();
init_openclaw_state_db_operator_approval_migration();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_migration_required();
init_openclaw_state_db_schema_v12_foldin();
init_openclaw_state_db_schema_version();
init_openclaw_state_db_session_watch_migration();
init_openclaw_state_db_table_retirements();
init_openclaw_state_db_paths();
}));
//#endregion
//#region src/state/openclaw-state-db-fast-path.ts
function assertCurrentStateRuntimeSchema(database, pathname, readTable) {
assertCanonicalStateSchemaShape(database, pathname);
assertOpenClawStateDatabaseForMaintenance(database, { pathname }, readTable);
}
/** Catalog presence is enough to refuse retired history without reading or rewriting its rows. */
function assertNoLegacyStateRuntimeRepair(database, pathname) {
if (hasLegacyCronRunLogs(database)) throw new OpenClawStateDatabaseSchemaMigrationRequiredError("legacy-cron-run-logs", pathname);
}
var init_openclaw_state_db_fast_path = __esmMin((() => {
init_node_sqlite();
init_sqlite_integrity();
init_sqlite_schema_contract();
init_sqlite_transaction();
init_state_migrations_cron_run_logs();
init_openclaw_state_db_contract();
init_openclaw_state_db_maintenance();
init_openclaw_state_db_schema_migration_required();
init_openclaw_state_db_schema_repair();
init_openclaw_state_db_schema_version();
init_openclaw_state_schema_compatibility();
}));
//#endregion
//#region src/state/openclaw-state-db-existing-schema.ts
/** Prove the existing runtime contract without certifying this release's repairs. */
function assertExistingOpenClawStateRuntimeSchema(database, pathname) {
const schemaCookie = runSqliteDeferredTransactionSync(database, () => {
const version = assertSupportedStateSchemaVersion(database, pathname);
if (readStateSchemaMigrationVersion(database) !== 19) throw new Error(`Existing shared-state database ${pathname} requires schema migration by its owning installation before this node can use it.`);
let metadata;
try {
metadata = executeSqliteQueryTakeFirstSync(database, getNodeSqliteKysely(database).selectFrom("schema_meta").select(["role", "schema_version"]).where("meta_key", "=", "primary").limit(1));
} catch (error) {
throw classifySqliteTableReadError(database, "schema_meta", [
"meta_key",
"role",
"schema_version"
], error);
}
if (metadata?.role !== "global" || metadata.schema_version !== version) throw new Error(`Existing shared-state database ${pathname} has inconsistent ownership or schema metadata.`);
const currentCookie = readSqliteSchemaCookie(database);
if (typeof currentCookie !== "number") throw new Error(`Existing shared-state database ${pathname} schema version is unavailable.`);
const cached = validatedSchemas.get(database);
if (cached?.cookie !== currentCookie) {
cached?.unregister();
validatedSchemas.delete(database);
assertSqliteIntegrity(database, pathname);
const readTable = createSqliteTableContractReader(database);
assertCurrentStateRuntimeSchema(database, pathname, readTable);
assertNoLegacyStateRuntimeRepair(database, pathname);
assertSqliteSchemaContains(database, pathname, getOpenClawStateRuntimeSchema({ includeVersionLazyAdditiveTables: false }), STATE_PERSISTENT_SCHEMA_COMPATIBILITY, readTable);
}
return currentCookie;
});
if (!database.isTransaction && validatedSchemas.get(database)?.cookie !== schemaCookie) {
const unregister = registerNodeSqliteDisposeCallback(database, () => {
validatedSchemas.delete(database);
unregister();
});
validatedSchemas.set(database, {
cookie: schemaCookie,
unregister
});
}
}
var validatedSchemas;
var init_openclaw_state_db_existing_schema = __esmMin((() => {
init_kysely_sync_cache_state();
init_kysely_sync();
init_sqlite_integrity();
init_sqlite_schema_contract();
init_sqlite_transaction();
init_openclaw_state_db_contract();
init_openclaw_state_db_fast_path();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_version();
init_openclaw_state_schema_compatibility();
validatedSchemas = /* @__PURE__ */ new WeakMap();
}));
//#endregion
//#region src/infra/fs-safe.ts
var init_fs_safe = __esmMin((() => {}));
//#endregion
//#region src/infra/directory-durability.ts
/** Require a real directory sync at product commit boundaries. */
function requireDirectorySync(outcome, label) {
if (outcome.status !== "unsupported" || process.platform === "win32") return;
const code = outcome.code ? ` (${outcome.code})` : "";
throw new Error(`${label} does not support crash-durable directory synchronization${code}.`);
}
var init_directory_durability = __esmMin((() => {
init_fs_safe();
}));
//#endregion
//#region src/state/openclaw-state-db-task-delivery-recovery.ts
function orphanRows(database) {
const statement = database.prepare(`SELECT rowid, * FROM task_delivery_state
WHERE ${ORPHAN_PREDICATE} ORDER BY rowid`);
statement.setReadBigInts(true);
return statement.iterate();
}
function encodeOrphanRow(row) {
if (typeof row.rowid !== "bigint" || typeof row.task_id !== "string" || row.requester_origin_json !== null && typeof row.requester_origin_json !== "string" || row.last_notified_event_at !== null && typeof row.last_notified_event_at !== "bigint") throw new Error("Orphan task delivery values do not match the supported recovery contract.");
return `${JSON.stringify(row, (_key, value) => typeof value === "bigint" ? value.toString() : value)}\n`;
}
function assertRecoveryShape(database) {
const columns = database.prepare("PRAGMA table_xinfo(task_delivery_state)").all();
const expected = [
{
cid: 0,
name: "task_id",
type: "TEXT",
notnull: 1,
dflt_value: null,
pk: 1,
hidden: 0
},
{
cid: 1,
name: "requester_origin_json",
type: "TEXT",
notnull: 0,
dflt_value: null,
pk: 0,
hidden: 0
},
{
cid: 2,
name: "last_notified_event_at",
type: "INTEGER",
notnull: 0,
dflt_value: null,
pk: 0,
hidden: 0
}
];
const foreignKeys = database.prepare("PRAGMA foreign_key_list(task_delivery_state)").all();
const canonicalForeignKey = [{
id: 0,
seq: 0,
table: "task_runs",
from: "task_id",
to: "task_id",
on_update: "NO ACTION",
on_delete: "CASCADE",
match: "NONE"
}];
const triggers = database.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'trigger' AND tbl_name = 'task_delivery_state'").get();
if (JSON.stringify(columns) !== JSON.stringify(expected) || JSON.stringify(foreignKeys) !== JSON.stringify(canonicalForeignKey) || triggers) throw new Error("Orphan task delivery recovery refused an unrecognized table, foreign key, or trigger.");
}
function assertKnownOrphanIntegrity(database) {
try {
assertSqliteIntegrity(database, "task delivery recovery database");
return 0;
} catch (error) {
if (error instanceof SqliteRepairableForeignKeyError) return error.repair.orphanCount;
throw error;
}
}
function syncAndHash(filePath) {
const descriptor = fs.openSync(filePath, "r+");
try {
fs.fsyncSync(descriptor);
return hashFileDescriptorSync(descriptor);
} finally {
fs.closeSync(descriptor);
}
}
/**
* Caller holds Doctor's ownership/schema fences and its immediate write transaction.
* Foreign-key actions stay disabled: inbound dependents must fail the post-check,
* never cascade into unrelated data. The caller rolls back any failed check.
*/
function recoverOrphanTaskDeliveryRows(database, pathname) {
if (!tableExists(database, "task_delivery_state") || !tableExists(database, "task_runs") || !database.prepare(`SELECT 1 FROM task_delivery_state WHERE ${ORPHAN_PREDICATE} LIMIT 1`).get()) return [];
assertOpenClawStateDatabaseOwner(database, { pathname });
assertRecoveryShape(database);
const count = assertKnownOrphanIntegrity(database);
if (!database.isTransaction) throw new Error("Orphan task delivery recovery requires the Doctor write transaction.");
const prepared = prepareSqliteReadOnlyLocationSync(pathname);
let recoveryDirectory;
try {
const snapshot = openNodeSqliteDatabase(prepared.location);
try {
snapshot.exec("PRAGMA journal_mode = DELETE;");
assertRecoveryShape(snapshot);
if (assertKnownOrphanIntegrity(snapshot) !== count) throw new Error("Orphan task delivery snapshot changed before preservation.");
const sourceHash = createHash("sha256");
const snapshotHash = createHash("sha256");
for (const row of orphanRows(database)) sourceHash.update(encodeOrphanRow(row));
for (const row of orphanRows(snapshot)) snapshotHash.update(encodeOrphanRow(row));
if (sourceHash.digest("hex") !== snapshotHash.digest("hex")) throw new Error("Orphan task delivery snapshot does not preserve the current payload.");
} finally {
snapshot.close();
}
recoveryDirectory = createPrivateSqliteTempDirectorySync(path.dirname(pathname), "openclaw-task-delivery-recovery-");
const backupPath = path.join(recoveryDirectory, "database.sqlite");
const expectedBackup = syncAndHash(prepared.location);
fs.copyFileSync(prepared.location, backupPath, fs.constants.COPYFILE_EXCL);
fs.chmodSync(backupPath, 384);
if (JSON.stringify(syncAndHash(backupPath)) !== JSON.stringify(expectedBackup)) throw new Error("Orphan task delivery backup verification failed.");
const exportPath = path.join(recoveryDirectory, "orphan-rows.jsonl");
const exportDescriptor = fs.openSync(exportPath, "wx+", 384);
const exportHash = createHash("sha256");
let exportedCount = 0;
try {
for (const row of orphanRows(database)) {
const encoded = encodeOrphanRow(row);
fs.writeFileSync(exportDescriptor, encoded);
exportHash.update(encoded);
exportedCount += 1;
}
fs.fsyncSync(exportDescriptor);
if (hashFileDescriptorSync(exportDescriptor).sha256 !== exportHash.digest("hex")) throw new Error("Orphan task delivery export verification failed.");
} finally {
fs.closeSync(exportDescriptor);
}
if (exportedCount !== count) throw new Error("Orphan task delivery export did not account for every foreign-key violation.");
fs.writeFileSync(path.join(recoveryDirectory, "manifest.json"), JSON.stringify({
format: "openclaw.task-delivery-recovery.v1",
state: "preserved-before-repair",
sourcePath: pathname,
backup: {
file: "database.sqlite",
...expectedBackup,
integrity: "structural-ok-known-orphans"
},
export: {
file: "orphan-rows.jsonl",
...syncAndHash(exportPath),
count,
integerEncoding: "decimal-string"
},
relation: "task_delivery_state.task_id -> task_runs.task_id",
createdAt: (/* @__PURE__ */ new Date()).toISOString()
}, null, 2), {
flag: "wx",
mode: 384,
flush: true
});
requireDirectorySync(syncDirectorySync(recoveryDirectory), "Task delivery recovery directory");
requireDirectorySync(syncDirectorySync(path.dirname(recoveryDirectory)), "Task delivery recovery parent");
const removed = database.prepare(`DELETE FROM task_delivery_state WHERE ${ORPHAN_PREDICATE}`).run();
if (Number(removed.changes) !== count) throw new Error("Orphan task delivery recovery removed an unexpected number of rows.");
assertSqliteIntegrity(database, pathname);
return [`Preserved and recovered ${count} orphan task delivery rows; backup and row export: ${recoveryDirectory}`];
} catch (error) {
throw new Error(`Task delivery recovery failed without committing row removal${recoveryDirectory ? `; retained artifacts: ${recoveryDirectory}` : ""}: ${String(error)}`, { cause: error });
} finally {
prepared.cleanup();
}
}
var ORPHAN_PREDICATE;
var init_openclaw_state_db_task_delivery_recovery = __esmMin((() => {
init_directory_durability();
init_file_descriptor();
init_node_sqlite();
init_sqlite_integrity();
init_sqlite_private_directory();
init_sqlite_snapshot_source();
init_openclaw_state_db_maintenance();
init_openclaw_state_db_schema_helpers();
ORPHAN_PREDICATE = "NOT EXISTS (SELECT 1 FROM task_runs WHERE task_runs.task_id = task_delivery_state.task_id)";
}));
//#endregion
//#region src/state/openclaw-state-db-transaction.ts
function runManagedStateTransaction(database, operation, options) {
if (database.isTransaction && !managedStateTransactions.has(database)) throw new Error("Cannot join an unmanaged shared-state transaction; enter through runOpenClawStateWriteTransaction before BEGIN.");
const transaction = () => withSqlitePostCommitPublications(database, () => {
const outer = !database.isTransaction;
if (outer) managedStateTransactions.add(database);
try {
return runSqliteImmediateTransactionSync(database, operation, options);
} finally {
if (outer) managedStateTransactions.delete(database);
}
});
return options.busyTimeoutMs === void 0 ? transaction() : runWithSqliteBusyTimeout(database, options.busyTimeoutMs, transaction);
}
var managedStateTransactions;
var init_openclaw_state_db_transaction = __esmMin((() => {
init_sqlite_busy_timeout();
init_sqlite_post_commit();
init_sqlite_transaction();
init_global_singleton();
managedStateTransactions = resolveGlobalSingleton(Symbol.for("openclaw.managedStateTransactions"), () => /* @__PURE__ */ new WeakSet());
}));
//#endregion
//#region src/state/openclaw-state-db-existing-write.ts
/** Validate only the stable storage subset used by an existing-schema owner.
* This read neither repairs nor grants write authority; callers retain their
* actual handle, generation, lease and publication checks. */
function assertExistingOpenClawStateSchema(db, pathname, schemaSql) {
const version = assertSupportedStateSchemaVersion(db, pathname);
const metadata = assertOpenClawStateDatabaseOwner(db, { pathname });
if (version < 1 || metadata?.schema_version !== version) throw new Error("Existing-state schema metadata is inconsistent.");
assertSqliteIntegrity(db, pathname);
assertSqliteSchemaContains(db, pathname, schemaSql);
return version;
}
/** A synchronous write to an already-compatible, caller-owned schema subset.
* No database bootstrap, schema repair, journal-mode setup, cached publication or WAL timer.
* First-use owners may install their declared additive tables; existing objects
* must already match. This never opens or migrates the full runtime schema.
* The admitted native connection owns transaction serialization.
*/
function runExistingOpenClawStateWriteTransaction(operation, options, contract) {
if (options.database || options.readOnly) throw new Error("Existing-state writes require their own tracked writable connection.");
const env = options.env ?? process.env;
const busyTimeoutMs = contract.busyTimeoutMs ?? 5e3;
const pathname = path.resolve(options.path ?? resolveOpenClawStateSqlitePath(env));
const existingSchema = isExistingOpenClawStateSchema(pathname);
if (contract.recoverTaskDeliveryOrphans) assertOpenClawStateSchemaRepairAllowed(pathname);
const original = fs.lstatSync(pathname);
if (!original.isFile()) throw new Error("Existing-state write requires a regular database file.");
const assertSameFile = () => {
const current = fs.lstatSync(pathname);
if (!current.isFile() || current.dev !== original.dev || current.ino !== original.ino) throw new Error("Existing-state database generation changed.");
};
const write = () => {
assertSameFile();
openClawStateDatabaseCache.assertOpenClawStateDatabaseFreshOpenAllowedAtPath(pathname, env);
const db = openTrackedStateDatabase(pathname, {
existingOnly: true,
...contract.recoverTaskDeliveryOrphans ? { enableForeignKeyConstraints: false } : {}
});
try {
setSqliteBusyTimeout(db, busyTimeoutMs);
return runManagedStateTransaction(db, () => {
assertSameFile();
assertOpenClawStateWriteAllowed({
database: db,
databasePath: pathname,
env
});
if (existingSchema) assertExistingOpenClawStateRuntimeSchema(db, pathname);
const validate = () => assertExistingOpenClawStateSchema(db, pathname, contract.initializeAdditiveSchema ? "" : contract.schemaSql);
let version;
let recoveryChanges = [];
try {
version = validate();
} catch (error) {
if (!contract.recoverTaskDeliveryOrphans || !(error instanceof SqliteRepairableForeignKeyError)) throw error;
recoveryChanges = recoverOrphanTaskDeliveryRows(db, pathname);
version = validate();
}
if (contract.initializeAdditiveSchema) {
assertSqliteSchemaContains(db, pathname, contract.schemaSql, { allowedMissingTables: getCanonicalSqliteTableNames(contract.schemaSql) });
db.exec(contract.schemaSql);
assertSqliteSchemaContains(db, pathname, contract.schemaSql);
}
const schemaVersion = readSqliteSchemaCookie(db);
const result = operation({
db,
path: pathname,
recoveryChanges
});
assertSameFile();
if (readSqliteUserVersion(db) !== version || readSqliteSchemaCookie(db) !== schemaVersion) throw new Error("Existing-state transaction cannot migrate schema.");
if (contract.recoverTaskDeliveryOrphans) assertSqliteIntegrity(db, pathname);
return result;
}, {
busyTimeoutMs,
databaseLabel: pathname,
operationLabel: contract.operationLabel
});
} finally {
clearNodeSqliteKyselyCacheForDatabase(db);
closeTrackedStateDatabase(db);
}
};
return contract.recoverTaskDeliveryOrphans ? withStateDatabaseSchemaMaintenance({ databasePath: pathname }, write) : write();
}
var init_openclaw_state_db_existing_write = __esmMin((() => {
init_kysely_sync_cache_state();
init_sqlite_busy_timeout();
init_sqlite_integrity();
init_sqlite_schema_contract();
init_sqlite_user_version();
init_state_database_maintenance();
init_openclaw_state_db_cache();
init_openclaw_state_db_contract();
init_openclaw_state_db_existing_schema();
init_openclaw_state_db_handle();
init_openclaw_state_db_maintenance();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_schema_version();
init_openclaw_state_db_task_delivery_recovery();
init_openclaw_state_db_transaction();
init_openclaw_state_db_paths();
init_openclaw_state_ownership();
}));
//#endregion
//#region src/config/model-policy-allowlist-migration.ts
var init_model_policy_allowlist_migration = __esmMin((() => {
init_utils();
}));
//#endregion
//#region src/agents/agent-dir-registry.ts
var init_agent_dir_registry = __esmMin((() => {
init_boundary_path();
init_path_guards();
init_session_key();
init_utils();
}));
//#endregion
//#region src/agents/agent-roster.ts
var init_agent_roster = __esmMin((() => {
init_session_key();
}));
//#endregion
//#region src/agents/workspace-default-path.ts
/**
* Default agent workspace resolver.
*
* Derives the process workspace directory from env, profile, and home-directory state.
*/
/** Resolve the default agent workspace directory from env/profile/home state. */
function resolveDefaultAgentWorkspaceDir(env = process.env, homedir = os.homedir) {
const workspaceDir = env.OPENCLAW_WORKSPACE_DIR?.trim();
if (workspaceDir) return path.resolve(workspaceDir);
if (env.OPENCLAW_STATE_DIR?.trim()) return path.join(resolveStateDir(env, homedir), "workspace");
const home = resolveRequiredHomeDir(env, homedir);
const profile = env.OPENCLAW_PROFILE?.trim();
if (profile && normalizeOptionalLowercaseString(profile) !== "default") return path.join(resolveProfileStateDir(profile, env, homedir), "workspace");
return path.join(home, ".openclaw", "workspace");
}
var init_workspace_default_path = __esmMin((() => {
init_string_coerce();
init_profile_utils();
init_state_dir();
init_home_dir();
}));
var init_workspace_default = __esmMin((() => {
init_workspace_default_path();
resolveDefaultAgentWorkspaceDir();
}));
//#endregion
//#region src/agents/agent-scope-config.ts
var init_agent_scope_config = __esmMin((() => {
init_model_policy_allowlist_migration();
init_paths$1();
init_session_key();
init_utils();
init_agent_dir_registry();
init_agent_roster();
init_workspace_default();
}));
//#endregion
//#region src/config/resolution-facts.ts
var init_resolution_facts = __esmMin((() => {
init_types_secrets();
}));
//#endregion
//#region src/config/io.read-helpers.ts
var init_io_read_helpers = __esmMin((() => {
init_crypto_digest();
init_env();
init_errno();
init_errors$2();
init_config_env_vars();
init_env_substitution();
init_includes();
init_paths$1();
init_resolution_facts();
}));
//#endregion
//#region src/infra/zstd-codec.ts
/** Resolve the process runtime once; persisted readers must reject unsupported compressed data. */
function resolveZstdCodec() {
if (resolvedCodec !== void 0) return resolvedCodec;
if (typeof zlib.zstdCompressSync !== "function" || typeof zlib.zstdDecompressSync !== "function") {
resolvedCodec = null;
return resolvedCodec;
}
const compress = zlib.zstdCompressSync.bind(zlib);
const decompress = zlib.zstdDecompressSync.bind(zlib);
resolvedCodec = {
compress: (data, level, checksum) => {
if (level === void 0 && checksum === void 0) return compress(data);
return compress(data, { params: {
...level === void 0 ? {} : { [zlib.constants.ZSTD_c_compressionLevel]: level },
...checksum === void 0 ? {} : { [zlib.constants.ZSTD_c_checksumFlag]: checksum }
} });
},
decompress: (data, maxOutputLength) => decompress(data, maxOutputLength === void 0 ? void 0 : { maxOutputLength })
};
return resolvedCodec;
}
var resolvedCodec;
var init_zstd_codec = __esmMin((() => {}));
var init_archive_compression = __esmMin((() => {
init_zstd_codec();
resolveZstdCodec();
}));
//#endregion
//#region src/config/sessions/artifacts.ts
var init_artifacts = __esmMin((() => {
init_number_coercion();
init_archive_compression();
}));
//#endregion
//#region src/config/sessions/paths.ts
var init_paths = __esmMin((() => {
init_boundary_path();
init_session_key();
init_openclaw_agent_db_paths();
init_artifacts();
}));
//#endregion
//#region src/config/sessions/session-sqlite-target-paths.ts
var init_session_sqlite_target_paths = __esmMin((() => {
init_errno();
}));
//#endregion
//#region src/config/sessions/targets-configured-agents.ts
var init_targets_configured_agents = __esmMin((() => {
init_agent_roster();
init_agent_scope_config();
init_session_key();
}));
//#endregion
//#region src/config/agent-store-source.ts
var init_agent_store_source = __esmMin((() => {
init_agent_scope_config();
init_errno();
init_utils();
init_config_env_vars();
init_io_read_helpers();
init_paths$1();
init_paths();
init_session_sqlite_target_paths();
init_targets_configured_agents();
}));
//#endregion
//#region src/state/openclaw-state-db-initialization.ts
var init_openclaw_state_db_initialization = __esmMin((() => {
init_agent_store_source();
init_session_sqlite_target_paths();
init_errno();
init_sqlite_files();
init_openclaw_state_db_paths();
}));
//#endregion
//#region src/infra/dedupe.ts
/** Creates a bounded in-memory dedupe cache with optional TTL expiry. */
function createDedupeCache(options) {
const ttlMs = resolveNonNegativeIntegerOption(options.ttlMs, 0);
const maxSize = resolveNonNegativeIntegerOption(options.maxSize, 0);
const cache = /* @__PURE__ */ new Map();
let oldestRecordedAt = Number.POSITIVE_INFINITY;
let newestRecordedAt = Number.NEGATIVE_INFINITY;
let timestampsOrdered = true;
const prune = (now) => {
const cutoff = ttlMs > 0 ? now - ttlMs : void 0;
if (cutoff !== void 0 && cutoff >= oldestRecordedAt) {
oldestRecordedAt = Number.POSITIVE_INFINITY;
for (const [entryKey, entry] of cache) if (entry.recordedAt <= cutoff) cache.delete(entryKey);
else if (entry.recordedAt < oldestRecordedAt) {
oldestRecordedAt = entry.recordedAt;
if (timestampsOrdered) break;
}
}
if (maxSize <= 0) {
cache.clear();
oldestRecordedAt = Number.POSITIVE_INFINITY;
return;
}
pruneMapToMaxSize(cache, maxSize);
};
const hasUnexpired = (key, now, touchOnRead) => {
const existing = cache.get(key);
if (!existing) return false;
if (ttlMs > 0 && now - existing.recordedAt >= ttlMs) {
cache.delete(key);
return false;
}
if (touchOnRead) {
existing.recordedAt = now;
cache.delete(key);
cache.set(key, existing);
}
return true;
};
return {
check: (key, now, ownerToken) => {
if (!key) return false;
const checkedAt = now ?? Date.now();
if (ttlMs > 0) {
if (checkedAt < oldestRecordedAt) oldestRecordedAt = checkedAt;
if (timestampsOrdered) {
timestampsOrdered = checkedAt >= newestRecordedAt;
newestRecordedAt = checkedAt;
}
}
if (hasUnexpired(key, checkedAt, true)) return true;
cache.set(key, {
recordedAt: checkedAt,
...ownerToken ? { ownerToken } : {}
});
prune(checkedAt);
return false;
},
peek: (key, now = Date.now()) => {
if (!key) return false;
return hasUnexpired(key, now, false);
},
delete: (key, ownerToken) => {
if (!key) return;
if (ownerToken && cache.get(key)?.ownerToken !== ownerToken) return;
cache.delete(key);
},
clear: () => {
cache.clear();
oldestRecordedAt = Number.POSITIVE_INFINITY;
newestRecordedAt = Number.NEGATIVE_INFINITY;
timestampsOrdered = true;
},
size: () => cache.size
};
}
var init_dedupe = __esmMin((() => {
init_number_coercion();
init_map_size();
}));
var init_openclaw_state_db_permissions = __esmMin((() => {
init_dedupe();
init_errno();
init_sqlite_files();
init_subsystem();
init_openclaw_state_db_paths();
createSubsystemLogger("state/db");
createDedupeCache({
ttlMs: 0,
maxSize: 4096
});
}));
var init_openclaw_state_db_open = __esmMin((() => {
init_errors$2();
init_gateway_state_owner();
init_kysely_sync();
init_sqlite_files();
init_sqlite_integrity();
init_sqlite_lifecycle_errors();
init_sqlite_user_version();
init_sqlite_wal_reclamation();
init_sqlite_wal();
init_sqlite_worker_identity();
init_sqlite_worker_state_context();
init_state_database_maintenance();
init_subsystem();
init_openclaw_state_db_cache();
init_openclaw_state_db_contract();
init_openclaw_state_db_handle();
init_openclaw_state_db_initialization();
init_openclaw_state_db_permissions();
init_openclaw_state_db_schema_version();
init_openclaw_state_ownership();
createSubsystemLogger("state/db");
}));
//#endregion
//#region src/state/openclaw-state-db-read-connection.ts
var init_openclaw_state_db_read_connection = __esmMin((() => {
init_node_sqlite();
init_sqlite_lifecycle_errors();
init_sqlite_schema_facts();
init_sqlite_snapshot_staging();
init_sqlite_transaction();
init_sqlite_wal();
init_sqlite_worker_identity();
init_openclaw_state_db_cache();
init_openclaw_state_db_contract();
init_openclaw_state_db_existing_schema();
init_openclaw_state_db_handle();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_schema_version();
}));
//#endregion
//#region src/state/openclaw-state-db-content-version.ts
var init_openclaw_state_db_content_version = __esmMin((() => {
init_sqlite_snapshot_source();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_cache();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_paths();
}));
//#endregion
//#region src/state/openclaw-state-db-readonly-reuse.ts
var init_openclaw_state_db_readonly_reuse = __esmMin((() => {
init_sqlite_lifecycle_errors();
init_sqlite_worker_identity();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_cache();
init_openclaw_state_db_read_connection();
init_openclaw_state_db_transaction();
}));
//#endregion
//#region src/state/openclaw-state-read-scope.ts
var init_openclaw_state_read_scope = __esmMin((() => {
init_sqlite_lifecycle_errors();
init_async_work_scope();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_cache();
}));
var init_worker_task_native_sections = __esmMin((() => {
init_global_singleton();
resolveGlobalSingleton(Symbol.for("openclaw.workerTaskNativeSection"), () => new AsyncLocalStorage());
}));
var init_worker_task_pool_completion = __esmMin((() => {
channel("openclaw.worker.task");
}));
//#endregion
//#region src/infra/worker-task-pool-retirement.ts
var init_worker_task_pool_retirement = __esmMin((() => {
init_worker_cpu();
init_worker_task_native_sections();
}));
var init_worker_task_pool_core = __esmMin((() => {
init_number_coercion();
init_runtime_worker_url();
init_worker_cpu();
init_worker_task_native_sections();
init_worker_task_pool_completion();
init_worker_task_pool_retirement();
AsyncLocalStorage.snapshot();
}));
//#endregion
//#region src/infra/worker-task-pool.ts
var init_worker_task_pool = __esmMin((() => {
init_worker_task_pool_core();
}));
//#endregion
//#region src/state/openclaw-state-read-worker.ts
var init_openclaw_state_read_worker = __esmMin((() => {
init_bun_sqlite_library();
init_runtime_process_url();
init_sqlite_lifecycle_errors();
init_worker_task_pool();
init_openclaw_state_db_cache();
init_openclaw_state_worker_error();
}));
//#endregion
//#region src/state/openclaw-state-worker-context.ts
var init_openclaw_state_worker_context = __esmMin((() => {
init_config_env_vars();
init_sqlite_worker_identity();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_cache();
init_openclaw_state_db_paths();
init_openclaw_state_worker_context_capture();
}));
var init_openclaw_state_db_readonly = __esmMin((() => {
init_errno();
init_sqlite_lifecycle_errors();
init_sqlite_readonly_location_cleanup();
init_sqlite_readonly_location();
init_sqlite_snapshot_source();
init_sqlite_worker_identity();
init_async_work_scope();
init_global_singleton();
init_openclaw_state_db_cache();
init_openclaw_state_db_content_version();
init_openclaw_state_db_read_connection();
init_openclaw_state_db_readonly_reuse();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_paths();
init_openclaw_state_read_scope();
init_openclaw_state_read_worker();
init_openclaw_state_worker_context();
resolveGlobalSingleton(Symbol.for("openclaw.artifactPreservingStateReads"), () => new AsyncLocalStorage());
resolveGlobalSingleton(Symbol.for("openclaw.disposableStateReads"), () => new AsyncLocalStorage());
resolveGlobalSingleton(Symbol.for("openclaw.stateSnapshotReads"), () => new AsyncLocalStorage());
resolveGlobalSingleton(Symbol.for("openclaw.synchronousStateReadSnapshots"), () => ({ current: void 0 }));
}));
//#endregion
//#region src/infra/sqlite-index-schema.ts
var init_sqlite_index_schema = __esmMin((() => {
init_sqlite_integrity();
init_sqlite_pinned_read_snapshot();
init_sqlite_schema_contract();
init_sqlite_transaction();
}));
//#endregion
//#region src/infra/sqlite-index-recovery.ts
var init_sqlite_index_recovery = __esmMin((() => {
init_directory_durability();
init_file_descriptor();
init_node_sqlite();
init_sqlite_index_schema();
init_sqlite_private_directory();
init_sqlite_snapshot_source();
}));
//#endregion
//#region src/state/agent-deletion-journal-history.ts
var init_agent_deletion_journal_history = __esmMin((() => {
init_kysely_sync();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_version();
}));
//#endregion
//#region src/state/openclaw-state-db-schema-additive.ts
var init_openclaw_state_db_schema_additive = __esmMin((() => {
init_sqlite_schema_contract();
init_openclaw_state_db_additive_columns();
init_openclaw_state_db_legacy_backfills();
init_openclaw_state_db_schema_helpers();
}));
//#endregion
//#region src/state/openclaw-state-db-startup-checkpoint.ts
var init_openclaw_state_db_startup_checkpoint = __esmMin((() => {
init_gateway_state_owner();
init_kysely_sync_cache_state();
init_node_sqlite();
init_sqlite_files();
init_sqlite_integrity();
init_sqlite_schema_contract();
init_sqlite_transaction();
init_sqlite_user_version();
init_sqlite_wal();
init_state_database_maintenance();
init_openclaw_state_db_contract();
init_openclaw_state_db_initialization();
init_openclaw_state_db_maintenance();
init_openclaw_state_db_permissions();
init_openclaw_state_db_readonly();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_schema_version();
init_openclaw_state_ownership();
}));
var init_openclaw_state_db_schema_runtime = __esmMin((() => {
init_sqlite_index_schema();
init_sqlite_integrity();
init_sqlite_strict();
init_state_database_maintenance();
init_state_migrations_cron_run_logs();
init_subsystem();
init_agent_deletion_journal_history();
init_openclaw_state_db_contract();
init_openclaw_state_db_existing_schema();
init_openclaw_state_db_fast_path();
init_openclaw_state_db_maintenance();
init_openclaw_state_db_schema_additive();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_schema_repair();
init_openclaw_state_db_schema_v12_foldin();
init_openclaw_state_db_schema_version();
init_openclaw_state_db_session_watch_migration();
init_openclaw_state_db_startup_checkpoint();
init_openclaw_state_db_table_retirements();
init_openclaw_state_db_paths();
init_openclaw_state_ownership();
init_openclaw_state_schema_compatibility();
createSubsystemLogger("state/db");
}));
//#endregion
//#region src/state/openclaw-state-db-repair.ts
var init_openclaw_state_db_repair = __esmMin((() => {
init_kysely_sync();
init_node_sqlite();
init_sqlite_index_recovery();
init_sqlite_index_schema();
init_sqlite_integrity();
init_sqlite_lifecycle_errors();
init_sqlite_schema_contract();
init_sqlite_strict();
init_sqlite_transaction();
init_state_migrations_cron_run_logs();
init_agent_deletion_journal_history();
init_openclaw_quarantine_store();
init_openclaw_state_db_audit_migration();
init_openclaw_state_db_cache();
init_openclaw_state_db_contract();
init_openclaw_state_db_fast_path();
init_openclaw_state_db_maintenance();
init_openclaw_state_db_operator_approval_migration();
init_openclaw_state_db_permissions();
init_openclaw_state_db_schema_additive();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_schema_repair();
init_openclaw_state_db_schema_runtime();
init_openclaw_state_db_schema_v12_foldin();
init_openclaw_state_db_schema_version();
init_openclaw_state_db_session_watch_migration();
init_openclaw_state_db_table_retirements();
init_openclaw_state_db_task_delivery_recovery();
init_openclaw_state_db_paths();
init_openclaw_state_ownership();
init_openclaw_state_schema_compatibility();
init_openclaw_update_schema_refusal();
}));
//#endregion
//#region src/state/openclaw-state-db-schema-discovery.ts
var init_openclaw_state_db_schema_discovery = __esmMin((() => {
init_node_sqlite();
init_openclaw_state_db_maintenance();
init_openclaw_state_db_readonly();
init_openclaw_state_db_schema_repair();
}));
//#endregion
//#region src/state/openclaw-state-db.ts
var init_openclaw_state_db = __esmMin((() => {
init_gateway_state_owner();
init_sqlite_integrity();
init_sqlite_lifecycle_errors();
init_sqlite_snapshot_source();
init_sqlite_transaction();
init_sqlite_user_version();
init_sqlite_wal_reclamation();
init_state_database_maintenance();
init_openclaw_state_db_async_lifecycle();
init_openclaw_state_db_cache();
init_openclaw_state_db_contract();
init_openclaw_state_db_existing_schema();
init_openclaw_state_db_fast_path();
init_openclaw_state_db_maintenance();
init_openclaw_state_db_open();
init_openclaw_state_db_permissions();
init_openclaw_state_db_read_connection();
init_openclaw_state_db_readonly();
init_openclaw_state_db_repair();
init_openclaw_state_db_schema_policy();
init_openclaw_state_db_schema_runtime();
init_openclaw_state_db_schema_version();
init_openclaw_state_db_startup_checkpoint();
init_openclaw_state_db_transaction();
init_openclaw_state_ownership();
init_openclaw_state_schema_publication();
init_openclaw_state_db_schema_discovery();
}));
//#endregion
//#region src/node-host/node-worker-launch-receipt.ts
function isNodeWorkerTerminalState(value) {
return value === "completed" || value === "failed" || value === "interrupted" || value === "cancelled";
}
function validateNodeWorkerContainerIdentity(identity) {
if (identity.engine !== "docker" && identity.engine !== "podman") throw new Error("node worker container engine must be docker or podman");
if (!/^[a-f0-9]{64}$/u.test(identity.containerId)) throw new Error("node worker container id must contain exactly 64 lowercase hexadecimal digits");
if (!/^[a-f0-9]{64}$/u.test(identity.engineTarget)) throw new Error("node worker container engine target must contain exactly 64 lowercase hexadecimal digits");
}
function containerIdentity(value) {
if (value == null) return null;
let parsed;
try {
parsed = JSON.parse(value);
} catch {
throw new Error("invalid node worker container identity");
}
if (!isRecord(parsed) || Object.keys(parsed).length !== 3 || parsed.engine !== "docker" && parsed.engine !== "podman" || typeof parsed.containerId !== "string" || typeof parsed.engineTarget !== "string") throw new Error("invalid node worker container identity");
const identity = {
engine: parsed.engine,
containerId: parsed.containerId,
engineTarget: parsed.engineTarget
};
validateNodeWorkerContainerIdentity(identity);
return identity;
}
function nodeWorkerLaunchReceiptFromRow(row) {
if (row.state !== "pending" && row.state !== "running" && !isNodeWorkerTerminalState(row.state)) throw new Error(`invalid node worker launch state ${row.state}`);
const container = containerIdentity(row.container_json);
const cleanupMode = row.cleanup_mode ?? null;
if (cleanupMode !== null && cleanupMode !== "process-group" && cleanupMode !== "owned-anchor") throw new Error("invalid node worker cleanup mode");
return {
launchId: row.launch_id,
planHash: row.plan_hash,
gatewayNamespace: row.gateway_namespace,
environmentId: row.environment_id,
sessionId: row.session_id,
ownerEpoch: row.owner_epoch,
placementGeneration: row.placement_generation,
runId: row.run_id,
state: row.state,
supervisor: {
pid: row.supervisor_pid,
startTime: row.supervisor_start_time
},
worker: row.worker_pid === null || row.worker_start_time === null ? null : {
pid: row.worker_pid,
startTime: row.worker_start_time
},
workerCleanupMode: cleanupMode,
workerLineageSettled: row.lineage_settled === 1,
...container ? { container } : {},
resultJson: row.result_json,
errorText: row.error_text,
completedAtMs: row.completed_at_ms,
createdAtMs: row.created_at_ms,
updatedAtMs: row.updated_at_ms
};
}
var init_node_worker_launch_receipt = __esmMin((() => {
init_record_coerce();
}));
//#endregion
//#region src/node-host/node-worker-launch-store.kernel.ts
function query(database) {
return getNodeSqliteKysely(database);
}
function selectLaunchRows(database) {
return query(database).selectFrom("node_worker_launches").selectAll("node_worker_launches").$if(tableExists(database, "node_worker_launch_containers"), (selection) => selection.leftJoin("node_worker_launch_containers", "node_worker_launch_containers.launch_id", "node_worker_launches.launch_id").select("node_worker_launch_containers.container_json")).$if(tableExists(database, "node_worker_launch_cleanup"), (selection) => selection.leftJoin("node_worker_launch_cleanup", "node_worker_launch_cleanup.launch_id", "node_worker_launches.launch_id").select(["node_worker_launch_cleanup.cleanup_mode", "node_worker_launch_cleanup.lineage_settled"]));
}
function readRow(database, launchId) {
return executeSqliteQueryTakeFirstSync(database, selectLaunchRows(database).where("node_worker_launches.launch_id", "=", launchId));
}
/** Read the authoritative physical owner within an already-open journal transaction. */
function readNodeWorkerLaunchReceipt(database, launchId) {
if (!tableExists(database, "node_worker_launches")) return;
const row = readRow(database, launchId);
return row ? nodeWorkerLaunchReceiptFromRow(row) : void 0;
}
var init_node_worker_launch_store_kernel = __esmMin((() => {
init_gateway_supervision();
init_kysely_sync();
init_sqlite_worker_operation_admission();
init_openclaw_state_db_schema_helpers();
init_openclaw_state_db();
init_node_worker_launch_receipt();
}));
//#endregion
//#region src/node-host/node-worker-process-identity.ts
function requireNodeWorkerProcessIdentity(pid) {
const startTime = getFileLockProcessStartTime(pid);
if (startTime === null) throw new Error(`cannot establish PID-reuse-safe identity for process ${pid}`);
return {
pid,
startTime
};
}
function inspectNodeWorkerProcessIdentity(identity) {
const observedStartTime = getFileLockProcessStartTime(identity.pid);
if (observedStartTime !== null) {
if (observedStartTime !== identity.startTime) return "reused";
return isPidDefinitelyDead(identity.pid) ? "dead" : "live";
}
return isPidDefinitelyDead(identity.pid) ? "dead" : "unknown";
}
var init_node_worker_process_identity = __esmMin((() => {
init_pid_alive();
}));
//#endregion
//#region src/node-host/node-worker-lineage-completion.ts
var node_worker_lineage_completion_exports = /* @__PURE__ */ __exportAll({ recordNodeWorkerLineageSettled: () => recordNodeWorkerLineageSettled });
/** The anchor records root exit and positive lineage EOF before extinguishing its own group. */
function recordNodeWorkerLineageSettled(binding) {
const worker = requireNodeWorkerProcessIdentity(process.pid);
return runExistingOpenClawStateWriteTransaction(({ db }) => {
const current = readNodeWorkerLaunchReceipt(db, binding.launchId);
if (!current || current.state !== "running" || current.planHash !== binding.planHash || current.workerCleanupMode !== "owned-anchor" || current.container || current.supervisor.pid !== binding.supervisor.pid || current.supervisor.startTime !== binding.supervisor.startTime || current.worker?.pid !== worker.pid || current.worker.startTime !== worker.startTime || inspectNodeWorkerProcessIdentity(worker) !== "live") return false;
return executeSqliteQuerySync(db, getNodeSqliteKysely(db).updateTable("node_worker_launch_cleanup").set({ lineage_settled: 1 }).where("launch_id", "=", binding.launchId).where("cleanup_mode", "=", "owned-anchor")).numAffectedRows === 1n;
}, {
path: binding.databasePath,
env: {
...process.env,
OPENCLAW_SUPERVISOR_MODE: binding.externallySupervised ? "external" : void 0
}
}, {
schemaSql: COMPLETION_SCHEMA,
operationLabel: "node-worker-launch.lineage-settled"
});
}
var COMPLETION_SCHEMA;
var init_node_worker_lineage_completion = __esmMin((() => {
init_kysely_sync();
init_sqlite_schema_sql();
init_openclaw_state_db_existing_write();
init_openclaw_state_schema();
init_node_worker_launch_store_kernel();
init_node_worker_process_identity();
COMPLETION_SCHEMA = ["node_worker_launches", "node_worker_launch_cleanup"].map((table) => extractSqliteTableSchema(OPENCLAW_STATE_SCHEMA_SQL, table)).join("\n");
}));
//#endregion
//#region src/process/supervisor/service-child-group-anchor.ts
init_record_coerce();
init_deferred$1();
function commandStdio(start) {
const stdio = [
start.stdinMode === "inherit" ? "inherit" : "pipe",
"pipe",
"pipe"
];
if (start.secretFd !== void 0) setStdioEntry(stdio, start.secretFd, start.secretFd);
const lineageFd = reserveStdioEntry(stdio, start.lineageFd ?? "pipe");
const inheritedLineageFds = [lineageFd, ...(start.parentLineageFds ?? []).map((fd) => reserveStdioEntry(stdio, fd))];
if (start.ownedWorker) stdio.push("ipc");
return {
stdio,
lineageFd,
inheritedLineageFds
};
}
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms).unref?.();
});
}
function runServiceChildGroupAnchor() {
let start;
let state = "starting";
let sequence = 0;
let lastHostSequence = 0;
let command;
let lineageCompletion;
let inheritedLineageClosed = false;
let workerStarted = false;
let workerLineageFds = [];
let control;
let rootSettlementStarted = false;
let rootResultDelivery;
let rootExit;
let stdoutDrained = false;
let stderrDrained = false;
let lineageClosed = false;
let lineageObservationFailed = false;
let markHostLineageClosed;
let forceCleanup = false;
const forceCleanupRequested = createDeferredCore();
const lineageDone = createDeferredCore();
const rootExited = createDeferredCore();
const rootSettledDone = createDeferredCore();
const startupErrorAcknowledged = createDeferredCore();
const retirementReady = createDeferredCore();
let closingSequence;
const send = async (message) => {
if (!start || !control || control.destroyed) return;
sequence += 1;
await new Promise((resolve) => {
const framed = {
...message,
generation: start.generation,
sequence
};
control.write(encodeServiceChildMessage(framed), () => resolve());
});
};
const closeAuthority = async (reason, hardKill, deadline = Date.now() + GRACEFUL_CANCEL_TIMEOUT_MS) => {
if (!start || state === "closed") return;
state = "closed";
if (hardKill && start.lineageFd === void 0 && !lineageClosed) {
process.kill(0, "SIGKILL");
return;
}
const requiresAcknowledgement = start.acknowledgeClosing === true;
closingSequence = requiresAcknowledgement ? sequence + 1 : void 0;
const remainingMs = deadline - Date.now();
if (remainingMs > 0) send({
type: "closing",
reason
}).then(() => {
if (!requiresAcknowledgement) retirementReady.resolve(true);
}, () => retirementReady.resolve(false));
if (remainingMs <= 0 || !await Promise.race([retirementReady.promise, delay(remainingMs).then(() => false)]) || Date.now() >= deadline || hardKill) {
process.kill(0, "SIGKILL");
return;
}
control?.end(() => process.exit(0));
};
const closeInheritedLineage = () => {
if (start?.lineageFd !== void 0 && !inheritedLineageClosed) {
inheritedLineageClosed = true;
closeSync(start.lineageFd);
}
};
const reportStartupFailure = async (error, hardKill = false) => {
closeInheritedLineage();
await send({
type: "startup-error",
error
});
await Promise.race([startupErrorAcknowledged.promise, retirementReady.promise]);
await closeAuthority("lineage-lost", hardKill);
};
const requestCleanup = async (reason, signal = "SIGTERM") => {
if (!start || state === "closed") return;
if (state === "closing") {
forceCleanup ||= signal === "SIGKILL";
if (forceCleanup) forceCleanupRequested.resolve();
return;
}
state = "closing";
forceCleanup = signal === "SIGKILL";
if (!command) {
await reportStartupFailure("command startup cancelled before spawn", true);
return;
}
const cleanupDeadline = Date.now() + GRACEFUL_CANCEL_TIMEOUT_MS;
const termGraceDone = delay(GRACEFUL_CANCEL_TIMEOUT_MS);
if (start.ownedWorker) {
if (!forceCleanup) process.kill(0, "SIGTERM");
const settled = Promise.all([rootExited.promise, lineageDone.promise]);
if (!forceCleanup) await Promise.race([
settled,
termGraceDone,
forceCleanupRequested.promise
]);
if (!rootExit) command?.kill("SIGKILL");
await settled;
await rootResultDelivery;
let lineageRecorded = false;
if (rootExit && lineageClosed && lineageCompletion) try {
lineageRecorded = lineageCompletion.recordNodeWorkerLineageSettled(start.cleanupBinding);
} catch {}
if (!lineageRecorded) await send({
type: "output",
stream: "stderr",
chunk: "node worker lineage completion was not recorded; restart recovery will retain capacity until cleanup can be verified\n"
});
if (!forceCleanup) await Promise.race([
rootSettledDone.promise,
termGraceDone,
forceCleanupRequested.promise
]);
await closeAuthority(reason, true);
return;
}
if (!forceCleanup) {
process.kill(0, "SIGTERM");
await Promise.race([
lineageDone.promise,
termGraceDone,
forceCleanupRequested.promise
]);
}
if (state !== "closing" || !start) return;
if (lineageClosed && !rootExit && !forceCleanup) await Promise.race([
rootExited.promise,
termGraceDone,
forceCleanupRequested.promise
]);
if (state !== "closing" || !start) return;
if (rootExit && !forceCleanup) {
await Promise.race([
rootSettledDone.promise,
termGraceDone,
forceCleanupRequested.promise
]);
if (state !== "closing" || !start) return;
}
for (;;) {
if (forceCleanup || !rootExit || !stdoutDrained || !stderrDrained || !lineageClosed) break;
const remainingMs = cleanupDeadline - Date.now();
if (remainingMs <= 0) break;
if (hasLiveOwnedProcessGroupMembers(remainingMs) === false) {
await closeAuthority(reason, false, cleanupDeadline);
return;
}
const nextObservationMs = Math.min(100, cleanupDeadline - Date.now());
if (nextObservationMs <= 0) break;
await Promise.race([delay(nextObservationMs), forceCleanupRequested.promise]);
}
await closeAuthority(reason, true);
};
const onControlMessage = (message) => {
if (!start || message.generation !== start.generation || !Number.isSafeInteger(message.sequence) || message.sequence <= lastHostSequence) return;
if (message.type === "closing-ack") {
if (state === "closed" && closingSequence !== void 0 && message.closingSequence === closingSequence) {
lastHostSequence = message.sequence;
retirementReady.resolve(true);
}
return;
}
if (state === "closed") return;
lastHostSequence = message.sequence;
if (message.type === "startup-error-ack") {
startupErrorAcknowledged.resolve();
return;
}
if (message.type === "lineage-closed") {
markHostLineageClosed?.();
return;
}
if (message.type === "worker-close") {
if (start.ownedWorker && !command) requestCleanup("cancel");
else if (start.ownedWorker && command?.connected) command.disconnect();
return;
}
if (message.type === "worker-start") {
if (!start.ownedWorker || workerStarted || state !== "active") return;
if (!command?.connected) {
requestCleanup("parent-lost");
return;
}
workerStarted = true;
command.send({
type: "openclaw-worker-start-v1",
lineageFds: workerLineageFds
}, (error) => {
if (error) requestCleanup("parent-lost");
});
return;
}
requestCleanup("cancel", message.signal);
};
const startCommand = async (next) => {
const controlFd = next.controlFd;
if (controlFd === void 0) {
process.exitCode = 1;
return;
}
start = next;
const socket = process.versions.bun ? new Socket({
readable: true,
writable: true
}) : new Socket({
fd: controlFd,
readable: true,
writable: true
});
control = socket;
socket.setEncoding("utf8");
let pending = "";
socket.on("data", (chunk) => {
pending += chunk;
for (;;) {
const newline = pending.indexOf("\n");
if (newline < 0) break;
const line = pending.slice(0, newline);
pending = pending.slice(newline + 1);
try {
onControlMessage(JSON.parse(line));
} catch {
requestCleanup("parent-lost");
}
}
});
const onControlLoss = () => {
retirementReady.resolve(false);
if (state !== "closed") requestCleanup("parent-lost");
};
socket.once("end", onControlLoss);
socket.once("close", onControlLoss);
socket.once("error", onControlLoss);
if (process.versions.bun) socket.connect({ fd: controlFd });
lineageCompletion = next.ownedWorker && true ? await Promise.resolve().then(() => (init_node_worker_lineage_completion(), node_worker_lineage_completion_exports)).catch(() => void 0) : void 0;
if (start !== next || control !== socket || state !== "starting" || socket.destroyed || socket.readableEnded || socket.writableEnded || !process.connected) {
await requestCleanup("parent-lost");
return;
}
const { stdio, lineageFd, inheritedLineageFds } = commandStdio(start);
workerLineageFds = inheritedLineageFds;
try {
command = spawnWithInheritedOomScore(start.command, start.args, {
cwd: start.cwd,
env: start.env,
argv0: start.argv0,
stdio,
detached: false,
windowsHide: true
});
await once(command, "spawn");
} catch (error) {
await reportStartupFailure(error instanceof Error ? error.message : String(error));
return;
}
const markLineageClosed = () => {
if (lineageClosed || lineageObservationFailed) return;
lineageClosed = true;
lineageDone.resolve();
if (state === "active") (async () => {
await rootExited.promise;
if (state !== "active") return;
if (rootSettlementStarted) await rootSettledDone.promise;
if (state !== "active") return;
requestCleanup("lineage-lost");
})();
};
if (start.lineageFd !== void 0) {
markHostLineageClosed = markLineageClosed;
closeInheritedLineage();
} else {
const lineage = command.stdio[lineageFd];
if (!lineage) {
await send({
type: "startup-error",
error: "command lineage pipe was not created"
});
await requestCleanup("lineage-lost", "SIGKILL");
return;
}
lineage.once("end", markLineageClosed);
const markLineageFailed = () => {
if (lineageClosed || lineageObservationFailed) return;
lineageObservationFailed = true;
lineageDone.resolve();
requestCleanup("lineage-lost");
};
lineage.once("close", () => {
if (!lineage.readableEnded) markLineageFailed();
});
lineage.once("error", markLineageFailed);
lineage.resume();
}
const settleRoot = async () => {
if (rootSettlementStarted || !rootResultDelivery || !stdoutDrained || !stderrDrained) return;
rootSettlementStarted = true;
await rootResultDelivery;
rootSettledDone.resolve();
if (lineageClosed && state === "active") await requestCleanup("lineage-lost");
};
const stdout = process.versions.bun ? createWriteStream("", {
fd: 1,
autoClose: true
}) : process.stdout;
const stderr = process.versions.bun ? createWriteStream("", {
fd: 2,
autoClose: true
}) : process.stderr;
pipeline(command.stdout, stdout, () => {
stdoutDrained = true;
settleRoot();
});
pipeline(command.stderr, stderr, () => {
stderrDrained = true;
settleRoot();
});
if (start.stdinMode !== "inherit" && command.stdin) {
const input = process.stdin;
const destination = command.stdin;
const endInput = () => destination.end();
let inputClosed = false;
const stopInput = () => {
input.unpipe(destination);
input.off("end", endInput);
input.destroy();
if (!inputClosed) {
inputClosed = true;
send({ type: "stdin-closed" });
}
};
destination.once("error", stopInput);
destination.once("close", stopInput);
input.pipe(destination, { end: false });
if (input.readableEnded) endInput();
else input.once("end", endInput);
}
command.once("error", (error) => {
if (state === "starting") reportStartupFailure(error.message);
});
if (start.ownedWorker) command.on("message", (message) => {
if (state === "active") send({
type: "worker-message",
message
});
});
if (command.pid && state === "starting") {
state = "active";
send({
type: "ready",
commandPid: command.pid,
anchorPid: process.pid
});
}
command.once("exit", (code, signal) => {
rootExit = {
code,
signal
};
rootResultDelivery = send({
type: "root-result",
code,
signal
});
rootExited.resolve();
settleRoot();
});
};
const onParentSignal = () => {
if (state === "active" || start && state === "starting") requestCleanup("parent-lost");
};
process.on("SIGTERM", onParentSignal);
process.on("SIGINT", onParentSignal);
process.once("disconnect", () => {
retirementReady.resolve(false);
if (state !== "closed") requestCleanup("parent-lost");
});
process.on("message", (raw) => {
const message = raw;
if (message.type === "start" && !start && state === "starting") {
if (isRecord(raw) && raw.acknowledgeClosing !== void 0 && raw.acknowledgeClosing !== true) process.exit(1);
startCommand(message);
} else if (message.type === "parent-loss" && message.generation === start?.generation) {
retirementReady.resolve(false);
requestCleanup("parent-lost");
}
});
}
runServiceChildGroupAnchor();
//#endregion
export { runServiceChildGroupAnchor };