UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

140 lines • 433 kB
import{r as e,t}from"./fs-safe-copy.worker-errno-CsW5NI8i.mjs";import{i as n,t as r}from"./fs-safe-copy.worker-global-singleton-DIJgobpU.mjs";import{a as i,i as a,n as o,r as s,t as c}from"./fs-safe-copy.worker-fs-safe-env-DlxNGTI7.mjs";import{A as l,B as u,C as d,F as f,G as p,H as m,I as h,K as g,L as ee,M as te,N as ne,O as re,P as ie,Q as ae,S as oe,U as se,V as ce,b as le,c as ue,dt as de,et as fe,g as pe,h as me,it as he,j as ge,k as _e,lt as ve,m as ye,nt as be,p as xe,rt as Se,st as v,t as Ce,ut as we,v as Te,w as Ee,x as De,y as Oe,z as ke}from"./fs-safe-copy.worker-sqlite-snapshot-staging-owner-BB9Ddai8.mjs";import{c as Ae,i as je,t as Me}from"./fs-safe-copy.worker-error-coercion-AIKMMQJR.mjs";import{i as Ne,r as Pe}from"./fs-safe-copy.worker-path-existence-DvAA8vT7.mjs";import{n as Fe,t as Ie}from"./fs-safe-copy.worker-path-guards-CHyQsMxp.mjs";import"./fs-safe-copy.worker-fs-safe-BFxtX2RT.mjs";import{I as Le,L as Re,k as ze}from"./fs-safe-copy.worker-redact-BQxLxSX2.mjs";import{m as Be}from"./fs-safe-copy.worker-number-coercion-1FVMw2ic.mjs";import{c as Ve,l as He,o as Ue}from"./fs-safe-copy.worker-diagnostic-events-CJsrCJVq.mjs";import{i as We}from"./fs-safe-copy.worker-record-coerce-BUlpHiHI.mjs";import{i as Ge}from"./fs-safe-copy.worker-home-dir-CeEbrKea.mjs";import{n as Ke,r as qe}from"./fs-safe-copy.worker-utils-C58aD3xL.mjs";import{n as Je}from"./fs-safe-copy.worker-sleep-BA4lY26w.mjs";import{a as Ye}from"./fs-safe-copy.worker-worker-diagnostic-script-C6p7spUr.mjs";import{a as Xe,i as Ze,o as Qe}from"./fs-safe-copy.worker-cli-invocation-fIA_-Tg7.mjs";import{r as $e}from"./fs-safe-copy.worker-runtime-worker-url-DWAWJihB.mjs";import{r as et}from"./fs-safe-copy.worker-cancellation-policy-BEVdpGz3.mjs";import{a as tt,c as nt,l as rt,o as it,u as at}from"./fs-safe-copy.worker-file-descriptor-CG9tnqhN.mjs";import{f as ot,i as st,t as ct}from"./fs-safe-copy.worker-subsystem-CSYDX9_J.mjs";import{F as lt,H as ut,_ as dt,f as ft,g as pt,h as mt,it as ht,m as gt,ot as _t,p as vt,st as yt,w as bt}from"./fs-safe-copy.worker-sqlite-worker-database-admission-relay-ByY9vBCO.mjs";import{c as xt,u as St}from"./fs-safe-copy.worker-worker-task-pool-B6bX9dmP.mjs";import{t as Ct}from"./fs-safe-copy.worker-promise-like-3qqJObCs.mjs";import{n as wt}from"./fs-safe-copy.worker-error-graph-internal-BcTi4PZl.mjs";import{$ as Tt,A as Et,At as Dt,Bt as Ot,Ct as kt,Gt as At,Ht as jt,J as Mt,K as Nt,Lt as Pt,M as Ft,Ot as It,St as Lt,Tt as Rt,Ut as zt,Vt as Bt,W as Vt,Wt as y,X as Ht,Y as Ut,at as Wt,g as Gt,ht as Kt,it as qt,j as Jt,kt as Yt,lt as Xt,o as Zt,ot as Qt,p as $t,q as en,rt as tn,s as nn,tt as rn,u as an,v as on,xt as sn,y as cn,yt as ln}from"./fs-safe-copy.worker-sqlite-database-admission-CoQADBJP.mjs";import{t as un}from"./fs-safe-copy.worker-usingCtx-03vOGQ3v.mjs";import{t as dn}from"./fs-safe-copy.worker-deferred-B75K7ut7.mjs";import{t as pn}from"./fs-safe-copy.worker-process-exit-cleanup-BJBelOoF.mjs";import{C as mn,J as hn,Q as gn,S as _n,U as vn,W as yn,Y as bn,n as xn,o as Sn,r as Cn,t as wn,w as Tn}from"./fs-safe-copy.worker-sqlite-reader-lifecycle-DsyhPrac.mjs";import{t as En}from"./fs-safe-copy.worker-process-env-DgVwfN3Y.mjs";import{f as Dn,p as On,u as kn}from"./fs-safe-copy.worker-service-child-group-ownership-D9CheQE8.mjs";import{o as An}from"./fs-safe-copy.worker-openclaw-root-DvAU5BUQ.mjs";import{d as jn,f as Mn,o as Nn,t as Pn}from"./fs-safe-copy.worker-gateway-process-argv-BiDr_SAo.mjs";import{A as Fn,F as In,I as Ln,M as Rn,N as zn,P as Bn,R as Vn,_ as Hn,a as Un,c as Wn,f as Gn,g as Kn,k as qn,r as Jn,s as Yn,t as Xn}from"./fs-safe-copy.worker-sqlite-schema-facts-BFpL4_ic.mjs";import{a as Zn,c as Qn,d as $n,f as er,i as tr,l as nr,o as rr,r as ir,s as ar,u as or}from"./fs-safe-copy.worker-sqlite-staging-token-DWEKH9M7.mjs";import{r as sr,t as cr}from"./fs-safe-copy.worker-node-version-CFmGtosp.mjs";import{a as lr,t as ur}from"./fs-safe-copy.worker-sqlite-integrity-wA_pGRsW.mjs";import{r as dr}from"./fs-safe-copy.worker-gc-observer-B1TRYy-e.mjs";import{t as fr}from"./fs-safe-copy.worker-cleanup-budget-4kNMohY0.mjs";import b,{chmodSync as pr,existsSync as mr,realpathSync as hr,statSync as gr,unlinkSync as _r,writeFileSync as vr}from"node:fs";import"node:fs/promises";import x from"node:path";import{setImmediate as yr}from"node:timers/promises";import{MessageChannel as br,isMainThread as xr,threadId as Sr}from"node:worker_threads";import{FsSafeError as Cr}from"@openclaw/fs-safe/errors";import{createDirectorySync as wr}from"@openclaw/fs-safe/advanced";import"node:util";import{AsyncLocalStorage as Tr}from"node:async_hooks";import Er from"node:os";import{spawnSync as Dr}from"node:child_process";import{createHash as Or,hash as kr,randomUUID as Ar}from"node:crypto";import{channel as jr}from"node:diagnostics_channel";import"semver";import"node:buffer";import{acquireFileLockSync as Mr}from"@openclaw/fs-safe/file-lock";const Nr=`ai.openclaw.node`,Pr=`OpenClaw Node`;function normalizeGatewayProfile(e){let t=e?.trim();return t&&Be(t)!=="default"?t:null}function resolveGatewayProfileSuffix(e){let t=normalizeGatewayProfile(e);return t?`-${t}`:``}function resolveNodeLaunchAgentLabel(e){let t=normalizeGatewayProfile(e);return t?`${Nr}.${t}`:Nr}function resolveNodeSystemdServiceName(e){return`openclaw-node${resolveGatewayProfileSuffix(e)}`}function resolveNodeWindowsTaskName(e){let t=normalizeGatewayProfile(e);return t?`${Pr} (${t})`:Pr}function resolveNodeServiceIdentityEnvironment(e={}){let t=e.OPENCLAW_PROFILE;return{OPENCLAW_PROFILE:t,OPENCLAW_LAUNCHD_LABEL:resolveNodeLaunchAgentLabel(t),OPENCLAW_SYSTEMD_UNIT:resolveNodeSystemdServiceName(t),OPENCLAW_WINDOWS_TASK_NAME:resolveNodeWindowsTaskName(t),OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER:`1`,OPENCLAW_TASK_SCRIPT_NAME:`node.cmd`,OPENCLAW_LOG_PREFIX:`node${resolveGatewayProfileSuffix(t)}`,OPENCLAW_SERVICE_MARKER:`openclaw`,OPENCLAW_SERVICE_KIND:`node`}}var Fr={blockedEverywhereKeys:/* @__PURE__ */ `NODE_OPTIONS.NODE_PATH.NODE_REDIRECT_WARNINGS.NODE_REPL_EXTERNAL_MODULE.NODE_REPL_HISTORY.NODE_V8_COVERAGE.PYTHONHOME.PYTHONPATH.PERL5LIB.PERL5OPT.PERL5SHELL.PERLLIB.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`.split(`.`),blockedOverrideOnlyKeys:/* @__PURE__ */ `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`.split(`.`),allowedInheritedOverrideOnlyKeys:/* @__PURE__ */ `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`.split(`.`),blockedOverridePrefixes:[`GIT_CONFIG_`,`NPM_CONFIG_`,`CARGO_REGISTRIES_`,`TF_VAR_`],blockedPrefixes:[`DYLD_`,`LD_`,`BASH_FUNC_`]};function sortUniqueUppercase(e){return Object.freeze(Array.from(new Set(e.map(e=>e.toUpperCase()))).toSorted((e,t)=>e<t?-1:+(e>t)))}function derivePolicyArrays(e){let t=e.blockedEverywhereKeys??[],n=e.blockedOverrideOnlyKeys??[],r=e.allowedInheritedOverrideOnlyKeys??[],i=new Set(r.map(e=>e.toUpperCase())),a=e.blockedPrefixes??[],o=e.blockedOverridePrefixes??[],s=e.blockedInheritedPrefixes??a;return{blockedInheritedKeys:sortUniqueUppercase([...t,...n.filter(e=>!i.has(e.toUpperCase()))]),blockedInheritedPrefixes:sortUniqueUppercase(s),blockedKeys:sortUniqueUppercase(t),blockedOverrideKeys:sortUniqueUppercase(n),blockedPrefixes:sortUniqueUppercase(a),blockedOverridePrefixes:sortUniqueUppercase(o)}}function loadHostEnvSecurityPolicy(e=Fr){let t=derivePolicyArrays(e);return Object.freeze({blockedEverywhereKeys:Object.freeze(e.blockedEverywhereKeys??[]),blockedOverrideOnlyKeys:Object.freeze(e.blockedOverrideOnlyKeys??[]),allowedInheritedOverrideOnlyKeys:Object.freeze(e.allowedInheritedOverrideOnlyKeys??[]),blockedInheritedKeys:t.blockedInheritedKeys,blockedInheritedPrefixes:t.blockedInheritedPrefixes,blockedPrefixes:t.blockedPrefixes,blockedOverridePrefixes:t.blockedOverridePrefixes,blockedKeys:t.blockedKeys,blockedOverrideKeys:t.blockedOverrideKeys})}const Ir=loadHostEnvSecurityPolicy(),Lr=/^[A-Za-z_][A-Za-z0-9_]*$/,Rr=new Set(Ir.blockedKeys);new Set(Ir.blockedInheritedKeys);const zr=new Set(Ir.blockedOverrideKeys);(/* @__PURE__ */ new Set([...Object.keys(resolveNodeServiceIdentityEnvironment()),`OPENCLAW_GATEWAY_SERVICE_PID`])).delete(`OPENCLAW_PROFILE`);const Br=/^CARGO_TARGET_[A-Z0-9_]+_(?:LINKER|RUNNER)$/;new Tr;function normalizeEnvVarKey(e,t){let n=e.trim();return!n||t?.portable&&!Lr.test(n)?null:n}function isDangerousHostEnvVarName(e){let t=normalizeEnvVarKey(e)?.toUpperCase();return t!==void 0&&(Rr.has(t)||Ir.blockedPrefixes.some(e=>t.startsWith(e)))}function isDangerousHostEnvOverrideVarName(e){let t=normalizeEnvVarKey(e)?.toUpperCase();return t!==void 0&&(zr.has(t)||Br.test(t)||Ir.blockedOverridePrefixes.some(e=>t.startsWith(e)))}function isConfigRuntimeEnvVarAllowed(e,t){let n=e.toUpperCase();return!!t.trim()&&n!==`OPENCLAW_ALLOW_OLDER_BINARY_DESTRUCTIVE_ACTIONS`&&n!==`OPENCLAW_INCLUDE_ROOTS`&&n!==`OPENCLAW_CONFIG_READONLY`&&n!==`OPENCLAW_CONFIG_READONLY_NOTICE`&&n!==`OPENCLAW_DISABLE_GATEWAY_LOCAL_TERMINALS`&&n!==`OPENCLAW_DISABLE_CRON_HOST_EXECUTION`&&n!==`OPENCLAW_DEV_RELOAD_BUNDLED_PLUGINS`&&!isDangerousHostEnvVarName(e)&&!isDangerousHostEnvOverrideVarName(e)&&!ze(t)}function collectConfigRuntimeEnvVars(e){let t=e?.env;if(!t)return{};let n={},r=[...Object.entries(t.vars??{}),...Object.entries(t).filter(([e])=>e!==`shellEnv`&&e!==`vars`)];for(let[e,t]of r){if(typeof t!=`string`)continue;let r=normalizeEnvVarKey(e,{portable:!0});r&&isConfigRuntimeEnvVarAllowed(r,t)&&(n[r]=t)}return n}function findCaseInsensitiveEnvKey(e,t){if(Object.hasOwn(e,t))return t;let n=t.toUpperCase();return Object.keys(e).find(e=>e.toUpperCase()===n)}function envSnapshotKey(e){return process.platform===`win32`?e.toUpperCase():e}function indexConfigRuntimeEnvValues(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of Object.entries(e))for(let e of He(n)){let n=t.get(e)??/* @__PURE__ */ new Set;n.add(r),t.set(e,n)}return t}const Vr=/* @__PURE__ */ new WeakMap;function resolveAppliedConfigEnvOwnership(e){return{...Vr.get(i(e)),...e===process.env?Hr.ownedEnv:{}}}new Tr;function cloneEnvWithPlatformSemantics(e){let t={...o(e)};return process.platform===`win32`&&(t=new Proxy(t,{deleteProperty(e,t){if(typeof t!=`string`)return Reflect.deleteProperty(e,t);let n=findCaseInsensitiveEnvKey(e,t);return!n||Reflect.deleteProperty(e,n)},get(e,t,n){if(typeof t!=`string`)return Reflect.get(e,t,n);let r=findCaseInsensitiveEnvKey(e,t);return r?e[r]:Reflect.get(e,t,n)},getOwnPropertyDescriptor(e,t){if(typeof t!=`string`)return Reflect.getOwnPropertyDescriptor(e,t);let n=findCaseInsensitiveEnvKey(e,t);if(n)return{configurable:!0,enumerable:!0,value:e[n],writable:!0}},has(e,t){return typeof t==`string`?findCaseInsensitiveEnvKey(e,t)!==void 0:Reflect.has(e,t)},set(e,t,n){return typeof t==`string`?(e[findCaseInsensitiveEnvKey(e,t)??t]=n,!0):Reflect.set(e,t,n)}})),Vr.set(a(t),resolveAppliedConfigEnvOwnership(e)),s(t),t}let Hr={ownedEnv:{},sourceConfig:null};function collectConfigRuntimeEnvOwnership(e,t,n,r={}){let i=o(t),a=o(n),s={},c=new Set((r.replacedLowerPrecedenceKeys??[]).map(envSnapshotKey));for(let[t,n]of Object.entries(collectConfigRuntimeEnvVars(e)))for(let e of He(t)){let t=findCaseInsensitiveEnvKey(a,e);if(!t||a[t]!==n)continue;let r=findCaseInsensitiveEnvKey(i,e);(!r||i[r]!==n||c.has(envSnapshotKey(t)))&&(s[t]=n)}return s}function filterConfigRuntimeEnvOwnership(e,t,n){let r=o(t),i=indexConfigRuntimeEnvValues(collectConfigRuntimeEnvVars(e)),a={};for(let[e,t]of Object.entries(n)){let n=He(e)[0]??e,o=findCaseInsensitiveEnvKey(r,e);o&&r[o]===t&&i.get(n)?.has(t)&&(a[o]=t)}return a}function applyConfigEnvVars(e,t=process.env,n={}){c(t);let r={...t},i=resolveAppliedConfigEnvOwnership(t),o=collectConfigRuntimeEnvVars(e),l=Object.entries(n.lowerPrecedenceEnv??{}),u=new Map(l.map(([e,t])=>[envSnapshotKey(e),t])),d=Ue(Object.keys(o)),f=indexConfigRuntimeEnvValues(o),p=/* @__PURE__ */ new Map;for(let e of Object.keys(o)){let n=He(e),r=n.map(e=>[e,t[e]]).find(([e,t])=>t?.trim()&&u.get(e)!==t&&!f.get(e)?.has(t))?.[1];if(r!==void 0)for(let e of n)p.set(e,r)}let m=[];for(let[e,n]of l)d.has(envSnapshotKey(e))&&t[e]===n&&(delete t[e],m.push(e));m.length>0&&n.onLowerPrecedenceKeysReplaced?.(m);for(let[e,n]of Object.entries(o)){let r=p.get(envSnapshotKey(e));if(r!==void 0){t[e]=r;continue}let i=t[e];i?.trim()&&u.get(envSnapshotKey(e))!==i||(t[e]=n)}Ve(t),Vr.set(a(t),{...filterConfigRuntimeEnvOwnership(e,t,i),...collectConfigRuntimeEnvOwnership(e,r,t,{replacedLowerPrecedenceKeys:m})}),s(t)}function getEnumValues(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function joinValues(e,t=`|`){return e.map(e=>stringifyPrimitive(e)).join(t)}function jsonStringifyReplacer(e,t){return typeof t==`bigint`?t.toString():t}var Cached=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function cached(e){return new Cached(e)}function nullish(e){return e==null}function cleanRegex(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function floatSafeRemainder(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function assignProp(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function rawShape(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function sourceShape(e){return rawShape(e._zod.def)??e._zod.def.shape}function deferProp(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return assignProp(this,t,e),e},enumerable:!0,configurable:!0})}function putProp(e,t,n){t in e?assignProp(e,t,n):e[t]=n}function mirrorShape(e,t,n,r){let i=sourceShape(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?deferProp(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):putProp(e,a,r?r(n.value,a):n.value))}}function mirrorProps(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?deferProp(e,n,()=>t[n]):putProp(e,n,r.value))}}function mergeDefs(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function esc(e){return JSON.stringify(e)}function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Ur=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Wr=/* @__PURE__*/ cached(()=>{if(S.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function isPlainObject(e){if(isObject$1(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return isObject$1(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function shallowClone(e){return isPlainObject(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Gr=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function normalizeParams(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function stringifyPrimitive(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const Kr={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},qr={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function pick(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return mirrorShape(i,e,maskedKeys(e,t)),clone(e,mergeDefs(n,{shape:i,checks:[]}))}function maskedKeys(e,t){let n=sourceShape(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function omit(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(maskedKeys(e,t)),a={};return mirrorShape(a,e,Reflect.ownKeys(sourceShape(e)).filter(e=>!i.has(e))),clone(e,mergeDefs(n,{shape:a,checks:[]}))}function extend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=sourceShape(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(e,mergeDefs(e._zod.def,{shape:extended(e,t)}))}function extended(e,t){let n={};return mirrorShape(n,e,Reflect.ownKeys(sourceShape(e))),mirrorProps(n,t),n}function safeExtend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return clone(e,mergeDefs(e._zod.def,{shape:extended(e,t)}))}function merge(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return mirrorShape(n,e,Reflect.ownKeys(sourceShape(e))),mirrorShape(n,t,Reflect.ownKeys(sourceShape(t))),clone(e,mergeDefs(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function partial(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(maskedKeys(t,n)):void 0,o={};return mirrorShape(o,t,Reflect.ownKeys(sourceShape(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),clone(t,mergeDefs(t._zod.def,{shape:o,checks:[]}))}function required(e,t,n){let r=n?new Set(maskedKeys(t,n)):void 0,i={};return mirrorShape(i,t,Reflect.ownKeys(sourceShape(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),clone(t,mergeDefs(t._zod.def,{shape:i}))}function aborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function explicitlyAborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return typeof e==`string`?e:e?.message}function sizeCaps(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function attachSchema(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function finalizeIssue(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(a?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(n.customError?.(e))??unwrapMessage(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}const Jr=/[\uD800-\uDBFF]/;function codePointLength(e){let t=e.length;if(!Jr.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function getLengthableOrigin(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function parsedType(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function issue(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function members(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):defineBound(e,n,r.value)}}function own(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function hide(e,t,n){return own(e,t,n,!1)}/* @__NO_SIDE_EFFECTS__ */
function derived(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return own(this,n,r(this))},set(e){own(this,n,e)}})}return t}function defineBound(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:own(this,t,n.bind(this))},set(e){own(this,t,e)}})}function claim(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Yr,Xr=!1;const Zr={configurable:!0,get(){Xr=!0}};function defineLazyInternal(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Yr!==e._zod?Yr=void 0:(Yr=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Zr);let e=Xr;Xr=!1;try{let r=n(this);return Xr?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Xr||=e,r}catch(n){throw delete this[t],Xr||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function installLazyProp(e,t,n,r){let i=claim(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function constantCatch(e){let fn=()=>e;return fn[`~constantCatch`]=!0,fn}var Qr;const $r={value:void 0,enumerable:!1};let ei=`captureStackTrace`in Error?Error:null;function newError(e){let t=ei;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return ei=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}/* @__NO_SIDE_EFFECTS__ */
function $constructor(e,t,n,r){let i={};function Internals(e){this.def=e,this.constr=_,this.traits=/* @__PURE__ */ new Set}Internals.prototype=i;let a=n,o=a&&/* @__PURE__ */ new WeakSet;function init(n,r){if(!n._zod){$r.value=new Internals(r);try{Object.defineProperty(n,"_zod",$r)}finally{$r.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),o){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;o.has(i)||(o.add(i),members(i,a))}let i=_.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let s=r?.Parent??Object;class Definition extends s{}Object.defineProperty(Definition,"name",{value:e});function _(e){let t=r?.Parent?newError(Definition):this;init(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(_,"name",{value:e}),_}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Qr=globalThis).__zod_globalConfig??(Qr.__zod_globalConfig={});const S=globalThis.__zod_globalConfig;function config(e){return e&&Object.assign(S,e),S}function _getMessage(){let e=this._zod;return e.message??=JSON.stringify(e.def,jsonStringifyReplacer,2),e.message}function _setMessage(e){this._zod.message=e}const ti={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},ni={value:void 0,enumerable:!1},ri=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),ii=/* @__PURE__ */ $constructor(`$ZodError`,(e,t)=>{e.name=`$ZodError`,ni.value=t,Object.defineProperty(e,"issues",ni),ni.value=void 0,Object.defineProperty(e,"message",ti);let n=Object.getPrototypeOf(e);ri.has(n)||(ri.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let value=()=>this.message;return Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0}),value},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))});function node(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function flattenError(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?node(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function formatError(e,t=e=>e.message){let n={_errors:[]},processError=(e,r=[])=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>processError({issues:e},[...r,...i.path]));else if(i.code===`invalid_key`)processError({issues:i.issues},[...r,...i.path]);else if(i.code===`invalid_element`)processError({issues:i.issues},[...r,...i.path]);else{let e=[...r,...i.path];if(e.length===0)n._errors.push(t(i));else{let r=n,a=0;for(;a<e.length;){let n=e[a],o=a===e.length-1;if(n===`_errors`){o&&r._errors.push(t(i)),a++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(i)),r=s,a++}}}};return processError(e),n}function finalizeParams(e,t){return{callee:t?.callee??e,Err:t?.Err}}const _parse=e=>{let fn=(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new $ZodAsyncError;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>finalizeIssue(e,a,config())));throw Ur(t,i?.callee??fn),t}return o.value};return fn},_parseAsync=e=>{let fn=async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>finalizeIssue(e,a,config())));throw Ur(t,i?.callee??fn),t}return o.value};return fn},_safeParse=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $ZodAsyncError;return a.issues.length?failure(e,a.issues,i):{success:!0,data:a.value}};function failure(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>finalizeIssue(e,n,config()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const _safeParseAsync=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?failure(e,a.issues,i):{success:!0,data:a.value}},ai=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),oi=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),validate=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==ai)return!0;if(r.definite===!0&&n===void 0)return!1}return validateFallback(e,t,n)});function validateFallback(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[oi]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new $ZodAsyncError;return a.issues.length===0}const validateAsync$1=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},_encode=e=>{let t=_parse(e),fn=(e,n,r,i)=>{let a=r?{...r,direction:`backward`}:{direction:`backward`};return t(e,n,a,finalizeParams(fn,i))};return fn},_decode=e=>{let t=_parse(e),fn=(e,n,r,i)=>t(e,n,r,finalizeParams(fn,i));return fn},_encodeAsync=e=>{let t=_parseAsync(e),fn=async(e,n,r,i)=>{let a=r?{...r,direction:`backward`}:{direction:`backward`};return await t(e,n,a,finalizeParams(fn,i))};return fn},_decodeAsync=e=>{let t=_parseAsync(e),fn=async(e,n,r,i)=>await t(e,n,r,finalizeParams(fn,i));return fn},_safeEncode=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParse(e)(t,n,i)},_safeDecode=e=>(t,n,r)=>_safeParse(e)(t,n,r),_safeEncodeAsync=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParseAsync(e)(t,n,i)},_safeDecodeAsync=e=>async(t,n,r)=>_safeParseAsync(e)(t,n,r),si=/^[cC][0-9a-z]{6,}$/,ci=/^[0-9a-z]+$/,li=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,ui=/^[0-9a-vA-V]{20}$/,di=/^[A-Za-z0-9]{27}$/,fi=/^[a-zA-Z0-9_-]{21}$/;function nanoidOfLength(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const pi=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,mi=/^([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=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([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)$/,hi=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function emoji(){return/* @__PURE__ */ RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const gi=/^(?:(?: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])$/,_i=/^(([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}|:))$/,vi=/^((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])$/,yi=/^(([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])$/,bi=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,xi=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Si=/^https?$/,Ci=/^\+[1-9]\d{6,14}$/,wi=`(?:(?:\\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])))`;function anchor(e){return RegExp(`^${e}$`)}const Ti=/*@__PURE__*/ anchor(wi);function timeSource(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(e){return RegExp(`^${timeSource(e)}$`)}function datetime(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${timeSource({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${timeSource({precision:e.precision})}`:n;return RegExp(`^${wi}T(?:${r})$`)}const Ei=/^[\s\S]{0,}$/,Di=/^-?\d+$/,Oi=/^-?\d+(?:\.\d+)?$/,ki=/^(?:true|false)$/i,Ai=/^undefined$/i,ji=/^[^A-Z]*$/,Mi=/^[^a-z]*$/,C=/*@__PURE__*/ $constructor(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),_whenHasLength=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0},Ni={number:`number`,bigint:`bigint`,object:`date`},Pi=/*@__PURE__*/ $constructor(`$ZodCheckLessThan`,(e,t)=>{C.init(e,t);let n=Ni[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Ni[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Fi=/*@__PURE__*/ $constructor(`$ZodCheckGreaterThan`,(e,t)=>{C.init(e,t);let n=Ni[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Ni[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ii=/*@__PURE__*/ $constructor(`$ZodCheckMultipleOf`,(e,t)=>{C.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):floatSafeRemainder(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Li=/*@__PURE__*/ $constructor(`$ZodCheckNumberFormat`,(e,t)=>{C.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Kr[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Ri=/*@__PURE__*/ $constructor(`$ZodCheckMaxLength`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?codePointLength(r):i)<=t.maximum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),zi=/*@__PURE__*/ $constructor(`$ZodCheckMinLength`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?codePointLength(r):i)>=t.minimum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Bi=/*@__PURE__*/ $constructor(`$ZodCheckLengthEquals`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?codePointLength(r):i;if(a===t.length)return;let o=getLengthableOrigin(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Vi=/*@__PURE__*/ $constructor(`$ZodCheckStringFormat`,(e,t)=>{var n,r;C.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Hi=/*@__PURE__*/ $constructor(`$ZodCheckRegex`,(e,t)=>{Vi.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Ui=/*@__PURE__*/ $constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=ji,Vi.init(e,t)}),Wi=/*@__PURE__*/ $constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Mi,Vi.init(e,t)}),Gi=/*@__PURE__*/ $constructor(`$ZodCheckIncludes`,(e,t)=>{C.init(e,t);let n=escapeRegex(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Ki=/*@__PURE__*/ $constructor(`$ZodCheckStartsWith`,(e,t)=>{C.init(e,t);let n=RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),qi=/*@__PURE__*/ $constructor(`$ZodCheckEndsWith`,(e,t)=>{C.init(e,t);let n=RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Ji=/*@__PURE__*/ $constructor(`$ZodCheckOverwrite`,(e,t)=>{C.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Doc=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
`)}\n};`)(...Object.values(this.closed))}};const Yi={major:4,minor:6,patch:7},w=/*@__PURE__*/ $constructor(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Yi;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let runChecks=(t,n,r)=>{if(t.memo)return t;let i=aborted(t),a;for(let o of n){if(o._zod.def.when){if(explicitlyAborted(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new $ZodAsyncError;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(attachSchema(t.issues,n,e),i||=aborted(t,n))});else{if(t.issues.length===n)continue;attachSchema(t.issues,n,e),i||=aborted(t,n)}}return a?a.then(()=>t):t},handleCanaryResult=(t,n,r)=>{if(aborted(t))return t.aborted=!0,t;let a=runChecks(n,i,r);if(a instanceof Promise){if(r.async===!1)throw new $ZodAsyncError;return a.then(t=>e._zod.parse(t,r))}return e._zod.parse(a,r)};e._zod.run=(t,n)=>{if(n.skipChecks)return e._zod.parse(t,n);if(n.direction===`backward`){let r=e._zod.parse({value:t.value,issues:[]},{...n,skipChecks:!0});return r instanceof Promise?r.then(e=>handleCanaryResult(e,t,n)):handleCanaryResult(r,t,n)}let r=e._zod.parse(t,n);if(r instanceof Promise){if(n.async===!1)throw new $ZodAsyncError;return r.then(e=>runChecks(e,i,n))}return runChecks(r,i,n)}}},{get"~standard"(){return hide(this,`~standard`,standardProps(this))},set"~standard"(e){own(this,`~standard`,e)}}),toStandardResult=(e,t)=>e.issues.length?{issues:e.issues.map(e=>finalizeIssue(e,t,config()))}:{value:e.value};async function validateAsync(e,t){let n={async:!0};return toStandardResult(await e._zod.run({value:t,issues:[]},n),n)}function standardProps(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return toStandardResult(r,n)}catch{}return validateAsync(e,t)},vendor:`zod`,version:1}}const Xi=/*@__PURE__*/ $constructor(`$ZodString`,(e,t)=>{w.init(e,t),e._zod.pattern=t.pattern??Ei,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),T=/*@__PURE__*/ $constructor(`$ZodStringFormat`,(e,t)=>{Vi.init(e,t),Xi.init(e,t)}),Zi=/*@__PURE__*/ $constructor(`$ZodGUID`,(e,t)=>{t.pattern??=mi,T.init(e,t)}),Qi=/*@__PURE__*/ $constructor(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=uuid(e)}else t.pattern??=uuid();T.init(e,t)}),$i=/*@__PURE__*/ $constructor(`$ZodEmail`,(e,t)=>{t.pattern??=hi,T.init(e,t)});function canParseURL(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function validateURL(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?canParseURL(e)||2:parseURLObject(e,t)}function parseURLObject(e,t){if(!t.normalize&&t.protocol?.source===Si.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}const ea=/[\t\n\r]/g;function stripTabAndNewline(e){return e.replace(ea,``)}function urlHostnameOk(e,t){return t.lastIndex=0,t.test(e.hostname)}function urlProtocolOk(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const ta=/*@__PURE__*/ $constructor(`$ZodURL`,(e,t)=>{T.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=validateURL(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=stripTabAndNewline(r);return}t.hostname&&!urlHostnameOk(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!urlProtocolOk(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:stripTabAndNewline(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),na=/*@__PURE__*/ $constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),T.init(e,t)}),ra=/*@__PURE__*/ $constructor(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?fi:nanoidOfLength(t.length),T.init(e,t)}),ia=/*@__PURE__*/ $constructor(`$ZodCUID`,(e,t)=>{t.pattern??=si,T.init(e,t)}),aa=/*@__PURE__*/ $constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=ci,T.init(e,t)}),oa=/*@__PURE__*/ $constructor(`$ZodULID`,(e,t)=>{t.pattern??=li,T.init(e,t)}),sa=/*@__PURE__*/ $constructor(`$ZodXID`,(e,t)=>{t.pattern??=ui,T.init(e,t)}),ca=/*@__PURE__*/ $constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=di,T.init(e,t)}),la=/*@__PURE__*/ $constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime(t),T.init(e,t)}),ua=/*@__PURE__*/ $constructor(`$ZodISODate`,(e,t)=>{t.pattern??=Ti,T.init(e,t)}),da=/*@__PURE__*/ $constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time(t),T.init(e,t)}),fa=/*@__PURE__*/ $constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=pi,T.init(e,t)}),pa=/*@__PURE__*/ $constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=gi,T.init(e,t)}),ma=/^[0-9a-fA-F:.]+$/;function isValidIPv6(e){return ma.test(e)?canParseURL(`http://[${e}]`):!1}const ha=/*@__PURE__*/ $constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=_i,T.init(e,t),e._zod.check=n=>{isValidIPv6(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),ga=/*@__PURE__*/ $constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=vi,T.init(e,t)});function isValidCIDRv6(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:isValidIPv6(n)}const _a=/*@__PURE__*/ $constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=yi,T.init(e,t),e._zod.check=n=>{isValidCIDRv6(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function isValidBase64(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const va=/^[0-9a-zA-Z+/]*={0,2}$/,ya=/*@__PURE__*/ $constructor(`$ZodBase64`,(e,t)=>{t.pattern??=va,T.init(e,t),e._zod.check=n=>{isValidBase64(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),ba=/^[A-Za-z0-9_-]*$/;function isValidBase64URL(e){if(!ba.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const xa=/*@__PURE__*/ $constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=ba,T.init(e,t),e._zod.check=n=>{isValidBase64URL(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Sa=/*@__PURE__*/ $constructor(`$ZodE164`,(e,t)=>{t.pattern??=Ci,T.init(e,t)});function isValidJWT(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const Ca=/*@__PURE__*/ $constructor(`$ZodJWT`,(e,t)=>{T.init(e,t),e._zod.check=n=>{isValidJWT(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),wa=/*@__PURE__*/ $constructor(`$ZodNumber`,(e,t)=>{w.init(e,t),e._zod.pattern=Oi,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Ta=/*@__PURE__*/ $constructor(`$ZodNumberFormat`,(e,t)=>{Li.init(e,t),wa.init(e,t)}),Ea=/*@__PURE__*/ $constructor(`$ZodBoolean`,(e,t)=>{w.init(e,t),e._zod.pattern=ki,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Da=/*@__PURE__*/ $constructor(`$ZodUndefined`,(e,t)=>{w.init(e,t),e._zod.pattern=Ai,e._zod.values=/* @__PURE__ */ new Set([void 0]),e._zod.parse=(t,n)=>{let r=t.value;return r===void 0||t.issues.push({expected:`undefined`,code:`invalid_type`,input:r,inst:e}),t}}),Oa=/*@__PURE__*/ $constructor(`$ZodUnknown`,(e,t)=>{w.init(e,t),e._zod.parse=e=>e}),ka=/*@__PURE__*/ $constructor(`$ZodNever`,(e,t)=>{w.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function capSize(e,t){let n=sizeCaps(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of sizeCaps(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,attachSchema(n.issues,t,e),n}}return i(n,a)}}const arraySize=e=>Array.isArray(e)?e.length:-1;function handleArrayResult(e,t,n){e.issues.length&&t.issues.push(...prefixIssues(n,e.issues)),t.value[n]=e.value}const Aa=/*@__PURE__*/ $constructor(`$ZodArray`,(e,t)=>{w.init(e,t);let n=S.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>handleArrayResult(t,r,e)));else if(handleArrayResult(c,r,e),s&&c.issues.length!==0&&aborted(c))break}return o.length?Promise.all(o).then(()=>r):r},capSize(e,arraySize)});function handlePropertyResult(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...prefixIssues(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}const ja=[];function normalizeDef(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:ja,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=optionalKeys(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function handleCatchall(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(aborted(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>handlePropertyResult(e,n,i,t,d,f))):handlePropertyResult(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Ma=/*@__PURE__*/ $constructor(`$ZodObject`,(e,t)=>{w.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let get=()=>{let e={...r};return Object.defineProperty(t,"shape",{value:e}),get.raw=e,e};get.raw=r,Object.defineProperty(t,"shape",{get})}let i=cached(()=>normalizeDef(t));defineLazyInternal(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||assignProp(n,e,/* @__PURE__ */ new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=isObject$1,o=t.catchall,s,c=S.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(aborted(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>handlePropertyResult(n,t,e,r,a,o))):handlePropertyResult(s,t,e,r,a,o)}return o?handleCatchall(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),Na=/*@__PURE__*/ $constructor(`$ZodObjectJIT`,(e,t)=>{Ma.init(e,t);let n=e._zod.parse,r=cached(()=>normalizeDef(t)),i=S.memoizer,generateFastpass=t=>{let n=r.value,a=n.symbolKeys,o=new Doc([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),parseStr=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,prefixStr=(e,t)=>`
          let ${e}_ab = false;
          for (let i = 0; i < ${e}.issues.length; i++) {
            const iss = ${e}.issues[i];
            iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
            payload.issues.push(iss);
            if (iss.continue !== true) ${e}_ab = true;
          }
          if (${e}_ab && ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }`;o.write(`const input = payload.value;`);let s=Object.create(null),c=0;for(let e of n.allKeys)s[e]=`key_${c++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=s[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:esc(e),i=`${r} in input`,c=t[e],l=c?._zod?.optin,u=l!==void 0,d=c?._zod?.optout===`optional`;if(o.write(`const ${n} = ${parseStr(r)};`),u&&d){let e=l===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
        const ${n}_present = ${i};
        if (!${n}.issues.length || ${n}_present) {
          if (${n}.issues.length) {${prefixStr(n,r)}
          }

          if (${e}) {
            newResult[${r}] = ${n}.value;
          }
        }

      `)}else u?(o.write(`
        if (${n}.issues.length) {${prefixStr(n,r)}
        }
      `),l===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(`
        if (${n}.value !== undefined || ${i}) {
          newResult[${r}] = ${n}.value;
        }
      `)):o.write(`
        const ${n}_present = ${i};
        if (${n}.issues.length) {${prefixStr(n,r)}
        }
        if (!${n}_present && !${n}.issues.length) {
          payload.issues.push({
            code: "invalid_type",
            expected: "nonoptional",
            input: undefined,
            path: [${r}]
          });
          if (ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }
        }

        if (${n}_present) {
          newResult[${r}] = ${n}.value;
        }

      `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},a,o=isObject$1,s=!S.jitless,c=s&&Wr.value,l=t.catchall,u;e._zod.parse=(i,d)=>{u??=r.value;let f=i.value;return o(f)?s&&c&&d?.async===!1&&d.jitless!==!0?(a||=generateFastpass(t.shape),i=a(i,d),l?handleCatchall([],f,i,d,u,e,d?.abortEarly===!0):i):n(i,d):(i.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),i)}});function handleUnionResults(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!aborted(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>finalizeIssue(e,r,config())))}),t)}const Pa=/*@__PURE__*/ $constructor(`$ZodUnion`,(e,t)=>{w.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),defineLazyInternal(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),defineLazyInternal(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),defineLazyInternal(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>cleanRegex(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>handleUnionResults(t,r,e,i)):handleUnionResults(o,r,e,i)}});function discriminatorMap(e){let t=/* @__PURE__ */ new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}const Fa=/*@__PURE__*/ $constructor(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Pa.init(e,t);let n=e._zod.parse;defineLazyInternal(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||assignProp(t,e,/* @__PURE__ */ new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=rawShape(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=cached(()=>discriminatorMap(t));e._zod.parse=(i,a)=>{let o=i.value;if(!isObject$1(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),Ia=/*@__PURE__*/ $constructor(`$ZodIntersection`,(e,t)=>{w.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>handleIntersectionResults(e,t,n)):handleIntersectionResults(e,i,a)}});function mergeValues(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(isPlainObject(e)&&isPlainObject(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=mergeValues(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=mergeValues(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function handleIntersectionResults(e,t,n){let r=/* @__PURE__ */ new Map,i,a=/* @__PURE__ */ new Map,collect=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)collect(n,`l`)||e.issues.push(n);for(let t of n.issues)collect(t,`r`)||e.issues.push(t);let o=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length){let t=i?o.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of o)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let s=mergeValues(t.value,n.value);if(!s.valid){if(aborted(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`)}return e.value=s.data,e}const La=/*@__PURE__*/ $constructor(`$ZodRecord`,(e,t)=>{w.init(e,t);let n=S.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!isPlainObject(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=/* @__PURE__ */ new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>finalizeIssue(e,i,config())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...prefixIssues(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...prefixIssues(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&Oi.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>finalizeIssue(e,i,config())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...prefixIssues(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...prefixIssues(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Ra=/*@__PURE__*/ $constructor(`$ZodEnum`,(e,t)=>{w.init(e,t);let n=getEnumValues(t.entries),r=new Set(n);e._zod.values=r,defineLazyInternal(e,`pattern`,e=>{let t=getEnumValues(e.def.entries).filter(e=>Gr.has(typeof e));return RegExp(t.length?`^(${t.map(e=>escapeRegex(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),za=/*@__PURE__*/ $constructor(`$ZodLiteral`,(e,t)=>{w.init(e,t);let n=new Set(t.values);e._zod.values=n,defineLazyInternal(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?escapeRegex(e):e?escapeRegex(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Ba=/*@__PURE__*/ $constructor(`$ZodTransform`,(e,t)=>{w.init(e,t),e._zod.optin=`optional`,S.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new $ZodAsyncError;return n.value=i,n}});function handleOptionalResult(e,t){return e.value=t.issues.length?void 0:t.value,e}const Va=/*@__PURE__*/ $constructor(`$ZodOptional`,(e,t)=>{w.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,defineLazyInternal(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0}),defineLazyInternal(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${cleanRegex(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>handleOptionalResult(e,t)):handleOptionalResult(e,r)}return t.innerType._zod.run(e,n)}}),Ha=/*@__PURE__*/ $constructor(`$ZodExactOptional`,(e,t)=>{Va.init(e,t),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),defineLazyInternal(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Ua=/*@__PURE__*/ $constructor(`$ZodNullable`,(e,t)=>{w.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin),defineLazyInternal(e,`optout`,e=>e.def.innerType._zod.optout),defineLazyInternal(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${cleanRegex(t.source)}|null)$`):void 0}),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values?/* @__PURE__ */ new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Wa=/*@__PURE__*/ $constructor(`$ZodDefault`,(e,t)=>{w.init(e,t),e._zod.optin=`defaulted`,defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>handleDefaultResult(e,t)):handleDefaultResult(r,t)}});function handleDefaultResult(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Ga=/*@__PURE__*/ $constructor(`$ZodPrefault`,(e,t)=>{w.init(e,t),e._zod.optin=`defaulted`,defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Ka=/*@__PURE__*/ $constructor(`$ZodNonOptional`,(e,t)=>{w.init(e,t),defineLazyInternal(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>handleNonOptionalResult(t,e)):handleNonOptionalResult(i,e)}});function handleNonOptionalResult(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function handleCatchResult(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>finalizeIssue(e,r,config()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const qa=/*@__PURE__*/ $constructor(`$ZodCatch`,(e,t)=>{w.init(e,t),defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),defineLazyInternal(e,`optout`,e=>e.def.innerType._zod.optout),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>handleCatchResult(e,r,t,n)):handleCatchResult(e,r,t,n)}}),Ja=/*@__PURE__*/ $constructor(`$ZodPipe`,(e,t)=>{w.init(e,t),defineLazyInternal(e,`values`,e=>e.def.in._zod.values),defineLazyInternal(e,`optin`,e=>e.def.in._zod.optin),defineLazyInternal(e,`optout`,e=>e.def.out._zod.optout),defineLazyInternal(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.in,n)):handlePipeResult(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>handlePipeResult(e,t.out,n)):handlePipeResult(r,t.out,n)}});function handlePipeResult(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Ya=/*@__PURE__*/ $constructor(`$ZodReadonly`,(e,t)=>{w.init(e,t),defineLazyInternal(e,`propValues`,e=>e.def.innerType._zod.propValues),defineLazyInternal(e,`values`,e=>e.def.innerType._zod.values),defineLazyInternal(e,`optin`,e=>e.def.innerType?._zod?.optin),defineLazyInternal(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(handleReadonlyResult):handleReadonlyResult(r)}});function handleReadonlyResult(e){return e.memo||(e.value=Object.freeze(e.value)),e}const Xa=/*@__PURE__*/ $constructor(`$ZodCustom`,(e,t)=>{C.init(e,t),w.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>handleRefineResult(t,n,r,e));handleRefineResult(i,n,r,e)}});function handleRefineResult(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(issue(e))}}var $ZodCyclicError=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const Za=`~memo`,Qa=[];function isRef(e){return typeof e==`object`&&!!e}function cloneIssues(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const $a=/*@__PURE__*/ new WeakMap;function isRecursive(e,t,n){let r=$a.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,check=e=>{if(i!==2&&e?._zod){let r=isRecursive(e,t,n);r>i&&(i=r)}},shape=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?1:o.value?._zod?isRecursive(o.value,t,n):0;s>i&&(i=s)}return i},merge=e=>{e>i&&(i=e)},a=e._zod.def;switch(a.type){case`object`:{let e=rawShape(a);merge(e?shape(e,!0):1),check(a.catchall);break}case`array`:check(a.element);break;case`tuple`:for(let e of a.items)check(e);check(a.rest);break;case`record`:case`map`:check(a.keyType),check(a.valueType);break;case`set`:check(a.valueType);break;case`union`:for(let e of a.options)check(e);break;case`intersection`:check(a.left),check(a.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:check(a.innerType);break;case`pipe`:check(a.in),check(a.out);break;case`function`:check(a.input),check(a.output);break;case`lazy`:{let r=a._cachedInner??(n?e._zod.innerType:void 0);merge(r?isRecursive(r,t,!1):1);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(let e in a){let t=Object.getOwnPropertyDescriptor(a,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)check(n);else if(Array.isArray(n))for(let e of n)check(e)}}}return t.delete(e),settle(e,i)}function settle(e,t){return t!==1&&$a.set(e,t===2),t}function bucketFor(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let eo;const to=[],no={alloc(e,t,n){let r=eo;if(!r)return n;eo=void 0;let i={value:n,issues:null};return r.set(t.value,i),to.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,wrapped=(e,n)=>{if(n.direction!==`backward`&&isBackEdge(n,e.value))throw new $ZodCyclicError;return t(e,n)};e._zod.parse=wrapped,e._zod.run===t&&(e._zod.run=wrapped)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,wrapped=(o,s)=>{if(n===void 0){let i=isRecursive(e,/* @__PURE__ */ new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===wrapped&&(e._zod.run=t),t(o,s);i===2||r?n=!0:r=!0}let c=o.value;if(!isRef(c))return t(o,s);let l=s[Za];l||(l={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},s[Za]=l);let u;i===s?u=a:(u=bucketFor(l,e),i=s,a=u);let d=u.get(c);if(d)return o.value=d.value,d.issues?d.issues.length&&o.issues.push(...cloneIssues(d.issues)):(o.memo=!0,l.backEdges??(l.backEdges=/* @__PURE__ */ new WeakSet),l.backEdges.add(d.value)),o;eo=u;let f=to.length,p=t(o,s);eo=void 0;let m=to.length>f?to.pop():void 0;return p instanceof Promise?p.then(e=>(m&&(m.issues=e.issues.length?cloneIssues(e.issues):Qa),e)):(m&&(m.issues=p.issues.length?cloneIssues(p.issues):Qa),p)};e._zod.parse=wrapped,e._zod.run===t&&(e._zod.run=wrapped)})}};function memoizer(){return no}function isBackEdge(e,t){let n=e[Za]?.backEdges;return n!==void 0&&isRef(t)&&n.has(t)}const error=()=>{let e={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(t){return e[t]??null}let t={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`},n={nan:`NaN`};function getTypeName(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):n[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${getTypeName(e.expected)}, received ${getTypeName(parsedType(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${stringifyPrimitive(e.values[0])}`:`Invalid option: expected one of ${joinValues(e.values,`|`)}`;case`too_big`:{let t=e.exact?`exactly `:e.inclusive?`<=`:`<`,n=getSizing(e.origin);return n?`Too big: expected ${e.origin??`value`} to have ${t}${e.maximum.toString()} ${n.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${t}${e.maximum.toString()}`}case`too_small`:{let t=e.exact?`exactly `:e.inclusive?`>=`:`>`,n=getSizing(e.origin);return n?`Too small: expected ${e.origin} to have ${t}${e.minimum.toString()} ${n.unit}`:`Too small: expected ${e.origin} to be ${t}${e.minimum.toString()}`}case`invalid_format`:{let n=e;return n.format===`starts_with`?`Invalid string: must start with "${n.prefix}"`:n.format===`ends_with`?`Invalid string: must end with "${n.suffix}"`:n.format===`includes`?`Invalid string: must include "${n.includes}"`:n.format===`regex`?`Invalid string: must match pattern ${n.pattern}`:`Invalid ${t[n.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${joinValues(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function en_default(){return{localeError:error()}}var ro,$ZodRegistry=class{constructor(){this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function registry(){return new $ZodRegistry}(ro=globalThis).__zod_globalRegistry??(ro.__zod_globalRegistry=registry());const io=globalThis.__zod_globalRegistry;function snapshotChecks(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
function _string(e,t){return new e(snapshotChecks({type:`string`,...normalizeParams(t)}))}// @__NO_SIDE_EFFECTS__
function _email(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _guid(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuid(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv4(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv6(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv7(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _url(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _emoji(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _nanoid(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cuid(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cuid2(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ulid(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _xid(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ksuid(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ipv4(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ipv6(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cidrv4(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cidrv6(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _base64(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _base64url(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _e164(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _jwt(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDateTime(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDate(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoTime(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDuration(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _number(e,t){return new e(snapshotChecks({type:`number`,checks:[],...normalizeParams(t)}))}// @__NO_SIDE_EFFECTS__
function _int(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _boolean(e,t){return new e({type:`boolean`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _undefined$1(e,t){return new e({type:`undefined`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _unknown(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
function _never(e,t){return new e({type:`never`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _lt(e,t){return new Pi({check:`less_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _lte(e,t){return new Pi({check:`less_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _gt(e,t){return new Fi({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _gte(e,t){return new Fi({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _multipleOf(e,t){return new Ii({check:`multiple_of`,...normalizeParams(t),value:e})}// @__NO_SIDE_EFFECTS__
function _maxLength(e,t){return new Ri({check:`max_length`,...normalizeParams(t),maximum:e})}// @__NO_SIDE_EFFECTS__
function _minLength(e,t){return new zi({check:`min_length`,...normalizeParams(t),minimum:e})}// @__NO_SIDE_EFFECTS__
function _length(e,t){return new Bi({check:`length_equals`,...normalizeParams(t),length:e})}// @__NO_SIDE_EFFECTS__
function _regex(e,t){return new Hi({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}// @__NO_SIDE_EFFECTS__
function _lowercase(e){return new Ui({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _uppercase(e){return new Wi({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _includes(e,t){return new Gi({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}// @__NO_SIDE_EFFECTS__
function _startsWith(e,t){return new Ki({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}// @__NO_SIDE_EFFECTS__
function _endsWith(e,t){return new qi({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}// @__NO_SIDE_EFFECTS__
function _overwrite(e){return new Ji({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
function _normalize(e){return/* @__PURE__ */ _overwrite(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
function _trim(){return/* @__PURE__ */ _overwrite(e=>e.trim())}// @__NO_SIDE_EFFECTS__
function _toLowerCase(){return/* @__PURE__ */ _overwrite(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
function _toUpperCase(){return/* @__PURE__ */ _overwrite(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
function _slugify(){return/* @__PURE__ */ _overwrite(e=>slugify(e))}// @__NO_SIDE_EFFECTS__
function _array(e,t,n){return new e({type:`array`,element:t,...normalizeParams(n)})}// @__NO_SIDE_EFFECTS__
function _custom(e,t,n){let r=normalizeParams(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
function _refine(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...normalizeParams(n)})}// @__NO_SIDE_EFFECTS__
function _superRefine(e,t){let n=/* @__PURE__ */ _check(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(issue(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(issue(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
function _check(e,t){let n=new C({check:`custom`,...normalizeParams(t)});return n._zod.check=e,n}function assignProps(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&assignProp(e,t,n[t]);return e}function initializeContext(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??io,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function handleUnrepresentable(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function processSchema(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,processSchema(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&assignProps(o.schema,c),t.io===`input`&&isTransforming(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function encodeJSONPointerSegment(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function extractDefs(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let makeURI=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${encodeJSONPointerSegment(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+encodeJSONPointerSegment(a)}},extractToDef=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=makeURI(e);t.def={...t.schema},r&&(t.defId=r);let i=t.schema;for(let e in i)delete i[e];i.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])extractToDef(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){extractToDef(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&extractToDef(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function compactTypeUnion(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;compactTypeUnion(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const ao=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),oo=[`oneOf`,`anyOf`];function undeclaredConstraint(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function foldObjects(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!ao.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??undeclaredConstraint(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}assignProp(n,r,e.length===1?e[0]:foldObjects(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=undeclaredConstraint(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function foldIntersection(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of ao)if(t in e)return;let n=t.filter(e=>oo.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=foldObjects(t);else{let e=n[0],i=oo.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>foldObjects([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,assignProps(e,r))}function finalize(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let flattenRef=t=>{let n=e.seen.get(t);if(n.ref===null)return;let r=n.def??n.schema,i={...r},a=n.ref;if(n.ref=null,a){flattenRef(a);let n=e.seen.get(a),o=n.schema;if(o.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(r.allOf=r.allOf??[],r.allOf.push(o)):assignProps(r,o),assignProps(r,i),t._zod.parent===a)for(let e in r)e!==`$ref`&&e!==`allOf`&&(e in i||delete r[e]);if(o.$ref&&n.def)for(let e in r)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(r[e])===JSON.stringify(n.def[e])&&delete r[e]}let o=t._zod.parent;if(o&&o!==a){flattenRef(o);let t=e.seen.get(o);if(t?.schema.$ref&&(r.$ref=t.schema.$ref,t.def))for(let e in r)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(r[e])===JSON.stringify(t.def[e])&&delete r[e]}e.override({zodSchema:t,jsonSchema:r,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())flattenRef(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())compactTypeUnion(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])foldIntersection(e)}}let r={};if(e.target===`draft-2020-12`?r.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?r.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?r.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(n)}assignProps(r,n.defId?n.schema:n.def??n.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&r.id===i&&delete r.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,assignProp(a,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?r.$defs=a:r.definitions=a);try{let n=JSON.parse(JSON.stringify(r));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return isTransforming(r.element,n);if(r.type===`set`)return isTransforming(r.valueType,n);if(r.type===`lazy`)return isTransforming(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return isTransforming(r.innerType,n);if(r.type===`intersection`)return isTransforming(r.left,n)||isTransforming(r.right,n);if(r.type===`record`||r.type===`map`)return isTransforming(r.keyType,n)||isTransforming(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:isTransforming(r.in,n)||isTransforming(r.out,n);if(r.type===`object`){for(let e in r.shape)if(isTransforming(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(isTransforming(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(isTransforming(e,n))return!0;return!!(r.rest&&isTransforming(r.rest,n))}return!1}const createToJSONSchemaMethod=(e,t={})=>n=>{let r=initializeContext({...n,processors:t});return processSchema(e,r),extractDefs(r,e),finalize(r,e)},createStandardJSONSchemaMethod=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=initializeContext({...i??{},target:a,io:t,processors:n});return processSchema(e,o),extractDefs(o,e),finalize(o,e)},narrowMin=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},narrowMax=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},narrowBoth=(e,t)=>{narrowMin(e,`minimum`,t),narrowMax(e,`maximum`,t)},addDivisor=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},addPattern=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},intersectMime=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},setFormat=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},minContributor=(e,t)=>narrowMin(e,`minimum`,t.minimum),maxContributor=(e,t)=>narrowMax(e,`maximum`,t.maximum),formatContributor=e=>(t,n)=>{setFormat(t,n.format);let[r,i]=e[n.format];narrowMin(t,`minimum`,r),narrowMax(t,`maximum`,i)},so={greater_than:(e,t)=>narrowMin(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>narrowMax(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>addDivisor(e,t.value),number_format:formatContributor(Kr),bigint_format:formatContributor(qr),min_length:minContributor,max_length:maxContributor,length_equals:(e,t)=>narrowBoth(e,t.length),min_size:minContributor,max_size:maxContributor,size_equals:(e,t)=>narrowBoth(e,t.size),string_format:(e,t)=>{setFormat(e,t.format),t.pattern&&addPattern(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>intersectMime(e,t.mime)};function aggregateChecks(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)so[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&narrowMin(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&narrowMin(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&narrowMax(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&narrowMax(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&addDivisor(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&intersectMime(t,i.mime);for(let e of i.patterns??[])addPattern(t,e);return t}const co={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},lo=/* @__PURE__ */ new Map([[va,bi],[ba,xi]]),exactPattern=e=>lo.get(e)??e,stringProcessor=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=aggregateChecks(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=co[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(exactPattern);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=aggregateChecks(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):handleUnrepresentable(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},booleanProcessor=(e,t,n,r)=>{n.type=`boolean`},undefinedProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},neverProcessor=(e,t,n,r)=>{n.not={}},enumProcessor=(e,t,n,r)=>{let i=e._zod.def,a=getEnumValues(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},literalProcessor=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(handleUnrepresentable(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(handleUnrepresentable(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},customProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},transformProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},arrayProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=aggregateChecks(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=processSchema(a.element,t,{...r,path:[...r.path,`items`]})};function inputOptin(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?inputOptin(t.out):t.type===`catch`?inputOptin(t.innerType):e._zod.optin}const objectProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&handleUnrepresentable(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)assignProp(i.properties,e,processSchema(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?inputOptin(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=processSchema(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},unionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>processSchema(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},intersectionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=processSchema(i.right,t,{...r,path:[...r.path,`allOf`,1]}),isSimpleIntersection=e=>`allOf`in e&&Object.keys(e).length===1,s=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(o)?o.allOf:[o]];n.allOf=s,t.intersections.push(s)};function stringifyKeyNames(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=stringifyKeyNames(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>stringifyKeyNames(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Oi:Di).source)),p}const uo=/* @__PURE__ */ new WeakMap;function rewriteKeyNames(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of uo.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=stringifyKeyNames(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}const recordProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=aggregateChecks(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=processSchema(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)assignProp(i.patternProperties,exactPattern(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=processSchema(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=uo.get(t);n||(n=[],uo.set(t,n),t.deferred.push(()=>rewriteKeyNames(t))),n.push(e)}i.additionalProperties=processSchema(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&inputOptin(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},nullableProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},nonoptionalProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},fo=Symbol();function serializeDefaultValue(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(handleUnrepresentable(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),fo):JSON.parse(o)}const defaultProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=serializeDefaultValue(i.defaultValue,e,t,n,r);o!==fo&&(n.default=o)},prefaultProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=serializeDefaultValue(i.defaultValue,e,t,n,r);o!==fo&&(n._prefault=o)},catchProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{handleUnrepresentable(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},pipeProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;processSchema(o,t,r);let s=t.seen.get(e);s.ref=o},readonlyProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},optionalProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},po=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const E=/*@__PURE__*/ $constructor(`ZodError`,(e,t)=>{ii.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);po.has(n)||(po.add(n),_lazyMethod(n,`format`,e=>t=>formatError(e,t)),_lazyMethod(n,`flatten`,e=>t=>flattenError(e,t)),_lazyMethod(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),_lazyMethod(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),mo=/* @__PURE__ */ _parse(E),ho=/* @__PURE__ */ _parseAsync(E),go=/* @__PURE__ */ _safeParse(E),_o=/* @__PURE__ */ _safeParseAsync(E),vo=/* @__PURE__ */ _encode(E),yo=/* @__PURE__ */ _decode(E),bo=/* @__PURE__ */ _encodeAsync(E),xo=/* @__PURE__ */ _decodeAsync(E),So=/* @__PURE__ */ _safeEncode(E),Co=/* @__PURE__ */ _safeDecode(E),wo=/* @__PURE__ */ _safeEncodeAsync(E),To=/* @__PURE__ */ _safeDecodeAsync(E);function _ensureDefaultLocale(){S.localeError||config(en_default())}function _ensureDefaultMemoizer(){S.memoizer||config({memoizer:memoizer()})}const D=/*@__PURE__*/ $constructor(`ZodType`,(e,t)=>(_ensureDefaultLocale(),w.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return clone(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(refine(e,t))},superRefine(e,t){return this.check(superRefine(e,t))},overwrite(e){return this.check(/* @__PURE__ */ _overwrite(e))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(e){return nonoptional(this,e)},array(){return array(this)},or(e){return union([this,e])},and(e){return intersection(this,e)},transform(e){return pipe(this,transform(e))},default(e){return _default(this,e)},prefault(e){return prefault(this,e)},catch(e){return _catch(this,e)},pipe(e){return pipe(this,e)},readonly(){return readonly(this)},describe(e){let t=this.clone();return io.add(t,{description:e}),t},meta(...e){if(e.length===0)return io.get(this);let t=this.clone();return io.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return hide(this,`~standard`,{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,`input`),output:createStandardJSONSchemaMethod(this,`output`)}})},set"~standard"(e){own(this,`~standard`,e)},parse:function _parse(e,t){return mo(this,e,t,{callee:_parse})},parseAsync:async function _parseAsync(e,t){return await ho(this,e,t,{callee:_parseAsync})},safeParse(e,t){return go(this,e,t)},async safeParseAsync(e,t){return _o(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){own(this,`spa`,e)},validate(e,t){return validate(this,e,t)},validateAsync(e,t){return validateAsync$1(this,e,t)},encode:function _encode(e,t){return vo(this,e,t,{callee:_encode})},decode:function _decode(e,t){return yo(this,e,t,{callee:_decode})},encodeAsync:async function _encodeAsync(e,t){return await bo(this,e,t,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(e,t){return await xo(this,e,t,{callee:_decodeAsync})},safeEncode(e,t){return So(this,e,t)},safeDecode(e,t){return Co(this,e,t)},async safeEncodeAsync(e,t){return wo(this,e,t)},async safeDecodeAsync(e,t){return To(this,e,t)},toJSONSchema(e){return createToJSONSchemaMethod(this,{})(e)},get description(){return io.get(this)?.description},get _def(){return this._zod.def}}),Eo=/*@__PURE__*/ $constructor(`_ZodString`,(e,t)=>{Xi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>stringProcessor(e,t,n,r)},/*@__PURE__*/ derived({format:e=>aggregateChecks(e).format??null,minLength:e=>aggregateChecks(e).minimum??null,maxLength:e=>aggregateChecks(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ _regex(...e))},includes(...e){return this.check(/* @__PURE__ */ _includes(...e))},startsWith(...e){return this.check(/* @__PURE__ */ _startsWith(...e))},endsWith(...e){return this.check(/* @__PURE__ */ _endsWith(...e))},min(...e){return this.check(/* @__PURE__ */ _minLength(...e))},max(...e){return this.check(/* @__PURE__ */ _maxLength(...e))},length(...e){return this.check(/* @__PURE__ */ _length(...e))},nonempty(...e){return this.check(/* @__PURE__ */ _minLength(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ _lowercase(e))},uppercase(e){return this.check(/* @__PURE__ */ _uppercase(e))},trim(){return this.check(/* @__PURE__ */ _trim())},normalize(...e){return this.check(/* @__PURE__ */ _normalize(...e))},toLowerCase(){return this.check(/* @__PURE__ */ _toLowerCase())},toUpperCase(){return this.check(/* @__PURE__ */ _toUpperCase())},slugify(){return this.check(/* @__PURE__ */ _slugify())}})),Do=/*@__PURE__*/ $constructor(`ZodString`,(e,t)=>{Xi.init(e,t),Eo.init(e,t)},{email(e){return this.check(/* @__PURE__ */ _email(Mo,e))},url(e){return this.check(/* @__PURE__ */ _url(Fo,e))},jwt(e){return this.check(/* @__PURE__ */ _jwt(Xo,e))},emoji(e){return this.check(/* @__PURE__ */ _emoji(Io,e))},guid(e){return this.check(/* @__PURE__ */ _guid(No,e))},uuid(e){return this.check(/* @__PURE__ */ _uuid(Po,e))},uuidv4(e){return this.check(/* @__PURE__ */ _uuidv4(Po,e))},uuidv6(e){return this.check(/* @__PURE__ */ _uuidv6(Po,e))},uuidv7(e){return this.check(/* @__PURE__ */ _uuidv7(Po,e))},nanoid(e){return this.check(/* @__PURE__ */ _nanoid(Lo,e))},cuid(e){return this.check(/* @__PURE__ */ _cuid(Ro,e))},cuid2(e){return this.check(/* @__PURE__ */ _cuid2(zo,e))},ulid(e){return this.check(/* @__PURE__ */ _ulid(Bo,e))},base64(e){return this.check(/* @__PURE__ */ _base64(qo,e))},base64url(e){return this.check(/* @__PURE__ */ _base64url(Jo,e))},xid(e){return this.check(/* @__PURE__ */ _xid(Vo,e))},ksuid(e){return this.check(/* @__PURE__ */ _ksuid(Ho,e))},ipv4(e){return this.check(/* @__PURE__ */ _ipv4(Uo,e))},ipv6(e){return this.check(/* @__PURE__ */ _ipv6(Wo,e))},cidrv4(e){return this.check(/* @__PURE__ */ _cidrv4(Go,e))},cidrv6(e){return this.check(/* @__PURE__ */ _cidrv6(Ko,e))},e164(e){return this.check(/* @__PURE__ */ _e164(Yo,e))},datetime(e){return this.check(/* @__PURE__ */ _isoDateTime(Oo,e))},date(e){return this.check(/* @__PURE__ */ _isoDate(ko,e))},time(e){return this.check(/* @__PURE__ */ _isoTime(Ao,e))},duration(e){return this.check(/* @__PURE__ */ _isoDuration(jo,e))}});function string(e){return/* @__PURE__ */ _string(Do,e)}const O=/*@__PURE__*/ $constructor(`ZodStringFormat`,(e,t)=>{T.init(e,t),Eo.init(e,t)}),Oo=/*@__PURE__*/ $constructor(`ZodISODateTime`,(e,t)=>{la.init(e,t),O.init(e,t)}),ko=/*@__PURE__*/ $constructor(`ZodISODate`,(e,t)=>{ua.init(e,t),O.init(e,t)}),Ao=/*@__PURE__*/ $constructor(`ZodISOTime`,(e,t)=>{da.init(e,t),O.init(e,t)}),jo=/*@__PURE__*/ $constructor(`ZodISODuration`,(e,t)=>{fa.init(e,t),O.init(e,t)}),Mo=/*@__PURE__*/ $constructor(`ZodEmail`,(e,t)=>{$i.init(e,t),O.init(e,t)}),No=/*@__PURE__*/ $constructor(`ZodGUID`,(e,t)=>{Zi.init(e,t),O.init(e,t)}),Po=/*@__PURE__*/ $constructor(`ZodUUID`,(e,t)=>{Qi.init(e,t),O.init(e,t)}),Fo=/*@__PURE__*/ $constructor(`ZodURL`,(e,t)=>{ta.init(e,t),O.init(e,t)}),Io=/*@__PURE__*/ $constructor(`ZodEmoji`,(e,t)=>{na.init(e,t),O.init(e,t)}),Lo=/*@__PURE__*/ $constructor(`ZodNanoID`,(e,t)=>{ra.init(e,t),O.init(e,t)}),Ro=/*@__PURE__*/ $constructor(`ZodCUID`,(e,t)=>{ia.init(e,t),O.init(e,t)}),zo=/*@__PURE__*/ $constructor(`ZodCUID2`,(e,t)=>{aa.init(e,t),O.init(e,t)}),Bo=/*@__PURE__*/ $constructor(`ZodULID`,(e,t)=>{oa.init(e,t),O.init(e,t)}),Vo=/*@__PURE__*/ $constructor(`ZodXID`,(e,t)=>{sa.init(e,t),O.init(e,t)}),Ho=/*@__PURE__*/ $constructor(`ZodKSUID`,(e,t)=>{ca.init(e,t),O.init(e,t)}),Uo=/*@__PURE__*/ $constructor(`ZodIPv4`,(e,t)=>{pa.init(e,t),O.init(e,t)}),Wo=/*@__PURE__*/ $constructor(`ZodIPv6`,(e,t)=>{ha.init(e,t),O.init(e,t)}),Go=/*@__PURE__*/ $constructor(`ZodCIDRv4`,(e,t)=>{ga.init(e,t),O.init(e,t)}),Ko=/*@__PURE__*/ $constructor(`ZodCIDRv6`,(e,t)=>{_a.init(e,t),O.init(e,t)}),qo=/*@__PURE__*/ $constructor(`ZodBase64`,(e,t)=>{ya.init(e,t),O.init(e,t)}),Jo=/*@__PURE__*/ $constructor(`ZodBase64URL`,(e,t)=>{xa.init(e,t),O.init(e,t)}),Yo=/*@__PURE__*/ $constructor(`ZodE164`,(e,t)=>{Sa.init(e,t),O.init(e,t)}),Xo=/*@__PURE__*/ $constructor(`ZodJWT`,(e,t)=>{Ca.init(e,t),O.init(e,t)}),Zo=/*@__PURE__*/ $constructor(`ZodNumber`,(e,t)=>{wa.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>numberProcessor(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ derived({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=aggregateChecks(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=aggregateChecks(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=aggregateChecks(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>aggregateChecks(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ _gt(e,t))},gte(e,t){return this.check(/* @__PURE__ */ _gte(e,t))},min(e,t){return this.check(/* @__PURE__ */ _gte(e,t))},lt(e,t){return this.check(/* @__PURE__ */ _lt(e,t))},lte(e,t){return this.check(/* @__PURE__ */ _lte(e,t))},max(e,t){return this.check(/* @__PURE__ */ _lte(e,t))},int(e){return this.check(int(e))},safe(e){return this.check(int(e))},positive(e){return this.check(/* @__PURE__ */ _gt(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ _gte(0,e))},negative(e){return this.check(/* @__PURE__ */ _lt(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ _lte(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ _multipleOf(e,t))},step(e,t){return this.check(/* @__PURE__ */ _multipleOf(e,t))},finite(){return this}}));function number(e){return/* @__PURE__ */ _number(Zo,e)}const Qo=/*@__PURE__*/ $constructor(`ZodNumberFormat`,(e,t)=>{Ta.init(e,t),Zo.init(e,t)});function int(e){return/* @__PURE__ */ _int(Qo,e)}const $o=/*@__PURE__*/ $constructor(`ZodBoolean`,(e,t)=>{Ea.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n,r)});function boolean(e){return/* @__PURE__ */ _boolean($o,e)}const es=/*@__PURE__*/ $constructor(`ZodUndefined`,(e,t)=>{Da.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>undefinedProcessor(e,t,n,r)});function _undefined(e){return/* @__PURE__ */ _undefined$1(es,e)}const ts=/*@__PURE__*/ $constructor(`ZodUnknown`,(e,t)=>{Oa.init(e,t),D.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function unknown(){return/* @__PURE__ */ _unknown(ts)}const ns=/*@__PURE__*/ $constructor(`ZodNever`,(e,t)=>{ka.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)});function never(e){return/* @__PURE__ */ _never(ns,e)}const rs=/*@__PURE__*/ $constructor(`ZodArray`,(e,t)=>{_ensureDefaultMemoizer(),Aa.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>arrayProcessor(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ _minLength(e,t))},nonempty(e){return this.check(/* @__PURE__ */ _minLength(1,e))},max(e,t){return this.check(/* @__PURE__ */ _maxLength(e,t))},length(e,t){return this.check(/* @__PURE__ */ _length(e,t))},unwrap(){return this.element}});function array(e,t){return/* @__PURE__ */ _array(rs,e,t)}const is=/*@__PURE__*/ $constructor(`ZodObject`,(e,t)=>{_ensureDefaultMemoizer(),Na.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>objectProcessor(e,t,n,r),installLazyProp(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(mergeDefs(this._zod.def,{catchall:e}))},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(e){return extend(this,e)},safeExtend(e){return safeExtend(this,e)},merge(e){return merge(this,e)},pick(e){return pick(this,e)},omit(e){return omit(this,e)},partial(...e){return partial(fs,this,e[0])},exactPartial(...e){return partial(ps,this,e[0],`exactPartial`)},required(...e){return required(_s,this,e[0])}});function object(e,t){let n={type:`object`,shape:e??{},...normalizeParams(t)};return new is(n)}function strictObject(e,t){return new is({type:`object`,shape:e,catchall:never(),...normalizeParams(t)})}function looseObject(e,t){return new is({type:`object`,shape:e,catchall:unknown(),...normalizeParams(t)})}const as=/*@__PURE__*/ $constructor(`ZodUnion`,(e,t)=>{Pa.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r),e.options=t.options});function union(e,t){return new as({type:`union`,options:e,...normalizeParams(t)})}const os=/*@__PURE__*/ $constructor(`ZodDiscriminatedUnion`,(e,t)=>{as.init(e,t),Fa.init(e,t)});function discriminatedUnion(e,t,n){return new os({type:`union`,options:t,discriminator:e,...normalizeParams(n)})}const ss=/*@__PURE__*/ $constructor(`ZodIntersection`,(e,t)=>{Ia.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)});function intersection(e,t){return new ss({type:`intersection`,left:e,right:t})}const cs=/*@__PURE__*/ $constructor(`ZodRecord`,(e,t)=>{_ensureDefaultMemoizer(),La.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>recordProcessor(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,n){return!t||!t._zod?new cs({type:`record`,keyType:string(),valueType:e,...normalizeParams(t)}):new cs({type:`record`,keyType:e,valueType:t,...normalizeParams(n)})}const ls=/*@__PURE__*/ $constructor(`ZodEnum`,(e,t)=>{Ra.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>enumProcessor(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new ls({...t,checks:[],...normalizeParams(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new ls({...t,checks:[],...normalizeParams(r),entries:i})}});function _enum(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ls({type:`enum`,entries:n,...normalizeParams(t)})}const us=/*@__PURE__*/ $constructor(`ZodLiteral`,(e,t)=>{za.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>literalProcessor(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new us({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ds=/*@__PURE__*/ $constructor(`ZodTransform`,(e,t)=>{_ensureDefaultMemoizer(),Ba.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>transformProcessor(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(issue(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(issue(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function transform(e){return new ds({type:`transform`,transform:e})}const fs=/*@__PURE__*/ $constructor(`ZodOptional`,(e,t)=>{Va.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new fs({type:`optional`,innerType:e})}const ps=/*@__PURE__*/ $constructor(`ZodExactOptional`,(e,t)=>{Ha.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new ps({type:`optional`,innerType:e})}const ms=/*@__PURE__*/ $constructor(`ZodNullable`,(e,t)=>{Ua.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nullableProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new ms({type:`nullable`,innerType:e})}const hs=/*@__PURE__*/ $constructor(`ZodDefault`,(e,t)=>{Wa.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>defaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new hs({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const gs=/*@__PURE__*/ $constructor(`ZodPrefault`,(e,t)=>{Ga.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>prefaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new gs({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const _s=/*@__PURE__*/ $constructor(`ZodNonOptional`,(e,t)=>{Ka.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nonoptionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new _s({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const vs=/*@__PURE__*/ $constructor(`ZodCatch`,(e,t)=>{qa.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>catchProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new vs({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:constantCatch(t)})}const ys=/*@__PURE__*/ $constructor(`ZodPipe`,(e,t)=>{Ja.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pipeProcessor(e,t,n,r),e.in=t.in,e.out=t.out});function pipe(e,t){return new ys({type:`pipe`,in:e,out:t})}const bs=/*@__PURE__*/ $constructor(`ZodReadonly`,(e,t)=>{Ya.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>readonlyProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new bs({type:`readonly`,innerType:e})}const xs=/*@__PURE__*/ $constructor(`ZodCustom`,(e,t)=>{Xa.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)});function custom(e,t){return/* @__PURE__ */ _custom(xs,e??(()=>!0),t)}function refine(e,t={}){return/* @__PURE__ */ _refine(xs,e,t)}function superRefine(e,t){return/* @__PURE__ */ _superRefine(e,t)}function safeParseWithSchema(e,t){let n=e.safeParse(t);return n.success?n.data:null}function safeParseJsonWithSchema(e,t){try{return safeParseWithSchema(e,JSON.parse(t))}catch{return null}}function readLockFileOwnerPayload(e){return e?{pid:typeof e.pid==`number`&&Number.isInteger(e.pid)&&e.pid>0?e.pid:void 0,createdAt:typeof e.createdAt==`string`?e.createdAt:void 0,starttime:typeof e.starttime==`number`&&Number.isInteger(e.starttime)&&e.starttime>=0?e.starttime:void 0}:null}function inspectStaleLockOwner(e){let t=readLockFileOwnerPayload(e.payload);if(!t?.pid)return null;if((e.isPidDefinitelyDead??On)(t.pid))return{reason:`owner-process-exited`,pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:null};let n=t.starttime===void 0?null:(e.getProcessStartTime??kn)(t.pid),r={pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:n},i=process.platform===`darwin`&&t.starttime!==void 0&&t.starttime>1e10?Math.floor(t.starttime/1e6):t.starttime;return n!==null&&n!==i?{reason:`owner-starttime-changed`,...r}:null}function isLockOwnerDefinitelyStale(e){return inspectStaleLockOwner(e)!==null}const Ss=string().min(1).max(4096),Cs={pid:number().int().positive(),startIdentity:Ss.max(128)},ws=strictObject({...Cs,startIdentitySource:literal(`argv-sha256`).nullable().optional()}).refine(({startIdentity:e,startIdentitySource:t})=>t===`argv-sha256`?/^win32-argv-sha256:[a-f0-9]{64}$/.test(e):!e.startsWith(`win32-argv-sha256:`)),Ts=union([strictObject({platform:_enum([`linux`,`darwin`]),identity:string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i)}),strictObject({platform:literal(`win32`),identity:string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/)}),strictObject({platform:literal(`freebsd`),identity:string().regex(/^[a-f0-9]{32}$/)})]),Es=strictObject({kind:literal(`native`),unit:Ss,scope:Ss,placement:discriminatedUnion(`kind`,[strictObject({kind:literal(`pending`)}),strictObject({kind:literal(`attached`),invocation:string().regex(/^[a-f0-9]{32}$/i)})])}),Ds=literal(`original-cancellation-v1`),Os=strictObject({kind:literal(`update`),mutationProtocol:Ds}).extend({mutationProtocol:Ds.optional(),custody:_enum([`reserved`,`bound`]).optional()}),ks=discriminatedUnion(`kind`,[Os,strictObject({kind:literal(`triage`),phase:_enum([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:discriminatedUnion(`kind`,[strictObject({kind:literal(`foreground`),boot:Ts}),Es])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]),As=Ss.refine(x.isAbsolute,`Native source path must be absolute`),js=string().regex(/^[a-f0-9]{64}$/),Ms=strictObject({runId:Ss,transactionId:Ss,claimId:Ss,revision:number().int().nonnegative(),recordSha256:js,serviceKey:As,configPaths:array(As).min(1).max(512),lifetimeId:Ss}),Ns=strictObject({id:string().uuid(),phase:_enum([`reserved`,`admitted`]),source:Ms}),Ps={executor:ws,helper:ws,action:ks},Fs=strictObject({version:literal(2),executor:ws,helper:ws,action:Os}),Is=strictObject({key:Ss,owner:Ss,payload:string().min(1),updatedAt:number().int().nonnegative()});discriminatedUnion(`version`,[strictObject({version:literal(4),executor:ws,helper:ws,action:Os,cancellation:Is}).refine(e=>{let t=safeParseJsonWithSchema(Fs,e.cancellation.payload);return t!==null&&JSON.stringify(t.helper)===JSON.stringify(e.helper)&&JSON.stringify(t.executor)===JSON.stringify(e.executor)&&JSON.stringify(t.action)===JSON.stringify(e.action)&&(JSON.stringify(e.helper)===JSON.stringify(e.executor)||t.action.mutationProtocol===`original-cancellation-v1`)}),strictObject({version:literal(2),...Ps,mutationOriginal:Is.optional()}).refine(e=>{if(!e.mutationOriginal)return!0;let t=safeParseJsonWithSchema(Fs,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`}),strictObject({version:literal(3),...Ps,action:strictObject({kind:literal(`update`)}),nativeBorrower:Ns})]),strictObject({version:literal(1),...Cs});const Ls=[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`];function createManagedHandoffBootIdentityReader(e){return function(){let t,n=process.platform===`android`?`linux`:process.platform;if(n===`linux`)t=b.readFileSync(`/proc/sys/kernel/random/boot_id`,`utf8`).trim();else if([`freebsd`,`darwin`,`win32`].includes(process.platform)){let n=process.platform===`freebsd`,r=process.platform===`win32`,i=Dr(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?Ls:n?[`-b`,`kern.boot_id`]:[`-n`,`kern.bootsessionuuid`],{env:e,...n?{maxBuffer:16}:{encoding:`utf8`,windowsHide:!0},timeout:r?5e3:1e3,killSignal:`SIGKILL`,stdio:[`ignore`,`pipe`,`ignore`]});!i.error&&i.status===0&&(t=n?Buffer.isBuffer(i.stdout)&&i.stdout.length===16?i.stdout.toString(`hex`):void 0:i.stdout.toString().trim())}let r={platform:n,identity:n===`win32`?t:t?.toLowerCase()},i=Ts.safeParse(r);if(!i.success)throw Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}}const[Rs,zs,Bs]=Ts.options,Vs=string().min(1),Hs=string().regex(/^[a-f0-9]{64}$/u),Us=discriminatedUnion(`platform`,[Rs.extend({host:Vs,platform:literal(`linux`),pidNsInode:string().min(1)}),Rs.extend({host:Vs,platform:literal(`darwin`)}),zs.extend({host:Vs,identity:zs.shape.identity.optional()}),Bs.extend({host:Vs})]);let Ws;function readGatewayLockProcessNamespace(){if(Ws?.platform===process.platform&&(Ws.value!==null||process.platform!==`linux`&&process.platform!==`android`))return Ws.value;try{let e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)(),t=Us.parse({host:Er.hostname(),...e,...e.platform===`linux`?{pidNsInode:b.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});return Ws={platform:process.platform,value:t},t}catch{return Ws={platform:process.platform,value:null},null}}function isLegacyGatewayLeaseLock(e){return process.platform===`linux`&&e.processNamespace===void 0&&e.role===`gateway`&&typeof e.ownerId==`string`&&e.ownerId.length>0&&typeof e.createdAt==`string`}function readLockHeartbeat(e){try{return b.statSync(e).mtimeMs}catch{return}}function isForeignLinuxNamespace(e,t){return e?.platform===`linux`&&t?.platform===`linux`&&(e.host!==t.host||e.pidNsInode!==t.pidNsInode)}function describeGatewayLockHolder(e,t,n){let r=Us.safeParse(e.processNamespace).data,i=(t?readLockHeartbeat(t):void 0)??e.heartbeatAt,a=i===void 0?void 0:Date.now()-i,o=`${r?.host??e.host??`unknown host`}${r?.platform===`linux`?`/pid-ns ${r.pidNsInode}`:``}`,s=n===`live`?`The holder ${e.pid} is alive on this host, stop it first`:n===`unknown`?`Stop the holder before retrying`:`Run this command inside the Gateway container or with a shared PID namespace`;return`holder ${e.pid??`unknown`} at ${o}, last renewed ${a===void 0?`at an unknown time`:`${Math.max(0,Math.floor(a/1e3))} s ago`}. ${s}.`}var GatewayLockNamespaceError=class extends Error{constructor(e,t){let n=process.platform===`linux`&&e.processNamespace===void 0;super(`cannot verify Gateway ownership from this process${t?` at ${t}`:``}. ${n?`Legacy holder ${e.pid??`unknown`} has no PID namespace evidence. It may already have stopped. Independently verify that no Gateway using this state is running on this host or in any sharing container. With a current OpenClaw CLI using the same state and profile, run \`openclaw gateway recover-lock --json\`, then \`openclaw gateway recover-lock --confirm <confirmation> --json\` with the returned confirmation. Retry Doctor afterward.`:describeGatewayLockHolder(e,t)}`),this.name=`GatewayLockNamespaceError`,this.legacyLock=n,this.legacyLease=isLegacyGatewayLeaseLock(e)||n&&typeof e.expiresAt==`number`;let r=Us.safeParse(e.processNamespace).data;if(isForeignLinuxNamespace(r,readGatewayLockProcessNamespace())){let n=t?readLockHeartbeat(t):e.heartbeatAt;n!==void 0&&(this.heartbeatAgeMs=Math.max(0,Date.now()-n))}}};function classifyGatewayOwnerProcessNamespace(e,t={}){let n=Us.safeParse(e).data;if(!n||t.ownerHost!==void 0&&t.ownerHost!==n.host)return`unknown`;let r=readGatewayLockProcessNamespace();if(!r||n.platform!==r.platform)return`unknown`;if(t.readGatewayHeartbeat&&isForeignLinuxNamespace(n,r)){if(n.host===r.host&&/^[a-f0-9]{12}$/u.test(r.host)&&Mn())return`dead`;let e=t.readGatewayHeartbeat();if(e!==void 0&&Date.now()-e>9e4)return`dead`}if(n.platform===`darwin`&&t.machineIdentity!==void 0){let e=Hs.safeParse(t.machineIdentity).data,i=Kt();if(e&&i){if(e!==i)return`unknown`;if(n.identity!==r.identity)return`dead`}}let i=n.platform===`darwin`&&r.platform===`darwin`&&n.identity===r.identity;return n.host!==r.host&&!i?`unknown`:n.platform===`win32`?`same`:n.identity===r.identity?n.platform!==`linux`||r.platform===`linux`&&n.pidNsInode===r.pidNsInode?`same`:`unknown`:`dead`}const Gs=object({pid:number(),ownerId:string().min(1).optional(),stateOwnerKind:literal(`schema`).optional(),cronOwnerProjection:literal(`dynamic-default-v1`).optional(),createdAt:string(),startupPhase:literal(`starting`).optional(),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(),parentPid:number().int().positive().optional(),parentStartTime:number().optional(),processNamespace:Us.nullable().optional(),machineIdentity:Hs.nullable().optional()});function parseGatewayLockPayload(e){return safeParseJsonWithSchema(Gs,e)}function createColdAdmissionBudget(e){let t=Qn(e.busyTimeoutMs,`busyTimeoutMs`),n=performance.now()+t,r=Ne(e.databasePath);return{remainingBusyTimeoutMs:()=>Math.max(0,Math.ceil(n-performance.now())),retryDelay:t=>{if(!(t instanceof gt)||Ne(t.databasePath)!==r||e.canRetry?.()===!1)throw t;let i=n-performance.now();if(i<=0)throw t;return Math.min(10,i)}}}function sha256Hex(e){return kr(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}const Ks=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);function hasRestrictivePermissions(e){try{return!(gr(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(t){let n;try{let e=gr(t).isDirectory()?t:x.dirname(t);n=x.join(e,`.openclaw-chmod-probe-${Ar()}`),vr(n,``,{flag:`wx`,mode:384})}catch{return!1}try{return pr(n,384),!1}catch(t){return e(t)&&t.code===`EPERM`}finally{try{_r(n)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&Ks.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(t,n){if((gr(t).mode&4095)===n)return{applied:!0};try{return pr(t,n),{applied:!0}}catch(n){if(!canIgnorePrivateChmodError(t,e(n)?n.code:void 0,hasRestrictivePermissions(t)))throw n;return{applied:!1,error:n}}}const qs=`Run OpenClaw as the user that owns its state directory, and keep that directory on a local filesystem that supports file ownership and permissions`;function ensureOwnerDirectory(e,t){let n=b.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let r=x.toNamespacedPath(n),i=[];for(let t=e;;){let{dev:e,ino:n}=b.lstatSync(t,{bigint:!0});if(i.push({path:t,dev:e,ino:n}),x.toNamespacedPath(t)===r)break;let a=x.dirname(t);if(a===t)throw Error(`Created state ownership directory is outside its expected ancestry`);t=a}for(let e of i){let n=t.findIndex(t=>t.path===e.path);n<0?t.push(e):t[n]=e}}let r=b.lstatSync(e),i=process.getuid?.();if(!r.isDirectory())throw Error(`State ownership directory must be a user-owned real directory`);if(i!==void 0&&r.uid!==i)throw Error(`State ownership directory ${e} is owned by uid ${r.uid}, not this user (uid ${i}). ${qs}`);if(process.platform!==`win32`&&(r.mode&4095)!=448&&(applyPrivateModeSync(e,448),b.lstatSync(e).mode&63))throw Error(`State ownership directory ${e} permissions could not be set to 0700. ${qs}`)}function removeCreatedProjectionDirectories(e){let t=e[0];for(;t;){try{let e=b.lstatSync(t.path,{bigint:!0});e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino&&b.rmdirSync(t.path)}catch(e){let t=je(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift(),t=e[0]}}function resolveStateOwnerIdentity(e){let t=Ne(e);return stateOwnerIdentity(t,Ne(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await Pe(e);return stateOwnerIdentity(t,await Pe(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:x.join(t,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?Fe(e):e}}function stateOwnerDirectory(e){let t=process.getuid?.();return process.platform===`win32`?x.join(Er.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):Re(ve(e))}function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}const Js=Date.now.bind(Date);function captureLock(e){let t=b.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,n){let r={};for(let t of e)r[t.lockPath]=captureLock(t);let i=Object.keys(r)[0];if(!i)throw Error(`Gateway state ownership requires a held lock`);let a=b.statSync(i,{bigint:!0}),{moduleUrl:o,runtimeGeneration:s}=xt(et(`gatewayStateOwnerHeartbeat`));return Ye(()=>{let c=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(c,0,BigInt(Js()));let{port1:l,port2:u}=new br,d=bt(o,{workerData:{clock:`epoch`,locks:r,intervalMs:15e3,failureMs:6e4,lastBeat:c.buffer,events:u},transferList:[u],execArgv:$e(o)}),f=dn();d.on(`message`,e=>{e===`closed`&&f.resolve()}),d.unref();let p=0,m=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of m.values())t.reject(e);m.clear(),l.unref()};l.on(`message`,e=>{if(lt(`lifecycle`,`from_worker`),e===`parent-lost`)Xe();else if(e&&typeof e==`object`&&e.type===`lost`)n(/* @__PURE__ */ Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e==`object`&&e.type===`verified`){let t=m.get(e.id);m.delete(e.id),m.size===0&&l.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),l.unref(),d.on(`error`,e=>{let t=/* @__PURE__ */ Error(`${Me(e)}; restart Gateway.`);rejectPending(t),n(t)}),d.once(`exit`,()=>{f.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let h,remainingUntilInspection=()=>{let e=Atomics.load(c,0),t=Js()-Number(e);return t<0?0:6e4-t},inspect=()=>{let e=remainingUntilInspection();if(e<=0)throw Error(`Gateway state ownership renewal is overdue at ${i}; retry after storage recovers.`);return e},renewAsync=async()=>{let n=Js(),o=new Date(n);for(let n of e)try{let t=r[n.lockPath];if(t===void 0)throw Error(`owner acquisition bytes were not registered`);let s=await b.promises.open(n.lockPath,`r+`);try{let r=await s.stat({bigint:!0}),c=await b.promises.lstat(n.lockPath,{bigint:!0}),l=Buffer.alloc(Buffer.byteLength(t)+1),{bytesRead:u}=await s.read(l,0,l.length,0),d=await b.promises.lstat(n.lockPath,{bigint:!0});if(h||!e.has(n))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(r,c,t,l.subarray(0,u).toString(`utf8`))||!d.isFile()||d.dev!==r.dev||d.ino!==r.ino||n.lockPath===i&&(r.dev!==a.dev||r.ino!==a.ino)){if(n.lockPath!==i)continue;throw Error(`owner lock was removed or replaced`)}await s.utimes(o,o)}finally{await s.close()}}catch(e){if(n.lockPath!==i&&t(e,`ENOENT`))continue;throw e}!h&&e.size>0&&Atomics.store(c,0,BigInt(n))},g,ee,watch=()=>{let e=remainingUntilInspection();e>0?(g=setTimeout(watch,e),g.unref()):ee??=renewAsync().then(()=>{ee=void 0,h||watch()},e=>{ee=void 0,h||n(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${i}: ${Me(e)}; restart the Gateway.`))})};watch();let stop=()=>(h||=(clearTimeout(g),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),l.close(),d.ref(),d.postMessage(`stop`,[]),(async()=>(await An(f.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${Qe}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),d.terminate()))()),Promise.all([h,ee]).then(()=>void 0));s?.retain(d,async()=>async()=>{await stop()});let assertActive=()=>{if(h||d.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},te=new Set(Object.keys(r));return{worker:d,paths:te,register(e){let t=captureLock(e);r[e.lockPath]=t,d.postMessage([e.lockPath,t],[]),te.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let t=++p;return new Promise((n,r)=>{m.set(t,{resolve:n,reject:r}),l.ref();try{d.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){m.delete(t),m.size===0&&l.unref(),r(Ae(e,`Gateway state ownership verification failed`))}})},stop}})}function hasPhysicalOwnership(e){try{return verifyOwnerLock(e,e.locks.values().next().value)}catch(t){if(e.lost.signal.aborted)return!1;throw t}}function verifyOwnerLock(e,t){if(e.lost.signal.throwIfAborted(),e.heartbeat?.inspect(),!t)return!1;let n=e.getProjection?.();n&&e.heartbeat&&!e.heartbeat.paths.has(n.lockPath)&&e.heartbeat.register(n);let r=e.payload.role??`gateway`;return e.kind===`process`&&e.accepting&&(r===`gateway`||r===`agent-embedded`)&&e.heartbeat?(e.heartbeat.assertActive(),!0):t.verifyStillHeld()?!0:(loseOwner(e,/* @__PURE__ */ Error(`${t.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`)),!1)}const Ys=ct(`gateway/state`);function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,k.clear(),e.heartbeat?.stop(),Ys.error(t.message),e.lost.abort(t))}function observeOwnerLoss(e,t,n){let r=[...e.locks,e.getProjection?.()];(!n||r.some(e=>e?.lockPath===n))&&loseOwner(e,t)}const k=n(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),A=n(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map),Xs=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),Zs=/* @__PURE__ */ new Set([`--tailscale-reset-on-exit`,`--allow-unconfigured`,`--dev`,`--ambient-channels`,`--dev-ambient-channels`,`--reset`,`--update-canary`,`--force`,`--verbose`,`--cli-backend-logs`,`--claude-cli-logs`,`--compact`,`--raw-stream`]);function isForegroundGatewayRunArgv(e){let t=Nn(e,{commandPath:[`gateway`],booleanFlags:[...Zs,`--task-supervisor`],valueFlags:[...Xs,`--task-supervisor-child`],mode:`command-path`});return t?t.length===0||t.length===1&&t[0]===`run`:!1}function isUndefined(e){return e===void 0||e===void 0}function isString(e){return typeof e==`string`}function isNumber(e){return typeof e==`number`}function isBoolean(e){return typeof e==`boolean`}function isNull(e){return e===null}function isDate(e){return e instanceof Date}function isBigInt(e){return typeof e==`bigint`}function isFunction(e){return typeof e==`function`}function isObject(e){return typeof e==`object`&&!!e}function freeze(e){return Object.freeze(e)}function asArray(e){return isReadonlyArray(e)?e:[e]}function isReadonlyArray(e){return Array.isArray(e)}function noop(e){return e}function getMessage(e){return e instanceof Error?e.message:String(e)}const j=freeze({is(e){return e.kind===`AlterTableNode`},create(e){return freeze({kind:`AlterTableNode`,table:e})},cloneWithTableProps(e,t){return freeze({...e,...t})},cloneWithColumnAlteration(e,t){return freeze({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,t]:[t]})}}),M=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}}),Qs=freeze({is(e){return e.kind===`CreateIndexNode`},create(e){return freeze({kind:`CreateIndexNode`,name:M.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}}),$s=freeze({is(e){return e.kind===`CreateSchemaNode`},create(e,t){return freeze({kind:`CreateSchemaNode`,schema:M.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),ec=[`preserve rows`,`delete rows`,`drop`],N=freeze({is(e){return e.kind===`CreateTableNode`},create(e){return freeze({kind:`CreateTableNode`,table:e,columns:freeze([])})},cloneWithColumn(e,t){return freeze({...e,columns:freeze([...e.columns,t])})},cloneWithConstraint(e,t){return freeze({...e,constraints:e.constraints?freeze([...e.constraints,t]):freeze([t])})},cloneWithIndex(e,t){return freeze({...e,indexes:e.indexes?freeze([...e.indexes,t]):freeze([t])})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWith(e,t){return freeze({...e,...t})}}),tc=freeze({is(e){return e.kind===`SchemableIdentifierNode`},create(e){return freeze({kind:`SchemableIdentifierNode`,identifier:M.create(e)})},createWithSchema(e,t){return freeze({kind:`SchemableIdentifierNode`,schema:M.create(e),identifier:M.create(t)})}}),nc=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:tc.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),rc=freeze({is(e){return e.kind===`DropSchemaNode`},create(e,t){return freeze({kind:`DropSchemaNode`,schema:M.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),ic=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}}),ac=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),P=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:tc.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:tc.createWithSchema(e,t)})}});function isOperationNodeSource(e){return isObject(e)&&isFunction(e.toOperationNode)}function isExpression(e){return isObject(e)&&`expressionType`in e&&isOperationNodeSource(e)}function isAliasedExpression(e){return isObject(e)&&`expression`in e&&isString(e.alias)&&isOperationNodeSource(e)}const oc=freeze({is(e){return e.kind===`SelectModifierNode`},create(e,t){return freeze({kind:`SelectModifierNode`,modifier:e,of:t})},createWithExpression(e){return freeze({kind:`SelectModifierNode`,rawModifier:e})}}),sc=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),cc=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),lc=freeze({is(e){return e.kind===`OnNode`},create(e){return freeze({kind:`OnNode`,on:e})},cloneWithOperation(e,t,n){return freeze({...e,on:t===`And`?sc.create(e.on,n):cc.create(e.on,n)})}}),uc=freeze({is(e){return e.kind===`JoinNode`},create(e,t){return freeze({kind:`JoinNode`,joinType:e,table:t,on:void 0})},createWithOn(e,t,n){return freeze({kind:`JoinNode`,joinType:e,table:t,on:lc.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?lc.cloneWithOperation(e.on,`And`,t):lc.create(t)})}}),dc=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),fc=freeze({"=":!0,"==":!0,"!=":!0,"<>":!0,">":!0,">=":!0,"<":!0,"<=":!0,in:!0,"not in":!0,is:!0,"is not":!0,like:!0,"not like":!0,match:!0,ilike:!0,"not ilike":!0,"@>":!0,"<@":!0,"^@":!0,"&&":!0,"?":!0,"?&":!0,"?|":!0,"!<":!0,"!>":!0,"<=>":!0,"!~":!0,"~":!0,"~*":!0,"!~*":!0,"@@":!0,"@@@":!0,"!!":!0,"<->":!0,regexp:!0,"is distinct from":!0,"is not distinct from":!0});Object.keys(fc);const pc=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(pc);const mc=freeze({"->":!0,"->>":!0}),hc=Object.keys(mc),gc=freeze({...fc,...pc,"||":!0}),_c=Object.keys(gc),vc=freeze({exists:!0,"not exists":!0});Object.keys(vc);const yc=freeze({...vc,"-":!0,not:!0}),bc=Object.keys(yc);[..._c,...hc,...bc];const xc=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&gc[e]}function isJSONOperator(e){return isString(e)&&mc[e]}function isUnaryOperator(e){return isString(e)&&yc[e]}const F=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:M.create(e)})}}),Sc=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),Cc=freeze({is(e){return e.kind===`ReferenceNode`},create(e,t){return freeze({kind:`ReferenceNode`,table:t,column:e})},createSelectAll(e){return freeze({kind:`ReferenceNode`,table:e,column:Sc.create()})}});var DynamicReferenceBuilder=class{#e;get dynamicReference(){return this.#e}get refType(){}constructor(e){this.#e=e}toOperationNode(){return parseSimpleReferenceExpression(this.#e)}};function isDynamicReferenceBuilder(e){return isObject(e)&&isOperationNodeSource(e)&&isString(e.dynamicReference)}const wc=freeze({is(e){return e.kind===`OrderByItemNode`},create(e,t){return freeze({kind:`OrderByItemNode`,orderBy:e,direction:t})},cloneWith(e,t){return freeze({...e,...t})}}),I=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return I.create([e],[])},createWithChild(e){return I.create([``,``],[e])},createWithChildren(e){return I.create(Array(e.length+1).fill(``),e)}}),Tc=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:M.create(e)})}});var Ec=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:wc.cloneWith(this.#e.node,{direction:I.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:wc.cloneWith(this.#e.node,{direction:I.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:wc.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:wc.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:wc.cloneWith(this.#e.node,{collation:Tc.create(e)})})}toOperationNode(){return this.#e.node}};const Dc=/* @__PURE__ */ new Set;function logOnce(e){Dc.has(e)||(Dc.add(e),console.log(e))}function isOrderByDirection(e){return e===`asc`||e===`desc`}function parseOrderBy(e){if(e.length===2)return[parseOrderByItem(e[0],e[1])];if(e.length===1){let[t]=e;return Array.isArray(t)?(logOnce(`orderBy(array) is deprecated, use multiple orderBy calls instead.`),t.map(e=>parseOrderByItem(e))):[parseOrderByItem(t)]}throw Error(`Invalid number of arguments at order by! expected 1-2, received ${e.length}`)}function parseOrderByItem(e,t){let n=parseOrderByExpression(e);if(wc.is(n)){if(t)throw Error(`Cannot specify direction twice!`);return n}return parseOrderByWithModifiers(n,t)}function parseOrderByExpression(e){if(isExpressionOrFactory(e))return parseExpression(e);if(isDynamicReferenceBuilder(e))return e.toOperationNode();let[t,n]=e.split(` `);return n?(logOnce("`orderBy('column asc')` is deprecated. Use `orderBy('column', 'asc')` instead."),parseOrderByWithModifiers(parseStringReference(t),n)):parseStringReference(e)}function parseOrderByWithModifiers(e,t){if(typeof t==`string`){if(!isOrderByDirection(t))throw Error(`Invalid order by direction: ${t}`);return wc.create(e,I.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),wc.create(e,t.toOperationNode());let n=wc.create(e);return t?t(new Ec({node:n})).toOperationNode():n}const Oc=freeze({is(e){return e.kind===`JSONReferenceNode`},create(e,t){return freeze({kind:`JSONReferenceNode`,reference:e,traversal:t})},cloneWithTraversal(e,t){return freeze({...e,traversal:t})}}),kc=freeze({is(e){return e.kind===`JSONOperatorChainNode`},create(e){return freeze({kind:`JSONOperatorChainNode`,operator:e,values:freeze([])})},cloneWithValue(e,t){return freeze({...e,values:freeze([...e.values,t])})}}),Ac=freeze({is(e){return e.kind===`JSONPathNode`},create(e){return freeze({kind:`JSONPathNode`,inOperator:e,pathLegs:freeze([])})},cloneWithLeg(e,t){return freeze({...e,pathLegs:freeze([...e.pathLegs,t])})}});function parseSimpleReferenceExpression(e){return isString(e)?parseStringReference(e):e.toOperationNode()}function parseReferenceExpressionOrList(e){return isReadonlyArray(e)?e.map(e=>parseReferenceExpression(e)):[parseReferenceExpression(e)]}function parseReferenceExpression(e){return isExpressionOrFactory(e)?parseExpression(e):parseSimpleReferenceExpression(e)}function parseJSONReference(e,t){if(isJSONOperator(t))return Oc.create(parseStringReference(e),kc.create(xc.create(t)));if(t===`->$`||t===`->>$`)return Oc.create(parseStringReference(e),Ac.create(xc.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return Cc.create(F.create(e));let t=e.split(`.`).map(trim$2);if(t.length===3)return parseStringReferenceWithTableAndSchema(t);if(t.length===2)return parseStringReferenceWithTable(t);throw Error(`invalid column reference ${e}`)}function parseAliasedStringReference(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim$2);return ac.create(parseStringReference(n),M.create(r))}return parseStringReference(e)}function parseColumnName(e){return F.create(e)}function parseOrderedColumnName(e){if(e.includes(` `)){let[t,n]=e.split(` `).map(trim$2);if(!isOrderByDirection(n))throw Error(`invalid order direction "${n}" next to "${t}"`);return parseOrderBy([t,n])[0]}return parseColumnName(e)}function parseStringReferenceWithTableAndSchema(e){let[t,n,r]=e;return Cc.create(F.create(r),P.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return Cc.create(F.create(n),P.create(t))}function trim$2(e){return e.trim()}const jc=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),Mc=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),L=freeze({is(e){return e.kind===`ValueNode`},create(e){return freeze({kind:`ValueNode`,value:e})},createImmediate(e){return freeze({kind:`ValueNode`,value:e,immediate:!0})}});function parseValueExpressionOrList(e){return isReadonlyArray(e)?parseValueExpressionList(e):parseValueExpression(e)}function parseValueExpression(e){return isExpressionOrFactory(e)?parseExpression(e):L.create(e)}function isSafeImmediateValue(e){return isNumber(e)||isBoolean(e)||isNull(e)}function parseSafeImmediateValue(e){if(!isSafeImmediateValue(e))throw Error(`unsafe immediate value ${JSON.stringify(e)}`);return L.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?Mc.create(e.map(e=>parseValueExpression(e))):jc.create(e)}const Nc=freeze({is(e){return e.kind===`ParensNode`},create(e){return freeze({kind:`ParensNode`,node:e})}});function parseValueBinaryOperationOrExpression(e){if(e.length===3)return parseValueBinaryOperation(e[0],e[1],e[2]);if(e.length===1)return parseValueExpression(e[0]);throw Error(`invalid arguments: ${JSON.stringify(e)}`)}function parseValueBinaryOperation(e,t,n){return isIsOperator(t)&&needsIsOperator(n)?dc.create(parseReferenceExpression(e),parseBinaryOperator(t),L.createImmediate(n)):dc.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return dc.create(parseReferenceExpression(e),parseBinaryOperator(t),parseReferenceExpression(n))}function parseFilterObject(e,t){return parseFilterList(Object.entries(e).filter(([,e])=>!isUndefined(e)).map(([e,t])=>parseValueBinaryOperation(e,needsIsOperator(t)?`is`:`=`,t)),t)}function parseFilterList(e,t,n=!0){let r=t===`and`?sc.create:cc.create;if(e.length===0)return dc.create(L.createImmediate(1),xc.create(`=`),L.createImmediate(+(t===`and`)));let i=toOperationNode(e[0]);for(let t=1;t<e.length;++t)i=r(i,toOperationNode(e[t]));return e.length>1&&n?Nc.create(i):i}function isIsOperator(e){return e===`is`||e===`is not`}function needsIsOperator(e){return isNull(e)||isBoolean(e)}function parseBinaryOperator(e){if(isBinaryOperator(e))return xc.create(e);if(isOperationNodeSource(e))return e.toOperationNode();throw Error(`invalid operator ${JSON.stringify(e)}`)}function toOperationNode(e){return isOperationNodeSource(e)?e.toOperationNode():e}const Pc=freeze({is(e){return e.kind===`OrderByNode`},create(e){return freeze({kind:`OrderByNode`,items:freeze([...e])})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),Fc=freeze({is(e){return e.kind===`PartitionByNode`},create(e){return freeze({kind:`PartitionByNode`,items:freeze(e)})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),Ic=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Pc.cloneWithItems(e.orderBy,t):Pc.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?Fc.cloneWithItems(e.partitionBy,t):Fc.create(t)})}}),Lc=freeze({is(e){return e.kind===`FromNode`},create(e){return freeze({kind:`FromNode`,froms:freeze(e)})},cloneWithFroms(e,t){return freeze({...e,froms:freeze([...e.froms,...t])})}}),Rc=freeze({is(e){return e.kind===`GroupByNode`},create(e){return freeze({kind:`GroupByNode`,items:freeze(e)})},cloneWithItems(e,t){return freeze({...e,items:freeze([...e.items,...t])})}}),zc=freeze({is(e){return e.kind===`HavingNode`},create(e){return freeze({kind:`HavingNode`,having:e})},cloneWithOperation(e,t,n){return freeze({...e,having:t===`And`?sc.create(e.having,n):cc.create(e.having,n)})}}),R=freeze({is(e){return e.kind===`InsertQueryNode`},create(e,t,n){return freeze({kind:`InsertQueryNode`,into:e,...t&&{with:t},replace:n})},createWithoutInto(){return freeze({kind:`InsertQueryNode`})},cloneWith(e,t){return freeze({...e,...t})}}),Bc=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),Vc=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:Bc.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?Lc.cloneWithFroms(e.from,t):Lc.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),Hc=freeze({is(e){return e.kind===`UsingNode`},create(e){return freeze({kind:`UsingNode`,tables:freeze(e)})},cloneWithTables(e,t){return freeze({...e,tables:freeze([...e.tables,...t])})}}),Uc=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:Lc.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>V.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>V.cloneWithoutOrderBy(e),cloneWithLimit(e,t){return freeze({...e,limit:t})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithUsing(e,t){return freeze({...e,using:e.using===void 0?Hc.create(t):Hc.cloneWithTables(e.using,t)})}}),z=freeze({is(e){return e.kind===`WhereNode`},create(e){return freeze({kind:`WhereNode`,where:e})},cloneWithOperation(e,t,n){return freeze({...e,where:t===`And`?sc.create(e.where,n):cc.create(e.where,n)})}}),Wc=freeze({is(e){return e.kind===`ReturningNode`},create(e){return freeze({kind:`ReturningNode`,selections:freeze(e)})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})}}),Gc=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),Kc=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),B=freeze({is(e){return e.kind===`MergeQueryNode`},create(e,t){return freeze({kind:`MergeQueryNode`,into:e,...t&&{with:t}})},cloneWithUsing(e,t){return freeze({...e,using:t})},cloneWithWhen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens,t]):freeze([t])})},cloneWithThen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens.slice(0,-1),Kc.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),qc=freeze({is(e){return e.kind===`OutputNode`},create(e){return freeze({kind:`OutputNode`,selections:freeze(e)})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})}}),V=freeze({is(e){return H.is(e)||R.is(e)||Vc.is(e)||Uc.is(e)||B.is(e)},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWithWhere(e,t){return freeze({...e,where:e.where?z.cloneWithOperation(e.where,`And`,t):z.create(t)})},cloneWithJoin(e,t){return freeze({...e,joins:e.joins?freeze([...e.joins,t]):freeze([t])})},cloneWithReturning(e,t){return freeze({...e,returning:e.returning?Wc.cloneWithSelections(e.returning,t):Wc.create(t)})},cloneWithoutReturning(e){return freeze({...e,returning:void 0})},cloneWithoutWhere(e){return freeze({...e,where:void 0})},cloneWithExplain(e,t,n){return freeze({...e,explain:Gc.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?qc.cloneWithSelections(e.output,t):qc.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Pc.cloneWithItems(e.orderBy,t):Pc.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),H=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:Lc.create(e),...t&&{with:t}})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})},cloneWithDistinctOn(e,t){return freeze({...e,distinctOn:e.distinctOn?freeze([...e.distinctOn,...t]):freeze(t)})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithOrderByItems:(e,t)=>V.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?Rc.cloneWithItems(e.groupBy,t):Rc.create(t)})},cloneWithLimit(e,t){return freeze({...e,limit:t})},cloneWithOffset(e,t){return freeze({...e,offset:t})},cloneWithFetch(e,t){return freeze({...e,fetch:t})},cloneWithHaving(e,t){return freeze({...e,having:e.having?zc.cloneWithOperation(e.having,`And`,t):zc.create(t)})},cloneWithSetOperations(e,t){return freeze({...e,setOperations:e.setOperations?freeze([...e.setOperations,...t]):freeze([...t])})},cloneWithoutSelections(e){return freeze({...e,selections:[]})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithoutOffset(e){return freeze({...e,offset:void 0})},cloneWithoutOrderBy:e=>V.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var Jc=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:uc.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:uc.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:uc.cloneWithOn(this.#e.joinNode,I.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const Yc=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(Yc.create)}var Xc=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:Ic.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:V.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:Ic.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const Zc=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:Sc.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:Cc.createSelectAll(e)})}});function parseSelectArg(e){return isFunction(e)?parseSelectArg(e(expressionBuilder())):isReadonlyArray(e)?e.map(e=>parseSelectExpression(e)):[parseSelectExpression(e)]}function parseSelectExpression(e){return isString(e)?Zc.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?Zc.create(e.toOperationNode()):Zc.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[Zc.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return Zc.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}const Qc=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}}),$c=freeze({is(e){return e.kind===`DefaultInsertValueNode`},create(){return freeze({kind:`DefaultInsertValueNode`})}});function parseInsertExpression(e){let t=isFunction(e)?e(expressionBuilder()):e;return parseInsertColumnsAndValues(isReadonlyArray(t)?t:freeze([t]))}function parseInsertColumnsAndValues(e){let t=parseColumnNamesAndIndexes(e);return[freeze([...t.keys()].map(F.create)),Qc.create(e.map(e=>parseRowValues(e,t)))]}function parseColumnNamesAndIndexes(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=Object.keys(n);for(let r of e)!t.has(r)&&n[r]!==void 0&&t.set(r,t.size)}return t}function parseRowValues(e,t){let n=Object.keys(e),r=Array.from({length:t.size}),i=!1,a=n.length;for(let o of n){let n=t.get(o);if(isUndefined(n)){a--;continue}let s=e[o];(isUndefined(s)||isExpressionOrFactory(s))&&(i=!0),r[n]=s}if(a<t.size||i){let e=$c.create();return Mc.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return jc.create(r)}const el=freeze({is(e){return e.kind===`ColumnUpdateNode`},create(e,t){return freeze({kind:`ColumnUpdateNode`,column:e,value:t})}});function parseUpdate(...e){return e.length===2?[el.create(parseReferenceExpression(e[0]),parseValueExpression(e[1]))]:parseUpdateObjectExpression(e[0])}function parseUpdateObjectExpression(e){let t=isFunction(e)?e(expressionBuilder()):e;return Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>el.create(F.create(e),parseValueExpression(t)))}const tl=freeze({is(e){return e.kind===`OnDuplicateKeyNode`},create(e){return freeze({kind:`OnDuplicateKeyNode`,updates:e})}});var InsertResult=class{insertId;numInsertedOrUpdatedRows;constructor(e,t){this.insertId=e,this.numInsertedOrUpdatedRows=t}},NoResultError=class extends Error{node;constructor(e){super(`no result`),this.node=e}};function isNoResultErrorConstructor(e){return Object.prototype.hasOwnProperty.call(e,`prototype`)}const U=freeze({is(e){return e.kind===`OnConflictNode`},create(){return freeze({kind:`OnConflictNode`})},cloneWith(e,t){return freeze({...e,...t})},cloneWithIndexWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?z.cloneWithOperation(e.indexWhere,`And`,t):z.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?z.cloneWithOperation(e.indexWhere,`Or`,t):z.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?z.cloneWithOperation(e.updateWhere,`And`,t):z.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?z.cloneWithOperation(e.updateWhere,`Or`,t):z.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}});var nl=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=F.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:U.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,t]):freeze([t])})})}columns(e){let t=e.map(F.create);return new OnConflictBuilder({...this.#e,onConflictNode:U.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,...t]):freeze(t)})})}constraint(e){return new OnConflictBuilder({...this.#e,onConflictNode:U.cloneWith(this.#e.onConflictNode,{constraint:M.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:U.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:U.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:U.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:U.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:U.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new rl({...this.#e,onConflictNode:U.cloneWith(this.#e.onConflictNode,{updates:parseUpdateObjectExpression(e)})})}$call(e){return e(this)}},OnConflictDoNothingBuilder=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.onConflictNode}},rl=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:U.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:U.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:U.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}};const il=freeze({is(e){return e.kind===`TopNode`},create(e,t){return freeze({kind:`TopNode`,expression:e,modifiers:t})}});function parseTop(e,t){if(!isNumber(e)&&!isBigInt(e))throw Error(`Invalid top expression: ${e}`);if(!isUndefined(t)&&!isTopModifiers(t))throw Error(`Invalid top modifiers: ${t}`);return il.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const al=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}});var ol=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{columns:freeze(e.map(F.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{orAction:al.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{orAction:al.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{orAction:al.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{orAction:al.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{orAction:al.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{orAction:al.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:V.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{onConflict:e(new nl({onConflictNode:U.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:R.cloneWith(this.#e.queryNode,{onDuplicateKey:tl.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:V.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new InsertQueryBuilder({...this.#e})}$castTo(){return new InsertQueryBuilder(this.#e)}$narrowType(){return new InsertQueryBuilder(this.#e)}$assertType(){return new InsertQueryBuilder(this.#e)}withPlugin(e){return new InsertQueryBuilder({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new InsertResult(n.insertId,n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new InsertQueryBuilder({...this.#e,queryNode:V.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}};const sl=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}});var W,DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new W({...this.#e,queryNode:V.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new W({...this.#e,queryNode:V.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new W({...this.#e,queryNode:V.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new W({...this.#e,queryNode:V.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new W({...this.#e,queryNode:Uc.cloneWithUsing(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new W({...this.#e,queryNode:V.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new W({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new W({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new W({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new W({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new W({...this.#e,queryNode:V.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new W({...this.#e,queryNode:Uc.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new W({...this.#e,queryNode:V.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new W({...this.#e,queryNode:V.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new W({...this.#e,queryNode:Uc.cloneWithLimit(this.#e.queryNode,sl.create(parseValueExpression(e)))})}modifyEnd(e){return new W({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new W({...this.#e})}$castTo(){return new W(this.#e)}$narrowType(){return new W(this.#e)}$assertType(){return new W(this.#e)}withPlugin(e){return new W({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new DeleteResult(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new W({...this.#e,queryNode:V.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};W=DeleteQueryBuilder;var UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},G,UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new G({...this.#e,queryNode:V.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new G({...this.#e,queryNode:V.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new G({...this.#e,queryNode:V.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new G({...this.#e,queryNode:V.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new G({...this.#e,queryNode:Vc.cloneWithFromItems(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new G({...this.#e,queryNode:V.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new G({...this.#e,queryNode:V.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new G({...this.#e,queryNode:V.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new G({...this.#e,queryNode:Vc.cloneWithLimit(this.#e.queryNode,sl.create(parseValueExpression(e)))})}set(...e){return new G({...this.#e,queryNode:Vc.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new G({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new G({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new G({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new G({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new G({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new G({...this.#e,queryNode:V.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new G({...this.#e})}$castTo(){return new G(this.#e)}$narrowType(){return new G(this.#e)}$assertType(){return new G(this.#e)}withPlugin(e){return new G({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new UpdateResult(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new G({...this.#e,queryNode:V.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};G=UpdateQueryBuilder;const cl=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:P.create(e),columns:t?freeze(t.map(F.create)):void 0})}}),ll=freeze({is(e){return e.kind===`CommonTableExpressionNode`},create(e,t){return freeze({kind:`CommonTableExpressionNode`,name:e,expression:t})},cloneWith(e,t){return freeze({...e,...t})}});var ul=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:ll.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:ll.cloneWith(this.#e.node,{materialized:!1})})}toOperationNode(){return this.#e.node}};function parseCommonTableExpression(e,t){let n=isOperationNodeSource(t)?t.toOperationNode():t(createQueryCreator()).toOperationNode();return isFunction(e)?e(cteBuilderFactory(n)).toOperationNode():ll.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new ul({node:ll.create(parseCommonTableExpressionName(t),e)})}function parseCommonTableExpressionName(e){if(e.includes(`(`)){let t=e.split(/[\(\)]/),n=t[0],r=t[1].split(`,`).map(e=>e.trim());return cl.create(n,r)}return cl.create(e)}const dl=freeze({is(e){return e.kind===`WithNode`},create(e,t){return freeze({kind:`WithNode`,expressions:freeze([e]),...t})},cloneWithExpression(e,t){return freeze({...e,expressions:freeze([...e.expressions,t])})}}),fl=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return fl[~~(Math.random()*fl.length)]}function createQueryId(){return new LazyQueryId}var LazyQueryId=class{#e;get queryId(){return this.#e===void 0&&(this.#e=randomString(8)),this.#e}},OperationNodeTransformer=class{nodeStack=[];#e=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(e,t){if(!e)return e;this.nodeStack.push(e);let n=this.transformNodeImpl(e,t);return this.nodeStack.pop(),freeze(n)}transformNodeImpl(e,t){return this.#e[e.kind](e,t)}transformNodeList(e,t){return e&&freeze(e.map(e=>this.transformNode(e,t)))}transformSelectQuery(e,t){return{kind:`SelectQueryNode`,from:this.transformNode(e.from,t),selections:this.transformNodeList(e.selections,t),distinctOn:this.transformNodeList(e.distinctOn,t),joins:this.transformNodeList(e.joins,t),groupBy:this.transformNode(e.groupBy,t),orderBy:this.transformNode(e.orderBy,t),where:this.transformNode(e.where,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),limit:this.transformNode(e.limit,t),offset:this.transformNode(e.offset,t),with:this.transformNode(e.with,t),having:this.transformNode(e.having,t),explain:this.transformNode(e.explain,t),setOperations:this.transformNodeList(e.setOperations,t),fetch:this.transformNode(e.fetch,t),top:this.transformNode(e.top,t)}}transformSelection(e,t){return{kind:`SelectionNode`,selection:this.transformNode(e.selection,t)}}transformColumn(e,t){return{kind:`ColumnNode`,column:this.transformNode(e.column,t)}}transformAlias(e,t){return{kind:`AliasNode`,node:this.transformNode(e.node,t),alias:this.transformNode(e.alias,t)}}transformTable(e,t){return{kind:`TableNode`,table:this.transformNode(e.table,t)}}transformFrom(e,t){return{kind:`FromNode`,froms:this.transformNodeList(e.froms,t)}}transformReference(e,t){return{kind:`ReferenceNode`,column:this.transformNode(e.column,t),table:this.transformNode(e.table,t)}}transformAnd(e,t){return{kind:`AndNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformOr(e,t){return{kind:`OrNode`,left:this.transformNode(e.left,t),right:this.transformNode(e.right,t)}}transformValueList(e,t){return{kind:`ValueListNode`,values:this.transformNodeList(e.values,t)}}transformParens(e,t){return{kind:`ParensNode`,node:this.transformNode(e.node,t)}}transformJoin(e,t){return{kind:`JoinNode`,joinType:e.joinType,table:this.transformNode(e.table,t),on:this.transformNode(e.on,t)}}transformRaw(e,t){return{kind:`RawNode`,sqlFragments:freeze([...e.sqlFragments]),parameters:this.transformNodeList(e.parameters,t)}}transformWhere(e,t){return{kind:`WhereNode`,where:this.transformNode(e.where,t)}}transformInsertQuery(e,t){return{kind:`InsertQueryNode`,into:this.transformNode(e.into,t),columns:this.transformNodeList(e.columns,t),values:this.transformNode(e.values,t),returning:this.transformNode(e.returning,t),onConflict:this.transformNode(e.onConflict,t),onDuplicateKey:this.transformNode(e.onDuplicateKey,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orAction:this.transformNode(e.orAction,t),replace:e.replace,explain:this.transformNode(e.explain,t),defaultValues:e.defaultValues,top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformValues(e,t){return{kind:`ValuesNode`,values:this.transformNodeList(e.values,t)}}transformDeleteQuery(e,t){return{kind:`DeleteQueryNode`,from:this.transformNode(e.from,t),using:this.transformNode(e.using,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),orderBy:this.transformNode(e.orderBy,t),limit:this.transformNode(e.limit,t),explain:this.transformNode(e.explain,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t)}}transformReturning(e,t){return{kind:`ReturningNode`,selections:this.transformNodeList(e.selections,t)}}transformCreateTable(e,t){return{kind:`CreateTableNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),constraints:this.transformNodeList(e.constraints,t),indexes:this.transformNodeList(e.indexes,t),temporary:e.temporary,ifNotExists:e.ifNotExists,onCommit:e.onCommit,frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),selectQuery:this.transformNode(e.selectQuery,t)}}transformColumnDefinition(e,t){return{kind:`ColumnDefinitionNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),references:this.transformNode(e.references,t),primaryKey:e.primaryKey,autoIncrement:e.autoIncrement,unique:e.unique,notNull:e.notNull,unsigned:e.unsigned,defaultTo:this.transformNode(e.defaultTo,t),check:this.transformNode(e.check,t),generated:this.transformNode(e.generated,t),frontModifiers:this.transformNodeList(e.frontModifiers,t),endModifiers:this.transformNodeList(e.endModifiers,t),nullsNotDistinct:e.nullsNotDistinct,identity:e.identity,ifNotExists:e.ifNotExists}}transformAddColumn(e,t){return{kind:`AddColumnNode`,column:this.transformNode(e.column,t)}}transformDropTable(e,t){return{kind:`DropTableNode`,table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade,temporary:e.temporary}}transformOrderBy(e,t){return{kind:`OrderByNode`,items:this.transformNodeList(e.items,t)}}transformOrderByItem(e,t){return{kind:`OrderByItemNode`,orderBy:this.transformNode(e.orderBy,t),direction:this.transformNode(e.direction,t),collation:this.transformNode(e.collation,t),nulls:e.nulls}}transformGroupBy(e,t){return{kind:`GroupByNode`,items:this.transformNodeList(e.items,t)}}transformGroupByItem(e,t){return{kind:`GroupByItemNode`,groupBy:this.transformNode(e.groupBy,t)}}transformUpdateQuery(e,t){return{kind:`UpdateQueryNode`,table:this.transformNode(e.table,t),from:this.transformNode(e.from,t),joins:this.transformNodeList(e.joins,t),where:this.transformNode(e.where,t),updates:this.transformNodeList(e.updates,t),returning:this.transformNode(e.returning,t),endModifiers:this.transformNodeList(e.endModifiers,t),with:this.transformNode(e.with,t),explain:this.transformNode(e.explain,t),limit:this.transformNode(e.limit,t),top:this.transformNode(e.top,t),output:this.transformNode(e.output,t),orderBy:this.transformNode(e.orderBy,t)}}transformColumnUpdate(e,t){return{kind:`ColumnUpdateNode`,column:this.transformNode(e.column,t),value:this.transformNode(e.value,t)}}transformLimit(e,t){return{kind:`LimitNode`,limit:this.transformNode(e.limit,t)}}transformOffset(e,t){return{kind:`OffsetNode`,offset:this.transformNode(e.offset,t)}}transformOnConflict(e,t){return{kind:`OnConflictNode`,columns:this.transformNodeList(e.columns,t),constraint:this.transformNode(e.constraint,t),indexExpression:this.transformNode(e.indexExpression,t),indexWhere:this.transformNode(e.indexWhere,t),updates:this.transformNodeList(e.updates,t),updateWhere:this.transformNode(e.updateWhere,t),doNothing:e.doNothing}}transformOnDuplicateKey(e,t){return{kind:`OnDuplicateKeyNode`,updates:this.transformNodeList(e.updates,t)}}transformCreateIndex(e,t){return{kind:`CreateIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists,where:this.transformNode(e.where,t),nullsNotDistinct:e.nullsNotDistinct}}transformList(e,t){return{kind:`ListNode`,items:this.transformNodeList(e.items,t)}}transformDropIndex(e,t){return{kind:`DropIndexNode`,name:this.transformNode(e.name,t),table:this.transformNode(e.table,t),ifExists:e.ifExists,cascade:e.cascade}}transformPrimaryKeyConstraint(e,t){return{kind:`PrimaryKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformUniqueConstraint(e,t){return{kind:`UniqueConstraintNode`,columns:this.transformNodeList(e.columns,t),name:this.transformNode(e.name,t),nullsNotDistinct:e.nullsNotDistinct,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformForeignKeyConstraint(e,t){return{kind:`ForeignKeyConstraintNode`,columns:this.transformNodeList(e.columns,t),references:this.transformNode(e.references,t),name:this.transformNode(e.name,t),onDelete:e.onDelete,onUpdate:e.onUpdate,deferrable:e.deferrable,initiallyDeferred:e.initiallyDeferred}}transformSetOperation(e,t){return{kind:`SetOperationNode`,operator:e.operator,expression:this.transformNode(e.expression,t),all:e.all}}transformReferences(e,t){return{kind:`ReferencesNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t),onDelete:e.onDelete,onUpdate:e.onUpdate}}transformCheckConstraint(e,t){return{kind:`CheckConstraintNode`,expression:this.transformNode(e.expression,t),name:this.transformNode(e.name,t)}}transformWith(e,t){return{kind:`WithNode`,expressions:this.transformNodeList(e.expressions,t),recursive:e.recursive}}transformCommonTableExpression(e,t){return{kind:`CommonTableExpressionNode`,name:this.transformNode(e.name,t),materialized:e.materialized,expression:this.transformNode(e.expression,t)}}transformCommonTableExpressionName(e,t){return{kind:`CommonTableExpressionNameNode`,table:this.transformNode(e.table,t),columns:this.transformNodeList(e.columns,t)}}transformHaving(e,t){return{kind:`HavingNode`,having:this.transformNode(e.having,t)}}transformCreateSchema(e,t){return{kind:`CreateSchemaNode`,schema:this.transformNode(e.schema,t),ifNotExists:e.ifNotExists}}transformDropSchema(e,t){return{kind:`DropSchemaNode`,schema:this.transformNode(e.schema,t),ifExists:e.ifExists,cascade:e.cascade}}transformAlterTable(e,t){return{kind:`AlterTableNode`,table:this.transformNode(e.table,t),renameTo:this.transformNode(e.renameTo,t),setSchema:this.transformNode(e.setSchema,t),columnAlterations:this.transformNodeList(e.columnAlterations,t),addConstraint:this.transformNode(e.addConstraint,t),dropConstraint:this.transformNode(e.dropConstraint,t),renameConstraint:this.transformNode(e.renameConstraint,t),addIndex:this.transformNode(e.addIndex,t),dropIndex:this.transformNode(e.dropIndex,t)}}transformDropColumn(e,t){return{kind:`DropColumnNode`,column:this.transformNode(e.column,t),ifExists:e.ifExists}}transformRenameColumn(e,t){return{kind:`RenameColumnNode`,column:this.transformNode(e.column,t),renameTo:this.transformNode(e.renameTo,t)}}transformAlterColumn(e,t){return{kind:`AlterColumnNode`,column:this.transformNode(e.column,t),dataType:this.transformNode(e.dataType,t),dataTypeExpression:this.transformNode(e.dataTypeExpression,t),setDefault:this.transformNode(e.setDefault,t),dropDefault:e.dropDefault,setNotNull:e.setNotNull,dropNotNull:e.dropNotNull}}transformModifyColumn(e,t){return{kind:`ModifyColumnNode`,column:this.transformNode(e.column,t)}}transformAddConstraint(e,t){return{kind:`AddConstraintNode`,constraint:this.transformNode(e.constraint,t)}}transformDropConstraint(e,t){return{kind:`DropConstraintNode`,constraintName:this.transformNode(e.constraintName,t),ifExists:e.ifExists,modifier:e.modifier}}transformRenameConstraint(e,t){return{kind:`RenameConstraintNode`,oldName:this.transformNode(e.oldName,t),newName:this.transformNode(e.newName,t)}}transformCreateView(e,t){return{kind:`CreateViewNode`,name:this.transformNode(e.name,t),temporary:e.temporary,orReplace:e.orReplace,ifNotExists:e.ifNotExists,materialized:e.materialized,columns:this.transformNodeList(e.columns,t),as:this.transformNode(e.as,t)}}transformRefreshMaterializedView(e,t){return{kind:`RefreshMaterializedViewNode`,name:this.transformNode(e.name,t),concurrently:e.concurrently,withNoData:e.withNoData}}transformDropView(e,t){return{kind:`DropViewNode`,name:this.transformNode(e.name,t),ifExists:e.ifExists,materialized:e.materialized,cascade:e.cascade}}transformGenerated(e,t){return{kind:`GeneratedNode`,byDefault:e.byDefault,always:e.always,identity:e.identity,stored:e.stored,expression:this.transformNode(e.expression,t)}}transformDefaultValue(e,t){return{kind:`DefaultValueNode`,defaultValue:this.transformNode(e.defaultValue,t)}}transformOn(e,t){return{kind:`OnNode`,on:this.transformNode(e.on,t)}}transformSelectModifier(e,t){return{kind:`SelectModifierNode`,modifier:e.modifier,rawModifier:this.transformNode(e.rawModifier,t),of:this.transformNodeList(e.of,t)}}transformCreateType(e,t){return{kind:`CreateTypeNode`,name:this.transformNode(e.name,t),enum:this.transformNode(e.enum,t)}}transformDropType(e,t){return{kind:`DropTypeNode`,name:this.transformNode(e.name,t),additionalNames:this.transformNodeList(e.additionalNames,t),cascade:e.cascade,ifExists:e.ifExists}}transformExplain(e,t){return{kind:`ExplainNode`,format:e.format,options:this.transformNode(e.options,t)}}transformSchemableIdentifier(e,t){return{kind:`SchemableIdentifierNode`,schema:this.transformNode(e.schema,t),identifier:this.transformNode(e.identifier,t)}}transformAggregateFunction(e,t){return{kind:`AggregateFunctionNode`,func:e.func,aggregated:this.transformNodeList(e.aggregated,t),distinct:e.distinct,orderBy:this.transformNode(e.orderBy,t),withinGroup:this.transformNode(e.withinGroup,t),filter:this.transformNode(e.filter,t),over:this.transformNode(e.over,t)}}transformOver(e,t){return{kind:`OverNode`,orderBy:this.transformNode(e.orderBy,t),partitionBy:this.transformNode(e.partitionBy,t)}}transformPartitionBy(e,t){return{kind:`PartitionByNode`,items:this.transformNodeList(e.items,t)}}transformPartitionByItem(e,t){return{kind:`PartitionByItemNode`,partitionBy:this.transformNode(e.partitionBy,t)}}transformBinaryOperation(e,t){return{kind:`BinaryOperationNode`,leftOperand:this.transformNode(e.leftOperand,t),operator:this.transformNode(e.operator,t),rightOperand:this.transformNode(e.rightOperand,t)}}transformUnaryOperation(e,t){return{kind:`UnaryOperationNode`,operator:this.transformNode(e.operator,t),operand:this.transformNode(e.operand,t)}}transformUsing(e,t){return{kind:`UsingNode`,tables:this.transformNodeList(e.tables,t)}}transformFunction(e,t){return{kind:`FunctionNode`,func:e.func,arguments:this.transformNodeList(e.arguments,t)}}transformCase(e,t){return{kind:`CaseNode`,value:this.transformNode(e.value,t),when:this.transformNodeList(e.when,t),else:this.transformNode(e.else,t),isStatement:e.isStatement}}transformWhen(e,t){return{kind:`WhenNode`,condition:this.transformNode(e.condition,t),result:this.transformNode(e.result,t)}}transformJSONReference(e,t){return{kind:`JSONReferenceNode`,reference:this.transformNode(e.reference,t),traversal:this.transformNode(e.traversal,t)}}transformJSONPath(e,t){return{kind:`JSONPathNode`,inOperator:this.transformNode(e.inOperator,t),pathLegs:this.transformNodeList(e.pathLegs,t)}}transformJSONPathLeg(e,t){return{kind:`JSONPathLegNode`,type:e.type,value:e.value}}transformJSONOperatorChain(e,t){return{kind:`JSONOperatorChainNode`,operator:this.transformNode(e.operator,t),values:this.transformNodeList(e.values,t)}}transformTuple(e,t){return{kind:`TupleNode`,values:this.transformNodeList(e.values,t)}}transformMergeQuery(e,t){return{kind:`MergeQueryNode`,into:this.transformNode(e.into,t),using:this.transformNode(e.using,t),whens:this.transformNodeList(e.whens,t),with:this.transformNode(e.with,t),top:this.transformNode(e.top,t),endModifiers:this.transformNodeList(e.endModifiers,t),output:this.transformNode(e.output,t),returning:this.transformNode(e.returning,t)}}transformMatched(e,t){return{kind:`MatchedNode`,not:e.not,bySource:e.bySource}}transformAddIndex(e,t){return{kind:`AddIndexNode`,name:this.transformNode(e.name,t),columns:this.transformNodeList(e.columns,t),unique:e.unique,using:this.transformNode(e.using,t),ifNotExists:e.ifNotExists}}transformCast(e,t){return{kind:`CastNode`,expression:this.transformNode(e.expression,t),dataType:this.transformNode(e.dataType,t)}}transformFetch(e,t){return{kind:`FetchNode`,rowCount:this.transformNode(e.rowCount,t),modifier:e.modifier}}transformTop(e,t){return{kind:`TopNode`,expression:e.expression,modifiers:e.modifiers}}transformOutput(e,t){return{kind:`OutputNode`,selections:this.transformNodeList(e.selections,t)}}transformAlterType(e,t){return{kind:`AlterTypeNode`,name:this.transformNode(e.name,t),addValue:this.transformNode(e.addValue,t),renameTo:this.transformNode(e.renameTo,t),renameValue:this.transformNode(e.renameValue,t),setSchema:this.transformNode(e.setSchema,t)}}transformAddValue(e,t){return{kind:`AddValueNode`,value:this.transformNode(e.value,t),ifNotExists:e.ifNotExists,isBefore:e.isBefore,neighborValue:this.transformNode(e.neighborValue,t)}}transformRenameValue(e,t){return{kind:`RenameValueNode`,oldValue:this.transformNode(e.oldValue,t),newValue:this.transformNode(e.newValue,t)}}transformDataType(e,t){return e}transformSelectAll(e,t){return e}transformIdentifier(e,t){return e}transformValue(e,t){return e}transformPrimitiveValueList(e,t){return e}transformOperator(e,t){return e}transformDefaultInsertValue(e,t){return e}transformOrAction(e,t){return e}transformCollate(e,t){return e}};function isOperationNode(e){return isObject(e)&&isString(e.kind)}const pl={AlterTableNode:!0,AlterTypeNode:!0,CreateIndexNode:!0,CreateSchemaNode:!0,CreateTableNode:!0,CreateTypeNode:!0,CreateViewNode:!0,DeleteQueryNode:!0,DropIndexNode:!0,DropSchemaNode:!0,DropTableNode:!0,DropTypeNode:!0,RefreshMaterializedViewNode:!0,DropViewNode:!0,InsertQueryNode:!0,RawNode:!0,SelectQueryNode:!0,UpdateQueryNode:!0,MergeQueryNode:!0};function isRootOperationNode(e){return isOperationNode(e)&&pl[e.kind]===!0}const ml=freeze({json_agg:!0,to_json:!0});var WithSchemaTransformer=class extends OperationNodeTransformer{#e;#t=/* @__PURE__ */ new Set;#n=/* @__PURE__ */ new Set;constructor(e){super(),this.#e=e}transformNodeImpl(e,t){if(!isRootOperationNode(e))return super.transformNodeImpl(e,t);let n=this.#a(e);for(let e of n)this.#n.add(e);let r=this.#i(e);for(let e of r)this.#t.add(e);let i=super.transformNodeImpl(e,t);for(let e of r)this.#t.delete(e);for(let e of n)this.#n.delete(e);return i}transformSchemableIdentifier(e,t){let n=super.transformSchemableIdentifier(e,t);return n.schema||!this.#t.has(e.identifier.name)?n:{...n,schema:M.create(this.#e)}}transformReferences(e,t){let n=super.transformReferences(e,t);return n.table.table.schema?n:{...n,table:P.createWithSchema(this.#e,n.table.table.identifier.name)}}transformAggregateFunction(e,t){return{...super.transformAggregateFunction({...e,aggregated:[]},t),aggregated:this.#r(e,t,`aggregated`)}}transformFunction(e,t){return{...super.transformFunction({...e,arguments:[]},t),arguments:this.#r(e,t,`arguments`)}}transformSelectModifier(e,t){return{...super.transformSelectModifier({...e,of:void 0},t),of:e.of?.map(e=>P.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return ml[e.func]?e[n].map(e=>!P.is(e)||e.table.schema?this.transformNode(e,t):{...e,table:this.transformIdentifier(e.table.identifier,t)}):this.transformNodeList(e[n],t)}#i(e){let t=/* @__PURE__ */ new Set;if(`name`in e&&e.name&&tc.is(e.name)&&this.#s(e.name,t),`from`in e&&e.from)for(let n of e.from.froms)this.#o(n,t);if(`into`in e&&e.into&&this.#o(e.into,t),`table`in e&&e.table&&this.#o(e.table,t),`joins`in e&&e.joins)for(let n of e.joins)this.#o(n.table,t);return`using`in e&&e.using&&(uc.is(e.using)?this.#o(e.using.table,t):this.#o(e.using,t)),t}#a(e){let t=/* @__PURE__ */ new Set;return`with`in e&&e.with&&this.#c(e.with,t),t}#o(e,t){if(P.is(e))return this.#s(e.table,t);if(ac.is(e)&&P.is(e.node))return this.#s(e.node.table,t);if(Bc.is(e))for(let n of e.items)this.#o(n,t);else if(Hc.is(e))for(let n of e.tables)this.#o(n,t)}#s(e,t){let n=e.identifier.name;!this.#t.has(n)&&!this.#n.has(n)&&t.add(n)}#c(e,t){for(let n of e.expressions){let e=n.name.table.table.identifier.name;this.#n.has(e)||t.add(e)}}},WithSchemaPlugin=class{#e;constructor(e){this.#e=new WithSchemaTransformer(e)}transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}async transformResult(e){return e.result}};const hl=freeze({is(e){return e.kind===`MatchedNode`},create(e,t=!1){return freeze({kind:`MatchedNode`,not:e,bySource:t})}});function parseMergeWhen(e,t,n){return Kc.create(parseFilterList([hl.create(!e.isMatched,e.bySource),...t&&t.length>0?[t.length===3&&n?parseReferentialBinaryOperation(t[0],t[1],t[2]):parseValueBinaryOperationOrExpression(t)]:[]],`and`,!1))}function parseMergeThen(e){return isString(e)?I.create([e],[]):isOperationNodeSource(e)?e.toOperationNode():e}var Deferred=class{#e;#t;#n;constructor(){this.#e=new Promise((e,t)=>{this.#n=t,this.#t=e})}get promise(){return this.#e}resolve=e=>{this.#t?.(e),this.#t=this.#n=void 0};reject=e=>{this.#n?.(e),this.#n=this.#t=void 0}};async function provideControlledConnection(e,t){let n=new Deferred,r=new Deferred;return e.provideConnection(async e=>(n.resolve(e),await r.promise),t).catch(e=>n.reject(e)),freeze({connection:await n.promise,release:r.resolve})}function getInflightQueryAbortHandler(e=`ignore query`,t,n){if(e!==`ignore query`){if(e===`cancel query`){let r=t.cancelQuery;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.killSession?`kill session`:void 0)),r.bind(t)}if(e===`kill session`){let r=t.killSession;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.cancelQuery?`cancel query`:void 0)),r.bind(t)}throw n(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function throwUnsupportedInflightQueryAbortStrategyError(e,t){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${t?` or "${t}"`:``} instead.`)}function assertNotAborted(e,t,n){e?.aborted&&(n?.(),throwReasonWithTiming(e.reason,t))}function throwReasonWithTiming(e,t){throw decorateWithTiming(e,t),e}const K={};async function waitOrAbort(e,t,n,r){if(!t)return e;assertNotAborted(t,`before ${n}`,r);let{promise:i,resolve:a}=new Deferred,abortListener=()=>a(K);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==K)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(K)}}function printBackgroundFail(e){return t=>console.error(`\`${e}\` failed in the background after abortion: ${getMessage(t)}`)}function decorateWithTiming(e,t){typeof e==`object`&&e&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:t,writable:!1})}const gl=freeze([]);var QueryExecutorBase=class{#e;constructor(e=gl){this.#e=e}get plugins(){return this.#e}transformQuery(e,t){for(let n of this.#e){let r=n.transformQuery({node:e,queryId:t});if(r.kind===e.kind)e=r;else throw Error([`KyselyPlugin.transformQuery must return a node`,`of the same kind that was given to it.`,`The plugin was given a ${e.kind}`,`but it returned a ${r.kind}`].join(` `))}return e}async executeQuery(e,t){let{inflightQueryAbortStrategy:n=`ignore query`,signal:r}=t||{};if(!r){let n=await this.provideConnection(async t=>await t.executeQuery(e),t);return await this.#t(n,e.queryId)}assertNotAborted(r,`before query execution`),t=freeze({signal:r});let{connection:i,release:a}=await provideControlledConnection(this,t),o=this.provideConnection.bind(this),{promise:s,resolve:c}=new Deferred,abortListener=()=>c(K);r.addEventListener(`abort`,abortListener,{once:!0});try{assertNotAborted(r,`before query execution`,a);let c=getInflightQueryAbortHandler(n,i,a);if(c&&i.collectSessionInfo){assertNotAborted(r,`before query execution`,a);let e=i.collectSessionInfo();await Promise.race([s,e]).catch(e=>{throw a(),e})===K&&(e.catch(printBackgroundFail(`collectSessionInfo`)).finally(a),throwReasonWithTiming(r.reason,`before query execution`))}let l=i.executeQuery(e,t),u=await Promise.race([s,l]).catch(e=>{throw a(),e});u===K?(Promise.allSettled([l.catch(printBackgroundFail(`query`)),c?.(o).catch(printBackgroundFail(`inflightQueryAbortHandler`))]).finally(a),throwReasonWithTiming(r.reason,`during query execution`)):a();let d=this.#t(u,e.queryId,t),f=await Promise.race([s,d]);return f===K&&(d.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),f}finally{c(K),r.removeEventListener(`abort`,abortListener)}}async*stream(e,t,n){let{signal:r}=n||{};if(!r){let{connection:r,release:i}=await provideControlledConnection(this);try{for await(let i of r.streamQuery(e,t))yield await this.#t(i,e.queryId,n)}finally{i()}return}n=freeze({signal:r}),assertNotAborted(r,`before connection acquisition`);let{connection:i,release:a}=await provideControlledConnection(this,n),{promise:o,resolve:s}=new Deferred,abortListener=()=>s(K);r.addEventListener(`abort`,abortListener,{once:!0});let c,l;assertNotAborted(r,`before query streaming`,a);let{queryId:u}=e;try{for(c=i.streamQuery(e,t,n);;){assertNotAborted(r,`during query streaming`);let e=c.next(),t=await Promise.race([o,e]);if(t===K&&(l=e.catch(printBackgroundFail(`iterator.next`)),throwReasonWithTiming(r.reason,`during query streaming`)),t.done)break;let i=this.#t(t.value,u,n),a=await Promise.race([o,i]);a===K&&(l=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{s(K),r.removeEventListener(`abort`,abortListener);let e=(c?.return?.()||Promise.resolve()).finally(()=>l).finally(a);l||await e}}async#t(e,t,n){let{signal:r}=n||{};for(let n of this.#e)e=await n.transformResult(freeze({queryId:t,result:e,signal:r}));return e}};const _l=new class NoopQueryExecutor extends QueryExecutorBase{get adapter(){throw Error(`this query cannot be compiled to SQL`)}compileQuery(){throw Error(`this query cannot be compiled to SQL`)}provideConnection(){throw Error(`this query cannot be executed`)}withConnectionProvider(){throw Error(`this query cannot have a connection provider`)}withPlugin(e){return new NoopQueryExecutor([...this.plugins,e])}withPlugins(e){return new NoopQueryExecutor([...this.plugins,...e])}withPluginAtFront(e){return new NoopQueryExecutor([e,...this.plugins])}withoutPlugins(){return new NoopQueryExecutor([])}};var MergeResult=class{numChangedRows;constructor(e){this.numChangedRows=e}},vl=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:V.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new yl({...this.#e,queryNode:B.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},yl=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:V.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}whenMatched(){return this.#t([])}whenMatchedAnd(...e){return this.#t(e)}whenMatchedAndRef(e,t,n){return this.#t([e,t,n],!0)}#t(e,t){return new MatchedThenableMergeQueryBuilder({...this.#e,queryNode:B.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!0},e,t))})}whenNotMatched(){return this.#n([])}whenNotMatchedAnd(...e){return this.#n(e)}whenNotMatchedAndRef(e,t,n){return this.#n([e,t,n],!0)}whenNotMatchedBySource(){return this.#n([],!1,!0)}whenNotMatchedBySourceAnd(...e){return this.#n(e,!1,!0)}whenNotMatchedBySourceAndRef(e,t,n){return this.#n([e,t,n],!0,!0)}returning(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:V.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:V.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:B.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!1,bySource:n},e,t))};return new(n?MatchedThenableMergeQueryBuilder:NotMatchedThenableMergeQueryBuilder)(r)}$call(e){return e(this)}$if(e,t){return e?t(this):new WheneableMergeQueryBuilder({...this.#e})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new MergeResult(n.numAffectedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}},MatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDelete(){return new yl({...this.#e,queryNode:B.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new yl({...this.#e,queryNode:B.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new yl({...this.#e,queryNode:B.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:_l,queryNode:Vc.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new yl({...this.#e,queryNode:B.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new yl({...this.#e,queryNode:B.cloneWithThen(this.#e.queryNode,parseMergeThen(R.cloneWith(R.createWithoutInto(),{columns:t,values:n})))})}},bl=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:H.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:H.cloneWithSelections(H.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new ol({queryId:createQueryId(),executor:this.#e.executor,queryNode:R.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new ol({queryId:createQueryId(),executor:this.#e.executor,queryNode:R.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Uc.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Vc.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new vl({queryId:createQueryId(),executor:this.#e.executor,queryNode:B.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?dl.cloneWithExpression(this.#e.withNode,n):dl.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?dl.cloneWithExpression(this.#e.withNode,n):dl.create(n,{recursive:!0})})}withPlugin(e){return new QueryCreator({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new QueryCreator({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new QueryCreator({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}};function createQueryCreator(){return new bl({executor:_l})}function createJoinBuilder(e,t){return new Jc({joinNode:uc.create(e,parseTableExpression(t))})}function createOverBuilder(){return new Xc({overNode:Ic.create()})}function parseJoin(e,t){if(t.length===3)return parseSingleOnJoin(e,t[0],t[1],t[2]);if(t.length===2)return parseCallbackJoin(e,t[0],t[1]);if(t.length===1)return parseOnlessJoin(e,t[0]);throw Error(`not implemented`)}function parseCallbackJoin(e,t,n){return n(createJoinBuilder(e,t)).toOperationNode()}function parseSingleOnJoin(e,t,n,r){return uc.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return uc.create(e,parseTableExpression(t))}const xl=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),Sl=freeze({is(e){return e.kind===`GroupByItemNode`},create(e){return freeze({kind:`GroupByItemNode`,groupBy:e})}});function parseGroupBy(e){return e=isFunction(e)?e(expressionBuilder()):e,parseReferenceExpressionOrList(e).map(Sl.create)}const Cl=freeze({is(e){return e.kind===`SetOperationNode`},create(e,t,n){return freeze({kind:`SetOperationNode`,operator:e,expression:t,all:n})}});function parseSetOperations(e,t,n){return isFunction(t)&&(t=t(createExpressionBuilder())),isReadonlyArray(t)||(t=[t]),t.map(t=>Cl.create(e,parseExpression(t),n))}var q=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new wl(cc.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new Tl(sc.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new ExpressionWrapper(this.#e)}$notNull(){return new ExpressionWrapper(this.#e)}toOperationNode(){return this.#e}},AliasedExpressionWrapper=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return ac.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():M.create(this.#t))}},wl=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(cc.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return Nc.create(this.#e)}},Tl=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(sc.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return Nc.create(this.#e)}};const El=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:L.create(e),modifier:t}}});function parseFetch(e,t){if(!isNumber(e)&&!isBigInt(e))throw Error(`Invalid fetch row count: ${e}`);if(!isFetchModifier(t))throw Error(`Invalid fetch modifier: ${t}`);return El.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var J,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new J({...this.#e,queryNode:V.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new J({...this.#e,queryNode:V.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new J({...this.#e,queryNode:H.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new J({...this.#e,queryNode:H.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new J({...this.#e,queryNode:H.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new J({...this.#e,queryNode:H.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new J({...this.#e,queryNode:H.cloneWithFrontModifier(this.#e.queryNode,oc.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new J({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,oc.createWithExpression(e.toOperationNode()))})}distinct(){return new J({...this.#e,queryNode:H.cloneWithFrontModifier(this.#e.queryNode,oc.create(`Distinct`))})}forUpdate(e){return new J({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,oc.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new J({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,oc.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new J({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,oc.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new J({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,oc.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new J({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,oc.create(`SkipLocked`))})}noWait(){return new J({...this.#e,queryNode:V.cloneWithEndModifier(this.#e.queryNode,oc.create(`NoWait`))})}selectAll(e){return new J({...this.#e,queryNode:H.cloneWithSelections(this.#e.queryNode,parseSelectAll(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}crossJoin(...e){return this.#t(`CrossJoin`,e)}innerJoinLateral(...e){return this.#t(`LateralInnerJoin`,e)}leftJoinLateral(...e){return this.#t(`LateralLeftJoin`,e)}crossJoinLateral(...e){return this.#t(`LateralCrossJoin`,e)}crossApply(...e){return this.#t(`CrossApply`,e)}outerApply(...e){return this.#t(`OuterApply`,e)}#t(e,t){return new J({...this.#e,queryNode:V.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new J({...this.#e,queryNode:V.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new J({...this.#e,queryNode:H.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new J({...this.#e,queryNode:H.cloneWithLimit(this.#e.queryNode,sl.create(parseValueExpression(e)))})}offset(e){return new J({...this.#e,queryNode:H.cloneWithOffset(this.#e.queryNode,xl.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new J({...this.#e,queryNode:H.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new J({...this.#e,queryNode:V.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new J({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new J({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new J({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new J({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new J({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new J({...this.#e,queryNode:H.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new J({...this.#e,queryNode:H.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new J({...this.#e,queryNode:V.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new J({...this.#e,queryNode:H.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new J({...this.#e,queryNode:H.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new J({...this.#e,queryNode:V.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new J({...this.#e,queryNode:H.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new J({...this.#e})}$castTo(){return new J(this.#e)}$narrowType(){return new J(this.#e)}$assertType(){return new J(this.#e)}$asTuple(){return new q(this.toOperationNode())}$asScalar(){return new q(this.toOperationNode())}withPlugin(e){return new J({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile();return(await this.#e.executor.executeQuery(t,e)).rows}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new J({...this.#e,queryNode:V.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};J=SelectQueryBuilderImpl;function createSelectQueryBuilder(e){return new SelectQueryBuilderImpl(e)}var AliasedSelectQueryBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return ac.create(this.#e.toOperationNode(),M.create(this.#t))}};const Dl=freeze({is(e){return e.kind===`AggregateFunctionNode`},create(e,t=[]){return freeze({kind:`AggregateFunctionNode`,func:e,aggregated:t})},cloneWithDistinct(e){return freeze({...e,distinct:!0})},cloneWithOrderBy(e,t,n=!1){let r=n?`withinGroup`:`orderBy`;return freeze({...e,[r]:e[r]?Pc.cloneWithItems(e[r],t):Pc.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?z.cloneWithOperation(e.filter,`And`,t):z.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?z.cloneWithOperation(e.filter,`Or`,t):z.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),Ol=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var kl=class AggregateFunctionBuilder{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}as(e){return new AliasedAggregateFunctionBuilder(this,e)}distinct(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Dl.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:V.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:V.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Dl.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Dl.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Dl.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Dl.cloneWithOver(this.#e.aggregateFunctionNode,(e?e(t):t).toOperationNode())})}$call(e){return e(this)}$castTo(){return new AggregateFunctionBuilder(this.#e)}$notNull(){return new AggregateFunctionBuilder(this.#e)}toOperationNode(){return this.#e.aggregateFunctionNode}},AliasedAggregateFunctionBuilder=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return ac.create(this.#e.toOperationNode(),M.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new q(Ol.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new kl({aggregateFunctionNode:Dl.create(e,t?parseReferenceExpressionOrList(t):void 0)});return Object.assign(fn,{agg,avg(e){return agg(`avg`,[e])},coalesce(...e){return fn(`coalesce`,e)},count(e){return agg(`count`,[e])},countAll(e){return new kl({aggregateFunctionNode:Dl.create(`count`,parseSelectAll(e))})},max(e){return agg(`max`,[e])},min(e){return agg(`min`,[e])},sum(e){return agg(`sum`,[e])},any(e){return fn(`any`,[e])},jsonAgg(e){return new kl({aggregateFunctionNode:Dl.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new q(Ol.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const Al=freeze({is(e){return e.kind===`UnaryOperationNode`},create(e,t){return freeze({kind:`UnaryOperationNode`,operator:e,operand:t})}});function parseUnaryOperation(e,t){if(isUnaryOperator(e))return Al.create(xc.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const Y=freeze({is(e){return e.kind===`CaseNode`},create(e){return freeze({kind:`CaseNode`,value:e})},cloneWithWhen(e,t){return freeze({...e,when:freeze(e.when?[...e.when,t]:[t])})},cloneWithThen(e,t){return freeze({...e,when:e.when?freeze([...e.when.slice(0,-1),Kc.cloneWithResult(e.when[e.when.length-1],t)]):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var CaseBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:Y.cloneWithWhen(this.#e.node,Kc.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:Y.cloneWithWhen(this.#e.node,Kc.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:Y.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:Y.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:Y.cloneWithWhen(this.#e.node,Kc.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:Y.cloneWithWhen(this.#e.node,Kc.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:Y.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:Y.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new q(Y.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new q(Y.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new q(Y.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new q(Y.cloneWith(this.#e.node,{isStatement:!0}))}};const jl=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),Ml=/^#-\d+$/;var JSONPathBuilder=class{#e;constructor(e){this.#e=e}at(e){if(typeof e!=`number`&&typeof e!=`string`||typeof e==`number`&&!Number.isInteger(e)||typeof e==`string`&&e!==`last`&&!Ml.test(e))throw Error(`Unexpected index value in .at(...): ${e}`);return this.#t(`ArrayLocation`,e)}key(e){return this.#t(`Member`,e)}#t(e,t){return Oc.is(this.#e)?new Nl(Oc.cloneWithTraversal(this.#e,Ac.is(this.#e.traversal)?Ac.cloneWithLeg(this.#e.traversal,jl.create(e,t)):kc.cloneWithValue(this.#e.traversal,L.createImmediate(t)))):new Nl(Ac.cloneWithLeg(this.#e,jl.create(e,t)))}},Nl=class TraversedJSONPathBuilder extends JSONPathBuilder{#e;constructor(e){super(e),this.#e=e}get expressionType(){}as(e){return new AliasedJSONPathBuilder(this,e)}$castTo(){return new TraversedJSONPathBuilder(this.#e)}$notNull(){return new TraversedJSONPathBuilder(this.#e)}toOperationNode(){return this.#e}},AliasedJSONPathBuilder=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}toOperationNode(){return ac.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():M.create(this.#t))}};const Pl=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),Fl=freeze({bigint:!0,bigserial:!0,binary:!0,blob:!0,boolean:!0,bytea:!0,char:!0,date:!0,datemultirange:!0,daterange:!0,datetime:!0,datetime2:!0,decimal:!0,"double precision":!0,float4:!0,float8:!0,int2:!0,int4:!0,int4multirange:!0,int4range:!0,int8:!0,int8multirange:!0,int8range:!0,integer:!0,json:!0,jsonb:!0,numeric:!0,nummultirange:!0,numrange:!0,real:!0,serial:!0,smallint:!0,text:!0,time:!0,timestamp:!0,timestamptz:!0,timetz:!0,tsmultirange:!0,tsrange:!0,tstzmultirange:!0,tstzrange:!0,uuid:!0,varbinary:!0,varchar:!0}),Il=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+\)$/]),Ll=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return Fl[e]||Il.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return Ll.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const Rl=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=_l){function binary(e,t,n){return new q(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new q(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:H.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:Y.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new q(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(Ac.create())},table(e){return new q(parseTable(e))},val(e){return new q(parseValueExpression(e))},refTuple(...e){return new q(Pl.create(e.map(parseReferenceExpression)))},tuple(...e){return new q(Pl.create(e.map(parseValueExpression)))},lit(e){return new q(parseSafeImmediateValue(e))},unary,not(e){return unary(`not`,e)},exists(e){return unary(`exists`,e)},neg(e){return unary(`-`,e)},between(e,t,n){return new q(dc.create(parseReferenceExpression(e),xc.create(`between`),sc.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new q(dc.create(parseReferenceExpression(e),xc.create(`between symmetric`),sc.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new q(parseFilterList(e,`and`)):new q(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new q(parseFilterList(e,`or`)):new q(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return Nc.is(t)?new q(t):new q(Nc.create(t))},cast(e,t){return new q(Rl.create(parseReferenceExpression(e),parseDataTypeExpression(t)))}});return t.fn=createFunctionModule(),t.eb=t,t}function expressionBuilder(e){return createExpressionBuilder()}function parseExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid expression: ${JSON.stringify(e)}`)}function parseAliasedExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isFunction(e))return e(expressionBuilder()).toOperationNode();throw Error(`invalid aliased expression: ${JSON.stringify(e)}`)}function isExpressionOrFactory(e){return isExpression(e)||isAliasedExpression(e)||isFunction(e)}var DynamicTableBuilder=class{#e;get table(){return this.#e}constructor(e){this.#e=e}as(e){return new AliasedDynamicTableBuilder(this.#e,e)}},AliasedDynamicTableBuilder=class{#e;#t;get table(){return this.#e}get alias(){return this.#t}constructor(e,t){this.#e=e,this.#t=t}toOperationNode(){return ac.create(parseTable(this.#e),M.create(this.#t))}};function isAliasedDynamicTableBuilder(e){return isObject(e)&&isOperationNodeSource(e)&&isString(e.table)&&isString(e.alias)}function parseTableExpressionOrList(e){return isReadonlyArray(e)?e.map(e=>parseTableExpression(e)):[parseTableExpression(e)]}function parseTableExpression(e){return isString(e)?parseAliasedTable(e):isAliasedDynamicTableBuilder(e)?e.toOperationNode():parseAliasedExpression(e)}function parseAliasedTable(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim$1);return ac.create(parseTable(n),M.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return P.createWithSchema(t,n)}return P.create(e)}function trim$1(e){return e.trim()}const zl=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}}),X=freeze({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return freeze({kind:`ColumnDefinitionNode`,column:F.create(e),dataType:t})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):[t]})},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):[t]})},cloneWith(e,t){return freeze({...e,...t})}}),Bl=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:F.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Vl=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:F.create(e),renameTo:F.create(t)})}}),Hl=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?M.create(t):void 0})}}),Ul=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys(Ul);const Wl=freeze({is(e){return e.kind===`ReferencesNode`},create(e,t){return freeze({kind:`ReferencesNode`,table:e,columns:freeze([...t])})},cloneWithOnDelete(e,t){return freeze({...e,onDelete:t})},cloneWithOnUpdate(e,t){return freeze({...e,onUpdate:t})}});function isOnModifyForeignAction(e){return isString(e)&&Ul[e]}function parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():L.createImmediate(e)}const Gl=freeze({is(e){return e.kind===`GeneratedNode`},create(e){return freeze({kind:`GeneratedNode`,...e})},createWithExpression(e){return freeze({kind:`GeneratedNode`,always:!0,expression:e})},cloneWith(e,t){return freeze({...e,...t})}}),Kl=freeze({is(e){return e.kind===`DefaultValueNode`},create(e){return freeze({kind:`DefaultValueNode`,defaultValue:e})}});function parseOnModifyForeignAction(e){if(isOnModifyForeignAction(e))return e;throw Error(`invalid OnModifyForeignAction ${e}`)}var ql=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||Sc.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{references:Wl.create(t.table,[t.column])}))}onDelete(e){if(!this.#e.references)throw Error(`on delete constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{references:Wl.cloneWithOnDelete(this.#e.references,parseOnModifyForeignAction(e))}))}onUpdate(e){if(!this.#e.references)throw Error(`on update constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{references:Wl.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{defaultTo:Kl.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{check:Hl.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{generated:Gl.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{generated:Gl.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{generated:Gl.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{generated:Gl.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(X.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(X.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(X.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}};const Jl=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}}),Yl=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:Wl.create(t,n),name:r?M.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var Xl=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(Yl.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(Yl.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(Yl.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(Yl.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(Yl.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(Yl.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}};const Zl=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}}),Ql=freeze({is(e){return e.kind===`UniqueConstraintNode`},create(e,t,n){return isString(e.at(0))&&(logOnce("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(F.create)),freeze({kind:`UniqueConstraintNode`,columns:freeze(e),name:t?M.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return freeze({...e,...t})}}),$l=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:M.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),eu=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:F.create(e),[t]:n})}});var AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(eu.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(eu.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(eu.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(eu.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(eu.create(this.#e,`dropNotNull`,!0))}$call(e){return e(this)}},AlteredColumnBuilder=class{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}},AlterTableExecutor=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},tu=class AlterTableAddForeignKeyConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}onDelete(e){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.onDelete(e)})}onUpdate(e){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.onUpdate(e)})}deferrable(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.deferrable()})}notDeferrable(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new AlterTableAddForeignKeyConstraintBuilder({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyImmediate()})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(j.cloneWithTableProps(this.#e.node,{addConstraint:Zl.create(this.#e.constraintBuilder.toOperationNode())}),this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},nu=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:j.cloneWithTableProps(this.#e.node,{dropConstraint:$l.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:j.cloneWithTableProps(this.#e.node,{dropConstraint:$l.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:j.cloneWithTableProps(this.#e.node,{dropConstraint:$l.cloneWith(this.#e.node.dropConstraint,{modifier:`restrict`})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const ru=freeze({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return freeze({kind:`PrimaryKeyConstraintNode`,columns:freeze(e.map(F.create)),name:t?M.create(t):void 0})},cloneWith(e,t){return freeze({...e,...t})}}),iu=freeze({is(e){return e.kind===`AddIndexNode`},create(e){return freeze({kind:`AddIndexNode`,name:M.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}});var au=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:j.cloneWithTableProps(this.#e.node,{addIndex:iu.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:j.cloneWithTableProps(this.#e.node,{addIndex:iu.cloneWithColumns(this.#e.node.addIndex,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})})}columns(e){return new AlterTableAddIndexBuilder({...this.#e,node:j.cloneWithTableProps(this.#e.node,{addIndex:iu.cloneWithColumns(this.#e.node.addIndex,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})})}expression(e){return new AlterTableAddIndexBuilder({...this.#e,node:j.cloneWithTableProps(this.#e.node,{addIndex:iu.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:j.cloneWithTableProps(this.#e.node,{addIndex:iu.cloneWith(this.#e.node.addIndex,{using:I.createWithSql(e)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},ou=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(Ql.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(Ql.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(Ql.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(Ql.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(Ql.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},su=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(ru.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(ru.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(ru.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(ru.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},CheckConstraintBuilder=class{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}};const cu=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:M.create(e),newName:M.create(t)})}});var lu=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:Bl.cloneWith(this.#e.node,{ifExists:!0})})}toOperationNode(){return this.#e.node}},AlterTableBuilder=class{#e;constructor(e){this.#e=freeze(e)}renameTo(e){return new AlterTableExecutor({...this.#e,node:j.cloneWithTableProps(this.#e.node,{renameTo:parseTable(e)})})}setSchema(e){return new AlterTableExecutor({...this.#e,node:j.cloneWithTableProps(this.#e.node,{setSchema:M.create(e)})})}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new uu({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new lu({node:Bl.create(e)}));return new uu({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new uu({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,Vl.create(e,t))})}addColumn(e,t,n=noop){let r=n(new ql(X.create(e,parseDataTypeExpression(t))));return new uu({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,zl.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new ql(X.create(e,parseDataTypeExpression(t))));return new uu({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,Jl.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new ou(Ql.create(t.map(e=>isString(e)?F.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:j.cloneWithTableProps(this.#e.node,{addConstraint:Zl.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Hl.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:j.cloneWithTableProps(this.#e.node,{addConstraint:Zl.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new Xl(Yl.create(t.map(F.create),parseTable(n),r.map(F.create),e)));return new tu({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new su(ru.create(t,e)));return new AlterTableExecutor({...this.#e,node:j.cloneWithTableProps(this.#e.node,{addConstraint:Zl.create(r.toOperationNode())})})}dropConstraint(e){return new nu({...this.#e,node:j.cloneWithTableProps(this.#e.node,{dropConstraint:$l.create(e)})})}renameConstraint(e,t){return new nu({...this.#e,node:j.cloneWithTableProps(this.#e.node,{renameConstraint:cu.create(e,t)})})}addIndex(e){return new au({...this.#e,node:j.cloneWithTableProps(this.#e.node,{addIndex:iu.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:j.cloneWithTableProps(this.#e.node,{dropIndex:nc.create(e)})})}$call(e){return e(this)}},uu=class AlterTableColumnAlteringBuilder{#e;constructor(e){this.#e=freeze(e)}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new lu({node:Bl.create(e)}));return new AlterTableColumnAlteringBuilder({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new AlterTableColumnAlteringBuilder({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,Vl.create(e,t))})}addColumn(e,t,n=noop){let r=n(new ql(X.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,zl.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new ql(X.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:j.cloneWithColumnAlteration(this.#e.node,Jl.create(r.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},ImmediateValueTransformer=class extends OperationNodeTransformer{transformPrimitiveValueList(e){return Mc.create(e.values.map(L.createImmediate))}transformValue(e){return L.createImmediate(e.value)}},du=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:Qs.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:Qs.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:Qs.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:Qs.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:Qs.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:Qs.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:Qs.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:Qs.cloneWith(this.#e.node,{using:I.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:V.cloneWithWhere(this.#e.node,t.transformNode(parseValueBinaryOperationOrExpression(e),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},fu=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:$s.cloneWith(this.#e.node,{ifNotExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};function parseOnCommitAction(e){if(ec.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var pu=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder(iu.cloneWith(this.#e,{using:I.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},mu=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:N.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:N.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:N.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new ql(X.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:N.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new su(ru.create(t,e)));return new CreateTableBuilder({...this.#e,node:N.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new ou(Ql.create(t.map(e=>isString(e)?F.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:N.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new pu(iu.cloneWithColumns(iu.create(e),t.map(e=>isString(e)?F.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:N.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Hl.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:N.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new Xl(Yl.create(t.map(F.create),parseTable(n),r.map(F.create),e)));return new CreateTableBuilder({...this.#e,node:N.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:N.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:N.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:N.cloneWith(this.#e.node,{selectQuery:parseExpression(e)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},hu=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:nc.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:nc.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:nc.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},gu=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:rc.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:rc.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},_u=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:ic.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:ic.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:ic.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const vu=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:tc.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var ImmediateValuePlugin=class{#e=new ImmediateValueTransformer;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}},yu=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:vu.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:vu.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:vu.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:vu.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:vu.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:vu.cloneWith(this.#e.node,{as:t})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const bu=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:tc.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var xu=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:bu.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:bu.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:bu.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const Su=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:Mc.create(t.map(L.createImmediate))})}});var Cu=class CreateTypeBuilder{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(e){return new CreateTypeBuilder({...this.#e,node:Su.cloneWithEnum(this.#e.node,e)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const wu=freeze({is(e){return e.kind===`DropTypeNode`},create(e){return Array.isArray(e)||(e=[e]),freeze({kind:`DropTypeNode`,name:e[0],additionalNames:e.slice(1)})},cloneWith(e,t){return freeze({...e,...t})}});var Tu=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:wu.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:wu.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};function parseSchemableIdentifier(e){if(e.includes(`.`)){let t=e.split(`.`).map(trim);if(t.length===2)return tc.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return tc.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}const Eu=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:tc.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var Du=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:Eu.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Eu.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Eu.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}};const Ou=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}}),ku=freeze({is(e){return e.kind===`AddValueNode`},create(e){return freeze({kind:`AddValueNode`,value:e})},cloneWith(e,t){return freeze({...e,...t})}});var QueryFinalizer=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){return await this.#e.executor.executeQuery(this.compile(),e)}},Au,AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new Au({...this.#e,node:Ou.cloneWith(this.#e.node,{addValue:ku.cloneWith(this.#e.node.addValue,{ifNotExists:!0})})})}before(e){return this.#t(e,!0)}after(e){return this.#t(e,!1)}#t(e,t){return new Au({...this.#e,node:Ou.cloneWith(this.#e.node,{addValue:ku.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:L.createImmediate(e)})})})}};Au=AlterTypeAddValueBuilder;const ju=freeze({is(e){return e.kind===`RenameValueNode`},create(e,t){return freeze({kind:`RenameValueNode`,oldValue:e,newValue:t})}});var AlterTypeBuilder=class{#e;constructor(e){this.#e=freeze(e)}addValue(e){return new AlterTypeAddValueBuilder({...this.#e,node:Ou.cloneWith(this.#e.node,{addValue:ku.create(L.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:Ou.cloneWith(this.#e.node,{renameTo:M.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:Ou.cloneWith(this.#e.node,{renameValue:ju.create(L.createImmediate(e),L.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:Ou.cloneWith(this.#e.node,{setSchema:M.create(e)})})}},Mu=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new mu({queryId:createQueryId(),executor:this.#e,node:N.create(parseTable(e))})}dropTable(e){return new _u({queryId:createQueryId(),executor:this.#e,node:ic.create(parseTable(e))})}createIndex(e){return new du({queryId:createQueryId(),executor:this.#e,node:Qs.create(e)})}dropIndex(e){return new hu({queryId:createQueryId(),executor:this.#e,node:nc.create(e)})}createSchema(e){return new fu({queryId:createQueryId(),executor:this.#e,node:$s.create(e)})}dropSchema(e){return new gu({queryId:createQueryId(),executor:this.#e,node:rc.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:j.create(parseTable(e))})}createView(e){return new yu({queryId:createQueryId(),executor:this.#e,node:vu.create(e)})}refreshMaterializedView(e){return new Du({queryId:createQueryId(),executor:this.#e,node:Eu.create(e)})}dropView(e){return new xu({queryId:createQueryId(),executor:this.#e,node:bu.create(e)})}createType(e){return new Cu({queryId:createQueryId(),executor:this.#e,node:Su.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:Ou.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new Tu({queryId:createQueryId(),executor:this.#e,node:wu.create(parseSchemableIdentifierArray(e))})}withPlugin(e){return new SchemaModule(this.#e.withPlugin(e))}withoutPlugins(){return new SchemaModule(this.#e.withoutPlugins())}withSchema(e){return new SchemaModule(this.#e.withPluginAtFront(new WithSchemaPlugin(e)))}},DynamicModule=class{ref(e){return new DynamicReferenceBuilder(e)}table(e){return new DynamicTableBuilder(e)}},DefaultConnectionProvider=class{#e;constructor(e){this.#e=e}async provideConnection(e,t){let n=await this.#e.acquireConnection(t);try{return await e(n)}finally{await this.#e.releaseConnection(n,t)}}},Nu=class DefaultQueryExecutor extends QueryExecutorBase{#e;#t;#n;constructor(e,t,n,r=[]){super(r),this.#e=e,this.#t=t,this.#n=n}get adapter(){return this.#t}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e,t){return this.#n.provideConnection(e,t)}withPlugins(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[...this.plugins,...e])}withPlugin(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[...this.plugins,e])}withPluginAtFront(e){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[e,...this.plugins])}withConnectionProvider(e){return new DefaultQueryExecutor(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new DefaultQueryExecutor(this.#e,this.#t,this.#n,[])}};function performanceNow(){return typeof performance<`u`&&isFunction(performance.now)?performance.now():Date.now()}var ConnectionMutex=class{#e;#t;async obtainLock(){for(;this.#e;)await this.#e;this.#e=new Promise(e=>{this.#t=e})}releaseLock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},RuntimeDriver=class{#e;#t;#n;#r;#i;#a=/* @__PURE__ */ new WeakSet;#o;constructor(e,t,n){this.#e=e,this.#r=!1,this.#t=n,t.supportsMultipleConnections===!1&&(this.#o=new ConnectionMutex)}async init(e){if(this.#i)throw Error(`driver has already been destroyed`);this.#n??=this.#e.init(e).then(()=>{this.#r=!0}).catch(e=>{throw this.#n=void 0,e}),await waitOrAbort(this.#n,e?.signal,`init`)}async acquireConnection(e){if(this.#i)throw Error(`driver has already been destroyed`);if(this.#r||await this.init(e),this.#o){let t=this.#o.obtainLock();await waitOrAbort(t,e?.signal,`acquireConnection:mutex`,()=>t.then(()=>this.#o?.releaseLock()))}let t=this.#e.acquireConnection(e),n=await waitOrAbort(t,e?.signal,`acquireConnection:acquire`,()=>t?.then(e=>this.releaseConnection(e).catch(printBackgroundFail(`driver.releaseConnection`))).catch(printBackgroundFail(`driver.acquireConnection`)));return this.#a.has(n)||(this.#s()&&this.#c(n),this.#a.add(n)),n}async releaseConnection(e,t){await this.#e.releaseConnection(e,t),this.#o?.releaseLock()}async beginTransaction(e,t){return await this.#e.beginTransaction(e,t)}async commitTransaction(e){return await this.#e.commitTransaction(e)}async rollbackTransaction(e){return await this.#e.rollbackTransaction(e)}async savepoint(e,t,n){if(this.#e.savepoint)return await this.#e.savepoint(e,t,n);throw Error("The `savepoint` method is not supported by this driver")}async rollbackToSavepoint(e,t,n){if(this.#e.rollbackToSavepoint)return await this.#e.rollbackToSavepoint(e,t,n);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}async releaseSavepoint(e,t,n){if(this.#e.releaseSavepoint)return await this.#e.releaseSavepoint(e,t,n);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(e){this.#n&&(await waitOrAbort(this.#n,e?.signal,`destroy:initPromise`),this.#i??=this.#e.destroy(e).catch(e=>{throw this.#i=void 0,e}),await waitOrAbort(this.#i,e?.signal,`destroy`))}#s(){return this.#t.isLevelEnabled(`query`)||this.#t.isLevelEnabled(`error`)}#c(e){let t=e.executeQuery,n=e.streamQuery,r=this;e.executeQuery=async(n,i)=>{let a,o=performanceNow();try{return await t.call(e,n,i)}catch(e){throw a=e,await r.#l(e,n,o),e}finally{a||await r.#u(n,o)}},e.streamQuery=async function*(t,i,a){let o,s=performanceNow();try{for await(let r of n.call(e,t,i,a))yield r}catch(e){throw o=e,await r.#l(e,t,s),e}finally{o||await r.#u(t,s,!0)}}}async#l(e,t,n){await this.#t.error(()=>({level:`error`,error:e,query:t,queryDurationMillis:this.#d(n)}))}async#u(e,t,n=!1){await this.#t.query(()=>({level:`query`,isStream:n,query:e,queryDurationMillis:this.#d(t)}))}#d(e){return performanceNow()-e}};const ignoreError=()=>{};var SingleConnectionProvider=class{#e;#t;constructor(e){this.#e=e}async provideConnection(e){for(;this.#t;)await this.#t.catch(ignoreError);return this.#t=this.#n(e).finally(()=>{this.#t=void 0}),this.#t}async#n(e){return await e(this.#e)}};const Pu=[`read only`,`read write`],Fu=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function validateTransactionSettings(e){if(e.accessMode&&!Pu.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!Fu.includes(e.isolationLevel))throw Error(`invalid transaction isolation level ${e.isolationLevel}`)}freeze([`query`,`error`]);var Log=class{#e;#t;constructor(e){isFunction(e)?(this.#t=e,this.#e=freeze({query:!0,error:!0})):(this.#t=defaultLogger,this.#e=freeze({query:e.includes(`query`),error:e.includes(`error`)}))}isLevelEnabled(e){return this.#e[e]}async query(e){this.#e.query&&await this.#t(e())}async error(e){this.#e.error&&await this.#t(e())}};function defaultLogger(e){if(e.level===`query`){let t=`kysely:query:${e.isStream?`stream:`:``}`;console.log(`${t} ${e.query.sql}`),console.log(`${t} duration: ${e.queryDurationMillis.toFixed(1)}ms`)}else e.level===`error`&&(e.error instanceof Error?console.error(`kysely:error: ${e.error.stack??e.error.message}`):console.error(`kysely:error: ${JSON.stringify({error:e.error,query:e.query.sql,queryDurationMillis:e.queryDurationMillis})}`))}function isCompilable(e){return isObject(e)&&isFunction(e.compile)}Symbol.asyncDispose??=Symbol(`Symbol.asyncDispose`);var Iu=class Kysely extends bl{#e;constructor(e){let t,n;if(isKyselyProps(e))t={executor:e.executor},n={...e};else{let r=e.dialect,i=r.createDriver(),a=r.createQueryCompiler(),o=r.createAdapter(),s=new RuntimeDriver(i,o,new Log(e.log??[])),c=new Nu(a,o,new DefaultConnectionProvider(s),e.plugins??[]);t={executor:c},n={config:e,executor:c,dialect:r,driver:s}}super(t),this.#e=freeze(n)}get schema(){return new Mu(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:Y.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new Ru({...this.#e})}startTransaction(){return new zu({...this.#e})}connection(){return new ConnectionBuilder({...this.#e})}withPlugin(e){return new Kysely({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Kysely({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Kysely({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}$extendTables(){return new Kysely({...this.#e})}$omitTables(){return new Kysely({...this.#e})}$pickTables(){return new Kysely({...this.#e})}withTables(){return this.$extendTables()}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}async executeQuery(e,t){let n=isCompilable(e)?e.compile():e;return await this.#e.executor.executeQuery(n,t)}async[Symbol.asyncDispose](){await this.destroy()}},Lu=class Transaction extends Iu{#e;constructor(e){super(e),this.#e=e}get isTransaction(){return!0}transaction(){throw Error(`calling the transaction method for a Transaction is not supported`)}startTransaction(){throw Error(`calling the controlled transaction method for a Transaction is not supported`)}connection(){throw Error(`calling the connection method for a Transaction is not supported`)}destroy(){throw Error(`calling the destroy method for a Transaction is not supported`)}withPlugin(e){return new Transaction({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new Transaction({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new Transaction({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new Transaction({...this.#e})}$extendTables(){return new Transaction({...this.#e})}$omitTables(){return new Transaction({...this.#e})}$pickTables(){return new Transaction({...this.#e})}};function isKyselyProps(e){return isObject(e)&&isObject(e.config)&&isObject(e.driver)&&isObject(e.executor)&&isObject(e.dialect)}var ConnectionBuilder=class{#e;constructor(e){this.#e=freeze(e)}async execute(e,t){return this.#e.executor.provideConnection(async t=>{let n=this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t));return await e(new Iu({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},Ru=class TransactionBuilder{#e;constructor(e){this.#e=freeze(e)}setAccessMode(e){return new TransactionBuilder({...this.#e,accessMode:e})}setIsolationLevel(e){return new TransactionBuilder({...this.#e,isolationLevel:e})}async execute(e){let{isolationLevel:t,accessMode:n,...r}=this.#e,i={isolationLevel:t,accessMode:n};return validateTransactionSettings(i),this.#e.executor.provideConnection(async t=>{let n={isCommitted:!1,isRolledBack:!1},a=new Vu(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),o=new Lu({...r,executor:a}),s=!1;try{await this.#e.driver.beginTransaction(t,i),s=!0;let r=await e(o);return await this.#e.driver.commitTransaction(t),n.isCommitted=!0,r}catch(e){throw s&&(await this.#e.driver.rollbackTransaction(t),n.isRolledBack=!0),e}})}},zu=class ControlledTransactionBuilder{#e;constructor(e){this.#e=freeze(e)}setAccessMode(e){return new ControlledTransactionBuilder({...this.#e,accessMode:e})}setIsolationLevel(e){return new ControlledTransactionBuilder({...this.#e,isolationLevel:e})}async execute(){let{isolationLevel:e,accessMode:t,...n}=this.#e,r={isolationLevel:e,accessMode:t};validateTransactionSettings(r);let i=await provideControlledConnection(this.#e.executor);try{await this.#e.driver.beginTransaction(i.connection,r)}catch(e){throw i.release(),e}return new Bu({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},Bu=class ControlledTransaction extends Lu{#e;#t;constructor(e){e={...e,executor:new Vu(e.executor,e.state)};let{connection:t,state:n,...r}=e;super(r),this.#e=freeze(e);let i=createQueryId();this.#t=t=>e.executor.compileQuery(t,i)}get isCommitted(){return this.#e.state.isCommitted}get isRolledBack(){return this.#e.state.isRolledBack}commit(){return new Command(async()=>{await this.#e.executor.provideConnection(async e=>{await this.#e.driver.commitTransaction(e),this.#e.state.isCommitted=!0,this.#e.connection.release()})})}rollback(){return new Command(async()=>{await this.#e.executor.provideConnection(async e=>{try{await this.#e.driver.rollbackTransaction(e)}finally{this.#e.state.isRolledBack=!0,this.#e.connection.release()}})})}savepoint(e){return new Command(async()=>(await this.#e.executor.provideConnection(async t=>{await this.#e.driver.savepoint?.(t,e,this.#t)}),new ControlledTransaction({...this.#e})))}rollbackToSavepoint(e){return new Command(async()=>(await this.#e.executor.provideConnection(async t=>{await this.#e.driver.rollbackToSavepoint?.(t,e,this.#t)}),new ControlledTransaction({...this.#e})))}releaseSavepoint(e){return new Command(async()=>(await this.#e.executor.provideConnection(async t=>{await this.#e.driver.releaseSavepoint?.(t,e,this.#t)}),new ControlledTransaction({...this.#e})))}withPlugin(e){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new ControlledTransaction({...this.#e,executor:this.#e.executor.withPluginAtFront(new WithSchemaPlugin(e))})}withTables(){return new ControlledTransaction({...this.#e})}$extendTables(){return new ControlledTransaction({...this.#e})}$omitTables(){return new ControlledTransaction({...this.#e})}$pickTables(){return new ControlledTransaction({...this.#e})}},Command=class{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}};function assertNotCommittedOrRolledBack(e){if(e.isCommitted)throw Error(`Transaction is already committed`);if(e.isRolledBack)throw Error(`Transaction is already rolled back`)}var Vu=class NotCommittedOrRolledBackAssertingExecutor{#e;#t;constructor(e,t){this.#e=e instanceof NotCommittedOrRolledBackAssertingExecutor?e.#e:e,this.#t=t}get adapter(){return this.#e.adapter}get plugins(){return this.#e.plugins}transformQuery(e,t){return this.#e.transformQuery(e,t)}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e,t){return assertNotCommittedOrRolledBack(this.#t),this.#e.provideConnection(async t=>(assertNotCommittedOrRolledBack(this.#t),await e(t)),t)}executeQuery(e,t){return assertNotCommittedOrRolledBack(this.#t),this.#e.withConnectionProvider(this).executeQuery(e,t)}stream(e,t,n){return assertNotCommittedOrRolledBack(this.#t),this.#e.withConnectionProvider(this).stream(e,t,n)}withConnectionProvider(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withConnectionProvider(e),this.#t)}withPlugin(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPlugin(e),this.#t)}withPlugins(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPlugins(e),this.#t)}withPluginAtFront(e){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withPluginAtFront(e),this.#t)}withoutPlugins(){return new NotCommittedOrRolledBackAssertingExecutor(this.#e.withoutPlugins(),this.#t)}},Hu=class RawBuilderImpl{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isRawBuilder(){return!0}as(e){return new AliasedRawBuilderImpl(this,e)}$castTo(){return new RawBuilderImpl({...this.#e})}$notNull(){return new RawBuilderImpl(this.#e)}withPlugin(e){return new RawBuilderImpl({...this.#e,plugins:this.#e.plugins===void 0?freeze([e]):freeze([...this.#e.plugins,e])})}toOperationNode(){return this.#n(this.#t())}compile(e){return this.#r(this.#t(e))}async execute(e,t){let n=this.#t(e);return n.executeQuery(this.#r(n),t)}#t(e){let t=e===void 0?_l:e.getExecutor();return this.#e.plugins===void 0?t:t.withPlugins(this.#e.plugins)}#n(e){return e.transformQuery(this.#e.rawNode,this.#e.queryId)}#r(e){return e.compileQuery(this.#n(e),this.#e.queryId)}};function createRawBuilder(e){return new Hu(e)}var AliasedRawBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get rawBuilder(){return this.#e}toOperationNode(){return ac.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():M.create(this.#t))}};const Z=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:I.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:I.create(t,e.map(M.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChild(L.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithSql(e)})},join(e,t=Z`, `){let n=Array(Math.max(2*e.length-1,0)),r=t.toOperationNode();for(let t=0;t<e.length;++t)n[2*t]=parseParameter(e[t]),t!==e.length-1&&(n[2*t+1]=r);return createRawBuilder({queryId:createQueryId(),rawNode:I.createWithChildren(n)})}});function parseParameter(e){return isOperationNodeSource(e)?e.toOperationNode():parseValueExpression(e)}var OperationNodeVisitor=class{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#e=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=e=>{this.nodeStack.push(e),this.#e[e.kind](e),this.nodeStack.pop()}};const Uu=/'/g,Wu=/['"]/g;var DefaultQueryCompiler=class extends OperationNodeVisitor{#e=``;#t=[];get numParameters(){return this.#t.length}compileQuery(e,t){return this.#e=``,this.#t=[],this.nodeStack.splice(0,this.nodeStack.length),this.visitNode(e),freeze({query:e,queryId:t,sql:this.getSql(),parameters:[...this.#t]})}getSql(){return this.#e}visitSelectQuery(e){let t=this.parentNode!==void 0&&!Nc.is(this.parentNode)&&!R.is(this.parentNode)&&!N.is(this.parentNode)&&!vu.is(this.parentNode)&&!Cl.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`select`),e.distinctOn&&(this.append(` `),this.compileDistinctOn(e.distinctOn)),e.frontModifiers?.length&&(this.append(` `),this.compileList(e.frontModifiers,` `)),e.top&&(this.append(` `),this.visitNode(e.top)),e.selections&&(this.append(` `),this.compileList(e.selections)),e.from&&(this.append(` `),this.visitNode(e.from)),e.joins&&(this.append(` `),this.compileList(e.joins,` `)),e.where&&(this.append(` `),this.visitNode(e.where)),e.groupBy&&(this.append(` `),this.visitNode(e.groupBy)),e.having&&(this.append(` `),this.visitNode(e.having)),e.setOperations&&(this.append(` `),this.compileList(e.setOperations,` `)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),e.offset&&(this.append(` `),this.visitNode(e.offset)),e.fetch&&(this.append(` `),this.visitNode(e.fetch)),e.endModifiers?.length&&(this.append(` `),this.compileList(this.sortSelectModifiers(e.endModifiers),` `)),t&&this.append(`)`)}visitFrom(e){this.append(`from `),this.compileList(e.froms)}visitSelection(e){this.visitNode(e.selection)}visitColumn(e){this.visitNode(e.column)}compileDistinctOn(e){this.append(`distinct on (`),this.compileList(e),this.append(`)`)}compileList(e,t=`, `){let n=e.length-1;for(let r=0;r<=n;r++)this.visitNode(e[r]),r<n&&this.append(t)}visitWhere(e){this.append(`where `),this.visitNode(e.where)}visitHaving(e){this.append(`having `),this.visitNode(e.having)}visitInsertQuery(e){let t=this.parentNode!==void 0&&!Nc.is(this.parentNode)&&!I.is(this.parentNode)&&!Kc.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(e.replace?`replace`:`insert`),e.orAction&&(this.append(` `),this.visitNode(e.orAction)),e.top&&(this.append(` `),this.visitNode(e.top)),e.into&&(this.append(` into `),this.visitNode(e.into)),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.output&&(this.append(` `),this.visitNode(e.output)),e.values&&(this.append(` `),this.visitNode(e.values)),e.defaultValues&&(this.append(` `),this.append(`default values`)),e.onConflict&&(this.append(` `),this.visitNode(e.onConflict)),e.onDuplicateKey&&(this.append(` `),this.visitNode(e.onDuplicateKey)),e.returning&&(this.append(` `),this.visitNode(e.returning)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitValues(e){this.append(`values `),this.compileList(e.values)}visitDeleteQuery(e){let t=this.parentNode!==void 0&&!Nc.is(this.parentNode)&&!I.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`delete `),e.top&&(this.visitNode(e.top),this.append(` `)),this.visitNode(e.from),e.output&&(this.append(` `),this.visitNode(e.output)),e.using&&(this.append(` `),this.visitNode(e.using)),e.joins&&(this.append(` `),this.compileList(e.joins,` `)),e.where&&(this.append(` `),this.visitNode(e.where)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitReturning(e){this.append(`returning `),this.compileList(e.selections)}visitAlias(e){this.visitNode(e.node),this.append(` as `),this.visitNode(e.alias)}visitReference(e){e.table&&(this.visitNode(e.table),this.append(`.`)),this.visitNode(e.column)}visitSelectAll(e){this.append(`*`)}visitIdentifier(e){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(e),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(e){if(!isString(e.name))throw Error(`a non-string identifier was passed to compileUnwrappedIdentifier.`);this.append(this.sanitizeIdentifier(e.name))}visitAnd(e){this.visitNode(e.left),this.append(` and `),this.visitNode(e.right)}visitOr(e){this.visitNode(e.left),this.append(` or `),this.visitNode(e.right)}visitValue(e){e.immediate?this.appendImmediateValue(e.value):this.appendValue(e.value)}visitValueList(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitTuple(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitPrimitiveValueList(e){this.append(`(`);let{values:t}=e;for(let e=0;e<t.length;++e)this.appendValue(t[e]),e!==t.length-1&&this.append(`, `);this.append(`)`)}visitParens(e){this.append(`(`),this.visitNode(e.node),this.append(`)`)}visitJoin(e){this.append(qu[e.joinType]),this.append(` `),this.visitNode(e.table),e.on&&(this.append(` `),this.visitNode(e.on))}visitOn(e){this.append(`on `),this.visitNode(e.on)}visitRaw(e){let{sqlFragments:t,parameters:n}=e;for(let e=0;e<t.length;++e)this.append(t[e]),n.length>e&&this.visitNode(n[e])}visitOperator(e){this.append(e.operator)}visitTable(e){this.visitNode(e.table)}visitSchemableIdentifier(e){e.schema&&(this.visitNode(e.schema),this.append(`.`)),this.visitNode(e.identifier)}visitCreateTable(e){this.append(`create `),e.frontModifiers?.length&&(this.compileList(e.frontModifiers,` `),this.append(` `)),e.temporary&&this.append(`temporary `),this.append(`table `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.table),e.selectQuery||(this.append(` (`),this.compileList([...e.columns,...e.constraints??[],...e.indexes??[]]),this.append(`)`)),e.onCommit&&(this.append(` on commit `),this.append(e.onCommit)),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `)),e.selectQuery&&(this.append(` as `),this.visitNode(e.selectQuery))}visitColumnDefinition(e){e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.column),this.append(` `),this.visitNode(e.dataType),e.unsigned&&this.append(` unsigned`),e.frontModifiers&&e.frontModifiers.length>0&&(this.append(` `),this.compileList(e.frontModifiers,` `)),e.generated&&(this.append(` `),this.visitNode(e.generated)),e.identity&&this.append(` identity`),e.defaultTo&&(this.append(` `),this.visitNode(e.defaultTo)),e.notNull&&this.append(` not null`),e.unique&&this.append(` unique`),e.nullsNotDistinct&&this.append(` nulls not distinct`),e.primaryKey&&this.append(` primary key`),e.autoIncrement&&(this.append(` `),this.append(this.getAutoIncrement())),e.references&&(this.append(` `),this.visitNode(e.references)),e.check&&(this.append(` `),this.visitNode(e.check)),e.endModifiers&&e.endModifiers.length>0&&(this.append(` `),this.compileList(e.endModifiers,` `))}getAutoIncrement(){return`auto_increment`}visitReferences(e){this.append(`references `),this.visitNode(e.table),this.append(` (`),this.compileList(e.columns),this.append(`)`),e.onDelete&&(this.append(` on delete `),this.append(e.onDelete)),e.onUpdate&&(this.append(` on update `),this.append(e.onUpdate))}visitDropTable(e){this.append(`drop `),e.temporary&&this.append(`temporary `),this.append(`table `),e.ifExists&&this.append(`if exists `),this.visitNode(e.table),e.cascade&&this.append(` cascade`)}visitDataType(e){this.append(e.dataType)}visitOrderBy(e){this.append(`order by `),this.compileList(e.items)}visitOrderByItem(e){this.visitNode(e.orderBy),e.collation&&(this.append(` `),this.visitNode(e.collation)),e.direction&&(this.append(` `),this.visitNode(e.direction)),e.nulls&&(this.append(` nulls `),this.append(e.nulls))}visitGroupBy(e){this.append(`group by `),this.compileList(e.items)}visitGroupByItem(e){this.visitNode(e.groupBy)}visitUpdateQuery(e){let t=this.parentNode!==void 0&&!Nc.is(this.parentNode)&&!I.is(this.parentNode)&&!Kc.is(this.parentNode);if(this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`update `),e.top&&(this.visitNode(e.top),this.append(` `)),e.table&&(this.visitNode(e.table),this.append(` `)),this.append(`set `),e.updates&&this.compileList(e.updates),e.output&&(this.append(` `),this.visitNode(e.output)),e.from&&(this.append(` `),this.visitNode(e.from)),e.joins){if(!e.from)throw 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(e.joins,` `)}e.where&&(this.append(` `),this.visitNode(e.where)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitColumnUpdate(e){this.visitNode(e.column),this.append(` = `),this.visitNode(e.value)}visitLimit(e){this.append(`limit `),this.visitNode(e.limit)}visitOffset(e){this.append(`offset `),this.visitNode(e.offset)}visitOnConflict(e){this.append(`on conflict`),e.columns?(this.append(` (`),this.compileList(e.columns),this.append(`)`)):e.constraint?(this.append(` on constraint `),this.visitNode(e.constraint)):e.indexExpression&&(this.append(` (`),this.visitNode(e.indexExpression),this.append(`)`)),e.indexWhere&&(this.append(` `),this.visitNode(e.indexWhere)),e.doNothing===!0?this.append(` do nothing`):e.updates&&(this.append(` do update set `),this.compileList(e.updates),e.updateWhere&&(this.append(` `),this.visitNode(e.updateWhere)))}visitOnDuplicateKey(e){this.append(`on duplicate key update `),this.compileList(e.updates)}visitCreateIndex(e){this.append(`create `),e.unique&&this.append(`unique `),this.append(`index `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.name),e.table&&(this.append(` on `),this.visitNode(e.table)),e.using&&(this.append(` using `),this.visitNode(e.using)),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.nullsNotDistinct&&this.append(` nulls not distinct`),e.where&&(this.append(` `),this.visitNode(e.where))}visitDropIndex(e){this.append(`drop index `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.table&&(this.append(` on `),this.visitNode(e.table)),e.cascade&&this.append(` cascade`)}visitCreateSchema(e){this.append(`create schema `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.schema)}visitDropSchema(e){this.append(`drop schema `),e.ifExists&&this.append(`if exists `),this.visitNode(e.schema),e.cascade&&this.append(` cascade`)}visitPrimaryKeyConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`primary key (`),this.compileList(e.columns),this.append(`)`),this.buildDeferrable(e)}buildDeferrable(e){e.deferrable!==void 0&&(e.deferrable?this.append(` deferrable`):this.append(` not deferrable`)),e.initiallyDeferred!==void 0&&(e.initiallyDeferred?this.append(` initially deferred`):this.append(` initially immediate`))}visitUniqueConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`unique`),e.nullsNotDistinct&&this.append(` nulls not distinct`),this.append(` (`),this.compileList(e.columns),this.append(`)`),this.buildDeferrable(e)}visitCheckConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`check (`),this.visitNode(e.expression),this.append(`)`)}visitForeignKeyConstraint(e){e.name&&(this.append(`constraint `),this.visitNode(e.name),this.append(` `)),this.append(`foreign key (`),this.compileList(e.columns),this.append(`) `),this.visitNode(e.references),e.onDelete&&(this.append(` on delete `),this.append(e.onDelete)),e.onUpdate&&(this.append(` on update `),this.append(e.onUpdate)),this.buildDeferrable(e)}visitList(e){this.compileList(e.items)}visitWith(e){this.append(`with `),e.recursive&&this.append(`recursive `),this.compileList(e.expressions)}visitCommonTableExpression(e){this.visitNode(e.name),this.append(` as `),isBoolean(e.materialized)&&(e.materialized||this.append(`not `),this.append(`materialized `)),this.visitNode(e.expression)}visitCommonTableExpressionName(e){this.visitNode(e.table),e.columns&&(this.append(`(`),this.compileList(e.columns),this.append(`)`))}visitAlterTable(e){this.append(`alter table `),this.visitNode(e.table),this.append(` `),e.renameTo&&(this.append(`rename to `),this.visitNode(e.renameTo)),e.setSchema&&(this.append(`set schema `),this.visitNode(e.setSchema)),e.addConstraint&&this.visitNode(e.addConstraint),e.dropConstraint&&this.visitNode(e.dropConstraint),e.renameConstraint&&this.visitNode(e.renameConstraint),e.columnAlterations&&this.compileColumnAlterations(e.columnAlterations),e.addIndex&&this.visitNode(e.addIndex),e.dropIndex&&this.visitNode(e.dropIndex)}visitAddColumn(e){this.append(`add column `),this.visitNode(e.column)}visitRenameColumn(e){this.append(`rename column `),this.visitNode(e.column),this.append(` to `),this.visitNode(e.renameTo)}visitDropColumn(e){this.append(`drop column `),e.ifExists&&this.append(`if exists `),this.visitNode(e.column)}visitAlterColumn(e){this.append(`alter column `),this.visitNode(e.column),this.append(` `),e.dataType&&(this.announcesNewColumnDataType()&&this.append(`type `),this.visitNode(e.dataType),e.dataTypeExpression&&(this.append(`using `),this.visitNode(e.dataTypeExpression))),e.setDefault&&(this.append(`set default `),this.visitNode(e.setDefault)),e.dropDefault&&this.append(`drop default`),e.setNotNull&&this.append(`set not null`),e.dropNotNull&&this.append(`drop not null`)}visitModifyColumn(e){this.append(`modify column `),this.visitNode(e.column)}visitAddConstraint(e){this.append(`add `),this.visitNode(e.constraint)}visitDropConstraint(e){this.append(`drop constraint `),e.ifExists&&this.append(`if exists `),this.visitNode(e.constraintName),e.modifier===`cascade`?this.append(` cascade`):e.modifier===`restrict`&&this.append(` restrict`)}visitRenameConstraint(e){this.append(`rename constraint `),this.visitNode(e.oldName),this.append(` to `),this.visitNode(e.newName)}visitSetOperation(e){this.append(e.operator),this.append(` `),e.all&&this.append(`all `),this.visitNode(e.expression)}visitCreateView(e){this.append(`create `),e.orReplace&&this.append(`or replace `),e.materialized&&this.append(`materialized `),e.temporary&&this.append(`temporary `),this.append(`view `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.name),this.append(` `),e.columns&&(this.append(`(`),this.compileList(e.columns),this.append(`) `)),e.as&&(this.append(`as `),this.visitNode(e.as))}visitRefreshMaterializedView(e){this.append(`refresh materialized view `),e.concurrently&&this.append(`concurrently `),this.visitNode(e.name),e.withNoData?this.append(` with no data`):this.append(` with data`)}visitDropView(e){this.append(`drop `),e.materialized&&this.append(`materialized `),this.append(`view `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.cascade&&this.append(` cascade`)}visitGenerated(e){this.append(`generated `),e.always&&this.append(`always `),e.byDefault&&this.append(`by default `),this.append(`as `),e.identity&&this.append(`identity`),e.expression&&(this.append(`(`),this.visitNode(e.expression),this.append(`)`)),e.stored&&this.append(` stored`)}visitDefaultValue(e){this.append(`default `),this.visitNode(e.defaultValue)}visitSelectModifier(e){e.rawModifier?this.visitNode(e.rawModifier):this.append(Gu[e.modifier]),e.of&&(this.append(` of `),this.compileList(e.of,`, `))}visitCreateType(e){this.append(`create type `),this.visitNode(e.name),e.enum&&(this.append(` as enum `),this.visitNode(e.enum))}visitDropType(e){this.append(`drop type `),e.ifExists&&this.append(`if exists `),this.visitNode(e.name),e.additionalNames?.length&&(this.append(`, `),this.compileList(e.additionalNames)),e.cascade&&this.append(` cascade`)}visitAlterType(e){this.append(`alter type `),this.visitNode(e.name),this.append(` `),e.addValue?this.visitNode(e.addValue):e.renameTo?(this.append(`rename to `),this.visitNode(e.renameTo)):e.renameValue?this.visitNode(e.renameValue):e.setSchema&&(this.append(`set schema `),this.visitNode(e.setSchema))}visitAddValue(e){this.append(`add value `),e.ifNotExists&&this.append(`if not exists `),this.visitNode(e.value),e.neighborValue&&(this.append(e.isBefore?` before `:` after `),this.visitNode(e.neighborValue))}visitRenameValue(e){this.append(`rename value `),this.visitNode(e.oldValue),this.append(` to `),this.visitNode(e.newValue)}visitExplain(e){this.append(`explain`),(e.options||e.format)&&(this.append(` `),this.append(this.getLeftExplainOptionsWrapper()),e.options&&(this.visitNode(e.options),e.format&&this.append(this.getExplainOptionsDelimiter())),e.format&&(this.append(`format`),this.append(this.getExplainOptionAssignment()),this.append(e.format)),this.append(this.getRightExplainOptionsWrapper()))}visitDefaultInsertValue(e){this.append(`default`)}visitAggregateFunction(e){this.append(e.func),this.append(`(`),e.distinct&&this.append(`distinct `),this.compileList(e.aggregated),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),this.append(`)`),e.withinGroup&&(this.append(` within group (`),this.visitNode(e.withinGroup),this.append(`)`)),e.filter&&(this.append(` filter(`),this.visitNode(e.filter),this.append(`)`)),e.over&&(this.append(` `),this.visitNode(e.over))}visitOver(e){this.append(`over(`),e.partitionBy&&(this.visitNode(e.partitionBy),e.orderBy&&this.append(` `)),e.orderBy&&this.visitNode(e.orderBy),this.append(`)`)}visitPartitionBy(e){this.append(`partition by `),this.compileList(e.items)}visitPartitionByItem(e){this.visitNode(e.partitionBy)}visitBinaryOperation(e){this.visitNode(e.leftOperand),this.append(` `),this.visitNode(e.operator),this.append(` `),this.visitNode(e.rightOperand)}visitUnaryOperation(e){this.visitNode(e.operator),this.isMinusOperator(e.operator)||this.append(` `),this.visitNode(e.operand)}isMinusOperator(e){return xc.is(e)&&e.operator===`-`}visitUsing(e){this.append(`using `),this.compileList(e.tables)}visitFunction(e){this.append(e.func),this.append(`(`),this.compileList(e.arguments),this.append(`)`)}visitCase(e){this.append(`case`),e.value&&(this.append(` `),this.visitNode(e.value)),e.when&&(this.append(` `),this.compileList(e.when,` `)),e.else&&(this.append(` else `),this.visitNode(e.else)),this.append(` end`),e.isStatement&&this.append(` case`)}visitWhen(e){this.append(`when `),this.visitNode(e.condition),e.result&&(this.append(` then `),this.visitNode(e.result))}visitJSONReference(e){this.visitNode(e.reference),this.visitNode(e.traversal)}visitJSONPath(e){e.inOperator&&this.visitNode(e.inOperator),this.append(`'$`);for(let t of e.pathLegs)this.visitNode(t);this.append(`'`)}visitJSONPathLeg(e){let t=e.type===`ArrayLocation`,n=String(e.value);t?(this.append(`[`),this.append(this.sanitizeStringLiteral(n)),this.append(`]`)):(this.append(`."`),this.append(this.sanitizeJSONPathMemberValue(n)),this.append(`"`))}visitJSONOperatorChain(e){for(let t=0,n=e.values.length;t<n;t++)t===n-1?this.visitNode(e.operator):this.append(`->`),this.visitNode(e.values[t])}visitMergeQuery(e){e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`merge `),e.top&&(this.visitNode(e.top),this.append(` `)),this.append(`into `),this.visitNode(e.into),e.using&&(this.append(` `),this.visitNode(e.using)),e.whens&&(this.append(` `),this.compileList(e.whens,` `)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.output&&(this.append(` `),this.visitNode(e.output)),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitMatched(e){e.not&&this.append(`not `),this.append(`matched`),e.bySource&&this.append(` by source`)}visitAddIndex(e){this.parentNode&&N.is(this.parentNode)||this.append(`add `),e.unique&&this.append(`unique `),this.append(`index `),this.visitNode(e.name),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.using&&(this.append(` using `),this.visitNode(e.using))}visitCast(e){this.append(`cast(`),this.visitNode(e.expression),this.append(` as `),this.visitNode(e.dataType),this.append(`)`)}visitFetch(e){this.append(`fetch next `),this.visitNode(e.rowCount),this.append(` rows ${e.modifier}`)}visitOutput(e){this.append(`output `),this.compileList(e.selections)}visitTop(e){this.append(`top(${e.expression})`),e.modifiers&&this.append(` ${e.modifiers}`)}visitOrAction(e){this.append(e.action)}visitCollate(e){this.append(`collate `),this.visitNode(e.collation)}append(e){this.#e+=e}appendValue(e){this.addParameter(e),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getCurrentParameterPlaceholder(){return`$`+this.numParameters}getLeftExplainOptionsWrapper(){return`(`}getExplainOptionAssignment(){return` `}getExplainOptionsDelimiter(){return`, `}getRightExplainOptionsWrapper(){return`)`}sanitizeIdentifier(e){let t=this.getLeftIdentifierWrapper(),n=this.getRightIdentifierWrapper(),r=``;for(let i of e)r+=i,i===t?r+=t:i===n&&(r+=n);return r}sanitizeStringLiteral(e){return e.replace(Uu,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(Wu,e=>e===`'`?`''`:`\\"`)}addParameter(e){this.#t.push(e)}appendImmediateValue(e){if(isString(e))this.appendStringLiteral(e);else if(isNumber(e)||isBoolean(e)||isBigInt(e))this.append(e.toString());else if(isNull(e))this.append(`null`);else if(isDate(e))this.appendImmediateValue(e.toISOString());else throw Error(`invalid immediate value ${e}`)}appendStringLiteral(e){this.append(`'`),this.append(this.sanitizeStringLiteral(e)),this.append(`'`)}sortSelectModifiers(e){return freeze(e.toSorted((e,t)=>e.modifier&&t.modifier?Ku[e.modifier]-Ku[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const Gu=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),Ku=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),qu=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`}),Ju=freeze({raw(e,t=[]){return freeze({sql:e,query:I.createWithSql(e),parameters:freeze(t),queryId:createQueryId()})}});var DialectAdapterBase=class{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}};function parseSavepointCommand(e,t){return I.createWithChildren([I.createWithSql(`${e} `),M.create(t)])}var SqliteDriver=class{#e;#t;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#t=isFunction(this.#e.database)?await this.#e.database(e):this.#e.database,this.#n=new SqliteConnection(this.#t),this.#e.onCreateConnection&&await this.#e.onCreateConnection(this.#n,e)}async acquireConnection(){return this.#n}async beginTransaction(e){await e.executeQuery(Ju.raw(`begin`))}async commitTransaction(e){await e.executeQuery(Ju.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Ju.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`savepoint`,t),createQueryId()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`rollback to`,t),createQueryId()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`release`,t),createQueryId()))}async releaseConnection(){}async destroy(){this.#t?.close()}},SqliteConnection=class{#e;constructor(e){this.#e=e}async executeQuery(e){let{sql:t,parameters:n}=e,r=this.#e.prepare(t);if(r.reader)return{rows:r.all(n)};let{changes:i,lastInsertRowid:a}=r.run(n);return{insertId:a==null?void 0:BigInt(a),numAffectedRows:i==null?void 0:BigInt(i),rows:[]}}async*streamQuery(e,t){let{sql:n,parameters:r,query:i}=e,a=this.#e.prepare(n);if(!H.is(i))throw Error(`Sqlite driver only supports streaming of select queries`);let o=a.iterate(r);for(let e of o)yield{rows:[e]}}};const Yu=/"/g,Xu=/[\\'"]/g;var SqliteQueryCompiler=class extends DefaultQueryCompiler{visitOrAction(e){this.append(`or `),this.append(e.action)}getCurrentParameterPlaceholder(){return`?`}getLeftExplainOptionsWrapper(){return``}getRightExplainOptionsWrapper(){return``}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getAutoIncrement(){return`autoincrement`}sanitizeIdentifier(e){return e.replace(Yu,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(Xu,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const Zu=`kysely_migration`,Qu=`kysely_migration_lock`;freeze({__noMigrations__:!0});var SqliteIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){return await this.#n(e)}#t(e,t){let n=e.selectFrom(`sqlite_master`).where(`type`,`in`,[`table`,`view`]).where(`name`,`not like`,`sqlite_%`).select([`name`,`sql`,`type`]).orderBy(`name`);return t.withInternalKyselyTables||(n=n.where(`name`,`!=`,Zu).where(`name`,`!=`,Qu)),n}async#n(e){let t=await this.#t(this.#e,e).execute(),n=await this.#e.with(`table_list`,t=>this.#t(t,e)).selectFrom([`table_list as tl`,Z`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(),r={};for(let e of n)r[e.table]??=[],r[e.table].push(e);return t.map(({name:e,sql:t,type:n})=>{let i=t?.split(/[\(\),]/)?.find(e=>e.toLowerCase().includes(`autoincrement`))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,``),a=r[e]??[];if(!i){let e=a.filter(e=>e.pk>0);e.length===1&&e[0].type.toLowerCase()===`integer`&&(i=e[0].name)}return{name:e,isView:n===`view`,isForeign:!1,columns:a.map(e=>({name:e.name,dataType:e.type,isNullable:!e.notnull,isAutoIncrementing:e.name===i,hasDefaultValue:e.dflt_value!=null,comment:void 0}))}})}},SqliteAdapter=class extends DialectAdapterBase{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}},SqliteDialect=class{#e;constructor(e){this.#e=freeze({...e})}createDriver(){return new SqliteDriver(this.#e)}createQueryCompiler(){return new SqliteQueryCompiler}createAdapter(){return new SqliteAdapter}createIntrospector(e){return new SqliteIntrospector(e)}};function extendStackTrace(e,t){if(isStackHolder(e)&&t.stack){let n=t.stack.split(`
`).slice(1).join(`
`);return e.stack+=`\n${n}`,e}return e}function isStackHolder(e){return isObject(e)&&isString(e.stack)}const $u=Symbol();var PostgresDriver=class{#e;#t=/* @__PURE__ */ new WeakMap;#n;constructor(e){this.#e=freeze({...e})}async init(e){this.#n=isFunction(this.#e.pool)?await this.#e.pool(e):this.#e.pool}async acquireConnection(e){let t=await this.#n.connect();if(!this.#n)throw t.release(),Error(`driver has already been destroyed`);let n=this.#t.get(t);return n||(n=new PostgresConnection(t,{controlClient:this.#e.controlClient||this.#n.Client,cursor:this.#e.cursor??null,poolOptions:this.#n.options}),this.#t.set(t,n),this.#e.onCreateConnection&&await this.#e.onCreateConnection(n,e)),this.#e.onReserveConnection&&await this.#e.onReserveConnection(n,e),n}async beginTransaction(e,t){let n=`begin`;(t.isolationLevel||t.accessMode)&&(n=`start transaction`,t.isolationLevel&&(n+=` isolation level ${t.isolationLevel}`),t.accessMode&&(n+=` ${t.accessMode}`)),await e.executeQuery(Ju.raw(n))}async commitTransaction(e){await e.executeQuery(Ju.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Ju.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`savepoint`,t),createQueryId()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`rollback to`,t),createQueryId()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`release`,t),createQueryId()))}async releaseConnection(e){e[$u]()}async destroy(){if(this.#n){let e=this.#n;this.#n=void 0,await e.end()}}},PostgresConnection=class{#e;#t;#n;#r;constructor(e,t){this.#e=e,this.#t=t}async cancelQuery(e){return await this.#i(`select pg_cancel_backend(${this.#r})`,e)}async collectSessionInfo(){if(this.#r)return;let{processID:e}=this.#e;if(e)this.#r=e;else{let{rows:[{pid:e}]}=await this.#e.query(`select pg_backend_pid() as pid`,[]);this.#r=Number(e)}}async executeQuery(e){try{this.#n=e.queryId;let{command:t,rowCount:n,rows:r}=await this.#e.query(e.sql,e.parameters);return{numAffectedRows:t===`INSERT`||t===`UPDATE`||t===`DELETE`||t===`MERGE`?BigInt(n):void 0,rows:r??[]}}catch(e){throw extendStackTrace(e,/* @__PURE__ */ Error())}finally{this.#n=void 0}}async killSession(e){return await this.#i(`select pg_terminate_backend(${this.#r})`,e)}async*streamQuery(e,t){if(!this.#t.cursor)throw Error("`cursor` is not present in your postgres dialect config. It's required to make streaming work in postgres.");this.#n=e.queryId;let n=this.#e.query(new this.#t.cursor(e.sql,e.parameters.slice()));try{for(;;){let e=await n.read(t);if(e.length===0)break;yield{rows:e}}}finally{await n.close(),this.#n=void 0}}[$u](){this.#e.release()}async#i(e,t){if(!this.#n)return;let{controlClient:n,poolOptions:r}=this.#t,i=this.#n;if(!n)return await t(async t=>{i.queryId===this.#n?.queryId&&await t.executeQuery(Ju.raw(e,[]))});let a=new n({...r,password:`password`in r?r.password:void 0});try{if(await a.connect(),i.queryId!==this.#n.queryId)return;await a.query(e,[])}finally{a.end()}}},PostgresIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom(`pg_catalog.pg_namespace`).select(`nspname`).$castTo().execute()).map(e=>({name:e.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom(`pg_catalog.pg_attribute as a`).innerJoin(`pg_catalog.pg_class as c`,`a.attrelid`,`c.oid`).innerJoin(`pg_catalog.pg_namespace as ns`,`c.relnamespace`,`ns.oid`).innerJoin(`pg_catalog.pg_type as typ`,`a.atttypid`,`typ.oid`).innerJoin(`pg_catalog.pg_namespace as dtns`,`typ.typnamespace`,`dtns.oid`).select([`a.attname as column`,`a.attnotnull as not_null`,`a.atthasdef as has_default`,`c.relname as table`,`c.relkind as table_type`,`ns.nspname as schema`,`typ.typname as type`,`dtns.nspname as type_schema`,Z`col_description(a.attrelid, a.attnum)`.as(`column_description`),Z`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(`auto_incrementing`)]).where(`c.relkind`,`in`,[`r`,`v`,`p`,`f`]).where(`ns.nspname`,`!~`,`^pg_`).where(`ns.nspname`,`!=`,`information_schema`).where(`ns.nspname`,`!=`,`crdb_internal`).where(Z`has_schema_privilege(ns.nspname, 'USAGE')`).where(`a.attnum`,`>=`,0).where(`a.attisdropped`,`!=`,!0).orderBy(`ns.nspname`).orderBy(`c.relname`).orderBy(`a.attnum`).$castTo();e.withInternalKyselyTables||(t=t.where(`c.relname`,`!=`,Zu).where(`c.relname`,`!=`,Qu));let n=await t.execute();return this.#t(n)}#t(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){let e=n.get(r.schema);e||(e=/* @__PURE__ */ new Map,n.set(r.schema,e));let i=e.get(r.table);i||(i=freeze({columns:[],isForeign:r.table_type===`f`,isView:r.table_type===`v`,name:r.table,schema:r.schema}),e.set(r.table,i),t.push(i)),i.columns.push(freeze({comment:r.column_description??void 0,dataType:r.type,dataTypeSchema:r.type_schema,hasDefaultValue:r.has_default,isAutoIncrementing:r.auto_incrementing!==null,isNullable:!r.not_null,name:r.column}))}return t}};const ed=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(ed,`""`)}};const td=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await Z`
    with set_timeout as (
      select set_config('lock_timeout', '${Z.lit(36e5)}', true) as config_val
    )
    select pg_advisory_lock(${Z.lit(td)})
    from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await Z`select pg_advisory_unlock(${Z.lit(td)})`.execute(e)}},PostgresDialect=class{#e;constructor(e){this.#e=e}createDriver(){return new PostgresDriver(this.#e)}createQueryCompiler(){return new PostgresQueryCompiler}createAdapter(){return new PostgresAdapter}createIntrospector(e){return new PostgresIntrospector(e)}};const templateFragments=(e,t)=>e,nd=templateFragments`(SELECT value FROM json_each(${0}))`,rd=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!I.is(e)||e.sqlFragments!==nd||e.parameters.length!==1)return;let t=e.parameters[0];for(;I.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!L.is(t)||t.immediate||typeof t.value!=`string`)return;let n;try{n=JSON.parse(t.value)}catch{return}if(Array.isArray(n)&&n.every(e=>typeof e==`string`))return`{${n.map(e=>`"${e.replace(/["\\]/g,`\\$&`)}"`).join(`,`)}}`}var OpenClawPostgresQueryCompiler=class extends PostgresQueryCompiler{visitBinaryOperation(e){if(xc.is(e.operator)&&e.operator.operator===`in`){let t=postgresStringArray(e.rightOperand);if(t!==void 0){this.visitNode(e.leftOperand),this.append(` = ANY(`),this.appendValue(t),this.append(`::text[])`);return}}super.visitBinaryOperation(e)}visitRaw(e){let t=e.sqlFragments===nd;!t&&e.sqlFragments!==rd?super.visitRaw(e):(this.append(t?`(SELECT value FROM json_array_elements_text(`:`(SELECT ordinality - 1 AS key, value FROM json_array_elements_text(`),this.compileList(e.parameters),this.append(t?`::json) AS value)`:`::json) WITH ORDINALITY AS entries(value, ordinality))`))}},OpenClawPostgresDialect=class extends PostgresDialect{createQueryCompiler(){return new OpenClawPostgresQueryCompiler}};const id=sr(process.versions.node),ad=!process.versions.bun&&(id?.major===24&&cr(id,{major:24,minor:20,patch:0})||cr(id,{major:26,minor:6,patch:0})),od=new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),sd=/* @__PURE__ */ new WeakMap,cd=new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});function getNodeSqliteKysely(e){if(y(e)){let t=sd.get(e);return t||(t=new Iu({dialect:cd}),sd.set(e,t)),t}let t=Bn.get(e);if(t)return t;let n=new Iu({dialect:od});return Bn.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{In.get(e)?.(t)}catch{}}function releaseSqliteIterator(e,t,n,r){let i;try{e.return?.()}catch(e){i=e}if(t.release(),!n&&i!==void 0)throw Ae(i,r)}function executeCompiledSqliteQuerySync(e,t,n=!1,r=t.parameters){if(y(e)){let i=e.query(t.sql,r),a=n?i.rows.slice(0,1):i.rows;return i.columns.length>0?{rows:a}:{rows:[],numAffectedRows:BigInt(i.rowCount)}}try{let i=t.sql;return zn(e),Rn(e,i,r,i=>{if(n&&H.is(t.query)){let e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(H.is(t.query)||i.columns().length>0){if(ad)return{rows:i.all(...r)};let t=i.iterate(...r),n=Sn(e,`kysely eager query`),a=!1,o,s=[];try{for(let e of t)n.progress(),s.push(e)}catch(e){a=!0,o=e}if(releaseSqliteIterator(t,n,a,`SQLite query cleanup failed`),a)throw Ae(o,`SQLite query failed`);return{rows:s}}i.setReadBigInts(!0);let a;try{a=i.run(...r)}finally{i.setReadBigInts(!1)}let{changes:o,lastInsertRowid:s}=a,c={numAffectedRows:BigInt(o),rows:[]};return R.is(t.query)&&o>0?{...c,insertId:BigInt(s)}:c})}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}}function executeSqliteQuerySync(e,t){return executeCompiledSqliteQuerySync(e,t.compile())}function createSqliteQueryCache(e){let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);return r===void 0&&(r=e(n),t.set(n,r)),r}}function compileSqliteQueryBindings(e){let t=/* @__PURE__ */ new Map,n=e(e=>{let n=Symbol(`sqlite-query-parameter`);return t.set(n,e),Z`${n}`}).compile(),r=n.parameters.map(e=>t.get(e)??(()=>e));return{compiled:n,bind:e=>r.map(t=>t(e))}}function prepareSqliteQuerySync(e,t){let{compiled:n,bind:r}=compileSqliteQueryBindings(t);return t=>executeCompiledSqliteQuerySync(e,n,!1,r(t))}function iterateSqliteQuerySync(e,t){if(y(e))return(function*(){yield*executeCompiledSqliteQuerySync(e,t.compile()).rows})();let n=wn();return(function*(){let r=t.compile(),i;try{if(i=e.prepare(r.sql),!H.is(r.query)&&i.columns().length===0)return;let t=r.parameters,a=i.iterate(...t),o=Sn(e,`kysely iterator`,n),s=!1;try{for(let e of a)o.progress(),yield e}catch(e){throw s=!0,Ae(e,`SQLite iterator failed`)}finally{releaseSqliteIterator(a,o,s,`SQLite iterator cleanup failed`)}}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}finally{i&&Fn(i)}})()}function executeSqliteQueryTakeFirstSync(e,t){return executeCompiledSqliteQuerySync(e,t.compile(),!0).rows[0]}function classifyGatewayLockProcessNamespace(e,t,n){if(e&&n&&isLegacyGatewayLeaseLock(e)){let t=Date.now(),r=Date.parse(e.createdAt);if(!Number.isFinite(r)||t-r<=3e5)return`unknown`;try{let r=ir(rr(n),{readOnly:!0});try{let n=getNodeSqliteKysely(r),{rows:i}=executeSqliteQuerySync(r,{compile:()=>Z`SELECT expires_at AS expiresAt
              FROM ${Z`state_leases NOT INDEXED`}
              WHERE scope = ${`gateway-owner`} AND owner = ${e.ownerId}`.compile(n)});return i.every(e=>typeof e.expiresAt==`number`&&e.expiresAt<=t)?`dead`:`unknown`}finally{r.close()}}catch{return`unknown`}}if((process.platform===`win32`||process.platform===`darwin`)&&e&&e.processNamespace===void 0&&t){try{if(Date.now()-b.statSync(t).mtimeMs>9e4&&isLockOwnerDefinitelyStale({payload:{pid:e.pid,starttime:e.startTime}}))return`dead`}catch{}return`unknown`}return classifyGatewayOwnerProcessNamespace(e?.processNamespace,{machineIdentity:e?.machineIdentity,readGatewayHeartbeat:t?()=>readLockHeartbeat(t):void 0})}function finiteNonNegativeNumber(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=x.resolve(e);for(;;)try{return b.statSync(t).isDirectory()?t:x.dirname(t)}catch{let e=x.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){let t=findExistingDiskSpacePath(e);if(!t)return null;try{let n=b.statfsSync(t),r=finiteNonNegativeNumber(n.bsize),i=finiteNonNegativeNumber(n.bavail);if(r===null||i===null)return null;let a=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:r*i,totalBytes:a===null?null:r*a}}catch{return null}}function formatDiskSpaceBytes(e){let t=e/1048576,n=Math.max(0,Math.round(t));if(n<1024)return`${n} MiB`;let r=t/1024;return`${r.toFixed(+(r<10))} GiB`}const ld=new Tr;function comparableStateOwnerStaleReason(e,t){return t===`dead`?`owner-process-exited`:t===`same`?inspectStaleLockOwner({payload:{pid:e.pid,starttime:e.startTime}})?.reason:void 0}function isGatewayStateOwnerDefinitelyStale(e,t,n){let r=We(e)?e:null;if(!r)return!1;let i=classifyGatewayLockProcessNamespace(r,t,n);if(i===`unknown`)throw new GatewayLockNamespaceError(r,t);return comparableStateOwnerStaleReason(r,i)!==void 0}function assertPersistedStateDatabaseAccessAllowed(e){let{databasePath:t,ownerPath:n,assertMaintenance:r}=e,i=`OpenClaw state ownership at ${t} could not be verified from ${n}; restart the Gateway.`,a;try{a=b.readFileSync(n,`utf8`)}catch(e){if(je(e)===`ENOENT`)return;throw new vt(i,{cause:e})}let o=ld.getStore();if(o?.deadOwner?.path===n&&o.deadOwner.raw===a)return;let s=parseGatewayLockPayload(a);if(!s)throw new gt(t,i);if(!Number.isSafeInteger(s.pid)||s.pid<=0)throw new vt(i);let c=classifyGatewayLockProcessNamespace(s,n,t),l=comparableStateOwnerStaleReason(s,c);if(l){o&&l===`owner-process-exited`&&(o.deadOwner={path:n,raw:a});return}if(c===`same`&&s.pid===process.pid&&!xr)return;if(c===`same`&&!Dn(s.pid))throw new gt(t,i);let u=s.role??`gateway`;if(u===`gateway`||u===`agent-embedded`)return;if(c===`same`&&s.pid===process.pid){r();return}let d=`OpenClaw state at ${t} is undergoing offline maintenance by ${u} process ${s.pid}, started ${s.createdAt}; retry when it finishes. For update progress, run \`openclaw update status --json\`. ${describeGatewayLockHolder(s,n,c===`same`?`live`:`unknown`)}`;throw s.stateOwnerKind===`schema`&&s.role===`sqlite-maintenance`?new gt(t,d):new pt(t,d)}function defaultPayload(e){let t=ve(e),n=kn(process.pid),r=Ze(),i=r===void 0?null:kn(r);return{pid:process.pid,ownerId:Ar(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:x.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?Kt():void 0,...r===void 0?{}:{parentPid:r},...i===null?{}:{parentStartTime:i},...n===null?{}:{startTime:n}}}function assertGatewayRestorationPriority(e,t,n){if(n.role===`gateway`)return;let r;try{r=b.readFileSync(t,`utf8`)}catch(e){if(je(e)===`ENOENT`)return;throw e}let i=parseGatewayLockPayload(r);if(!(isGatewayStateOwnerDefinitelyStale(i)||i?.pid===n.pid)&&!(n.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&Pn(process.argv,{command:`gateway`}).kind===`openclaw`))throw new gt(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,t,n,r=0,i){let a=performance.now()+r,o=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,o,n),ensureOwnerDirectory(x.dirname(t),i);let s={holder:null},stale=({payload:n})=>(s.holder=Gs.safeParse(n).data??null,isGatewayStateOwnerDefinitelyStale(s.holder,t,e));if(r>0)try{let n=s.holder=parseGatewayLockPayload(b.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t,e)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&Dn(n.pid)))throw new ft(e)}catch(e){if(je(e)!==`ENOENT`)throw e}for(let c=!1;;)try{return Mr(t,{lockPath:t,retry:r>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:!1}:{retries:0},timeoutMs:Math.max(0,Math.ceil(a-performance.now())),staleMs:1/0,staleRecovery:`remove-if-unchanged`,reentrantOwner:n.ownerId,payload:()=>(assertGatewayRestorationPriority(e,o,n),n),shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(n){let r=je(n);if(r===`ENOENT`&&!c){c=!0,ensureOwnerDirectory(x.dirname(t),i);continue}if(r===`file_lock_timeout`||r===`file_lock_stale`){let{holder:r}=s,i=describeGatewayLockHolder(r??{},t,r&&Dn(r.pid)?`live`:`unknown`);throw new ft(e,n,i,r?{pid:r.pid,role:r.role}:void 0)}throw n}}const ud=n(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new Tr);function getStateDatabaseSchemaLease(e){let t=ud.getStore()?.get(resolveStateOwnerIdentity(e).key);if(t&&!t.active)throw Error(`State schema maintenance scope is no longer current`);return t?.lease.assertCurrent(),t?.lease}function withStateDatabaseColdAdmission(e,t){let{remainingBusyTimeoutMs:n,retryDelay:r}=createColdAdmissionBudget(e),i=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));for(;;)try{return assertStateDatabaseAccessAllowed(e.databasePath),t(n)}catch(e){Atomics.wait(i,0,0,r(e))}}function resolveGatewayStateOwnerPath(e){return resolveStateOwnerIdentity(e).ownerPath}function leaseForFile(e,t,n,r){let i=!1,holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent(),k.clear();let t=new Map(ud.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,k.clear()};try{let n=ud.run(t,e);return Ct(n)?Promise.resolve(n).finally(leave):(leave(),n)}catch(e){throw leave(),e}}let a={path:e,assertCurrent(){if(i||!holdsPhysicalLease())throw Error(`OpenClaw state ownership is no longer current`)},assertDatabaseAccess(e){if(i||A.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw Error(`OpenClaw state maintenance does not own this database`)},run,release(){k.clear(),i||(r?.release(),t.release(),i=!0,n.locks.delete(t),r&&n.locks.delete(r),n.locks.size===0&&A.get(n.key)===n&&(n.heartbeat?.stop(),n.accepting=!1,A.delete(n.key),n.onReleased?.())),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){k.clear();let n=resolveStateOwnerIdentity(e),r=A.get(n.key),i=r?.path??n.ownerPath;if(r&&(!r.accepting||!hasPhysicalOwnership(r)))throw new ft(e,r.lost.signal.reason);r&&assertStateDatabaseAccessAllowed(e);let a=r?.payload??{...defaultPayload(e),stateOwnerKind:`schema`},o,s=[];try{o=acquireGatewayStateOwnerFile(e,i,a,r?0:t.busyTimeoutMs??5e3,s)}catch(t){if(t instanceof ft)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof gt)throw e}throw t}let c=r?.projectionPath??x.join(Le(ve(Ne(e))),`gateway.state.lock`),l;try{l=r?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,c,{...a,role:a.role===`gateway`?`gateway`:`agent-embedded`},0,s)}catch(e){return Bt({release(){o.release(),removeCreatedProjectionDirectories(s)}},`state schema projection admission`,()=>{throw e})}r?(r.locks.add(o),r.locks.add(l),r.projectionDirectories.push(...s)):(r={key:n.key,path:i,kind:`schema`,payload:a,projectionPath:c,locks:/* @__PURE__ */ new Set([o,l]),projectionDirectories:s,lost:new AbortController,accepting:!0},A.set(r.key,r));let u=leaseForFile(i,o,r,l);try{let e=r.heartbeat??=startGatewayStateOwnerHeartbeat(r.locks,(e,t)=>observeOwnerLoss(r,e,t));return u.assertCurrent(),e.register(l),u}catch(e){return Bt(u,`state schema ownership verification`,()=>{throw e})}}function prepareStateDatabaseReadAccess(e){return captureAdmittedGatewayStateOwner(e,!1)}async function captureAdmittedGatewayStateOwner(e,t){e.assertCurrent();let n=e.identity.canonicalPath,r=process.platform===`win32`?Fe(n):n,i=A.get(r);if(!i||i.kind!==`process`)return;let a={canonicalPath:n,key:r,ownerPath:i.path},assertRegistered=()=>{if(e.assertCurrent(),i.lost.signal.throwIfAborted(),A.get(r)!==i)throw dt()},assertCurrent=()=>{if(assertRegistered(),!i.accepting)throw dt();assertStateDatabaseAccessAtOwnerPath(n,a,void 0)},o=createStateDatabaseAccess(a,i),assertReadAllowed=e=>{assertRegistered(),o.assertReadAllowed(e)},s=x.resolve(e.databasePath),c=t?assertCurrent:assertRegistered;if(c(),t||k.get(s)!==i){let t=await Pe(s);if(c(),(process.platform===`win32`?Fe(t):t)!==r)throw new ft(e.databasePath)}return t||(assertReadAllowed(),k.get(x.resolve(n))===i&&k.set(s,i)),{ownerId:i.payload.ownerId,role:i.payload.role??`gateway`,signal:i.lost.signal,assertCurrent,assertReadAllowed,prepareAccess:o.prepareAccess}}function assertStateDatabaseReadAllowed(e,t){assertStateDatabaseReadAtOwnerPath(e,t)}function assertStateDatabaseReadAtOwnerPath(e,t,n){if(A.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}let r=x.resolve(e);if(k.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=A.get(i.key),o=a?.payload.role??`gateway`;if(!a||a.kind!==`process`||!a.accepting||o!==`gateway`&&o!==`agent-embedded`)assertStateDatabaseAccessAtOwnerPath(e,i,t);else{if(!hasPhysicalOwnership(a))throw a.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);k.set(r,a)}}function assertStateDatabaseAccessAllowed(e,t){assertStateDatabaseAccessAtOwnerPath(e,resolveStateOwnerIdentity(e),t)}async function captureStateDatabaseAccess(e){return createStateDatabaseAccess(await resolveStateOwnerIdentityAsync(e))}function createStateDatabaseAccess(e,t){let{canonicalPath:n}=e,r=A.get(e.key);return{canonicalPath:n,processOwner:r?.kind===`process`?{role:r.payload.role??`gateway`,signal:r.lost.signal,assertCurrent(){if(r.lost.signal.throwIfAborted(),!r.accepting||A.get(e.key)!==r)throw dt()}}:void 0,prepareAccess:async r=>{let i=t??A.get(e.key),a=i?.payload.role??`gateway`;if(!i||i.kind!==`process`||!i.accepting||a!==`gateway`&&a!==`agent-embedded`)return assertStateDatabaseAccessAtOwnerPath(n,e,r),(t=r)=>{if(i&&A.get(e.key)!==i)throw dt();assertStateDatabaseReadAtOwnerPath(n,t,e)};let o=i.heartbeat,s=i.locks.values().next().value,c=i.getProjection?.();if(!o||!s)throw dt();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),o.assertActive(),A.get(e.key)!==i||i.heartbeat!==o)throw dt();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(s)||i.getProjection?.()!==c)throw dt()};assertCurrent();let l=[s.lockPath];c&&l.push(c.lockPath);let u=await o.verify(l).catch(e=>{throw i.lost.signal.throwIfAborted(),e});if(assertCurrent(),!u){let e=/* @__PURE__ */ Error(`${s.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`);throw loseOwner(i,e),e}return k.set(x.resolve(n),i),assertCurrent},assertReadAllowed(t){assertStateDatabaseReadAtOwnerPath(n,t,e)}}}function assertStateDatabaseAccessAtOwnerPath(e,t,n){let assertMaintenance=()=>{let t=n?n.schemaLease:getStateDatabaseSchemaLease(e);if(t){t.assertDatabaseAccess(e);return}let r=n?n.maintenanceScope:it();if(!r)throw new mt(e);r.assertDatabaseAccess(e)},r=A.get(t.key);if(r){if(!hasPhysicalOwnership(r))throw r.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);let t=r.payload.role??`gateway`;(!r.accepting||t!==`gateway`&&t!==`agent-embedded`)&&assertMaintenance()}else assertPersistedStateDatabaseAccessAllowed({databasePath:e,ownerPath:t.ownerPath,assertMaintenance})}function createSqliteTerminalOpenLatch(e){let t=/* @__PURE__ */ new Map;return{peek:e=>t.get(x.resolve(e)),get:e=>t.get(x.resolve(e)),record:(n,r)=>{let i=x.resolve(n);wt(r),t.set(i,r),e.closeByPath(i,r)},clear:e=>{t.delete(x.resolve(e))},clearAll:e=>{for(let n of t.keys())(e===void 0||Ie(e,n))&&t.delete(n)}}}function sameFileFingerprint(e,t){return e.dev===t.dev&&e.ino===t.ino&&p(e,t)&&e.sha256===t.sha256}function sameOptionalFileFingerprint(e,t){return e===void 0?t===void 0:t!==void 0&&sameFileFingerprint(e,t)}function sameSqliteFileGeneration(e,t){return sameFileFingerprint(e.database,t.database)&&sameOptionalFileFingerprint(e.journal,t.journal)&&sameOptionalFileFingerprint(e.wal?.size===0n?void 0:e.wal,t.wal?.size===0n?void 0:t.wal)}function parseFileFingerprint(e){if(!We(e))throw Error(`SQLite file fingerprint must be an object`);for(let t of[`birthtimeNs`,`ctimeNs`,`dev`,`ino`,`mtimeNs`,`size`])if(typeof e[t]!=`string`||!/^-?\d+$/u.test(e[t]))throw Error(`SQLite file fingerprint ${t} is invalid`);if(typeof e.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(e.sha256))throw Error(`SQLite file fingerprint sha256 is invalid`);return{birthtimeNs:BigInt(e.birthtimeNs),ctimeNs:BigInt(e.ctimeNs),dev:BigInt(e.dev),ino:BigInt(e.ino),mtimeNs:BigInt(e.mtimeNs),sha256:e.sha256,size:BigInt(e.size)}}function parseSqliteFileGeneration(e){let t=JSON.parse(e);if(!We(t))throw Error(`SQLite file generation must be an object`);return{database:parseFileFingerprint(t.database),...t.journal===void 0?{}:{journal:parseFileFingerprint(t.journal)},...t.wal===void 0?{}:{wal:parseFileFingerprint(t.wal)}}}function readSqliteFileGenerationSync(e){return parseSqliteFileGeneration(le(e,void 0,`file-generation`))}async function backupNodeSqliteDatabase(e,t,n){let r=setInterval(()=>{},100);try{let r=await Xt().backup(e,ar(t),{progress:n});return n?.({totalPages:r,remainingPages:0}),r}finally{clearInterval(r)}}function createPrivateWindowsDirectory(e){let t=!1;try{wr(x.resolve(e),{private:!0,assertBeforeMutation(){t=!0}})}catch(e){throw!t||e instanceof Cr&&e.code===`already-exists`?Ee(e):e}}function resolvePrivateSqliteSnapshotStagingRoot(e=process.env){try{return resolveSnapshotStagingRoot(e)}catch(e){throw e instanceof Error&&oe(e)?new De(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`,{cause:e}):e}}function resolveSnapshotStagingRoot(e){let t=e.OPENCLAW_UPDATE_IN_PROGRESS===`1`?e.TMPDIR?.trim():void 0;if(t&&x.isAbsolute(t))return ot({preferredDir:x.join(t,`openclaw`),tmpdir:()=>t});let n=process.platform===`win32`?e.LOCALAPPDATA?.trim():void 0,r=process.platform===`win32`?`AppData/Local`:`.cache`,i=process.platform===`darwin`?`Library/Caches`:r,a=[e.XDG_CACHE_HOME?.trim(),n].find(e=>e&&x.isAbsolute(e))??x.join(Ge(e),i),o=qe(e),s=Or(`sha256`).update(o).digest(`hex`).slice(0,24);b.mkdirSync(a,{recursive:!0,mode:448});let c=ot({preferredDir:x.join(a,`openclaw`),tmpdir:()=>a}),[l=``,...u]=x.relative(c,o).split(x.sep),d=u.length>0&&/^sqlite-[a-f0-9]{24}$/u.test(l)?l:`sqlite-${s}`,f=x.join(c,d);b.mkdirSync(f,{recursive:!0,mode:448});let p=b.lstatSync(f);if(!p.isDirectory()||process.getuid&&p.uid!==process.getuid()||process.platform!==`win32`&&p.mode&63)throw Error(`SQLite snapshot namespace must be a private user-owned directory`);return f}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return b.mkdtempSync(x.join(e,t))}catch(e){throw Ee(e)}let n=x.join(e,`${t}${Ar()}`);return createPrivateWindowsDirectory(n),n}function sqliteSnapshotSourceFileSize(e){try{let t=b.statSync(e);return t.isFile()?t.size:0}catch(e){if(t(e,`ENOENT`))return 0;throw e}}function assertSqliteSnapshotSpace(e,t){let n=typeof e==`string`?[``,`-wal`,`-journal`].reduce((t,n)=>t+sqliteSnapshotSourceFileSize(e+n),0):lr(e),r=tryReadDiskSpace(t);if(r&&r.availableBytes<n)throw Object.assign(/* @__PURE__ */ Error(`SQLite read-only snapshot needs ${formatDiskSpaceBytes(n)} (${n} bytes) near ${t}, but only ${formatDiskSpaceBytes(r.availableBytes)} (${r.availableBytes} bytes) is available. Free disk space before retrying.`),{code:`ENOSPC`})}function acquireSqliteSnapshotReadToken(e){return u(e,`read`)}function sqliteSnapshotStagingError(e,t,n=!1,r){Tt(t,`snapshot`);let i=n,a=!1,o=!1,s;for(let n=0,r=t;n<8&&r instanceof Error;n+=1){o||=r instanceof AggregateError||r instanceof Pt;let{errcode:t,path:n}=r;a||=oe(r),(a||typeof t==`number`&&[13,778,1034,1290].includes(t)||`${n??``}${x.sep}`.startsWith(`${e}${x.sep}`))&&(i=!0,typeof t==`number`&&(s=t)),r=r.cause}if(!i)return t;let c=a?`free disk space/quota`:`check filesystem health and write permissions`,l=``;if(a&&r)try{let t=sqliteSnapshotSourceFileSize(r)+sqliteSnapshotSourceFileSize(`${r}-wal`)+sqliteSnapshotSourceFileSize(`${r}-journal`),n=tryReadDiskSpace(e)?.availableBytes,i=b.existsSync(`${r}-wal`)&&b.existsSync(`${r}-shm`);l=`; estimated ${t} bytes needed; ${n===void 0?`available bytes unknown`:`${n} bytes available`}; source ${i?`has live WAL sidecars`:`has no live WAL sidecars`}`}catch{}let u=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`,f=`${t instanceof Error?t.message:String(t)}${s===void 0?``:` (SQLite errcode=${s})`}; snapshot staging root ${n?e:x.dirname(e)}${l}: ${c} or set ${u} to a writable filesystem`,p=a&&!o&&rn(t)!==`source`?new De(f,{cause:t}):Error(f,{cause:t});return d(t)?Ee(p):p}async function createSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){n?.throwIfAborted();try{return await allocateSqliteSnapshotStagingDirectory(e,t,n,r)}catch(e){throw e instanceof Pt||r&&e instanceof AggregateError||(n?.throwIfAborted(),Tt(e,`snapshot`)),e}}async function allocateSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){if(n?.throwIfAborted(),r){let r=new AbortController;return ee((async()=>{let{allocateWorkerOwnedSqliteSnapshotDirectory:i}=await import(`./fs-safe-copy.worker-sqlite-snapshot-staging-allocation-ChfFVgze.mjs`);n?.throwIfAborted(),r.signal.throwIfAborted();let a=await i(e,t,n?AbortSignal.any([n,r.signal]):r.signal);if(ne(a.directory),n?.aborted||r.signal.aborted){if(!await f(a.directory))throw new Pt(`SQLite snapshot cleanup failed: ${a.directory}`);n?.throwIfAborted(),r.signal.throwIfAborted()}return a.directory})(),()=>r.abort(/* @__PURE__ */ Error(`SQLite snapshot allocation stopped`)))}return createSqliteSnapshotStagingDirectorySync(e,t)}function createSqliteSnapshotStagingDirectorySync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n=createSqliteSnapshotStagingTokenSync(e,t);return ne(n.directory,n.release),n.directory}function createSqliteSnapshotStagingTokenSync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n;try{try{n=createPrivateSqliteTempDirectorySync(e,t?`openclaw-sqlite-readonly-${process.pid}-`:ke)}catch(t){throw sqliteSnapshotStagingError(e,t,!0)}return{directory:n,release:u(n,`create`)}}catch(e){throw n&&ie(n),e}}Buffer.from([217,213,5,249,32,161,99,215]);async function prepareSqliteReadOnlyLocationFromOwnedDatabase(e,t,n,r){let assertReady=()=>{if(n?.throwIfAborted(),t(),!e.isOpen||e.isTransaction)throw Error(`SQLite inspection requires an open owner outside a transaction`)};assertReady();let i=await createSqliteSnapshotStagingDirectory(void 0,!1,n,r===`async`);try{assertReady(),assertSqliteSnapshotSpace(e,i);let r=x.join(i,`database.sqlite.partial`);return await ee(backupNodeSqliteDatabase(e,r)),n?.throwIfAborted(),t(),ge(i)}catch(e){let t=[e];throw!await f(i,e=>t.push(e))&&r===`async`?l(t,`Owned SQLite snapshot preparation`):e}}const dd=n(Symbol.for(`openclaw.sqliteSnapshotFlights`),()=>({unscoped:/* @__PURE__ */ new Map,scoped:/* @__PURE__ */ new WeakMap}));function completed$1(e){let t=ht(()=>{});return t.resolve(e),t.operation}function serviceWhenSettled(e,t){e.result.then(t,t)}function createFlight(e,t,n){let r,i=!1,a=!1,o,s,c,l=ht(()=>{if(!(a||l.operation.read().status!==`pending`)){a=!0;try{i||(i=!0,r=n(d.controller.signal,e=>c=e),serviceWhenSettled(r.operation,serviceFlight)),r.operation.service();let e=r.operation.read();e.status===`fulfilled`?l.resolve(e.value):e.status===`rejected`&&l.reject(e.error)}catch(e){l.reject(e)}finally{a=!1}}}),u=ht(()=>{l.operation.service();let n=l.operation.read();if(n.status!==`pending`&&u.operation.read().status===`pending`){if(e.get(t)===d&&e.delete(t),n.status===`rejected`)u.reject(c??n.error);else if(d.references>0)u.resolve(n.value);else{o||(o=releaseSnapshot(d,n.value),serviceWhenSettled(o,()=>u.operation.service())),o.service();let e=o.read();e.status===`fulfilled`?e.value?u.resolve(n.value):u.reject(new Pt(`SQLite orphan snapshot cleanup did not complete`)):e.status===`rejected`&&u.reject(e.error)}}});function serviceFlight(){l.operation.service();for(let e of d.listeners)e();u.operation.service()}let d={controller:new AbortController,references:0,listeners:/* @__PURE__ */ new Set,production:l.operation,settled:u.operation,closeProducer(){return s??=r?.startClose?.()??completed$1(void 0),s}};return ee(u.operation.result,()=>{d.controller.abort(/* @__PURE__ */ Error(`SQLite snapshot owner stopped`)),serviceFlight()}),d}function releaseSnapshot(e,t){return _t(t.startCleanup(),t=>t?yt(e.closeProducer(),()=>!0):completed$1(!1))}function leaseFlight(e,t){let n=!1,r,releaseReference=()=>(n||(n=!0,e.references--),e.references===0),startCleanup=()=>(r??=!n&&releaseReference()?releaseSnapshot(e,t):completed$1(!0),r);return{location:t.location,cleanupRoot:t.cleanupRoot,privateFamily:t.privateFamily,cleanup(){if(n){let e=r?.read();return!e||e.status===`fulfilled`&&e.value}if(e.references>1)return releaseReference(),!0;let i=t.cleanup();return i&&releaseReference(),i},cleanupAsync:()=>startCleanup().result,startCleanup}}function startSnapshotFlight(e,t,n,r,i){r?.throwIfAborted();let a=`${gn(e).key}:${t}`,o=dd.unscoped;if(i?.scope){let e=dd.scoped.get(i.scope);e||(e=/* @__PURE__ */ new Map,dd.scoped.set(i.scope,e)),o=e}let s=o.get(a);s||(s=createFlight(o,a,n),o.set(a,s));let c=s;c.references++;let l=!1,u=!1,d,f=ht(()=>{if(f.operation.read().status===`pending`){if(l||r?.aborted){if(u||(u=!0,c.references--),c.references===0&&(c.controller.abort(r?.reason),o.get(a)===c&&o.delete(a),c.settled.service(),c.settled.read().status===`pending`))return;f.reject(r?.reason??/* @__PURE__ */ Error(`SQLite snapshot preparation closed`))}else{c.production.service();let e=c.production.read();if(e.status===`pending`)return;e.status===`fulfilled`?f.resolve(leaseFlight(c,e.value)):(c.references--,f.reject(e.error))}r?.removeEventListener(`abort`,service),c.listeners.delete(service),c.settled.service()}}),service=()=>f.operation.service();return serviceWhenSettled(c.settled,service),c.listeners.add(service),r?.addEventListener(`abort`,service,{once:!0}),queueMicrotask(service),{...f.operation,startClose(){l=!0,f.operation.service();let e=f.operation.read();return d??=e.status===`fulfilled`?yt(e.value.startCleanup(),e=>{if(!e)throw new Pt(`SQLite snapshot lease cleanup did not complete`)}):c.references===0?c.closeProducer():completed$1(void 0),d}}}function startAwaitedSnapshotWork(e){let t=ht(()=>{});return Promise.resolve().then(e).then(t.resolve,t.reject),t.operation}async function prepareSingleFlightSqliteSnapshot(e,t,n,r,i){return startSnapshotFlight(e,t,(e,t)=>({operation:startAwaitedSnapshotWork(async()=>{let r=await n(e,t);return{...r,startCleanup:()=>startAwaitedSnapshotWork(()=>r.cleanupAsync())}})}),r,i).result}function startSingleFlightSqliteSnapshot(e,t,n,r,i){return startSnapshotFlight(e,t,(e,t)=>{let r=n(e,t);return{operation:r,startClose:()=>r.startClose()}},r,i)}const fd=n(Symbol.for(`openclaw.sqliteLiveSnapshotOwners`),()=>/* @__PURE__ */ new Map);function registerLiveSqliteSnapshotOwner(e){let t=gn(e.databasePath),n={assertCurrent:e.assertCurrent,database:e.database};return fd.set(t.key,n),()=>{fd.get(t.key)===n&&fd.delete(t.key)}}function prepareSqliteSnapshotFromLiveOwner(e,t){t?.throwIfAborted();let n=gn(e),r=fd.get(n.key);if(r)return r.assertCurrent(),prepareSingleFlightSqliteSnapshot(n.canonicalPath,`live-owner:openclaw-state`,e=>prepareSqliteReadOnlyLocationFromOwnedDatabase(r.database,r.assertCurrent,e),t)}function fingerprint(e){return[e.dev,e.ino,e.birthtimeNs,e.ctimeNs,e.mtimeNs,e.size].join(`:`)}function walFingerprint(e){return[e.dev,e.ino,e.mtimeNs,e.size].join(`:`)}function readFile$2(e){let t=b.lstatSync(e,{bigint:!0,throwIfNoEntry:!1});if(t){if(!t.isFile()||t.nlink!==1n)throw Error(`Private SQLite snapshot must be an independent regular file: ${e}`);return t}}function captureSqlitePrivateSnapshotFamily(e,t){if(b.lstatSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=readFile$2(e),r=readFile$2(`${e}-wal`);return n?{root:t,main:fingerprint(n),wal:r&&r.size>32n?walFingerprint(r):null}:void 0}const pd=n(Symbol.for(`openclaw.sqliteReusableSnapshots`),()=>/* @__PURE__ */ new Map),md=n(Symbol.for(`openclaw.sqliteReusableSnapshotScopes`),()=>({depth:0,retiring:/* @__PURE__ */ new Set}));function isSqliteSnapshotReuseActive(){return md.depth>0}function completed(e){let t=ht(()=>{});return t.resolve(e),t.operation}function readSource(e){try{let t=b.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!t?.isFile()||b.statSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=b.statSync(`${e}-wal`,{bigint:!0,throwIfNoEntry:!1}),r=n&&n.size>0n?n:void 0;return{fingerprint:[`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`,r?`${r.dev}:${r.ino}:${r.size}:${r.mtimeNs}`:`none`].join(`|`),main:t,newestMs:Math.max(Number(t.mtimeMs),Number(r?.mtimeMs??0)),quiescentMs:[t,r].some(e=>e&&e.mtimeNs%1000000000n==0n)?2e3:50}}catch{return}}function canonicalKey(e){try{return b.realpathSync.native(e)}catch{return}}function retire(e,t){pd.get(e)===t&&pd.delete(e),t.retired=!0,t.leases===0&&settleRetirement(t.retire)}function settleRetirement(e){let t=new Promise(t=>{t(e())}).catch(reportRetirementFailure).finally(()=>md.retiring.delete(t));md.retiring.add(t)}function reportRetirementFailure(e){st({subsystem:`infra/sqlite-snapshot`}).warn({error:String(e)},`Retiring a reusable SQLite snapshot failed.`)}function lend(e,t){t.leases+=1;let n=!1,release=()=>(n||(n=!0,--t.leases,t.leases===0&&t.retired&&retire(e,t)),!0);return{location:t.location,cleanupRoot:t.cleanupRoot,privateFamily:t.privateFamily,cleanup:release,cleanupAsync:async()=>release(),startCleanup:()=>completed(release())}}function leaseReusableSqliteSnapshot(e,t,n={}){let r=canonicalKey(e),i=r?pd.get(r):void 0;if(r&&i){if(readSource(r)?.fingerprint!==i.fingerprint||!b.existsSync(i.location))retire(r,i);else if(!i.logicalOnly||n.logicalReader){if(t)try{vn(i.main,t)}catch{return}return lend(r,i)}}}function captureReusableSqliteSource(e){let t=md.depth>0?canonicalKey(e):void 0,n=t?readSource(t):void 0;return n&&Date.now()-n.newestMs>=n.quiescentMs?n:void 0}function captureFamily(e){try{return captureSqlitePrivateSnapshotFamily(e.location,e.cleanupRoot??x.dirname(e.location))}catch{return}}const hd=n(Symbol.for(`openclaw.sqliteReusableSnapshotSources`),()=>/* @__PURE__ */ new Map);function bindReusableSqliteSource(e,t){t&&hd.set(e,t)}function publishBoundReusableSqliteSnapshot(e,t,n){let r=canonicalKey(e)??x.resolve(e),i=pd.get(r),a=hd.get(t.location)??(i?.location===t.location?i:void 0);return hd.delete(t.location),a?publishReusableSqliteSnapshot(e,a,t,n):t}function publishReusableSqliteSnapshot(e,t,n,r,i={}){let a=canonicalKey(e)??x.resolve(e),o=pd.get(a);if(o?.location===n.location&&o.fingerprint===t.fingerprint)return settleRetirement(r),lend(a,o);o&&retire(a,o);let s={...t,logicalOnly:i.logicalOnly===!0,location:n.location,cleanupRoot:n.cleanupRoot,privateFamily:n.privateFamily??captureFamily(n),leases:0,retired:!1,retire:r};return pd.set(a,s),lend(a,s)}function createLeasedSqliteSnapshotPreparation(e){return{...completed(e),startClose:()=>yt(e.startCleanup(),()=>void 0)}}const gd=[``,`-wal`,`-shm`,`-journal`],_d=gd.slice(1);Buffer.from([0,5,22,7]);const vd=ct(`state/sqlite`);var SqliteOrphanedSidecarsError=class extends Error{constructor(e,t,n){super(`SQLite database is missing at ${e}, and orphaned sidecars could not be copied: ${t.join(`, `)}. Refusing to open because SQLite could delete orphan WAL or journal state. Preserve the sidecar bytes, restore the main database, and pair it with the matching sidecar before retrying.`,{cause:n}),this.name=`SqliteOrphanedSidecarsError`}};function resolveSqliteDatabaseFilePaths(e){return gd.map(t=>`${e}${t}`)}function findMatchingOrphanedSidecarCopy(e,t){let n=x.dirname(e),r=`${x.basename(e)}.orphaned-`,i=b.readdirSync(n,{withFileTypes:!0}).filter(e=>e.isFile()&&e.name.startsWith(r)).map(e=>x.join(n,e.name)).filter(e=>b.statSync(e).size===t);if(i.length===0)return;let a=jn(e);for(let e of i)if(jn(e)===a)return e}function copyOrphanedSidecar(e,t){let n=`${e}.orphaned-${t}`;for(let t=0;;t+=1){let r=t===0?n:`${n}-${t}`;try{return b.copyFileSync(e,r,b.constants.COPYFILE_EXCL),r}catch(e){if(e.code!==`EEXIST`)throw e}}}function quarantineOrphanedSqliteSidecars(e){if(b.existsSync(e))return;let t=[{path:`${e}-wal`,minimumBytes:32},{path:`${e}-journal`,minimumBytes:0}].flatMap(e=>{let t=b.statSync(e.path,{throwIfNoEntry:!1});return t?.isFile()===!0&&t.size>e.minimumBytes?[{path:e.path,size:t.size}]:[]});if(t.length===0)return;let n=Date.now(),r=[];try{for(let e of t){if(findMatchingOrphanedSidecarCopy(e.path,e.size))continue;let t=copyOrphanedSidecar(e.path,n);r.push({quarantinePath:t,sourcePath:e.path})}}catch(n){throw new SqliteOrphanedSidecarsError(e,t.map(e=>e.path),n)}if(r.length===0)return;let i=r.map(({sourcePath:e,quarantinePath:t})=>`${e} -> ${t}`);vd.warn(`SQLite database is missing at ${e}; copied orphaned sidecars: ${i.join(`, `)}. Committed frames could not be applied because the main database is missing. The bytes are preserved. Recovery requires restoring the main database and pairing it with the quarantined file.`,{databasePath:e,copiedSidecars:r})}function buildUpdateRehearsalPathEnv(e){return{HOME:e,USERPROFILE:e,TMPDIR:e,TMP:e,TEMP:e,XDG_CONFIG_HOME:x.join(e,`config`),XDG_CACHE_HOME:x.join(e,`cache`),XDG_DATA_HOME:x.join(e,`data`),XDG_STATE_HOME:x.join(e,`state`),OPENCLAW_HOME:e,OPENCLAW_STATE_DIR:e,OPENCLAW_CONFIG_PATH:x.join(e,`openclaw.json`),OPENCLAW_WORKSPACE_DIR:x.join(e,`workspace`),OPENCLAW_SKIP_CHANNELS:`1`,OPENCLAW_SKIP_PROVIDERS:`1`,OPENCLAW_SKIP_CRON:`1`,OPENCLAW_SKIP_GMAIL_WATCHER:`1`,OPENCLAW_SKIP_CANVAS_HOST:`1`,OPENCLAW_SKIP_BROWSER_CONTROL_SERVER:`1`,OPENCLAW_SKIP_STARTUP_MODEL_PREWARM:`1`,OPENCLAW_NO_AUTO_UPDATE:`1`,NODE_DISABLE_COMPILE_CACHE:`1`}}function projectUpdateRehearsalDatabaseConfig(e,t){if(!We(e)||!We(e.database)||!resolveUpdateRehearsalRoot(t))return e;let{engine:n,families:r}=e.database;return n===`postgres`||We(r)&&Object.values(r).some(e=>We(e)&&e.engine===`postgres`)?{...e,database:{engine:`sqlite`}}:e}function resolveUpdateRehearsalRoot(e){let t=e.OPENCLAW_STATE_DIR;if(t&&x.isAbsolute(t)&&[`0`,`1`].includes(e.OPENCLAW_UPDATE_IN_PROGRESS??``)&&!Object.entries(buildUpdateRehearsalPathEnv(t)).some(([t,n])=>e[t]!==n)&&e.OPENCLAW_SERVICE_REPAIR_POLICY===`external`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_SERVICE_REPAIR===`0`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_ACTIVATION===`0`&&!e.OPENCLAW_COMPATIBILITY_HOST_VERSION)return x.resolve(t)}function isUpdateRehearsalReadOnlyPath(e,t){let n=resolveUpdateRehearsalRoot(t);if(!n)return!1;let r=x.resolve(e);return!Ie(n,r)||!Ie(Ne(n),Ne(r))}function isUpdateRehearsalPrivateDatabase(e,t){return resolveUpdateRehearsalRoot(t)!==void 0&&resolveSqliteDatabaseFilePaths(e).every(e=>!isUpdateRehearsalReadOnlyPath(e,t))}function findArtifactSnapshot(e,t){let n=e.snapshots.get(t.canonicalPath);if(n&&(n.sourceIdentity.key!==t.key||n.sourceIdentity.birthtime!==t.birthtime))throw Error(`SQLite database file identity changed during inspection`);return n}function retainArtifactSnapshot(e,t,n){let r=h(t.cleanupRoot??x.dirname(t.location));e.privateRoots.add(t.cleanupRoot??x.dirname(t.location));let i={...t,sourceIdentity:n,cleanup:()=>(r(),t.cleanup()),cleanupAsync:()=>(r(),t.cleanupAsync())};return e.snapshots.set(n.canonicalPath,i),i}function assertCustodiedSourceUnchanged(e,t){let n=b.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!n||n.ino!==t.ino||n.size!==t.size||n.mtimeNs!==t.mtimeNs||at(e)===void 0)throw Error(`SQLite source changed during in-place inspection: ${e}`)}function openSqliteReadOnlyDatabase(e,t={}){let n=ce.getStore();if(!n||!m(`agent`,e))return ir(e,{...t,readOnly:!0});let r=gn(e),i=findArtifactSnapshot(n,r),a=i?void 0:at(r.canonicalPath);i||a||isUpdateRehearsalPrivateDatabase(e,process.env)||(i=retainArtifactSnapshot(n,prepareSqliteReadOnlyLocationSync(e),r));let o=i?h(i.cleanupRoot??x.dirname(i.location)):void 0,s={},close=()=>{s.close?.(),o?.(),n.readers.delete(close)};n.readers.add(close);let c=i?.location??(a?Zn(r.canonicalPath):e),l=ir(c,{...t,readOnly:!0}),u=l.close.bind(l);return s.close=()=>{l.isOpen&&(u(),a&&assertCustodiedSourceUnchanged(r.canonicalPath,a))},l.close=close,l}async function prepareSqliteReadOnlyLocation(e,t={}){let n=re(t.signal),r=t.preserveSourceArtifacts===!0||m(`agent`,e);try{if(n?.throwIfAborted(),!r&&t.allowLiveOwner!==!1){let t=prepareSqliteSnapshotFromLiveOwner(e,n);if(t)return await t}n?.throwIfAborted();let i=t.reuse===!0&&r,a=i?leaseReusableSqliteSnapshot(e,t.expectedSourceIdentity):void 0;if(a)return a;let o=t.requireCleanup??t.signal!==void 0,s=prepareSingleFlightSqliteSnapshot(e,`${r?`worker-sync`:`worker-async`}:${o?`strict`:`best-effort`}:sync-token${t.expectedSourceIdentity?`:${JSON.stringify(t.expectedSourceIdentity)}`:``}`,async(n,a)=>{let s,c=i?captureReusableSqliteSource(e):void 0;try{n.throwIfAborted(),s=await createSqliteSnapshotStagingDirectory(void 0,!1,n),n.throwIfAborted();let a=await Te(e,{mode:r?`sync`:`async`,signal:n,stagingRoot:s,expectedSourceIdentity:t.expectedSourceIdentity});n.throwIfAborted(),bindReusableSqliteSource(a,c);let l=_e(a,s,o);return i&&(l.privateFamily=captureFamily(l)),l}catch(e){if(s&&!await f(s)){let t=new Pt(`${Me(e)}; SQLite snapshot cleanup failed: ${s}`,{cause:e});throw a?.(t),t}throw e instanceof Pt?(a(e),e):(n.throwIfAborted(),e)}},n,t.shared===!1?{scope:{}}:void 0);return i?s.then(t=>publishBoundReusableSqliteSnapshot(e,t,()=>t.cleanup())):s}catch(e){throw n?.throwIfAborted(),e}}function startSqliteReadOnlyLocationAsync(e,t={}){let n=re(t.signal);n?.throwIfAborted();let r=x.resolve(e),i=t.preserveSourceArtifacts===!0||m(`agent`,r),a=t.expectedSourceIdentity===void 0?void 0:bn(t.expectedSourceIdentity);if(a&&!i)throw Error(`SQLite source identity requires artifact-preserving preparation`);let o=t.reuse&&i?leaseReusableSqliteSnapshot(r,a):void 0;if(o)return createLeasedSqliteSnapshotPreparation(o);let s=t.signal!==void 0,{env:c,cwd:l}=ye(),u=resolvePrivateSqliteSnapshotStagingRoot(),d=pe(),f=Ce(),p=Tr.snapshot();return startSingleFlightSqliteSnapshot(r,`${i?`worker-sync`:`worker-async`}:${s?`strict`:`best-effort`}:async-token${a?`:${JSON.stringify(a)}`:``}`,e=>p(()=>{let t=f.start({type:`prepare`,root:u,pathname:r,allowLegacyWorker:!1,preserveSourceArtifacts:i,expectedSourceIdentity:a,deadlineOwnedByCaller:d,launch:{env:c,cwd:l,transport:{kind:`native`}}},e);return{...yt(t,e=>{if(e.type!==`prepared`)throw Error(`SQLite snapshot producer returned an allocation without its prepared location`);let t=_e(e.location,e.directory,s);return t.privateFamily=i?captureSqlitePrivateSnapshotFamily(e.location,e.directory):void 0,t}),startClose:()=>t.startClose()}}),n,{scope:f})}async function prepareSqliteReadOnlyLocationAwaited(e,t){let n=re(t.signal),r=x.resolve(e),i=bn(t.expectedSourceIdentity);return(t.reuse?leaseReusableSqliteSnapshot(r,i):void 0)||(t.reuse&&!t.allowLiveOwner&&isSqliteSnapshotReuseActive()?prepareSqliteReadOnlyLocation(r,{preserveSourceArtifacts:!0,signal:n,requireCleanup:!0,reuse:!0,expectedSourceIdentity:i}):prepareSingleFlightSqliteSnapshot(r,`worker-${t.allowLiveOwner?`metadata`:`sync`}:strict:awaited-token:${JSON.stringify(i)}`,async(e,n)=>{let a=t.allowLiveOwner;return useAwaitedSnapshotWorker(e,n,async(t,n)=>{let o={mode:a?`metadata`:`sync`,stagingRoot:n,expectedSourceIdentity:i,signal:e},s=a?await Oe(r,o):await t.run(r,o);if(typeof s!=`string`)throw Error(`SQLite snapshot preparation returned an invalid location`);return e.throwIfAborted(),_e(s,n,!0)})},n))}async function useAwaitedSnapshotWorker(e,t,n){e.throwIfAborted();let r=ye(),i=me({...r,retainOnOperationError:!0}),a,o,retire=()=>{if(o&&o.read().status!==`rejected`)return o;let e=ht(()=>{});return o=e.operation,(async()=>{if(a){let e=i.isRetired();e&&(await i.close(),i=me(r)),await i.run(a,{mode:e?`staging-reconcile`:`staging-retire`})}await i.close(),await i.closed,a&&await b.promises.rm(a,{recursive:!0,force:!0,maxRetries:3,retryDelay:20})})().then(e.resolve,e.reject),o};try{let t=await i.run(resolvePrivateSqliteSnapshotStagingRoot(),{mode:`staging-create`,signal:e});if(typeof t!=`string`)throw Error(`SQLite snapshot allocation returned an invalid directory`);a=t,te(a,retire),e.throwIfAborted();let r=await n(i,a);return e.throwIfAborted(),r}catch(e){try{if(a){if(!await f(a))throw new Pt(`SQLite snapshot cleanup failed: ${a}`)}else await i.close(),await i.closed}catch(n){let r=AggregateError([e,n],`SQLite snapshot preparation and cleanup failed`);throw t?.(r),r}throw e}}function prepareSqliteReadOnlyLocationSync(e,t,n={}){let r=n.reuse?leaseReusableSqliteSnapshot(e,t):void 0;if(r)return r;let i=n.reuse?captureReusableSqliteSource(e):void 0,a=createSqliteSnapshotStagingDirectorySync();try{let n=_e(le(e,a,`sync`,t),a);return i?publishReusableSqliteSnapshot(e,i,n,()=>n.cleanup()):n}catch(e){throw ie(a)?e:new Pt(`${Me(e)}; SQLite snapshot cleanup failed: ${a}`,{cause:e})}}const yd={statement:jr(`openclaw.database.statement`),request:jr(`openclaw.database.request`)},bd=/* @__PURE__ */ new WeakSet;let statementTiming;function attributesSqliteStatements(e){return e.startsWith(`session.transcript.`)||e.startsWith(`sessions.transcript-`)||e.startsWith(`session.metadata.`)||e.startsWith(`trajectory.`)||e.startsWith(`audit.writer.`)||e.startsWith(`knowledge.`)||e===`session.lifecycle.delete`||e===`session context snapshot read`}function startSqliteStatementTiming(e=!1){let t=statementTiming,n,r;if(e)try{r=dr(e=>{for(let t of e)n=(n??0)+t.durationMs}),n=r?0:void 0}catch{}let i=/* @__PURE__ */ new Map,a=0,o=0,s=0,c;return statementTiming=(e,t,n)=>{a++,o+=t,(c===void 0||t>s)&&(c=e);let r=i.has(e)||i.size<32?e:``,l=i.get(r)??{count:0,totalMs:0,maxMs:0};i.set(r,l),s=Math.max(s,t),n!==void 0&&(l.rows=(l.rows??0)+n),l.count++,l.totalMs+=t,l.maxMs=Math.max(l.maxMs,t)},()=>{statementTiming=t;try{r?.()}catch{n=void 0}return{totalMs:o,callbackGcMs:n,summarize(){let identity=e=>{let t=normalizeSql(`sqlite`,e);return{id:e?Or(`sha256`).update(t).digest(`hex`).slice(0,16):`other`,operation:/^(SELECT|INSERT|UPDATE|DELETE|WITH|SAVEPOINT|RELEASE|ROLLBACK)\b/i.exec(t)?.[1]?.toUpperCase()??`OTHER`}};return{count:a,maxMs:s,slowest:c===void 0?void 0:{...identity(c),maxMs:s},statements:[...i].toSorted((e,t)=>t[1].totalMs-e[1].totalMs).slice(0,5).map(([e,t])=>Object.assign(identity(e),t,{totalMs:Math.round(t.totalMs*100)/100,maxMs:Math.round(t.maxMs*100)/100})),omittedGroups:Math.max(0,i.size-5)}}}}}function normalizeSql(e,t){let n=``;for(let r=0;r<t.length;){let i=t.slice(r);if(i.startsWith(`/*`)){let e=1;for(r+=2;r<t.length&&e;)t.startsWith(`/*`,r)?(e++,r+=2):t.startsWith(`*/`,r)?(e--,r+=2):r++;n+=` `;continue}let a=/^--[^\r\n]*/.exec(i)?.[0],o=(e===`postgres`?/^[eE]'(?:\\[\s\S]|''|[^'\\])*(?:'|$)/.exec(i)?.[0]:void 0)??/^(?:[uU]&)?'(?:''|[^'])*(?:'|$)/.exec(i)?.[0],s=/^\$(?:[A-Za-z_][\w]*)?\$/.exec(i)?.[0],c=/^(?:"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\])/.exec(i)?.[0],l=/[\w$]/.test(t[r-1]??``)?void 0:/^(?:0x[\da-f]+|\d+(?:\.\d*)?(?:e[+-]?\d+)?)(?!\w)/i.exec(i)?.[0];if(s){let e=t.indexOf(s,r+s.length);r=e<0?t.length:e+s.length,n+=`?`}else if(a||o||c||l){let e=a??o??c??l??``;r+=e.length,n+=a?` `:c?e:`?`}else n+=t[r++]}return n.replace(/\s+/g,` `).trim()}function observeDatabaseOperation(e,t,n,r,i){let a=yd[t],o=e===`sqlite`&&t===`statement`?statementTiming:void 0;if(!a.hasSubscribers&&!o)return r();let s=performance.now(),c=`error`,l;try{let e=r();return c=`ok`,l=i===`all`&&Array.isArray(e)?e.length:i===`get`?Number(e!==void 0):void 0,e}finally{let t=performance.now()-s;n!==void 0&&o?.(n,t,l),a.hasSubscribers&&a.publish({engine:e,sql:n===void 0?void 0:normalizeSql(e,n),threadId:Sr,outcome:c,durationMs:t})}}function observeConnection(e){if(bd.has(e))return e;bd.add(e);let t=e.exec.bind(e),n=e.prepare.bind(e);return e.exec=e=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>t(e)),e.prepare=e=>{let t=n(e);for(let n of[`get`,`all`,`run`]){let r=t[n].bind(t);Object.defineProperty(t,n,{configurable:!0,writable:!0,value:(...t)=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>r(...t),n===`run`?void 0:n)})}let r=t.iterate.bind(t);return t.iterate=(...t)=>{let n=r(...t),i=statementTiming;if(!yd.statement.hasSubscribers&&!i)return n;let a=0,o=0,s=!1,c=!1,finish=t=>{c||(c=!0,s&&(i?.(e,a,o),yd.statement.hasSubscribers&&yd.statement.publish({engine:`sqlite`,sql:normalizeSql(`sqlite`,e),threadId:Sr,outcome:t,durationMs:a})))},step=e=>{if(c)return e();let t=performance.now();try{let n=e();return a+=performance.now()-t,n.done?finish(`ok`):o++,n}catch(e){throw a+=performance.now()-t,finish(`error`),e}},l={next:(...e)=>(s=!0,step(()=>n.next(...e))),return:e=>step(()=>n.return?.(e)??{done:!0,value:e}),[Symbol.iterator](){return this}};return Object.setPrototypeOf(l,Object.getPrototypeOf(n)),l},t},e}const xd=1e3,Sd=1e3,Cd=Symbol.for(`openclaw.sqliteAbortedTransaction`);function assertTransactionUsable(e){if(y(e))return;let t=e[Cd];if(t)throw t.error}const wd=ct(`sqlite/transaction`),Td=n(Symbol.for(`openclaw.sqliteWriteAdmissionServices`),()=>/* @__PURE__ */ new Map),Ed=/* @__PURE__ */ new WeakMap;function writeAdmissionLocation(e){let t=Ed.get(e);if(t!==void 0)return t;let n=e.location(),r=n===null?null:hn(n);return Ed.set(e,r),r}function retainSqliteWriteAdmissionService(e,t){let n=[...new Set(e.map(hn))].map(e=>{let n=Td.get(e)??/* @__PURE__ */ new Set,retained=()=>t();return n.add(retained),Td.set(e,n),{location:e,services:n,retained}});return()=>{for(let{location:e,services:t,retained:r}of n)t.delete(r),t.size===0&&Td.get(e)===t&&Td.delete(e)}}function execNativeBegin(e,t){let n=Date.now();t.nativeAttempts+=1;try{e.exec(`BEGIN IMMEDIATE`)}finally{t.nativeMs+=Date.now()-n}}function beginImmediateTransaction(e,t){let n=Td.size>0?writeAdmissionLocation(e):null,r=n===null?void 0:Td.get(n);if(!r){execNativeBegin(e,t);return}let i=performance.now()+nr(e);for(;;)try{or(e,Math.min(25,Math.max(0,Math.ceil(i-performance.now()))),()=>execNativeBegin(e,t));return}catch(e){if(!Ht(e)||performance.now()>=i)throw e;for(let e of r){let n=Date.now();t.serviceCalls+=1;try{e()}finally{t.serviceMs+=Date.now()-n}}if(performance.now()>=i)throw e}}function slowBusyWaitThresholdMs(e){return e?.busyTimeoutMs===void 0||e.busyTimeoutMs<=0?xd:Math.min(xd,e.busyTimeoutMs)}function transactionDiagnosticLabels(e,t){let n=t?.databaseLabel;if(!n)try{n=e?e.location()??`:memory:`:`unavailable`}catch{n=`unavailable`}return{database:n,operation:t?.operationLabel||wn()?.operation||`unlabeled`,...t?.diagnosticContext?{context:{...t.diagnosticContext}}:{}}}function logTransactionStep(e,t){try{if(!t&&e.elapsedMs<slowBusyWaitThresholdMs(e.options))return;let n=t?qt(t.error):void 0,r=t?Wt(t.error):void 0;(e.options?.logger??wd).warn(t?`SQLite transaction lock wait failed`:`slow SQLite transaction step`,{async:!1,...e.options?.busyTimeoutMs===void 0?{}:{busyTimeoutMs:e.options.busyTimeoutMs},...transactionDiagnosticLabels(e.db,e.options),...t?{code:tn(t.error)}:{},elapsedMs:e.elapsedMs,...e.holderAtWaitStart?{holderAtWaitStart:e.holderAtWaitStart}:{},...t?{failureKind:`lock-contention`}:{},isMainThread:xr,pid:process.pid,...n===void 0?{}:{sqliteErrcode:n},...r===void 0?{}:{sqlitePrimaryCode:r},step:e.step,threadId:Sr,...e.beginAdmission?{beginAdmission:{...e.beginAdmission}}:{}})}catch{}}function execTimedTransactionStep(e){let t=Date.now(),n=e.sql===`BEGIN IMMEDIATE`?{nativeAttempts:0,nativeMs:0,serviceCalls:0,serviceMs:0}:void 0,r=n?_n(e.db,t):void 0;try{n?beginImmediateTransaction(e.db,n):e.db.exec(e.sql);let i=Date.now()-t;return logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:i,holderAtWaitStart:r,options:e.options,step:e.step}),i}catch(i){let a=Date.now()-t;throw Ht(i)&&er(e.db)&&(e.step!==`begin`||e.options?.beginLockFailureReporting!==`suppress`)&&logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:a,holderAtWaitStart:r,options:e.options,step:e.step},{error:i}),i}}function discardUnsafeConnection(e,t){let n={error:t};e[Cd]??=n;try{Vt(e,t)}catch(t){throw e[Cd]===n&&(n.error=t),t}finally{qn(e);try{e.close()}catch{}}}function abortImmediateTransaction(e,t,n){if(!e[Cd]){if(!n&&e.isOpen&&!e.isTransaction)Vt(e,t,`rolled-back`);else try{e.exec(`ROLLBACK`)}catch{discardUnsafeConnection(e,t)}}}function runSqliteTransactionSync(e,t,n,r){if(e.isTransaction){e.exec(`SAVEPOINT openclaw_tx_nested`);try{let n=Wn(e,t);return zt(n),assertTransactionUsable(e),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`),n}catch(t){let n=e[Cd];if(n)throw n.error;try{e.exec(`ROLLBACK TO SAVEPOINT openclaw_tx_nested`),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`)}catch{discardUnsafeConnection(e,t)}throw t}}let i=xn(),a=i?Date.now()-i.preparedAtMs:void 0,o=execTimedTransactionStep({db:e,options:r,sql:n===`immediate`?`BEGIN IMMEDIATE`:`BEGIN`,step:`begin`});return i&&(i.transactions.count+=1),settleSqliteTransactionSync(e,t,n,o,a,r)}function settleSqliteTransactionSync(e,t,n,r,i,a,o=!1){let s=xn(),c=Date.now(),l=n===`immediate`?Tn(e):void 0;l&&mn(l,a?.operationLabel||wn()?.operation||`unlabeled`,c);let u=s?.hostAdmissionWaitMs??0,d=s?.databaseAdmissionWaitMs??0,f=0,commit=()=>{let t=Date.now(),n=s?.databaseAdmissionWaitMs??0;try{Nt(e),execTimedTransactionStep({db:e,options:a,sql:`COMMIT`,step:`commit`})}finally{f+=Date.now()-t-((s?.databaseAdmissionWaitMs??0)-n)}},p=!1,m=a?.operationLabel||wn()?.operation,h=m?.startsWith(`sessions.transcript-hydration.`)===!0,g;try{let n=m&&attributesSqliteStatements(m)?startSqliteStatementTiming(h):void 0,r;try{r=o?t():Wn(e,t)}finally{g=n?.()}return zt(r),assertTransactionUsable(e),p=!0,a?.withCommit?zt(a.withCommit(commit)):commit(),r}catch(t){throw abortImmediateTransaction(e,t,p),assertTransactionUsable(e),t}finally{l&&Atomics.compareExchange(l,1,Sr+1,0);try{s?.diskRead&&(s.diskRead.context=a?.diagnosticContext);let t=Date.now()-c,o=(s?.hostAdmissionWaitMs??0)-u,l=(s?.databaseAdmissionWaitMs??0)-d,p=Math.max(0,t-o-l-f);t<(a?.slowTransactionHoldMs??Sd)||(a?.logger??wd).warn(`slow SQLite transaction hold`,{async:!1,callbackKind:`application-transaction`,isMainThread:xr,mode:n,pid:process.pid,threadId:Sr,...transactionDiagnosticLabels(e,a),...s?.holdContext||h&&s?.hydrationActiveEvents!==void 0?{context:Cn(a?.diagnosticContext,h)}:{},elapsedMs:t,phases:{prepareMs:i,beginMs:r,sqlMs:p,...g?{statementExecutionMs:Math.round(g.totalMs*100)/100,callbackOtherMs:Math.round(Math.max(0,p-g.totalMs)*100)/100,callbackGcMs:g.callbackGcMs===void 0?void 0:Math.round(g.callbackGcMs*100)/100}:{},hostAdmissionWaitMs:o,databaseAdmissionWaitMs:l,commitMs:f},...g?{statementTiming:g.summarize()}:{},thresholdMs:a?.slowTransactionHoldMs??Sd})}catch{}finally{s&&(s.preparedAtMs=Date.now(),s.hydrationActiveEvents!==void 0&&(s.hydrationActiveEvents=void 0))}}}function runSqliteDeferredTransactionSync(e,t,n){return y(e)?e.runTransaction(t,n):(assertTransactionUsable(e),Mt(e,()=>runSqliteTransactionSync(e,t,`deferred`,n)))}function runSqliteReadSnapshotSync(e,t,n){if(y(e)){if(e.isTransaction){let e=t();return zt(e),e}return e.runTransaction(t,n,!0)}if(assertTransactionUsable(e),!e.isTransaction)return runSqliteDeferredTransactionSync(e,t,n);let r=Wn(e,t);return zt(r),assertTransactionUsable(e),r}function runSqliteImmediateTransactionSync(e,t,n){return y(e)?e.runTransaction(t,n):(assertTransactionUsable(e),Mt(e,()=>runSqliteTransactionSync(e,t,`immediate`,n)))}function runSqliteSingleStatementSync(e,t){return y(e)?e.runTransaction(t):(assertTransactionUsable(e),Mt(e,()=>{let n=Td.size>0?writeAdmissionLocation(e):null;if(e.isTransaction||n!==null&&Td.has(n))return runSqliteTransactionSync(e,t,`immediate`);let r=Wn(e,t);return zt(r),r}))}const Dd={name:`openclaw.quarantine.schema`,lifetime:`process`,schemaDependent:!0,read(e){if(typeof e==`object`&&e&&`version`in e&&typeof e.version==`number`)return{version:e.version}}};function quarantineDecisionAdmission(e){return{name:`openclaw.quarantine.decision:${x.resolve(e)}`,lifetime:`process`,read:e=>e===null||isQuarantineDecision(e)?e:void 0}}function isQuarantineDecision(e){return We(e)&&(e.kind===`agent`||e.kind===`state`)&&typeof e.reason==`string`&&typeof e.quarantinedAt==`number`&&(e.verifiedGenerationJson===null||typeof e.verifiedGenerationJson==`string`)}function readQuarantineSchemaVersion(e,t,n=!1){let r=n?void 0:nn(e,Dd);if(r)return r.version;let i=e.prepare(`PRAGMA user_version`).get()?.user_version;if(typeof i!=`number`||!Number.isInteger(i))throw Error(`OpenClaw quarantine store ${t} has an invalid schema version.`);if(i>2)throw Error(`OpenClaw quarantine store ${t} uses newer schema version ${i}.`);return i!==0&&cn(e,Dd,{version:i}),i}function readOpenClawDatabaseQuarantine(e,t={}){let n=de(t.env??process.env);t.refreshIdentity&&Gt(n);let load=()=>readPersistedQuarantineDecision(e,n,t.fresh)??null,r=t.fresh?load():Zt(n,quarantineDecisionAdmission(e),load);return r?resolveQuarantineDecision(r,e,n):void 0}function readPersistedQuarantineDecision(e,t,n=!1){if(!mr(t))return;let r=openSqliteReadOnlyDatabase(t,{timeout:5e3}),i;try{i={value:readQuarantineDecision(r,e,t,n)}}catch(e){i={error:e}}try{r.close()}catch(n){let r,a=`error`in i?i.error:void 0;if(`value`in i&&i.value)try{r=resolveQuarantineDecision(i.value,e,t)}catch(e){a=e}throw new g(a===void 0?[n]:[a,n],r)}if(`error`in i)throw i.error;return i.value}function readQuarantineDecision(e,t,n,r=!1){let i=readQuarantineSchemaVersion(e,n,r);if(i===0)return;let a=i>=2?`, verified_generation`:``,o=e.prepare(`SELECT kind, reason, quarantined_at${a} FROM quarantined_databases WHERE path = ? LIMIT 1`).get(x.resolve(t));if(!o)return;let s=i>=2?o.verified_generation:void 0;if(o.kind!==`agent`&&o.kind!==`state`||typeof o.reason!=`string`||typeof o.quarantined_at!=`number`||!Number.isInteger(o.quarantined_at)||s!=null&&typeof s!=`string`)throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`);return{kind:o.kind,quarantinedAt:o.quarantined_at,reason:o.reason,verifiedGenerationJson:typeof s==`string`?s:null}}function resolveQuarantineDecision(e,t,n){if(e.verifiedGenerationJson!==null){let r;try{r=parseSqliteFileGeneration(e.verifiedGenerationJson)}catch{throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`)}try{let e=readSqliteFileGenerationSync(x.resolve(t));if(!sameSqliteFileGeneration(r,e))return}catch{return}}return{kind:e.kind,quarantinedAt:e.quarantinedAt,reason:e.reason}}function readOpenClawDatabaseQuarantineFailure(e,t,n={}){let r,i;try{r=readOpenClawDatabaseQuarantine(t,n)}catch(e){if(!(e instanceof g))return;if(!e.quarantine)throw e;r=e.quarantine,i=e}if(!r)return;let a=/* @__PURE__ */ Error(`OpenClaw ${e} database ${t} is quarantined after integrity verification failed: ${r.reason??`unknown integrity error`}. Restore the database from a backup or repair it, then run openclaw doctor --fix to clear the quarantine. See ${ae}.`);return a.name=`SqliteIntegrityError`,i&&(a.cause=i),a}function createStateDatabaseRetainer(e,t){let admit=(e,n,r)=>{let i=it();return n===`cached-read`?i?.assertReadAdmission():i?.assertAdmission(),t.assertOpen(e,n,r),i},retain=(n,r,i=!1)=>{if(t.capture(n.path).assertCurrent(),e.cachedDatabases.get(n.path)!==n||!n.db.isOpen)throw Error(`OpenClaw state database borrow requires its current canonical handle`);let a=e.borrowers.get(n.db)??{references:/* @__PURE__ */ new Set,retiring:!1,cleanupComplete:!1};if(a.retiring)throw Error(`OpenClaw state database native owner is retiring`);i||rt(n.db),e.borrowers.set(n.db,a);let isCurrent=()=>!r||nt(n.db,r),o=i?void 0:{ordinary:r===void 0,isCurrent,retire:()=>{isCurrent()?t.retire(n,r===void 0):a.retiring=!1}};function createAsyncStateDatabaseRetirement(){let e={},r,i,finish=r=>{a.references.delete(e),a.releaseJoin?a.releaseJoin.resolve():r?.isCurrent()?r.retire():a.retiring=!1,a.retirement=void 0,a.asyncRetirement=void 0,i?.(),i=void 0,a.releaseJoin||t.touch(n)},run=()=>r||(a.cleanupComplete||a.references.size>+!!a.references.has(e)?Promise.resolve():a.retirement?.isCurrent()?(a.retiring=!0,a.references.add(e),i??=t.ownRetirement(n,close),r=Promise.resolve().then(async()=>{await n.walMaintenance.stop(),finish(a.retirement)}).catch(r=>{throw a.references.add(e),t.retainFailed(n),a.releaseJoin?.reject(r),a.releaseJoin=void 0,r}),r.catch(()=>{}),r):(finish(),Promise.resolve()));function close(){let e=run();return e.catch(t=>{throw r===e&&(r=void 0),t})}return{start:()=>void run(),close}}let s={};a.references.add(s);let c=!1,release=()=>{if(c||a.cleanupComplete)c=!0;else if(c=!0,a.references.delete(s),a.releaseJoin)a.references.size===0&&a.releaseJoin.resolve();else if(a.retirement&&!a.retirement.isCurrent()&&(a.retirement=void 0,a.asyncRetirement=void 0,a.retiring=!1),o?.isCurrent()&&!a.retirement?.ordinary&&(a.retirement=o),!(a.references.size>0)){if(!a.retirement)t.touch(n);else if(a.retiring=!0,a.asyncRetirement)a.asyncRetirement.start();else{try{a.retirement.retire()}catch(e){throw c=!1,t.retainFailed(n),e}a.retirement=void 0,t.touch(n)}}},l={release,async releaseAsync(){a.cleanupComplete||(a.releaseJoin?release():((o?.isCurrent()&&!a.retirement?.ordinary?o:a.retirement)?.isCurrent()&&(a.asyncRetirement??=createAsyncStateDatabaseRetirement()),release(),await a.asyncRetirement?.close()))}};return r?.own(l,`shared-references`,()=>l.releaseAsync()),l},findReadDatabase=(t,n,r)=>{let i=v({path:t}),a=e.cachedDatabases.get(i);return a?.db.isOpen?{database:a,scope:admit(i,n,r)}:{database:void 0,scope:void 0}},retainReadReference=(t,n)=>{let r=retain(t,n,!0),assertCurrent=()=>{if(e.cachedDatabases.get(t.path)!==t||!t.db.isOpen)throw Error(`Shared-state read lost its original native owner`)};return{assertCurrent,observe(){assertCurrent(),rt(t.db)},release:()=>r.release()}};return{retain:e=>retain(e,admit(e.path)),retainForIndependentRead(e,t,n){let{database:r,scope:i}=findReadDatabase(e,t,n);return r?retainReadReference(r,i):void 0},borrowForRead(e,t,n){let{database:r,scope:i}=findReadDatabase(e,t,n);if(r){if(r.db.isTransaction)throw Error(`Asynchronous shared-state reads cannot run inside a native transaction`);return{database:r,...retainReadReference(r,i)}}}}}async function joinStateDatabaseBorrowersReleased(e,t){e&&!e.cleanupComplete&&(e.retiring=!0,e.references.size!==0&&(e.releaseJoin||(e.releaseJoin=dn(),fr()?.warn(`Waiting for ${e.references.size} active native borrower(s) before retiring OpenClaw state database: ${t}`)),await e.releaseJoin.promise))}function assertStateDatabaseBorrowersReleased(e,t){if(e?.references.size)throw Error(`OpenClaw state database still has active native borrowers (${e.references.size}): ${t}`)}function createStateDatabaseCacheAdmission(e){return{closeTerminalFailure(t,n){xe(n,t),Ft(t),e.invalidate(t);let r=e.cachedDatabases.get(t),i=[];try{r&&e.evict(r)}catch(e){i.push(e)}try{e.notifyTerminalFailure(t,n)}catch(e){i.push(e)}jt(i,`Terminal shared-state failure cleanup failed`)},read(t,n){if(!t.db.isOpen)return n(t);let r=!1;try{return Wn(t.db,()=>(r=!0,n(t)))}catch(n){if(r)throw n;let i=n instanceof Error?n:Error(String(n));if(Ut(i)){e.evict(t);return}throw i}}}}const Od=n(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));function getDatabaseProcessRole(){return Od.role}let kd=0;function withEngineStoreAdmission(e){kd+=1;try{let t=e();if(Ct(t))throw Error(`Database engine admission must remain synchronous`);return t}finally{--kd}}function assertEngineStoreExecutionAllowed(){if(Sr===0&&kd===0&&Od.role!==`cli-oneshot`)throw Error(`PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread`)}const Ad=18e5,jd=ct(`state/db`);function createStateDatabaseIdleRetirement({cachedDatabases:e,retainedDatabaseHandles:t,idleTimers:n,idleReferences:r,borrowers:i},a){let touch=o=>{if(!(e.get(o.path)===o&&o.db.isOpen)&&t.get(o.db)!==o)return;let s=n.get(o.db);if(s){s.refresh();return}let c=Ye(()=>setTimeout(()=>{n.delete(o.db);try{o.db.isOpen&&o.db.isTransaction?touch(o):!i.get(o.db)?.references.size&&!r.get(o.db)?.size&&a(o,!1,{busyTimeoutMs:0,checkpointMode:`PASSIVE`})}catch(e){jd.warn(`Idle shared-state database cleanup failed`,{path:o.path,error:e}),touch(o)}},Ad));c.unref(),n.set(o.db,c)};return{touch,retain(t){if(e.get(t.path)!==t||!t.db.isOpen||i.get(t.db)?.retiring)throw Error(`OpenClaw state database idle retention requires its current canonical handle`);let n=r.get(t.db)??/* @__PURE__ */ new Set,a={};return n.add(a),r.set(t.db,n),()=>{n.delete(a)&&e.get(t.path)===t&&t.db.isOpen&&touch(t)}}}}const Md=n(Symbol.for(`openclaw.sqliteWalWriteAdmissions`),()=>/* @__PURE__ */ new WeakMap);function registerSqliteWalWorkerMaintenance(e,t,n){e.exec(`PRAGMA wal_autocheckpoint = 0;`);let r=Md.get(e)?.stopCheckpointTick;Md.set(e,{execute:t,cancel:n}),r?.()}function isSqliteWalWorkerMaintained(e){return Md.get(e)?.execute!==void 0}function cancelSqliteWalWriteAdmission(e){return Md.get(e)?.cancel?.()}function createSqliteWalMaintenanceScheduler(e,t,n,r,i,a,o){let s=Md.get(e);Md.set(e,{...s,stopCheckpointTick:o});let c;return()=>(c||=(async()=>{let i=a(),o=!1;for(;;){let a=n(i);if(!a||i===0&&Md.get(e)?.execute)return;a.continuation=o;let s,admitted=()=>{n(i)&&(s=t(a))},c=Md.get(e);c?.execute?(s=await c.execute(a),s?.checkpoint&&r(s.checkpoint)):c?.admit?await c.admit(admitted):admitted();let l=s?.reclaimedPages??0;if(i-=l,l<=0||i<=0)return;o=!0,await yr()}})().catch(i).finally(()=>{c=void 0}),c)}const Nd=n(Symbol.for(`openclaw.gatewayServiceInstallation`),()=>new Tr);function getGatewayServiceInstallation(){return Nd.getStore()?.installation}function isGatewayExternallySupervised(e=process.env){return e.OPENCLAW_SUPERVISOR_MODE?.trim().toLowerCase()===`external`}function objectPath(e){return Z`string_to_array(substr(${e}, 3), '.')`}function jsonPathValue(e,t,n,r=`text`){if(!y(e))return Z`json_extract(${t}, ${n})`;let i=Z`(${t}::jsonb ${Z.raw(r===`json`?`#>`:`#>>`)} ${objectPath(n)})`;return Z`${i}${Z.raw(r===`number`?`::double precision`:r===`json`?`::text`:``)}`}function jsonValid(e,t){return y(e)?Z`pg_input_is_valid(${t}, 'json')`:Z`json_valid(${t})`}function jsonPickObject(e,t,n){return y(e)?Z`(SELECT coalesce(jsonb_object_agg(key, value), '{}'::jsonb)::text
        FROM jsonb_each(CASE WHEN jsonb_typeof(${t}::jsonb) = 'object' THEN ${t}::jsonb ELSE '{}'::jsonb END)
        WHERE key IN (${Z.join(n)}))`:Z`(SELECT json_group_object(key, CASE type
    WHEN 'object' THEN json(value) WHEN 'array' THEN json(value)
    WHEN 'true' THEN json('true') WHEN 'false' THEN json('false')
    ELSE value END) FROM json_each(${t}) WHERE key IN (${Z.join(n)}))`}const Pd=n(Symbol.for(`openclaw.stateDatabaseSchemaPolicies`),()=>({scopes:new Tr,existingDatabases:/* @__PURE__ */ new WeakMap,hasAdmittedExistingDatabase:!1}));function canonicalPath(e){let n=v({path:e});try{return hn(hr.native(n))}catch(e){if(t(e,`ENOENT`))return n;throw e}}function assertSchemaScopeActive(e){if(e&&!e.active)throw Error(`Existing shared-state schema admission has ended.`)}function getExistingOpenClawStateSchemaPath(){let e=Pd.scopes.getStore();return assertSchemaScopeActive(e),e?.path}function captureOpenClawStateSchemaReadAdmission(e){let t=Pd.scopes.getStore();if(t)return isExistingOpenClawStateSchema(e),{path:t.path,assertCurrent:()=>assertSchemaScopeActive(t)}}function isExistingOpenClawStateSchema(e,t){let n=getExistingOpenClawStateSchemaPath(),r=Pd.scopes.getStore(),i=t&&Pd.existingDatabases.get(t);if(!r&&!i)return!1;let a=v({path:e}),o=n!==void 0&&(n===a||r?.canonicalPath===a||r?.canonicalPath===canonicalPath(a));if(n&&!o)throw Error(`Existing shared-state schema admission is bound to ${n}, not ${e}.`);if(i&&(!o||i!==r?.canonicalPath))throw Error(`Shared-state database ${e} was admitted without schema repair; close its existing handle before ordinary admission.`);return o}function recordExistingOpenClawStateSchemaDatabase(e,t){let n=Pd.scopes.getStore();if(!n||!isExistingOpenClawStateSchema(t,e))throw Error(`Existing shared-state schema admission requires its active path scope.`);Pd.existingDatabases.set(e,n.canonicalPath),Pd.hasAdmittedExistingDatabase=!0}function assertExistingOpenClawStateSchemaCacheAdmission(e,t){let n=getExistingOpenClawStateSchemaPath();if(!Pd.hasAdmittedExistingDatabase)return;let r=Pd.scopes.getStore(),i=r?v({path:e}):void 0,a=r&&(n===i||r.canonicalPath===i)?r.canonicalPath:void 0;for(let n of[t.cachedDatabases,t.retainedDatabaseHandles])for(let{db:t}of n.values()){let n=Pd.existingDatabases.get(t);n&&t.isOpen&&(a??=canonicalPath(e),n===a&&isExistingOpenClawStateSchema(e,t))}}function captureSqliteWorkerStateContext(e){return{databaseEngineSelection:e.databaseEngineSelection??ut(),environment:{...e.environment},initializationCronDefaultStoreKey:e.initializationCronDefaultStoreKey,...e.initializationEnvironment?{initializationEnvironment:{...e.initializationEnvironment}}:{},...e.initializationAgentPaths?{initializationAgentPaths:[...e.initializationAgentPaths]}:{},existingSchemaPath:e.existingSchemaPath,gatewayServiceInstallation:e.gatewayServiceInstallation,...e.stateIntegrity?{stateIntegrity:e.stateIntegrity}:{},artifactPreservingReads:e.artifactPreservingReads,liveStateReads:e.liveStateReads,...e.scheduledMaintenanceSuspension?{scheduledMaintenanceSuspension:e.scheduledMaintenanceSuspension}:{}}}function sqliteWorkerRequestBytes(e,t,n){let r=t?.initializationAgentPaths?.reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0)??0;return[t?.environment,t?.initializationEnvironment].reduce((e,t)=>Object.entries(t??{}).reduce((e,[t,n])=>e+Buffer.byteLength(t,`utf8`)+Buffer.byteLength(n??``,`utf8`),e),e.byteLength+Buffer.byteLength(JSON.stringify(t?.databaseEngineSelection)??``,`utf8`)+Buffer.byteLength(JSON.stringify(t?.gatewayServiceInstallation)??``,`utf8`)+(n?.byteLength??0)+r+Buffer.byteLength(t?.initializationCronDefaultStoreKey??``,`utf8`)+(t?.scheduledMaintenanceSuspension?.byteLength??0))}const Fd=n(Symbol.for(`openclaw.sqliteWorkerStateContext`),()=>new Tr);function captureSqliteWorkerWalMaintenanceSuspension(){let e=Fd.getStore()?.scheduledMaintenanceSuspension;if(!e)return;let t=new Int32Array(e);return()=>Atomics.load(t,0)>0}function getSqliteWorkerCronDefaultStoreKey(){return Fd.getStore()?.initializationCronDefaultStoreKey}function getSqliteWorkerExistingDatabaseIdentity(e){let t=Fd.getStore()?.existingDatabase;return t?.databasePath===e?t.identity:void 0}function getSqliteWorkerStateIntegrityAdmission(){return Fd.getStore()?.stateIntegrity}var SqliteSchemaMismatchError=class extends Error{constructor(...e){super(...e),this.name=`SqliteSchemaMismatchError`}};function isSqliteSchemaMismatchError(e){return e instanceof Error&&e.name===`SqliteSchemaMismatchError`}const Id={"missing-table":`missing table`,"missing-column":`column definitions differ for`,"unexpected-column":`column definitions differ for`,"column-definition-drift":`column definitions differ for`,"table-constraint-drift":`table constraints differ for`,"table-definition-drift":`table definition differs for`,"missing-or-drifted-index":`missing or drifted index`,"unexpected-unique-index":`unexpected unique index`,"missing-or-drifted-trigger":`missing or drifted trigger`,"missing-or-drifted-view":`missing or drifted view`,"unexpected-trigger":`unexpected trigger`,"virtual-table-definition-drift":`virtual table definition differs for`,"table-options-drift":`table options differ for`};function isColumnIssue(e){return e===`column-definition-drift`||e===`missing-column`||e===`unexpected-column`}function defaultIssueMessage(e,t){let n=isColumnIssue(e)?t.split(`.`,1)[0]:t;return`${Id[e]} ${n}`}function createSqliteSchemaIssue(e,t,n){return{code:e,objectName:t,message:n??defaultIssueMessage(e,t)}}function legacySqliteSchemaIssueMessages(e){let t=new Set(e.filter(e=>isColumnIssue(e.code)).map(e=>e.objectName.split(`.`,1)[0]));return[...new Set(e.filter(e=>e.code!==`table-constraint-drift`||!t.has(e.objectName)).map(e=>e.message))]}function throwSqliteSchemaMismatches(e,t){let n=t.slice(0,8);throw t.length>n.length&&n.push(`${t.length-n.length} additional mismatch(es)`),new SqliteSchemaMismatchError(`SQLite schema is incomplete or noncanonical for ${e}: ${n.join(`; `)}; run openclaw doctor --fix to repair it.`)}const Ld=/* @__PURE__ */ new WeakMap;function readCanonicalTableDefinition(e,t){if(!/^CREATE TABLE\b/iu.test(e)||kt(e,/\bAS\b/giu))return;let n=ln(e,t);return[...n.columns.values()].every(e=>{let t=It(e,0);return t?.keyword!==`CONSTRAINT`&&/^[a-z_][a-z0-9_]*$/u.test(t?.raw??``)})?n:void 0}function tableHasColumn(e,t,n){return readTableColumns(e,t).has(n)}function readTableColumns(e,t){if(y(e)){let n=Kn(e);if(!n){let n=e.prepare(`SELECT a.attname AS name FROM pg_catalog.pg_attribute a
        JOIN pg_catalog.pg_class c ON c.oid = a.attrelid
        WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ?
          AND a.attnum > 0 AND NOT a.attisdropped
        ORDER BY a.attnum`).all(t);return new Set(n.map(e=>String(e.name)))}return new Set(n.catalog.flatMap(e=>e.table===t&&e.kind===`column`&&e.value&&typeof e.value==`object`&&`name`in e.value&&typeof e.value.name==`string`?[e.value.name]:[]))}let n=Jn(e),r=n?.tableSql.get(t);if(n&&!r&&![...n.tables,...n.views].some(e=>e.toLowerCase()===t.toLowerCase()))return/* @__PURE__ */ new Set;if(n&&r){let e=Ld.get(n),i=e?.get(t);if(i)return i;let a=readCanonicalTableDefinition(r,t);if(a){let r=new Set(a.columns.keys());return e||(e=/* @__PURE__ */ new Map,Ld.set(n,e)),e.set(t,r),r}}let i=e.prepare(`PRAGMA table_info(${t})`).all();return new Set(i.flatMap(e=>typeof e.name==`string`?[e.name]:[]))}function classifySqliteTableReadError(e,t,n,r){if(y(e)||Wt(r)!==1)return r;try{let i=readTableColumns(e,t);if(i.size>0&&n.some(e=>!i.has(e)))return new SqliteSchemaMismatchError(`SQLite table ${t} is missing required columns; run openclaw doctor --fix to repair it.`,{cause:r})}catch{}return r}function tablePrimaryKeyColumns(e,t){if(y(e)){let n=Kn(e);if(!n)return e.prepare(`SELECT a.attname AS name FROM pg_catalog.pg_index i
        JOIN pg_catalog.pg_class c ON c.oid = i.indrelid
        CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, position)
        JOIN pg_catalog.pg_attribute a ON a.attrelid = c.oid AND a.attnum = k.attnum
        WHERE c.relnamespace = current_schema()::regnamespace AND c.relname = ? AND i.indisprimary
        ORDER BY k.position`).all(t).map(e=>String(e.name));let r=n.catalog.find(e=>e.table===t&&e.kind===`primaryKey`)?.value;return Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}let n=Jn(e)?.tableSql.get(t),r=n&&readCanonicalTableDefinition(n,t);if(r){let e=r.constraints.find(e=>{let t=It(e,0);return t&&Yt(e,t)===`PRIMARY`});if(!e)return[...r.columns].flatMap(([e,t])=>kt(t,/\bPRIMARY\s+KEY\b/giu)?[e]:[]);let t=sn(e,`(`),n=Dt(e.slice(t+1,Lt(e,t))).map(e=>Rt(It(e,0)?.raw??``));if(n.every(e=>r.columns.has(e)))return[...new Set(n)]}return e.prepare(`PRAGMA table_info(${t})`).all().filter(e=>Number(e.pk??0)>0&&typeof e.name==`string`).toSorted((e,t)=>Number(e.pk??0)-Number(t.pk??0)).map(e=>e.name)}function tableExists(e,t){if(y(e)){let n=Kn(e);return n?n.catalog.some(e=>e.table===t&&e.kind===`table`):e.prepare(`SELECT 1 AS present FROM pg_catalog.pg_class
      WHERE relnamespace = current_schema()::regnamespace AND relname = ? AND relkind IN ('r', 'p')`).get(t)?.present===1}let n=Jn(e);return n?n.tables.has(t):Rn(e,`SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?`,[t],e=>e.get(t))?.ok===1}function ensureColumn(e,t,n){let r=n.trim().split(/\s+/,1)[0];return!r||!tableExists(e,t)||tableHasColumn(e,t,r)?!1:(e.exec(`ALTER TABLE ${t} ADD COLUMN ${n};`),!0)}const Rd=`cron.defaultStoreKey`;function resolveLegacyCronDefaultStoreKey(e){return x.resolve(Ke(e),`cron`,`jobs.json`)}function resolveCronIdentityMigrationDefaultStoreKey(e){return getSqliteWorkerCronDefaultStoreKey()??resolveLegacyCronDefaultStoreKey(e)}function readBindingRow(e,t){if(t?.has(`config_machine_state`)??tableExists(e,`config_machine_state`))return executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`config_machine_state`).select(`value_json`).where(`state_key`,`=`,Rd))}function resolveUnboundCronDefaultStoreKey(e,t){return e.length===0||e.some(e=>e.storeKey===t)?t:void 0}const zd=[[`cron_jobs`,`jobs`],[`cron_job_scratch`,`scratch`],[`cron_run_receipts`,`receipts`]];function readCronStorePartitionInventoryInDatabase(e,t){let n=/* @__PURE__ */ new Map,add=(e,t,r)=>{if(typeof e!=`string`||e.length===0)return;let i=n.get(e);i||(i={storeKey:e,jobs:0,scratch:0,receipts:0,history:0,quarantine:0,proactiveReceipts:0},n.set(e,i)),i[t]+=r};for(let[n,r]of zd)if(t?.has(n)??tableExists(e,n)){let t=getNodeSqliteKysely(e).selectFrom(n).select(`store_key`).select(e=>e.fn.countAll().as(`count`)).groupBy(`store_key`);for(let n of executeSqliteQuerySync(e,t).rows)add(n.store_key,r,Number(n.count))}if(t?.has(`cron_run_logs`)??tableExists(e,`cron_run_logs`)){let t=getNodeSqliteKysely(e).selectFrom(`cron_run_logs`).select(`store_key`).select(e=>e.fn.countAll().as(`count`)).groupBy(`store_key`);for(let n of executeSqliteQuerySync(e,t).rows)add(n.store_key,`history`,Number(n.count))}if(t?.has(`task_runs`)??tableExists(e,`task_runs`)){let t=getNodeSqliteKysely(e).selectFrom(`task_runs`).select(t=>[Z`CASE WHEN ${jsonValid(e,t.ref(`detail_json`))}
          THEN ${jsonPickObject(e,t.ref(`detail_json`),[`storeKey`])} END`.as(`detail_json`)]).where(`runtime`,`=`,`cron`);for(let n of executeSqliteQuerySync(e,t).rows)if(typeof n.detail_json==`string`)try{let e=JSON.parse(n.detail_json);We(e)&&add(e.storeKey,`history`,1)}catch{}}if(t?.has(`diagnostic_events`)??tableExists(e,`diagnostic_events`)){let t=getNodeSqliteKysely(e).selectFrom(`diagnostic_events`).select(`scope`).select(e=>e.fn.countAll().as(`count`)).where(`scope`,`like`,`cron.quarantine:%`).groupBy(`scope`);for(let n of executeSqliteQuerySync(e,t).rows)typeof n.scope==`string`&&add(n.scope.slice(16),`quarantine`,Number(n.count))}if(t?.has(`config_machine_state`)??tableExists(e,`config_machine_state`)){let t=getNodeSqliteKysely(e).selectFrom(`config_machine_state`).select(`state_key`).where(`state_key`,`like`,`automation-default:%`);for(let n of executeSqliteQuerySync(e,t).rows)add(n.state_key.slice(19,n.state_key.lastIndexOf(`:`)),`proactiveReceipts`,1)}return[...n.values()].toSorted((e,t)=>e.storeKey<t.storeKey?-1:+(e.storeKey>t.storeKey))}const Bd={version:34,tables:[`config_machine_state`],columns:[],migrate:(e,t,n)=>migrateCronDefaultStoreIdentity(e,{previousVersion:t,legacyDefaultStoreKey:n.legacyCronDefaultStoreKey??resolveCronIdentityMigrationDefaultStoreKey(n.env)}),applied:`Introduced durable default cron partition selection (v34)`};function migrateCronDefaultStoreIdentity(e,t){if(t.previousVersion>=34||readBindingRow(e,t.sourceTables))return!1;let n=t.fresh?t.legacyDefaultStoreKey:void 0;if(!t.fresh){if(zd.some(([n])=>(t.sourceTables?.has(n)??tableExists(e,n))&&executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(n).select(`store_key`).where(`store_key`,`=`,t.legacyDefaultStoreKey).limit(1))))n=t.legacyDefaultStoreKey;else{let r=readCronStorePartitionInventoryInDatabase(e,t.sourceTables);n=resolveUnboundCronDefaultStoreKey(r,t.legacyDefaultStoreKey)??(r.length===1?r[0]?.storeKey:void 0)}}return n!==void 0&&(executeSqliteQuerySync(e,getNodeSqliteKysely(e).insertInto(`config_machine_state`).values({state_key:Rd,value_json:JSON.stringify(n),updated_at_ms:t.nowMs??Date.now()})),!0)}function captureOpenClawStateReadContextWithAdmission(e,t,n,r){let i=captureOpenClawStateSchemaReadAdmission(e),a=t(e,r),o=getGatewayServiceInstallation(),s=a.captureIntegrity?.(),c=a.assertCurrent,l=a,runInCapturedSchemaScope;if(i){let e=Tr.snapshot();l={databasePath:a.databasePath,coordinationKey:a.coordinationKey,get identity(){return a.identity},captureIntegrity:a.captureIntegrity,assertCurrent(){a.assertCurrent(),i.assertCurrent()}},runInCapturedSchemaScope=t=>e(()=>(l.assertCurrent(),t()))}return{databaseEngineSelection:ut(),maintenanceScope:it(),admission:l,assertPublicationCurrent:c,existingSchemaPath:i?.path,gatewayServiceInstallation:o&&n(o.databasePath)?.key===a.identity.key?o:void 0,stateIntegrity:s,runInCapturedSchemaScope,artifactPreservingReads:m(`agent`,e)||void 0,liveStateReads:se()||void 0}}function captureOpenClawStateReadWorkerContextWithAdmission(e,t,n){let r=e.env??process.env,i=process.platform===`win32`?cloneEnvWithPlatformSemantics(r):r,a={OPENCLAW_STATE_DIR:qe(i),...isGatewayExternallySupervised(i)?{OPENCLAW_SUPERVISOR_MODE:`external`}:{}};return{...captureOpenClawStateReadContextWithAdmission(e.path??we(a),t,n),environment:a}}function captureOpenClawStateWorkerContextWithAdmission(e,t,n){let r=captureOpenClawStateReadWorkerContextWithAdmission(e,t,n);return{...r,initializationCronDefaultStoreKey:resolveLegacyCronDefaultStoreKey(e.env??process.env),initializationEnvironment:En([e.env??process.env,{OPENCLAW_STATE_DIR:void 0,OPENCLAW_SUPERVISOR_MODE:void 0},r.environment]),...e.initializationAgentPaths?{initializationAgentPaths:e.initializationAgentPaths.map(e=>x.resolve(e))}:{}}}function createStateDatabaseWalOwner({cachedDatabases:e,retainedDatabaseHandles:t,databaseIdentities:n,asyncResources:r},i,a){return{ownRetirement(e,t){let n={admission:{identity:a(e)},close:t},i=r.register(n);return tt(e.db)?.own(n,`shared-references`,()=>n.close()),i},async stop(r,i){let a=/* @__PURE__ */ new Set([...t.values(),...e.values()]);await Promise.all([...a].filter(e=>r===void 0||e.path===r||i!==void 0&&n.get(e.db)?.key===i.key).flatMap(({walMaintenance:e})=>e?[e.stop()]:[]))},register(t,n,a,o){if(!xr||y(t.db))return;let s=captureOpenClawStateWorkerContextWithAdmission({path:t.path,env:o},()=>a,r.knownIdentity),c=new AbortController,l,cancel=()=>{if(c.abort(),!l)d();else return l.then(()=>void 0,()=>void 0)},u={admission:{identity:n},async close(){cancel(),await t.walMaintenance.stop(),d()}},d=r.register(u),run=async r=>{let a=tt(t.db),o={...s,maintenanceScope:a},assertCurrent=()=>{if(c.signal.throwIfAborted(),o.admission.assertCurrent(),a?.assertAdmission(),tt(t.db)!==a||e.get(t.path)!==t||!t.db.isOpen)throw new be(`Shared-state WAL maintenance owner changed`)},l,u=!1;try{assertCurrent(),l=i(t);let{runOpenClawStateWorkerOperation:e}=await import(`./fs-safe-copy.worker-openclaw-state-worker-store-B3TSh4Ne.mjs`);return assertCurrent(),await e(o,e=>e.execute({type:`database.walMaintenance`,input:r},{signal:c.signal}),{existingOnly:!0,assertCurrent,createAdmission:()=>({nativeLocations:[t.path,n.canonicalPath],databaseIdentity:{databasePath:t.path,key:n.key,birthtime:n.birthtime},admission:St((e,t)=>{if(assertCurrent(),!t())throw new be(`Shared-state WAL maintenance authority expired`);u=!0})})})}catch(e){if(!u&&(he(e)||c.signal.aborted&&Je(e)))return;throw e}finally{l?.()}};registerSqliteWalWorkerMaintenance(t.db,e=>{if(c.signal.aborted)return Promise.resolve(void 0);let t=run(e);return l=t,t.finally(()=>{l===t&&(l=void 0),c.signal.aborted&&d()})},cancel)},readHealth(){let t=e.get(x.resolve(we()));return t?.db.isOpen?t.walMaintenance.health:void 0}}}const Vd=n(Symbol.for(`openclaw.stateNativeIdentities`),()=>/* @__PURE__ */ new WeakMap);function readTrackedStateDatabaseIdentity(e){return Vd.get(At(e))}function openTrackedStateDatabase(e,t){let n=openTrackedStateDatabaseResult(e,t);if(n.status===`unavailable`)throw n.error;return n.database}function openTrackedStateDatabaseResult(e,t){assertStateDatabaseAccessAllowed(e);try{t?.expectedIdentity!==void 0&&yn(e,t.expectedIdentity);let n=t?.existingOnly||t?.expectedIdentity!==void 0?tr(e):e,r=t?.readOnly?{readOnly:!0,timeout:t.timeout}:{enableForeignKeyConstraints:t?.enableForeignKeyConstraints},i=gn(e),a=Qt(()=>ir(n,r));try{assertStateDatabaseAccessAllowed(e),i.key.startsWith(`file:`)&&yn(e,i.key,i.birthtime);let t=i.key.startsWith(`file:`)?i:gn(e);if(t.key.startsWith(`file:`)){Vd.set(a,t);let e=Ln(a,()=>{Vd.delete(a),e()})}}catch(e){throw a.close(),e}return{status:`available`,database:a}}catch(e){return{status:`unavailable`,error:e}}}function closeTrackedStateDatabase(e){e.isOpen&&e.close()}function closeStateDatabaseHandle(e,t){try{var n=un();let r=[];if(y(e.db)){for(let t of[e.db,e.db.anchor]){if(t===e.db.anchor&&e.db.isOpen)break;try{t.isOpen&&t.close()}catch(e){r.push(e)}}let t=e.db.isOpen||e.db.anchor.isOpen;if(!t)try{e.afterClose?.()}catch(e){r.push(e),t=!0}return{errors:r,cleanupPending:t}}let i=n.u(on(e.db)),a=isSqliteWalWorkerMaintained(e.db),o=e.walMaintenance?.health?.state===`error`,s=!1;try{e.db.isOpen&&!a&&$n(e.db,0),s=e.walMaintenance?.close(t)===!0&&t?.checkpointMode!==`PASSIVE`}catch(e){r.push(e)}try{qn(e.db)}catch(e){r.push(e)}try{closeTrackedStateDatabase(e.db)}catch(e){r.push(e)}let c=!1;if(!e.db.isOpen)try{e.afterClose?.()}catch(e){r.push(e),c=!0}return r.length===0&&!c&&t?.checkpointMode!==`PASSIVE`&&(s||a&&!o)&&i.publish(),{errors:r,cleanupPending:c}}catch(e){n.e=e}finally{n.d()}}function getStateSchemaFacts(e){return y(e)?Kn(e):Jn(e)}const Hd={name:`state.schema-version`,lifetime:`process`,schemaDependent:!0,read(e){if(typeof e==`object`&&e&&`userVersion`in e&&typeof e.userVersion==`number`&&`contentVersion`in e&&typeof e.contentVersion==`number`)return{userVersion:e.userVersion,contentVersion:e.contentVersion}}};function createStateSchemaAdmission(e,t,n){let r={name:e,lifetime:n,schemaDependent:!0,read(e){if(typeof e!=`object`||!e||!(`value`in e)||!(`admissionId`in e)||typeof e.admissionId!=`string`)return;let n=t(e.value);return n===void 0?void 0:{value:n,admissionId:e.admissionId}}};return{get(e){if(an(e))return;let t=nn(e,r);if(!t)return;let n=getStateSchemaFacts(e);return t.admissionId===n?.admissionId?t.value:void 0},publish(e,t){!y(e)&&Un(e)&&Xn(e);let n=getStateSchemaFacts(e);if(!n||!y(e)&&nn(e,Gn)?.admissionId!==n.admissionId)return;getStateSchemaVersionAdmission(e);let i={value:t,admissionId:n.admissionId};cn(e,r,i)}}}const Ud=createStateSchemaAdmission(`state.runtime-schema`,e=>typeof e==`object`&&e&&`startupReady`in e&&typeof e.startupReady==`boolean`?{startupReady:e.startupReady}:void 0,`process`),Wd=/* @__PURE__ */ new WeakMap;function rememberConnectionVersion(e,t){let n=Wd.get(e),install=t=>{t?Wd.set(e,t):Wd.delete(e)};en(e,{stage:()=>install(t),commit:()=>{},rollback:()=>install(n)})||install(t)}function schemaVersionKey(e){return{name:`state.schema-version:${e}`,read:Hd.read}}function getStateSchemaVersionAdmission(e){let t=getStateSchemaFacts(e);if(!t)return;let n=Wd.get(e);if(n?.schema===t)return n.facts;let r=nn(e,schemaVersionKey(t.admissionId)),i=r?void 0:nn(e,Gn);if(!r&&!y(e)&&i?.admissionId!==t.admissionId)return;let a=r??nn(e,Hd);return a&&(rememberConnectionVersion(e,{schema:t,facts:a}),r||cn(e,schemaVersionKey(t.admissionId),a)),a}function rememberStateSchemaVersionAdmission(e,t){let n=getStateSchemaFacts(e);if(!n)return;rememberConnectionVersion(e,{schema:n,facts:t});let r=nn(e,Gn);(y(e)||r?.admissionId===n.admissionId)&&(cn(e,schemaVersionKey(n.admissionId),t),cn(e,Hd,t))}function publishStateSchemaVersionAdmission(e,t){cn(e,Hd,t);let n=getStateSchemaFacts(e);n?(rememberConnectionVersion(e,{schema:n,facts:t}),cn(e,schemaVersionKey(n.admissionId),t)):rememberConnectionVersion(e)}function adoptPeerPublishedStateSchemaVersion(e,t){return t?.schema_version!==40||ue(e)!==40?!1:(publishStateSchemaVersionAdmission(e,{userVersion:40,contentVersion:40}),!0)}function getStateRuntimeSchemaAdmission(e){return Ud.get(e)}function publishStateRuntimeSchemaAdmission(e,t){Ud.publish(e,{startupReady:t})}function readPublishedStateSchemaVersion(e){let t=getStateSchemaVersionAdmission(e);return t?t.userVersion:(y(e)&&Hn(`postgres`,`repair`),ue(e))}const Gd=n(Symbol.for(`openclaw.stateIntegrityBindings`),()=>/* @__PURE__ */ new WeakMap),Kd={name:`state.integrity`,lifetime:`process`,read:e=>e===!0||void 0};function hasStateDatabaseIntegrityAdmission(e){return!!(getStateRuntimeSchemaAdmission(e)||nn(e,Kd))}function assertStateDatabaseIntegrityOnce(e,t){hasStateDatabaseIntegrityAdmission(e)||(ur(e,t),cn(e,Kd,!0))}function invalidate(e){let t=Atomics.load(e,0);for(;t>=0n;){let n=Atomics.compareExchange(e,0,t,t+1n);if(n===t)return;t=n}}function invalidateOpenClawStateRuntimeIntegrity(e){Jt(e);let t=Gd.get(e);t&&(invalidate(new BigInt64Array(t.revision)),invalidate(new BigInt64Array(t.lifetimeRevision)))}function bind(e,t){if(Gd.get(e)?.revision===t.revision)return;Gd.get(e)?.release();let n=new BigInt64Array(t.revision),r=Yn(e,()=>invalidate(n)),release=()=>{r(),i()},i=Ln(e,e=>{e===`replace`&&(invalidate(n),invalidate(new BigInt64Array(t.lifetime.revision))),release()});Gd.set(e,{revision:t.revision,lifetimeRevision:t.lifetime.revision,release})}function assertOpenClawStateRuntimeIntegrity(e,t,n,r,i=`verify`){let a=r&&readTrackedStateDatabaseIdentity(e);if(!r||!a||!a.key.startsWith(`file:`)||a.key!==r.identity.key||a.birthtime!==r.identity.birthtime){if(i===`require-proof`)throw Error(`Shared-state reader requires current worker integrity proof`);assertStateDatabaseIntegrityOnce(e,t);return}bind(e,r);let o=new BigInt64Array(r.revision),s=new BigInt64Array(r.proof),c=BigInt.asIntN(64,BigInt(n.userVersion>>>0)<<32n|BigInt(n.schemaVersion>>>0)),l=Atomics.load(s,0);if(Atomics.load(o,0)===r.epoch&&l!==-1n){if(l===c&&Atomics.load(o,0)===r.epoch&&hasStateDatabaseIntegrityAdmission(e))return;invalidate(o)}if(i===`require-proof`)throw Error(`Shared-state reader requires current worker integrity proof`);assertStateDatabaseIntegrityOnce(e,t);let publish=()=>{Atomics.load(o,0)===r.epoch&&Atomics.store(s,0,c)};return()=>{e.isTransaction?en(e,{commit:publish}):publish()}}function retainSqliteDatabaseRemovalExclusion(e,t){if(!mr(e))return;let n=ir(tr(e)),close=()=>{if(!n.isOpen)return;let e=[];try{n.isTransaction&&n.exec(`ROLLBACK`)}catch(t){e.push(t)}try{n.close()}catch(t){e.push(t)}jt(e,`SQLite state removal exclusion cleanup failed.`)};try{t.own(n,`shared-handles`,close),n.exec(`PRAGMA busy_timeout = 0; PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE;`)}catch(e){try{close()}catch(t){throw Ot([e,t],`SQLite state removal admission and cleanup both failed.`,e)}if(Ht(e))throw Error(`Cannot remove OpenClaw state directory while another SQLite connection is active`,{cause:e});let t=Wt(e);if(t!==11&&t!==26)throw e;return}process.platform===`win32`&&close()}function createOpenClawStateSnapshotOwnerRegistry(){let e=/* @__PURE__ */ new WeakMap;return{register(t,n){y(t.db)||e.set(t.db,registerLiveSqliteSnapshotOwner({database:t.db,databasePath:t.path,assertCurrent:()=>{if(n()!==t||!t.db.isOpen)throw Error(`OpenClaw state snapshot owner is no longer current`)}}))},release(t){y(t)||(e.get(t)?.(),e.delete(t))}}}const qd=n(Symbol.for(`openclaw.stateSnapshotOwners`),createOpenClawStateSnapshotOwnerRegistry),Jd=n(fe,()=>({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:(e,t)=>lf.closeTerminalFailure(e,t)}),asyncResources:Se()}),()=>closeOpenClawStateDatabaseAsync(),`shared-state`),{cachedDatabases:Q,retainedDatabaseHandles:Yd,idleTimers:Xd,idleReferences:Zd,databaseIdentities:Qd,borrowers:$d,databaseLifecycleListeners:ef,terminalOpenLatch:tf,asyncResources:$}=Jd,{touch:nf,retain:rf}=createStateDatabaseIdleRetirement(Jd,retireOpenClawStateDatabaseHandle),{register:af,readHealth:of,ownRetirement:sf,stop:cf}=createStateDatabaseWalOwner(Jd,rf,requireOpenClawStateDatabaseIdentity);function notifyOpenClawStateDatabaseLifecycle(e){let t=e.kind===`open-error`?{...e,identity:e.identity??$.knownIdentity(e.path)}:e;for(let e of ef)e(t)}function notifyOpenClawStateDatabaseClosed(e){notifyOpenClawStateDatabaseLifecycle({kind:`closed`,path:e.path,identity:requireOpenClawStateDatabaseIdentity(e)})}function requireOpenClawStateDatabaseIdentity(e){let t=Qd.get(e.db);if(!t)throw Error(`Published shared-state owner has no recorded database identity`);return t}const lf=createStateDatabaseCacheAdmission({cachedDatabases:Q,evict:evictCachedOpenClawStateDatabase,invalidate:e=>$.invalidate(e),notifyTerminalFailure:(e,t)=>notifyOpenClawStateDatabaseLifecycle({kind:`terminal-failure`,path:e,error:t,identity:$.knownIdentity(e)})});function registerOpenClawStateDatabaseLifecycleListener(e){ef.add(e);for(let t of Q.values())t.db.isOpen&&e({kind:`opened`,database:t,identity:requireOpenClawStateDatabaseIdentity(t)});return()=>ef.delete(e)}function registerOpenClawStatePathCacheInvalidation(e){return registerOpenClawStateDatabaseLifecycleListener(t=>{if(t.kind!==`opened`)for(let[n,r]of e)r.path===(t.identity?.canonicalPath??t.path)&&e.delete(n)})}function retainStateDatabaseClose(e){Yd.set(e.db,e),Jd.unregisterRetainedExitClose??=pn(closeOpenClawStateDatabase)}function ownMaintenanceStateDatabaseHandle(e){it()?.own(e.db,`shared-handles`,async()=>{let t=it();t&&nt(e.db,t)&&(Q.get(e.path)===e||Yd.get(e.db)===e)&&(await e.walMaintenance?.stop(),nt(e.db,t)&&(Q.get(e.path)===e||Yd.get(e.db)===e)&&retireOpenClawStateDatabaseHandle(e,!1))})}function closeUnpublishedOpenClawStateDatabaseHandle(e){let t=closeOpenClawStateDatabaseHandle(e);return Yd.get(e.db)===e&&ownMaintenanceStateDatabaseHandle(e),t}const{retain:uf,borrowForRead:df,retainForIndependentRead:ff}=createStateDatabaseRetainer(Jd,{assertOpen(e,t,n){assertOpenClawStateDatabaseOpenAllowed(e,t,n),assertExistingOpenClawStateSchemaCacheAdmission(e,Jd)},capture:e=>$.capture(e),retire:retireOpenClawStateDatabaseHandle,retainFailed:retainStateDatabaseClose,ownRetirement:sf,touch:nf});function closeOpenClawStateDatabaseHandle(e,t){clearTimeout(Xd.get(e.db)),Xd.delete(e.db);try{assertStateDatabaseBorrowersReleased($d.get(e.db),e.path)}catch(n){let r=$d.get(e.db);return r&&(r.retiring=!0,r.retirement={ordinary:!0,isCurrent:()=>!0,retire:()=>{jt(closeOpenClawStateDatabaseHandle(e,t),`OpenClaw state database cleanup failed for ${e.path}.`),r.cleanupComplete=!0,$d.delete(e.db)}}),retainStateDatabaseClose(e),[n]}Zd.delete(e.db),qd.release(e.db);let{errors:n,cleanupPending:r}=closeStateDatabaseHandle(e,t);return e.db.isOpen||r?retainStateDatabaseClose(e):Yd.delete(e.db),Q.get(e.path)?.db===e.db&&Q.delete(e.path),Yd.size===0&&(Jd.unregisterRetainedExitClose?.(),Jd.unregisterRetainedExitClose=void 0),n}function evictCachedOpenClawStateDatabase(e){return y(e.db)||invalidateOpenClawStateRuntimeIntegrity(e.db),Q.get(e.path)===e&&($.invalidate(e.path),Q.delete(e.path),notifyOpenClawStateDatabaseClosed(e),closeOpenClawStateDatabaseHandle(e,{checkpointMode:`PASSIVE`}),!0)}function evictOpenClawStateDatabaseAfterCorruption(e,t){return Ut(t)&&evictCachedOpenClawStateDatabase(e)}function publishOpenClawStateDatabase(e,t){let{db:n,path:r}=e,{identity:i,admission:a}=$.publish(r);return Qd.set(n,readTrackedStateDatabaseIdentity(n)??i),Q.set(r,e),af(e,i,a,t),nf(e),qd.register(e,()=>Q.get(r)),ownMaintenanceStateDatabaseHandle(e),notifyOpenClawStateDatabaseLifecycle({kind:`opened`,database:e,identity:i}),y(n)||Vn(n,t=>{!n.isTransaction&&Ut(t)&&evictCachedOpenClawStateDatabase(e)}),tf.clear(r),e}function getCachedOpenClawStateDatabase(e,t){let n=v({path:e}),r=tf.get(n);if(r)throw r;let i=readCachedOpenClawStateDatabase(n,t?.readOnly===!0);return i&&nf(i),i}function readCachedOpenClawStateDatabase(e,t){let n=it();t?n?.assertReadAdmission():n?.assertAdmission(),assertExistingOpenClawStateSchemaCacheAdmission(e,Jd);let r=Q.get(e);if(r&&$d.get(r.db)?.retiring)throw Error(`OpenClaw state database native borrower cleanup is pending: ${e}`);return r}function prepareOpenClawStateCachedRead(e){let t=v({path:e});getCachedOpenClawStateDatabase(t,{readOnly:!0});let n=$.capture(t);return()=>(n.assertCurrent(),readCachedOpenClawStateDatabase(t,!0))}function withCachedOpenClawStateDatabase(e,t,n){let r=getCachedOpenClawStateDatabase(e,t);return r&&lf.read(r,n)}function getOpenClawStateDatabaseIfOpenAtPath(e){let t=getCachedOpenClawStateDatabase(e);return rt(t?.db.isOpen?t.db:void 0),t?.db.isOpen?t:void 0}function closeStaleCachedOpenClawStateDatabase(e){if(Q.get(e.path)!==e)return;$.invalidate(e.path);let t=closeOpenClawStateDatabaseHandle(e);notifyOpenClawStateDatabaseClosed(e),jt(t,`Stale OpenClaw state database cleanup failed for ${e.path}.`)}function recordOpenClawStateDatabaseOpenFailure(e,t){tf.record(v({path:e}),t)}function clearOpenClawStateDatabaseOpenFailure(e){let t=v({path:e});tf.clear(t),$.invalidate(t),notifyOpenClawStateDatabaseLifecycle({kind:`failure-cleared`,path:t,identity:$.knownIdentity(t)})}async function getOpenClawStateDatabaseTerminalFailureAsync(e,t){return e.admission.assertCurrent(),t?.throwIfAborted(),tf.get(e.admission.databasePath)}function assertOpenClawStateDatabaseOpenAllowed(e,t,n){let r=v({path:e});t===`cached-read`&&n?n.assertReadAllowed():(t===`cached-read`?assertStateDatabaseReadAllowed:assertStateDatabaseAccessAllowed)(e);let{identity:i}=$.capture(r),a=tf.get(r);if(a)throw a;for(let t of Yd.values())if($d.get(t.db)?.retiring&&(t.path===r||Qd.get(t.db)?.key===i.key))throw Error(`OpenClaw state database native borrower cleanup is pending: ${e}`)}function recordOpenClawStateDatabaseLifecycleOpenError(e,t){notifyOpenClawStateDatabaseLifecycle({kind:`open-error`,path:v({path:e}),error:t})}function assertOpenClawStateDatabaseFreshOpenAllowedAtPath(e,t,n,r){assertOpenClawStateDatabaseOpenAllowed(e);let i;try{i=readOpenClawDatabaseQuarantineFailure(`state`,e,{env:t,refreshIdentity:r})}catch(e){if(!(e instanceof g))throw e;n?.(e)}if(i?.cause instanceof g&&n?.(i.cause),i)throw lf.closeTerminalFailure(e,i),i}function retireOpenClawStateDatabaseHandle(e,t=!0,n){assertStateDatabaseBorrowersReleased($d.get(e.db),e.path);let r=$d.get(e.db);try{let r=Q.get(e.path)?.db===e.db;t&&$.invalidate(e.path);let i=closeOpenClawStateDatabaseHandle(e,n);if(r&&t)try{notifyOpenClawStateDatabaseClosed(e)}catch(e){i.push(e)}jt(i,`OpenClaw state database cleanup failed for ${e.path}.`)}catch(t){throw r&&retainStateDatabaseClose(e),t}r&&(r.cleanupComplete=!0,$d.delete(e.db))}function stateDatabaseHandlesAt(e,t){return[.../* @__PURE__ */ new Set([...Yd.values(),...Q.values()])].filter(n=>e===void 0||n.path===e||t!==void 0&&Qd.get(n.db)?.key===t.key)}function retireOpenClawStateDatabaseHandles(e,t,n){let r=stateDatabaseHandlesAt(e,n),i=[];for(let e of r)try{retireOpenClawStateDatabaseHandle(e,!0,t)}catch(e){i.push(e)}return jt(i,`OpenClaw state database cleanup failed.`),r.length>0}function closeOpenClawStateDatabaseByPath(e,t){return retireOpenClawStateDatabaseHandles(v({path:e}),t,$.identity(e))}function sealOpenClawStateDatabaseByPath(e){let t=v({path:e}),n=$.identity(e);return!stateDatabaseHandlesAt(t,n).some(e=>$d.get(e.db)?.references.size)&&retireOpenClawStateDatabaseHandles(t,void 0,n)}function closeOpenClawStateDatabase(e){retireOpenClawStateDatabaseHandles(void 0,e)}const pf=$.register;function registerOpenClawStatePathAsyncResource(e,t){return pf({close(n){return!n||n.key===e.identity.key||n.canonicalPath===e.identity.canonicalPath?t():Promise.resolve()}})}const mf=$.capture,hf=$.integrity;function publishOpenClawStateDatabaseWorkerAdmission(e,t){t&&e.assertCurrent(),$.publish(e.databasePath,t),e.assertCurrent(),$t(e.databasePath,e.identity)}function closeOpenClawStateDatabaseByPathAsync(e,t){let n=v({path:e});return $.close(n,async e=>(await cf(n,e),retireOpenClawStateDatabaseHandles(n,t,e)))}function closeOpenClawStateDatabaseWorkersByPathAsync(e){return $.close(v({path:e}),()=>!1)}async function closeOpenClawStateDatabaseAsync(e){await $.close(void 0,async()=>(await cf(),retireOpenClawStateDatabaseHandles(void 0,e)))}async function joinOpenClawStateDatabaseBorrowers(){await Promise.all(stateDatabaseHandlesAt().map(e=>joinStateDatabaseBorrowersReleased($d.get(e.db),e.path)))}async function releaseOpenClawStateDatabaseCustody(){await closeOpenClawStateDatabaseAsync(),Et()}function isOpenClawStateDatabaseOpen(e){return e===void 0?Array.from(Q.values()).some(e=>e.db.isOpen):Q.get(v({path:e}))?.db.isOpen===!0}function closeOpenClawStateDatabaseForTest(){closeOpenClawStateDatabase(),tf.clearAll()}function assertPublishedOpenClawStateDatabaseLifecycle(){if(r(fe)!==Jd)throw Error(`OpenClaw state database lifecycle is retired; its owners cannot serve the published lifecycle`)}const gf={assertOpenClawStateDatabaseFreshOpenAllowedAtPath,assertOpenClawStateDatabaseOpenAllowed,clearOpenClawStateDatabaseOpenFailure,closeOpenClawStateDatabase,closeOpenClawStateDatabaseByPath,sealOpenClawStateDatabaseByPath,closeOpenClawStateDatabaseForTest,closeOpenClawStateDatabaseHandle,closeUnpublishedOpenClawStateDatabaseHandle,closeStaleCachedOpenClawStateDatabase,evictCachedOpenClawStateDatabase,evictOpenClawStateDatabaseAfterCorruption,getCachedOpenClawStateDatabase,peekOpenClawStateDatabaseConnection:e=>Q.get(v({path:e}))?.db,withCachedOpenClawStateDatabase,getOpenClawStateDatabaseRecordedFailure:tf.peek,getOpenClawStateDatabaseIfOpenAtPath,getKnownOpenClawStateDatabaseIdentity:$.knownIdentity,isOpenClawStateDatabaseOpen,isOpenClawStateDatabaseSchemaReady:e=>Q.get(e.path)===e&&e.db.isOpen,publishOpenClawStateDatabase,recordOpenClawStateDatabaseOpenFailure,recordOpenClawStateDatabaseLifecycleOpenError,async reconcileFailedWorkerAdmission(e){await $.retireChangedAdmission(e),e.assertCurrent()},touchStateDatabase:nf};async function prepareOpenClawStateDatabaseRemoval(e,t){let n=v({path:e}),r=it();if(!r?.ownsSchemaMaintenance)throw Error(`State removal requires the installation's maintenance owner`);r.assertAdmission();let i=$.holdExclusion(n);try{await closeOpenClawStateDatabaseByPathAsync(n),r.assertOwnerCurrent(),retainSqliteDatabaseRemovalExclusion(n,r),r.assertOwnerCurrent()}catch(e){throw i(),e}let a=!0;return{assertCurrent(){if(!a)throw Error(`State removal admission has been released`);t()},release(){a&&(a=!1,i())}}}export{tableHasColumn as $,resolveGatewayStateOwnerPath as $t,assertOpenClawStateRuntimeIntegrity as A,object as An,runSqliteSingleStatementSync as At,rememberStateSchemaVersionAdmission as B,quarantineOrphanedSqliteSidecars as Bt,registerOpenClawStatePathAsyncResource as C,boolean as Cn,getDatabaseProcessRole as Ct,uf as D,looseObject as Dn,runSqliteDeferredTransactionSync as Dt,requireOpenClawStateDatabaseIdentity as E,literal as En,retainSqliteWriteAdmissionService as Et,getStateRuntimeSchemaAdmission as F,applyConfigEnvVars as Fn,prepareSqliteReadOnlyLocationSync as Ft,captureOpenClawStateWorkerContextWithAdmission as G,publishReusableSqliteSnapshot as Gt,openTrackedStateDatabaseResult as H,captureReusableSqliteSource as Ht,getStateSchemaVersionAdmission as I,cloneEnvWithPlatformSemantics as In,startSqliteReadOnlyLocationAsync as It,Bd as J,acquireStateDatabaseSchemaLease as Jt,migrateCronDefaultStoreIdentity as K,prepareSqliteReadOnlyLocationFromOwnedDatabase as Kt,publishStateRuntimeSchemaAdmission as L,isUpdateRehearsalPrivateDatabase as Lt,invalidateOpenClawStateRuntimeIntegrity as M,string as Mn,observeDatabaseOperation as Mt,adoptPeerPublishedStateSchemaVersion as N,union as Nn,openSqliteReadOnlyDatabase as Nt,rf as O,never as On,runSqliteImmediateTransactionSync as Ot,createStateSchemaAdmission as P,unknown as Pn,prepareSqliteReadOnlyLocationAwaited as Pt,tableExists as Q,prepareStateDatabaseReadAccess as Qt,publishStateSchemaVersionAdmission as R,projectUpdateRehearsalDatabaseConfig as Rt,registerOpenClawStateDatabaseLifecycleListener as S,array as Sn,assertEngineStoreExecutionAllowed as St,releaseOpenClawStateDatabaseCustody as T,discriminatedUnion as Tn,assertTransactionUsable as Tt,readTrackedStateDatabaseIdentity as U,isSqliteSnapshotReuseActive as Ut,openTrackedStateDatabase as V,resolveSqliteDatabaseFilePaths as Vt,captureOpenClawStateReadWorkerContextWithAdmission as W,leaseReusableSqliteSnapshot as Wt,ensureColumn as X,captureStateDatabaseAccess as Xt,classifySqliteTableReadError as Y,assertStateDatabaseAccessAllowed as Yt,readTableColumns as Z,getStateDatabaseSchemaLease as Zt,prepareOpenClawStateDatabaseRemoval as _,classifyGatewayOwnerProcessNamespace as _n,getGatewayServiceInstallation as _t,clearOpenClawStateDatabaseOpenFailure as a,executeSqliteQueryTakeFirstSync as an,throwSqliteSchemaMismatches as at,recordOpenClawStateDatabaseOpenFailure as b,_enum as bn,isSqliteWalWorkerMaintained as bt,closeOpenClawStateDatabaseByPath as c,prepareSqliteQuerySync as cn,getSqliteWorkerExistingDatabaseIdentity as ct,closeOpenClawStateDatabaseWorkersByPathAsync as d,k as dn,getExistingOpenClawStateSchemaPath as dt,withStateDatabaseColdAdmission as en,tablePrimaryKeyColumns as et,getOpenClawStateDatabaseTerminalFailureAsync as f,applyPrivateModeSync as fn,isExistingOpenClawStateSchema as ft,prepareOpenClawStateCachedRead as g,Hs as gn,isGatewayExternallySupervised as gt,gf as h,Us as hn,jsonValid as ht,hf as i,executeSqliteQuerySync as in,legacySqliteSchemaIssueMessages as it,assertStateDatabaseIntegrityOnce as j,record as jn,observeConnection as jt,ff as k,number as kn,runSqliteReadSnapshotSync as kt,closeOpenClawStateDatabaseByPathAsync as l,SqliteQueryCompiler as ln,getSqliteWorkerStateIntegrityAdmission as lt,joinOpenClawStateDatabaseBorrowers as m,GatewayLockNamespaceError as mn,jsonPathValue as mt,df as n,compileSqliteQueryBindings as nn,createSqliteSchemaIssue as nt,closeOpenClawStateDatabase as o,getNodeSqliteKysely as on,captureSqliteWorkerStateContext as ot,isOpenClawStateDatabaseOpen as p,sha256Hex as pn,recordExistingOpenClawStateSchemaDatabase as pt,resolveCronIdentityMigrationDefaultStoreKey as q,acquireSqliteSnapshotReadToken as qt,mf as r,createSqliteQueryCache as rn,isSqliteSchemaMismatchError as rt,closeOpenClawStateDatabaseAsync as s,iterateSqliteQuerySync as sn,captureSqliteWorkerWalMaintenanceSuspension as st,assertPublishedOpenClawStateDatabaseLifecycle as t,classifyGatewayLockProcessNamespace as tn,SqliteSchemaMismatchError as tt,closeOpenClawStateDatabaseForTest as u,expressionBuilder as un,sqliteWorkerRequestBytes as ut,publishOpenClawStateDatabaseWorkerAdmission as v,parseGatewayLockPayload as vn,cancelSqliteWalWriteAdmission as vt,registerOpenClawStatePathCacheInvalidation as w,custom as wn,withEngineStoreAdmission as wt,pf as x,_undefined as xn,Ad as xt,of as y,createManagedHandoffBootIdentityReader as yn,createSqliteWalMaintenanceScheduler as yt,readPublishedStateSchemaVersion as z,_d as zt};