UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

26 lines • 329 kB
import{Bt as e,Et as t,F as n,I as r,Jt as i,Lt as a,Yt as o,d as s,f as c,jt as l,kt as u,mt as d,n as f,qt as p,t as m,u as h}from"./sqlite-readonly-subsystem-Bfq7Sewc.mjs";import{t as ee}from"./sqlite-readonly-deferred-B75K7ut7.mjs";import{Dt as g,Et as _,I as te,Mt as ne,Ot as v,R as re,St as ie,Ut as y,Vt as b,W as ae,X as oe,an as x,d as se,gt as ce,kt as le,ln as S,pt as ue,qt as de,s as fe,ut as pe,v as me,z as he}from"./sqlite-readonly-runtime-process-manifest-DDSkIpjb.mjs";import{A as ge,Q as _e,T as ve,f as ye,h as be,k as xe,o as Se,p as Ce,r as we,t as Te,u as Ee,v as De}from"./sqlite-readonly-sqlite-snapshot-capacity-error-CpnKAwJy.mjs";import{c as Oe}from"./sqlite-readonly-file-open-error-B05Kb3Yo.mjs";import{C as ke,S as Ae,_ as je,a as Me,b as Ne,f as Pe,g as Fe,h as Ie,m as Le,n as Re,r as ze,s as Be,t as Ve,v as He,w as Ue,x as We,y as Ge}from"./sqlite-readonly-sqlite-readonly-location-CrsaHxKY.mjs";import{D as Ke,_ as qe,a as Je,c as Ye,d as Xe,f as Ze,g as Qe,h as $e,i as et,l as tt,m as nt,o as rt,p as it,r as at,s as ot,u as st,v as ct,y as lt}from"./sqlite-readonly-sidecar-lock-HPXNMcm7.mjs";import{t as ut}from"./sqlite-readonly-lock-config-CQM_E5H4.mjs";import{An as dt,G as ft,Ht as pt,L as mt,Tn as ht,c as gt,cn as _t,dn as vt,gn as yt,in as bt,jn as xt,kn as St,o as Ct,on as wt,q as Tt,qt as Et,rn as Dt,tt as Ot}from"./sqlite-readonly-sqlite-database-admission-Bj6bmeyX.mjs";import{n as kt,r as At}from"./sqlite-readonly-path-existence-lfal2A68.mjs";import{l as jt}from"./sqlite-readonly-openclaw-state-db-async-lifecycle-BwAy3Dr9.mjs";import{r as Mt}from"./sqlite-readonly-openclaw-state-maintenance-context-BTKm0Xem.mjs";import"./sqlite-readonly-openclaw-state-db-contract-DiFTYPe3.mjs";import{a as Nt,d as Pt,g as Ft,m as C,n as It,p as w,s as T,t as Lt,u as Rt}from"./sqlite-readonly-schemas-CQ3oYUYf.mjs";import{I as zt,J as Bt,K as Vt,W as Ht,Y as Ut,g as Wt,i as Gt,q as Kt,r as qt,t as Jt}from"./sqlite-readonly-node-sqlite-C-jA8uc4.mjs";import{a as Yt,i as Xt,o as Zt,t as Qt}from"./sqlite-readonly-cli-invocation-9KSnD_FV.mjs";import{a as $t,n as en,r as tn,t as nn}from"./sqlite-readonly-runtime-binary-CQkI442k.mjs";import{n as rn,r as an}from"./sqlite-readonly-runtime-worker-url-Ca-_reGi.mjs";import{t as on}from"./sqlite-readonly-retained-operation-CV17ZGcz.mjs";import*as sn from"node:module";import{createRequire as cn}from"node:module";import E from"node:path";import{setImmediate as ln}from"node:timers/promises";import{deserialize as un,serialize as dn,setFlagsFromString as pn}from"node:v8";import{hash as mn,randomUUID as hn}from"node:crypto";import D,{chmodSync as gn,statSync as _n,unlinkSync as vn,writeFileSync as yn}from"node:fs";import O from"node:fs/promises";import bn,{hostname as xn}from"node:os";import{fileURLToPath as Sn,pathToFileURL as Cn}from"node:url";import{MessageChannel as wn,MessagePort as Tn,Worker as En,isMainThread as Dn,receiveMessageOnPort as On,threadId as kn}from"node:worker_threads";import{toUSVString as An,types as jn}from"node:util";import{AsyncLocalStorage as Mn}from"node:async_hooks";import Nn,{spawnSync as Pn}from"node:child_process";import"node:buffer";import{channel as Fn}from"node:diagnostics_channel";import{ProcSafeError as In}from"@openclaw/proc-safe/errors";import{readProcessIdentity as Ln}from"@openclaw/proc-safe/identity";Dn&&process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED===`gateway`&&(delete process.env.NODE_DISABLE_COMPILE_CACHE,delete process.env.OPENCLAW_PACKAGED_COMPILE_CACHE_RESPAWNED);const Rn=36e5,zn=3e4,Bn=/^(?:[a-f0-9]{16}|\d+-\d+|no-package-json|build-[A-Za-z0-9._-]+)$/,sanitize=e=>{let t=e.replace(/[^A-Za-z0-9._-]+/g,`_`).replace(/^_+|_+$/g,``);return t&&t!==`.`&&t!==`..`?t:`unknown`};function scheduleOpenClawCompileCacheFlush(){if(!sn.getCompileCacheDir?.())return;let e=globalThis[Symbol.for(`openclaw.nodeCompileCacheBase`)]??={};e.flush||(e.flush=setImmediate(()=>{e.flush=void 0;try{sn.flushCompileCache()}catch{}}),e.flush.unref())}function resolveSafeNodeCompileCacheDirectory(e){if(process.platform===`win32`&&E.resolve(e).length>200)process.stderr.write(`[openclaw] Compile cache disabled: Windows cache path exceeds 200 characters.
`);else return e}async function maintain(e){let t=E.dirname(E.dirname(e)),n=E.basename(E.dirname(e));if(E.basename(t)!==`openclaw`||sanitize(n)!==n||!Bn.test(E.basename(e)))return;let r=Date.now(),i=await O.lstat(t).catch(()=>void 0);for(let n of[t,E.dirname(e),e]){let e=n===t?i:await O.lstat(n).catch(()=>void 0);if(e&&!e.isDirectory())return}if(i&&r-i.mtimeMs<Rn)return;await O.mkdir(t,{recursive:!0});let a=`${t}.maintenance`,o=await O.lstat(a).catch(()=>void 0);if(o&&r-o.mtimeMs>3e5&&await O.rmdir(a).catch(()=>{}),!await O.mkdir(a).then(()=>!0,()=>!1))return;let s=[],c=0,l=0,u=!1;async function prune(){for(s.sort((e,t)=>t.mtimeMs-e.mtimeMs);s.length;){if(Date.now()-r>zn)return!1;let e=s[s.length-1];if(c<=536870912&&s.length<=4096&&r-e.mtimeMs<=6048e5)break;await O.unlink(e.file).catch(e=>{if(e.code!==`ENOENT`)throw e}),c-=e.size,s.pop()}return!0}async function visit(e){for await(let t of await O.opendir(e)){if(++l>16384||Date.now()-r>zn)return!1;let n=E.join(e,t.name);if(t.isDirectory()){if(!await visit(n))return!1}else if(t.isFile()){let e=await O.lstat(n).catch(e=>{if(e.code!==`ENOENT`)throw e});if(!e)continue;if(c+=e.size,s.push({file:n,size:e.size,mtimeMs:e.mtimeMs}),s.length%256==0&&!await prune())return!1}}return!0}try{if(r-(await O.lstat(t)).mtimeMs<Rn){u=!0;return}let e=await visit(t);if(await prune()&&e){let e=/* @__PURE__ */ new Date;await O.utimes(t,e,e),u=!0}}finally{u||await O.utimes(t,i?.atime??/* @__PURE__ */ new Date(0),i?.mtime??/* @__PURE__ */ new Date(0)).catch(()=>{}),await O.rmdir(a)}}process.argv[2]===`--maintain`&&process.argv[1]===Sn(import.meta.url)&&process.argv[3]&&maintain(process.argv[3]).catch(()=>{});function safeParseJson(e){try{return JSON.parse(e)}catch{return}}function safeParseJsonRecord(e){return/^[\t\n\r ]*\{/.test(e)?p(safeParseJson(e)):void 0}const Vn=a(Symbol.for(`openclaw.artifactPreservingStateReads`),()=>new Mn),Hn=a(Symbol.for(`openclaw.liveStateReads`),()=>new Mn);function isLiveStateRead(){return Hn.getStore()!==void 0}function isStartupConfigStateRead(){return Hn.getStore()===`startup-config`}function withArtifactPreservingStateReads(e,t={}){if(isArtifactPreservingStateRead(`agent`))return e();let n={agentDatabases:t.agentDatabases===!0,readers:/* @__PURE__ */ new Set,privateRoots:/* @__PURE__ */ new Set,snapshots:/* @__PURE__ */ new Map},closeReaders=e=>{for(let t of n.readers)try{t()}catch(t){e.push(t)}},finish=(e,t=[])=>{closeReaders(t);for(let e of n.snapshots.values())try{if(!e.cleanup())throw new ht(`SQLite inspection snapshot cleanup failed.`)}catch(e){t.push(e)}return dt(t,`Artifact-preserving inspection and cleanup failed.`),e},finishAsync=async(e,t=[])=>{closeReaders(t);for(let e of n.snapshots.values())try{if(!await e.cleanupAsync())throw new ht(`SQLite inspection snapshot cleanup failed.`)}catch(e){t.push(e)}return dt(t,`Artifact-preserving inspection and cleanup failed.`),e},r;try{r=Vn.run(n,e)}catch(e){return finish(void 0,[e])}return xt(r)?Promise.resolve(r).then(finishAsync,e=>finishAsync(void 0,[e])):finish(r)}function isArtifactPreservingStateRead(e=`shared`,t){let n=Vn.getStore();return!(!n||e!==`shared`&&!n.agentDatabases||t&&[...n.privateRoots].some(e=>le(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}}let Un;function isContainerEnvironment(){return Un??=detectContainerEnvironment()}function detectContainerEnvironment(){if(process.env.FLY_MACHINE_ID?.trim()&&process.env.FLY_APP_NAME?.trim())return!0;for(let e of[`/.dockerenv`,`/run/.containerenv`,`/var/run/.containerenv`])try{return D.accessSync(e,D.constants.F_OK),!0}catch{}try{let e=D.readFileSync(`/proc/1/cgroup`,`utf8`);if(/\/docker\/|cri-containerd-[0-9a-f]|containerd\/[0-9a-f]{64}|\/kubepods[/.]|\blxc\b/.test(e))return!0}catch{}return!1}function resolveEnvironmentValue(e,t,n=process.platform){if(!e)return;if(n!==`win32`)return e[t]??(t===`PATH`?e.Path:void 0);let r=t.toUpperCase(),i=Object.keys(e).toSorted().find(e=>e.toUpperCase()===r);return i===void 0?void 0:e[i]}function mergeProcessEnv(e,t=process.platform){let n=Object.create(null),r=/* @__PURE__ */ new Map;for(let i of e){if(!i)continue;let e=Object.keys(i),a=/* @__PURE__ */ new Set;for(let o of t===`win32`?e.toSorted():e){let e=t===`win32`?o.toUpperCase():void 0;if(e!==void 0){if(a.has(e))continue;a.add(e);let t=r.get(e);t!==void 0&&delete n[t],r.delete(e)}let s=i[o];s===void 0?delete n[o]:(n[o]=s,e!==void 0&&Object.hasOwn(n,o)&&r.set(e,o))}}return n}const Wn=/* @__PURE__ */ new Set(/* @__PURE__ */ `PATH.Path.HOME.USER.LOGNAME.TMPDIR.TMP.TEMP.LANG.LANGUAGE.TZ.LC_ALL.LC_COLLATE.LC_CTYPE.LC_MESSAGES.LC_MONETARY.LC_NUMERIC.LC_TIME.LC_ADDRESS.LC_IDENTIFICATION.LC_MEASUREMENT.LC_NAME.LC_PAPER.LC_TELEPHONE.SYSTEMROOT.WINDIR.COMSPEC.PATHEXT.SYSTEMDRIVE.USERPROFILE.HOMEDRIVE.HOMEPATH.USERNAME.USERDOMAIN.APPDATA.LOCALAPPDATA.PROGRAMDATA.ALLUSERSPROFILE.PROGRAMFILES.PROGRAMFILES(X86).PROGRAMW6432.COMMONPROGRAMFILES.COMMONPROGRAMFILES(X86).COMMONPROGRAMW6432.PSMODULEANALYSISCACHEPATH`.split(`.`));function resolveDiagnosticProcessEnv(e=process.env,t=process.platform){return Object.fromEntries(Object.entries(mergeProcessEnv([e],t)).filter(([e])=>Wn.has(t===`win32`?e.toUpperCase():e)))}const Gn=`C:\\Windows`;function readNativeProcessStartTime(e){if(!(process.platform!==`win32`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=Ln(e);return t&&!t.exited?Math.floor(t.startTimeMicros/1e3):null}catch{return}}function windowsSystemRoot(e){let t=resolveEnvironmentValue(e,`SystemRoot`,`win32`)??resolveEnvironmentValue(e,`WINDIR`,`win32`);if(!t)return Gn;let n=E.win32.normalize(t);return/^[A-Za-z]:\\/.test(n)&&!n.startsWith(`\\\\`)?n:Gn}function windowsPowerShellPath(e){return E.win32.join(windowsSystemRoot(e),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}function windowsWmicPath(e){return E.win32.join(windowsSystemRoot(e),`System32`,`wbem`,`wmic.exe`)}function decodeWindowsProcessOutput(e){return Buffer.isBuffer(e)?e.length>=2&&e[0]===255&&e[1]===254?e.toString(`utf16le`):e.toString(`utf8`):e}function parseWindowsProcessStartTime(e){let t=decodeWindowsProcessOutput(e).split(/\r?\n/).map(e=>e.trim()).filter(Boolean),n=t.find(e=>e.toLowerCase().startsWith(`creationdate=`))?.slice(13).trim()??t.find(e=>e.toLowerCase()!==`creationdate`)??``,r=Date.parse(n);if(Number.isFinite(r))return r;let i=n.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);if(!i)return null;let[,a,o,s,c,l,u,d,f,p]=i;return Date.UTC(Number(a),Number(o)-1,Number(s),Number(c),Number(l),Number(u),Math.floor(Number(d)/1e3))-Number(p)*6e4*(f===`+`?1:-1)}function readWindowsProcessStartTimeSync(e,t=1e4,n=process.env){if(!Number.isInteger(e)||e<=0||e>4294967295)return null;let r=performance.now()+t,i=readNativeProcessStartTime(e);if(i!==void 0)return i;let a=Math.ceil(r-performance.now());if(a<=0)return null;let o=Pn(windowsPowerShellPath(n),[`-NoProfile`,`-NonInteractive`,`-Command`,`$process = [System.Diagnostics.Process]::GetProcessById(${e}); try { [Console]::Out.Write($process.StartTime.ToUniversalTime().ToString("o")) } finally { $process.Dispose() }`],{encoding:`utf8`,env:resolveDiagnosticProcessEnv(n,`win32`),timeout:Math.min(a,5e3),windowsHide:!0});if(!o.error&&o.status===0){let e=parseWindowsProcessStartTime(o.stdout);if(e!==null)return e}let s=Math.ceil(r-performance.now());if(s<=0)return null;let c=Pn(windowsWmicPath(n),[`process`,`where`,`ProcessId=${e}`,`get`,`CreationDate`,`/value`],{env:resolveDiagnosticProcessEnv(n,`win32`),timeout:s,windowsHide:!0,stdio:[`ignore`,`pipe`,`ignore`]});return!c.error&&c.status===0?parseWindowsProcessStartTime(c.stdout):null}let Kn;function loadFreeBsdProcessIdentityNative(){if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`FreeBSD process identity is unavailable in this sealed runtime`);return Kn||=cn(import.meta.url)(`@openclaw/proc-safe/identity`),Kn}function readFreeBsdProcessStartTime(e){if(process.platform!==`freebsd`||!Number.isInteger(e)||e<=0||e>2147483647)return null;try{return loadFreeBsdProcessIdentityNative().readProcessIdentity(e)?.startTimeSinceBootMicros??null}catch{return null}}function readDarwinNativeIdentity(e){if(!(process.platform!==`darwin`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=Ln(e);return t&&!t.exited?{startedAt:Math.floor(t.startTimeMicros/1e6),startTimeMicros:t.startTimeMicros}:null}catch{return}}function readNativeLiveness(e){if(!(![`darwin`,`win32`,`freebsd`].includes(process.platform)||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=Ln(e);return t!==null&&!t.exited}catch(e){return e instanceof In&&(e.code===`helper-unavailable`||e.code===`unsupported-platform`)?void 0:!0}}let qn=null;function isValidPid(e){return Number.isInteger(e)&&e>0}function hasLinuxProcfs(){return process.platform===`linux`||process.platform===`android`}function exitedLinuxStatus(e,t){let n=t.match(/^State:\s+(\S)/m)?.[1],r=t.match(/^Threads:[ \t]+(\d+)[ \t]*$/m)?.[1];if(r===`0`)return;let i=t.match(/^Tgid:[ \t]+(\d+)[ \t]*$/m)?.[1];return i!==void 0&&Number(i)!==e||(n===`Z`||n===`X`)&&r===`1`}function isMissingPid(e){try{process.kill(e,0)}catch(e){return _(e,`ESRCH`)}return!1}function isExitedLinuxProcess(e){if(!hasLinuxProcfs())return!1;try{let t=exitedLinuxStatus(e,D.readFileSync(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}async function isPidDefinitelyDeadAsync(e){if(!hasLinuxProcfs())return isPidDefinitelyDead(e);if(!isValidPid(e))return!0;try{process.kill(e,0)}catch(e){return _(e,`ESRCH`)}try{let t=exitedLinuxStatus(e,await D.promises.readFile(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}function isPidAlive(e){if(!isValidPid(e))return!1;try{process.kill(e,0)}catch(t){let n=g(t)?t.code:void 0;if(n!==`EPERM`)return n===`ESRCH`?readNativeLiveness(e)??!1:!1}return readNativeLiveness(e)??!isExitedLinuxProcess(e)}function isPidDefinitelyDead(e){if(!isValidPid(e))return!0;let t=!1;try{process.kill(e,0)}catch(e){let n=g(e)?e.code:void 0;if(n!==`ESRCH`&&(process.platform!==`win32`||n!==`EPERM`))return!1;t=n===`ESRCH`}let n=readNativeLiveness(e);return n===void 0?t&&process.platform!==`freebsd`||isExitedLinuxProcess(e):!n}function getDarwinProcessStartTime(e,t,n){let r=performance.now(),i=readDarwinNativeIdentity(e);if(i!==void 0)return i?.startedAt??null;let a=n===void 0?1e3:Math.ceil(n-(performance.now()-r));if(a<=0)return null;try{let n=Nn.execFileSync(`/bin/ps`,[`-o`,`lstart=`,`-p`,String(e)],{encoding:`utf8`,env:{...resolveDiagnosticProcessEnv(t),LC_ALL:`C`,TZ:`UTC`},stdio:[`ignore`,`pipe`,`ignore`],timeout:a,killSignal:`SIGKILL`}).trim(),r=Date.parse(`${n} UTC`);return Number.isFinite(r)?Math.floor(r/1e3):null}catch{return null}}function parseLinuxProcessStat(e,t){let n=t.lastIndexOf(`)`);if(n<0||!t.startsWith(`${e} (`))return null;let r=t.slice(n+1).trimStart().split(/\s+/),i=Number(r[19]),a=Number(r[1]);return Number.isSafeInteger(i)&&i>=0&&Number.isSafeInteger(a)&&a>=0?{parentPid:a,startedAt:i}:null}function readLinuxProcessStat(e){if(!isValidPid(e)||!hasLinuxProcfs())return null;try{return parseLinuxProcessStat(e,D.readFileSync(`/proc/${e}/stat`,`utf8`))}catch{return null}}function getProcessStartTime(e){return readLinuxProcessStat(e)?.startedAt??null}function getProcessInstanceStartTime(e){if(!isValidPid(e))return null;if(hasLinuxProcfs()){let t=getProcessStartTime(e);return Number.isSafeInteger(t)?t:null}let t=readDarwinNativeIdentity(e);if(!t)return null;let n=t.startTimeMicros;return Number.isSafeInteger(n)?n:null}function getFileLockProcessStartTime(e,t=process.env,n){if(!isValidPid(e))return null;let r=e===process.pid;if(r&&qn!==null)return qn;let i=process.platform===`darwin`?getDarwinProcessStartTime(e,t,n):process.platform===`win32`?readWindowsProcessStartTimeSync(e,n,t):process.platform===`freebsd`?readFreeBsdProcessStartTime(e):getProcessStartTime(e);return r&&i!==null&&(qn=i),i}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??isPidDefinitelyDead)(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??getFileLockProcessStartTime)(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 k=C().min(1).max(4096),Jn={pid:Rt().int().positive(),startIdentity:k.max(128)},Yn=w({...Jn,startIdentitySource:T(`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:`)),Xn=Ft([w({platform:Lt([`linux`,`darwin`]),identity:C().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i)}),w({platform:T(`win32`),identity:C().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/)}),w({platform:T(`freebsd`),identity:C().regex(/^[a-f0-9]{32}$/)})]),Zn=w({kind:T(`native`),unit:k,scope:k,placement:Nt(`kind`,[w({kind:T(`pending`)}),w({kind:T(`attached`),invocation:C().regex(/^[a-f0-9]{32}$/i)})])}),Qn=T(`original-cancellation-v1`),$n=w({kind:T(`update`),mutationProtocol:Qn}).extend({mutationProtocol:Qn.optional(),custody:Lt([`reserved`,`bound`]).optional()}),er=Nt(`kind`,[$n,w({kind:T(`triage`),phase:Lt([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:Nt(`kind`,[w({kind:T(`foreground`),boot:Xn}),Zn])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]),tr=k.refine(E.isAbsolute,`Native source path must be absolute`),nr=C().regex(/^[a-f0-9]{64}$/),rr=w({runId:k,transactionId:k,claimId:k,revision:Rt().int().nonnegative(),recordSha256:nr,serviceKey:tr,configPaths:It(tr).min(1).max(512),lifetimeId:k}),ir=w({id:C().uuid(),phase:Lt([`reserved`,`admitted`]),source:rr}),ar={executor:Yn,helper:Yn,action:er},or=w({version:T(2),executor:Yn,helper:Yn,action:$n}),sr=w({key:k,owner:k,payload:C().min(1),updatedAt:Rt().int().nonnegative()}),cr=w({version:T(4),executor:Yn,helper:Yn,action:$n,cancellation:sr}).refine(e=>{let t=safeParseJsonWithSchema(or,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`)}),lr=w({version:T(2),...ar,mutationOriginal:sr.optional()}).refine(e=>{if(!e.mutationOriginal)return!0;let t=safeParseJsonWithSchema(or,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`});Nt(`version`,[cr,lr,w({version:T(3),...ar,action:w({kind:T(`update`)}),nativeBorrower:ir})]),w({version:T(1),...Jn});const ur=[`-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=D.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=Pn(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?ur: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=Xn.safeParse(r);if(!i.success)throw Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}}const[dr,fr,pr]=Xn.options,mr=C().min(1),hr=C().regex(/^[a-f0-9]{64}$/u),gr=Nt(`platform`,[dr.extend({host:mr,platform:T(`linux`),pidNsInode:C().min(1)}),dr.extend({host:mr,platform:T(`darwin`)}),fr.extend({host:mr,identity:fr.shape.identity.optional()}),pr.extend({host:mr})]);let _r;function readGatewayLockProcessNamespace(){if(_r?.platform===process.platform&&(_r.value!==null||process.platform!==`linux`&&process.platform!==`android`))return _r.value;try{let e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)(),t=gr.parse({host:bn.hostname(),...e,...e.platform===`linux`?{pidNsInode:D.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});return _r={platform:process.platform,value:t},t}catch{return _r={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 D.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=gr.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=gr.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=gr.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)&&isContainerEnvironment())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=hr.safeParse(t.machineIdentity).data,i=_t();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 vr=Pt({pid:Rt(),ownerId:C().min(1).optional(),stateOwnerKind:T(`schema`).optional(),cronOwnerProjection:T(`dynamic-default-v1`).optional(),createdAt:C(),startupPhase:T(`starting`).optional(),configPath:C(),port:Rt().int().min(1).max(65535).optional(),role:Lt([`gateway`,`agent-embedded`,`skill-workshop-apply`,`sqlite-maintenance`]).optional(),stateDir:C().optional(),startTime:Rt().optional(),parentPid:Rt().int().positive().optional(),parentStartTime:Rt().optional(),processNamespace:gr.nullable().optional(),machineIdentity:hr.nullable().optional()});function parseGatewayLockPayload(e){return safeParseJsonWithSchema(vr,e)}function createGatewayStateProcessOwnerRetiredError(){return/* @__PURE__ */ Error(`OpenClaw state process owner is no longer current`)}const yr=a(Symbol.for(`openclaw.stateDatabaseAccessError`),()=>class extends Error{constructor(...e){super(...e),this.name=`StateDatabaseAccessError`}}),br=a(Symbol.for(`openclaw.gatewayStateOwnerContentionError`),()=>class extends Error{constructor(e,t,n,r){super(`OpenClaw state database is busy at ${e}. ${n?`${n} `:``}Wait for the other OpenClaw process to finish, then retry. If it persists, run \`openclaw gateway status\` and check for other OpenClaw processes using the same state directory. A running Gateway can hold this ownership until it stops; stop it through its service manager or original terminal before retrying.`),this.databasePath=e,this.cause=t,this.holderDetail=n,this.holder=r,this.name=`GatewayStateOwnerContentionError`}}),xr=a(Symbol.for(`openclaw.stateDatabaseMaintenanceScopeError`),()=>class extends yr{constructor(e){super(`Internal state ownership error at ${e}: this process holds maintenance ownership without an active schema lease or maintenance scope. Retry the command; if it persists, report this error.`),this.name=`StateDatabaseMaintenanceScopeError`}}),Sr=a(Symbol.for(`openclaw.stateDatabaseAdmissionPendingError`),()=>class extends yr{constructor(e,t){super(t),this.databasePath=e}}),Cr=a(Symbol.for(`openclaw.stateDatabaseOfflineMaintenanceError`),()=>class extends yr{constructor(e,t){super(t),this.databasePath=e}});function createColdAdmissionBudget(e){let t=zt(e.busyTimeoutMs,`busyTimeoutMs`),n=performance.now()+t,r=At(e.databasePath);return{remainingBusyTimeoutMs:()=>Math.max(0,Math.ceil(n-performance.now())),retryDelay:t=>{if(!(t instanceof Sr)||At(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 mn(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}const wr=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);function hasRestrictivePermissions(e){try{return!(_n(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(e){let t;try{let n=_n(e).isDirectory()?e:E.dirname(e);t=E.join(n,`.openclaw-chmod-probe-${hn()}`),yn(t,``,{flag:`wx`,mode:384})}catch{return!1}try{return gn(t,384),!1}catch(e){return g(e)&&e.code===`EPERM`}finally{try{vn(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&wr.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if((_n(e).mode&4095)===t)return{applied:!0};try{return gn(e,t),{applied:!0}}catch(t){if(!canIgnorePrivateChmodError(e,g(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:!1,error:t}}}const Tr=`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=D.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let r=E.toNamespacedPath(n),i=[];for(let t=e;;){let{dev:e,ino:n}=D.lstatSync(t,{bigint:!0});if(i.push({path:t,dev:e,ino:n}),E.toNamespacedPath(t)===r)break;let a=E.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=D.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}). ${Tr}`);if(process.platform!==`win32`&&(r.mode&4095)!=448&&(applyPrivateModeSync(e,448),D.lstatSync(e).mode&63))throw Error(`State ownership directory ${e} permissions could not be set to 0700. ${Tr}`)}function removeCreatedProjectionDirectories(e){let t=e[0];for(;t;){try{let e=D.lstatSync(t.path,{bigint:!0});e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino&&D.rmdirSync(t.path)}catch(e){let t=u(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift(),t=e[0]}}function resolveStateOwnerIdentity(e){let t=At(e);return stateOwnerIdentity(t,At(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await kt(e);return stateOwnerIdentity(t,await kt(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:E.join(t,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?ne(e):e}}function stateOwnerDirectory(e){let t=process.getuid?.();return process.platform===`win32`?E.join(bn.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):r(jt(e))}async function settlesWithin(e,t){return await fe(e.then(()=>!0),t,()=>!1,{ref:!1})}function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}function captureRootSyncAcquireOptions(e){let t=e.lockPath,n=e.staleMs,r=e.timeoutMs,i=e.retry,a=e.staleRecovery,o=e.reentrantOwner,s=e.payload,c=e.shouldReclaim,l=e.shouldRemoveStaleLock,u=e.parsePayload,d=e.onCompromised,f=e.compromiseCheckIntervalMs,p=i===void 0?void 0:Object.freeze({retries:i.retries,factor:i.factor,minTimeout:i.minTimeout,maxTimeout:i.maxTimeout,randomize:i.randomize}),m=ut(),h=m.retry,ee=p??Object.freeze({retries:h?.retries,factor:h?.factor,minTimeout:h?.minTimeout,maxTimeout:h?.maxTimeout,randomize:h?.randomize}),g=r??m.timeoutMs,_=n??m.staleMs??3e4,te=a??m.staleRecovery;return st(ee),Ze(g),Xe(_),tt(f),Object.freeze({compromiseCheckIntervalMs:f,lockPath:t,onCompromised:d,optionsReceiver:e,parsePayload:u,payload:s,reentrantOwner:o,retry:ee,shouldReclaim:c,shouldRemoveStaleLock:l,staleMs:_,staleRecovery:te,timeoutMs:g})}const Er=Symbol.for(`fsSafe.syncSidecarLocks`),Dr=Symbol.for(`fsSafe.syncSidecarLockAdmissions`),Or=Symbol.for(`fsSafe.syncSidecarLockCleanupRegistered`),kr=Symbol.for(`fsSafe.syncSidecarLockCleanupHandler`),Ar=Symbol.for(`fsSafe.syncSidecarLockCleanupRegistration`),jr=Symbol.for(`fsSafe.syncRootSidecarLocks.v1`);function foreignSyncHeldLock(e,t){return globalThis[e===`raw`?jr:Er]?.get(t)}function getSyncHeldLocks(){let e=globalThis;return e[Er]||(e[Er]=/* @__PURE__ */ new Map),e[Er]}function getSyncLockAdmissions(){let e=globalThis;return e[Dr]||(e[Dr]=/* @__PURE__ */ new Map),e[Dr]}function syncReclaimGuardExists(e){try{return D.lstatSync(e,{throwIfNoEntry:!1})!==void 0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}function ensureSyncLockExitCleanupRegistered(e,t,n){at({event:`exit`,registered:Or,registering:Ar,handler:kr,reentryError:()=>Ye(t,n)},e,!0)}var SyncLockAcquisition=class{lockPath;normalizedTargetPath;retry;timeoutMs;#e=getSyncLockAdmissions();#t={};#n=!1;#r=performance.now();#i=0;#a=0;constructor(e,t,n,r){this.lockPath=e,this.normalizedTargetPath=t,this.retry=n,this.timeoutMs=r}get owns(){return this.#n}hasToken(){return this.#e.get(this.normalizedTargetPath)===this.#t}assert(){if(!this.hasToken())throw Ye(this.lockPath,this.normalizedTargetPath)}reserve(){if(!this.#n){if(this.#e.has(this.normalizedTargetPath))throw Ye(this.lockPath,this.normalizedTargetPath);this.#e.set(this.normalizedTargetPath,this.#t),this.#n=!0}}release(){this.#n&&this.hasToken()&&this.#e.delete(this.normalizedTargetPath),this.#n=!1}run(e){this.assert();try{return e()}finally{this.assert()}}waitForRetry(){this.release();let e=rt(this.retry,this.timeoutMs,performance.now()-this.#r,this.#i);if(e===void 0)throw Ye(this.lockPath,this.normalizedTargetPath);re(e),this.#i+=1}retryDenial(e){if(!Je(e,this.lockPath)||++this.#a>8)return!1;try{this.waitForRetry()}catch(t){throw t?.code===`file_lock_timeout`?e:t}return!0}monitor(e,t,n,r,i,a){if(!n||(r??0)<=0)return;let{lockPath:o,normalizedTargetPath:s}=this,c=setInterval(()=>{let r;try{r=t.verifyStillHeld()}catch{r=!1}!r&&e.timer&&(clearInterval(e.timer),e.timer=void 0,Reflect.apply(n,i,[{lockPath:o,normalizedTargetPath:s}]))},r);a?.(c),e.timer=c,c.unref()}};function observeDirectory(e,t){let n=pe(e,void 0,t),r=de.native(y(e));if(b(r,`filesystem`,`sidecar lock parent uses a Windows filesystem namespace alias`),!Ue(r,e))throw new S(`path-mismatch`,`sidecar lock parent changed during operation`);return Object.freeze({identity:Object.freeze({dev:n.dev,ino:n.ino}),path:e,realPath:r})}function assertDirectoryCurrent(e,t){pe(e.path,e.identity,t);let n=de.native(y(e.path));if(b(n,`filesystem`,`sidecar lock parent uses a Windows filesystem namespace alias`),n!==e.realPath)throw new S(`path-mismatch`,`sidecar lock parent changed during operation`)}function assertRetainedParentCurrent(e,t){let n=e.authority.context,r=t.path===n.rootReal&&t.identity.dev===n.rootIdentity.dev&&t.identity.ino===n.rootIdentity.ino,i;_e(n,r?e=>{i=e}:void 0),assertDirectoryCurrent(t,i),_e(n)}function exactFileIdentity(e){return Object.freeze({dev:e.dev,ino:e.ino})}function assertRegularFile(e,t){if(e.isSymbolicLink()||!e.isFile())throw new S(`not-file`,`sidecar lock is not a regular file`);if(t!==`allow`&&e.nlink>1n)throw ce()}function sameExactIdentity(e,t){return e.dev===t.dev&&e.ino===t.ino}function assertFreshPathCurrent(e){Ne(e),_e(e.authority.context)}function missingAfterCurrentRead(e,t){return t?assertRetainedParentCurrent(e,t.parent):assertFreshPathCurrent(e),null}function readFileLockSyncRootSnapshot(e,t={}){let n=t.expectedReceipt;n?assertRetainedParentCurrent(e,n.parent):assertFreshPathCurrent(e);let r;try{r=x(()=>D.lstatSync(y(e.path),{bigint:!0}),n?.identity)}catch(t){if(v(t)||n&&t instanceof S&&t.code===`path-mismatch`)return missingAfterCurrentRead(e,n);throw t}assertRegularFile(r,e.authority.hardlinks);let i=n?.parent??observeDirectory(E.dirname(e.path)),a,o,s=!1;try{try{a=D.openSync(y(e.path),me())}catch(r){if(v(r))return missingAfterCurrentRead(e,n);throw t.onOpenFailure?.(r),r}let o;try{o=x(()=>D.fstatSync(a,{bigint:!0}),exactFileIdentity(r))}catch(t){if(t instanceof S&&t.code===`path-mismatch`)return n?assertRetainedParentCurrent(e,i):(assertDirectoryCurrent(i),assertFreshPathCurrent(e)),null;throw t}assertRegularFile(o,e.authority.hardlinks);let s=oe(a,1048576).toString(`utf8`),c;try{c=x(()=>D.lstatSync(y(e.path),{bigint:!0}),exactFileIdentity(o))}catch(t){if(v(t)||t instanceof S&&t.code===`path-mismatch`)return n?assertRetainedParentCurrent(e,i):(assertDirectoryCurrent(i),assertFreshPathCurrent(e)),null;throw t}assertRegularFile(c,e.authority.hardlinks);let l=D.fstatSync(a,{bigint:!0});n?assertRetainedParentCurrent(e,i):(assertDirectoryCurrent(i),assertFreshPathCurrent(e));let u={raw:s,payload:null,stat:l};return Object.freeze({receipt:Object.freeze({identity:exactFileIdentity(o),parent:i}),snapshot:u})}catch(e){throw s=!0,o=e,e}finally{if(a!==void 0)try{D.closeSync(a)}catch(e){throw s?Ke(e,o,`sidecar snapshot admission and descriptor close both failed`):e}}}function fileLockSyncRootSnapshotStillCurrent(e,t){let n=readFileLockSyncRootSnapshot(e,{expectedReceipt:t.receipt});return!!n&&sameExactIdentity(n.receipt.identity,t.receipt.identity)&&lt(n.snapshot,t.snapshot)}function fileReceiptCurrentAfterParentCheck(e,t){let n;try{n=x(()=>D.lstatSync(y(e.path),{bigint:!0}),t.identity)}catch(e){if(v(e)||e instanceof S&&e.code===`path-mismatch`)return!1;throw e}return assertRegularFile(n,e.authority.hardlinks),assertRetainedParentCurrent(e,t.parent),!0}function fileLockSyncRootReceiptStillCurrent(e,t){return assertRetainedParentCurrent(e,t.parent),fileReceiptCurrentAfterParentCheck(e,t)}function ensureParent(e){let t=e.authority,n=t.context;Ne(e);let r=E.dirname(e.path),i=ae({rootPath:n.rootReal,candidatePath:r,rootIdentity:n.rootIdentity});if(!i)throw ie();let a=i.relativePath,o=n.rootReal,s=observeDirectory(o);for(let r of a.split(E.sep).filter(Boolean)){let i=E.join(o,r);_e(n),assertDirectoryCurrent(s);let a=!1,c;try{if(c=D.lstatSync(y(i),{bigint:!0}),c.isSymbolicLink()||!c.isDirectory())throw ue()}catch(e){if(!v(e))throw e;a=!0}if(a){He(i,t.denyMutations);let r=Ae(t);r&&Ne(e),assertDirectoryCurrent(s),_e(n),r&&He(i,t.denyMutations);try{D.mkdirSync(y(i))}catch(e){if(e.code!==`EEXIST`)throw e}}let l=observeDirectory(i,c);assertDirectoryCurrent(s),o=l.realPath,s=l}return _e(n),assertDirectoryCurrent(s),s}function createFileLockSyncRootFile(e,t){let n=ensureParent(e);Ae(e.authority)&&(Ne(e),assertRetainedParentCurrent(e,n));let r=process.platform!==`win32`&&typeof D.constants.O_NOFOLLOW==`number`?D.constants.O_NOFOLLOW:0,i,a;try{t.assertBeforeOpen();try{te(y(e.path))}catch(e){throw e.code===`EEXIST`&&t.onOpenFailure(e),e}try{i=D.openSync(y(e.path),D.constants.O_WRONLY|D.constants.O_CREAT|D.constants.O_EXCL|r,384)}catch(e){throw t.onOpenFailure(e),e}let o=x(()=>D.fstatSync(i,{bigint:!0}));if(assertRegularFile(o,e.authority.hardlinks),a=Object.freeze({identity:exactFileIdentity(o),parent:n}),!fileReceiptCurrentAfterParentCheck(e,a))throw new S(`path-mismatch`,`created sidecar lock changed before admission`);return{fd:i,receipt:a}}catch(t){if(i===void 0)throw t;let n=i;i=void 0;try{if(D.closeSync(n),a&&!removeFileLockSyncRootFile(e,a))throw new S(`path-mismatch`,`created sidecar lock changed before cleanup`)}catch(e){throw Ke(t,e,`file lock create admission and cleanup both failed`)}throw t}}function refreshFileLockSyncRootFileReceipt(e,t){if(!fileReceiptCurrentAfterParentCheck(e,t))throw new S(`path-mismatch`,`created sidecar lock changed before admission`);return t}function removeFileLockSyncRootFile(e,t,n,r){He(e.path,e.authority.denyMutations);let matches=()=>{if(!n)return fileLockSyncRootReceiptStillCurrent(e,t);let r=readFileLockSyncRootSnapshot(e,{expectedReceipt:t});return!!r&&sameExactIdentity(r.receipt.identity,t.identity)&&lt(r.snapshot,n)};if(!matches()||Ae(e.authority)&&!matches()||r?.()===!1)return!1;He(e.path,e.authority.denyMutations),D.unlinkSync(y(e.path)),assertRetainedParentCurrent(e,t.parent);let i;try{i=x(()=>D.lstatSync(y(e.path),{bigint:!0}))}catch(e){if(v(e))return!0;throw e}if(assertRegularFile(i,e.authority.hardlinks),assertRetainedParentCurrent(e,t.parent),!sameExactIdentity(exactFileIdentity(i),t.identity))return!0;if(n){let r=readFileLockSyncRootSnapshot(e);if(assertRetainedParentCurrent(e,t.parent),r){if(!sameExactIdentity(r.receipt.identity,t.identity)||!lt(r.snapshot,n))return!0}else{let n;try{n=x(()=>D.lstatSync(y(e.path),{bigint:!0}))}catch(n){if(v(n))return assertRetainedParentCurrent(e,t.parent),!0;throw n}if(assertRegularFile(n,e.authority.hardlinks),assertRetainedParentCurrent(e,t.parent),!sameExactIdentity(exactFileIdentity(n),t.identity))return!0}}throw new S(`path-mismatch`,`sidecar lock was replaced during removal`)}function fileLockSyncRootGuardExists(e){_e(e.authority.context);let t;try{t=D.lstatSync(y(e.path),{bigint:!0})}catch(t){if(v(t))return Ne(e),_e(e.authority.context),!1;throw t}if(t.isSymbolicLink()||!t.isDirectory()&&!t.isFile())throw ue();t.isFile()&&assertRegularFile(t,e.authority.hardlinks);let n=observeDirectory(E.dirname(e.path));return t.isFile()?assertRegularFile(x(()=>D.lstatSync(y(e.path),{bigint:!0}),exactFileIdentity(t)),e.authority.hardlinks):pe(e.path,exactFileIdentity(t)),assertDirectoryCurrent(n),Ne(e),_e(e.authority.context),!0}function createFileLockSyncRootDirectory(e){let t=ensureParent(e);Ae(e.authority)&&(Ne(e),assertRetainedParentCurrent(e,t));try{D.mkdirSync(y(e.path))}catch(e){if(e.code===`EEXIST`)return null;throw e}let n=pe(e.path),r=Object.freeze({identity:exactFileIdentity(n),parent:t});return assertRetainedParentCurrent(e,t),pe(e.path,r.identity),r}function removeFileLockSyncRootDirectory(e,t){return!fileLockSyncRootDirectoryReceiptStillCurrent(e,t)||(He(e.path,e.authority.denyMutations,!0),Ae(e.authority)&&!fileLockSyncRootDirectoryReceiptStillCurrent(e,t))?!1:(He(e.path,e.authority.denyMutations,!0),D.rmdirSync(y(e.path)),assertRetainedParentCurrent(e,t.parent),!0)}function fileLockSyncRootDirectoryReceiptStillCurrent(e,t){assertRetainedParentCurrent(e,t.parent);try{pe(e.path,t.identity)}catch(e){if(v(e)||e instanceof S&&e.code===`path-mismatch`)return!1;throw e}return assertRetainedParentCurrent(e,t.parent),!0}const Mr=Symbol.for(`fsSafe.syncRootSidecarLockCleanupRegistering.v1`),Nr=Symbol.for(`fsSafe.syncRootSidecarLockCleanupRegistered.v1`),Pr=Symbol.for(`fsSafe.syncRootSidecarLockCleanupRegistrationFailed.v1`),Fr=Symbol.for(`fsSafe.syncRootSidecarLockCleanupHandler.v1`);function unavailable(e){return new S(`helper-unavailable`,e)}function exactListenerCount(e){return process.listeners(`exit`).filter(t=>t===e).length}function ensureFileLockSyncRootExitCleanupRegistered(e){let t=globalThis;if(t[Nr]){if(typeof t[Fr]==`function`)return;throw t[Pr]=!0,unavailable(`Root sidecar exit cleanup registration state is inconsistent`)}if(t[Pr])throw unavailable(`Root sidecar exit cleanup registration previously failed`);if(t[Mr])throw unavailable(`Root sidecar exit cleanup registration is already in progress`);if(t[Fr]!==void 0)throw t[Pr]=!0,unavailable(`Root sidecar exit cleanup handler exists without registration`);t[Mr]=!0;let n,r=!1,i=!1;try{if(n=exactListenerCount(e),n!==0)throw i=!0,unavailable(`Root sidecar exit cleanup listener exists without registration`);if(r=!0,process.on(`exit`,e),exactListenerCount(e)!==n+1)throw unavailable(`Root sidecar exit cleanup listener was not registered exactly once`);t[Fr]=e,t[Nr]=!0,t[Pr]=!1,t[Mr]=!1}catch(a){let o=!1,s;if(r&&n!==void 0)try{let t=exactListenerCount(e);for(;t>n;){process.removeListener(`exit`,e);let n=exactListenerCount(e);if(n>=t)throw unavailable(`Root sidecar exit cleanup listener rollback made no progress`);t=n}if(t!==n)throw unavailable(`Root sidecar exit cleanup listener rollback was ambiguous`)}catch(e){o=!0,s=e}throw t[Fr]=void 0,t[Nr]=!1,t[Mr]=!1,i?(t[Pr]=!0,a):o?(t[Pr]=!0,Ke(a,s,`Root sidecar exit cleanup registration and rollback both failed`)):(t[Pr]=!1,a)}}const Ir=Symbol.for(`fsSafe.syncRootSidecarLocks.v1`),Lr=Symbol.for(`fsSafe.syncRootSidecarLockCleanupActive.v1`),Rr=/* @__PURE__ */ new WeakMap;function readRootSyncHeldReleaseState(e){return e.releaseState}function readRootSidecarSnapshotSync(e,t,n,r){let i=readFileLockSyncRootSnapshot(e,{expectedReceipt:r,onOpenFailure:n});if(!i)return null;let a;try{a=it(i.snapshot.raw,t)}catch(n){if(t)try{if(!fileLockSyncRootSnapshotStillCurrent(e,i))throw new S(`path-mismatch`,`sidecar changed during payload parsing`)}catch(e){throw Ke(n,e,`sidecar parser and post-callback admission both failed`)}throw n}return t&&!fileLockSyncRootSnapshotStillCurrent(e,i)?null:{receipt:i.receipt,snapshot:{...i.snapshot,payload:a}}}function getRootSyncHeldLocks(){let e=globalThis;return e[Ir]||(e[Ir]=/* @__PURE__ */ new Map),e[Ir]}function reactivateExactHeldLock(e,t,n){return e.get(t.normalizedTargetPath)!==t||t.releaseState===`released`?!1:(n&&(t.refCount+=1),t.releaseState=`active`,t.revision+=1,!0)}function finishDeferredExitReleases(e){let t=e.deferredExitReleases;if(t){for(let e of t)e.released=!0;t.clear(),e.deferredExitReleases=void 0}}function restoreDeferredExitReleases(e){let t=e.deferredExitReleases;if(!t)return 0;let n=t.size;return t.clear(),e.deferredExitReleases=void 0,n}function restoreExactHeldLockAfterExitCleanup(e,t){e.get(t.normalizedTargetPath)===t&&t.releaseState!==`released`&&(t.refCount+=restoreDeferredExitReleases(t),t.refCount<=0?(t.releaseState=`released`,t.revision+=1,e.delete(t.normalizedTargetPath)):(t.releaseState=`active`,t.revision+=1))}function releaseAllRootSyncHeldLocks(){let e=globalThis;if(!e[Lr]){e[Lr]=!0;try{let e=globalThis[Ir];if(!e)return;getSyncLockAdmissions().clear();for(let[t,n]of e){if(e.get(t)!==n||n.releaseState!==`active`)continue;n.releaseState=`exit-cleaning`,n.revision+=1;let r=n.revision,i=n.timer,a=n.fd;n.timer=void 0,n.fd=void 0,i&&clearInterval(i);try{a!==void 0&&D.closeSync(a)}catch{}let entryIsContinuous=()=>e.get(t)===n&&n.releaseState===`exit-cleaning`&&n.revision===r,beginFreshCleanupAttempt=()=>{n.releaseState=`exit-cleaning`,n.revision+=1,r=n.revision};if(!entryIsContinuous()){if(e.get(t)===n&&readRootSyncHeldReleaseState(n)!==`released`&&n.refCount===0)beginFreshCleanupAttempt();else{restoreExactHeldLockAfterExitCleanup(e,n);continue}}let o=!1;for(let r=0;r<2;r+=1){let i=!1,a=!1,s=!1;try{s=removeFileLockSyncRootFile(n.rootPath,n.rootReceipt,n.snapshot,()=>{let e=entryIsContinuous();return e||(i=!0),e})}catch{a=!0}if(!a&&s&&!i&&entryIsContinuous()){o=!0;break}let c=entryIsContinuous();if(e.get(t)===n&&readRootSyncHeldReleaseState(n)!==`released`&&(i||!c)&&n.refCount===0&&r+1<2)beginFreshCleanupAttempt();else{if(c&&n.refCount>0){o=!0;break}restoreExactHeldLockAfterExitCleanup(e,n);break}}o&&(finishDeferredExitReleases(n),n.releaseState=`released`,n.revision+=1,e.get(t)===n&&e.delete(t))}}finally{e[Lr]=!1}}}function ensureRootSyncExitCleanupRegistered(){ensureFileLockSyncRootExitCleanupRegistered(releaseAllRootSyncHeldLocks)}function verifyRootSyncHeldLock(e){let t=e.rootPath,n=e.parsePayload,r=e.rootReceipt,i=n?readRootSidecarSnapshotSync(t,n,void 0,r):readFileLockSyncRootSnapshot(t,{expectedReceipt:r});return i?i.receipt.identity.dev===e.rootReceipt.identity.dev&&i.receipt.identity.ino===e.rootReceipt.identity.ino&&lt(i.snapshot,e.snapshot):!1}function releaseRootSyncHeldLock(e,t){let n=getRootSyncHeldLocks();if(n.get(e.normalizedTargetPath)!==e||e.releaseState===`released`)return!0;if(e.releaseState!==`active`){if(e.deferredExitReleases?.has(t)||e.refCount<=0)return!1;if(!fileLockSyncRootReceiptStillCurrent(e.rootPath,e.rootReceipt))throw new S(`path-mismatch`,`held sidecar lock changed before release`);return--e.refCount,e.revision+=1,e.releaseState!==`exit-cleaning`||e.refCount>0||((e.deferredExitReleases??=/* @__PURE__ */ new Set).add(t),!1)}if(e.refCount>1){if(!fileLockSyncRootReceiptStillCurrent(e.rootPath,e.rootReceipt))throw new S(`path-mismatch`,`held sidecar lock changed before release`);return--e.refCount,e.revision+=1,!0}if(e.refCount!==1)return!1;e.refCount=0,e.releaseState=`releasing`,e.revision+=1;let r=e.revision,entryIsContinuous=()=>n.get(e.normalizedTargetPath)===e&&e.releaseState===`releasing`&&e.revision===r&&e.refCount===0,beginFreshReleaseAttempt=()=>{e.releaseState=`releasing`,e.revision+=1,r=e.revision},i=e.fd;e.fd=void 0;try{i!==void 0&&D.closeSync(i)}catch(t){throw reactivateExactHeldLock(n,e,!0),t}if(!entryIsContinuous()){if(n.get(e.normalizedTargetPath)!==e||readRootSyncHeldReleaseState(e)===`released`)return!0;if(e.refCount>0)return reactivateExactHeldLock(n,e,!1),!0;beginFreshReleaseAttempt()}for(let t=0;t<2;t+=1){let r=!1,i;try{i=removeFileLockSyncRootFile(e.rootPath,e.rootReceipt,e.snapshot,()=>{let e=entryIsContinuous();return e||(r=!0),e})}catch(t){throw reactivateExactHeldLock(n,e,!0),t}if(!r&&entryIsContinuous()){if(!i)throw reactivateExactHeldLock(n,e,!0),new S(`path-mismatch`,`owned sidecar lock changed before release`);let t=e.timer;return e.timer=void 0,e.releaseState=`released`,e.revision+=1,n.get(e.normalizedTargetPath)===e&&n.delete(e.normalizedTargetPath),t&&clearInterval(t),!0}if(n.get(e.normalizedTargetPath)!==e||readRootSyncHeldReleaseState(e)===`released`)return!0;if(e.refCount>0)return reactivateExactHeldLock(n,e,!1),!0;if(e.refCount===0&&t+1<2)beginFreshReleaseAttempt();else throw reactivateExactHeldLock(n,e,!0),new S(`path-mismatch`,`held sidecar release continuity changed repeatedly`)}throw new S(`path-mismatch`,`held sidecar release could not complete`)}function createRootSyncHeldLockHandle(e){let t={held:e,released:!1},n=!1,release=()=>{if(!(t.released||n)){n=!0;try{releaseRootSyncHeldLock(e,t)&&(t.released=!0)}finally{n=!1}}},r={lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,verifyStillHeld:()=>verifyRootSyncHeldLock(e),release,[Symbol.dispose]:release};return Rr.set(r,t),r}var FileLockSyncRootArbitrationCollision=class extends S{constructor(){super(`path-mismatch`,`file lock arbitration changed during local creation`)}};function cleanupCreatedRootSyncLock(e,t,n,r){let i=!1,a;try{r&&clearInterval(r)}catch(e){i=!0,a=e}try{if(D.closeSync(t),!removeFileLockSyncRootFile(e,n))throw new S(`path-mismatch`,`created sidecar lock changed before cleanup`)}catch(e){throw i?Ke(a,e,`unpublished lock timer and file cleanup both failed`):e}if(i)throw a}function acquireFileLockSyncWithRoot(e,t,n){let r=We(n),i=captureRootSyncAcquireOptions(t);ensureRootSyncExitCleanupRegistered(),b(e),i.lockPath!==void 0&&b(i.lockPath);let a=E.resolve(e),o=ke(r,a),s=E.resolve(i.lockPath??`${o}.lock`),c=je(r,s),l=je(r,`${c.path}.reclaim`),u=Object.freeze([c,l]),d=c.path,f=getRootSyncHeldLocks(),currentTargetHolder=()=>f.get(o)??foreignSyncHeldLock(`root`,o),tryReuseCurrentHeld=()=>{let e=f.get(o);if(e&&!foreignSyncHeldLock(`root`,o)&&i.reentrantOwner!==void 0&&e.reentrantOwner!==void 0&&i.reentrantOwner===e.reentrantOwner&&r.adapter===e.rootAuthority.adapter&&c.relativePath===e.rootPath.relativePath&&E.relative(c.path,e.rootPath.path)===``&&e.releaseState!==`released`){if(!verifyRootSyncHeldLock(e))throw new S(`path-mismatch`,`held sidecar lock changed before reentrant reuse`);if(f.get(o)!==e||e.releaseState===`released`||foreignSyncHeldLock(`root`,o))throw new S(`path-mismatch`,`held sidecar lock changed during reentrant reuse`);return e.refCount+=1,e.revision+=1,createRootSyncHeldLockHandle(e)}};if(f.has(o)&&!foreignSyncHeldLock(`root`,o)){Ge(u);let e=tryReuseCurrentHeld();if(e)return e}let p=new SyncLockAcquisition(d,o,i.retry,i.timeoutMs),m,h=!1,reuseCurrentHeld=()=>m?void 0:tryReuseCurrentHeld(),releaseReclaimGuard=()=>{let e=m;if(e){if(h=!0,!removeFileLockSyncRootDirectory(l,e))throw new S(`path-mismatch`,`owned sidecar reclaim guard changed before release`);m=void 0,h=!1}},assertOwnedReclaimGuardCurrent=()=>{let e=m;if(!e||!fileLockSyncRootDirectoryReceiptStillCurrent(l,e))throw new S(`path-mismatch`,`owned sidecar reclaim guard changed during acquisition`)};try{for(;;){if(p.reserve(),p.assert(),Ge(u),p.assert(),m&&assertOwnedReclaimGuardCurrent(),!m&&fileLockSyncRootGuardExists(l)){p.waitForRetry();continue}if(currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e}let e=Reflect.apply(i.payload,i.optionsReceiver,[]);p.assert();let{raw:t,ownershipToken:n}=ct(e);if(p.assert(),m&&assertOwnedReclaimGuardCurrent(),currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}let a,s,ee,g;try{let l=createFileLockSyncRootFile(c,{assertBeforeOpen:()=>{if(p.assert(),m&&assertOwnedReclaimGuardCurrent(),currentTargetHolder()!==void 0)throw new FileLockSyncRootArbitrationCollision},onOpenFailure:e=>{g={error:e}}});a=l.fd,s=l.receipt,D.writeFileSync(a,t,`utf8`),D.fsyncSync(a);let u={raw:t,payload:e,ownershipToken:n};m&&releaseReclaimGuard(),s=refreshFileLockSyncRootFileReceipt(c,s);let h={fd:a,lockPath:d,normalizedTargetPath:o,parsePayload:i.parsePayload,refCount:1,reentrantOwner:i.reentrantOwner,releaseState:`active`,revision:0,rootAuthority:r,rootPath:c,rootReceipt:s,snapshot:u},_=createRootSyncHeldLockHandle(h);if(p.monitor(h,_,i.onCompromised,i.compromiseCheckIntervalMs,i.optionsReceiver,e=>{ee=e}),currentTargetHolder()!==void 0)throw new FileLockSyncRootArbitrationCollision;return p.assert(),f.set(o,h),a=void 0,ee=void 0,_}catch(e){if(a!==void 0&&s){let t=a,n=s,r=ee;a=void 0,s=void 0,ee=void 0;try{cleanupCreatedRootSyncLock(c,t,n,r)}catch(t){throw Ke(e,t,`file lock acquisition and Root cleanup both failed`)}}if(e instanceof FileLockSyncRootArbitrationCollision){let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}let t=g!==void 0&&g.error===e;if(t&&p.retryDenial(e))continue;if(!t||e.code!==`EEXIST`)throw e;if(m){releaseReclaimGuard();let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}if(currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}let n=!1,r;try{r=readRootSidecarSnapshotSync(c,i.parsePayload,e=>{n=Je(e,d)})}catch(e){if(n&&p.retryDenial(e))continue;throw e}if(currentTargetHolder()!==void 0){let e=reuseCurrentHeld();if(e)return e;p.waitForRetry();continue}if(p.assert(),!r){p.waitForRetry();continue}let u=r.snapshot,f=Date.now(),_;if(i.shouldReclaim){if(_=Reflect.apply(i.shouldReclaim,i.optionsReceiver,[{lockPath:d,normalizedTargetPath:o,payload:u.payload,staleMs:i.staleMs,nowMs:f,heldByThisProcess:!1}]),Oe(_,`shouldReclaim`),p.assert(),!fileLockSyncRootSnapshotStillCurrent(c,r))throw new S(`path-mismatch`,`sidecar changed during reclaim policy callback`)}else _=et(u,i.staleMs,f);if(_){if(i.staleRecovery===`remove-if-unchanged`&&u.raw!==void 0&&i.shouldRemoveStaleLock){let e=createFileLockSyncRootDirectory(l);if(!e){p.waitForRetry();continue}m=e,h=!1;let t=Reflect.apply(i.shouldRemoveStaleLock,i.optionsReceiver,[{lockPath:d,normalizedTargetPath:o,raw:u.raw,payload:u.payload}]);if(Oe(t,`shouldRemoveStaleLock`),p.assert(),assertOwnedReclaimGuardCurrent(),t){if(!removeFileLockSyncRootFile(c,r.receipt,u,()=>{if(p.assert(),assertOwnedReclaimGuardCurrent(),currentTargetHolder()!==void 0)throw new FileLockSyncRootArbitrationCollision}))throw new S(`path-mismatch`,`stale sidecar changed before removal`);continue}if(!fileLockSyncRootSnapshotStillCurrent(c,r))throw new S(`path-mismatch`,`sidecar changed during stale-removal policy callback`);releaseReclaimGuard()}throw ot(d,o)}p.waitForRetry()}}}catch(e){if(m&&!h)try{releaseReclaimGuard()}catch(t){throw Ke(e,t,`file lock acquisition and reclaim cleanup both failed`)}throw e}finally{p.release()}}function handleSyncStaleAdmission(e,t){let n={},assertUnheld=()=>{if(e.assert(),t.currentHeld())throw n},retryHolderChange=t=>t===n&&(e.waitForRetry(),!0),r,i=!1;try{r=$e(e.lockPath,{rejectNonFile:!0,onOpenFailure:()=>{i=!0,assertUnheld()}}),assertUnheld()}catch(t){if(retryHolderChange(t))return;try{assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}if(i&&e.retryDenial(t))return;throw t}let a=t.staleOptions;try{a.shouldReclaimObserved||(assertUnheld(),a.shouldReclaim=t.options.shouldReclaim,a.shouldReclaimObserved=!0,assertUnheld()),a.shouldRemoveObserved||(assertUnheld(),a.shouldRemove=t.options.shouldRemoveStaleLock,a.shouldRemoveObserved=!0,assertUnheld())}catch(e){if(retryHolderChange(e))return;try{assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}throw e}let o=t.parsePayload&&(e=>{assertUnheld();try{return Reflect.apply(t.parsePayload,void 0,[e])}finally{assertUnheld()}}),s;try{s=nt(r,o),assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}if(!s){e.waitForRetry();return}let c=Date.now(),l;try{assertUnheld();try{l=a.shouldReclaim?Reflect.apply(a.shouldReclaim,t.options,[{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,payload:s.payload,staleMs:t.staleMs,nowMs:c,heldByThisProcess:!1}]):et(s,t.staleMs,c),Oe(l,`shouldReclaim`)}finally{assertUnheld()}}catch(e){if(retryHolderChange(e))return;throw e}if(!l)e.waitForRetry();else{if(t.staleRecovery===`remove-if-unchanged`&&s.raw!==void 0&&a.shouldRemove!==void 0){let r;try{assertUnheld();try{r=Reflect.apply(a.shouldRemove,t.options,[{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,raw:s.raw,payload:s.payload}]),Oe(r,`shouldRemoveStaleLock`)}finally{assertUnheld()}}catch(e){if(retryHolderChange(e))return;throw e}if(!r)throw ot(e.lockPath,e.normalizedTargetPath);try{D.mkdirSync(t.reclaimGuardPath)}catch(t){try{assertUnheld()}catch(e){if(retryHolderChange(e))return;throw e}if(t.code===`EEXIST`){e.waitForRetry();return}throw t}let i=!1;try{if(assertUnheld(),qe(e.lockPath,s,assertUnheld))return}catch(e){if(e===n)i=!0;else throw e}finally{try{D.rmdirSync(t.reclaimGuardPath)}catch{}}if(i){e.waitForRetry();return}}throw ot(e.lockPath,e.normalizedTargetPath)}}function releaseAllSyncHeldLocks(){let e=getSyncHeldLocks();for(let[t,n]of e){n.timer&&=(clearInterval(n.timer),void 0);try{n.fd!==void 0&&D.closeSync(n.fd)}catch{}try{qe(n.lockPath,n.snapshot)}catch{}e.delete(t)}getSyncLockAdmissions().clear()}function verifySyncHeldLock(e){let t=e.lockPath,n=e.parsePayload,r=n?Qe(t,n):$e(t);return!!r&&lt(r,e.snapshot)}function releaseSyncHeldLock(e){let t=getSyncHeldLocks();if(t.get(e.normalizedTargetPath)!==e)return!1;if(e.refCount>1)return--e.refCount,!1;if(e.timer&&=(clearInterval(e.timer),void 0),e.fd!==void 0){let t=e.fd;e.fd=void 0,D.closeSync(t)}return qe(e.lockPath,e.snapshot),t.delete(e.normalizedTargetPath),!0}function createSyncHeldLockHandle(e){let t=!1,release=()=>{t||=(releaseSyncHeldLock(e),!0)};return{lockPath:e.lockPath,normalizedTargetPath:e.normalizedTargetPath,verifyStillHeld:()=>verifySyncHeldLock(e),release,[Symbol.dispose]:release}}function canonicalLockParentSync(e){return process.platform===`win32`?de.native(e):de(e)}function normalizeTargetPath(e){let t=E.resolve(e);b(t);let n=E.dirname(t),r=!1;try{r=D.statSync(n).isDirectory()}catch{}r||D.mkdirSync(he(n),{recursive:!0});let i;try{i=canonicalLockParentSync(E.dirname(t))}catch{return t}b(i);let a=E.join(i,E.basename(t));return b(a),a}function acquireFileLockSync(e,t){let n=t.lockRoot;if(n)return acquireFileLockSyncWithRoot(e,t,n);let r=ut(),i=t.retry??r.retry??{},a=t.timeoutMs??r.timeoutMs;st(i),Ze(a);let o=t.staleMs??r.staleMs??3e4;Xe(o);let s=t.compromiseCheckIntervalMs;tt(s);let c=t.lockPath;b(e),c!==void 0&&b(c);let l=normalizeTargetPath(e),u=E.resolve(c??`${l}.lock`);b(u);let d=t.reentrantOwner,f=getSyncHeldLocks(),currentTargetHolder=()=>f.get(l)??foreignSyncHeldLock(`raw`,l),p=f.get(l);if(p&&!foreignSyncHeldLock(`raw`,l)&&d!==void 0&&p.reentrantOwner!==void 0&&d===p.reentrantOwner)return p.refCount+=1,createSyncHeldLockHandle(p);let m=new SyncLockAcquisition(u,l,i,a),h,ee,g=!1,_,ne=!1,v,re=!1,ie={},y=`${u}.reclaim`;try{for(;;){if(!m.owns){let e=f.get(l);if(e&&!foreignSyncHeldLock(`raw`,l)&&d!==void 0&&e.reentrantOwner!==void 0&&d===e.reentrantOwner)return e.refCount+=1,createSyncHeldLockHandle(e);m.reserve()}let e=currentTargetHolder(),holderWasReplaced=()=>{let t=currentTargetHolder();return t!==void 0&&t!==e};if(!re&&(v=m.run(()=>t.staleRecovery??r.staleRecovery),re=!0,holderWasReplaced())){m.waitForRetry();continue}let n=syncReclaimGuardExists(y);if(!m.hasToken())throw Ye(u,l);if(holderWasReplaced()||n){m.waitForRetry();continue}let i,a,c;if(h||=m.run(()=>t.payload),holderWasReplaced()){m.waitForRetry();continue}let p=m.run(()=>Reflect.apply(h,t,[]));if(holderWasReplaced()){m.waitForRetry();continue}let{raw:b,ownershipToken:ae}=m.run(()=>ct(p));if(holderWasReplaced()||currentTargetHolder()!==void 0||!g&&(ee=m.run(()=>t.onCompromised),g=!0,currentTargetHolder()!==void 0)||!ne&&(_=m.run(()=>t.parsePayload),ne=!0,currentTargetHolder()!==void 0)){m.waitForRetry();continue}let oe=!1,x=!1;try{let e=process.platform!==`win32`&&typeof D.constants.O_NOFOLLOW==`number`?D.constants.O_NOFOLLOW:0;try{te(u)}catch(e){throw x=e.code===`EEXIST`,e}try{i=D.openSync(u,D.constants.O_WRONLY|D.constants.O_CREAT|D.constants.O_EXCL|e,384)}catch(e){throw oe=Je(e,u),x=e.code===`EEXIST`,e}D.writeFileSync(i,b,`utf8`),D.fsyncSync(i),c={raw:b,payload:p,stat:D.fstatSync(i,{bigint:!0}),ownershipToken:ae},a={fd:i,lockPath:u,normalizedTargetPath:l,parsePayload:_,refCount:1,reentrantOwner:d,snapshot:c};let n=a;if(ensureSyncLockExitCleanupRegistered(releaseAllSyncHeldLocks,u,l),!m.hasToken()||currentTargetHolder()!==void 0)throw Ye(u,l);let r=createSyncHeldLockHandle(n);if(m.monitor(n,r,ee,s,t),!m.hasToken()||currentTargetHolder()!==void 0)throw Ye(u,l);return f.set(l,n),m.release(),i=void 0,r}catch(e){if(a?.timer&&(clearInterval(a.timer),a.timer=void 0),a&&f.get(l)===a&&f.delete(l),i!==void 0){let t=c??{payload:null};if(!t.stat)try{t.stat=D.fstatSync(i,{bigint:!0})}catch{}let n=i;i=void 0,a&&(a.fd=void 0);try{D.closeSync(n),t.stat&&qe(u,t)}catch(t){throw Ke(e,t,`file lock acquisition and cleanup both failed`)}}if(oe){if(!m.hasToken())throw Ye(u,l);if(currentTargetHolder()!==void 0){m.waitForRetry();continue}if(m.retryDenial(e))continue;throw e}if(!x)throw e;if(!m.hasToken())throw Ye(u,l);if(currentTargetHolder()!==void 0){m.waitForRetry();continue}handleSyncStaleAdmission(m,{currentHeld:currentTargetHolder,options:t,parsePayload:_,reclaimGuardPath:y,staleMs:o,staleOptions:ie,staleRecovery:v});continue}}}finally{m.release()}}const zr=/* @__PURE__ */ new Map;function resolveRuntimeProcessEntrypointUrl(e){return zr.get(e)??an($t[e])}const Br=a(Symbol.for(`openclaw.processRuntimeWorkerGeneration`),()=>({}));function resolveProcessRuntimeWorkerFile(e){let t=Br.resolve;if(!t)return e;if(e instanceof URL)return e.protocol===`file:`?t(e):e;if(typeof e==`string`&&e.startsWith(`/`)){let n=t(Cn(e));return n.protocol===`file:`?Sn(n):e}return e}const Vr=a(Symbol.for(`openclaw.runtimeWorkerGeneration`),()=>new Mn);function resolveRuntimeWorkerGenerationUrl(e,t){return Qt(e.href)?e:t?.resolve(e)??e}function captureRuntimeWorkerSource(e){let t=Vr.getStore()?.generation,n=resolveRuntimeWorkerGenerationUrl(e,t);return n.href===e.href?{moduleUrl:e}:{moduleUrl:n,runtimeGeneration:t}}const Hr=`${process.execArgv.join(` `)} ${process.env.NODE_OPTIONS??``}`;Dn&&!process.versions.bun&&/--max[-_](?:old[-_]space[-_]size(?:[-_]percentage)?|heap[-_]size)(?:=|\s)/u.test(Hr)&&(/--(?:freeze[-_]flags[-_]after[-_]init|(?:abort|exit)[-_]on[-_]contradictory[-_]flags)(?:=(?:true|1))?(?:\s|$)/u.test(Hr)?process.emitWarning(`V8 startup flags prevent enforcing per-worker heap limits.`):pn(`--max-old-space-size=0 --max-heap-size=0`));const Ur=/* @__PURE__ */ `admit,audit.events.list,audit.writer.process,audit.writer.prune,database.domain.bind,database.domain.close,database.domain.publish,database.prepareWrite,database.walMaintenance,localWorkspace.prepare,localWorkspace.pruneLegacy,localWorkspace.beginSweep,localWorkspace.finishSweep,localWorkspace.sweepBatch,localWorkspace.mutate,localWorkspace.manifest,localWorkspace.readBacking,localWorkspace.sweepCandidates,localWorkspace.reviewBase,localWorkspace.byProjectionPath,localWorkspace.exists,localWorkspace.get,stateLease.acquire,stateLease.release,stateLease.renew,stateLease.verify,worktrees.assertPredicates,worktrees.delete,worktrees.slotCount,worktrees.pendingSlots,worktrees.reservePending,worktrees.releasePending,worktrees.insert,worktrees.update,worktrees.claimRemoval,worktrees.finalizeRemoval,worktrees.abortRemoval,worktrees.findLiveByOwner,worktrees.get,worktrees.sessionBinding,worktrees.findLiveByPath,worktrees.list,worktrees.liveIds,worktrees.provisionedPaths,worktrees.provisionedState,worktrees.provisionedChunk,worktrees.writeProvisionedSnapshot,worktrees.retireMissing,worktrees.deferCleanup,worktrees.admitRunLease,worktrees.releaseRunLease,worktrees.reapRunLeases,worktrees.reserveCapacity,worktrees.recoverPending,worktrees.templates.read,worktrees.templates.has,worktrees.templates.list,worktrees.templates.reserve,worktrees.templates.ready,worktrees.templates.delete,worktrees.templates.retainReader,worktrees.templates.releaseReader,worktrees.templates.hasReaders`.split(`,`),Wr=/* @__PURE__ */ `acp.acpSessions.agentDatabaseDeletion.agentDatabaseRegistry.agentDatabases.agentDeletionJournal.agentProvenance.apns.audit.authProfiles.backup.bootstrap.capture.channelIngress.templates.config.conversation.conversationBindings.database.deliveryQueue.deviceAuth.deviceIdentity.devicePairing.diagnostic.doctor.exec-approvals.execApprovals.generatedHtmlProvenance.githubPublication.githubRepository.legacyMcpOAuth.localWorkspace.managedImages.mcpOAuth.mentions.modelCatalog.nativeHookRelay.node.nodeHost.nodeWorker.onboardingRecommendations.operator.operatorApprovals.pairing.placementJournals.placementTools.placementTranscript.placementTurns.pluginBlob.pluginModelCatalogCredentials.plugins.preparedPoolPresence.projects.promotions.repositoryWorkspaces.restartSentinel.sandboxRegistry.secrets.sessionDelivery.sessionGroups.sessionRepositoryWorkspaces.sessionState.sessionUpstream.skillLibrary.skillUploads.skills.stateLease.subagents.telemetry.tts.tui.updateRuns.usageCache.userModelAccounts.userPreferences.userProfiles.webPush.workerEnvironments.workerInference.workerPlacements.workers.workspace.workshop.worktrees`.split(`.`),Gr=/* @__PURE__ */ new Set([...Ur,...Wr]);function classifySqliteWorkerExecute(e){if(Gr.has(e))return e;let t=e.indexOf(`.`),n=t===-1?e:e.slice(0,t);return Gr.has(n)?n:`execute`}const Kr=/* @__PURE__ */ new Set(/* @__PURE__ */ `abortedPartial,acceptIntent,add,append,appendChunk,assistant,batch,boards.applyOps,boards.grant,boards.putWidget,cache.clear,cache.prune,cache.read,cache.retire,cache.stage.start,cache.write,cache.write.inline,cancel,catalog.pruneRemovedProviders,catalog.removeCredentials,catalog.replace,category.apply,category.prepare,claim,complete,connection.inspect,create,delete,deleteChunk,discardIntent,discover,enqueueIntent,finalize,finish,forget.mark,forget.purge,hasPending,index.facts,index.upgradeProviderKey,index.writeEmbeddingRefusal,index.writeMetadata,involvement,list,listPendingSessions,match,owner.assign,participant,preflight,prepare,prepareRun,prune,publishClosedTurn,put,readNextPending,record,recordFailure,remove,reserve,schema.admit,source.chunks,source.delete,source.hash,source.refresh,source.replace,source.replace.group,source.replace.inline,source.state,stage.append,stage.discard,stage.start,suggestion.add,suggestion.claim,suggestion.finalize,suggestion.release,sweep,vector.ensure,vector.prepare,devicePairing.ensureToken,devicePairing.list,devicePairing.lookup,devicePairing.updateMetadata,devicePairing.updatePresence,devicePairing.verifyToken,session.actor.acceptInput,session.actor.adoptRun,session.actor.appendToolResult,session.actor.appendTranscriptEvent,session.actor.completeTurn,session.actor.deliveryPending,session.actor.deliverySettled,session.actor.patch,session.actor.read,session.agentPurge.commit,session.agentPurge.prepare,session.archivePruning.deletePublished,session.archivePruning.pruneRetention,session.archivePruning.reclaimPages,session.archivePruning.removeLegacy,session.archives.preparePublication,session.archives.recordPublication,session.entries.replace,session.entry.acp,session.entry.patch.commit,session.entry.patch.prepare,session.entry.read,session.entry.readResult,session.entry.replacements.commit,session.entry.replacements.prepare,session.goal.mutate,session.lifecycle.delete,session.lifecycle.deletePlan,session.lifecycle.project,session.lifecycle.reset,session.maintenance.finalize,session.maintenance.metadata,session.maintenance.prepare,session.maintenance.size,session.messageCut.commit,session.messageCut.fork,session.messageCut.preflight,session.messageRewrite.commit,session.messageRewrite.modelPrompt,session.messageRewrite.prepare,session.metadata.append,session.metadata.initialize,session.metadata.mutation,session.nativeBindings.delete,session.parentFork.commit,session.parentFork.prepare,session.parentFork.source,session.pendingInputs.mutate,session.pendingInputs.read,session.pendingInputs.withdraw,session.providerReview.compare,session.reaction.set,session.rowTranscript.backfill,session.turn.commit,session.turn.prepare,trajectory.events.append,trajectory.retention.begin,trajectory.retention.delete,transcript.commit,transcript.prepare,usageCache.prune,usageCache.writeQuarters,usageCache.writeRollup`.split(`,`)),qr=/* @__PURE__ */ new Map([[`preflight`,`transcript-projection.preflight`],[`sweep`,`transcript-projection.sweep`],[`claim`,`transcript-projection.claim`],[`deleteChunk`,`transcript-projection.deleteChunk`],[`appendChunk`,`transcript-projection.appendChunk`],[`finalize`,`transcript-projection.finalize`]]),Jr=[`/config/sessions/session-transcript-projection-publication.worker.js`,`/config/sessions/session-transcript-projection-publication.worker.ts`],Yr=[[`pluginState.`,`plugin_state`],[`session.history.`,`transcript_read`],[`trajectory.`,`transcripts`],[`session.transcript.`,`transcripts`],[`transcripts.`,`transcripts`],[`session.`,`sessions`],[`cron.`,`cron`]];function classifyWorkerRequest(e,t){if(typeof e!=`string`)return`execute`;if(Kr.has(e))return e;if(e===`auth-profile-rows`)return`auth_profiles`;if(e===`database.domain.execute`||e===`database.domain.publish`){let n=i(t)?t:void 0,r=n&&i(n.command)?n.command:void 0,a=n?.moduleUrl;if(e===`database.domain.publish`&&typeof a==`string`&&typeof r?.type==`string`&&Jr.some(e=>a.endsWith(e))){let e=qr.get(r.type);if(e)return e}let o=r?classifyWorkerRequest(r.type):`execute`;return o===`execute`?`domain_execute`:o}for(let[t,n]of Yr)if(e.startsWith(t))return n;return classifySqliteWorkerExecute(e)}const Xr=/* @__PURE__ */ new Set([...Kr,...qr.values(),...Gr,...Yr.map(([,e])=>e),`task`,`open`,`close`,`execute`,`domain_execute`,`auth_profiles`]);function normalizeWorkerRequestClass(e){return e!==void 0&&Xr.has(e)?e:`other`}function sampleWorkerAuthorityOperation(e){return Dn&&normalizeWorkerRequestClass(e).startsWith(`session.actor.`)&&Math.random()<1/128}function recordWorkerAuthorityMessage(e,t,n=sampleWorkerAuthorityOperation(t)){return recordWorkerMessage(e?.kind===`sqlite-database-admissions`?`admission`:`authority`,`from_worker`,typeof e?.payloadBytes==`number`?e.payloadBytes:void 0,t,n?e:void 0),n}function withoutField(e,t){if(!i(e)||!Object.hasOwn(e,t))return e;let n={...e};return delete n[t],n}function recordAuthorityPayload(e,t,n){let r=normalizeWorkerRequestClass(n);if(!r.startsWith(`session.actor.`))return;let a=t.kind===`native-settlement`&&i(t.settlement)?t.settlement.committed:t.committed,o=i(a);if(!o&&!Object.hasOwn(t,`facts`))return;let s=o?[`receipt_entry`,`receipt_events`,`receipt_value`,`receipt_other`]:[`admission_entry`,`admission_other`],c=(e.payloadComponents??={})[r]??={},l,u=o&&typeof t.payloadBytes==`number`?t.payloadBytes:void 0;try{let e=o?a.facts:t.facts;if(u??=dn(e).byteLength,o&&i(e)&&i(e.receipt)){let t={...e.receipt,postimage:withoutField(e.receipt.postimage,`entry`)};delete t.entryMetadata;let n={...e,receipt:t},r=Math.min(u,dn(n).byteLength),i={...n,receipt:{...n.receipt,transcript:withoutField(withoutField(e.receipt.transcript,`appendedEvents`),`authorityReceipts`)}},a=Math.min(r,dn(i).byteLength),o=Math.min(a,dn({...i,value:void 0,receipt:{...i.receipt,transcript:withoutField(i.receipt.transcript,`append`)}}).byteLength);l=[u-r,r-a,a-o,o]}else if(!o&&i(e)&&i(e.publication)&&e.publication.kind===`session-actor-admission`){let t=dn({...e,publication:{...e.publication,snapshot:withoutField(e.publication.snapshot,`entry`)}}).byteLength;l=[u-t,t]}else l=o?[0,0,0,u]:[0,u];l.some(e=>e<0)&&(l=void 0)}catch{}for(let[e,t]of s.entries()){let n=c[t]??={bytes:0,samples:0,unmeasured:0};l?(n.bytes+=l[e]??0,n.samples++):(n.unmeasured++,t===`receipt_other`&&u!==void 0&&(n.bytes+=u))}}const Zr=a(Symbol.for(`openclaw.workerMessageMetrics`),()=>/* @__PURE__ */ new Map);function recordWorkerMessage(e,t,n,r,i){if(!Dn)return;let a=Zr.get(e);a||(a={},Zr.set(e,a));let o=a[t]??={kind:e,direction:t,messages:0,payloadBytes:0,unmeasuredMessages:0};if(o.messages++,n===void 0)o.unmeasuredMessages++;else if(o.payloadBytes+=n,e===`sqlite_request`||e===`sqlite_reply`||e===`authority`){let e=o.payloadBytesByRequestClass??={},t=normalizeWorkerRequestClass(r);e[t]=(e[t]??0)+n}i&&e===`authority`&&t===`from_worker`&&recordAuthorityPayload(o,i,r)}function messageData(e){return i(e)&&!jn.isProxy(e)?e:void 0}function dataProperty(e,t){return Object.getOwnPropertyDescriptor(e,t)?.value}function messageBody(e){let t=messageData(e),n=t&&dataProperty(t,`type`);return t&&(n===`post`||n===`message`)?dataProperty(t,`value`):e}function workerMessagePayloadBytes(e){if(!Dn)return;let t=messageBody(e),n=messageData(t),r=n&&(Object.getOwnPropertyDescriptor(n,`value`)??Object.getOwnPropertyDescriptor(n,`input`));if(r&&!(`value`in r))return;let i=r?r.value:t;if(!jn.isProxy(i)){if(ArrayBuffer.isView(i)||i instanceof ArrayBuffer){let e=n&&dataProperty(n,`type`)===`open`?dataProperty(n,`preparation`):void 0;return i.byteLength+(ArrayBuffer.isView(e)?e.byteLength:0)}if(typeof i==`string`)return i.length*2;if(i==null)return 0}}function messageKind(e,t){let n=messageData(messageBody(e));if(!n)return t;switch(dataProperty(n,`status`)){case`ok`:case`failed`:return`task_reply`;case`request`:return`task_request`;case`notification`:return`task_notification`;case`consumed`:return`task_consumed`;case`memory`:return`memory`;case`ready`:return`lifecycle`}if(typeof dataProperty(n,`taskId`)==`number`)return`task_input`;if(typeof dataProperty(n,`actor`)==`number`)return`sqlite_request`;if(typeof dataProperty(n,`id`)==`number`&&typeof dataProperty(n,`ok`)==`boolean`)return`sqlite_reply`;if(typeof dataProperty(n,`operationId`)==`number`)switch(dataProperty(n,`type`)){case`prepare`:case`reclaim`:case`canonical-validation`:return`sqlite_request`;case`reclaimed`:case`refused`:case`checkpoint`:return`sqlite_reply`;case`admission`:case`admission-request`:case`admission-release`:return`admission`;case`commit-request`:return`authority`}switch(dataProperty(n,`type`)){case`resource-owner`:case`resource-message`:case`resource-closed`:return`resource`;case`cpu`:case`heap`:return`memory`;case`create`:case`created`:case`stop`:case`stopped`:case`close`:case`closed`:case`release`:case`execution-exit`:case`error`:case`messageerror`:case`create-error`:case`stop-error`:case`request-error`:return`lifecycle`}return dataProperty(n,`closeResource`)===!0?`resource`:t}function observeWorkerMessage(e,t,n=`other`,r,i){Dn&&recordWorkerMessage(messageKind(e,n),t,r===void 0?workerMessagePayloadBytes(e):r??void 0,i)}function canObserveWorkerMessages(e){if(!Object.isExtensible(e))return!1;for(let t of[`postMessage`,`emit`]){let n=e;for(;n;){let e=Object.getOwnPropertyDescriptor(n,t);if(e){if(!e.writable||typeof e.value!=`function`)return!1;break}n=Reflect.getPrototypeOf(n)}if(!n)return!1}return!0}function readPostgresBridgeCounters(e){return Array.isArray(e)?e.filter(e=>i(e)&&typeof e.threadId==`number`&&Number.isSafeInteger(e.threadId)&&e.threadId!==kn&&e.count instanceof Int32Array&&e.count.length===1&&e.count.buffer instanceof SharedArrayBuffer&&(e.selfRootCount===void 0||e.selfRootCount instanceof Int32Array&&e.selfRootCount.length===1&&e.selfRootCount.buffer instanceof SharedArrayBuffer)):[]}const Qr=Fn(`openclaw.code-mode.gc-storm`),A=a(Symbol.for(`openclaw.workerCpuSources`),()=>(process.on(`worker`,trackWorker),{gcObserver:void 0,postgresBridgeCount:new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),postgresPoolSelfRootCount:new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT)),postgresBridgeObservers:/* @__PURE__ */ new Set,revision:0,cpuSources:void 0,nextPoolId:0,poolIds:/* @__PURE__ */ new WeakMap,workers:/* @__PURE__ */ new Map,lifecycle:/* @__PURE__ */ new Map,taskMetrics:/* @__PURE__ */ new Map}));function createCpuTrackedWorker(e,t,n){let r=s(`worker:${h(e,t?.eval)}`,()=>new En(t?.eval?e:resolveProcessRuntimeWorkerFile(e),t));return trackNativeWorkerForCpu(r,e,t?.eval),Object.assign(A.workers.get(r),{internalMessages:!0,requestClass:n}),r}function trackNativeWorkerForCpu(e,t,n=!1){trackWorker(e);let r=A.workers.get(e),i=h(t,n);if(r.script!==i&&(r.script===`bridge.worker.js`&&Atomics.sub(A.postgresBridgeCount,0,1),i===`bridge.worker.js`&&Atomics.add(A.postgresBridgeCount,0,1),r.script=i),r.script===`sqlite-store.worker.js`&&attributeWorkerMetrics(r,`writer`),r.script===`code-mode-node.worker.js`&&r.workerSlot===void 0){let e=new Set([...A.workers.values()].map(e=>e.workerSlot));for(let t=1;t<=64;t++)if(!e.has(t)){r.workerSlot=t;break}}r.lifecycleMessages=r.script===`openclaw-state-lease-heartbeat.worker.js`||r.script===`gateway-state-owner-heartbeat.worker.js`}function recordPostgresPoolSelfRoot(){return Atomics.compareExchange(A.postgresPoolSelfRootCount,0,0,1)===0}function publishPostgresBridgeCounters(){for(let e of A.postgresBridgeObservers)e()}function receivePostgresBridgeCounters(e,t){let n=readPostgresBridgeCounters(t),r=e.postgresBridgeCounters;n.length===(r?.length??0)&&n.every((e,t)=>e.threadId===r?.[t]?.threadId)||(e.postgresBridgeCounters=n,publishPostgresBridgeCounters())}function attributeWorkerToPool(e,t,n){let r=A.workers.get(e);if(!r)return;let i=A.poolIds.get(t);i===void 0&&(i=++A.nextPoolId,A.poolIds.set(t,i)),r.poolId=i,attributeWorkerMetrics(r,n,0)}function attributeWorkerMetrics(e,t,n){let r=t===`reader`||t===`file-reader`||t===`compute`||t===`writer`||t===`singleton`?t:`other`,i=`${r}:${e.script}`,a=A.taskMetrics.get(i);a||(a={workerClass:r,script:e.script,tasksCompleted:n,heapUsedHighWaterBytes:0,gc:[]},A.taskMetrics.set(i,a)),e.taskMetrics=a}function forgetWorker(e){let t=A.workers.get(e);if(!t)return;let n=countWorkerStart(t),r=t.retirementReason??`exit`;n.retired.set(r,(n.retired.get(r)??0)+1),t.script===`bridge.worker.js`&&Atomics.sub(A.postgresBridgeCount,0,1),t.memoryFlush?.resolve(),drainWorkerMemoryPort(t),bt(t),t.memoryPort?.close(),A.workers.delete(e),A.revision++,A.cpuSources=void 0,t.postgresBridgeCounters&&publishPostgresBridgeCounters()}function countWorkerStart(e){let t=A.lifecycle.get(e.script);return t||(t={started:0,retired:/* @__PURE__ */ new Map},A.lifecycle.set(e.script,t)),e.started||(e.started=!0,t.started++),t}function markWorkerRetirement(e,t){let n=A.workers.get(e);n&&(n.retirementReason??=t)}function flushWorkerDiagnostics(e,t){let n=A.workers.get(e);if(n?.memoryFlush)return n.memoryFlush.operation;let r=n?.memoryPort;if(!n?.taskMetrics||!r||!A.gcObserver||[`failure`,`cancelled`,`crash`,`gc-thrash`,`gc-storm`,`exit`].includes(t))return;let i=performance.now()+100,a=on(()=>{drainWorkerMemoryPort(n),performance.now()>=i&&a.resolve()});n.memoryFlush=a;let o=setTimeout(()=>a.resolve(),100);a.operation.result.then(()=>clearTimeout(o));try{r.postMessage({flush:!0}),recordWorkerMessage(`memory`,`to_worker`,1)}catch{a.resolve()}return a.operation}function trackWorker(e){if(A.workers.has(e))return;if(Dn&&e instanceof En&&recordWorkerMessage(`lifecycle`,`to_worker`),Dn&&e instanceof En&&canObserveWorkerMessages(e)){let t=Object.getPrototypeOf(e)===En.prototype,r=!t||Object.hasOwn(e,`postMessage`)?e.postMessage:void 0;e.postMessage=function(e,t){let i=n.internalMessages?workerMessagePayloadBytes(e):void 0;(r??En.prototype.postMessage).call(this,e,t),n.lifecycleMessages?recordWorkerMessage(`lifecycle`,`to_worker`,i):n.internalMessages?observeWorkerMessage(e,`to_worker`,`other`,i??null,n.requestClass?.()):recordWorkerMessage(`other`,`to_worker`)};let a=!t||Object.hasOwn(e,`emit`)?e.emit:void 0;e.emit=function(e,...t){if(e===`error`&&n.script===`code-mode-node.worker.js`){let e=t[0];n.retirementReason??=i(e)&&e.code===`ERR_CODE_MODE_GC_THRASH`?`gc-thrash`:`crash`}return e===`message`&&(n.lifecycleMessages?recordWorkerMessage(`lifecycle`,`from_worker`,workerMessagePayloadBytes(t[0])):n.internalMessages?observeWorkerMessage(t[0],`from_worker`,`other`,void 0,n.requestClass?.()):recordWorkerMessage(`other`,`from_worker`)),(a??En.prototype.emit).call(this,e,...t)}}let t=!1,finishCpuUsage=e=>(t=!1,e),failCpuUsage=()=>finishCpuUsage(void 0),n={script:`other`,cpuUsage(){if(t)return Promise.resolve(void 0);t=!0;try{return e.cpuUsage().then(finishCpuUsage,failCpuUsage)}catch{return Promise.resolve(failCpuUsage())}}};A.workers.set(e,n),queueMicrotask(()=>countWorkerStart(n)),A.revision++,A.cpuSources=void 0,e.once(`exit`,()=>forgetWorker(e))}function recordWorkerHeap({taskMetrics:e},t){e&&(e.heapUsedHighWaterBytes=Math.max(e.heapUsedHighWaterBytes,t))}function isWorkerGcObservationEnabled(){return!!A.gcObserver}function recordWorkerGc(e,t){let n=e.taskMetrics;if(n)for(let e of t){if(!e||![`scavenge`,`mark_sweep_compact`,`incremental`,`weak_processing`].includes(e.kind)||!Number.isFinite(e.durationMs)||e.durationMs<0)continue;let t=n.gc.find(t=>t.kind===e.kind);t||(t={kind:e.kind,count:0,durationMs:0,reclaimedBytes:0},n.gc.push(t)),t.count++,t.durationMs+=e.durationMs,Number.isFinite(e.reclaimedBytes)&&e.reclaimedBytes>=0&&(t.reclaimedBytes+=e.reclaimedBytes),n.heapUsedHighWaterBytes=Math.max(n.heapUsedHighWaterBytes,Number.isFinite(e.heapUsedBeforeBytes)?e.heapUsedBeforeBytes:0)}A.gcObserver?.(t,e.script,e.workerSlot)}function drainWorkerMemoryPort({memoryPort:e,memoryReceive:t}){if(e&&t)for(let n=On(e);n;n=On(e))t(n.message)}function receiveWorkerMemoryPort(e,t){if(i(t)&&(t.status===`ok`||t.status===`failed`)&&t.diagnostics===!0){let t=A.workers.get(e);return t?.taskMetrics?.tasksCompleted!==void 0&&t.taskMetrics.tasksCompleted++,!1}if(!i(t)||t.status!==`memory`||!(t.port instanceof Tn))return!1;let n=t.port,r=A.workers.get(e);if(!r||r.memoryPort||e.threadId===-1)return n.close(),!0;receivePostgresBridgeCounters(r,t.postgresBridgeCounters),r.memoryPort=n,r.memoryPending=!0;let close=()=>{r.memoryPort=void 0,r.memoryReceive=void 0,r.memoryPending=!1,r.memoryUnavailable=!0,r.memoryFlush?.resolve(),n.close()};return r.memoryReceive=t=>{if(`sqliteReaderCounter`in t)Dt(r,t.sqliteReaderCounter),recordWorkerMessage(`memory`,`from_worker`,16);else if(`postgresBridgeCounters`in t)receivePostgresBridgeCounters(r,t.postgresBridgeCounters),recordWorkerMessage(`memory`,`from_worker`);else if(`flushed`in t)recordWorkerMessage(`memory`,`from_worker`,8),recordWorkerHeap(r,t.heapUsed),r.memoryFlush?.resolve();else if(`retireWorkerId`in t)recordWorkerMessage(`memory`,`from_worker`),Qr.publish(t.retireWorkerId);else if(`gcStorm`in t){recordWorkerMessage(`memory`,`from_worker`);let i=e.threadId,a=r.workerSlot;import(`./sqlite-readonly-diagnostic-worker-gc-profile-DAS-FYjn.mjs`).then(async({reportWorkerGcStorm:e})=>{let o=await e(t.gcStorm,i,a);o&&r.memoryPort===n&&n.postMessage({captureGcProfile:o})})}else recordWorkerMessage(`memory`,`from_worker`,(`heapUsed`in t?32+(t.heapSizeLimitBytes===void 0?0:8):0)+(`heapUsed`in t&&t.oldGenerationAfterGcBytes!==void 0?8:0)+(`heapUsed`in t?(t.heapSpaces?.length??0)*8:0)+(`heapUsed`in t?t.retainedData?.reduce((e,t)=>e+16+(t.stringBytes===void 0?0:8)+(t.objects===void 0?0:8)+(t.generations===void 0?0:8)+(t.providers===void 0?0:8)+(t.accounts===void 0?0:8)+(t.truncated===void 0?0:1),0)??0:0)+(t.gc?.length??0)*8),t.gc&&recordWorkerGc(r,t.gc),`heapUsed`in t&&(recordWorkerHeap(r,t.heapUsed),delete t.gc,r.heap={value:t,sampledAt:performance.now()},r.memoryPending=!1,r.memoryUnavailable=!1)},n.on(`message`,r.memoryReceive),n.once(`close`,close),n.once(`messageerror`,close),n.unref(),A.gcObserver&&(n.postMessage({gc:!0}),recordWorkerMessage(`memory`,`to_worker`,1)),!0}const $r=Date.now.bind(Date);function captureLock(e){let t=D.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=D.statSync(i,{bigint:!0}),{moduleUrl:o,runtimeGeneration:s}=captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl(`gatewayStateOwnerHeartbeat`));return c(()=>{let c=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(c,0,BigInt($r()));let{port1:u,port2:d}=new wn,f=createCpuTrackedWorker(o,{workerData:{clock:`epoch`,locks:r,intervalMs:15e3,failureMs:6e4,lastBeat:c.buffer,events:d},transferList:[d],execArgv:rn(o)}),p=ee();f.on(`message`,e=>{e===`closed`&&p.resolve()}),f.unref();let m=0,h=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of h.values())t.reject(e);h.clear(),u.unref()};u.on(`message`,e=>{if(recordWorkerMessage(`lifecycle`,`from_worker`),e===`parent-lost`)Yt();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=h.get(e.id);h.delete(e.id),h.size===0&&u.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),u.unref(),f.on(`error`,e=>{let r=/* @__PURE__ */ Error(`${t(e)}; restart Gateway.`);rejectPending(r),n(r)}),f.once(`exit`,()=>{p.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let g,remainingUntilInspection=()=>{let e=Atomics.load(c,0),t=$r()-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 t=$r(),n=new Date(t);for(let t of e)try{let o=r[t.lockPath];if(o===void 0)throw Error(`owner acquisition bytes were not registered`);let s=await D.promises.open(t.lockPath,`r+`);try{let r=await s.stat({bigint:!0}),c=await D.promises.lstat(t.lockPath,{bigint:!0}),l=Buffer.alloc(Buffer.byteLength(o)+1),{bytesRead:u}=await s.read(l,0,l.length,0),d=await D.promises.lstat(t.lockPath,{bigint:!0});if(g||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(r,c,o,l.subarray(0,u).toString(`utf8`))||!d.isFile()||d.dev!==r.dev||d.ino!==r.ino||t.lockPath===i&&(r.dev!==a.dev||r.ino!==a.ino)){if(t.lockPath!==i)continue;throw Error(`owner lock was removed or replaced`)}await s.utimes(n,n)}finally{await s.close()}}catch(e){if(t.lockPath!==i&&_(e,`ENOENT`))continue;throw e}!g&&e.size>0&&Atomics.store(c,0,BigInt(t))},te,ne,watch=()=>{let e=remainingUntilInspection();e>0?(te=setTimeout(watch,e),te.unref()):ne??=renewAsync().then(()=>{ne=void 0,g||watch()},e=>{ne=void 0,g||n(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${i}: ${t(e)}; restart the Gateway.`))})};watch();let stop=()=>(g||=(clearTimeout(te),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),u.close(),f.ref(),f.postMessage(`stop`,[]),(async()=>(await settlesWithin(p.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${Zt}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),f.terminate()))()),Promise.all([g,ne]).then(()=>void 0));s?.retain(f,async()=>async()=>{await stop()});let assertActive=()=>{if(g||f.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},v=new Set(Object.keys(r));return{worker:f,paths:v,register(e){let t=captureLock(e);r[e.lockPath]=t,f.postMessage([e.lockPath,t],[]),v.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let t=++m;return new Promise((n,r)=>{h.set(t,{resolve:n,reject:r}),u.ref();try{f.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){h.delete(t),h.size===0&&u.unref(),r(l(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 ei=m(`gateway/state`);function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,j.clear(),e.heartbeat?.stop(),ei.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 j=a(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),M=a(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map),ti=/* @__PURE__ */ new Set([`--dev`,`--no-color`]),ni=/* @__PURE__ */ new Set([`--profile`,`--log-level`,`--container`]);function isValueToken(e){return!e||e===`--`?!1:!e.startsWith(`-`)||/^-\d+(?:\.\d+)?$/.test(e)}function consumeRootOptionToken(e,t){let n=e[t];return n?ti.has(n)||n.startsWith(`--profile=`)||n.startsWith(`--log-level=`)||n.startsWith(`--container=`)?1:ni.has(n)?isValueToken(e[t+1])?2:1:0:0}function consumeRootCommandOptionToken(e,t){return consumeKnownOptionToken(e,t,ti,ni,`command-path`)}function getRootOptionAwareCommandPath(e,t){let n=e.slice(2),r=[],i=!1;for(let e=0;e<n.length;e+=1){let a=n[e];if(!a)break;if(!i&&a===`--`){if(r.length>0)break;i=!0;continue}let o=i?0:consumeRootCommandOptionToken(n,e);if(o>0)e+=o-1;else if((i||!a.startsWith(`-`))&&(r.push(a),r.length>=t))break}return r}function rewriteUpdateFlagArgv(e){let t=e.indexOf(`--update`);if(t===-1)return e;for(let n=2;n<e.length;n++){let r=e[n];if(!r||r===`--`)return e;if(n===t)return[...e.slice(0,t),`update`,...e.slice(t+1)];let i=consumeRootOptionToken(e,n);if(i>0)n+=i-1;else if(!r.startsWith(`-`))return e}return e}function isUpdateCommandArgv(e){return getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(e),1)[0]===`update`}function consumeKnownOptionToken(e,t,n,r,i){let a=e[t];if(!a||a===`--`||!a.startsWith(`-`))return 0;let o=a.indexOf(`=`),s=o===-1?a:a.slice(0,o);return n.has(s)?+(o===-1):r.has(s)?o===-1?i===`command-path`?e[t+1]===void 0?0:2:isValueToken(e[t+1])?2:0:i===`command-path`||a.slice(o+1).trim()?1:0:0}function getCommandPositionalsWithRootOptions(e,t){return parseCommandArgsWithRootOptions(e,t,!1)}function parseCommandArgsWithRootOptions(e,t,n,r=!1){let i=e.slice(2),a=new Set(t.booleanFlags??[]),o=new Set(t.valueFlags??[]),s=[],c=[],l=[],u=0,d=!1;for(let e=0;e<i.length;e+=1){let f=i[e];if(f===void 0)break;if(!d&&f===`--`){if(t.mode!==`command-path`)break;d=!0;continue}let p=d?0:t.mode===`command-path`?consumeRootCommandOptionToken(i,e):consumeRootOptionToken(i,e);if(p>0)(u>0&&a.has(f)?l:c).push(...i.slice(e,e+p)),e+=p-1;else if(!d&&f.startsWith(`-`)){let n=consumeKnownOptionToken(i,e,a,o,t.mode);if(n===0||u===0)return null;l.push(f),e+=n-1}else if(u<t.commandPath.length){if(f!==t.commandPath[u])return null;if(u+=1,n&&u===t.commandPath.length){let t=i.slice(e+1);return d?[`--`,...t]:t}}else if(s.push(f),!r&&s.length===t.maxPositionals)return s}return u<t.commandPath.length?null:r?{rootOptions:c,commandOptions:l}:s}const ri=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),ii=/* @__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=getCommandPositionalsWithRootOptions(e,{commandPath:[`gateway`],booleanFlags:[...ii,`--task-supervisor`],valueFlags:[...ri,`--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 N=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]})}}),P=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}}),ai=freeze({is(e){return e.kind===`CreateIndexNode`},create(e){return freeze({kind:`CreateIndexNode`,name:P.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}}),oi=freeze({is(e){return e.kind===`CreateSchemaNode`},create(e,t){return freeze({kind:`CreateSchemaNode`,schema:P.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),si=[`preserve rows`,`delete rows`,`drop`],F=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})}}),ci=freeze({is(e){return e.kind===`SchemableIdentifierNode`},create(e){return freeze({kind:`SchemableIdentifierNode`,identifier:P.create(e)})},createWithSchema(e,t){return freeze({kind:`SchemableIdentifierNode`,schema:P.create(e),identifier:P.create(t)})}}),li=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:ci.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),ui=freeze({is(e){return e.kind===`DropSchemaNode`},create(e,t){return freeze({kind:`DropSchemaNode`,schema:P.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),di=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}}),fi=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),I=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:ci.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:ci.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 pi=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})}}),mi=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),hi=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),gi=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`?mi.create(e.on,n):hi.create(e.on,n)})}}),_i=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:gi.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?gi.cloneWithOperation(e.on,`And`,t):gi.create(t)})}}),vi=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),yi=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(yi);const bi=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(bi);const xi=freeze({"->":!0,"->>":!0}),Si=Object.keys(xi),Ci=freeze({...yi,...bi,"||":!0}),wi=Object.keys(Ci),Ti=freeze({exists:!0,"not exists":!0});Object.keys(Ti);const Ei=freeze({...Ti,"-":!0,not:!0}),Di=Object.keys(Ei);[...wi,...Si,...Di];const Oi=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&Ci[e]}function isJSONOperator(e){return isString(e)&&xi[e]}function isUnaryOperator(e){return isString(e)&&Ei[e]}const L=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:P.create(e)})}}),ki=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),Ai=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:ki.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 ji=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})}}),R=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return R.create([e],[])},createWithChild(e){return R.create([``,``],[e])},createWithChildren(e){return R.create(Array(e.length+1).fill(``),e)}}),Mi=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:P.create(e)})}});var Ni=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:ji.cloneWith(this.#e.node,{direction:R.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:ji.cloneWith(this.#e.node,{direction:R.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:ji.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:ji.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:ji.cloneWith(this.#e.node,{collation:Mi.create(e)})})}toOperationNode(){return this.#e.node}};const Pi=/* @__PURE__ */ new Set;function logOnce(e){Pi.has(e)||(Pi.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(ji.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 ji.create(e,R.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),ji.create(e,t.toOperationNode());let n=ji.create(e);return t?t(new Ni({node:n})).toOperationNode():n}const Fi=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})}}),Ii=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])})}}),Li=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 Fi.create(parseStringReference(e),Ii.create(Oi.create(t)));if(t===`->$`||t===`->>$`)return Fi.create(parseStringReference(e),Li.create(Oi.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return Ai.create(L.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 fi.create(parseStringReference(n),P.create(r))}return parseStringReference(e)}function parseColumnName(e){return L.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 Ai.create(L.create(r),I.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return Ai.create(L.create(n),I.create(t))}function trim$2(e){return e.trim()}const Ri=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),zi=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),z=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):z.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 z.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?zi.create(e.map(e=>parseValueExpression(e))):Ri.create(e)}const Bi=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)?vi.create(parseReferenceExpression(e),parseBinaryOperator(t),z.createImmediate(n)):vi.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return vi.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`?mi.create:hi.create;if(e.length===0)return vi.create(z.createImmediate(1),Oi.create(`=`),z.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?Bi.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 Oi.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 Vi=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])})}}),Hi=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])})}}),Ui=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Vi.cloneWithItems(e.orderBy,t):Vi.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?Hi.cloneWithItems(e.partitionBy,t):Hi.create(t)})}}),Wi=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])})}}),Gi=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])})}}),Ki=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`?mi.create(e.having,n):hi.create(e.having,n)})}}),B=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})}}),qi=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),Ji=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:qi.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?Wi.cloneWithFroms(e.from,t):Wi.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),Yi=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])})}}),Xi=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:Wi.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>U.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>U.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?Yi.create(t):Yi.cloneWithTables(e.using,t)})}}),V=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`?mi.create(e.where,n):hi.create(e.where,n)})}}),Zi=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)})}}),Qi=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),$i=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),H=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),$i.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),ea=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)})}}),U=freeze({is(e){return W.is(e)||B.is(e)||Ji.is(e)||Xi.is(e)||H.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?V.cloneWithOperation(e.where,`And`,t):V.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?Zi.cloneWithSelections(e.returning,t):Zi.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:Qi.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?ea.cloneWithSelections(e.output,t):ea.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Vi.cloneWithItems(e.orderBy,t):Vi.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),W=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:Wi.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)=>U.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?Gi.cloneWithItems(e.groupBy,t):Gi.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?Ki.cloneWithOperation(e.having,`And`,t):Ki.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=>U.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var ta=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:_i.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:_i.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:_i.cloneWithOn(this.#e.joinNode,R.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const na=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(na.create)}var ra=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:Ui.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:U.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:Ui.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const ia=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:ki.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:Ai.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)?ia.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?ia.create(e.toOperationNode()):ia.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[ia.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return ia.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}const aa=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}}),oa=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(L.create)),aa.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=oa.create();return zi.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return Ri.create(r)}const sa=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?[sa.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])=>sa.create(L.create(e),parseValueExpression(t)))}const ca=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 G=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?V.cloneWithOperation(e.indexWhere,`And`,t):V.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?V.cloneWithOperation(e.indexWhere,`Or`,t):V.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?V.cloneWithOperation(e.updateWhere,`And`,t):V.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?V.cloneWithOperation(e.updateWhere,`Or`,t):V.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}});var la=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=L.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,t]):freeze([t])})})}columns(e){let t=e.map(L.create);return new OnConflictBuilder({...this.#e,onConflictNode:G.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:G.cloneWith(this.#e.onConflictNode,{constraint:P.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:G.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new ua({...this.#e,onConflictNode:G.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}},ua=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:G.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:G.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:G.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}};const da=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 da.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const fa=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}});var pa=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{columns:freeze(e.map(L.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:fa.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:fa.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:fa.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:fa.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:fa.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:fa.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{onConflict:e(new la({onConflictNode:G.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{onDuplicateKey:ca.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:U.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:U.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}};const ma=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}});var K,DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new K({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new K({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new K({...this.#e,queryNode:U.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new K({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new K({...this.#e,queryNode:Xi.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 K({...this.#e,queryNode:U.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new K({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new K({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new K({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new K({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new K({...this.#e,queryNode:U.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new K({...this.#e,queryNode:Xi.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new K({...this.#e,queryNode:U.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new K({...this.#e,queryNode:U.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new K({...this.#e,queryNode:Xi.cloneWithLimit(this.#e.queryNode,ma.create(parseValueExpression(e)))})}modifyEnd(e){return new K({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new K({...this.#e})}$castTo(){return new K(this.#e)}$narrowType(){return new K(this.#e)}$assertType(){return new K(this.#e)}withPlugin(e){return new K({...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 K({...this.#e,queryNode:U.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};K=DeleteQueryBuilder;var UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},q,UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new q({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new q({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new q({...this.#e,queryNode:U.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new q({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new q({...this.#e,queryNode:Ji.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 q({...this.#e,queryNode:U.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new q({...this.#e,queryNode:U.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new q({...this.#e,queryNode:U.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new q({...this.#e,queryNode:Ji.cloneWithLimit(this.#e.queryNode,ma.create(parseValueExpression(e)))})}set(...e){return new q({...this.#e,queryNode:Ji.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new q({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new q({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new q({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new q({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new q({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new q({...this.#e,queryNode:U.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new q({...this.#e})}$castTo(){return new q(this.#e)}$narrowType(){return new q(this.#e)}$assertType(){return new q(this.#e)}withPlugin(e){return new q({...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 q({...this.#e,queryNode:U.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};q=UpdateQueryBuilder;const ha=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:I.create(e),columns:t?freeze(t.map(L.create)):void 0})}}),ga=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 _a=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:ga.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:ga.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():ga.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new _a({node:ga.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 ha.create(n,r)}return ha.create(e)}const va=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])})}}),ya=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return ya[~~(Math.random()*ya.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 ba={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)&&ba[e.kind]===!0}const xa=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:P.create(this.#e)}}transformReferences(e,t){let n=super.transformReferences(e,t);return n.table.table.schema?n:{...n,table:I.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=>I.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return xa[e.func]?e[n].map(e=>!I.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&&ci.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&&(_i.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(I.is(e))return this.#s(e.table,t);if(fi.is(e)&&I.is(e.node))return this.#s(e.node.table,t);if(qi.is(e))for(let n of e.items)this.#o(n,t);else if(Yi.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 Sa=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 $i.create(parseFilterList([Sa.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)?R.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 J={};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(J);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==J)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(J)}}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 Ca=freeze([]);var QueryExecutorBase=class{#e;constructor(e=Ca){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(J);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})===J&&(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===J?(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===J&&(d.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),f}finally{c(J),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(J);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===J&&(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===J&&(l=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{s(J),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 wa=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}},Ta=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new Ea({...this.#e,queryNode:H.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},Ea=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.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:H.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:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:H.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 Ea({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new Ea({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new Ea({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:wa,queryNode:Ji.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new Ea({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new Ea({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(B.cloneWith(B.createWithoutInto(),{columns:t,values:n})))})}},Da=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:W.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:W.cloneWithSelections(W.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new pa({queryId:createQueryId(),executor:this.#e.executor,queryNode:B.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new pa({queryId:createQueryId(),executor:this.#e.executor,queryNode:B.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Xi.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Ji.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new Ta({queryId:createQueryId(),executor:this.#e.executor,queryNode:H.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?va.cloneWithExpression(this.#e.withNode,n):va.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?va.cloneWithExpression(this.#e.withNode,n):va.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 Da({executor:wa})}function createJoinBuilder(e,t){return new ta({joinNode:_i.create(e,parseTableExpression(t))})}function createOverBuilder(){return new ra({overNode:Ui.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 _i.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return _i.create(e,parseTableExpression(t))}const Oa=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),ka=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(ka.create)}const Aa=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=>Aa.create(e,parseExpression(t),n))}var Y=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new ja(hi.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new Ma(mi.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 fi.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():P.create(this.#t))}},ja=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(hi.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return Bi.create(this.#e)}},Ma=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(mi.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return Bi.create(this.#e)}};const Na=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:z.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 Na.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var X,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new X({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new X({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new X({...this.#e,queryNode:W.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new X({...this.#e,queryNode:W.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new X({...this.#e,queryNode:W.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new X({...this.#e,queryNode:W.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new X({...this.#e,queryNode:W.cloneWithFrontModifier(this.#e.queryNode,pi.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,pi.createWithExpression(e.toOperationNode()))})}distinct(){return new X({...this.#e,queryNode:W.cloneWithFrontModifier(this.#e.queryNode,pi.create(`Distinct`))})}forUpdate(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,pi.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,pi.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,pi.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,pi.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,pi.create(`SkipLocked`))})}noWait(){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,pi.create(`NoWait`))})}selectAll(e){return new X({...this.#e,queryNode:W.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 X({...this.#e,queryNode:U.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new X({...this.#e,queryNode:U.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new X({...this.#e,queryNode:W.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new X({...this.#e,queryNode:W.cloneWithLimit(this.#e.queryNode,ma.create(parseValueExpression(e)))})}offset(e){return new X({...this.#e,queryNode:W.cloneWithOffset(this.#e.queryNode,Oa.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new X({...this.#e,queryNode:W.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new X({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new X({...this.#e,queryNode:W.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new X({...this.#e,queryNode:U.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new X({...this.#e,queryNode:W.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new X({...this.#e,queryNode:W.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new X({...this.#e,queryNode:U.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new X({...this.#e,queryNode:W.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new X({...this.#e})}$castTo(){return new X(this.#e)}$narrowType(){return new X(this.#e)}$assertType(){return new X(this.#e)}$asTuple(){return new Y(this.toOperationNode())}$asScalar(){return new Y(this.toOperationNode())}withPlugin(e){return new X({...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 X({...this.#e,queryNode:U.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};X=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 fi.create(this.#e.toOperationNode(),P.create(this.#t))}};const Pa=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]?Vi.cloneWithItems(e[r],t):Vi.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?V.cloneWithOperation(e.filter,`And`,t):V.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?V.cloneWithOperation(e.filter,`Or`,t):V.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),Fa=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var Ia=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:Pa.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:U.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:U.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Pa.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Pa.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Pa.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Pa.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 fi.create(this.#e.toOperationNode(),P.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new Y(Fa.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new Ia({aggregateFunctionNode:Pa.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 Ia({aggregateFunctionNode:Pa.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 Ia({aggregateFunctionNode:Pa.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new Y(Fa.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const La=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 La.create(Oi.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const Z=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),$i.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:Z.cloneWithWhen(this.#e.node,$i.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:Z.cloneWithWhen(this.#e.node,$i.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:Z.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:Z.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:Z.cloneWithWhen(this.#e.node,$i.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:Z.cloneWithWhen(this.#e.node,$i.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:Z.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:Z.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new Y(Z.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Y(Z.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new Y(Z.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Y(Z.cloneWith(this.#e.node,{isStatement:!0}))}};const Ra=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),za=/^#-\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`&&!za.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 Fi.is(this.#e)?new Ba(Fi.cloneWithTraversal(this.#e,Li.is(this.#e.traversal)?Li.cloneWithLeg(this.#e.traversal,Ra.create(e,t)):Ii.cloneWithValue(this.#e.traversal,z.createImmediate(t)))):new Ba(Li.cloneWithLeg(this.#e,Ra.create(e,t)))}},Ba=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 fi.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():P.create(this.#t))}};const Va=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),Ha=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}),Ua=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+\)$/]),Wa=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return Ha[e]||Ua.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return Wa.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const Ga=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=wa){function binary(e,t,n){return new Y(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new Y(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:W.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:Z.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new Y(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(Li.create())},table(e){return new Y(parseTable(e))},val(e){return new Y(parseValueExpression(e))},refTuple(...e){return new Y(Va.create(e.map(parseReferenceExpression)))},tuple(...e){return new Y(Va.create(e.map(parseValueExpression)))},lit(e){return new Y(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 Y(vi.create(parseReferenceExpression(e),Oi.create(`between`),mi.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new Y(vi.create(parseReferenceExpression(e),Oi.create(`between symmetric`),mi.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new Y(parseFilterList(e,`and`)):new Y(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new Y(parseFilterList(e,`or`)):new Y(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return Bi.is(t)?new Y(t):new Y(Bi.create(t))},cast(e,t){return new Y(Ga.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 fi.create(parseTable(this.#e),P.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 fi.create(parseTable(n),P.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return I.createWithSchema(t,n)}return I.create(e)}function trim$1(e){return e.trim()}const Ka=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}}),Q=freeze({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return freeze({kind:`ColumnDefinitionNode`,column:L.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})}}),qa=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:L.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Ja=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:L.create(e),renameTo:L.create(t)})}}),Ya=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?P.create(t):void 0})}}),Xa=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys(Xa);const Za=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)&&Xa[e]}function parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():z.createImmediate(e)}const Qa=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})}}),$a=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 eo=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||ki.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{references:Za.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(Q.cloneWith(this.#e,{references:Za.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(Q.cloneWith(this.#e,{references:Za.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{defaultTo:$a.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{check:Ya.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{generated:Qa.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{generated:Qa.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{generated:Qa.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{generated:Qa.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(Q.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(Q.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}};const to=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}}),no=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:Za.create(t,n),name:r?P.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var ro=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(no.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(no.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(no.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(no.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(no.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(no.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}};const io=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}}),ao=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(L.create)),freeze({kind:`UniqueConstraintNode`,columns:freeze(e),name:t?P.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return freeze({...e,...t})}}),oo=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:P.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),so=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:L.create(e),[t]:n})}});var AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(so.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(so.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(so.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(so.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(so.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)}},co=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(N.cloneWithTableProps(this.#e.node,{addConstraint:io.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)}},lo=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:N.cloneWithTableProps(this.#e.node,{dropConstraint:oo.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:N.cloneWithTableProps(this.#e.node,{dropConstraint:oo.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:N.cloneWithTableProps(this.#e.node,{dropConstraint:oo.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 uo=freeze({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return freeze({kind:`PrimaryKeyConstraintNode`,columns:freeze(e.map(L.create)),name:t?P.create(t):void 0})},cloneWith(e,t){return freeze({...e,...t})}}),fo=freeze({is(e){return e.kind===`AddIndexNode`},create(e){return freeze({kind:`AddIndexNode`,name:P.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}});var po=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:N.cloneWithTableProps(this.#e.node,{addIndex:fo.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:N.cloneWithTableProps(this.#e.node,{addIndex:fo.cloneWithColumns(this.#e.node.addIndex,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})})}columns(e){return new AlterTableAddIndexBuilder({...this.#e,node:N.cloneWithTableProps(this.#e.node,{addIndex:fo.cloneWithColumns(this.#e.node.addIndex,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})})}expression(e){return new AlterTableAddIndexBuilder({...this.#e,node:N.cloneWithTableProps(this.#e.node,{addIndex:fo.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:N.cloneWithTableProps(this.#e.node,{addIndex:fo.cloneWith(this.#e.node.addIndex,{using:R.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)}},mo=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(ao.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(ao.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(ao.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(ao.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(ao.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},ho=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(uo.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(uo.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(uo.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(uo.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 go=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:P.create(e),newName:P.create(t)})}});var _o=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:qa.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:N.cloneWithTableProps(this.#e.node,{renameTo:parseTable(e)})})}setSchema(e){return new AlterTableExecutor({...this.#e,node:N.cloneWithTableProps(this.#e.node,{setSchema:P.create(e)})})}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new vo({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new _o({node:qa.create(e)}));return new vo({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new vo({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,Ja.create(e,t))})}addColumn(e,t,n=noop){let r=n(new eo(Q.create(e,parseDataTypeExpression(t))));return new vo({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,Ka.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new eo(Q.create(e,parseDataTypeExpression(t))));return new vo({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,to.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new mo(ao.create(t.map(e=>isString(e)?L.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:N.cloneWithTableProps(this.#e.node,{addConstraint:io.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Ya.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:N.cloneWithTableProps(this.#e.node,{addConstraint:io.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new ro(no.create(t.map(L.create),parseTable(n),r.map(L.create),e)));return new co({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new ho(uo.create(t,e)));return new AlterTableExecutor({...this.#e,node:N.cloneWithTableProps(this.#e.node,{addConstraint:io.create(r.toOperationNode())})})}dropConstraint(e){return new lo({...this.#e,node:N.cloneWithTableProps(this.#e.node,{dropConstraint:oo.create(e)})})}renameConstraint(e,t){return new lo({...this.#e,node:N.cloneWithTableProps(this.#e.node,{renameConstraint:go.create(e,t)})})}addIndex(e){return new po({...this.#e,node:N.cloneWithTableProps(this.#e.node,{addIndex:fo.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:N.cloneWithTableProps(this.#e.node,{dropIndex:li.create(e)})})}$call(e){return e(this)}},vo=class AlterTableColumnAlteringBuilder{#e;constructor(e){this.#e=freeze(e)}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new _o({node:qa.create(e)}));return new AlterTableColumnAlteringBuilder({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new AlterTableColumnAlteringBuilder({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,Ja.create(e,t))})}addColumn(e,t,n=noop){let r=n(new eo(Q.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,Ka.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new eo(Q.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:N.cloneWithColumnAlteration(this.#e.node,to.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 zi.create(e.values.map(z.createImmediate))}transformValue(e){return z.createImmediate(e.value)}},yo=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:ai.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:ai.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:ai.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:ai.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:ai.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:ai.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:ai.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:ai.cloneWith(this.#e.node,{using:R.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:U.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)}},bo=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:oi.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(si.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var xo=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder(fo.cloneWith(this.#e,{using:R.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},So=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:F.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:F.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:F.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new eo(Q.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:F.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new ho(uo.create(t,e)));return new CreateTableBuilder({...this.#e,node:F.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new mo(ao.create(t.map(e=>isString(e)?L.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:F.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new xo(fo.cloneWithColumns(fo.create(e),t.map(e=>isString(e)?L.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:F.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Ya.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:F.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new ro(no.create(t.map(L.create),parseTable(n),r.map(L.create),e)));return new CreateTableBuilder({...this.#e,node:F.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:F.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:F.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:F.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)}},Co=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:li.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:li.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:li.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)}},wo=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:ui.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:ui.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)}},To=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:di.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:di.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:di.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 Eo=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:ci.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)}},Do=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:Eo.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:Eo.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:Eo.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:Eo.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:Eo.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:Eo.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 Oo=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:ci.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var ko=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:Oo.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:Oo.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:Oo.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 Ao=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:zi.create(t.map(z.createImmediate))})}});var jo=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:Ao.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 Mo=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 No=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:Mo.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:Mo.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 ci.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return ci.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}const Po=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:ci.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var Fo=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:Po.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Po.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Po.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 Io=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}}),Lo=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)}},Ro,AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new Ro({...this.#e,node:Io.cloneWith(this.#e.node,{addValue:Lo.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 Ro({...this.#e,node:Io.cloneWith(this.#e.node,{addValue:Lo.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:z.createImmediate(e)})})})}};Ro=AlterTypeAddValueBuilder;const zo=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:Io.cloneWith(this.#e.node,{addValue:Lo.create(z.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:Io.cloneWith(this.#e.node,{renameTo:P.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:Io.cloneWith(this.#e.node,{renameValue:zo.create(z.createImmediate(e),z.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:Io.cloneWith(this.#e.node,{setSchema:P.create(e)})})}},Bo=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new So({queryId:createQueryId(),executor:this.#e,node:F.create(parseTable(e))})}dropTable(e){return new To({queryId:createQueryId(),executor:this.#e,node:di.create(parseTable(e))})}createIndex(e){return new yo({queryId:createQueryId(),executor:this.#e,node:ai.create(e)})}dropIndex(e){return new Co({queryId:createQueryId(),executor:this.#e,node:li.create(e)})}createSchema(e){return new bo({queryId:createQueryId(),executor:this.#e,node:oi.create(e)})}dropSchema(e){return new wo({queryId:createQueryId(),executor:this.#e,node:ui.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:N.create(parseTable(e))})}createView(e){return new Do({queryId:createQueryId(),executor:this.#e,node:Eo.create(e)})}refreshMaterializedView(e){return new Fo({queryId:createQueryId(),executor:this.#e,node:Po.create(e)})}dropView(e){return new ko({queryId:createQueryId(),executor:this.#e,node:Oo.create(e)})}createType(e){return new jo({queryId:createQueryId(),executor:this.#e,node:Ao.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:Io.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new No({queryId:createQueryId(),executor:this.#e,node:Mo.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)}}},Vo=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 Ho=[`read only`,`read write`],Uo=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function validateTransactionSettings(e){if(e.accessMode&&!Ho.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!Uo.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 Wo=class Kysely extends Da{#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 Vo(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 Bo(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:Z.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new Ko({...this.#e})}startTransaction(){return new qo({...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()}},Go=class Transaction extends Wo{#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 Wo({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},Ko=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 Yo(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),o=new Go({...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}})}},qo=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 Jo({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},Jo=class ControlledTransaction extends Go{#e;#t;constructor(e){e={...e,executor:new Yo(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 Yo=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)}},Xo=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?wa: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 Xo(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 fi.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():P.create(this.#t))}};const $=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:R.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:R.create(t,e.map(P.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(z.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithSql(e)})},join(e,t=$`, `){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:R.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 Zo=/'/g,Qo=/['"]/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&&!Bi.is(this.parentNode)&&!B.is(this.parentNode)&&!F.is(this.parentNode)&&!Eo.is(this.parentNode)&&!Aa.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&&!Bi.is(this.parentNode)&&!R.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(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&&!Bi.is(this.parentNode)&&!R.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(ts[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&&!Bi.is(this.parentNode)&&!R.is(this.parentNode)&&!$i.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($o[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 Oi.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&&F.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(Zo,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(Qo,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?es[e.modifier]-es[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const $o=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),es=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),ts=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`}),ns=freeze({raw(e,t=[]){return freeze({sql:e,query:R.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 R.createWithChildren([R.createWithSql(`${e} `),P.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(ns.raw(`begin`))}async commitTransaction(e){await e.executeQuery(ns.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(ns.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(!W.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 rs=/"/g,is=/[\\'"]/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(rs,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(is,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const as=`kysely_migration`,os=`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`,`!=`,as).where(`name`,`!=`,os)),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`,$`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 ss=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(ns.raw(n))}async commitTransaction(e){await e.executeQuery(ns.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(ns.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[ss]()}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}}[ss](){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(ns.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`,$`col_description(a.attrelid, a.attnum)`.as(`column_description`),$`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($`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`,`!=`,as).where(`c.relname`,`!=`,os));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 cs=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(cs,`""`)}};const ls=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await $`
    with set_timeout as (
      select set_config('lock_timeout', '${$.lit(36e5)}', true) as config_val
    )
    select pg_advisory_lock(${$.lit(ls)})
    from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await $`select pg_advisory_unlock(${$.lit(ls)})`.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 us=/^v?((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u,ds=[{major:24,minor:16,patch:0},{major:26,minor:1,patch:0}],fs=ds[ds.length-1];`${ds.map(({major:e,minor:t,patch:n},r)=>`>=${e}.${t}.${n}${r<ds.length-1?` <${e+1}`:``}`).join(` || `).replaceAll(` || `,`, `).replace(/, ([^,]+)$/,`, or $1`)}`;function parseNodeReleaseVersion(e){if(typeof e!=`string`)return null;let t=us.exec(e.trim());if(!t)return null;let n={major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])};return Object.values(n).every(Number.isSafeInteger)&&(!t[4]||n.major>fs.major)?n:null}function isNodeVersionAtLeast(e,t){return e?e.major===t.major?e.minor===t.minor?e.patch>=t.patch:e.minor>t.minor:e.major>t.major:!1}function renderProcessNodeVersionCheck(){return`((value) => {
  if (typeof value !== "string") return false;
  const match = new RegExp(${JSON.stringify(us.source)}, "u").exec(value.trim());
  if (!match) return false;
  const version = { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) };
  if (!Object.values(version).every(Number.isSafeInteger)) return false;
  const floors = ${JSON.stringify(ds)};
  if (match[4] && version.major <= floors[floors.length - 1].major) return false;
  const minimum = floors.find((floor) => floor.major === version.major);
  const atLeast = (floor) =>
    version.major > floor.major ||
    (version.major === floor.major &&
      (version.minor > floor.minor ||
        (version.minor === floor.minor && version.patch >= floor.patch)));
  return minimum ? atLeast(minimum) : version.major > floors[floors.length - 1].major;
})(process.versions.node)`}renderProcessNodeVersionCheck();const templateFragments=(e,t)=>e,ps=templateFragments`(SELECT value FROM json_each(${0}))`,ms=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!R.is(e)||e.sqlFragments!==ps||e.parameters.length!==1)return;let t=e.parameters[0];for(;R.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!z.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(Oi.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===ps;!t&&e.sqlFragments!==ms?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 hs=parseNodeReleaseVersion(process.versions.node),gs=!process.versions.bun&&(hs?.major===24&&isNodeVersionAtLeast(hs,{major:24,minor:20,patch:0})||isNodeVersionAtLeast(hs,{major:26,minor:6,patch:0})),_s=new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),vs=/* @__PURE__ */ new WeakMap,ys=new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});function getNodeSqliteKysely(e){if(wt(e)){let t=vs.get(e);return t||(t=new Wo({dialect:ys}),vs.set(e,t)),t}let t=Bt.get(e);if(t)return t;let n=new Wo({dialect:_s});return Bt.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{Ut.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 l(i,r)}function executeCompiledSqliteQuerySync(e,t,n=!1,r=t.parameters){if(wt(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 Kt(e),Vt(e,i,r,i=>{if(n&&W.is(t.query)){let e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(W.is(t.query)||i.columns().length>0){if(gs)return{rows:i.all(...r)};let t=i.iterate(...r),n=Et(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 l(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 B.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),$`${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(wt(e))return(function*(){yield*executeCompiledSqliteQuerySync(e,t.compile()).rows})();let n=pt();return(function*(){let r=t.compile(),i;try{if(i=e.prepare(r.sql),!W.is(r.query)&&i.columns().length===0)return;let t=r.parameters,a=i.iterate(...t),o=Et(e,`kysely iterator`,n),s=!1;try{for(let e of a)o.progress(),yield e}catch(e){throw s=!0,l(e,`SQLite iterator failed`)}finally{releaseSqliteIterator(a,o,s,`SQLite iterator cleanup failed`)}}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}finally{i&&Ht(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=Jt(Gt(n),{readOnly:!0});try{let n=getNodeSqliteKysely(r),{rows:i}=executeSqliteQuerySync(r,{compile:()=>$`SELECT expires_at AS expiresAt
              FROM ${$`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()-D.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 isLegacyPluginSourceCaptureName(e){return e.startsWith(`openclaw-plugin-build-`)||e.startsWith(`openclaw-model-catalog-`)}function normalizeProcArg(t){return e(t.replaceAll(`\\`,`/`))}const bs=[`openclaw.mjs`,`dist/index.js`,`dist/entry.js`,`scripts/run-node.mjs`,`src/entry.ts`,`src/index.ts`];function referencesRetainedArtifact(e){return e.split(/[\\/=]/u).some(e=>isLegacyPluginSourceCaptureName(e)||/^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(e))}function readProcessPackageIdentity(e,t=!1){for(let n=e;;){let e;try{e=JSON.parse(D.readFileSync(E.join(n,`package.json`),`utf8`))}catch(e){let r=E.dirname(n);if(t&&u(e)===`ENOENT`){if(r===n)return{kind:`absent`};if(E.basename(n)===`node_modules`)return{kind:`unknown`,reason:`could not read package identity`};n=r;continue}return{kind:`unknown`,reason:`could not read package identity`}}return!i(e)||typeof e.name!=`string`||!e.name.trim()||e.name!==e.name.trim()?{kind:`unknown`,reason:`package identity has no valid name`}:{kind:`package`,name:e.name,scripts:i(e.scripts)?e.scripts:{}}}}function readProcessWorkingDirectories(e){let t=new Set(e.filter(e=>Number.isSafeInteger(e)&&e>0)),n=/* @__PURE__ */ new Map;if(t.size===0)return n;if(process.platform===`linux`){for(let e of t)try{n.set(e,D.readlinkSync(`/proc/${e}/cwd`))}catch{}return n}try{if(process.platform===`darwin`){let e=Pn(`/usr/sbin/lsof`,[`-a`,`-p`,[...t].join(`,`),`-d`,`cwd`,`-F0pn`],{encoding:`utf8`,timeout:5e3,maxBuffer:4194304,env:resolveDiagnosticProcessEnv()});if(e.error||e.status!==0&&e.status!==1)return n;let r=e.stdout.split(`\0`);r.pop();let i=/* @__PURE__ */ new Set,a;for(let e of r){let r=e.replace(/^\n/,``);if(r.startsWith(`p`)){let e=/^p(\d+)$/.exec(r);a=e&&t.has(Number(e[1]))?Number(e[1]):void 0}else a!==void 0&&r.startsWith(`n`)&&E.isAbsolute(r.slice(1))&&(n.delete(a)?i.add(a):i.has(a)||n.set(a,r.slice(1)))}}}catch{}return n}function classifyEntrypoint(e,t={}){let n=normalizeProcArg(e[0]??``).replace(/\.(bat|cmd|exe)$/i,``);if(!t.requirePackageIdentity&&(n.endsWith(`/openclaw`)||n===`openclaw`))return{kind:`openclaw`,entryIndex:0};let r=/(?:^|\/)openclaw\.mjs$/.test(n)?0:tn(e).position;if(typeof r!=`number`)return r.kind===`unclassified`?{kind:`unclassified`,cause:`runtime-syntax`,reason:r.reason}:{kind:`other`};let i=e[r];if(t.inspectPackage&&!t.requirePackageIdentity&&t.cwd&&E.isAbsolute(t.cwd)&&nn(e[0]??``)&&!/[\\/]/u.test(i)&&!E.extname(i)){let e=readProcessPackageIdentity(t.cwd,!0);if(e.kind===`unknown`)return{kind:`unclassified`,cause:`package-identity`,reason:e.reason};let n=e.kind===`package`?e.scripts[i]:void 0;if(typeof n==`string`&&n.trim())return e.kind===`package`&&e.name===`openclaw`?{kind:`openclaw`}:{kind:`other`}}let a=classifyOpenClawEntrypointPath(i,t);return a.kind===`openclaw`?{...a,entryIndex:r}:a}function classifyOpenClawEntrypointPath(e,t={}){let n=normalizeProcArg(e);if(!t.requirePackageIdentity&&!t.inspectPackage&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};let r=[...bs,...t.additionalEntrypoints??[]],i=e;if(!E.isAbsolute(e)){let n=t.cwd??(t.pid===void 0?void 0:readProcessWorkingDirectories([t.pid]).get(t.pid));if(!n||!E.isAbsolute(n))return{kind:`unclassified`,cause:`cwd`,reason:`working directory is unavailable`};i=E.resolve(n,e)}let a,o;try{if(a=D.realpathSync(i),t.inspectPackage&&!t.requirePackageIdentity&&referencesRetainedArtifact(a))return{kind:`openclaw`,artifactPath:a};let n=t.requirePackageIdentity||t.inspectPackage?D.statSync(a):void 0;if(t.requirePackageIdentity&&!n?.isFile())return{kind:`unclassified`,cause:`script`,reason:`entrypoint is not a regular file: ${e}`};o=n?.isDirectory()??!1}catch{return{kind:`unclassified`,cause:`script`,reason:`could not resolve script`}}let s=normalizeProcArg(a);if(!t.requirePackageIdentity&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};let c=o?void 0:r.find(e=>s.endsWith(`/${e}`));if(!c&&(!t.inspectPackage||t.requirePackageIdentity))return{kind:`other`};let l=c?a.slice(0,-c.length):o?a:E.dirname(a),u=readProcessPackageIdentity(l,t.inspectPackage&&!t.requirePackageIdentity||!c&&!o);return u.kind===`unknown`?{kind:`unclassified`,cause:`package-identity`,reason:u.reason}:u.kind===`package`&&u.name===`openclaw`?{kind:`openclaw`,...t.requirePackageIdentity?{packageIdentity:{root:E.resolve(l),entrypoint:a}}:{}}:{kind:`other`}}function classifyOpenClawArgv(e,t={}){let{command:n,owner:r,pid:i,port:a}=t;if(!t.requirePackageIdentity&&n===`gateway`&&r?.pid===i&&r?.state===`live`&&(a===void 0||r.port===a))return{kind:`openclaw`};let o=normalizeProcArg(e[0]??``).split(`/`).at(-1)?.replace(/\.(exe|cmd|bat)$/,``)??``;if(!t.requirePackageIdentity&&/^openclaw-[a-z0-9-]+$/.test(o))return!n||o===`openclaw-${n}`?{kind:`openclaw`}:{kind:`other`};let s=classifyEntrypoint(e,t);if(n)return s.kind===`openclaw`&&normalizeProcArg(getRootOptionAwareCommandPath([`node`,...e.slice(s.entryIndex)],1)[0]??``)!==n?{kind:`other`}:s;if(s.kind===`openclaw`||!t.requirePackageIdentity&&e.some(e=>e.replaceAll(`\\`,`/`).split(`/`).some(isLegacyPluginSourceCaptureName)))return s.kind===`openclaw`?s:{kind:`openclaw`};if(t.serviceMarkerUnavailable&&!t.requirePackageIdentity)return{kind:`unclassified`,cause:`service-marker`,reason:`process environment is unreadable`};let c=t.serviceMarker;if(i!==void 0&&process.platform===`linux`&&(en(o)||nn(o)||o===`tsx`))try{c=D.readFileSync(`/proc/${i}/environ`,`utf8`).split(`\0`).find(e=>e.startsWith(`OPENCLAW_SERVICE_MARKER=`))?.slice(24)}catch(e){return{kind:`unclassified`,cause:`service-marker`,reason:`process identity inspection failed (${u(e)??`unavailable`})`}}return!t.requirePackageIdentity&&c===`openclaw`?{kind:`openclaw`}:s}const xs=new Mn;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=i(e)?e:null;if(!r)return!1;let a=classifyGatewayLockProcessNamespace(r,t,n);if(a===`unknown`)throw new GatewayLockNamespaceError(r,t);return comparableStateOwnerStaleReason(r,a)!==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=D.readFileSync(n,`utf8`)}catch(e){if(u(e)===`ENOENT`)return;throw new yr(i,{cause:e})}let o=xs.getStore();if(o?.deadOwner?.path===n&&o.deadOwner.raw===a)return;let s=parseGatewayLockPayload(a);if(!s)throw new Sr(t,i);if(!Number.isSafeInteger(s.pid)||s.pid<=0)throw new yr(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&&!Dn)return;if(c===`same`&&!isPidAlive(s.pid))throw new Sr(t,i);let d=s.role??`gateway`;if(d===`gateway`||d===`agent-embedded`)return;if(c===`same`&&s.pid===process.pid){r();return}let f=`OpenClaw state at ${t} is undergoing offline maintenance by ${d} 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 Sr(t,f):new Cr(t,f)}function defaultPayload(e){let t=jt(e),n=getFileLockProcessStartTime(process.pid),r=Xt(),i=r===void 0?null:getFileLockProcessStartTime(r);return{pid:process.pid,ownerId:hn(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:E.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?_t():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=D.readFileSync(t,`utf8`)}catch(e){if(u(e)===`ENOENT`)return;throw e}let i=parseGatewayLockPayload(r);if(!(isGatewayStateOwnerDefinitelyStale(i)||i?.pid===n.pid)&&!(n.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&classifyOpenClawArgv(process.argv,{command:`gateway`}).kind===`openclaw`))throw new Sr(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(E.dirname(t),i);let s={holder:null},stale=({payload:n})=>(s.holder=vr.safeParse(n).data??null,isGatewayStateOwnerDefinitelyStale(s.holder,t,e));if(r>0)try{let n=s.holder=parseGatewayLockPayload(D.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t,e)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&isPidAlive(n.pid)))throw new br(e)}catch(e){if(u(e)!==`ENOENT`)throw e}for(let c=!1;;)try{return acquireFileLockSync(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=u(n);if(r===`ENOENT`&&!c){c=!0,ensureOwnerDirectory(E.dirname(t),i);continue}if(r===`file_lock_timeout`||r===`file_lock_stale`){let{holder:r}=s,i=describeGatewayLockHolder(r??{},t,r&&isPidAlive(r.pid)?`live`:`unknown`);throw new br(e,n,i,r?{pid:r.pid,role:r.role}:void 0)}throw n}}const Ss=a(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new Mn);function getStateDatabaseSchemaLease(e){let t=Ss.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(),j.clear();let t=new Map(Ss.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,j.clear()};try{let n=Ss.run(t,e);return xt(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||M.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw Error(`OpenClaw state maintenance does not own this database`)},run,release(){j.clear(),i||(r?.release(),t.release(),i=!0,n.locks.delete(t),r&&n.locks.delete(r),n.locks.size===0&&M.get(n.key)===n&&(n.heartbeat?.stop(),n.accepting=!1,M.delete(n.key),n.onReleased?.())),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){j.clear();let r=resolveStateOwnerIdentity(e),i=M.get(r.key),a=i?.path??r.ownerPath;if(i&&(!i.accepting||!hasPhysicalOwnership(i)))throw new br(e,i.lost.signal.reason);i&&assertStateDatabaseAccessAllowed(e);let o=i?.payload??{...defaultPayload(e),stateOwnerKind:`schema`},s,c=[];try{s=acquireGatewayStateOwnerFile(e,a,o,i?0:t.busyTimeoutMs??5e3,c)}catch(t){if(t instanceof br)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof Sr)throw e}throw t}let l=i?.projectionPath??E.join(n(jt(At(e))),`gateway.state.lock`),u;try{u=i?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,l,{...o,role:o.role===`gateway`?`gateway`:`agent-embedded`},0,c)}catch(e){return St({release(){s.release(),removeCreatedProjectionDirectories(c)}},`state schema projection admission`,()=>{throw e})}i?(i.locks.add(s),i.locks.add(u),i.projectionDirectories.push(...c)):(i={key:r.key,path:a,kind:`schema`,payload:o,projectionPath:l,locks:/* @__PURE__ */ new Set([s,u]),projectionDirectories:c,lost:new AbortController,accepting:!0},M.set(i.key,i));let d=leaseForFile(a,s,i,u);try{let e=i.heartbeat??=startGatewayStateOwnerHeartbeat(i.locks,(e,t)=>observeOwnerLoss(i,e,t));return d.assertCurrent(),e.register(u),d}catch(e){return St(d,`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`?ne(n):n,i=M.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(),M.get(r)!==i)throw createGatewayStateProcessOwnerRetiredError()},assertCurrent=()=>{if(assertRegistered(),!i.accepting)throw createGatewayStateProcessOwnerRetiredError();assertStateDatabaseAccessAtOwnerPath(n,a,void 0)},o=createStateDatabaseAccess(a,i),assertReadAllowed=e=>{assertRegistered(),o.assertReadAllowed(e)},s=E.resolve(e.databasePath),c=t?assertCurrent:assertRegistered;if(c(),t||j.get(s)!==i){let t=await kt(s);if(c(),(process.platform===`win32`?ne(t):t)!==r)throw new br(e.databasePath)}return t||(assertReadAllowed(),j.get(E.resolve(n))===i&&j.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(M.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}let r=E.resolve(e);if(j.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=M.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.`);j.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=M.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||M.get(e.key)!==r)throw createGatewayStateProcessOwnerRetiredError()}}:void 0,prepareAccess:async r=>{let i=t??M.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&&M.get(e.key)!==i)throw createGatewayStateProcessOwnerRetiredError();assertStateDatabaseReadAtOwnerPath(n,t,e)};let o=i.heartbeat,s=i.locks.values().next().value,c=i.getProjection?.();if(!o||!s)throw createGatewayStateProcessOwnerRetiredError();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),o.assertActive(),M.get(e.key)!==i||i.heartbeat!==o)throw createGatewayStateProcessOwnerRetiredError();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(s)||i.getProjection?.()!==c)throw createGatewayStateProcessOwnerRetiredError()};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 j.set(E.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:Mt();if(!r)throw new xr(e);r.assertDatabaseAccess(e)},r=M.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})}const Cs=8192;function*jsonFieldBatches(e){let t=[],n=16;for(let r of fields(e)){let e=dn(r).byteLength+16;n+e>65536&&(yield t,t=[],n=16),t.push(r),n+=e}t.length&&(yield t)}function*textFields(e,t){yield{kind:e,value:t.slice(0,Cs)};for(let n=Cs;n<t.length;n+=Cs)yield{kind:e,value:t.slice(n,n+Cs),append:!0}}function*fields(e){if(e!==void 0){if(typeof e==`string`)yield*textFields(`value`,e);else if(e===null||typeof e==`boolean`||typeof e==`number`)yield{kind:`value`,value:typeof e==`number`&&!Number.isFinite(e)?null:e};else if(typeof e==`object`){yield{kind:Array.isArray(e)?`array`:`object`};for(let[t,n]of Object.entries(e))n!==void 0&&(yield*textFields(`key`,t),yield*fields(n));yield{kind:`end`}}else throw TypeError(`JSON document contains non-JSON value: ${typeof e}`)}}function isJsonTransferField(e){return i(e)?e.kind===`object`||e.kind===`array`||e.kind===`end`||(e.kind===`key`||e.kind===`value`)&&(e.append===void 0||e.append===!0&&typeof e.value==`string`)&&(typeof e.value==`string`||e.kind===`value`&&(e.value===null||typeof e.value==`boolean`||typeof e.value==`number`)):!1}function createJsonFieldReceiver(){let e,t=!1,n=[],r,write=r=>{let i=n.at(-1);if(i){if(i.key===void 0)throw Error(`JSON field has no property key`);Object.defineProperty(i.container,i.key,{value:r,writable:!0,enumerable:!0,configurable:!0}),i.key=void 0}else{if(t)throw Error(`JSON transfer has more than one root`);e=r,t=!0}},flush=()=>{if(!r)return;let e=r.chunks.join(``);if(r.kind===`key`){let t=n.at(-1);if(!t||t.key!==void 0)throw Error(`JSON property key has no value or container`);t.key=e}else write(e);r=void 0};return{accept(e){if(!isJsonTransferField(e))throw Error(`Invalid JSON transfer field`);if(e.kind===`key`||e.kind===`value`){if(e.append){if(!r||r.kind!==e.kind||typeof e.value!=`string`)throw Error(`Invalid JSON string continuation`);r.chunks.push(e.value);return}flush(),typeof e.value==`string`?r={kind:e.kind,chunks:[e.value]}:write(e.value)}else if(flush(),e.kind===`end`){let e=n.pop();if(!e||e.key!==void 0)throw Error(`JSON container ended with an incomplete field`)}else{let t=e.kind===`array`?[]:{};write(t),n.push({container:t})}},finish(){if(flush(),n.length)throw Error(`JSON transfer ended with an incomplete container`);return e}}}function parseStateLeaseProcessOwner(e){let t=safeParseJsonRecord(e??``)?.owner;if(!i(t))return null;let{pid:n,host:r,startedAt:a}=t;return typeof n!=`number`||!Number.isSafeInteger(n)||n<=0||typeof r!=`string`||!r||a!==null&&(typeof a!=`number`||!Number.isSafeInteger(a)||a<0)?null:{pid:n,host:r,startedAt:a,...t.machineIdentity===void 0?{}:{machineIdentity:hr.safeParse(t.machineIdentity).data??null},...t.processNamespace===void 0?{}:{processNamespace:gr.safeParse(t.processNamespace).data??null}}}function readStateLeaseProcessOwnerStatus(e,t){if(!e)return`unknown`;let n=classifyGatewayOwnerProcessNamespace(e.processNamespace,{ownerHost:e.host,machineIdentity:e.machineIdentity,readGatewayHeartbeat:t===void 0?void 0:()=>t});return n===`same`?readSameNamespaceProcessOwnerStatus(e):n}function readSameNamespaceProcessOwnerStatus(e){if(isPidDefinitelyDead(e.pid))return`dead`;let t=getFileLockProcessStartTime(e.pid);return e.startedAt===null||t===null?`unknown`:t===e.startedAt?`live`:`dead`}function hasVerifiedLiveSqliteOwner(e,t){if(j.get(E.resolve(e))?.accepting)return!0;let n=resolveGatewayStateOwnerPath(e),r;try{r=parseGatewayLockPayload(D.readFileSync(n,`utf8`))}catch{return!1}if(!r||r.role&&r.role!==`gateway`&&r.role!==`agent-embedded`||classifyGatewayLockProcessNamespace(r,n)===`dead`)return!1;let i=readStateLeaseProcessOwnerStatus({pid:r.pid,host:r.processNamespace?.host??xn(),startedAt:r.startTime??null,processNamespace:r.processNamespace,machineIdentity:r.machineIdentity});if(i===`unknown`&&t?.unknownOwner!==`return-false`)throw new GatewayLockNamespaceError(r,n);return i===`live`}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$1(e){let t=D.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(D.lstatSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=readFile$1(e),r=readFile$1(`${e}-wal`);return n?{root:t,main:fingerprint(n),wal:r&&r.size>32n?walFingerprint(r):null}:void 0}function readSqlitePrivateSnapshotFamily(e){let isFingerprint=(e,t)=>typeof e==`string`&&t.test(e);if(!i(e)||typeof e.root!=`string`||!E.isAbsolute(e.root)||!isFingerprint(e.main,/^-?\d+(?::-?\d+){5}$/)||e.wal!==null&&!isFingerprint(e.wal,/^-?\d+(?::-?\d+){3}$/))throw Error(`SQLite private fork requires its producer's captured family`);return{root:e.root,main:e.main,wal:e.wal}}async function forkSqlitePrivateSnapshotInProcess(e,t,n){let r=E.relative(t.root,e);if(!r||r===`..`||r.startsWith(`..${E.sep}`)||E.isAbsolute(r))throw Error(`SQLite private fork source is outside its retained directory`);let i=Pe(t.root),a;try{return St({release:i},`Private SQLite snapshot fork`,()=>{let r=captureSqlitePrivateSnapshotFamily(e,t.root);if(r?.main!==t.main||r?.wal!==t.wal)throw new Ve(`retained-snapshot-changed`);a=Le(n);let i=E.join(a,`database.sqlite.partial`);for(let[n,r]of[[``,t.main],[`-wal`,t.wal]]){if(r===null)continue;let a=`${e}${n}`,o=se({rootPath:t.root,absolutePath:a,boundaryLabel:`retained SQLite snapshot`});if(!o.ok)throw Error(`Cannot open retained SQLite snapshot: ${a}`,{cause:o.error});try{let e=D.fstatSync(o.fd,{bigint:!0});Re(a,`${i}${n}`,{key:`file:${e.dev}:${e.ino}`})}finally{D.closeSync(o.fd)}}return Ee(a)})}catch(e){let t=[e];throw a&&!await be(a,e=>t.push(e))&&t.push(/* @__PURE__ */ Error(`Private SQLite fork cleanup failed: ${a}`)),dt(t,`Private SQLite fork and cleanup failed`),e}}function captureSqliteAuthSchema(e,t){if(gt(e)?.key!==t)return;let n=Ct(e,Wt,()=>void 0);if(!n)return;let kind=e=>n.tables.has(e)?`table`:n.views.has(e)||n.indexes.has(e)||n.triggers.has(e)?`other`:`missing`;return{userVersion:n.userVersion,store:kind(`auth_profile_store`),state:kind(`auth_profile_state`)}}function readSqliteAuthSchema(e){if(e===void 0)return;let isKind=e=>e===`table`||e===`other`||e===`missing`;if(!i(e)||typeof e.userVersion!=`number`||!Number.isSafeInteger(e.userVersion)||e.userVersion<0||!isKind(e.store)||!isKind(e.state))throw Error(`Invalid auth profile schema projection`);return{userVersion:e.userVersion,store:e.store,state:e.state}}function createSqliteWorkerTransferOwner(){let e=0,t,cleanup=e=>{let t=[];for(let[n,r]of[[`iteratorClosed`,()=>e.iterator.return?.()],[`cleaned`,()=>e.cleanup?.()]])if(!e[n])try{r(),e[n]=!0}catch(e){t.push(e)}dt(t,`SQLite read transfer cleanup failed`)},cancel=()=>{t&&=(cleanup(t),void 0)},requireTransfer=e=>{if(!t||t.id!==e)throw Error(`SQLite read transfer is no longer active`);return t};return{start(n,r){if(t)throw Error(`The preceding SQLite read transfer was not released`);return t={id:++e,iterator:n,cleanup:r.cleanup,iteratorClosed:!1,cleaned:!1,counts:new Map(r.kinds.map(e=>[e,0])),sequence:0,finished:!1},{id:t.id,kinds:[...t.counts.keys()]}},next(e){let t=requireTransfer(e);if(t.finished)throw Error(`SQLite read transfer has already reached its end`);if(t.record&&t.record.offset===t.record.bytes.byteLength&&(t.record=void 0),!t.record){let n=t.iterator.next();if(n.done)return cleanup(t),t.finished=!0,{id:e,sequence:t.sequence++,done:!0,counts:[...t.counts]};let{kind:r}=n.value,i=t.counts.get(r);if(i===void 0)throw Error(`SQLite read transfer returned an unexpected record kind`);t.record={kind:r,bytes:`serialized`in n.value?n.value.serialized:dn(n.value.value),offset:0},t.counts.set(r,i+1)}let n=t.record,r=n.offset,i=Math.min(n.bytes.byteLength,r+8388608);return n.offset=i,{id:e,sequence:t.sequence++,done:!1,kind:n.kind,recordBytes:n.bytes.byteLength,offset:r,recordDone:i===n.bytes.byteLength,bytes:new Uint8Array(n.bytes.subarray(r,i))}},end(e){if(!requireTransfer(e).finished)throw Error(`SQLite read transfer ended before its complete result`);cancel()},cancel,close:cancel}}function createSqliteWorkerTransferReceiver(e,t){let n=new Map(e.kinds.map(e=>[e,0])),r=0,i=!1,a;return{accept(o){try{if(i||o.id!==e.id||o.sequence!==r++)throw Error(`SQLite read transfer frame is out of order`);if(o.done){if(a||o.counts.length!==n.size||o.counts.some(([e,t])=>n.get(e)!==t)||new Set(o.counts.map(([e])=>e)).size!==n.size)throw Error(`SQLite read transfer ended with an incomplete result`);return i=!0,o.counts}let s=n.get(o.kind);if(s===void 0||!Number.isSafeInteger(o.recordBytes)||o.recordBytes<1||!Number.isSafeInteger(o.offset)||o.offset<0||o.bytes.byteLength<1||o.bytes.byteLength>8388608)throw Error(`SQLite read transfer returned an invalid frame`);if(!a){if(o.offset!==0)throw Error(`SQLite read transfer omitted the start of a record`);a={kind:o.kind,bytes:o.recordDone?o.bytes:new Uint8Array(o.recordBytes),offset:0}}let c=o.offset+o.bytes.byteLength;if(a.kind!==o.kind||a.bytes.byteLength!==o.recordBytes||a.offset!==o.offset||c>o.recordBytes||o.recordDone!==(c===o.recordBytes))throw Error(`SQLite read transfer returned a discontinuous record`);if(a.bytes!==o.bytes&&a.bytes.set(o.bytes,o.offset),a.offset=c,o.recordDone){let e=un(a.bytes),r=a.kind;a=void 0,t({kind:r,value:e}),n.set(r,s+1)}return}catch(e){throw a=void 0,i=!0,e}}}}function encodeSqliteAuthTransferFrame(e){return e.done?e:{...e,bytes:Buffer.from(e.bytes.buffer,e.bytes.byteOffset,e.bytes.byteLength).toString(`base64`)}}function decodeFrame(e,t){if(e.done)return e;if(e.bytes.length>11184812)throw Error(`Invalid ${t} transfer bytes`);let n=Buffer.from(e.bytes,`base64`);if(n.toString(`base64`)!==e.bytes)throw Error(`Invalid ${t} transfer encoding`);return{...e,bytes:n}}function createSqliteReadOnlyTransferReceiver(e){let t,n,r=!1,i=!1;return{accept(a){if(i)throw Error(`Invalid ${e.label} transfer response`);if(a.type===`start`&&!t){let r=a.handle;if(!Number.isSafeInteger(r.id)||r.id<1||r.kinds.length!==e.kinds.length||r.kinds.some((t,n)=>t!==e.kinds[n]))throw Error(`Invalid ${e.label} transfer handle`);return n=r.id,t=createSqliteWorkerTransferReceiver({id:n,kinds:e.kinds},({kind:t,value:n})=>e.acceptRecord(t,n)),{request:{type:`next`,transferId:n}}}if(!t||n===void 0)throw Error(`${e.label.charAt(0).toUpperCase()}${e.label.slice(1)} transfer has not started`);if(a.type===`frame`&&!r){let i=decodeFrame(a.frame,e.label);if(!i.done&&e.maxRecordBytes&&i.recordBytes>e.maxRecordBytes)throw Error(`${e.label} transfer record exceeds its bound`);let o=t.accept(i);if(o){if(o.length!==e.kinds.length||o.some(([,e])=>e<1))throw Error(`Incomplete ${e.label} transfer result`);r=!0}return{request:{type:r?`end`:`next`,transferId:n}}}if(a.type===`complete`&&r)return i=!0,{value:e.readResult()};throw Error(`${e.label.charAt(0).toUpperCase()}${e.label.slice(1)} transfer response is out of order`)}}}function createSqliteAuthTransferReceiver(){let e=createJsonFieldReceiver();return createSqliteReadOnlyTransferReceiver({kinds:[`fields`],label:`auth profile`,maxRecordBytes:65536,acceptRecord(t,n){if(!Array.isArray(n))throw Error(`Invalid auth profile field batch`);for(let t of n)e.accept(t)},readResult(){let t=e.finish();if(!i(t)||!(`store`in t)||!(`state`in t)||typeof t.cacheable!=`boolean`)throw Error(`Invalid auth profile transfer rows`);return{store:t.store,state:t.state,cacheable:t.cacheable}}})}function createSqliteOperationTransferReceiver(e){let t;return createSqliteReadOnlyTransferReceiver({kinds:[`result`],label:`SQLite operation`,acceptRecord(n,r){if(t||!i(r)||r.operation!==e||!(`value`in r))throw Error(`SQLite read-only worker returned a different or duplicate operation`);t={operation:e,value:r.value}},readResult(){if(!t)throw Error(`SQLite read-only worker returned no operation`);return t}})}function createWorkerOperationRegistry(e){let t=new Map(Object.entries(e).map(([e,t])=>[e,{load:t}])),domainFor=e=>typeof e==`string`?t.get(e)??t.get(e.slice(0,e.indexOf(`.`))):void 0,handlerFor=e=>{let t=domainFor(e)?.handlers;return t&&Object.hasOwn(t,e)?t[String(e)]:void 0};return{prepare(e){let t=domainFor(e);if(t&&!t.handlers)return t.pending??=Promise.resolve().then(t.load).then(e=>{t.handlers=e})},has(e){return handlerFor(e.type)!==void 0},execute(e,t){let n=handlerFor(e.type);if(!n)throw Error(`Worker operation is not prepared: ${String(e.type)}`);return n(e.input,t)}}}const ws=createWorkerOperationRegistry({startupMetadata:()=>import(`./sqlite-readonly-startup-metadata-live-read.worker-CZqkVv0O.mjs`).then(e=>e.startupMetadataReadOperations),deferredSessionImport:()=>import(`./sqlite-readonly-deferred-plugin-session-transcript-read.worker-BehyTJ8z.mjs`).then(e=>e.deferredSessionTranscriptReadOperations),agentRetirement:()=>import(`./sqlite-readonly-agent-delete-session-store-safety.kernel-C8y95yj5.mjs`).then(e=>e.agentDeletionSessionStoreAbsentReadOperations),pageCache:()=>import(`./sqlite-readonly-sqlite-page-cache.worker-Bg8xBKzQ.mjs`).then(e=>e.pageCacheReadOperations),databaseStore:()=>import(`./sqlite-readonly-database-store-live-read.worker-Dsic_VaX.mjs`).then(e=>e.databaseStoreLiveReadOperations),immutableInstall:()=>import(`./sqlite-readonly-package-update-activation-immutable-BtUYqtqO.mjs`).then(e=>e.immutableInstallReadOperations)}),Ts=1048576;function isSqliteSnapshotStagingMode(e){return e===`staging-create`||e===`staging-create-legacy`||e===`staging-reconcile`||e===`staging-retire`}var SqliteReadOnlyInspectionContentionError=class extends Error{};function sqliteReadOnlyWorkerRequestArgs(e,t){let n=[t.mode,E.resolve(e)];if(t.mode===`task-delivery-recovery`)return[...n,E.resolve(t.recoveryDirectory),E.resolve(t.sourcePath)];let r=t.stagingRoot&&E.resolve(t.stagingRoot);if(t.mode===`private-fork`)return[...n,r??``,JSON.stringify(t.family)];let i=t.mode===`auth-profile-rows`||t.mode===`operation`?void 0:t.expectedSourceIdentity;if(i!==void 0){if(t.mode!==`sync`&&t.mode!==`staged-sync`&&t.mode!==`metadata`)throw Error(`SQLite source identity is supported only for sync or metadata snapshots`);n.push(r??``,JSON.stringify(yt(i)))}else r&&n.push(r);return n}const Es=4e3;function isSqliteReadOnlyWorkerResult(e){return!e||typeof e!=`object`||Array.isArray(e)?!1:`ok`in e&&e.ok===!1&&`message`in e&&typeof e.message==`string`?Object.keys(e).length===2||Object.keys(e).length===3&&`errcode`in e&&typeof e.errcode==`number`&&Number.isInteger(e.errcode)&&e.errcode>=0&&e.errcode<=2147483647:Object.keys(e).length!==2||!(`ok`in e)?!1:e.ok===!0&&`engine`in e&&i(e.engine)&&(e.engine.engine===`sqlite`||e.engine.engine===`postgres`&&typeof e.engine.storeId==`string`&&typeof e.engine.namespace==`string`)||e.ok===!0&&`reclamation`in e&&i(e.reclamation)&&[e.reclamation.removed,e.reclamation.bytes,e.reclamation.skipped].every(e=>typeof e==`number`&&Number.isFinite(e)&&e>=0)||e.ok===!0&&`hasExistingData`in e&&typeof e.hasExistingData==`boolean`||e.ok===!0&&`location`in e&&typeof e.location==`string`||e.ok===!0&&`contentVersion`in e&&typeof e.contentVersion==`string`&&/^(?:[a-f0-9]{64})?$/.test(e.contentVersion)||e.ok===!0&&`generation`in e&&typeof e.generation==`string`||e.ok===!0&&`taskDeliveryRecovery`in e&&i(e.taskDeliveryRecovery)&&Object.keys(e.taskDeliveryRecovery).length===2&&typeof e.taskDeliveryRecovery.count==`number`&&Number.isSafeInteger(e.taskDeliveryRecovery.count)&&e.taskDeliveryRecovery.count>0&&typeof e.taskDeliveryRecovery.payloadSha256==`string`&&/^[a-f0-9]{64}$/u.test(e.taskDeliveryRecovery.payloadSha256)}function createSqliteReadOnlyWorkerError(e,t,n){let r=An(d(t.trim(),-4e3));return Error(`SQLite read-only worker ${e}${r?`\nstderr (tail): ${r}`:``}`,n)}function parseSqliteReadOnlyWorkerResult(e,t){if(!e.trim())throw createSqliteReadOnlyWorkerError(`returned no JSON result`,t);let n;try{n=JSON.parse(e)}catch{throw createSqliteReadOnlyWorkerError(`returned invalid JSON`,t)}if(!isSqliteReadOnlyWorkerResult(n))throw createSqliteReadOnlyWorkerError(`returned an invalid result`,t);return n}function readSqliteReadOnlyWorkerValue(e,t){if(e.kind===`launch-failed`)throw e.error;let n;try{n=parseSqliteReadOnlyWorkerResult(e.stdout,e.stderr)}catch(t){throw e.failure?createSqliteReadOnlyWorkerError(e.failure,e.stderr,{cause:e.cause}):t}if(e.status!==0||e.failure||!n.ok){let r=!n.ok&&(e.status===0||e.status===1)&&n.message.startsWith(`SQLite snapshot capacity unavailable: `),i=n.ok?e.failure??`exited with code ${e.status}`:r?n.message.slice(38):n.message,a=!n.ok&&i.startsWith(`Retryable SQLite inspection contention: `),o=a?i.slice(40):i,s=e.failure===void 0&&!n.ok&&(t===`staging-create`||t===`staging-create-legacy`)&&o.startsWith(`SQLite snapshot directory creation refused: `),c=createSqliteReadOnlyWorkerError(s?o.slice(44):o,e.stderr,{cause:e.cause});if(n.ok||n.errcode===void 0||t!==`backup-engine`&&t!==`backup-engine-preserving`&&t!==`state-sqlite-populated`||e.status!==0&&e.status!==1||Object.assign(c,{errcode:n.errcode}),r)throw new Te(c.message,{cause:e.cause});if(a){let e=new SqliteReadOnlyInspectionContentionError(c.message);throw s?ge(e):e}throw c}if((t===`sync`||t===`private-fork`||t===`async`||t===`staged-sync`||t===`staged-async`||t===`metadata`||t===`consolidated`||isSqliteSnapshotStagingMode(t))&&`location`in n)return n.location;if(t===`staging-sweep`&&`reclamation`in n)return n.reclamation;if((t===`backup-engine`||t===`backup-engine-preserving`)&&`engine`in n)return n.engine;if(t===`state-sqlite-populated`&&`hasExistingData`in n)return n.hasExistingData;if(t===`content-version`&&`contentVersion`in n)return n.contentVersion;if((t===`file-generation`||t===`update-generation`)&&`generation`in n)return n.generation;if(t===`task-delivery-recovery`&&`taskDeliveryRecovery`in n)return n.taskDeliveryRecovery;throw createSqliteReadOnlyWorkerError(`returned a result for a different operation`,e.stderr)}const Ds=/* @__PURE__ */ new Map;async function inspect(e,t){let n=e[0],r=e[1],i=e[2]||void 0;try{if(n===`staging-sweep`){if(e.length!==1)throw Error(`SQLite staging sweep does not accept a database path`);let{reclaimSqliteSnapshotInstallationInProcess:t}=await import(`./sqlite-readonly-sqlite-snapshot-reclamation-BwNk8dHJ.mjs`);return{ok:!0,reclamation:await t()}}if(n!==`sync`&&n!==`private-fork`&&n!==`update-generation`&&n!==`async`&&n!==`staged-sync`&&n!==`staged-async`&&n!==`metadata`&&n!==`backup-engine`&&n!==`backup-engine-preserving`&&n!==`state-sqlite-populated`&&n!==`consolidated`&&n!==`task-delivery-recovery`&&!isSqliteSnapshotStagingMode(n)||!r)return{ok:!1,message:`SQLite read-only worker requires a mode and a database path`};if(n===`state-sqlite-populated`){let[{inspectPhysicalStoreInProcess:e},{inspectStateSqlite:t}]=await Promise.all([import(`./sqlite-readonly-physical-store-inspection-BaNgFJEq.mjs`).then(e=>e.t),import(`./sqlite-readonly-openclaw-state-db-engine-pc5Xuwy7.mjs`).then(e=>e.s)]);return{ok:!0,hasExistingData:await e(r,!0,e=>{let n=t(e);return!n.hasEngineAnchor&&n.hasExistingData})}}if(n===`backup-engine`||n===`backup-engine-preserving`){let{readBackupEngineInProcess:e}=await import(`./sqlite-readonly-physical-store-inspection-BaNgFJEq.mjs`).then(e=>e.t);return{ok:!0,engine:await e(r,n===`backup-engine-preserving`)}}if(n===`task-delivery-recovery`){let t=e[2],n=e[3];if(e.length!==4||!t||!n)throw Error(`Task delivery recovery requires its private snapshot, recovery directory, and source path`);let{preserveOrphanTaskDeliveryRecoveryInProcess:i}=await import(`./sqlite-readonly-openclaw-state-db-task-delivery-recovery-preservation-CaAFxaLL.mjs`).then(e=>e.a);return{ok:!0,taskDeliveryRecovery:i(r,n,t)}}if(e.length>4||e[3]!==void 0&&n!==`sync`&&n!==`staged-sync`&&n!==`metadata`&&n!==`private-fork`)throw Error(`SQLite source identity is supported only for sync or metadata snapshots`);let a=e[3]===void 0||n===`private-fork`?void 0:yt(JSON.parse(e[3])),o=n===`staged-sync`||n===`staged-async`;if(o&&!i)throw Error(`SQLite staged snapshot requires its owner-allocated directory`);if(n===`update-generation`){let{readUpdateDatabaseGenerations:e}=await import(`./sqlite-readonly-update-database-generations-CnLHMbYV.mjs`);return{ok:!0,generation:JSON.stringify(e([r])[r])}}if(n===`staging-reconcile`)return Fe(r),{ok:!0,location:r};if(n===`staging-create`||n===`staging-create-legacy`){let e=Ie(r,n===`staging-create-legacy`);return Ds.set(e.directory,e.release),{ok:!0,location:e.directory}}if(n===`staging-retire`){let e=Ds.get(r);if(!e)throw Error(`SQLite snapshot token is not owned by this worker`);let t=ve(r,{token:e});try{for(let e of De(t))await ln();Ds.delete(r)}finally{t.release()}return{ok:!0,location:r}}let s;if(n===`private-fork`){if(!i||e[3]===void 0)throw Error(`SQLite private fork requires staging and its captured family`);s=await forkSqlitePrivateSnapshotInProcess(r,readSqlitePrivateSnapshotFamily(JSON.parse(e[3])),i)}else if(n===`consolidated`){if(!i||E.dirname(E.resolve(r))!==E.resolve(i))throw Error(`SQLite consolidation requires its caller-owned private snapshot directory`);s=await ze(r,i)}else if(n===`metadata`){if(!a)throw Error(`SQLite metadata snapshot requires a captured source identity`);vt(r,a.key,a.birthtime),assertStateDatabaseAccessAllowed(r),s=hasVerifiedLiveSqliteOwner(r)?await ze(r,i):await Me(r,i,a);try{vt(r,a.key,a.birthtime),assertStateDatabaseAccessAllowed(r)}catch(e){throw await s.cleanupAsync(),e}}else{let e=o&&i?{directory:i}:i;s=n===`sync`||n===`staged-sync`?await Me(r,e,a):await Be(r,e)}let c=s.cleanupRoot??E.dirname(s.location);return Ce(c),ye(c),t(s),{ok:!0,location:s.location}}catch(e){let t=e instanceof Ve||Tt(e),r=(n===`staging-create`||n===`staging-create-legacy`)&&xe(e),i=(we(e)?`SQLite snapshot capacity unavailable: `:``)+(t?`Retryable SQLite inspection contention: `:``)+(r?`SQLite snapshot directory creation refused: `:``),a=n===`backup-engine`||n===`backup-engine-preserving`||n===`state-sqlite-populated`?Ot(e):void 0;return{ok:!1,message:`${i}${ft(e)}`,...a===void 0?{}:{errcode:a}}}}function runSession(){let e=!1,t=!1,n=!1,r=0,a=!1,s=Promise.resolve(),c=createSqliteWorkerTransferOwner(),l,stop=(e=!1,t=!1)=>{if(e&&(r=1),n)return;n=!0;let retire=async()=>{if(t)for(let[e,t]of Ds)ye(e,t),await be(e);await Se();let e=[()=>c.close(),...Ds.values()];for(let t of e)try{t()}catch(e){r=1,process.stderr.write(`SQLite read-only worker cleanup failed: ${ft(e)}\n`)}Ds.clear(),l=void 0,process.stdin.destroy(),process.connected&&process.disconnect?.(),process.exitCode=r};s.then(retire,retire)},send=(r,i,o=!1,s)=>{if(!n){if(!process.connected||!process.send)stop(!0);else{a||=o;try{process.send({id:r,result:i},n=>{n||o?stop(!0):(s?.(),t&&!e&&stop())})}catch{stop(!0)}}}},fail=(e,t)=>{send(e,{ok:!1,message:ft(t)},!0)};process.once(`disconnect`,()=>stop(e,!0)),process.on(`message`,r=>{if(n||a)return;if(r===`close`){e?t=!0:stop();return}if(i(r)&&l&&r.id===l.requestId&&i(r.transfer)){let{requestId:t,transferId:n,label:i}=l;try{if(r.transfer.transferId!==n)throw Error(`${i} transfer identity changed`);if(r.transfer.type===`next`)send(t,{type:`frame`,frame:encodeSqliteAuthTransferFrame(c.next(n))});else if(r.transfer.type===`end`)c.end(n),l=void 0,e=!1,send(t,{type:`complete`});else throw Error(`Invalid ${i.toLowerCase()} transfer command`)}catch(e){fail(t,e)}return}if(!e&&i(r)&&typeof r.id==`number`&&Number.isSafeInteger(r.id)&&Array.isArray(r.args)&&r.args.length===2&&(r.args[0]===`auth-profile-rows`||r.args[0]===`operation`)&&typeof r.args[1]==`string`){let t=r.id,a=r.args[1],o=r.args[0]===`operation`,u=o?r.operation:r.auth;e=!0;let execute=async()=>{if(!i(u)||typeof u.expectedIdentity!=`string`||!u.expectedIdentity.startsWith(`file:`)||u.expectedBirthtime!==void 0&&typeof u.expectedBirthtime!=`string`)throw Error(o?`SQLite read requires captured physical ownership`:`Auth profile read requires captured physical ownership`);let{expectedIdentity:e,expectedBirthtime:r}=u;if(o){if(typeof u.command!=`string`)throw Error(`Invalid SQLite read-only operation encoding`);let o=un(Buffer.from(u.command,`base64`));if(!i(o)||typeof o.type!=`string`||!(`input`in o))throw Error(`Invalid SQLite read-only operation`);let s={type:o.type,input:o.input};if(await ws.prepare(s.type),n)return;if(!ws.has(s))throw Error(`Unknown SQLite read-only operation: ${s.type}`);vt(a,e,r);let d=await ws.execute(s,{path:a,env:process.env,assertCurrent:()=>{if(n)throw Error(`SQLite read-only worker is stopping`);vt(a,e,r)}});if(n)return;vt(a,e,r);let f=c.start([{kind:`result`,value:{operation:s.type,value:d}}].values(),{kinds:[`result`]});l={requestId:t,transferId:f.id,label:`SQLite operation`},send(t,{type:`start`,handle:f});return}let{readAuthProfileRowsReadOnly:s}=await import(`./sqlite-readonly-sqlite-json-ClTF7x_h.mjs`),d=u.immutable===!0?(e,t)=>Jt(qt(e),{...t,readOnly:!0}):u.artifactPreserving===!0?(await import(`./sqlite-readonly-sqlite-snapshot-source-DID1ReIT.mjs`).then(e=>e.a)).openSqliteReadOnlyDatabase:(e,t)=>Jt(e,{...t,readOnly:!0});if(n)return;vt(a,e,r);let f=s(a,d,readSqliteAuthSchema(u.schema),e,u.retainReader===!0);u.artifactPreserving===!0&&(f.cacheable=!1),vt(a,e,r);function*rowFields(){for(let e of jsonFieldBatches(f))yield{kind:`fields`,value:e}}let p=c.start(rowFields(),{kinds:[`fields`]});l={requestId:t,transferId:p.id,label:`Auth profile`},send(t,{type:`start`,handle:p})};s=(i(u)&&u.artifactPreserving===!0?withArtifactPreservingStateReads(execute,{agentDatabases:!0}):execute()).catch(e=>fail(t,e)).finally(scheduleOpenClawCompileCacheFlush);return}if(e||!r||typeof r!=`object`||Object.keys(r).length!==2||!(`id`in r)||typeof r.id!=`number`||!Number.isSafeInteger(r.id)||!(`args`in r)||!o(r.args)||r.args[0]!==`sync`&&r.args[0]!==`private-fork`&&!isSqliteSnapshotStagingMode(r.args[0])){stop(!0);return}e=!0;let u=r.id,d=isSqliteSnapshotStagingMode(r.args[0]),f;s=inspect(r.args,e=>{f=e}).then(t=>{let n=Buffer.byteLength(JSON.stringify(t))>1048576?{ok:!1,message:`exceeded its output buffer`}:t;send(u,n,!n.ok&&!d,()=>{f&&Ce(f.cleanupRoot??E.dirname(f.location)),e=!1})}).catch(e=>fail(u,e)).finally(scheduleOpenClawCompileCacheFlush)})}async function runOneShot(e){let t=e[0]===`staged-sync`||e[0]===`staged-async`?e[2]:void 0,n,r=!1;process.stdout.on(`error`,()=>{});try{let i=t?Pe(t):void 0,a;try{a=await inspect(e,e=>{n=e})}finally{i?.()}a.ok||(process.exitCode=1),await new Promise((e,t)=>{process.stdout.write(JSON.stringify(a),n=>n?t(n):e())}),r=!0,n&&Ce(n.cleanupRoot??E.dirname(n.location))}finally{r||(await Se(),t&&await be(t))}}process.argv[2]===`--openclaw-sqlite-readonly-child`&&(f(),mt(),process.argv[3]===`session`&&process.send?runSession():runOneShot(process.argv.slice(3)).catch(e=>{process.exitCode=1,process.stderr.write(`${ft(e)}\n`)}));export{workerMessagePayloadBytes as $,executeSqliteQuerySync as A,isUpdateCommandArgv as B,withStateDatabaseColdAdmission as C,isArtifactPreservingStateRead as Ct,readProcessWorkingDirectories as D,safeParseJson as Dt,readProcessPackageIdentity as E,withArtifactPreservingStateReads as Et,parseNodeReleaseVersion as F,isWorkerGcObservationEnabled as G,attributeWorkerToPool as H,SqliteQueryCompiler as I,recordPostgresPoolSelfRoot as J,markWorkerRetirement as K,$ as L,getNodeSqliteKysely as M,iterateSqliteQuerySync as N,referencesRetainedArtifact as O,safeParseJsonRecord as Ot,prepareSqliteQuerySync as P,recordWorkerMessage as Q,expressionBuilder as R,prepareStateDatabaseReadAccess as S,Vn as St,classifyOpenClawEntrypointPath as T,isStartupConfigStateRead as Tt,createCpuTrackedWorker as U,rewriteUpdateFlagArgv as V,flushWorkerDiagnostics as W,observeWorkerMessage as X,trackNativeWorkerForCpu as Y,recordWorkerAuthorityMessage as Z,acquireStateDatabaseSchemaLease as _,parseLinuxProcessStat as _t,isSqliteSnapshotStagingMode as a,applyPrivateModeSync as at,captureStateDatabaseAccess as b,resolveDiagnosticProcessEnv as bt,createSqliteAuthTransferReceiver as c,yr as ct,createSqliteWorkerTransferReceiver as d,Cr as dt,classifyWorkerRequest as et,captureSqliteAuthSchema as f,createManagedHandoffBootIdentityReader as ft,readStateLeaseProcessOwnerStatus as g,isPidDefinitelyDeadAsync as gt,parseStateLeaseProcessOwner as h,isPidDefinitelyDead as ht,isSqliteReadOnlyWorkerResult as i,resolveRuntimeProcessEntrypointUrl as it,executeSqliteQueryTakeFirstSync as j,createSqliteQueryCache as k,resolveSafeNodeCompileCacheDirectory as kt,createSqliteOperationTransferReceiver as l,Sr as lt,hasVerifiedLiveSqliteOwner as m,getProcessInstanceStartTime as mt,Ts as n,captureRuntimeWorkerSource as nt,readSqliteReadOnlyWorkerValue as o,sha256Hex as ot,captureSqlitePrivateSnapshotFamily as p,getFileLockProcessStartTime as pt,receiveWorkerMemoryPort as q,createSqliteReadOnlyWorkerError as r,resolveRuntimeWorkerGenerationUrl as rt,sqliteReadOnlyWorkerRequestArgs as s,br as st,Es as t,normalizeWorkerRequestClass as tt,createSqliteWorkerTransferOwner as u,xr as ut,assertStateDatabaseAccessAllowed as v,readLinuxProcessStat as vt,classifyOpenClawArgv as w,isLiveStateRead as wt,getStateDatabaseSchemaLease as x,isContainerEnvironment as xt,assertStateDatabaseReadAllowed as y,mergeProcessEnv as yt,getRootOptionAwareCommandPath as z};