openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
10 lines • 343 kB
JavaScript
import{t as e}from"./plugin-preparation-rolldown-runtime-C5ba_Z9N.mjs";import{h as t,i as n,s as r,t as i,u as a}from"./plugin-preparation-record-coerce-CWNcHDAn.mjs";import{n as o,o as s,t as c}from"./plugin-preparation-error-graph-internal-3EGECs5H.mjs";import{$ as l,G as u,U as d,X as f,Y as p,Z as ee,c as m,k as te,l as ne,s as h,u as re}from"./plugin-preparation-diagnostic-events-C0NITktC.mjs";import{E as ie,O as ae,S as oe,T as se,d as ce,f as le,i as ue,k as de,n as fe,o as pe,t as me,u as he,w as ge}from"./plugin-preparation-subsystem-D76Sei3m.mjs";import{$ as _e,A as ve,Bt as ye,Ct as g,Dt as be,Et as xe,Ht as Se,M as Ce,N as we,Rt as Te,S as Ee,St as De,T as Oe,Tt as ke,Ut as Ae,a as je,bt as Me,c as Ne,ct as Pe,d as Fe,dn as Ie,en as Le,et as Re,fn as ze,g as Be,gn as Ve,h as He,hn as Ue,i as We,j as Ge,kt as Ke,ln as qe,lt as Je,m as Ye,nt as Xe,o as Ze,ot as Qe,pn as $e,pt as et,qt as tt,rn as nt,rt,s as it,st as at,tn as ot,tt as st,un as ct,ut as lt,vt as ut,w as dt,wt as ft,x as pt,xt as mt,yt as ht}from"./plugin-preparation-worker-native-lifecycle-D72AWAt5.mjs";import{g as gt,h as _t,n as vt,p as yt,r as bt,u as xt}from"./plugin-preparation-sleep-D6xG-JRB.mjs";import{n as St}from"./plugin-preparation-utf8-truncate-DvnUPaRb.mjs";import{A as Ct,C as wt,D as Tt,F as Et,I as Dt,L as Ot,M as kt,N as At,O as jt,P as Mt,R as Nt,S as Pt,_ as Ft,b as It,d as _,f as v,g as Lt,h as Rt,i as zt,j as Bt,l as Vt,m as y,n as Ht,o as Ut,p as Wt,r as Gt,s as b,t as Kt,u as qt,v as Jt,x as Yt,y as Xt,z as Zt}from"./plugin-preparation-result-D34pSHZd.mjs";import{t as Qt}from"./plugin-preparation-deferred-B75K7ut7.mjs";import{n as $t}from"./plugin-preparation-src-f3atoZzb.mjs";import{a as en,o as tn,s as nn}from"./plugin-preparation-cli-invocation-CQPKFT_h.mjs";import{t as rn}from"./plugin-preparation-runtime-process-entrypoints-JtM_i2_8.mjs";import{n as an,t as on}from"./plugin-preparation-runtime-worker-url-D-YZ5wuH.mjs";import{t as sn}from"./plugin-preparation-expect-Cp38ZrcJ.mjs";import{t as cn}from"./plugin-preparation-errors-8b9QitPs.mjs";import{n as ln,r as un}from"./plugin-preparation-path-existence-C_m6CcB7.mjs";import{t as dn}from"./plugin-preparation-child-BfarVUUz.mjs";import{c as pn,d as mn,h as hn,u as gn}from"./plugin-preparation-service-child-group-ownership-DVaB1fex.mjs";import{D as _n,E as vn,F as yn,M as bn,O as xn,P as Sn,T as Cn,a as wn,f as Tn,g as En,h as Dn,i as On,k as kn,l as An,n as jn,o as Mn,p as Nn,r as Pn,t as Fn,w as In}from"./plugin-generation-preparation.worker.js";import{n as Ln,r as Rn,t as zn}from"./plugin-preparation-openclaw-process-census-C5htElpb.mjs";import{d as Bn,f as Vn}from"./plugin-preparation-exec-spawn-BuVpSm1O.mjs";import{t as Hn}from"./plugin-preparation-spawn-diagnostics-BTl-smV2.mjs";import{d as Un,f as Wn,r as Gn,u as Kn}from"./plugin-preparation-logger-file-worker-DAaYvJKx.mjs";import{createRequire as qn}from"node:module";import{MessageChannel as Jn,isMainThread as Yn,threadId as Xn}from"node:worker_threads";import{AsyncLocalStorage as x}from"node:async_hooks";import{randomUUID as Zn}from"node:crypto";import S,{chmodSync as Qn,existsSync as $n,realpathSync as er,statSync as tr,unlinkSync as nr,writeFileSync as rr}from"node:fs";import"node:fs/promises";import ir from"node:os";import C from"node:path";import{fileURLToPath as ar}from"node:url";import"@openclaw/fs-safe/path";import{toUSVString as or}from"node:util";import{deserialize as sr,serialize as cr}from"node:v8";import{channel as lr}from"node:diagnostics_channel";import"node:perf_hooks";import{readFileDescriptorBoundedSync as ur,readFileWindowFullySync as dr,sameFileIdentity as fr}from"@openclaw/fs-safe/advanced";import"@openclaw/fs-safe/errors";import pr,{spawnSync as mr}from"node:child_process";import"semver";import"@openclaw/fs-safe/durability";import{isUtf8 as hr}from"node:buffer";import{Socket as gr}from"node:net";import"node:timers/promises";import{acquireFileLockSync as _r}from"@openclaw/fs-safe/file-lock";function toStringifiedError(e){return e instanceof Error?e:Error(String(e))}const vr=[`byte`,`kilo`,`mega`,`giga`,`tera`],yr={iec:{base:1024,labels:[`B`,`KiB`,`MiB`,`GiB`,`TiB`]},"legacy-binary":{base:1024,labels:[`B`,`KB`,`MB`,`GB`,`TB`]}};function formatByteSize(e,t){let{base:n,labels:r}=yr[t.style],i=vr.indexOf(t.maxUnit),a=0,o=e;for(;o>=n&&a<i;)o/=n,a+=1;for(;;){let e=sn(vr[a],`byte-size unit`),s=sn(r[a],`byte-size label`),c=typeof t.fractionDigits==`function`?t.fractionDigits(o,e):t.fractionDigits;if(c===null)return`${o}${t.separator}${s}`;let l=t.floorUnits?.includes(e)?Math.floor(o*10**c)/10**c:o;if(a<i&&Number(l.toFixed(c))>=n)o/=n,a+=1;else return`${l.toFixed(c)}${t.separator}${s}`}}const br=`ai.openclaw.node`,xr=`OpenClaw Node`;function normalizeGatewayProfile(e){let t=e?.trim();return t&&d(t)!=="default"?t:null}function resolveGatewayProfileSuffix(e){let t=normalizeGatewayProfile(e);return t?`-${t}`:``}function resolveNodeLaunchAgentLabel(e){let t=normalizeGatewayProfile(e);return t?`${br}.${t}`:br}function resolveNodeSystemdServiceName(e){return`openclaw-node${resolveGatewayProfileSuffix(e)}`}function resolveNodeWindowsTaskName(e){let t=normalizeGatewayProfile(e);return t?`${xr} (${t})`:xr}function resolveNodeServiceIdentityEnvironment(e={}){let t=e.OPENCLAW_PROFILE;return{OPENCLAW_PROFILE:t,OPENCLAW_LAUNCHD_LABEL:resolveNodeLaunchAgentLabel(t),OPENCLAW_SYSTEMD_UNIT:resolveNodeSystemdServiceName(t),OPENCLAW_WINDOWS_TASK_NAME:resolveNodeWindowsTaskName(t),OPENCLAW_WINDOWS_TASK_HIDDEN_LAUNCHER:`1`,OPENCLAW_TASK_SCRIPT_NAME:`node.cmd`,OPENCLAW_LOG_PREFIX:`node${resolveGatewayProfileSuffix(t)}`,OPENCLAW_SERVICE_MARKER:`openclaw`,OPENCLAW_SERVICE_KIND:`node`}}function sameFileStatFingerprint(e,t){return fr(e,t)&&e.size===t.size}const Sr=`openclaw-sqlite-readonly-v2-`,Cr=`(?:[A-Za-z0-9]{6}|[\\da-f]{8}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{4}-[\\da-f]{12})$`,wr=RegExp(`^openclaw-sqlite-readonly-[1-9]\\d*-${Cr}`,`u`),Tr=RegExp(`^${Sr}${Cr}`,`u`),Er=/^\.fs-safe-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.tmp$/u;function releaseTokens(e){let t=c(e,e=>e());if(t.length)throw AggregateError(t,`SQLite snapshot retirement token release failed`)}const isSqliteSnapshotStagingName=e=>wr.test(e)||Tr.test(e);function acquireSqliteSnapshotToken(e,t){return Xt(e,t,{allowMissing:wr.test(C.basename(e))})}function beginSqliteSnapshotRetirement(e,t={}){let n=[],r=[],release=()=>releaseTokens(n.filter(e=>e!==t.token));if(!S.existsSync(e))return t.token?.(),{bytes:0,payload:r,release,retire:()=>{}};function inspect(i,a,o=``,s=!0){let c=S.lstatSync(i);if(!c.isDirectory()||process.getuid&&c.uid!==process.getuid())throw Error(`Snapshot directory ownership is unknown`);let l=!o&&wr.test(C.basename(i));if(!o&&t.allowLegacy===!1&&!Tr.test(C.basename(i)))throw Error(`Legacy or unrecognized snapshot requires offline operator cleanup`);let u=t.cutoff!==void 0&&l?Math.min(a,Date.now()-864e5):a,d=l?`Legacy snapshot contains activity newer than 24 hours`:`Snapshot contains activity within the reclamation grace period`;if(c.mtimeMs>=u)throw Error(d);l&&s&&t.cutoff!==void 0&&inspect(i,u,o,!1),!o&&s&&n.push(i===e&&t.token?t.token.beginRetirement():acquireSqliteSnapshotToken(i,`reclaim`));let f=0,p=c.mtimeMs;for(let e of S.readdirSync(i,{withFileTypes:!0})){let n=C.join(i,e.name),a=S.lstatSync(n);if(process.getuid&&a.uid!==process.getuid())throw Error(`Snapshot file ownership is unknown`);if(o&&t.cutoff!==void 0||!a.isFile()||!Jt.some(t=>t===e.name)){if(p=Math.max(p,a.mtimeMs),a.isDirectory()){let r=isSqliteSnapshotStagingName(e.name),i=r?``:[o,e.name].filter(Boolean).join(`/`);if(t.cutoff!==void 0&&(!r&&![`openclaw`,`openclaw-state`,`openclaw-state/state`].includes(i)&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(i)||r&&o!==``&&o!==`openclaw`&&!/^openclaw\/sqlite-[a-f0-9]{24}$/u.test(o)))throw Error(`Unrecognized snapshot directory`);let a=inspect(n,u,i,s);f+=a.bytes,p=Math.max(p,a.newest)}else if(t.cutoff===void 0||a.isFile()&&(o===`openclaw-state/state`?/^openclaw\.sqlite(?:-wal|-shm|-journal)?$/u.test(e.name):!o&&(/^(?:first|database\.sqlite(?:\.partial)?(?:-wal|-shm|-journal)?)$/u.test(e.name)||e.name===`schema-discovery-ownership.json`||Er.test(e.name)||/^inspection-result-[\da-f]{8}-[\da-f]{4}-4[\da-f]{3}-[89ab][\da-f]{3}-[\da-f]{12}\.json$/u.test(e.name))))f+=a.size,s&&r.push(n);else throw Error(`Unrecognized snapshot artifact`)}}if(p>=u)throw Error(d);return{bytes:f,newest:p}}try{let{bytes:i}=inspect(e,t.cutoff??1/0);return{bytes:i,payload:r,release,retire:()=>{for(let e of n)e(!0)}}}catch(e){throw release(),e}}const Dr=l(Symbol.for(`openclaw.sqliteSnapshotCleanup`),()=>({directories:/* @__PURE__ */ new Map,activeWork:/* @__PURE__ */ new Map,exitHandlerInstalled:!1,pendingSignalCleanup:void 0,signalCleanup:cleanupSnapshotOperations})),w=Dr.directories,Or=Dr.activeWork;function snapshotDirectory(e){let t=w.get(e);return t||(t={readers:/* @__PURE__ */ new Set},w.set(e,t)),t}function completeSnapshotDirectoryRemoval(e){return w.delete(e),!0}function cleanupSnapshotOperations(){return Dr.pendingSignalCleanup??=(async()=>{let e=w.entries();for(;;){for(;Or.size>0;){for(let e of Or.values())e();await Promise.allSettled(Or.keys())}let t=e.next();if(t.done)break;let[n]=t.value;await removeTempDirectoryAsync(n,e=>emitSnapshotCleanupFailure({cleanupRoot:n,operation:`rm`,code:a(e)}))}})().finally(()=>{Dr.pendingSignalCleanup=void 0}),Dr.pendingSignalCleanup}function retainSnapshotWork(e,t=()=>{}){registerSnapshotCleanup(),Or.set(e,t);let release=()=>Or.delete(e);return e.then(release,release),e}function registerSnapshotTempDirectory(e,t){let n=snapshotDirectory(e);n.release=t??n.release,registerSnapshotCleanup()}function registerSnapshotCleanup(){Dr.exitHandlerInstalled||(Dr.exitHandlerInstalled=!0,ue(()=>{for(let e of Or.values())e();if(Or.size===0)for(let e of w.keys())removeTempDirectory(e)})),pe(Dr.signalCleanup)}function retainSnapshotTempDirectory(e){registerSnapshotTempDirectory(e);let t=snapshotDirectory(e);if(t.retirementStarted)throw new g(`SQLite snapshot retirement has started`);let n=Symbol(`sqlite.snapshot.reader`);return t.readers.add(n),()=>t.readers.delete(n)}const kr={force:!0,maxRetries:3,recursive:!0,retryDelay:20};function emitSnapshotCleanupFailure(e,t){if(t)try{t(e);return}catch{}try{fe({subsystem:`infra/sqlite-snapshot`}).warn({path:e.cleanupRoot,operation:e.operation,errorCode:e.code},`SQLite read-only snapshot cleanup failed. Check directory permissions and available storage before retrying.`)}catch{}}function assertSnapshotReadersRetired(e){if(e?.readers.size)throw new g(`SQLite snapshot still belongs to an active reader`)}function prepareSnapshotRetirement(e,t){if(assertSnapshotReadersRetired(t),t?.releaseRetained)throw new g(`SQLite snapshot requires asynchronous cleanup`);if(!(t?.retired||!t?.release&&!S.existsSync(C.join(e,Jt[0]))))return t&&(t.retirementStarted=!0),beginSqliteSnapshotRetirement(e,{token:t?.release})}function*shrinkSnapshotPayload(e){let t=S.lstatSync(e,{throwIfNoEntry:!1});if(t?.isDirectory())for(let t of S.readdirSync(e))yield*shrinkSnapshotPayload(C.join(e,t));else if(t?.isFile()&&t.nlink>1)S.unlinkSync(e);else if(t?.isFile()&&t.nlink===1&&t.size>64*1024**2){let n=S.openSync(e,S.constants.O_RDWR|S.constants.O_NOFOLLOW);try{for(let e=t.size;e>64*1024**2;)e-=64*1024**2,yield{fd:n,size:e}}finally{S.closeSync(n)}}}async function shrinkSnapshotPayloadAsync(e){for(let{fd:t,size:n}of shrinkSnapshotPayload(e))await retainSnapshotWork(new Promise((e,r)=>{S.ftruncate(t,n,t=>t?r(t):e())}))}function*retireSqliteSnapshotPayload(e){for(let t of e.payload){ve(t);for(let{fd:e,size:n}of shrinkSnapshotPayload(t))S.ftruncateSync(e,n),yield;S.rmSync(t,kr)}e.retire()}function removeTempDirectory(e,t){let n=w.get(e);n&&(n.cleanupFailure=void 0);try{let t=prepareSnapshotRetirement(e,n);try{if(t){for(let e of retireSqliteSnapshotPayload(t));n=snapshotDirectory(e),n.release=void 0,n.retired=!0}else if(!n?.retired)for(let{fd:t,size:n}of shrinkSnapshotPayload(e))S.ftruncateSync(t,n);try{S.rmSync(e,kr)}catch(t){throw ft(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){return registerSnapshotTempDirectory(e),snapshotDirectory(e).cleanupFailure=n,t?.(n),!1}}async function removeTempDirectoryAsync(e,t){let n=w.get(e);if(n?.releaseRetained){let r=await startRemoveTempDirectory(e,t,n).result;return r&&w.delete(e),r}n&&(n.cleanupFailure=void 0);try{let t=prepareSnapshotRetirement(e,n);try{for(let e of t?.payload??[])ve(e),await shrinkSnapshotPayloadAsync(e),await retainSnapshotWork(S.promises.rm(e,kr));t?(t.retire(),n=snapshotDirectory(e),n.release=void 0,n.retired=!0):n?.retired||await shrinkSnapshotPayloadAsync(e);try{await retainSnapshotWork(S.promises.rm(e,kr))}catch(t){throw ft(e,t)}}finally{t?.release()}return completeSnapshotDirectoryRemoval(e)}catch(n){return registerSnapshotTempDirectory(e),snapshotDirectory(e).cleanupFailure=n,t?.(n),!1}}function startRemoveTempDirectory(e,t,n=w.get(e)){if(n?.retiringRetained)return n.retiringRetained;let r,i=Te(()=>{if(!r||i.operation.read().status!==`pending`)return;r.service();let a=r.read();a.status!==`pending`&&(n&&(n.retiringRetained=void 0),a.status===`rejected`?(snapshotDirectory(e).cleanupFailure=a.error,t?.(a.error),i.resolve(!1)):i.resolve(completeSnapshotDirectoryRemoval(e)))});try{if(n&&(n.cleanupFailure=void 0),sealRetainedSnapshotTempDirectory(e),!n?.releaseRetained)throw new g(`SQLite snapshot has no retained cleanup owner`);n.retiringRetained=i.operation,r=n.releaseRetained(),r.result.then(()=>i.operation.service(),()=>i.operation.service()),i.operation.service()}catch(r){snapshotDirectory(e).cleanupFailure=r,n&&(n.retiringRetained=void 0),t?.(r),i.resolve(!1)}return i.operation}function sealRetainedSnapshotTempDirectory(e,t){let n=w.get(e);if(!n?.releaseRetained)throw new g(`SQLite snapshot has no retained cleanup owner`);if(t?.requireRequested&&!n.retirementStarted)throw new g(`SQLite snapshot is still owned; cleanup has not been requested`);let r=[...w].filter(([t])=>ae(e,t));for(let[,e]of r)assertSnapshotReadersRetired(e);for(let[,e]of r)e.retirementStarted=!0;let i=/* @__PURE__ */ new Set([...nt().map(({location:e})=>e),...Fe()]);for(let t of i)ae(e,t)&&ve(t)}function adoptPreparedLocation(e,t,n=!1,r){let i=t??C.dirname(e);registerSnapshotTempDirectory(i);let o=!0,s,c,l=!1,reportFailure=e=>{!n&&!l&&(l=!0,emitSnapshotCleanupFailure({cleanupRoot:i,operation:`rm`,code:a(e)},r))},complete=e=>{if(e)o=!1,w.delete(i);else if(n)throw new g(`SQLite read-only worker snapshot cleanup failed: ${i}`,{cause:w.get(i)?.cleanupFailure});return e},startCleanup=()=>{if(c?.read().status===`pending`)return c;if(!o){let e=Te(()=>{});return e.resolve(complete(!0)),c=e.operation}return c=ye(startRemoveTempDirectory(i,reportFailure),complete)};return{location:e,cleanupRoot:i,cleanup:()=>s||c?.read().status===`pending`?n?complete(!1):!1:complete(!o||removeTempDirectory(i,reportFailure)),cleanupAsync:()=>w.get(i)?.releaseRetained||c?startCleanup().result:s||(o?(s=Promise.resolve().then(()=>removeTempDirectoryAsync(i,reportFailure)).then(complete).finally(()=>{s=void 0}),s):Promise.resolve(complete(!0))),startCleanup}}const Ar=/* @__PURE__ */ new Set([`--no-maglev`,`--maglev`,`--no-concurrent-sparkplug`,`--concurrent-sparkplug`]);function resolveForwardedNodeCompilerArgs(){return process.execArgv.filter(e=>Ar.has(e.replaceAll(`_`,`-`)))}const jr=l(Symbol.for(`openclaw.maintenanceLiveAuthorityReads`),()=>/* @__PURE__ */ new WeakMap);function allowsMaintenanceLiveAuthorityReads(e,t){return hasAdmittedMaintenanceLiveAuthorityReads(e,un(t))}function hasAdmittedMaintenanceLiveAuthorityReads(e,t){for(let n=e;n;n=Mr.parents.get(n))if(jr.get(n)?.has(t))return!0;return!1}function maintenanceOwnerHasSourceCustody(e,t){return e?.ownsSchemaMaintenance?(e.assertReadAdmission(),!allowsMaintenanceLiveAuthorityReads(e,t)):!1}function readCustodiedDrainedSqliteSource(e){if(!maintenanceOwnerHasSourceCustody(getOpenClawDatabaseMaintenanceScope(),e))return;let t=un(e);if(!(S.existsSync(`${t}-journal`)||(S.statSync(`${t}-wal`,{throwIfNoEntry:!1})?.size??0)>0))return S.statSync(t,{bigint:!0})}const Mr=l(Symbol.for(`openclaw.databaseMaintenanceResources`),()=>({current:new x,claims:/* @__PURE__ */ new WeakMap,parents:/* @__PURE__ */ new WeakMap}));function getOpenClawDatabaseMaintenanceScope(){return Mr.current.getStore()?.scope}function isOpenClawDatabaseMaintenanceResourceOwned(e,t){return Mr.claims.get(e)?.scope===t}function getOpenClawDatabaseMaintenanceResourceScope(e){return Mr.claims.get(e)?.scope}function observeOpenClawDatabaseMaintenanceResource(e){if(!e)return;let t=Mr.claims.get(e),n=getOpenClawDatabaseMaintenanceScope();if(!t)return;let r=commonMaintenanceAncestor(t.scope,n);r!==t.scope&&(t.scope.assertAdmission(),t.release(),Mr.claims.delete(e),r&&r.own(e,t.phase,t.close))}function commonMaintenanceAncestor(e,t){let n=/* @__PURE__ */ new Set;for(let t=e;t;t=Mr.parents.get(t))n.add(t);for(let e=t;e;e=Mr.parents.get(e))if(n.has(e))return e}const Nr=new p(Symbol(`sqliteReadOnlyWorkerScope`)),Pr=lr(`openclaw.memory.critical`);function createStateWorkerMemoryPressureSubscription(e,t){let n=!1,onPressure=e=>t(e===!0);return()=>{let t=e();t!==n&&(n=t,t?Pr.subscribe(onPressure):Pr.unsubscribe(onPressure))}}const Fr={"startupMetadata.readCurrent":`retire-after-result`,"startupMetadata.rollbackRecoveryRequired":`retire-after-result`};function sqliteReadOnlyOperationRequiresProcessRetirement(e){return e in Fr}const Ir=/^[a-z0-9][a-z0-9_-]{0,63}$/i,Lr=/[^a-z0-9_-]+/g,Rr=/^-+/,zr=/-+$/;function normalizeAgentId(e){let t=normalizeAgentIdStrict(e);return t.ok?t.value:`main`}function normalizeAgentIdStrict(e){let t=(e??``).trim(),n=t.toLowerCase();if(Ir.test(t))return Ht(n);let r=n.replace(Lr,`-`).replace(Rr,``).replace(zr,``).slice(0,64);return r?Ht(r):Kt(`unrepresentable`)}const Br=`incognito-openclaw-agent.sqlite`;(/* @__PURE__ */ new Map()).keys();const Vr=l(Symbol.for(`openclaw.agentCreationClaim`),()=>new x),Hr=l(Symbol.for(`openclaw.agentCreationClaimResources`),()=>/* @__PURE__ */ new Map);function getActiveAgentCreationClaim(e,t){let n=Vr.getStore();if(n&&n.kind===`host`&&n.isActive()&&n.agentId===normalizeAgentId(e)&&n.statePath===C.resolve(t))return n}function reserveAgentCreationClaimAdmission(e,t,n){let r=getActiveAgentCreationClaim(t.agentId,Lt(t.env??process.env));if(r)return Hr.set(e,r),r.registerClose(async()=>{Hr.get(e)===r&&(await n(),Hr.delete(e))}),()=>{Hr.delete(e)}}const Ur=l(Symbol.for(`openclaw.agentDatabaseExecutionAdmissionClosedError`),()=>class extends Error{});l(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionChangedError`),()=>class extends Error{constructor(){super(`Agent schema admission changed before publication; retry the operation`)}}),l(Symbol.for(`openclaw.agentDatabaseSchemaAdmissionInvalidError`),()=>class extends Error{constructor(){super(`Invalid agent schema admission receipt`)}}),l(Symbol.for(`openclaw.agentDatabaseStartupPublicationError`),()=>class extends Error{constructor(e){super(cn(e),{cause:e})}});const Wr=l(Symbol.for(`openclaw.agentDeletionDatabaseCleanup`),()=>new x);l(Symbol.for(`openclaw.agentDeletionDatabaseCleanupHandles`),()=>/* @__PURE__ */ new Map),l(Symbol.for(`openclaw.agentDeletionDatabaseCleanupExecutions`),()=>/* @__PURE__ */ new Map);function captureAgentDeletionResourceOwner(e){let t=Wr.getStore();if(t?.ownsDatabase&&(e(t)||t.canonicalPath&&e({agentId:t.agentId,path:t.canonicalPath})))return t.assertCurrentHost(),t}const Gr=`STATE_DATABASE_READ_ADMISSION_INVALIDATED`;var StateDatabaseReadAdmissionInvalidatedError=class extends Error{constructor(...e){super(...e),this.code=Gr}};function isStateDatabaseReadAdmissionInvalidatedError(e){return a(e)===Gr}function createOpenClawStateDatabaseAsyncLifecycle(){let e=/* @__PURE__ */ new Set,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=Promise.resolve(),proofFor=()=>{let e=new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT);return new BigInt64Array(e)[0]=-1n,e},generationFor=e=>{let t=new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT);return{integrity:{identity:e,lifetime:{revision:new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT),epoch:0n},revision:t,epoch:0n,proof:proofFor()}}},publishCreatedIdentity=(e,n)=>{Atomics.add(new BigInt64Array(e.generation.integrity.revision),0,1n),Atomics.add(new BigInt64Array(e.generation.integrity.lifetime.revision),0,1n),t.delete(e.identity.key),e.identity=n,e.generation.integrity.identity=n,t.set(n.key,e)},known=e=>n.get(e)??n.get(y({path:e})),bindPath=(e,t)=>{e.paths.add(t),n.has(t)||n.set(t,e)},overlaps=(e,t)=>{if(e.identity.key===t.identity.key)return!0;for(let n of e.paths)if(t.paths.has(n))return!0;return!1},isSealed=e=>{if(r.size===0)return!1;for(let t of r)if(t.record===void 0||overlaps(t.record,e))return!0;return!1},hasCloseCustody=e=>isSealed(e)||i.has(e),assertOpen=e=>{if(isSealed(e))throw new StateDatabaseReadAdmissionInvalidatedError(`OpenClaw state database read admission is closed`)},findPhysicalRecord=e=>{let r=t.get(e.key);if(!r||!e.key.startsWith(`file:`)||hasCloseCustody(r))return r;for(let t of ct(r.paths,e))r.admissions.delete(t),r.paths.delete(t),n.get(t)===r&&n.delete(t);if(r.paths.size>0)return r.paths.has(r.identity.canonicalPath)||(r.identity=e,r.generation.integrity.identity=e),r;invalidate(r),forget(r)},resolve=(e,r)=>{let i=n.get(e);if(i&&(!r||i.identity.key===r.key))return!r&&i.identity.key.startsWith(`path:`)?resolve(e,Ve(e)):i;let a=r??Ve(e),o=findPhysicalRecord(a);return!o&&a.key.startsWith(`file:`)&&(o=[...t.values()].find(e=>{if(!e.identity.key.startsWith(`path:`))return!1;try{return Ve(e.identity.canonicalPath).key===a.key}catch{return!1}}),o&&publishCreatedIdentity(o,a)),o||(o={coordinationKey:a.key,identity:a,paths:/* @__PURE__ */ new Set,generation:generationFor(a),admissions:/* @__PURE__ */ new Map},t.set(a.key,o)),bindPath(o,e),bindPath(o,a.canonicalPath),o},resolveForNative=e=>{let t=y({path:e}),r=n.get(t);if(r)return r;let i=Ie(t);return i?resolve(t,i):void 0},invalidate=e=>{for(let n of e?[e]:t.values())Atomics.store(new BigInt64Array(n.generation.integrity.revision),0,-1n),Atomics.store(new BigInt64Array(n.generation.integrity.lifetime.revision),0,-1n),n.generation=generationFor(n.identity),n.admissions.clear()},seal=e=>{invalidate(e);let t={record:e};return r.add(t),t},release=e=>{e.seal&&=(r.delete(e.seal),void 0)},forget=e=>{if(!hasCloseCustody(e)&&t.get(e.identity.key)===e){t.delete(e.identity.key);for(let r of e.paths)if(n.get(r)===e){n.delete(r);for(let e of t.values())if(e.paths.has(r)){n.set(r,e);break}}}},retireReplacedRecord=e=>{let t=i.get(e);t?(t.superseded=!0,t.seal??=seal(e)):invalidate(e),forget(e)},captureRecord=(e,n)=>{let r=e.admissions.get(n);if(r)return r;let i=e.generation,a=Object.freeze({databasePath:n,coordinationKey:e.coordinationKey,get identity(){return e.identity},captureIntegrity(){a.assertCurrent();let t=i.integrity,n=Atomics.load(new BigInt64Array(t.revision),0),r=Atomics.load(new BigInt64Array(t.lifetime.revision),0);return(n!==t.epoch||r!==t.lifetime.epoch)&&(i.integrity={...t,identity:e.identity,lifetime:{revision:t.lifetime.revision,epoch:r},epoch:n,proof:proofFor()}),i.integrity},assertCurrent(){if(assertOpen(e),t.get(e.identity.key)!==e||e.generation!==i||e.admissions.get(n)!==a)throw new StateDatabaseReadAdmissionInvalidatedError(`OpenClaw state database read admission changed`)}});return e.admissions.set(n,a),a};return{identity(e){return known(e)?.identity??Ie(e)},knownIdentity(e){return known(e)?.identity},integrity(e){let t=resolveForNative(e);return t&&!isSealed(t)?captureRecord(t,y({path:e})).captureIntegrity?.():void 0},publish(e,r){let i=y({path:e}),a=r??Ve(i),o=n.get(i),s=r&&o?.identity.key===a.key?t.get(a.key):findPhysicalRecord(a);return o&&o.identity.key!==a.key&&(o.identity.key.startsWith(`path:`)&&!s?(publishCreatedIdentity(o,a),s=o):retireReplacedRecord(o)),s||=resolve(i,a),bindPath(s,i),bindPath(s,r?s.identity.canonicalPath:a.canonicalPath),{identity:a,admission:captureRecord(s,i)}},async retireChangedAdmission(e){e.assertCurrent();let n=t.get(e.identity.key),r=await Ue(e.databasePath);e.assertCurrent(),n&&n.identity.key!==r.key&&retireReplacedRecord(n)},invalidate(e){if(e===void 0)invalidate();else{let t=known(e);t&&invalidate(t)}},register(t){e.add(t);for(let e of i.values())e.queue?.add(t);return()=>{e.delete(t)}},capture(e,t){let r=n.get(e),i=r?.admissions.get(e);if(r&&i&&r.identity.key.startsWith(`file:`))return i.assertCurrent(),i;let a=y({path:e}),o=resolve(a,t);return assertOpen(o),captureRecord(o,a)},holdExclusion(e){let n=resolve(y({path:e})),i=seal(n);return()=>{r.delete(i);for(let e of t.values())overlaps(n,e)&&forget(e)}},close(n,r){let o=n===void 0?void 0:resolveForNative(n);if(n!==void 0&&!o)return Promise.resolve(r());let s=i.get(o);if(s?.pending)return s.pending;s||(s={retained:/* @__PURE__ */ new Set},i.set(o,s)),s.seal??=seal(o);let c=s,l=a.then(async()=>{let n=/* @__PURE__ */ new Set([...e,...c.retained]);for(let e of i.values())for(let t of e.retained)n.add(t);c.queue=n;let a=[];for(;c.queue.size;){let e=[...c.queue].filter(e=>e.phase!==`after-resources`);if(!e.length&&a.length){for(let e of c.queue)c.retained.add(e);break}let t=e.length?e:[...c.queue];for(let e of t)c.queue.delete(e);await Promise.all(t.map(async e=>{try{let t=o?.identity;t&&e.admission&&t.key!==e.admission.identity.key||await e.close(t),c.retained.delete(e)}catch(t){c.retained.add(e),a.push(t)}}))}a.length&&!c.superseded&&release(c),be(a,`OpenClaw state resource drainage failed`);let s=await r(o?.identity);if(i.delete(o),release(c),o===void 0){for(let[e,t]of i)t.pending||(i.delete(e),release(t));for(let e of t.values())forget(e)}else forget(o);return s}).finally(()=>{c.queue=void 0});return c.pending=l,a=l.then(()=>void 0,()=>void 0),l.catch(()=>{c.pending=void 0}),l}}}const T=l(Symbol.for(`openclaw.agentDatabaseAsyncResources`),()=>({active:/* @__PURE__ */ new Set,closing:/* @__PURE__ */ new Map,selections:/* @__PURE__ */ new Map}));yn(async(e,t)=>{let n=(await Promise.allSettled([.../* @__PURE__ */ new Set([...T.active,...T.closing.keys()])].filter(n=>!t?.has(C.resolve(n.path))&&e.some(e=>Sn(e,n.path))).map(e=>closeAgentDatabaseResource(e)))).flatMap(e=>e.status===`rejected`?[e.reason]:[]);if(n.length>0)throw AggregateError(n,`Agent database resource cleanup failed`)});function matchesAgentDatabaseClose(e,t){return(e.path===void 0||e.path===t.path||t.ownership===`unresolved`&&Sn(t,e.path))&&(e.rootPath===void 0||ae(e.rootPath,t.path)||t.ownership===`unresolved`&&Sn(t,e.rootPath))&&(e.agentId===void 0||t.ownership===`unresolved`||e.agentId===t.agentId)}function registerOpenClawAgentDatabaseReadCandidateResource(e){return registerAgentDatabaseResource({...e,ownership:`unresolved`})}function registerAgentDatabaseResource(e,t){let n={...e,path:C.resolve(e.path)};n.cleanupOwner=captureAgentDeletionResourceOwner(e=>matchesAgentDatabaseClose(e,n)),assertAgentDatabaseResourceAdmission(n);let r=t&&n.ownership===`known`?reserveAgentCreationClaimAdmission(n,t,()=>closeAgentDatabaseResource(n)):void 0,unregister=()=>{T.active.delete(n),r?.(),T.onRelease?.(n)};return getOpenClawDatabaseMaintenanceScope()?.own(unregister,`agent-resources`,()=>closeAgentDatabaseResource(n)),T.active.add(n),unregister}function assertAgentDatabaseResourceAdmission(e){if([...T.selections.keys()].some(t=>matchesAgentDatabaseClose(t,e))||[...T.closing.keys()].some(t=>(t.path===e.path||t.ownership===`unresolved`&&Sn(t,e.path)||e.ownership===`unresolved`&&Sn(e,t.path))&&(t.ownership===`unresolved`||e.ownership===`unresolved`||t.agentId===e.agentId)))throw new Ur(`Agent database resources are closing: ${e.path}`)}function closeAgentDatabaseResource(e,n){if(e.ownership===`known`&&e.closeSync){T.closing.set(e,void 0);try{return e.revoke(),e.closeSync(),T.active.delete(e),T.closing.delete(e),T.onRelease?.(e),Promise.resolve()}catch(r){n&&n(e.path,r);let i=Promise.reject(t(r,`Agent database cleanup failed`));return i.catch(()=>{}),i}}let r=T.closing.get(e);return r||(r=Promise.resolve().then(()=>e.close()),T.closing.set(e,r),r.then(()=>{T.active.delete(e),T.closing.delete(e),T.onRelease?.(e)},()=>{T.closing.set(e,void 0)}).catch(()=>{})),n&&r.catch(t=>n(e.path,t)).catch(()=>{}),e.revoke(),r}function captureSqliteAuthSchema(e,t){if(Be(e)?.key!==t)return;let n=Ye(e,jt,()=>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 isJsonTransferField(e){return n(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 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)}be(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:cr(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=sr(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 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(!n(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(r,i){if(t||!n(i)||i.operation!==e||!(`value`in i))throw Error(`SQLite read-only worker returned a different or duplicate operation`);t={operation:e,value:i.value}},readResult(){if(!t)throw Error(`SQLite read-only worker returned no operation`);return t}})}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,C.resolve(e)];if(t.mode===`task-delivery-recovery`)return[...n,C.resolve(t.recoveryDirectory),C.resolve(t.sourcePath)];let r=t.stagingRoot&&C.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($e(i)))}else r&&n.push(r);return n}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&&n(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&&n(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&&n(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=or(oe(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 Pn(c.message,{cause:e.cause});if(a){let e=new SqliteReadOnlyInspectionContentionError(c.message);throw s?Mn(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)}function isSameSqliteReadOnlyWorkerLaunch(e,t){let n=Object.keys(t.env);return e.runtimeGeneration===t.runtimeGeneration&&e.transport.kind===t.transport.kind&&(e.transport.kind===`native`||t.transport.kind===`broker`&&e.transport.owner===t.transport.owner)&&t.cwd===e.cwd&&n.length===Object.keys(e.env).length&&n.every(n=>t.env[n]===e.env[n])}function createSqliteReadOnlyWorkerSession(e){Ze();let t={...e.env},n=e.cwd,r=process.execPath,i=e.transport.kind===`broker`?{kind:`broker`,owner:e.transport.owner}:{kind:`native`},a={env:t,cwd:n,transport:i,runtimeGeneration:e.runtimeGeneration},o=[...e.argv],s={env:t,...i.kind===`native`&&n===xt()?{}:{cwd:n},stdio:[`ignore`,`pipe`,`pipe`,`ipc`],windowsHide:!0},c=i.kind===`broker`?i.owner.spawn(r,o,s):pr.spawn(r,o,s);Hn(r,c,e.pooledRead?`sqlite.scoped-read.${i.kind}`:`sqlite.session.${i.kind}`);let setIdle=e=>{if(i.kind!==`native`)return;let t=e?`unref`:`ref`;c[t](),c.channel?.[t]?.();for(let e of[c.stdout,c.stderr])e instanceof gr&&e[t]()},l=!1,u=0,d,p=``,ee=0,m,{promise:te,resolve:ne}=Qt(),h=/* @__PURE__ */ new Map,re=te.then(async()=>{i.kind===`broker`&&c instanceof dn&&!c.notStarted&&c.exitCode===null&&c.signalCode===null&&await i.owner.waitForCleanup();for(let e of h.values())e();h.clear()}),retire=e=>{setIdle(!1),l=!0,m&&e!==void 0&&(m.failure??=e),c.kill(`SIGKILL`)},sendMessage=e=>c.send(e,e=>{e&&retire(e)}),releasePending=t=>{if(m=void 0,d=void 0,t.cleanup(),e.pooledRead){for(let e of h.values())e();h.clear()}return t};e.retainLifetime!==!1&&retainSnapshotWork(re,()=>retire(/* @__PURE__ */ Error(`SQLite snapshot owner stopped`)));let ie=!1,ae=!1,se=!1;c.once(`spawn`,()=>{ae=!0}),c.on(`error`,e=>retire(ae?e:Object.assign(Error([[`EACCES`,`ENOENT`,`EPERM`].includes(e.code??``)?`SQLite read-only worker runtime binary not executable: ${r} (${e.code}, cwd ${n}). Check runtime execute permissions and access to the working directory`:`SQLite read-only worker failed to start (executable ${r}, cwd ${n})`,e.message].join(`: `),{cause:e}),{code:e.code,path:e.path})));let finishClose=async(e,t)=>{se=!0,l=!0;let n=m?.failure??createSqliteReadOnlyWorkerError(`exited with ${t?`signal ${t}`:`code ${e}`}`,p),i=await Ne({execPath:r,error:n,stderr:p,signal:t,started:ie}).catch(toStringifiedError);if(m){let e=releasePending(m);e.reject(i??e.failure??n)}ne()};c.once(`close`,(e,t)=>{finishClose(e,t)});let captureOutput=(e,t)=>{ee+=e.length,t&&(p=oe(p+e.toString(`utf8`),-4e3)),ee>1048576&&retire(createSqliteReadOnlyWorkerError(`exceeded its output buffer`,p))},attachOutput=()=>{c.stdout?.on(`data`,e=>captureOutput(e,!1)),c.stderr?.on(`data`,e=>captureOutput(e,!0))},ce=c instanceof dn?c.ready().then(attachOutput).catch(retire):void 0;ce||attachOutput(),c.on(`message`,t=>{if(ie=!0,!l){if(!m||!t||typeof t!=`object`||Object.keys(t).length!==2||!(`id`in t)||t.id!==m.id||!(`result`in t))retire(createSqliteReadOnlyWorkerError(`returned an unexpected response`,p));else try{let e;if(m.transfer&&`type`in t.result){let n=m.transfer.accept(t.result);if(`request`in n){sendMessage({id:m.id,transfer:n.request});return}e=n.value}else e=readSqliteReadOnlyWorkerValue({kind:`launched`,stdout:JSON.stringify(t.result),stderr:p,status:0},m.mode);releasePending(m).resolve(e)}catch(n){if(m&&e.retainOnOperationError&&isSqliteSnapshotStagingMode(m.mode)&&isSqliteReadOnlyWorkerResult(t.result)&&!t.result.ok){releasePending(m).reject(n);return}retire(n)}}});let le={closed:re,isRetired(){return l},get notStarted(){return c instanceof dn?c.notStarted:se&&!ae},createNativeReplacement(){return f(()=>createSqliteReadOnlyWorkerSession({...e,env:t,cwd:n,argv:o,transport:{kind:`native`}}))},compatible(e){return!l&&isSameSqliteReadOnlyWorkerLaunch(a,e)},run(t,n){if(l)return Promise.reject(/* @__PURE__ */ Error(`SQLite read-only worker is closed`));if(n.mode===`auth-profile-rows`&&n.source===`canonical`&&!n.artifactPreserving){let e=C.resolve(t);h.has(e)||h.set(e,registerOpenClawAgentDatabaseReadCandidateResource({path:e,revoke:()=>retire(/* @__PURE__ */ Error(`Auth profile reader owner was revoked`)),close:()=>le.close()}))}return d=new Promise((r,i)=>{p=``,ee=0;let abort=()=>retire(n.signal?.reason),a,o=++u;m={id:o,mode:n.mode,...n.mode===`auth-profile-rows`?{transfer:createSqliteAuthTransferReceiver()}:n.mode===`operation`?{transfer:createSqliteOperationTransferReceiver(n.command.type)}:{},resolve:r,reject:i,cleanup:()=>{clearTimeout(a),n.signal?.removeEventListener(`abort`,abort)}},n.signal?.addEventListener(`abort`,abort,{once:!0}),n.signal?.aborted?abort():(async()=>{try{if(!e.deadlineOwnedByCaller()){let{timeoutMs:n,size:r}=await e.readBudget(t);if(l)return;a=setTimeout(()=>retire(e.timeoutError(t,n,r)),n)}if(ce&&(await ce,l))return;let r={id:o,args:e.requestArgs(t,n),...n.mode===`auth-profile-rows`||n.mode===`operation`?{[n.mode===`operation`?`operation`:`auth`]:{expectedIdentity:n.expectedIdentity,expectedBirthtime:n.expectedBirthtime,artifactPreserving:n.artifactPreserving,...n.mode===`operation`?{command:cr(n.command).toString(`base64`)}:{immutable:n.immutable,retainReader:!e.pooledRead&&n.source===`canonical`&&!n.artifactPreserving,schema:n.source===`canonical`&&!n.artifactPreserving?captureSqliteAuthSchema(t,n.expectedIdentity):void 0}}}:{}};if(n.mode===`operation`&&Buffer.byteLength(JSON.stringify(r))>1048576)throw Error(`SQLite read-only operation exceeded its request buffer`);sendMessage(r)}catch(e){retire(e)}})()})},setIdle,async close(){if(le.setIdle(!1),l){await re;return}l=!0;let t=setTimeout(()=>retire(),e.closeTimeoutMs);try{sendMessage(`close`)}catch(e){retire(e)}try{await re}finally{clearTimeout(t)}}};return e.runtimeGeneration?.retain(le,async()=>(await d?.catch(()=>void 0),()=>le.close())),le}const Kr=me(`state/sqlite`);function trackSqliteRead(e){return Kn(`sqlite_read`,Ae(e.mode===`operation`?e.command.type:e.mode),e.signal)}function createSqliteReadOnlyWorkerPool(e){let t=[],n=/* @__PURE__ */ new WeakMap,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new WeakSet,a=createStateWorkerMemoryPressureSubscription(()=>t.some(e=>e.idleSince!==void 0&&!e.session?.isRetired()),e=>{for(let n of t)n.session&&!n.leased&&!n.quarantined&&n.queued===0&&Un(n.idleSince,e)&&retireIdleSlot(n)}),assertBrokerOpen=e=>{if(e.transport.kind===`broker`&&i.has(e.transport.owner))throw Error(`SQLite read-only worker broker is closing`)};async function closeSlot(e){let t=e.session;try{await t?.close(),e.session=void 0}catch(t){e.quarantined={error:t};for(let e of r)e();throw t}}async function selectScopedReadWorker(e,i){assertBrokerOpen(i);let a=e.mode===`operation`&&(e.command.type===`pageCache.begin`||e.command.type===`pageCache.step`),o=Nr.getStore();if(a){if(!o?.active)throw Error(`Database page-cache warm requires an active read-only worker scope`);let t=n.get(o);if(t){if(!isSameSqliteReadOnlyWorkerLaunch(t.launch,i))throw Error(`Database page-cache warm worker launch changed during its scope`);return t}if(e.command.type===`pageCache.step`)throw Error(`Database page-cache warm is no longer active`)}for(;;){assertBrokerOpen(i),e.signal?.throwIfAborted();let s=t.filter(e=>!e.leased&&!e.quarantined),c=s.find(e=>isSameSqliteReadOnlyWorkerLaunch(e.launch,i));if(!c&&t.length<4&&(c={launch:i,tail:Promise.resolve(),queued:0},t.push(c)),c??=s.find(e=>e.queued===0&&!e.session),c??=s.reduce((e,t)=>!e||t.queued<e.queued?t:e,void 0),c){if(a&&o){let e=c,t={started:!1};e.leased=t,n.set(o,e),o.releaseReadWorker=async()=>{try{t.started&&(await e.tail,await closeSlot(e))}finally{e.leased=void 0,n.delete(o),o.releaseReadWorker=void 0,!e.quarantined&&e.queued===0&&e.session&&!e.session.isRetired()&&(e.session.setIdle(!0),armScopedReadWorkerIdle(e));for(let e of r)e()}}}return c}if(t.every(e=>e.quarantined))throw AggregateError(t.map(e=>e.quarantined?.error),`SQLite read-only worker capacity is held by unconfirmed cleanup`);let l,u=f(()=>new Promise(e=>{l=e}));r.add(l);try{await $t(u,e.signal,e=>e.reason)}finally{r.delete(l)}}}function retireIdleSlot(e){clearTimeout(e.idle),e.idleSince=void 0,a();let t=f(()=>closeSlot(e));return e.tail=t.catch(()=>{Kr.warn(`Idle SQLite read-only worker cleanup failed`)}),t}function armScopedReadWorkerIdle(e){e.launch.transport.kind===`broker`&&i.has(e.launch.transport.owner)?retireIdleSlot(e):(e.idleSince=performance.now(),a(),e.idle=f(()=>setTimeout(()=>{retireIdleSlot(e)},6e4)),e.idle.unref())}return{run:async function(t,n,r,i=trackSqliteRead(n)){let o=n.mode===`operation`&&(n.command.type===`pageCache.begin`||n.command.type===`pageCache.step`),s;try{s=await selectScopedReadWorker(n,r),assertBrokerOpen(r)}catch(e){throw i.completed(),e}clearTimeout(s.idle),s.idleSince=void 0,a(),s.queued++;let c=s.tail,l=f(()=>$t(c,n.signal,e=>e.reason)).then(async()=>{if(n.signal?.throwIfAborted(),s.quarantined)throw s.quarantined.error;if(i.started(),s.leased&&n.mode===`operation`&&n.command.type===`pageCache.begin`&&(s.leased.started=!0),(!isSameSqliteReadOnlyWorkerLaunch(s.launch,r)||s.session?.isRetired())&&await closeSlot(s),n.signal?.throwIfAborted(),s.launch=r,!s.session){s.session=e({...r,pooledRead:!0});let{closed:t}=s.session;f(()=>t.then(a,a))}let c=s.session;c.setIdle(!1);try{let e=await c.run(t,n);return n.signal?.throwIfAborted(),!o&&(n.mode===`operation`&&sqliteReadOnlyOperationRequiresProcessRetirement(n.command.type)||!_e().explicitSqliteCloseReleasesNativeResources)&&await closeSlot(s),e}catch(e){try{await closeSlot(s)}catch(t){throw ke([e,t],`SQLite read and child cleanup failed`,e)}throw e}}).finally(()=>{i.completed(),s.queued--,!s.leased&&!s.quarantined&&s.queued===0&&s.session&&!s.session.isRetired()&&(s.session?.setIdle(!0),armScopedReadWorkerIdle(s))});return s.tail=f(()=>Promise.allSettled([c,l]).then(()=>{})),l},async closeBroker(e){i.add(e);let n=await Promise.allSettled(t.filter(t=>t.launch.transport.kind===`broker`&&t.launch.transport.owner===e&&t.session&&t.queued===0&&!t.leased&&!t.quarantined).map(retireIdleSlot));s(n,`SQLite read-only broker worker cleanup failed`)}}}const qr=3e5,Jr=me(`state/sqlite`);function resolveSqliteInspectionBudget(e,t,n){let r=te(qr+Math.ceil(40*Number(n??0)/33554432)*1e3,qr),i=n===void 0?`unknown size`:formatByteSize(Number(n),{style:`iec`,maxUnit:`giga`,separator:` `,fractionDigits:n<1024n?0:1});return r>qr&&Jr.debug(`SQLite ${e} for ${t}: ${i}, budget ${r/1e3} seconds`),{timeoutMs:r,size:i}}function readSqliteInspectionBudget(e,t,n){let r=n;try{r??=S.statSync(t,{bigint:!0}).size;for(let e of[`-wal`,`-shm`,`-journal`])try{r+=S.statSync(t+e,{bigint:!0}).size}catch(e){if(!yt(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,r)}async function readSqliteInspectionBudgetAsync(e,t,n){let r=n;try{r??=(await S.promises.stat(t,{bigint:!0})).size;for(let e of[`-wal`,`-shm`,`-journal`])try{r+=(await S.promises.stat(t+e,{bigint:!0})).size}catch(e){if(!yt(e,`ENOENT`))throw e}}catch{}return resolveSqliteInspectionBudget(e,t,r)}function sqliteInspectionTimeoutError(e,t,n,r){return/* @__PURE__ */ Error(`SQLite ${e} timed out after ${n/1e3} seconds (budget for ${r}) for ${t}. Stop the Gateway service and other OpenClaw processes using this database, then retry; if already stopped, check storage performance.`)}function isSqliteInspectionDeadlineOwnedByCaller(){return Nr.getStore()?.deadlineOwnedByCaller===!0}function sqliteReadOnlyWorkerArgv(e){let{moduleUrl:t,runtimeGeneration:n}=We(ut(e[0]===`content-version`||e[0]===`file-generation`?`sqliteSourceRevision`:`sqliteReadOnly`));return{runtimeGeneration:n,argv:[...resolveForwardedNodeCompilerArgs(),...on(t),rn,...e]}}function createScopedSqliteReadOnlyWorker(e){let t=ut(`sqliteReadOnly`);return f(()=>createSqliteReadOnlyWorkerSession({...e,argv:[...resolveForwardedNodeCompilerArgs(),...on(je(t,e.runtimeGeneration)),rn,`session`],requestArgs:sqliteReadOnlyWorkerRequestArgs,readBudget:e=>readSqliteInspectionBudgetAsync(`read-only snapshot`,e),deadlineOwnedByCaller:e.retainLifetime===!1?()=>!1:isSqliteInspectionDeadlineOwnedByCaller,timeoutError:(e,t,n)=>sqliteInspectionTimeoutError(`read-only snapshot`,e,t,n),closeTimeoutMs:qr}))}createSqliteReadOnlyWorkerPool(createScopedSqliteReadOnlyWorker);function runSqliteReadOnlyWorkerSync(e,t,n=`sync`,r){Ze();let{timeoutMs:i,size:a}=readSqliteInspectionBudget(`read-only snapshot`,e),o=pr.spawnSync(process.execPath,sqliteReadOnlyWorkerArgv(sqliteReadOnlyWorkerRequestArgs(e,{mode:n,stagingRoot:t,expectedSourceIdentity:r})).argv,{encoding:`utf8`,windowsHide:!0,stdio:`pipe`,env:Re(Wn()),maxBuffer:1048576,timeout:i,killSignal:`SIGKILL`}),s=it({error:o.error,stderr:o.stderr,signal:o.signal,started:!!o.stdout});if(s)throw s;return readSqliteReadOnlyWorkerValue(o.error?{kind:`launch-failed`,error:Error(yt(o.error,`ETIMEDOUT`)?sqliteInspectionTimeoutError(`read-only snapshot`,e,i,a).message:`SQLite read-only worker failed to start for ${e}: ${o.error.message}`,{cause:o.error})}:{kind:`launched`,stdout:o.stdout,stderr:o.stderr,status:o.status,failure:o.status===0?void 0:`exited with ${o.signal?`signal ${o.signal}`:`code ${o.status}`}`},n)}const Yr=l(Symbol.for(`openclaw.quarantineReadCleanupError`),()=>class extends AggregateError{constructor(e,t){super(e,`OpenClaw quarantine reader cleanup failed.`,{cause:e[0]}),this.quarantine=t,this.name=`OpenClawQuarantineReadCleanupError`}}),Xr=l(Symbol.for(`openclaw.stateDatabaseFailurePaths`),()=>/* @__PURE__ */ new WeakMap);function markOpenClawStateDatabaseFailure(e,t){Xr.set(e,t)}function findOpenClawStateDatabaseFailure(e,t){let n=[e],r=/* @__PURE__ */ new Set;for(let e of n)if(e instanceof Error&&!r.has(e)){if(r.add(e),Xr.get(e)===t)return e;n.push(e.cause),e instanceof AggregateError&&n.push(...e.errors)}}var DuplicateAgentError=class extends Error{};const Zr=`openclaw doctor --fix`;var AuthProfileStoreUnreadableError=class extends Error{constructor(e){super(`Auth profile store ${le(e)} is unreadable; run ${Zr}.`),this.databasePath=e,this.code=`AUTH_PROFILE_STORE_UNREADABLE`,this.action=Zr,this.name=`AuthProfileStoreUnreadableError`}},McpOAuthStoreCorruptionError=class extends Error{constructor(e,t,n){super(`MCP OAuth store ${e} is invalid: ${t}`,n),this.name=`McpOAuthStoreCorruptionError`}},SandboxStateOwnerRequiredError=class extends Error{constructor(e){super(`Sandbox workspace preparation cannot run alongside a foreign live owner of the selected state root, or when that ownership cannot be verified. Run this SDK call inside the owning Gateway plugin/runtime, or stop the Gateway through its service owner and wait for any embedded run to finish, then retry offline. Inspect openclaw gateway status; this call does not acquire ownership or route remotely.`,{cause:e}),this.code=`GATEWAY_STATE_OWNER_REQUIRED`,this.name=`SandboxStateOwnerRequiredError`}},WorkspaceAliasRepointedError=class extends Error{constructor(e){super(`workspace path alias points to a different current target: ${e.aliasPath} now resolves to ${e.currentWorkspacePath}, but its stored workspace state belongs to ${e.storedWorkspacePath}. Run \`openclaw doctor --fix\` and confirm the move, or use \`openclaw doctor --fix --force\`.`),this.code=`WORKSPACE_ALIAS_REPOINTED`,this.name=`WorkspaceAliasRepointedError`,this.aliasPath=e.aliasPath,this.storedWorkspacePath=e.storedWorkspacePath,this.currentWorkspacePath=e.currentWorkspacePath}},WorktreeRemovalContentionError=class extends Error{constructor(e,t,n){super(t),this.kind=e,this.blockedByRun=n,this.name=`WorktreeRemovalContentionError`}},WorktreeRemovalLockError=class extends Error{constructor(e,t){super(t),this.kind=e,this.name=`WorktreeRemovalLockError`}},SessionWorktreeSourceChangedError=class extends Error{},SessionWorktreeLifecycleError=class extends Error{constructor(e,t){super(e),this.reason=t}},SessionGoalOperationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SessionGoalOperationError`}},SessionCanonicalKeyMigrationRequiredError=class extends Error{constructor(e){super(`${e}; stop the Gateway and run openclaw doctor --fix`),this.code=`SESSION_CANONICAL_KEY_MIGRATION_REQUIRED`,this.name=`SessionCanonicalKeyMigrationRequiredError`}},SqliteSessionMutationConflictError=class extends Error{constructor(e){super(`SQLite session state changed while preparing ${e}`),this.operationLabel=e,this.name=`SqliteSessionMutationConflictError`}},SqliteTranscriptMutationConflictError=class extends Error{constructor(e){super(`SQLite transcript changed while preparing rewrite for ${e}`),this.sessionId=e,this.name=`SqliteTranscriptMutationConflictError`}},SessionEntryLifecycleUpsertConflictError=class extends Error{constructor(e){super(`SQLite session entry changed before lifecycle upsert for ${e}`),this.sessionKey=e,this.name=`SessionEntryLifecycleUpsertConflictError`}},SessionPendingInputCustodyError=class extends Error{},SessionTranscriptReadFenceError=class extends Error{constructor(e){super(e),this.name=`SessionTranscriptReadFenceError`}},SessionTranscriptWriterClaimReboundError=class extends Error{constructor(e){super(`session writer claim changed before transcript persistence`,{cause:e}),this.name=`SessionTranscriptWriterClaimReboundError`}},ModelAccountConnectAuthorityError=class extends Error{constructor(){super(`This account action requires a current authorized connection; reconnect and try again.`)}},WorkerSessionAlreadyAttachedError=class extends Error{constructor(e,t){super(`Session ${e} is already attached to worker environment ${t}`),this.sessionId=e,this.environmentId=t}},SqliteJsonlReadBudgetExceededError=class extends Error{};const Qr=Symbol.for(`openclaw.stateDatabaseLifecycle`),$r=/* @__PURE__ */ `durable_background_processes.sandbox_persistent_execs.user_profile_identities.user_background_images.local_workspace_projections.local_workspace_manifest_nodes.local_workspace_tree_packs.local_workspace_source_path_sets.update_runs.session_repository_workspaces.github_repository_publication_requests.github_publication_session_lifecycles.skill_library_entries.skill_library_revisions.skill_library_events.skill_library_uploads.github_personal_publication_requests.cron_job_runtime_authorities.cron_run_trigger_state_retirements.execution_identity_contexts.mcp_oauth_pending_authorizations.node_worker_launch_containers.node_worker_launch_boots.node_worker_launch_cleanup.node_worker_launch_process_scopes.node_worker_launches.node_worker_prepared_workspaces.node_worker_turns.operator_approval_execution_identities.operator_approval_standing_grants.operator_approval_standing_grant_generations.web_push_approval_deliveries.execution_decision_facts.execution_owner_lifecycle_bindings.outbound_message_execution_bindings.outbound_message_progress`.split(`.`),ei=[`idx_sandbox_persistent_execs_container`,`idx_sandbox_persistent_execs_container_name`,`idx_sandbox_persistent_execs_source`,`idx_user_profile_identities_profile_id`,`idx_user_profile_identities_authorization`,`idx_update_runs_created`,`idx_update_runs_active`,`idx_github_repository_publication_shared_request`,`idx_github_repository_publication_personal_request`,`idx_github_personal_publication_owner_session`,`idx_github_personal_publication_pending`,`idx_node_worker_launches_terminal_completed`,`idx_node_worker_turns_terminal_completed`,`idx_node_worker_turns_active_owner`,`idx_operator_approval_standing_grants_binding`,`idx_web_push_approval_deliveries_subscription`,`execution_identity_contexts_run_created_idx`,`execution_decision_facts_cursor_id_idx`,`execution_decision_facts_context_occurred_idx`,`execution_decision_facts_run_occurred_idx`,`outbound_message_execution_bindings_execution_event_idx`,`outbound_message_progress_occurred_idx`,`outbound_message_progress_run_occurred_idx`];[...$r],[...ei];const ti=5e3;function walkUpFrom(e,t,n){let r=C.resolve(e);for(let e=0;t.maxDepth===void 0||e<t.maxDepth;e+=1){let e=n(r);if(e!=null)return e;let t=C.dirname(r);if(t===r)break;r=t}return null}function readGitMetadataFile(e,t=1048576){let n=S.openSync(e,S.constants.O_RDONLY|(S.constants.O_NONBLOCK??0));try{let e=S.fstatSync(n);if(!e.isFile()||e.size>t)throw Error(`Git metadata is not a bounded regular file`);let r=ur(n,Math.min(e.size,t));if(r.length!==e.size)throw Error(`Git metadata changed during its read`);return r}finally{S.closeSync(n)}}function readGitDirectoryPointerTarget(e,t=``){let n=readGitMetadataFile(e),r=n.toString(`utf8`).replace(/[\r\n]+$/u,``);if(!hr(n)||!r.startsWith(t)||r.length===t.length||r.includes(`\0`))throw Error(`Git directory pointer is incomplete or malformed`);let i=r.slice(t.length);return C.isAbsolute(i)?i:`${C.dirname(e)}${C.sep}${i}`}function readGitDirectoryPointer(e,t=``){return S.realpathSync.native(readGitDirectoryPointerTarget(e,t))}function resolveGitDirFromMarker(e){let t=C.join(e,`.git`);try{let e=S.statSync(t);return e.isDirectory()?t:e.isFile()?readGitDirectoryPointer(t,`gitdir: `):null}catch{return null}}function resolveGitHeadPath(e,t={}){return walkUpFrom(e,t,e=>{let t=resolveGitDirFromMarker(e);return t?C.join(t,`HEAD`):null})}function readGitMetadataPrefix(e,t=256){let n=S.openSync(e,S.constants.O_RDONLY|(S.constants.O_NONBLOCK??0));try{if(!S.fstatSync(n).isFile())throw Error(`Git metadata is not a regular file`);let e=Buffer.alloc(t),r=dr(n,e,0);return e.subarray(0,r).toString(`utf-8`)}finally{S.closeSync(n)}}function readGitHead(e,t={}){let n=resolveGitHeadPath(e,t);if(!n)return;let r=readGitMetadataFile(n).toString(`utf8`).trim();if(!r.startsWith(`ref:`))return{headPath:n,ref:null,value:r||null};let i=r.replace(/^ref:\s*/i,``).trim(),a=resolveGitRefsBase(n);return{headPath:n,ref:i,value:readGitRefs(a,[i]).get(i)??null,refsBase:a}}function resolveGitRefsBase(e){let t=C.dirname(e),n=C.join(t,`commondir`);try{return readGitDirectoryPointer(n)}catch(e){if(!gt(e)||S.lstatSync(n,{throwIfNoEntry:!1}))throw e}return t}function readGitRefs(e,t){let n=new Map(t.map(e=>[e,null])),r=/* @__PURE__ */ new Set;for(let i of t){let t=resolveRefPath(e,i);if(t)try{n.set(i,readGitMetadataPrefix(t).trim())}catch(e){if(!gt(e))throw e;r.add(i)}}if(r.size===0)return n;try{let t=readGitMetadataFile(C.join(e,`packed-refs`),2**53-1).toString(`utf8`),i=RegExp(`^(?![#^])[^\\S\\r\\n]*(\\S+)[^\\S\\r\\n]+(${[...r].map(bt).join(`|`)})(?=\\s|$)`,`gm`);for(let[,e,a]of t.matchAll(i))r.delete(a)&&n.set(a,e)}catch(e){if(!gt(e))throw e}return n}function resolveRefPath(e,t){if(!t.startsWith(`refs/`)||t.split(/[/]/).includes(`..`))return null;let n=C.resolve(e,t),r=C.relative(e,n);return!r||r.startsWith(`..`)||C.isAbsolute(r)?null:n}const formatCommit=e=>{let t=e?.match(/[0-9a-fA-F]{7,40}/);return t?d(t[0].slice(0,7)):null},ni=new ie(256),resolveCommitSearchDir=e=>{if(e.cwd)return C.resolve(e.cwd);if(e.moduleUrl)try{return C.dirname(ar(e.moduleUrl))}catch{}return process.cwd()},cacheGitCommit=(e,t)=>(ni.set(e,t),t),resolveGitLookupDepth=(e,t)=>{if(!t)return;let n=C.relative(t,e);if(!(n.startsWith(`..`)||C.isAbsolute(n)))return(n?n.split(C.sep).filter(Boolean).length:0)+1},readCommitFromGit=(e,t)=>{let n=readGitHead(e,{maxDepth:resolveGitLookupDepth(e,t)});return n===void 0?void 0:formatCommit(n.value)},readCommitFromPackageJson=()=>{try{let e=qn(import.meta.url)(`../../package.json`);return formatCommit(e.gitHead??e.githead??null)}catch{return null}},readCommitProbe=(e,t,n)=>{try{for(let r of t){let t=ar(new URL(r,e)),a;try{a=readGitMetadataPrefix(t,1024)}catch(e){if(gt(e))continue;return null}try{let e=i(JSON.parse(a))?.[n];return typeof e==`string`?formatCommit(e):null}catch{return null}}}catch{}},readCommitFromBuildInfo=(e=import.meta.url)=>readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)??null,readLoadedCommit=e=>{let t=readCommitProbe(e,[`../.buildstamp`,`./.buildstamp`],`head`),n=readCommitProbe(e,[`../.runtime-postbuildstamp`,`./.runtime-postbuildstamp`],`head`);return t!==void 0||n!==void 0?t||n?t&&t===n?t:null:readCommitFromBuildInfo(e):readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)},resolveCommitHash=(e={})=>{let t=e.env??process.env,n=t.GIT_COMMIT?.trim()||t.GIT_SHA?.trim(),r=formatCommit(n);if(r)return r;let i=resolveCommitSearchDir(e),a=ni.get(i);if(a!==void 0)return a;let o=An({cwd:e.cwd,moduleUrl:e.moduleUrl});try{let e=readCommitFromGit(i,o);if(e!==void 0)return cacheGitCommit(i,e)}catch{}let s=readCommitFromBuildInfo();if(s)return cacheGitCommit(i,s);let c=readCommitFromPackageJson();return c?cacheGitCommit(i,c):cacheGitCommit(i,null)};function resolveLoadedCommitHash(e={}){let t=e.moduleUrl??import.meta.url,n=readLoadedCommit(t);return n===void 0?resolveCommitHash({moduleUrl:t,...e.env?{env:e.env}:{}}):n}const ri=[`../package.json`,`../../package.json`,`../../../package.json`,`./package.json`],ii=[`../build-info.json`,`../../build-info.json`,`./build-info.json`];function readStringFromJsonCandidates(e,t,n,r=!1){try{let i=qn(e);for(let e of t)try{let t=i(e),a=u(t[n]);if(!a||r&&t.name!==`openclaw`)continue;return a}catch{}return null}catch{return null}}function firstNonEmpty(...e){for(let t of e){let e=u(t);if(e&&e.toLowerCase()!==`undefined`&&e.toLowerCase()!==`null`)return e}}function readVersionFromPackageJsonForModuleUrl(e){return readStringFromJsonCandidates(e,ri,`version`,!0)}function readVersionFromBuildInfoForModuleUrl(e){return readStringFromJsonCandidates(e,ii,`version`)}function readBuildProvenanceForModuleUrl(e){try{let t=qn(e);for(let e of ii)try{let n=t(e),r=u(n.buildId);if(r&&r.length<=96){let i={buildId:r};for(let e of[`version`,`commit`,`builtAt`]){let t=u(n[e]);t&&(i[e]=t)}try{i.buildInfoPath=t.resolve(e)}catch{}return i}}catch{}}catch{}return null}function resolveVersionFromModuleUrl(e){return readVersionFromBuildInfoForModuleUrl(e)||readVersionFromPackageJsonForModuleUrl(e)}function resolveBinaryVersion(e){return resolveVersionFromModuleUrl(e.moduleUrl)||firstNonEmpty(e.bundledVersion)||`0.0.0`}readBuildProvenanceForModuleUrl(import.meta.url),resolveLoadedCommitHash({moduleUrl:import.meta.url});const ai=resolveBinaryVersion({moduleUrl:import.meta.url,bundledVersion:process.env.OPENCLAW_BUNDLED_VERSION}),oi={"state-migrations":`state migration`,"newer-schema":`a newer OpenClaw build`,"agent-media":`offline media migration`,"audit-events-v2":`state database schema migration`,"legacy-workshop-review-index":`state database schema migration`,"legacy-cron-run-logs":`cron run history migration`,"legacy-workspace":`workspace setup state migration`,"legacy-session-store":`session store migration`};var StartupMaintenanceRequiredError=class extends Error{constructor(e,t,n){super(t,n),this.kind=e,this.code=`gateway.maintenance_required`,this.name=`StartupMaintenanceRequiredError`}get reason(){return oi[this.kind]}},SqliteSchemaVersionError=class extends StartupMaintenanceRequiredError{constructor(e){super(`newer-schema`,e),this.name=`SqliteSchemaVersionError`}},PluginBlobStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`PluginBlobStoreError`,this.code=t.code,this.operation=t.operation,t.path&&(this.path=t.path)}};function capturePluginStateErrorCause(e,t,n=/* @__PURE__ */ new Set){if(e===void 0)return;let r=t?.(e);if(r)return{canonical:r};if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return{name:`Error`,message:String(e)};if(typeof e!=`object`)return{name:`Error`,message:`Unknown SQLite error cause`};if(n.has(e)||n.size>=8)return{name:`Error`,message:`Additional SQLite error cause omitted`};n.add(e);let i=`name`in e&&typeof e.name==`string`?e.name:`Error`,a=`message`in e&&typeof e.message==`string`?e.message:i,o=`code`in e?e.code:void 0,s=`errcode`in e?e.errcode:void 0,c=`errno`in e?e.errno:void 0;return{name:i,message:a,...typeof o==`string`||typeof o==`number`?{errorCode:o}:{},...typeof s==`number`?{errcode:s}:{},...typeof c==`number`?{errno:c}:{},...`cause`in e?{cause:capturePluginStateErrorCause(e.cause,t,n)}:{},...e instanceof AggregateError?{errors:e.errors.slice(0,8).map(e=>capturePluginStateErrorCause(e,t,n))}:{}}}var PluginStateStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`PluginStateStoreError`,this.code=t.code,this.operation=t.operation,this.owner=t.owner??{pid:process.pid,threadId:Xn,version:ai},t.path&&(this.path=t.path)}toJSON(){return{name:this.name,message:this.message,code:this.code,operation:this.operation,path:this.path,owner:this.owner,cause:capturePluginStateErrorCause(this.cause)}}},SecretStoreValidationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SecretStoreValidationError`}},ModelSelectionLockedError=class extends Error{constructor(e=`Model selection is locked for this session.`){super(e),this.name=`ModelSelectionLockedError`}},SkillUploadRequestError=class extends Error{constructor(...e){super(...e),this.name=`SkillUploadRequestError`}},SkillLibraryError=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.currentRevision=n,this.name=`SkillLibraryError`}},OpenClawAgentDatabaseMediaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(`agent-media`,`OpenClaw agent database ${e} uses schema version ${t}; run openclaw doctor --fix to migrate persisted media before using it.`),this.pathname=e,this.schemaVersion=t,this.name=`OpenClawAgentDatabaseMediaMigrationRequiredError`}},OpenClawStateDatabaseSchemaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(e,`OpenClaw state database schema migration required (${e}) at ${t}; run openclaw doctor --fix to migrate it.`),this.kind=e,this.pathname=t,this.name=`OpenClawStateDatabaseSchemaMigrationRequiredError`}},OpenClawStateLeaseError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`OpenClawStateLeaseError`,this.code=t.code,this.loss=t.loss}},SessionMetadataUnavailableError=class extends Error{constructor(e,t,n=[]){super(`Session metadata unavailable (${[e,...n].join(`: `)}); retry after the agent store is ready.`,t),this.reason=e,this.missingTables=n,this.name=`SessionMetadataUnavailableError`}};const si={"worktree-source-changed":SessionWorktreeSourceChangedError,"model-account-authority":ModelAccountConnectAuthorityError,"duplicate-agent":DuplicateAgentError,"model-selection-locked":ModelSelectionLockedError,"session-canonical-key-migration":SessionCanonicalKeyMigrationRequiredError,"session-pending-input-custody":SessionPendingInputCustodyError,"session-transcript-read-fence":SessionTranscriptReadFenceError,"skill-upload-request":SkillUploadRequestError,"state-database-access":Cn,coordinator:De,ownership:Me,"newer-schema":SqliteSchemaVersionError,"jsonl-read-budget":SqliteJsonlReadBudgetExceededError,"range-error":RangeError,"syntax-error":SyntaxError,"type-error":TypeError};function isMessageOnlyErrorIdentity(e){return typeof e.type==`string`&&Object.hasOwn(si,e.type)}function createError(e){if(isMessageOnlyErrorIdentity(e)){let t=si[e.type];return new t(e.message)}switch(e.type){case`sandbox-state-owner-required`:return new SandboxStateOwnerRequiredError;case`session-worktree-owner-mismatch`:return new SessionWorktreeLifecycleError(e.message,`owner-mismatch`);case`worktree-removal-contention`:return new WorktreeRemovalContentionError(e.kind,e.message,e.blockedByRun);case`worktree-removal-lock`:return new WorktreeRemovalLockError(e.kind,e.message);case`plugin-state`:return new PluginStateStoreError(e.message,{code:e.stateCode,operation:e.operation,path:e.path,owner:e.owner});case`skill-library`:return new SkillLibraryError(e.libraryCode,e.message,e.currentRevision);case`secret-store-validation`:return new SecretStoreValidationError(e.secretCode,e.message);case`worker-session-already-attached`:return new WorkerSessionAlreadyAttachedError(e.sessionId,e.environmentId);case`workspace-alias-repointed`:return new WorkspaceAliasRepointedError(e);case`session-goal-operation`:return new SessionGoalOperationError(e.goalCode,e.message);case`session-lifecycle-upsert-conflict`:return new SessionEntryLifecycleUpsertConflictError(e.sessionKey);case`session-mutation-conflict`:return new SqliteSessionMutationConflictError(e.operationLabel);case`session-transcript-mutation-conflict`:return new SqliteTranscriptMutationConflictError(e.sessionId);case`session-transcript-writer-claim-rebound`:return new SessionTranscriptWriterClaimReboundError(e.refusal);case`session-metadata`:return new SessionMetadataUnavailableError(e.reason,void 0,e.missingTables);case`error`:return Error(e.message);case`mcp-oauth-corruption`:return new McpOAuthStoreCorruptionError(``,``);case`aggregate`:return AggregateError([],e.message);case`auth-profile-store-unreadable`:return new AuthProfileStoreUnreadableError(e.databasePath);case`state-owner-contention`:return new In(e.databasePath);case`state-admission-pending`:return new vn(e.databasePath,e.message);case`state-offline-maintenance`:return new xn(e.databasePath,e.message);case`state-maintenance-scope`:return new _n(``);case`ownership-metadata`:return new mt(e.databasePath,``);case`external-ownership`:return new ht(e.databasePath,e.managerId);case`plugin-blob`:return new PluginBlobStoreError(e.message,{code:e.blobCode,operation:e.operation,...e.path===void 0?{}:{path:e.path}});case`state-lease`:return new OpenClawStateLeaseError(e.message,{code:e.leaseCode,loss:e.leaseLoss});case`maintenance`:return new StartupMaintenanceRequiredError(e.kind,e.message);case`state-migration`:return new OpenClawStateDatabaseSchemaMigrationRequiredError(e.kind,e.pathname)}return new OpenClawAgentDatabaseMediaMigrationRequiredError(e.pathname,e.schemaVersion)}function isNativeErrorCode(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=2147483647}function isWorkerOutcomeCode(e){return e===`outcome-unknown`||e===`unavailable`}function decodeErrorGraph(e,t){try{if(e.version!==1)return;let n=e.nodes;if(t.includeOrdinary!==!0&&!n.some(e=>e.stateDatabasePath!==void 0||e.nativeOpen===!0||e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)||isNativeErrorCode(e.errcode)||at(e)||e.type===`aggregate`&&e.name===`OpenClawQuarantineReadCleanupError`||e.type!==`error`&&e.type!==`aggregate`))return;let r=n.map(e=>{if(e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)){let t=new Le(e.message,e.code);return e.type===`error`?t:ot(createError(e),t)}return createError(e)}),decodeValue=e=>`ref`in e?r[e.ref]:`value`in e?e.value:void 0;for(let[e,t]of n.entries()){let n=r[e];n.name=t.name,n.message=t.message,t.nativeOpen&&Je(n),t.stateDatabasePath!==void 0&&markOpenClawStateDatabaseFailure(n,t.stateDatabasePath);for(let[e,r]of Object.entries({...t.code===void 0?{}:{code:t.code},...t.errcode===void 0?{}:{errcode:t.errcode},...t.errno===void 0?{}:{errno:t.errno},...t.cause?{cause:decodeValue(t.cause)}:{}}))Object.defineProperty(n,e,{value:r,configurable:!0,writable:!0});n instanceof AggregateError&&(n.errors=(t.errors??[]).map(decodeValue))}return{errors:r,root:e.root}}catch{return}}const ci=l(Symbol.for(`openclaw.sharedStateWorkerErrorPayloads`),()=>/* @__PURE__ */ new WeakMap);function retainOpenClawStateWorkerErrorPayload(e,t){t&&ci.set(e,t)}function hydrateOpenClawStateWorkerError(e,t={}){if(!(e instanceof Error))return e;let n=/* @__PURE__ */ new Map,r=[{error:e,finish:!1}],replace=e=>e instanceof Error?n.get(e)??e:e;for(;r.length>0;){let e=r.pop(),{error:i}=e;if(!e.finish){if(n.has(i))continue;n.set(i,i);let e=ci.get(i),a=e===void 0?void 0:decodeErrorGraph(e,t);if(a){n.set(i,a.errors[a.root]);continue}if(r.push({error:i,finish:!0}),i.cause instanceof Error&&r.push({error:i.cause,finish:!1}),i instanceof AggregateError)for(let e of i.errors)e instanceof Error&&r.push({error:e,finish:!1});continue}let a=replace(i.cause),o=i instanceof AggregateError?i.errors:void 0,s=o?.map(replace);if(a===i.cause&&(!s||s.every((e,t)=>e===o?.[t])))continue;let c=i instanceof AggregateError?AggregateError([],i.message):Error(i.message);Object.setPrototypeOf(c,Object.getPrototypeOf(i));let l=Object.getOwnPropertyDescriptors(i);`cause`in i&&(l.cause={configurable:!0,writable:!0,...l.cause,value:a}),s&&(l.errors={configurable:!0,writable:!0,...l.errors,value:s}),Object.defineProperties(c,l),n.set(i,c)}return n.get(e)}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 E=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]})}}),D=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}}),li=freeze({is(e){return e.kind===`CreateIndexNode`},create(e){return freeze({kind:`CreateIndexNode`,name:D.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}}),ui=freeze({is(e){return e.kind===`CreateSchemaNode`},create(e,t){return freeze({kind:`CreateSchemaNode`,schema:D.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),di=[`preserve rows`,`delete rows`,`drop`],O=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})}}),fi=freeze({is(e){return e.kind===`SchemableIdentifierNode`},create(e){return freeze({kind:`SchemableIdentifierNode`,identifier:D.create(e)})},createWithSchema(e,t){return freeze({kind:`SchemableIdentifierNode`,schema:D.create(e),identifier:D.create(t)})}}),pi=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:fi.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),mi=freeze({is(e){return e.kind===`DropSchemaNode`},create(e,t){return freeze({kind:`DropSchemaNode`,schema:D.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),hi=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}}),gi=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),k=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:fi.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:fi.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 _i=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})}}),vi=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),yi=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),bi=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`?vi.create(e.on,n):yi.create(e.on,n)})}}),xi=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:bi.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?bi.cloneWithOperation(e.on,`And`,t):bi.create(t)})}}),Si=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),Ci=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(Ci);const wi=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(wi);const Ti=freeze({"->":!0,"->>":!0}),Ei=Object.keys(Ti),Di=freeze({...Ci,...wi,"||":!0}),Oi=Object.keys(Di),ki=freeze({exists:!0,"not exists":!0});Object.keys(ki);const Ai=freeze({...ki,"-":!0,not:!0}),ji=Object.keys(Ai);[...Oi,...Ei,...ji];const Mi=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&Di[e]}function isJSONOperator(e){return isString(e)&&Ti[e]}function isUnaryOperator(e){return isString(e)&&Ai[e]}const A=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:D.create(e)})}}),Ni=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),Pi=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:Ni.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 j=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})}}),M=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return M.create([e],[])},createWithChild(e){return M.create([``,``],[e])},createWithChildren(e){return M.create(Array(e.length+1).fill(``),e)}}),Fi=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:D.create(e)})}});var Ii=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:j.cloneWith(this.#e.node,{direction:M.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:j.cloneWith(this.#e.node,{direction:M.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:j.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:j.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:j.cloneWith(this.#e.node,{collation:Fi.create(e)})})}toOperationNode(){return this.#e.node}};const Li=/* @__PURE__ */ new Set;function logOnce(e){Li.has(e)||(Li.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(j.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 j.create(e,M.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),j.create(e,t.toOperationNode());let n=j.create(e);return t?t(new Ii({node:n})).toOperationNode():n}const Ri=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})}}),zi=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])})}}),Bi=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 Ri.create(parseStringReference(e),zi.create(Mi.create(t)));if(t===`->$`||t===`->>$`)return Ri.create(parseStringReference(e),Bi.create(Mi.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return Pi.create(A.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 gi.create(parseStringReference(n),D.create(r))}return parseStringReference(e)}function parseColumnName(e){return A.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 Pi.create(A.create(r),k.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return Pi.create(A.create(n),k.create(t))}function trim$2(e){return e.trim()}const Vi=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),Hi=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),N=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):N.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 N.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?Hi.create(e.map(e=>parseValueExpression(e))):Vi.create(e)}const Ui=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)?Si.create(parseReferenceExpression(e),parseBinaryOperator(t),N.createImmediate(n)):Si.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return Si.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`?vi.create:yi.create;if(e.length===0)return Si.create(N.createImmediate(1),Mi.create(`=`),N.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?Ui.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 Mi.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 Wi=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])})}}),Gi=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])})}}),Ki=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Wi.cloneWithItems(e.orderBy,t):Wi.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?Gi.cloneWithItems(e.partitionBy,t):Gi.create(t)})}}),qi=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])})}}),Ji=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])})}}),Yi=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`?vi.create(e.having,n):yi.create(e.having,n)})}}),P=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})}}),Xi=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),Zi=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:Xi.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?qi.cloneWithFroms(e.from,t):qi.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),Qi=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])})}}),$i=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:qi.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>L.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>L.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?Qi.create(t):Qi.cloneWithTables(e.using,t)})}}),F=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`?vi.create(e.where,n):yi.create(e.where,n)})}}),ea=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)})}}),ta=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),na=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),I=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),na.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),ra=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)})}}),L=freeze({is(e){return R.is(e)||P.is(e)||Zi.is(e)||$i.is(e)||I.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?F.cloneWithOperation(e.where,`And`,t):F.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?ea.cloneWithSelections(e.returning,t):ea.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:ta.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?ra.cloneWithSelections(e.output,t):ra.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Wi.cloneWithItems(e.orderBy,t):Wi.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),R=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:qi.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)=>L.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?Ji.cloneWithItems(e.groupBy,t):Ji.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?Yi.cloneWithOperation(e.having,`And`,t):Yi.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=>L.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var ia=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:xi.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:xi.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:xi.cloneWithOn(this.#e.joinNode,M.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const aa=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(aa.create)}var oa=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:Ki.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:L.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:Ki.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const sa=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:Ni.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:Pi.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)?sa.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?sa.create(e.toOperationNode()):sa.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[sa.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return sa.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}const ca=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}}),la=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(A.create)),ca.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=la.create();return Hi.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return Vi.create(r)}const ua=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?[ua.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])=>ua.create(A.create(e),parseValueExpression(t)))}const da=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 z=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?F.cloneWithOperation(e.indexWhere,`And`,t):F.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?F.cloneWithOperation(e.indexWhere,`Or`,t):F.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?F.cloneWithOperation(e.updateWhere,`And`,t):F.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?F.cloneWithOperation(e.updateWhere,`Or`,t):F.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}});var fa=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=A.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:z.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,t]):freeze([t])})})}columns(e){let t=e.map(A.create);return new OnConflictBuilder({...this.#e,onConflictNode:z.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:z.cloneWith(this.#e.onConflictNode,{constraint:D.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:z.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:z.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:z.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:z.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:z.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new pa({...this.#e,onConflictNode:z.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}},pa=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:z.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:z.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:z.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}};const ma=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 ma.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const ha=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}});var ga=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{columns:freeze(e.map(A.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{orAction:ha.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{orAction:ha.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{orAction:ha.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{orAction:ha.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{orAction:ha.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{orAction:ha.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:L.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{onConflict:e(new fa({onConflictNode:z.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:P.cloneWith(this.#e.queryNode,{onDuplicateKey:da.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:L.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:L.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:L.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:L.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}};const _a=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}});var B,DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new B({...this.#e,queryNode:L.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new B({...this.#e,queryNode:L.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new B({...this.#e,queryNode:L.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new B({...this.#e,queryNode:L.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new B({...this.#e,queryNode:$i.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 B({...this.#e,queryNode:L.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new B({...this.#e,queryNode:L.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new B({...this.#e,queryNode:L.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new B({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new B({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new B({...this.#e,queryNode:L.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new B({...this.#e,queryNode:$i.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new B({...this.#e,queryNode:L.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new B({...this.#e,queryNode:L.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new B({...this.#e,queryNode:$i.cloneWithLimit(this.#e.queryNode,_a.create(parseValueExpression(e)))})}modifyEnd(e){return new B({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new B({...this.#e})}$castTo(){return new B(this.#e)}$narrowType(){return new B(this.#e)}$assertType(){return new B(this.#e)}withPlugin(e){return new B({...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 B({...this.#e,queryNode:L.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};B=DeleteQueryBuilder;var UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},V,UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new V({...this.#e,queryNode:L.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new V({...this.#e,queryNode:L.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new V({...this.#e,queryNode:L.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new V({...this.#e,queryNode:L.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new V({...this.#e,queryNode:Zi.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 V({...this.#e,queryNode:L.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new V({...this.#e,queryNode:L.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new V({...this.#e,queryNode:L.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new V({...this.#e,queryNode:Zi.cloneWithLimit(this.#e.queryNode,_a.create(parseValueExpression(e)))})}set(...e){return new V({...this.#e,queryNode:Zi.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new V({...this.#e,queryNode:L.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new V({...this.#e,queryNode:L.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new V({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new V({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new V({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new V({...this.#e,queryNode:L.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new V({...this.#e})}$castTo(){return new V(this.#e)}$narrowType(){return new V(this.#e)}$assertType(){return new V(this.#e)}withPlugin(e){return new V({...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 V({...this.#e,queryNode:L.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};V=UpdateQueryBuilder;const va=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:k.create(e),columns:t?freeze(t.map(A.create)):void 0})}}),ya=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 ba=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:ya.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:ya.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():ya.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new ba({node:ya.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 va.create(n,r)}return va.create(e)}const xa=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])})}}),Sa=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return Sa[~~(Math.random()*Sa.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 Ca={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)&&Ca[e.kind]===!0}const wa=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:D.create(this.#e)}}transformReferences(e,t){let n=super.transformReferences(e,t);return n.table.table.schema?n:{...n,table:k.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=>k.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return wa[e.func]?e[n].map(e=>!k.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&&fi.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&&(xi.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(k.is(e))return this.#s(e.table,t);if(gi.is(e)&&k.is(e.node))return this.#s(e.node.table,t);if(Xi.is(e))for(let n of e.items)this.#o(n,t);else if(Qi.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 Ta=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 na.create(parseFilterList([Ta.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)?M.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 H={};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(H);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==H)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(H)}}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 Ea=freeze([]);var QueryExecutorBase=class{#e;constructor(e=Ea){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(H);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})===H&&(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===H?(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===H&&(d.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),f}finally{c(H),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(H);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===H&&(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===H&&(l=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{s(H),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 Da=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}},Oa=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:L.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new ka({...this.#e,queryNode:I.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:L.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:L.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},ka=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:L.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:I.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:L.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:L.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:L.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:I.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 ka({...this.#e,queryNode:I.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new ka({...this.#e,queryNode:I.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new ka({...this.#e,queryNode:I.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:Da,queryNode:Zi.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new ka({...this.#e,queryNode:I.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new ka({...this.#e,queryNode:I.cloneWithThen(this.#e.queryNode,parseMergeThen(P.cloneWith(P.createWithoutInto(),{columns:t,values:n})))})}},Aa=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:R.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:R.cloneWithSelections(R.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new ga({queryId:createQueryId(),executor:this.#e.executor,queryNode:P.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new ga({queryId:createQueryId(),executor:this.#e.executor,queryNode:P.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:$i.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Zi.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new Oa({queryId:createQueryId(),executor:this.#e.executor,queryNode:I.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?xa.cloneWithExpression(this.#e.withNode,n):xa.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?xa.cloneWithExpression(this.#e.withNode,n):xa.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 Aa({executor:Da})}function createJoinBuilder(e,t){return new ia({joinNode:xi.create(e,parseTableExpression(t))})}function createOverBuilder(){return new oa({overNode:Ki.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 xi.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return xi.create(e,parseTableExpression(t))}const ja=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),Ma=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(Ma.create)}const Na=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=>Na.create(e,parseExpression(t),n))}var U=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new Pa(yi.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new Fa(vi.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 gi.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():D.create(this.#t))}},Pa=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(yi.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return Ui.create(this.#e)}},Fa=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(vi.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return Ui.create(this.#e)}};const Ia=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:N.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 Ia.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var W,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new W({...this.#e,queryNode:L.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new W({...this.#e,queryNode:L.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new W({...this.#e,queryNode:R.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new W({...this.#e,queryNode:R.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new W({...this.#e,queryNode:R.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new W({...this.#e,queryNode:R.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new W({...this.#e,queryNode:R.cloneWithFrontModifier(this.#e.queryNode,_i.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new W({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,_i.createWithExpression(e.toOperationNode()))})}distinct(){return new W({...this.#e,queryNode:R.cloneWithFrontModifier(this.#e.queryNode,_i.create(`Distinct`))})}forUpdate(e){return new W({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,_i.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new W({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,_i.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new W({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,_i.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new W({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,_i.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new W({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,_i.create(`SkipLocked`))})}noWait(){return new W({...this.#e,queryNode:L.cloneWithEndModifier(this.#e.queryNode,_i.create(`NoWait`))})}selectAll(e){return new W({...this.#e,queryNode:R.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 W({...this.#e,queryNode:L.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new W({...this.#e,queryNode:L.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new W({...this.#e,queryNode:R.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new W({...this.#e,queryNode:R.cloneWithLimit(this.#e.queryNode,_a.create(parseValueExpression(e)))})}offset(e){return new W({...this.#e,queryNode:R.cloneWithOffset(this.#e.queryNode,ja.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new W({...this.#e,queryNode:R.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new W({...this.#e,queryNode:L.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new W({...this.#e,queryNode:R.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new W({...this.#e,queryNode:R.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new W({...this.#e,queryNode:R.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new W({...this.#e,queryNode:R.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new W({...this.#e,queryNode:R.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new W({...this.#e,queryNode:R.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new W({...this.#e,queryNode:R.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new W({...this.#e,queryNode:L.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new W({...this.#e,queryNode:R.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new W({...this.#e,queryNode:R.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new W({...this.#e,queryNode:L.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new W({...this.#e,queryNode:R.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new W({...this.#e})}$castTo(){return new W(this.#e)}$narrowType(){return new W(this.#e)}$assertType(){return new W(this.#e)}$asTuple(){return new U(this.toOperationNode())}$asScalar(){return new U(this.toOperationNode())}withPlugin(e){return new W({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile();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 W({...this.#e,queryNode:L.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};W=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 gi.create(this.#e.toOperationNode(),D.create(this.#t))}};const La=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]?Wi.cloneWithItems(e[r],t):Wi.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?F.cloneWithOperation(e.filter,`And`,t):F.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?F.cloneWithOperation(e.filter,`Or`,t):F.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),Ra=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var za=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:La.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:L.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:L.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:La.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:La.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:La.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:La.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 gi.create(this.#e.toOperationNode(),D.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new U(Ra.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new za({aggregateFunctionNode:La.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 za({aggregateFunctionNode:La.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 za({aggregateFunctionNode:La.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new U(Ra.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const Ba=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 Ba.create(Mi.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const G=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),na.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:G.cloneWithWhen(this.#e.node,na.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:G.cloneWithWhen(this.#e.node,na.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:G.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:G.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:G.cloneWithWhen(this.#e.node,na.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:G.cloneWithWhen(this.#e.node,na.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:G.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:G.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new U(G.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new U(G.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new U(G.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new U(G.cloneWith(this.#e.node,{isStatement:!0}))}};const Va=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),Ha=/^#-\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`&&!Ha.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 Ri.is(this.#e)?new Ua(Ri.cloneWithTraversal(this.#e,Bi.is(this.#e.traversal)?Bi.cloneWithLeg(this.#e.traversal,Va.create(e,t)):zi.cloneWithValue(this.#e.traversal,N.createImmediate(t)))):new Ua(Bi.cloneWithLeg(this.#e,Va.create(e,t)))}},Ua=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 gi.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():D.create(this.#t))}};const Wa=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),Ga=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}),Ka=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+\)$/]),qa=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return Ga[e]||Ka.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return qa.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const Ja=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=Da){function binary(e,t,n){return new U(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new U(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:R.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:G.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new U(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(Bi.create())},table(e){return new U(parseTable(e))},val(e){return new U(parseValueExpression(e))},refTuple(...e){return new U(Wa.create(e.map(parseReferenceExpression)))},tuple(...e){return new U(Wa.create(e.map(parseValueExpression)))},lit(e){return new U(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 U(Si.create(parseReferenceExpression(e),Mi.create(`between`),vi.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new U(Si.create(parseReferenceExpression(e),Mi.create(`between symmetric`),vi.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new U(parseFilterList(e,`and`)):new U(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new U(parseFilterList(e,`or`)):new U(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return Ui.is(t)?new U(t):new U(Ui.create(t))},cast(e,t){return new U(Ja.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 gi.create(parseTable(this.#e),D.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 gi.create(parseTable(n),D.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return k.createWithSchema(t,n)}return k.create(e)}function trim$1(e){return e.trim()}const Ya=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}}),K=freeze({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return freeze({kind:`ColumnDefinitionNode`,column:A.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})}}),Xa=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:A.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Za=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:A.create(e),renameTo:A.create(t)})}}),Qa=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?D.create(t):void 0})}}),$a=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys($a);const eo=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)&&$a[e]}function parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():N.createImmediate(e)}const to=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})}}),no=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 ro=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||Ni.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{references:eo.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(K.cloneWith(this.#e,{references:eo.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(K.cloneWith(this.#e,{references:eo.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{defaultTo:no.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{check:Qa.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{generated:to.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{generated:to.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{generated:to.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{generated:to.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(K.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(K.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(K.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}};const io=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}}),ao=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:eo.create(t,n),name:r?D.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var oo=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(ao.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(ao.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(ao.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(ao.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(ao.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(ao.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}};const so=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}}),co=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(A.create)),freeze({kind:`UniqueConstraintNode`,columns:freeze(e),name:t?D.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return freeze({...e,...t})}}),lo=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:D.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),uo=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:A.create(e),[t]:n})}});var AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(uo.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(uo.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(uo.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(uo.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(uo.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)}},fo=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(E.cloneWithTableProps(this.#e.node,{addConstraint:so.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)}},po=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:E.cloneWithTableProps(this.#e.node,{dropConstraint:lo.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:E.cloneWithTableProps(this.#e.node,{dropConstraint:lo.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:E.cloneWithTableProps(this.#e.node,{dropConstraint:lo.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 mo=freeze({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return freeze({kind:`PrimaryKeyConstraintNode`,columns:freeze(e.map(A.create)),name:t?D.create(t):void 0})},cloneWith(e,t){return freeze({...e,...t})}}),ho=freeze({is(e){return e.kind===`AddIndexNode`},create(e){return freeze({kind:`AddIndexNode`,name:D.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}});var go=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:E.cloneWithTableProps(this.#e.node,{addIndex:ho.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:E.cloneWithTableProps(this.#e.node,{addIndex:ho.cloneWithColumns(this.#e.node.addIndex,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})})}columns(e){return new AlterTableAddIndexBuilder({...this.#e,node:E.cloneWithTableProps(this.#e.node,{addIndex:ho.cloneWithColumns(this.#e.node.addIndex,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})})}expression(e){return new AlterTableAddIndexBuilder({...this.#e,node:E.cloneWithTableProps(this.#e.node,{addIndex:ho.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:E.cloneWithTableProps(this.#e.node,{addIndex:ho.cloneWith(this.#e.node.addIndex,{using:M.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)}},_o=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(co.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(co.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(co.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(co.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(co.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},vo=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(mo.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(mo.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(mo.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(mo.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 yo=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:D.create(e),newName:D.create(t)})}});var bo=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:Xa.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:E.cloneWithTableProps(this.#e.node,{renameTo:parseTable(e)})})}setSchema(e){return new AlterTableExecutor({...this.#e,node:E.cloneWithTableProps(this.#e.node,{setSchema:D.create(e)})})}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new xo({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new bo({node:Xa.create(e)}));return new xo({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new xo({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,Za.create(e,t))})}addColumn(e,t,n=noop){let r=n(new ro(K.create(e,parseDataTypeExpression(t))));return new xo({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,Ya.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new ro(K.create(e,parseDataTypeExpression(t))));return new xo({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,io.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new _o(co.create(t.map(e=>isString(e)?A.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:E.cloneWithTableProps(this.#e.node,{addConstraint:so.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Qa.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:E.cloneWithTableProps(this.#e.node,{addConstraint:so.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new oo(ao.create(t.map(A.create),parseTable(n),r.map(A.create),e)));return new fo({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new vo(mo.create(t,e)));return new AlterTableExecutor({...this.#e,node:E.cloneWithTableProps(this.#e.node,{addConstraint:so.create(r.toOperationNode())})})}dropConstraint(e){return new po({...this.#e,node:E.cloneWithTableProps(this.#e.node,{dropConstraint:lo.create(e)})})}renameConstraint(e,t){return new po({...this.#e,node:E.cloneWithTableProps(this.#e.node,{renameConstraint:yo.create(e,t)})})}addIndex(e){return new go({...this.#e,node:E.cloneWithTableProps(this.#e.node,{addIndex:ho.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:E.cloneWithTableProps(this.#e.node,{dropIndex:pi.create(e)})})}$call(e){return e(this)}},xo=class AlterTableColumnAlteringBuilder{#e;constructor(e){this.#e=freeze(e)}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new bo({node:Xa.create(e)}));return new AlterTableColumnAlteringBuilder({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new AlterTableColumnAlteringBuilder({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,Za.create(e,t))})}addColumn(e,t,n=noop){let r=n(new ro(K.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,Ya.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new ro(K.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:E.cloneWithColumnAlteration(this.#e.node,io.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 Hi.create(e.values.map(N.createImmediate))}transformValue(e){return N.createImmediate(e.value)}},So=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:li.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:li.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:li.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:li.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:li.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:li.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:li.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:li.cloneWith(this.#e.node,{using:M.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:L.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)}},Co=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:ui.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(di.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var wo=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder(ho.cloneWith(this.#e,{using:M.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},To=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:O.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:O.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:O.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new ro(K.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:O.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new vo(mo.create(t,e)));return new CreateTableBuilder({...this.#e,node:O.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new _o(co.create(t.map(e=>isString(e)?A.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:O.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new wo(ho.cloneWithColumns(ho.create(e),t.map(e=>isString(e)?A.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:O.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Qa.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:O.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new oo(ao.create(t.map(A.create),parseTable(n),r.map(A.create),e)));return new CreateTableBuilder({...this.#e,node:O.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:O.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:O.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:O.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)}},Eo=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:pi.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:pi.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:pi.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)}},Do=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:mi.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:mi.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)}},Oo=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:hi.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:hi.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:hi.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 ko=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:fi.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)}},Ao=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:ko.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:ko.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:ko.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:ko.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:ko.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:ko.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 jo=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:fi.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var Mo=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:jo.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:jo.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:jo.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 No=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:Hi.create(t.map(N.createImmediate))})}});var Po=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:No.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 Fo=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 Io=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:Fo.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:Fo.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 fi.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return fi.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}const Lo=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:fi.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var Ro=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:Lo.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Lo.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Lo.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 zo=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}}),Bo=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)}},Vo,AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new Vo({...this.#e,node:zo.cloneWith(this.#e.node,{addValue:Bo.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 Vo({...this.#e,node:zo.cloneWith(this.#e.node,{addValue:Bo.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:N.createImmediate(e)})})})}};Vo=AlterTypeAddValueBuilder;const Ho=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:zo.cloneWith(this.#e.node,{addValue:Bo.create(N.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:zo.cloneWith(this.#e.node,{renameTo:D.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:zo.cloneWith(this.#e.node,{renameValue:Ho.create(N.createImmediate(e),N.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:zo.cloneWith(this.#e.node,{setSchema:D.create(e)})})}},Uo=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new To({queryId:createQueryId(),executor:this.#e,node:O.create(parseTable(e))})}dropTable(e){return new Oo({queryId:createQueryId(),executor:this.#e,node:hi.create(parseTable(e))})}createIndex(e){return new So({queryId:createQueryId(),executor:this.#e,node:li.create(e)})}dropIndex(e){return new Eo({queryId:createQueryId(),executor:this.#e,node:pi.create(e)})}createSchema(e){return new Co({queryId:createQueryId(),executor:this.#e,node:ui.create(e)})}dropSchema(e){return new Do({queryId:createQueryId(),executor:this.#e,node:mi.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:E.create(parseTable(e))})}createView(e){return new Ao({queryId:createQueryId(),executor:this.#e,node:ko.create(e)})}refreshMaterializedView(e){return new Ro({queryId:createQueryId(),executor:this.#e,node:Lo.create(e)})}dropView(e){return new Mo({queryId:createQueryId(),executor:this.#e,node:jo.create(e)})}createType(e){return new Po({queryId:createQueryId(),executor:this.#e,node:No.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:zo.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new Io({queryId:createQueryId(),executor:this.#e,node:Fo.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)}}},Wo=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 Go=[`read only`,`read write`],Ko=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function validateTransactionSettings(e){if(e.accessMode&&!Go.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!Ko.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 qo=class Kysely extends Aa{#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 Wo(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 Uo(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:G.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new Yo({...this.#e})}startTransaction(){return new Xo({...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()}},Jo=class Transaction extends qo{#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 qo({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},Yo=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 Qo(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),o=new Jo({...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}})}},Xo=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 Zo({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},Zo=class ControlledTransaction extends Jo{#e;#t;constructor(e){e={...e,executor:new Qo(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 Qo=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)}},$o=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?Da: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 $o(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 gi.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():D.create(this.#t))}};const q=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:M.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:M.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:M.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:M.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:M.create(t,e.map(D.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:M.createWithChild(N.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:M.createWithSql(e)})},join(e,t=q`, `){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:M.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 es=/'/g,ts=/['"]/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&&!Ui.is(this.parentNode)&&!P.is(this.parentNode)&&!O.is(this.parentNode)&&!ko.is(this.parentNode)&&!Na.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&&!Ui.is(this.parentNode)&&!M.is(this.parentNode)&&!na.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&&!Ui.is(this.parentNode)&&!M.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(is[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&&!Ui.is(this.parentNode)&&!M.is(this.parentNode)&&!na.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(ns[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 Mi.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&&O.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(es,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(ts,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?rs[e.modifier]-rs[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const ns=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),rs=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),is=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`}),as=freeze({raw(e,t=[]){return freeze({sql:e,query:M.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 M.createWithChildren([M.createWithSql(`${e} `),D.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(as.raw(`begin`))}async commitTransaction(e){await e.executeQuery(as.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(as.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(!R.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 os=/"/g,ss=/[\\'"]/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(os,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(ss,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const cs=`kysely_migration`,ls=`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`,`!=`,cs).where(`name`,`!=`,ls)),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`,q`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 us=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(as.raw(n))}async commitTransaction(e){await e.executeQuery(as.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(as.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[us]()}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}}[us](){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(as.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`,q`col_description(a.attrelid, a.attnum)`.as(`column_description`),q`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(q`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`,`!=`,cs).where(`c.relname`,`!=`,ls));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 ds=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(ds,`""`)}};const fs=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await q`
with set_timeout as (
select set_config('lock_timeout', '${q.lit(36e5)}', true) as config_val
)
select pg_advisory_lock(${q.lit(fs)})
from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await q`select pg_advisory_unlock(${q.lit(fs)})`.execute(e)}},PostgresDialect=class{#e;constructor(e){this.#e=e}createDriver(){return new PostgresDriver(this.#e)}createQueryCompiler(){return new PostgresQueryCompiler}createAdapter(){return new PostgresAdapter}createIntrospector(e){return new PostgresIntrospector(e)}};const templateFragments=(e,t)=>e,ps=templateFragments`(SELECT value FROM json_each(${0}))`,ms=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!M.is(e)||e.sqlFragments!==ps||e.parameters.length!==1)return;let t=e.parameters[0];for(;M.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!N.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(Mi.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=Vn(process.versions.node),gs=!process.versions.bun&&(hs?.major===24&&Bn(hs,{major:24,minor:20,patch:0})||Bn(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(Xe(e)){let t=vs.get(e);return t||(t=new qo({dialect:ys}),vs.set(e,t)),t}let t=Mt.get(e);if(t)return t;let n=new qo({dialect:_s});return Mt.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{Et.get(e)?.(t)}catch{}}function releaseSqliteIterator(e,n,r,i){let a;try{e.return?.()}catch(e){a=e}if(n.release(),!r&&a!==void 0)throw t(a,i)}function executeCompiledSqliteQuerySync(e,n,r=!1,i=n.parameters){if(Xe(e)){let t=e.query(n.sql,i),a=r?t.rows.slice(0,1):t.rows;return t.columns.length>0?{rows:a}:{rows:[],numAffectedRows:BigInt(t.rowCount)}}try{let a=n.sql;return At(e),kt(e,a,i,a=>{if(r&&R.is(n.query)){let e=a.get(...i);return{rows:e===void 0?[]:[e]}}if(R.is(n.query)||a.columns().length>0){if(gs)return{rows:a.all(...i)};let n=a.iterate(...i),r=tt(e,`kysely eager query`),o=!1,s,c=[];try{for(let e of n)r.progress(),c.push(e)}catch(e){o=!0,s=e}if(releaseSqliteIterator(n,r,o,`SQLite query cleanup failed`),o)throw t(s,`SQLite query failed`);return{rows:c}}a.setReadBigInts(!0);let o;try{o=a.run(...i)}finally{a.setReadBigInts(!1)}let{changes:s,lastInsertRowid:c}=o,l={numAffectedRows:BigInt(s),rows:[]};return P.is(n.query)&&s>0?{...l,insertId:BigInt(c)}:l})}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}}function executeSqliteQuerySync(e,t){return executeCompiledSqliteQuerySync(e,t.compile())}l(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));function safeParseWithSchema(e,t){let n=e.safeParse(t);return n.success?n.data:null}function safeParseJsonWithSchema(e,t){try{return safeParseWithSchema(e,JSON.parse(t))}catch{return null}}function readLockFileOwnerPayload(e){return e?{pid:typeof e.pid==`number`&&Number.isInteger(e.pid)&&e.pid>0?e.pid:void 0,createdAt:typeof e.createdAt==`string`?e.createdAt:void 0,starttime:typeof e.starttime==`number`&&Number.isInteger(e.starttime)&&e.starttime>=0?e.starttime:void 0}:null}function inspectStaleLockOwner(e){let t=readLockFileOwnerPayload(e.payload);if(!t?.pid)return null;if((e.isPidDefinitelyDead??mn)(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??pn)(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 J=v().min(1).max(4096),bs={pid:Vt().int().positive(),startIdentity:J.max(128)},xs=_({...bs,startIdentitySource:b(`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:`)),Ss=Wt([_({platform:Gt([`linux`,`darwin`]),identity:v().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i)}),_({platform:b(`win32`),identity:v().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/)}),_({platform:b(`freebsd`),identity:v().regex(/^[a-f0-9]{32}$/)})]),Cs=_({kind:b(`native`),unit:J,scope:J,placement:Ut(`kind`,[_({kind:b(`pending`)}),_({kind:b(`attached`),invocation:v().regex(/^[a-f0-9]{32}$/i)})])}),ws=b(`original-cancellation-v1`),Ts=_({kind:b(`update`),mutationProtocol:ws}).extend({mutationProtocol:ws.optional(),custody:Gt([`reserved`,`bound`]).optional()}),Es=Ut(`kind`,[Ts,_({kind:b(`triage`),phase:Gt([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:Ut(`kind`,[_({kind:b(`foreground`),boot:Ss}),Cs])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]),Ds=J.refine(C.isAbsolute,`Native source path must be absolute`),Os=v().regex(/^[a-f0-9]{64}$/),ks=_({runId:J,transactionId:J,claimId:J,revision:Vt().int().nonnegative(),recordSha256:Os,serviceKey:Ds,configPaths:zt(Ds).min(1).max(512),lifetimeId:J}),As=_({id:v().uuid(),phase:Gt([`reserved`,`admitted`]),source:ks}),js={executor:xs,helper:xs,action:Es},Ms=_({version:b(2),executor:xs,helper:xs,action:Ts}),Ns=_({key:J,owner:J,payload:v().min(1),updatedAt:Vt().int().nonnegative()}),Ps=_({version:b(4),executor:xs,helper:xs,action:Ts,cancellation:Ns}).refine(e=>{let t=safeParseJsonWithSchema(Ms,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`)}),Fs=_({version:b(2),...js,mutationOriginal:Ns.optional()}).refine(e=>{if(!e.mutationOriginal)return!0;let t=safeParseJsonWithSchema(Ms,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`});Ut(`version`,[Ps,Fs,_({version:b(3),...js,action:_({kind:b(`update`)}),nativeBorrower:As})]),_({version:b(1),...bs});const Is=[`-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=S.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=mr(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?Is: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=Ss.safeParse(r);if(!i.success)throw Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}}const[Ls,Rs,zs]=Ss.options,Bs=v().min(1),Vs=v().regex(/^[a-f0-9]{64}$/u),Hs=Ut(`platform`,[Ls.extend({host:Bs,platform:b(`linux`),pidNsInode:v().min(1)}),Ls.extend({host:Bs,platform:b(`darwin`)}),Rs.extend({host:Bs,identity:Rs.shape.identity.optional()}),zs.extend({host:Bs})]);let Us;function readGatewayLockProcessNamespace(){if(Us?.platform===process.platform&&(Us.value!==null||process.platform!==`linux`&&process.platform!==`android`))return Us.value;try{let e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)(),t=Hs.parse({host:ir.hostname(),...e,...e.platform===`linux`?{pidNsInode:S.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});return Us={platform:process.platform,value:t},t}catch{return Us={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 S.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=Hs.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=Hs.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=Hs.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)&&Ln())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=Vs.safeParse(t.machineIdentity).data,i=st();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 Ws=qt({pid:Vt(),ownerId:v().min(1).optional(),stateOwnerKind:b(`schema`).optional(),cronOwnerProjection:b(`dynamic-default-v1`).optional(),createdAt:v(),startupPhase:b(`starting`).optional(),configPath:v(),port:Vt().int().min(1).max(65535).optional(),role:Gt([`gateway`,`agent-embedded`,`skill-workshop-apply`,`sqlite-maintenance`]).optional(),stateDir:v().optional(),startTime:Vt().optional(),parentPid:Vt().int().positive().optional(),parentStartTime:Vt().optional(),processNamespace:Hs.nullable().optional(),machineIdentity:Vs.nullable().optional()});function parseGatewayLockPayload(e){return safeParseJsonWithSchema(Ws,e)}const Gs=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);function hasRestrictivePermissions(e){try{return!(tr(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(e){let t;try{let n=tr(e).isDirectory()?e:C.dirname(e);t=C.join(n,`.openclaw-chmod-probe-${Zn()}`),rr(t,``,{flag:`wx`,mode:384})}catch{return!1}try{return Qn(t,384),!1}catch(e){return _t(e)&&e.code===`EPERM`}finally{try{nr(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&Gs.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if((tr(e).mode&4095)===t)return{applied:!0};try{return Qn(e,t),{applied:!0}}catch(t){if(!canIgnorePrivateChmodError(e,_t(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:!1,error:t}}}const Ks=`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=S.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let r=C.toNamespacedPath(n),i=[];for(let t=e;;){let{dev:e,ino:n}=S.lstatSync(t,{bigint:!0});if(i.push({path:t,dev:e,ino:n}),C.toNamespacedPath(t)===r)break;let a=C.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=S.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}). ${Ks}`);if(process.platform!==`win32`&&(r.mode&4095)!=448&&(applyPrivateModeSync(e,448),S.lstatSync(e).mode&63))throw Error(`State ownership directory ${e} permissions could not be set to 0700. ${Ks}`)}function removeCreatedProjectionDirectories(e){let t=e[0];for(;t;){try{let e=S.lstatSync(t.path,{bigint:!0});e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino&&S.rmdirSync(t.path)}catch(e){let t=a(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift(),t=e[0]}}function resolveStateOwnerIdentity(e){let t=un(e);return stateOwnerIdentity(t,un(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await ln(e);return stateOwnerIdentity(t,await ln(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:C.join(t,`state.${Nn(e,16)}.lock`),key:process.platform===`win32`?de(e):e}}function stateOwnerDirectory(e){let t=process.getuid?.();return process.platform===`win32`?C.join(ir.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):ce(Rt(e))}function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}const qs=Date.now.bind(Date);function captureLock(e){let t=S.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,n){let i={};for(let t of e)i[t.lockPath]=captureLock(t);let a=Object.keys(i)[0];if(!a)throw Error(`Gateway state ownership requires a held lock`);let o=S.statSync(a,{bigint:!0}),{moduleUrl:s,runtimeGeneration:c}=We(ut(`gatewayStateOwnerHeartbeat`));return f(()=>{let l=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(l,0,BigInt(qs()));let{port1:u,port2:d}=new Jn,f=Ke(s,{workerData:{clock:`epoch`,locks:i,intervalMs:15e3,failureMs:6e4,lastBeat:l.buffer,events:d},transferList:[d],execArgv:an(s)}),p=Qt();f.on(`message`,e=>{e===`closed`&&p.resolve()}),f.unref();let ee=0,m=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of m.values())t.reject(e);m.clear(),u.unref()};u.on(`message`,e=>{if(Se(`lifecycle`,`from_worker`),e===`parent-lost`)tn();else if(e&&typeof e==`object`&&e.type===`lost`)n(/* @__PURE__ */ Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e==`object`&&e.type===`verified`){let t=m.get(e.id);m.delete(e.id),m.size===0&&u.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),u.unref(),f.on(`error`,e=>{let t=/* @__PURE__ */ Error(`${r(e)}; restart Gateway.`);rejectPending(t),n(t)}),f.once(`exit`,()=>{p.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let te,remainingUntilInspection=()=>{let e=Atomics.load(l,0),t=qs()-Number(e);return t<0?0:6e4-t},inspect=()=>{let e=remainingUntilInspection();if(e<=0)throw Error(`Gateway state ownership renewal is overdue at ${a}; retry after storage recovers.`);return e},renewAsync=async()=>{let t=qs(),n=new Date(t);for(let t of e)try{let r=i[t.lockPath];if(r===void 0)throw Error(`owner acquisition bytes were not registered`);let s=await S.promises.open(t.lockPath,`r+`);try{let i=await s.stat({bigint:!0}),c=await S.promises.lstat(t.lockPath,{bigint:!0}),l=Buffer.alloc(Buffer.byteLength(r)+1),{bytesRead:u}=await s.read(l,0,l.length,0),d=await S.promises.lstat(t.lockPath,{bigint:!0});if(te||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(i,c,r,l.subarray(0,u).toString(`utf8`))||!d.isFile()||d.dev!==i.dev||d.ino!==i.ino||t.lockPath===a&&(i.dev!==o.dev||i.ino!==o.ino)){if(t.lockPath!==a)continue;throw Error(`owner lock was removed or replaced`)}await s.utimes(n,n)}finally{await s.close()}}catch(e){if(t.lockPath!==a&&yt(e,`ENOENT`))continue;throw e}!te&&e.size>0&&Atomics.store(l,0,BigInt(t))},ne,h,watch=()=>{let e=remainingUntilInspection();e>0?(ne=setTimeout(watch,e),ne.unref()):h??=renewAsync().then(()=>{h=void 0,te||watch()},e=>{h=void 0,te||n(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${a}: ${r(e)}; restart the Gateway.`))})};watch();let stop=()=>(te||=(clearTimeout(ne),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),u.close(),f.ref(),f.postMessage(`stop`,[]),(async()=>(await En(p.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${nn}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),f.terminate()))()),Promise.all([te,h]).then(()=>void 0));c?.retain(f,async()=>async()=>{await stop()});let assertActive=()=>{if(te||f.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},re=new Set(Object.keys(i));return{worker:f,paths:re,register(e){let t=captureLock(e);i[e.lockPath]=t,f.postMessage([e.lockPath,t],[]),re.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let n=++ee;return new Promise((r,i)=>{m.set(n,{resolve:r,reject:i}),u.ref();try{f.postMessage({type:`verify`,id:n,paths:e},[])}catch(e){m.delete(n),m.size===0&&u.unref(),i(t(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 Js=me(`gateway/state`);function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,Ys.clear(),e.heartbeat?.stop(),Js.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 Ys=l(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),Y=l(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map),Xs=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),Zs=/* @__PURE__ */ new Set([`--tailscale-reset-on-exit`,`--allow-unconfigured`,`--dev`,`--ambient-channels`,`--dev-ambient-channels`,`--reset`,`--update-canary`,`--force`,`--verbose`,`--cli-backend-logs`,`--claude-cli-logs`,`--compact`,`--raw-stream`]);function isForegroundGatewayRunArgv(e){let t=Rn(e,{commandPath:[`gateway`],booleanFlags:[...Zs,`--task-supervisor`],valueFlags:[...Xs,`--task-supervisor-child`],mode:`command-path`});return t?t.length===0||t.length===1&&t[0]===`run`:!1}function 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=It(wt(n),{readOnly:!0});try{let n=getNodeSqliteKysely(r),{rows:i}=executeSqliteQuerySync(r,{compile:()=>q`SELECT expires_at AS expiresAt
FROM ${q`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()-S.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})}const Qs=new x;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,r){let i=n(e)?e:null;if(!i)return!1;let a=classifyGatewayLockProcessNamespace(i,t,r);if(a===`unknown`)throw new GatewayLockNamespaceError(i,t);return comparableStateOwnerStaleReason(i,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.`,o;try{o=S.readFileSync(n,`utf8`)}catch(e){if(a(e)===`ENOENT`)return;throw new Cn(i,{cause:e})}let s=Qs.getStore();if(s?.deadOwner?.path===n&&s.deadOwner.raw===o)return;let c=parseGatewayLockPayload(o);if(!c)throw new vn(t,i);if(!Number.isSafeInteger(c.pid)||c.pid<=0)throw new Cn(i);let l=classifyGatewayLockProcessNamespace(c,n,t),u=comparableStateOwnerStaleReason(c,l);if(u){s&&u===`owner-process-exited`&&(s.deadOwner={path:n,raw:o});return}if(l===`same`&&c.pid===process.pid&&!Yn)return;if(l===`same`&&!gn(c.pid))throw new vn(t,i);let d=c.role??`gateway`;if(d===`gateway`||d===`agent-embedded`)return;if(l===`same`&&c.pid===process.pid){r();return}let f=`OpenClaw state at ${t} is undergoing offline maintenance by ${d} process ${c.pid}, started ${c.createdAt}; retry when it finishes. For update progress, run \`openclaw update status --json\`. ${describeGatewayLockHolder(c,n,l===`same`?`live`:`unknown`)}`;throw c.stateOwnerKind===`schema`&&c.role===`sqlite-maintenance`?new vn(t,f):new xn(t,f)}function defaultPayload(e){let t=Rt(e),n=pn(process.pid),r=en(),i=r===void 0?null:pn(r);return{pid:process.pid,ownerId:Zn(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:C.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?st():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=S.readFileSync(t,`utf8`)}catch(e){if(a(e)===`ENOENT`)return;throw e}let i=parseGatewayLockPayload(r);if(!(isGatewayStateOwnerDefinitelyStale(i)||i?.pid===n.pid)&&!(n.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&zn(process.argv,{command:`gateway`}).kind===`openclaw`))throw new vn(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,t,n,r=0,i){let o=performance.now()+r,s=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,s,n),ensureOwnerDirectory(C.dirname(t),i);let c={holder:null},stale=({payload:n})=>(c.holder=Ws.safeParse(n).data??null,isGatewayStateOwnerDefinitelyStale(c.holder,t,e));if(r>0)try{let n=c.holder=parseGatewayLockPayload(S.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t,e)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&gn(n.pid)))throw new In(e)}catch(e){if(a(e)!==`ENOENT`)throw e}for(let l=!1;;)try{return _r(t,{lockPath:t,retry:r>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:!1}:{retries:0},timeoutMs:Math.max(0,Math.ceil(o-performance.now())),staleMs:1/0,staleRecovery:`remove-if-unchanged`,reentrantOwner:n.ownerId,payload:()=>(assertGatewayRestorationPriority(e,s,n),n),shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(n){let r=a(n);if(r===`ENOENT`&&!l){l=!0,ensureOwnerDirectory(C.dirname(t),i);continue}if(r===`file_lock_timeout`||r===`file_lock_stale`){let{holder:r}=c,i=describeGatewayLockHolder(r??{},t,r&&gn(r.pid)?`live`:`unknown`);throw new In(e,n,i,r?{pid:r.pid,role:r.role}:void 0)}throw n}}const $s=l(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new x);function getStateDatabaseSchemaLease(e){let t=$s.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 leaseForFile(e,t,n,r){let i=!1,holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent(),Ys.clear();let t=new Map($s.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,Ys.clear()};try{let n=$s.run(t,e);return St(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||Y.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw Error(`OpenClaw state maintenance does not own this database`)},run,release(){Ys.clear(),i||(r?.release(),t.release(),i=!0,n.locks.delete(t),r&&n.locks.delete(r),n.locks.size===0&&Y.get(n.key)===n&&(n.heartbeat?.stop(),n.accepting=!1,Y.delete(n.key),n.onReleased?.())),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){Ys.clear();let n=resolveStateOwnerIdentity(e),r=Y.get(n.key),i=r?.path??n.ownerPath;if(r&&(!r.accepting||!hasPhysicalOwnership(r)))throw new In(e,r.lost.signal.reason);r&&assertStateDatabaseAccessAllowed(e);let a=r?.payload??{...defaultPayload(e),stateOwnerKind:`schema`},o,s=[];try{o=acquireGatewayStateOwnerFile(e,i,a,r?0:t.busyTimeoutMs??5e3,s)}catch(t){if(t instanceof In)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof vn)throw e}throw t}let c=r?.projectionPath??C.join(he(Rt(un(e))),`gateway.state.lock`),l;try{l=r?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,c,{...a,role:a.role===`gateway`?`gateway`:`agent-embedded`},0,s)}catch(e){return xe({release(){o.release(),removeCreatedProjectionDirectories(s)}},`state schema projection admission`,()=>{throw e})}r?(r.locks.add(o),r.locks.add(l),r.projectionDirectories.push(...s)):(r={key:n.key,path:i,kind:`schema`,payload:a,projectionPath:c,locks:/* @__PURE__ */ new Set([o,l]),projectionDirectories:s,lost:new AbortController,accepting:!0},Y.set(r.key,r));let u=leaseForFile(i,o,r,l);try{let e=r.heartbeat??=startGatewayStateOwnerHeartbeat(r.locks,(e,t)=>observeOwnerLoss(r,e,t));return u.assertCurrent(),e.register(l),u}catch(e){return xe(u,`state schema ownership verification`,()=>{throw e})}}function assertStateDatabaseReadAllowed(e,t){assertStateDatabaseReadAtOwnerPath(e,t)}function assertStateDatabaseReadAtOwnerPath(e,t,n){if(Y.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}let r=C.resolve(e);if(Ys.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=Y.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.`);Ys.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=Y.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||Y.get(e.key)!==r)throw kn()}}:void 0,prepareAccess:async r=>{let i=t??Y.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&&Y.get(e.key)!==i)throw kn();assertStateDatabaseReadAtOwnerPath(n,t,e)};let o=i.heartbeat,s=i.locks.values().next().value,c=i.getProjection?.();if(!o||!s)throw kn();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),o.assertActive(),Y.get(e.key)!==i||i.heartbeat!==o)throw kn();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(s)||i.getProjection?.()!==c)throw kn()};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 Ys.set(C.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:getOpenClawDatabaseMaintenanceScope();if(!r)throw new _n(e);r.assertDatabaseAccess(e)},r=Y.get(t.key);if(r){if(!hasPhysicalOwnership(r))throw r.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);let t=r.payload.role??`gateway`;(!r.accepting||t!==`gateway`&&t!==`agent-embedded`)&&assertMaintenance()}else assertPersistedStateDatabaseAccessAllowed({databasePath:e,ownerPath:t.ownerPath,assertMaintenance})}function sqliteSnapshotSourceFileSize(e){try{let t=S.statSync(e);return t.isFile()?t.size:0}catch(e){if(yt(e,`ENOENT`))return 0;throw e}}function sqliteSnapshotStagingError(e,t,n=!1,r){Pe(t,`snapshot`);let i=n,a=!1,o=!1,s;for(let n=0,r=t;n<8&&r instanceof Error;n+=1){o||=r instanceof AggregateError||r instanceof g;let{errcode:t,path:n}=r;a||=On(r),(a||typeof t==`number`&&[13,778,1034,1290].includes(t)||`${n??``}${C.sep}`.startsWith(`${e}${C.sep}`))&&(i=!0,typeof t==`number`&&(s=t)),r=r.cause}if(!i)return t;let c=a?`free disk space/quota`:`check filesystem health and write permissions`,l=``;if(a&&r)try{let t=sqliteSnapshotSourceFileSize(r)+sqliteSnapshotSourceFileSize(`${r}-wal`)+sqliteSnapshotSourceFileSize(`${r}-journal`),n=Tn(e)?.availableBytes,i=S.existsSync(`${r}-wal`)&&S.existsSync(`${r}-shm`);l=`; estimated ${t} bytes needed; ${n===void 0?`available bytes unknown`:`${n} bytes available`}; source ${i?`has live WAL sidecars`:`has no live WAL sidecars`}`}catch{}let u=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`,d=`${t instanceof Error?t.message:String(t)}${s===void 0?``:` (SQLite errcode=${s})`}; snapshot staging root ${n?e:C.dirname(e)}${l}: ${c} or set ${u} to a writable filesystem`,f=a&&!o&<(t)!==`source`?new Pn(d,{cause:t}):Error(d,{cause:t});return wn(t)?Mn(f):f}function createSqliteSnapshotStagingDirectorySync(e=jn(),t=!1){let n=createSqliteSnapshotStagingTokenSync(e,t);return registerSnapshotTempDirectory(n.directory,n.release),n.directory}function createSqliteSnapshotStagingTokenSync(e=jn(),t=!1){let n;try{try{n=Fn(e,t?`openclaw-sqlite-readonly-${process.pid}-`:Sr)}catch(t){throw sqliteSnapshotStagingError(e,t,!0)}return{directory:n,release:acquireSqliteSnapshotToken(n,`create`)}}catch(e){throw n&&removeTempDirectory(n),e}}Buffer.from([217,213,5,249,32,161,99,215]),l(Symbol.for(`openclaw.sqliteSnapshotFlights`),()=>({unscoped:/* @__PURE__ */ new Map,scoped:/* @__PURE__ */ new WeakMap}));const ec=l(Symbol.for(`openclaw.sqliteLiveSnapshotOwners`),()=>/* @__PURE__ */ new Map);function registerLiveSqliteSnapshotOwner(e){let t=Ve(e.databasePath),n={assertCurrent:e.assertCurrent,database:e.database};return ec.set(t.key,n),()=>{ec.get(t.key)===n&&ec.delete(t.key)}}function fingerprint(e){return[e.dev,e.ino,e.birthtimeNs,e.ctimeNs,e.mtimeNs,e.size].join(`:`)}function walFingerprint(e){return[e.dev,e.ino,e.mtimeNs,e.size].join(`:`)}function readFile$2(e){let t=S.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(S.lstatSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=readFile$2(e),r=readFile$2(`${e}-wal`);return n?{root:t,main:fingerprint(n),wal:r&&r.size>32n?walFingerprint(r):null}:void 0}const tc=l(Symbol.for(`openclaw.sqliteReusableSnapshots`),()=>/* @__PURE__ */ new Map),nc=l(Symbol.for(`openclaw.sqliteReusableSnapshotScopes`),()=>({depth:0,retiring:/* @__PURE__ */ new Set}));function completed(e){let t=Te(()=>{});return t.resolve(e),t.operation}function readSource(e){try{let t=S.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!t?.isFile()||S.statSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=S.statSync(`${e}-wal`,{bigint:!0,throwIfNoEntry:!1}),r=n&&n.size>0n?n:void 0;return{fingerprint:[`${t.dev}:${t.ino}:${t.size}:${t.mtimeNs}:${t.ctimeNs}`,r?`${r.dev}:${r.ino}:${r.size}:${r.mtimeNs}`:`none`].join(`|`),main:t,newestMs:Math.max(Number(t.mtimeMs),Number(r?.mtimeMs??0)),quiescentMs:[t,r].some(e=>e&&e.mtimeNs%1000000000n==0n)?2e3:50}}catch{return}}function canonicalKey(e){try{return S.realpathSync.native(e)}catch{return}}function retire(e,t){tc.get(e)===t&&tc.delete(e),t.retired=!0,t.leases===0&&settleRetirement(t.retire)}function settleRetirement(e){let t=new Promise(t=>{t(e())}).catch(reportRetirementFailure).finally(()=>nc.retiring.delete(t));nc.retiring.add(t)}function reportRetirementFailure(e){fe({subsystem:`infra/sqlite-snapshot`}).warn({error:String(e)},`Retiring a reusable SQLite snapshot failed.`)}function lend(e,t){t.leases+=1;let n=!1,release=()=>(n||(n=!0,--t.leases,t.leases===0&&t.retired&&retire(e,t)),!0);return{location:t.location,cleanupRoot:t.cleanupRoot,privateFamily:t.privateFamily,cleanup:release,cleanupAsync:async()=>release(),startCleanup:()=>completed(release())}}function leaseReusableSqliteSnapshot(e,t,n={}){let r=canonicalKey(e),i=r?tc.get(r):void 0;if(r&&i){if(readSource(r)?.fingerprint!==i.fingerprint||!S.existsSync(i.location))retire(r,i);else if(!i.logicalOnly||n.logicalReader){if(t)try{qe(i.main,t)}catch{return}return lend(r,i)}}}function captureReusableSqliteSource(e){let t=nc.depth>0?canonicalKey(e):void 0,n=t?readSource(t):void 0;return n&&Date.now()-n.newestMs>=n.quiescentMs?n:void 0}function captureFamily(e){try{return captureSqlitePrivateSnapshotFamily(e.location,e.cleanupRoot??C.dirname(e.location))}catch{return}}l(Symbol.for(`openclaw.sqliteReusableSnapshotSources`),()=>/* @__PURE__ */ new Map);function publishReusableSqliteSnapshot(e,t,n,r,i={}){let a=canonicalKey(e)??C.resolve(e),o=tc.get(a);if(o?.location===n.location&&o.fingerprint===t.fingerprint)return settleRetirement(r),lend(a,o);o&&retire(a,o);let s={...t,logicalOnly:i.logicalOnly===!0,location:n.location,cleanupRoot:n.cleanupRoot,privateFamily:n.privateFamily??captureFamily(n),leases:0,retired:!1,retire:r};return tc.set(a,s),lend(a,s)}const rc=[``,`-wal`,`-shm`,`-journal`];rc.slice(1),Buffer.from([0,5,22,7]),me(`state/sqlite`);function resolveSqliteDatabaseFilePaths(e){return rc.map(t=>`${e}${t}`)}function buildUpdateRehearsalPathEnv(e){return{HOME:e,USERPROFILE:e,TMPDIR:e,TMP:e,TEMP:e,XDG_CONFIG_HOME:C.join(e,`config`),XDG_CACHE_HOME:C.join(e,`cache`),XDG_DATA_HOME:C.join(e,`data`),XDG_STATE_HOME:C.join(e,`state`),OPENCLAW_HOME:e,OPENCLAW_STATE_DIR:e,OPENCLAW_CONFIG_PATH:C.join(e,`openclaw.json`),OPENCLAW_WORKSPACE_DIR:C.join(e,`workspace`),OPENCLAW_SKIP_CHANNELS:`1`,OPENCLAW_SKIP_PROVIDERS:`1`,OPENCLAW_SKIP_CRON:`1`,OPENCLAW_SKIP_GMAIL_WATCHER:`1`,OPENCLAW_SKIP_CANVAS_HOST:`1`,OPENCLAW_SKIP_BROWSER_CONTROL_SERVER:`1`,OPENCLAW_SKIP_STARTUP_MODEL_PREWARM:`1`,OPENCLAW_NO_AUTO_UPDATE:`1`,NODE_DISABLE_COMPILE_CACHE:`1`}}function resolveUpdateRehearsalRoot(e){let t=e.OPENCLAW_STATE_DIR;if(t&&C.isAbsolute(t)&&[`0`,`1`].includes(e.OPENCLAW_UPDATE_IN_PROGRESS??``)&&!Object.entries(buildUpdateRehearsalPathEnv(t)).some(([t,n])=>e[t]!==n)&&e.OPENCLAW_SERVICE_REPAIR_POLICY===`external`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_SERVICE_REPAIR===`0`&&e.OPENCLAW_UPDATE_PARENT_ALLOWS_GATEWAY_ACTIVATION===`0`&&!e.OPENCLAW_COMPATIBILITY_HOST_VERSION)return C.resolve(t)}function isUpdateRehearsalReadOnlyPath(e,t){let n=resolveUpdateRehearsalRoot(t);if(!n)return!1;let r=C.resolve(e);return!ae(n,r)||!ae(un(n),un(r))}function isUpdateRehearsalPrivateDatabase(e,t){return resolveUpdateRehearsalRoot(t)!==void 0&&resolveSqliteDatabaseFilePaths(e).every(e=>!isUpdateRehearsalReadOnlyPath(e,t))}function findArtifactSnapshot(e,t){let n=e.snapshots.get(t.canonicalPath);if(n&&(n.sourceIdentity.key!==t.key||n.sourceIdentity.birthtime!==t.birthtime))throw Error(`SQLite database file identity changed during inspection`);return n}function retainArtifactSnapshot(e,t,n){let r=retainSnapshotTempDirectory(t.cleanupRoot??C.dirname(t.location));e.privateRoots.add(t.cleanupRoot??C.dirname(t.location));let i={...t,sourceIdentity:n,cleanup:()=>(r(),t.cleanup()),cleanupAsync:()=>(r(),t.cleanupAsync())};return e.snapshots.set(n.canonicalPath,i),i}function assertCustodiedSourceUnchanged(e,t){let n=S.statSync(e,{bigint:!0,throwIfNoEntry:!1});if(!n||n.ino!==t.ino||n.size!==t.size||n.mtimeNs!==t.mtimeNs||readCustodiedDrainedSqliteSource(e)===void 0)throw Error(`SQLite source changed during in-place inspection: ${e}`)}function openSqliteReadOnlyDatabase(e,t={}){let n=Ot.getStore();if(!n||!Nt(`agent`,e))return It(e,{...t,readOnly:!0});let r=Ve(e),i=findArtifactSnapshot(n,r),a=i?void 0:readCustodiedDrainedSqliteSource(r.canonicalPath);i||a||isUpdateRehearsalPrivateDatabase(e,process.env)||(i=retainArtifactSnapshot(n,prepareSqliteReadOnlyLocationSync(e),r));let o=i?retainSnapshotTempDirectory(i.cleanupRoot??C.dirname(i.location)):void 0,s={},close=()=>{s.close?.(),o?.(),n.readers.delete(close)};n.readers.add(close);let c=i?.location??(a?Pt(r.canonicalPath):e),l=It(c,{...t,readOnly:!0}),u=l.close.bind(l);return s.close=()=>{l.isOpen&&(u(),a&&assertCustodiedSourceUnchanged(r.canonicalPath,a))},l.close=close,l}function prepareSqliteReadOnlyLocationSync(e,t,n={}){let i=n.reuse?leaseReusableSqliteSnapshot(e,t):void 0;if(i)return i;let a=n.reuse?captureReusableSqliteSource(e):void 0,o=createSqliteSnapshotStagingDirectorySync();try{let n=adoptPreparedLocation(runSqliteReadOnlyWorkerSync(e,o,`sync`,t),o);return a?publishReusableSqliteSnapshot(e,a,n,()=>n.cleanup()):n}catch(e){throw removeTempDirectory(o)?e:new g(`${r(e)}; SQLite snapshot cleanup failed: ${o}`,{cause:e})}}lr(`openclaw.database.statement`),lr(`openclaw.database.request`),me(`sqlite/transaction`);const ic=l(Symbol.for(`openclaw.sqliteWriteAdmissionServices`),()=>/* @__PURE__ */ new Map);function retainSqliteWriteAdmissionService(e,t){let n=[...new Set(e.map(ze))].map(e=>{let n=ic.get(e)??/* @__PURE__ */ new Set,retained=()=>t();return n.add(retained),ic.set(e,n),{location:e,services:n,retained}});return()=>{for(let{location:e,services:t,retained:r}of n)t.delete(r),t.size===0&&ic.get(e)===t&&ic.delete(e)}}function createSqliteTerminalOpenLatch(e){let t=/* @__PURE__ */ new Map;return{peek:e=>t.get(C.resolve(e)),get:e=>t.get(C.resolve(e)),record:(n,r)=>{let i=C.resolve(n);o(r),t.set(i,r),e.closeByPath(i,r)},clear:e=>{t.delete(C.resolve(e))},clearAll:e=>{for(let n of t.keys())(e===void 0||ae(e,n))&&t.delete(n)}}}function sameFileFingerprint(e,t){return e.dev===t.dev&&e.ino===t.ino&&sameFileStatFingerprint(e,t)&&e.sha256===t.sha256}function sameOptionalFileFingerprint(e,t){return e===void 0?t===void 0:t!==void 0&&sameFileFingerprint(e,t)}function sameSqliteFileGeneration(e,t){return sameFileFingerprint(e.database,t.database)&&sameOptionalFileFingerprint(e.journal,t.journal)&&sameOptionalFileFingerprint(e.wal?.size===0n?void 0:e.wal,t.wal?.size===0n?void 0:t.wal)}function parseFileFingerprint(e){if(!n(e))throw Error(`SQLite file fingerprint must be an object`);for(let t of[`birthtimeNs`,`ctimeNs`,`dev`,`ino`,`mtimeNs`,`size`])if(typeof e[t]!=`string`||!/^-?\d+$/u.test(e[t]))throw Error(`SQLite file fingerprint ${t} is invalid`);if(typeof e.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(e.sha256))throw Error(`SQLite file fingerprint sha256 is invalid`);return{birthtimeNs:BigInt(e.birthtimeNs),ctimeNs:BigInt(e.ctimeNs),dev:BigInt(e.dev),ino:BigInt(e.ino),mtimeNs:BigInt(e.mtimeNs),sha256:e.sha256,size:BigInt(e.size)}}function parseSqliteFileGeneration(e){let t=JSON.parse(e);if(!n(t))throw Error(`SQLite file generation must be an object`);return{database:parseFileFingerprint(t.database),...t.journal===void 0?{}:{journal:parseFileFingerprint(t.journal)},...t.wal===void 0?{}:{wal:parseFileFingerprint(t.wal)}}}function readSqliteFileGenerationSync(e){return parseSqliteFileGeneration(runSqliteReadOnlyWorkerSync(e,void 0,`file-generation`))}const ac={name:`openclaw.quarantine.schema`,lifetime:`process`,schemaDependent:!0,read(e){if(typeof e==`object`&&e&&`version`in e&&typeof e.version==`number`)return{version:e.version}}};function quarantineDecisionAdmission(e){return{name:`openclaw.quarantine.decision:${C.resolve(e)}`,lifetime:`process`,read:e=>e===null||isQuarantineDecision(e)?e:void 0}}function isQuarantineDecision(e){return n(e)&&(e.kind===`agent`||e.kind===`state`)&&typeof e.reason==`string`&&typeof e.quarantinedAt==`number`&&(e.verifiedGenerationJson===null||typeof e.verifiedGenerationJson==`string`)}function readQuarantineSchemaVersion(e,t,n=!1){let r=n?void 0:He(e,ac);if(r)return r.version;let i=e.prepare(`PRAGMA user_version`).get()?.user_version;if(typeof i!=`number`||!Number.isInteger(i))throw Error(`OpenClaw quarantine store ${t} has an invalid schema version.`);if(i>2)throw Error(`OpenClaw quarantine store ${t} uses newer schema version ${i}.`);return i!==0&&Oe(e,ac,{version:i}),i}function readOpenClawDatabaseQuarantine(e,t={}){let n=Ft(t.env??process.env);t.refreshIdentity&&Ee(n);let load=()=>readPersistedQuarantineDecision(e,n,t.fresh)??null,r=t.fresh?load():Ye(n,quarantineDecisionAdmission(e),load);return r?resolveQuarantineDecision(r,e,n):void 0}function readPersistedQuarantineDecision(e,t,n=!1){if(!$n(t))return;let r=openSqliteReadOnlyDatabase(t,{timeout:5e3}),i;try{i={value:readQuarantineDecision(r,e,t,n)}}catch(e){i={error:e}}try{r.close()}catch(n){let r,a=`error`in i?i.error:void 0;if(`value`in i&&i.value)try{r=resolveQuarantineDecision(i.value,e,t)}catch(e){a=e}throw new Yr(a===void 0?[n]:[a,n],r)}if(`error`in i)throw i.error;return i.value}function readQuarantineDecision(e,t,n,r=!1){let i=readQuarantineSchemaVersion(e,n,r);if(i===0)return;let a=i>=2?`, verified_generation`:``,o=e.prepare(`SELECT kind, reason, quarantined_at${a} FROM quarantined_databases WHERE path = ? LIMIT 1`).get(C.resolve(t));if(!o)return;let s=i>=2?o.verified_generation:void 0;if(o.kind!==`agent`&&o.kind!==`state`||typeof o.reason!=`string`||typeof o.quarantined_at!=`number`||!Number.isInteger(o.quarantined_at)||s!=null&&typeof s!=`string`)throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`);return{kind:o.kind,quarantinedAt:o.quarantined_at,reason:o.reason,verifiedGenerationJson:typeof s==`string`?s:null}}function resolveQuarantineDecision(e,t,n){if(e.verifiedGenerationJson!==null){let r;try{r=parseSqliteFileGeneration(e.verifiedGenerationJson)}catch{throw Error(`OpenClaw quarantine store ${n} contains an invalid row.`)}try{let e=readSqliteFileGenerationSync(C.resolve(t));if(!sameSqliteFileGeneration(r,e))return}catch{return}}return{kind:e.kind,quarantinedAt:e.quarantinedAt,reason:e.reason}}function readOpenClawDatabaseQuarantineFailure(e,t,n={}){let r,i;try{r=readOpenClawDatabaseQuarantine(t,n)}catch(e){if(!(e instanceof Yr))return;if(!e.quarantine)throw e;r=e.quarantine,i=e}if(!r)return;let a=/* @__PURE__ */ Error(`OpenClaw ${e} database ${t} is quarantined after integrity verification failed: ${r.reason??`unknown integrity error`}. Restore the database from a backup or repair it, then run openclaw doctor --fix to clear the quarantine. See https://docs.openclaw.ai/reference/database-schemas.`);return a.name=`SqliteIntegrityError`,i&&(a.cause=i),a}const oc=new x;function getProcessCleanupBudget(){return oc.getStore()}function createStateDatabaseRetainer(e,t){let admit=(e,n,r)=>{let i=getOpenClawDatabaseMaintenanceScope();return n===`cached-read`?i?.assertReadAdmission():i?.assertAdmission(),t.assertOpen(e,n,r),i},retain=(n,r,i=!1)=>{if(t.capture(n.path).assertCurrent(),e.cachedDatabases.get(n.path)!==n||!n.db.isOpen)throw Error(`OpenClaw state database borrow requires its current canonical handle`);let a=e.borrowers.get(n.db)??{references:/* @__PURE__ */ new Set,retiring:!1,cleanupComplete:!1};if(a.retiring)throw Error(`OpenClaw state database native owner is retiring`);i||observeOpenClawDatabaseMaintenanceResource(n.db),e.borrowers.set(n.db,a);let isCurrent=()=>!r||isOpenClawDatabaseMaintenanceResourceOwned(n.db,r),o=i?void 0:{ordinary:r===void 0,isCurrent,retire:()=>{isCurrent()?t.retire(n,r===void 0):a.retiring=!1}};function createAsyncStateDatabaseRetirement(){let e={},r,i,finish=r=>{a.references.delete(e),a.releaseJoin?a.releaseJoin.resolve():r?.isCurrent()?r.retire():a.retiring=!1,a.retirement=void 0,a.asyncRetirement=void 0,i?.(),i=void 0,a.releaseJoin||t.touch(n)},run=()=>r||(a.cleanupComplete||a.references.size>+!!a.references.has(e)?Promise.resolve():a.retirement?.isCurrent()?(a.retiring=!0,a.references.add(e),i??=t.ownRetirement(n,close),r=Promise.resolve().then(async()=>{await n.walMaintenance.stop(),finish(a.retirement)}).catch(r=>{throw a.references.add(e),t.retainFailed(n),a.releaseJoin?.reject(r),a.releaseJoin=void 0,r}),r.catch(()=>{}),r):(finish(),Promise.resolve()));function close(){let e=run();return e.catch(t=>{throw r===e&&(r=void 0),t})}return{start:()=>void run(),close}}let s={};a.references.add(s);let c=!1,release=()=>{if(c||a.cleanupComplete)c=!0;else if(c=!0,a.references.delete(s),a.releaseJoin)a.references.size===0&&a.releaseJoin.resolve();else if(a.retirement&&!a.retirement.isCurrent()&&(a.retirement=void 0,a.asyncRetirement=void 0,a.retiring=!1),o?.isCurrent()&&!a.retirement?.ordinary&&(a.retirement=o),!(a.references.size>0)){if(!a.retirement)t.touch(n);else if(a.retiring=!0,a.asyncRetirement)a.asyncRetirement.start();else{try{a.retirement.retire()}catch(e){throw c=!1,t.retainFailed(n),e}a.retirement=void 0,t.touch(n)}}},l={release,async releaseAsync(){a.cleanupComplete||(a.releaseJoin?release():((o?.isCurrent()&&!a.retirement?.ordinary?o:a.retirement)?.isCurrent()&&(a.asyncRetirement??=createAsyncStateDatabaseRetirement()),release(),await a.asyncRetirement?.close()))}};return r?.own(l,`shared-references`,()=>l.releaseAsync()),l},findReadDatabase=(t,n,r)=>{let i=y({path:t}),a=e.cachedDatabases.get(i);return a?.db.isOpen?{database:a,scope:admit(i,n,r)}:{database:void 0,scope:void 0}},retainReadReference=(t,n)=>{let r=retain(t,n,!0),assertCurrent=()=>{if(e.cachedDatabases.get(t.path)!==t||!t.db.isOpen)throw Error(`Shared-state read lost its original native owner`)};return{assertCurrent,observe(){assertCurrent(),observeOpenClawDatabaseMaintenanceResource(t.db)},release:()=>r.release()}};return{retain:e=>retain(e,admit(e.path)),retainForIndependentRead(e,t,n){let{database:r,scope:i}=findReadDatabase(e,t,n);return r?retainReadReference(r,i):void 0},borrowForRead(e,t,n){let{database:r,scope:i}=findReadDatabase(e,t,n);if(r){if(r.db.isTransaction)throw Error(`Asynchronous shared-state reads cannot run inside a native transaction`);return{database:r,...retainReadReference(r,i)}}}}}async function joinStateDatabaseBorrowersReleased(e,t){e&&!e.cleanupComplete&&(e.retiring=!0,e.references.size!==0&&(e.releaseJoin||(e.releaseJoin=Qt(),getProcessCleanupBudget()?.warn(`Waiting for ${e.references.size} active native borrower(s) before retiring OpenClaw state database: ${t}`)),await e.releaseJoin.promise))}function assertStateDatabaseBorrowersReleased(e,t){if(e?.references.size)throw Error(`OpenClaw state database still has active native borrowers (${e.references.size}): ${t}`)}function createStateDatabaseCacheAdmission(e){return{closeTerminalFailure(t,n){markOpenClawStateDatabaseFailure(n,t),we(t),e.invalidate(t);let r=e.cachedDatabases.get(t),i=[];try{r&&e.evict(r)}catch(e){i.push(e)}try{e.notifyTerminalFailure(t,n)}catch(e){i.push(e)}be(i,`Terminal shared-state failure cleanup failed`)},read(t,n){if(!t.db.isOpen)return n(t);let r=!1;try{return Tt(t.db,()=>(r=!0,n(t)))}catch(n){if(r)throw n;let i=n instanceof Error?n:Error(String(n));if(Qe(i)){e.evict(t);return}throw i}}}}const sc=18e5,cc=me(`state/db`);function createStateDatabaseIdleRetirement({cachedDatabases:e,retainedDatabaseHandles:t,idleTimers:n,idleReferences:r,borrowers:i},a){let touch=o=>{if(!(e.get(o.path)===o&&o.db.isOpen)&&t.get(o.db)!==o)return;let s=n.get(o.db);if(s){s.refresh();return}let c=f(()=>setTimeout(()=>{n.delete(o.db);try{o.db.isOpen&&o.db.isTransaction?touch(o):!i.get(o.db)?.references.size&&!r.get(o.db)?.size&&a(o,!1,{busyTimeoutMs:0,checkpointMode:`PASSIVE`})}catch(e){cc.warn(`Idle shared-state database cleanup failed`,{path:o.path,error:e}),touch(o)}},sc));c.unref(),n.set(o.db,c)};return{touch,retain(t){if(e.get(t.path)!==t||!t.db.isOpen||i.get(t.db)?.retiring)throw Error(`OpenClaw state database idle retention requires its current canonical handle`);let n=r.get(t.db)??/* @__PURE__ */ new Set,a={};return n.add(a),r.set(t.db,n),()=>{n.delete(a)&&e.get(t.path)===t&&t.db.isOpen&&touch(t)}}}}const lc=l(Symbol.for(`openclaw.sqliteWalWriteAdmissions`),()=>/* @__PURE__ */ new WeakMap);function registerSqliteWalWorkerMaintenance(e,t,n){e.exec(`PRAGMA wal_autocheckpoint = 0;`);let r=lc.get(e)?.stopCheckpointTick;lc.set(e,{execute:t,cancel:n}),r?.()}function isSqliteWalWorkerMaintained(e){return lc.get(e)?.execute!==void 0}var uc={blockedEverywhereKeys:/* @__PURE__ */ `NODE_OPTIONS.NODE_PATH.NODE_REDIRECT_WARNINGS.NODE_REPL_EXTERNAL_MODULE.NODE_REPL_HISTORY.NODE_V8_COVERAGE.PYTHONHOME.PYTHONPATH.PERL5LIB.PERL5OPT.PERL5SHELL.PERLLIB.RUBYLIB.RUBYOPT.BASHOPTS.BASH_ENV.ENV.KSH_ENV.BROWSER.GIT_ALLOW_PROTOCOL.GIT_EDITOR.GIT_EXTERNAL_DIFF.GIT_DIR.GIT_WORK_TREE.GIT_COMMON_DIR.GIT_EXEC_PATH.GIT_INDEX_FILE.GIT_OBJECT_DIRECTORY.GIT_ALTERNATE_OBJECT_DIRECTORIES.GIT_NAMESPACE.GIT_PROTOCOL_FROM_USER.GIT_SEQUENCE_EDITOR.GIT_TEMPLATE_DIR.GIT_SSL_NO_VERIFY.GIT_SSL_CAINFO.GIT_SSL_CAPATH.CC.CPP.CXX.CXXCPP.CARGO_BUILD_RUSTC.CARGO_BUILD_RUSTC_WRAPPER.CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER.CARGO_BUILD_RUSTDOC.RUSTC.RUSTC_WRAPPER.RUSTC_WORKSPACE_WRAPPER.RUSTDOC.CMAKE_C_COMPILER.CMAKE_CXX_COMPILER.SHELL.SHELLOPTS.PS4.GCONV_PATH.IFS.SSLKEYLOGFILE.JAVA_OPTS.JAVA_TOOL_OPTIONS._JAVA_OPTIONS.JDK_JAVA_OPTIONS.PYTHONBREAKPOINT.DOTNET_STARTUP_HOOKS.DOTNET_ADDITIONAL_DEPS.FPATH.GLIBC_TUNABLES.MAVEN_OPTS.MAKE.MAKEFLAGS.MFLAGS.SBT_OPTS.GRADLE_OPTS.ANT_OPTS.HGRCPATH.HGEDITOR.HGMERGE.EXINIT.VIMINIT.MYVIMRC.GVIMINIT.LUA_INIT.LUA_INIT_5_1.LUA_INIT_5_2.LUA_INIT_5_3.LUA_INIT_5_4.EMACSLOADPATH.RUBYSHELL.GIT_HOOK_PATH.SVN_EDITOR.SVN_SSH.BZR_EDITOR.BZR_SSH.BZR_PLUGIN_PATH.SUDO_ASKPASS.JULIA_EDITOR.CONFIG_SITE.CONFIG_SHELL.CMAKE_TOOLCHAIN_FILE.CATALINA_OPTS.CORECLR_PROFILER.HELM_PLUGINS.PACKER_PLUGIN_PATH.VAGRANT_VAGRANTFILE.ERL_AFLAGS.ERL_FLAGS.ERL_ZFLAGS.ELIXIR_ERL_OPTIONS.R_ENVIRON.R_PROFILE.R_ENVIRON_USER.R_PROFILE_USER.TCLLIBPATH.HOSTALIASES`.split(`.`),blockedOverrideOnlyKeys:/* @__PURE__ */ `HOME.GRADLE_USER_HOME.ZDOTDIR.GIT_DIR.GIT_WORK_TREE.GIT_COMMON_DIR.GIT_INDEX_FILE.GIT_OBJECT_DIRECTORY.GIT_ALTERNATE_OBJECT_DIRECTORIES.GIT_NAMESPACE.GIT_SSH_COMMAND.GIT_SSH.GIT_PROXY_COMMAND.GIT_ASKPASS.GIT_SSL_NO_VERIFY.GIT_SSL_CAINFO.GIT_SSL_CAPATH.SSH_ASKPASS.LESSOPEN.LESSCLOSE.PAGER.MANPAGER.GIT_PAGER.EDITOR.VISUAL.FCEDIT.SUDO_EDITOR.PROMPT_COMMAND.HISTFILE.PERL5DB.PERL5DBCMD.OPENSSL_CONF.OPENSSL_ENGINES.PYTHONSTARTUP.WGETRC.CURL_HOME.CLASSPATH.CFLAGS.CGO_CFLAGS.CGO_LDFLAGS.GOFLAGS.MAKEFLAGS.MFLAGS.CORECLR_PROFILER_PATH.PHPRC.PHP_INI_SCAN_DIR.DENO_DIR.BUN_CONFIG_REGISTRY.YARN_RC_FILENAME.HTTP_PROXY.HTTPS_PROXY.ALL_PROXY.NO_PROXY.NODE_TLS_REJECT_UNAUTHORIZED.NODE_EXTRA_CA_CERTS.SSL_CERT_FILE.SSL_CERT_DIR.REQUESTS_CA_BUNDLE.CURL_CA_BUNDLE.DOCKER_HOST.DOCKER_TLS_VERIFY.DOCKER_CERT_PATH.PIP_INDEX_URL.PIP_PYPI_URL.PIP_EXTRA_INDEX_URL.PIP_CONFIG_FILE.PIP_FIND_LINKS.PIP_TRUSTED_HOST.UV_INDEX.UV_INDEX_URL.UV_PYTHON.UV_EXTRA_INDEX_URL.UV_DEFAULT_INDEX.DOCKER_CONTEXT.LIBRARY_PATH.LDFLAGS.CPATH.C_INCLUDE_PATH.CPLUS_INCLUDE_PATH.OBJC_INCLUDE_PATH.GOPROXY.GONOSUMCHECK.GONOSUMDB.GONOPROXY.GOPRIVATE.GOENV.GOPATH.HGRCPATH.PYTHONUSERBASE.RUSTC_WRAPPER.RUSTFLAGS.RUSTUP_DIST_ROOT.RUSTUP_DIST_SERVER.RUSTUP_HOME.RUSTUP_TOOLCHAIN.RUSTUP_UPDATE_ROOT.CARGO_HOME.VIRTUAL_ENV.LUA_PATH.LUA_CPATH.GEM_HOME.GEM_PATH.BUNDLE_GEMFILE.COMPOSER_HOME.CONDA_DEFAULT_ENV.CONDA_PREFIX.CARGO_BUILD_RUSTC_WRAPPER.XDG_CACHE_HOME.XDG_CONFIG_DIRS.XDG_CONFIG_HOME.XDG_DATA_DIRS.XDG_DATA_HOME.XDG_RUNTIME_DIR.XDG_STATE_HOME.AWS_CONFIG_FILE.KUBECONFIG.GOOGLE_APPLICATION_CREDENTIALS.AWS_SHARED_CREDENTIALS_FILE.AWS_WEB_IDENTITY_TOKEN_FILE.AZURE_AUTH_LOCATION.HELM_HOME.ANSIBLE_CONFIG.ANSIBLE_LIBRARY.ANSIBLE_CALLBACK_PLUGINS.ANSIBLE_COLLECTIONS_PATH.ANSIBLE_CONNECTION_PLUGINS.ANSIBLE_FILTER_PLUGINS.ANSIBLE_INVENTORY_PLUGINS.ANSIBLE_LOOKUP_PLUGINS.ANSIBLE_MODULE_UTILS.ANSIBLE_REMOTE_TEMP.ANSIBLE_ROLES_PATH.ANSIBLE_STRATEGY_PLUGINS.R_LIBS_USER.TF_CLI_CONFIG_FILE.TF_PLUGIN_CACHE_DIR.AMQP_URL.AWS_ACCESS_KEY_ID.AWS_CONTAINER_CREDENTIALS_FULL_URI.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.AWS_SECRET_ACCESS_KEY.AWS_SECURITY_TOKEN.AWS_SESSION_TOKEN.AZURE_CLIENT_ID.AZURE_CLIENT_SECRET.DATABASE_URL.GH_TOKEN.GITHUB_TOKEN.GITLAB_TOKEN.MONGODB_URI.NODE_AUTH_TOKEN.NPM_TOKEN.REDIS_URL.SSH_AUTH_SOCK.SYSTEMROOT.WINDIR`.split(`.`),allowedInheritedOverrideOnlyKeys:/* @__PURE__ */ `ALL_PROXY.AWS_CONFIG_FILE.AWS_SHARED_CREDENTIALS_FILE.AWS_WEB_IDENTITY_TOKEN_FILE.AZURE_AUTH_LOCATION.CURL_CA_BUNDLE.DOCKER_CERT_PATH.DOCKER_CONTEXT.DOCKER_HOST.DOCKER_TLS_VERIFY.GIT_PAGER.GOOGLE_APPLICATION_CREDENTIALS.GRADLE_USER_HOME.HISTFILE.HOME.HTTPS_PROXY.HTTP_PROXY.KUBECONFIG.MANPAGER.NODE_EXTRA_CA_CERTS.NODE_TLS_REJECT_UNAUTHORIZED.NO_PROXY.PAGER.REQUESTS_CA_BUNDLE.RUSTUP_DIST_ROOT.RUSTUP_DIST_SERVER.RUSTUP_HOME.RUSTUP_TOOLCHAIN.RUSTUP_UPDATE_ROOT.SSH_AUTH_SOCK.SSL_CERT_DIR.SSL_CERT_FILE.SYSTEMROOT.WINDIR.XDG_CACHE_HOME.XDG_CONFIG_DIRS.XDG_CONFIG_HOME.XDG_DATA_DIRS.XDG_DATA_HOME.XDG_RUNTIME_DIR.XDG_STATE_HOME.ZDOTDIR`.split(`.`),blockedOverridePrefixes:[`GIT_CONFIG_`,`NPM_CONFIG_`,`CARGO_REGISTRIES_`,`TF_VAR_`],blockedPrefixes:[`DYLD_`,`LD_`,`BASH_FUNC_`]};function sortUniqueUppercase(e){return Object.freeze(Array.from(new Set(e.map(e=>e.toUpperCase()))).toSorted((e,t)=>e<t?-1:+(e>t)))}function derivePolicyArrays(e){let t=e.blockedEverywhereKeys??[],n=e.blockedOverrideOnlyKeys??[],r=e.allowedInheritedOverrideOnlyKeys??[],i=new Set(r.map(e=>e.toUpperCase())),a=e.blockedPrefixes??[],o=e.blockedOverridePrefixes??[],s=e.blockedInheritedPrefixes??a;return{blockedInheritedKeys:sortUniqueUppercase([...t,...n.filter(e=>!i.has(e.toUpperCase()))]),blockedInheritedPrefixes:sortUniqueUppercase(s),blockedKeys:sortUniqueUppercase(t),blockedOverrideKeys:sortUniqueUppercase(n),blockedPrefixes:sortUniqueUppercase(a),blockedOverridePrefixes:sortUniqueUppercase(o)}}function loadHostEnvSecurityPolicy(e=uc){let t=derivePolicyArrays(e);return Object.freeze({blockedEverywhereKeys:Object.freeze(e.blockedEverywhereKeys??[]),blockedOverrideOnlyKeys:Object.freeze(e.blockedOverrideOnlyKeys??[]),allowedInheritedOverrideOnlyKeys:Object.freeze(e.allowedInheritedOverrideOnlyKeys??[]),blockedInheritedKeys:t.blockedInheritedKeys,blockedInheritedPrefixes:t.blockedInheritedPrefixes,blockedPrefixes:t.blockedPrefixes,blockedOverridePrefixes:t.blockedOverridePrefixes,blockedKeys:t.blockedKeys,blockedOverrideKeys:t.blockedOverrideKeys})}const dc=loadHostEnvSecurityPolicy();new Set(dc.blockedKeys),new Set(dc.blockedInheritedKeys),new Set(dc.blockedOverrideKeys),(/* @__PURE__ */ new Set([...Object.keys(resolveNodeServiceIdentityEnvironment()),`OPENCLAW_GATEWAY_SERVICE_PID`])).delete(`OPENCLAW_PROFILE`),new x;function findCaseInsensitiveEnvKey(e,t){if(Object.hasOwn(e,t))return t;let n=t.toUpperCase();return Object.keys(e).find(e=>e.toUpperCase()===n)}const fc=/* @__PURE__ */ new WeakMap;function resolveAppliedConfigEnvOwnership(e){return{...fc.get(re(e)),...e===process.env?pc.ownedEnv:{}}}new x;function cloneEnvWithPlatformSemantics(e){let t={...h(e)};return process.platform===`win32`&&(t=new Proxy(t,{deleteProperty(e,t){if(typeof t!=`string`)return Reflect.deleteProperty(e,t);let n=findCaseInsensitiveEnvKey(e,t);return!n||Reflect.deleteProperty(e,n)},get(e,t,n){if(typeof t!=`string`)return Reflect.get(e,t,n);let r=findCaseInsensitiveEnvKey(e,t);return r?e[r]:Reflect.get(e,t,n)},getOwnPropertyDescriptor(e,t){if(typeof t!=`string`)return Reflect.getOwnPropertyDescriptor(e,t);let n=findCaseInsensitiveEnvKey(e,t);if(n)return{configurable:!0,enumerable:!0,value:e[n],writable:!0}},has(e,t){return typeof t==`string`?findCaseInsensitiveEnvKey(e,t)!==void 0:Reflect.has(e,t)},set(e,t,n){return typeof t==`string`?(e[findCaseInsensitiveEnvKey(e,t)??t]=n,!0):Reflect.set(e,t,n)}})),fc.set(ne(t),resolveAppliedConfigEnvOwnership(e)),m(t),t}let pc={ownedEnv:{},sourceConfig:null};const mc=l(Symbol.for(`openclaw.gatewayServiceInstallation`),()=>new x);function getGatewayServiceInstallation(){return mc.getStore()?.installation}function isGatewayExternallySupervised(e=process.env){return e.OPENCLAW_SUPERVISOR_MODE?.trim().toLowerCase()===`external`}const hc=l(Symbol.for(`openclaw.stateDatabaseSchemaPolicies`),()=>({scopes:new x,existingDatabases:/* @__PURE__ */ new WeakMap,hasAdmittedExistingDatabase:!1}));function canonicalPath(e){let t=y({path:e});try{return ze(er.native(t))}catch(e){if(yt(e,`ENOENT`))return t;throw e}}function assertSchemaScopeActive(e){if(e&&!e.active)throw Error(`Existing shared-state schema admission has ended.`)}function getExistingOpenClawStateSchemaPath(){let e=hc.scopes.getStore();return assertSchemaScopeActive(e),e?.path}function captureOpenClawStateSchemaReadAdmission(e){let t=hc.scopes.getStore();if(t)return isExistingOpenClawStateSchema(e),{path:t.path,assertCurrent:()=>assertSchemaScopeActive(t)}}function isExistingOpenClawStateSchema(e,t){let n=getExistingOpenClawStateSchemaPath(),r=hc.scopes.getStore(),i=t&&hc.existingDatabases.get(t);if(!r&&!i)return!1;let a=y({path:e}),o=n!==void 0&&(n===a||r?.canonicalPath===a||r?.canonicalPath===canonicalPath(a));if(n&&!o)throw Error(`Existing shared-state schema admission is bound to ${n}, not ${e}.`);if(i&&(!o||i!==r?.canonicalPath))throw Error(`Shared-state database ${e} was admitted without schema repair; close its existing handle before ordinary admission.`);return o}function assertExistingOpenClawStateSchemaCacheAdmission(e,t){let n=getExistingOpenClawStateSchemaPath();if(!hc.hasAdmittedExistingDatabase)return;let r=hc.scopes.getStore(),i=r?y({path:e}):void 0,a=r&&(n===i||r.canonicalPath===i)?r.canonicalPath:void 0;for(let n of[t.cachedDatabases,t.retainedDatabaseHandles])for(let{db:t}of n.values()){let n=hc.existingDatabases.get(t);n&&t.isOpen&&(a??=canonicalPath(e),n===a&&isExistingOpenClawStateSchema(e,t))}}function captureSqliteWorkerStateContext(e){return{databaseEngineSelection:e.databaseEngineSelection??bn(),environment:{...e.environment},initializationCronDefaultStoreKey:e.initializationCronDefaultStoreKey,...e.initializationEnvironment?{initializationEnvironment:{...e.initializationEnvironment}}:{},...e.initializationAgentPaths?{initializationAgentPaths:[...e.initializationAgentPaths]}:{},existingSchemaPath:e.existingSchemaPath,gatewayServiceInstallation:e.gatewayServiceInstallation,...e.stateIntegrity?{stateIntegrity:e.stateIntegrity}:{},artifactPreservingReads:e.artifactPreservingReads,liveStateReads:e.liveStateReads,...e.scheduledMaintenanceSuspension?{scheduledMaintenanceSuspension:e.scheduledMaintenanceSuspension}:{}}}function sqliteWorkerRequestBytes(e,t,n){let r=t?.initializationAgentPaths?.reduce((e,t)=>e+Buffer.byteLength(t,`utf8`),0)??0;return[t?.environment,t?.initializationEnvironment].reduce((e,t)=>Object.entries(t??{}).reduce((e,[t,n])=>e+Buffer.byteLength(t,`utf8`)+Buffer.byteLength(n??``,`utf8`),e),e.byteLength+Buffer.byteLength(JSON.stringify(t?.databaseEngineSelection)??``,`utf8`)+Buffer.byteLength(JSON.stringify(t?.gatewayServiceInstallation)??``,`utf8`)+(n?.byteLength??0)+r+Buffer.byteLength(t?.initializationCronDefaultStoreKey??``,`utf8`)+(t?.scheduledMaintenanceSuspension?.byteLength??0))}l(Symbol.for(`openclaw.sqliteWorkerStateContext`),()=>new x);function resolveLegacyCronDefaultStoreKey(e){return C.resolve(ge(e),`cron`,`jobs.json`)}function captureOpenClawStateReadContextWithAdmission(e,t,n,r){let i=captureOpenClawStateSchemaReadAdmission(e),a=t(e,r),o=getGatewayServiceInstallation(),s=a.captureIntegrity?.(),c=a.assertCurrent,l=a,runInCapturedSchemaScope;if(i){let e=x.snapshot();l={databasePath:a.databasePath,coordinationKey:a.coordinationKey,get identity(){return a.identity},captureIntegrity:a.captureIntegrity,assertCurrent(){a.assertCurrent(),i.assertCurrent()}},runInCapturedSchemaScope=t=>e(()=>(l.assertCurrent(),t()))}return{databaseEngineSelection:bn(),maintenanceScope:getOpenClawDatabaseMaintenanceScope(),admission:l,assertPublicationCurrent:c,existingSchemaPath:i?.path,gatewayServiceInstallation:o&&n(o.databasePath)?.key===a.identity.key?o:void 0,stateIntegrity:s,runInCapturedSchemaScope,artifactPreservingReads:Nt(`agent`,e)||void 0,liveStateReads:Zt()||void 0}}function captureOpenClawStateReadWorkerContextWithAdmission(e,t,n){let r=e.env??process.env,i=process.platform===`win32`?cloneEnvWithPlatformSemantics(r):r,a={OPENCLAW_STATE_DIR:se(i),...isGatewayExternallySupervised(i)?{OPENCLAW_SUPERVISOR_MODE:`external`}:{}};return{...captureOpenClawStateReadContextWithAdmission(e.path??Lt(a),t,n),environment:a}}function captureOpenClawStateWorkerContextWithAdmission(e,t,n){let r=captureOpenClawStateReadWorkerContextWithAdmission(e,t,n);return{...r,initializationCronDefaultStoreKey:resolveLegacyCronDefaultStoreKey(e.env??process.env),initializationEnvironment:hn([e.env??process.env,{OPENCLAW_STATE_DIR:void 0,OPENCLAW_SUPERVISOR_MODE:void 0},r.environment]),...e.initializationAgentPaths?{initializationAgentPaths:e.initializationAgentPaths.map(e=>C.resolve(e))}:{}}}function createStateDatabaseWalOwner({cachedDatabases:e,retainedDatabaseHandles:t,databaseIdentities:n,asyncResources:r},i,a){return{ownRetirement(e,t){let n={admission:{identity:a(e)},close:t},i=r.register(n);return getOpenClawDatabaseMaintenanceResourceScope(e.db)?.own(n,`shared-references`,()=>n.close()),i},async stop(r,i){let a=/* @__PURE__ */ new Set([...t.values(),...e.values()]);await Promise.all([...a].filter(e=>r===void 0||e.path===r||i!==void 0&&n.get(e.db)?.key===i.key).flatMap(({walMaintenance:e})=>e?[e.stop()]:[]))},register(t,n,a,o){if(!Yn||Xe(t.db))return;let s=captureOpenClawStateWorkerContextWithAdmission({path:t.path,env:o},()=>a,r.knownIdentity),c=new AbortController,l,cancel=()=>{if(c.abort(),!l)d();else return l.then(()=>void 0,()=>void 0)},u={admission:{identity:n},async close(){cancel(),await t.walMaintenance.stop(),d()}},d=r.register(u),run=async r=>{let a=getOpenClawDatabaseMaintenanceResourceScope(t.db),o={...s,maintenanceScope:a},assertCurrent=()=>{if(c.signal.throwIfAborted(),o.admission.assertCurrent(),a?.assertAdmission(),getOpenClawDatabaseMaintenanceResourceScope(t.db)!==a||e.get(t.path)!==t||!t.db.isOpen)throw new StateDatabaseReadAdmissionInvalidatedError(`Shared-state WAL maintenance owner changed`)},l,u=!1;try{assertCurrent(),l=i(t);let{runOpenClawStateWorkerOperation:e}=await import(`./plugin-preparation-openclaw-state-worker-store-K0-zco3h.mjs`);return assertCurrent(),await e(o,e=>e.execute({type:`database.walMaintenance`,input:r},{signal:c.signal}),{existingOnly:!0,assertCurrent,createAdmission:()=>({nativeLocations:[t.path,n.canonicalPath],databaseIdentity:{databasePath:t.path,key:n.key,birthtime:n.birthtime},admission:Gn((e,t)=>{if(assertCurrent(),!t())throw new StateDatabaseReadAdmissionInvalidatedError(`Shared-state WAL maintenance authority expired`);u=!0})})})}catch(e){if(!u&&(isStateDatabaseReadAdmissionInvalidatedError(e)||c.signal.aborted&&vt(e)))return;throw e}finally{l?.()}};registerSqliteWalWorkerMaintenance(t.db,e=>{if(c.signal.aborted)return Promise.resolve(void 0);let t=run(e);return l=t,t.finally(()=>{l===t&&(l=void 0),c.signal.aborted&&d()})},cancel)},readHealth(){let t=e.get(C.resolve(Lt()));return t?.db.isOpen?t.walMaintenance.health:void 0}}}const gc=l(Symbol.for(`openclaw.stateNativeIdentities`),()=>/* @__PURE__ */ new WeakMap);function readTrackedStateDatabaseIdentity(e){return gc.get(rt(e))}function closeTrackedStateDatabase(e){e.isOpen&&e.close()}function closeStateDatabaseHandle(e,t){try{var n=Dn();let r=[];if(Xe(e.db)){for(let t of[e.db,e.db.anchor]){if(t===e.db.anchor&&e.db.isOpen)break;try{t.isOpen&&t.close()}catch(e){r.push(e)}}let t=e.db.isOpen||e.db.anchor.isOpen;if(!t)try{e.afterClose?.()}catch(e){r.push(e),t=!0}return{errors:r,cleanupPending:t}}let i=n.u(dt(e.db)),a=isSqliteWalWorkerMaintained(e.db),o=e.walMaintenance?.health?.state===`error`,s=!1;try{e.db.isOpen&&!a&&Ct(e.db,0),s=e.walMaintenance?.close(t)===!0&&t?.checkpointMode!==`PASSIVE`}catch(e){r.push(e)}try{Bt(e.db)}catch(e){r.push(e)}try{closeTrackedStateDatabase(e.db)}catch(e){r.push(e)}let c=!1;if(!e.db.isOpen)try{e.afterClose?.()}catch(e){r.push(e),c=!0}return r.length===0&&!c&&t?.checkpointMode!==`PASSIVE`&&(s||a&&!o)&&i.publish(),{errors:r,cleanupPending:c}}catch(e){n.e=e}finally{n.d()}}const _c=l(Symbol.for(`openclaw.stateIntegrityBindings`),()=>/* @__PURE__ */ new WeakMap);function invalidate(e){let t=Atomics.load(e,0);for(;t>=0n;){let n=Atomics.compareExchange(e,0,t,t+1n);if(n===t)return;t=n}}function invalidateOpenClawStateRuntimeIntegrity(e){Ce(e);let t=_c.get(e);t&&(invalidate(new BigInt64Array(t.revision)),invalidate(new BigInt64Array(t.lifetimeRevision)))}function retainSqliteDatabaseRemovalExclusion(e,t){if(!$n(e))return;let n=It(Yt(e)),close=()=>{if(!n.isOpen)return;let e=[];try{n.isTransaction&&n.exec(`ROLLBACK`)}catch(t){e.push(t)}try{n.close()}catch(t){e.push(t)}be(e,`SQLite state removal exclusion cleanup failed.`)};try{t.own(n,`shared-handles`,close),n.exec(`PRAGMA busy_timeout = 0; PRAGMA locking_mode = EXCLUSIVE; BEGIN EXCLUSIVE;`)}catch(e){try{close()}catch(t){throw ke([e,t],`SQLite state removal admission and cleanup both failed.`,e)}if(at(e))throw Error(`Cannot remove OpenClaw state directory while another SQLite connection is active`,{cause:e});let t=et(e);if(t!==11&&t!==26)throw e;return}process.platform===`win32`&&close()}function createOpenClawStateSnapshotOwnerRegistry(){let e=/* @__PURE__ */ new WeakMap;return{register(t,n){Xe(t.db)||e.set(t.db,registerLiveSqliteSnapshotOwner({database:t.db,databasePath:t.path,assertCurrent:()=>{if(n()!==t||!t.db.isOpen)throw Error(`OpenClaw state snapshot owner is no longer current`)}}))},release(t){Xe(t)||(e.get(t)?.(),e.delete(t))}}}const vc=l(Symbol.for(`openclaw.stateSnapshotOwners`),createOpenClawStateSnapshotOwnerRegistry);var yc=/* @__PURE__ */ e({assertPublishedOpenClawStateDatabaseLifecycle:()=>assertPublishedOpenClawStateDatabaseLifecycle,borrowOpenClawStateDatabaseForAsyncRead:()=>Pc,captureOpenClawStateDatabaseReadAdmission:()=>Lc,captureOpenClawStateIntegrityAdmission:()=>Rc,clearOpenClawStateDatabaseOpenFailure:()=>clearOpenClawStateDatabaseOpenFailure,closeOpenClawStateDatabase:()=>closeOpenClawStateDatabase,closeOpenClawStateDatabaseAsync:()=>closeOpenClawStateDatabaseAsync,closeOpenClawStateDatabaseByPath:()=>closeOpenClawStateDatabaseByPath,closeOpenClawStateDatabaseByPathAsync:()=>closeOpenClawStateDatabaseByPathAsync,closeOpenClawStateDatabaseForTest:()=>closeOpenClawStateDatabaseForTest,closeOpenClawStateDatabaseWorkersByPathAsync:()=>closeOpenClawStateDatabaseWorkersByPathAsync,getOpenClawStateDatabaseTerminalFailureAsync:()=>getOpenClawStateDatabaseTerminalFailureAsync,isOpenClawStateDatabaseOpen:()=>isOpenClawStateDatabaseOpen,joinOpenClawStateDatabaseBorrowers:()=>joinOpenClawStateDatabaseBorrowers,openClawStateDatabaseCache:()=>zc,prepareOpenClawStateCachedRead:()=>prepareOpenClawStateCachedRead,prepareOpenClawStateDatabaseRemoval:()=>prepareOpenClawStateDatabaseRemoval,publishOpenClawStateDatabaseWorkerAdmission:()=>publishOpenClawStateDatabaseWorkerAdmission,readOpenClawStateWalHealth:()=>kc,recordOpenClawStateDatabaseOpenFailure:()=>recordOpenClawStateDatabaseOpenFailure,registerOpenClawStateDatabaseAsyncResource:()=>Ic,registerOpenClawStateDatabaseLifecycleListener:()=>registerOpenClawStateDatabaseLifecycleListener,registerOpenClawStatePathAsyncResource:()=>registerOpenClawStatePathAsyncResource,registerOpenClawStatePathCacheInvalidation:()=>registerOpenClawStatePathCacheInvalidation,releaseOpenClawStateDatabaseCustody:()=>releaseOpenClawStateDatabaseCustody,requireOpenClawStateDatabaseIdentity:()=>requireOpenClawStateDatabaseIdentity,retainOpenClawStateDatabase:()=>Nc,retainOpenClawStateDatabaseForIdle:()=>Dc,retainOpenClawStateDatabaseForIndependentRead:()=>Fc});const X=l(Qr,()=>({cachedDatabases:/* @__PURE__ */ new Map,retainedDatabaseHandles:/* @__PURE__ */ new Map,idleTimers:/* @__PURE__ */ new WeakMap,idleReferences:/* @__PURE__ */ new WeakMap,unregisterRetainedExitClose:void 0,databaseIdentities:/* @__PURE__ */ new WeakMap,borrowers:/* @__PURE__ */ new WeakMap,databaseLifecycleListeners:/* @__PURE__ */ new Set,terminalOpenLatch:createSqliteTerminalOpenLatch({closeByPath:(e,t)=>Mc.closeTerminalFailure(e,t)}),asyncResources:createOpenClawStateDatabaseAsyncLifecycle()}),()=>closeOpenClawStateDatabaseAsync(),`shared-state`),{cachedDatabases:Z,retainedDatabaseHandles:bc,idleTimers:xc,idleReferences:Sc,databaseIdentities:Cc,borrowers:Q,databaseLifecycleListeners:wc,terminalOpenLatch:Tc,asyncResources:$}=X,{touch:Ec,retain:Dc}=createStateDatabaseIdleRetirement(X,retireOpenClawStateDatabaseHandle),{register:Oc,readHealth:kc,ownRetirement:Ac,stop:jc}=createStateDatabaseWalOwner(X,Dc,requireOpenClawStateDatabaseIdentity);function notifyOpenClawStateDatabaseLifecycle(e){let t=e.kind===`open-error`?{...e,identity:e.identity??$.knownIdentity(e.path)}:e;for(let e of wc)e(t)}function notifyOpenClawStateDatabaseClosed(e){notifyOpenClawStateDatabaseLifecycle({kind:`closed`,path:e.path,identity:requireOpenClawStateDatabaseIdentity(e)})}function requireOpenClawStateDatabaseIdentity(e){let t=Cc.get(e.db);if(!t)throw Error(`Published shared-state owner has no recorded database identity`);return t}const Mc=createStateDatabaseCacheAdmission({cachedDatabases:Z,evict:evictCachedOpenClawStateDatabase,invalidate:e=>$.invalidate(e),notifyTerminalFailure:(e,t)=>notifyOpenClawStateDatabaseLifecycle({kind:`terminal-failure`,path:e,error:t,identity:$.knownIdentity(e)})});function registerOpenClawStateDatabaseLifecycleListener(e){wc.add(e);for(let t of Z.values())t.db.isOpen&&e({kind:`opened`,database:t,identity:requireOpenClawStateDatabaseIdentity(t)});return()=>wc.delete(e)}function registerOpenClawStatePathCacheInvalidation(e){return registerOpenClawStateDatabaseLifecycleListener(t=>{if(t.kind!==`opened`)for(let[n,r]of e)r.path===(t.identity?.canonicalPath??t.path)&&e.delete(n)})}function retainStateDatabaseClose(e){bc.set(e.db,e),X.unregisterRetainedExitClose??=ue(closeOpenClawStateDatabase)}function ownMaintenanceStateDatabaseHandle(e){getOpenClawDatabaseMaintenanceScope()?.own(e.db,`shared-handles`,async()=>{let t=getOpenClawDatabaseMaintenanceScope();t&&isOpenClawDatabaseMaintenanceResourceOwned(e.db,t)&&(Z.get(e.path)===e||bc.get(e.db)===e)&&(await e.walMaintenance?.stop(),isOpenClawDatabaseMaintenanceResourceOwned(e.db,t)&&(Z.get(e.path)===e||bc.get(e.db)===e)&&retireOpenClawStateDatabaseHandle(e,!1))})}function closeUnpublishedOpenClawStateDatabaseHandle(e){let t=closeOpenClawStateDatabaseHandle(e);return bc.get(e.db)===e&&ownMaintenanceStateDatabaseHandle(e),t}const{retain:Nc,borrowForRead:Pc,retainForIndependentRead:Fc}=createStateDatabaseRetainer(X,{assertOpen(e,t,n){assertOpenClawStateDatabaseOpenAllowed(e,t,n),assertExistingOpenClawStateSchemaCacheAdmission(e,X)},capture:e=>$.capture(e),retire:retireOpenClawStateDatabaseHandle,retainFailed:retainStateDatabaseClose,ownRetirement:Ac,touch:Ec});function closeOpenClawStateDatabaseHandle(e,t){clearTimeout(xc.get(e.db)),xc.delete(e.db);try{assertStateDatabaseBorrowersReleased(Q.get(e.db),e.path)}catch(n){let r=Q.get(e.db);return r&&(r.retiring=!0,r.retirement={ordinary:!0,isCurrent:()=>!0,retire:()=>{be(closeOpenClawStateDatabaseHandle(e,t),`OpenClaw state database cleanup failed for ${e.path}.`),r.cleanupComplete=!0,Q.delete(e.db)}}),retainStateDatabaseClose(e),[n]}Sc.delete(e.db),vc.release(e.db);let{errors:n,cleanupPending:r}=closeStateDatabaseHandle(e,t);return e.db.isOpen||r?retainStateDatabaseClose(e):bc.delete(e.db),Z.get(e.path)?.db===e.db&&Z.delete(e.path),bc.size===0&&(X.unregisterRetainedExitClose?.(),X.unregisterRetainedExitClose=void 0),n}function evictCachedOpenClawStateDatabase(e){return Xe(e.db)||invalidateOpenClawStateRuntimeIntegrity(e.db),Z.get(e.path)===e&&($.invalidate(e.path),Z.delete(e.path),notifyOpenClawStateDatabaseClosed(e),closeOpenClawStateDatabaseHandle(e,{checkpointMode:`PASSIVE`}),!0)}function evictOpenClawStateDatabaseAfterCorruption(e,t){return Qe(t)&&evictCachedOpenClawStateDatabase(e)}function publishOpenClawStateDatabase(e,t){let{db:n,path:r}=e,{identity:i,admission:a}=$.publish(r);return Cc.set(n,readTrackedStateDatabaseIdentity(n)??i),Z.set(r,e),Oc(e,i,a,t),Ec(e),vc.register(e,()=>Z.get(r)),ownMaintenanceStateDatabaseHandle(e),notifyOpenClawStateDatabaseLifecycle({kind:`opened`,database:e,identity:i}),Xe(n)||Dt(n,t=>{!n.isTransaction&&Qe(t)&&evictCachedOpenClawStateDatabase(e)}),Tc.clear(r),e}function getCachedOpenClawStateDatabase(e,t){let n=y({path:e}),r=Tc.get(n);if(r)throw r;let i=readCachedOpenClawStateDatabase(n,t?.readOnly===!0);return i&&Ec(i),i}function readCachedOpenClawStateDatabase(e,t){let n=getOpenClawDatabaseMaintenanceScope();t?n?.assertReadAdmission():n?.assertAdmission(),assertExistingOpenClawStateSchemaCacheAdmission(e,X);let r=Z.get(e);if(r&&Q.get(r.db)?.retiring)throw Error(`OpenClaw state database native borrower cleanup is pending: ${e}`);return r}function prepareOpenClawStateCachedRead(e){let t=y({path:e});getCachedOpenClawStateDatabase(t,{readOnly:!0});let n=$.capture(t);return()=>(n.assertCurrent(),readCachedOpenClawStateDatabase(t,!0))}function withCachedOpenClawStateDatabase(e,t,n){let r=getCachedOpenClawStateDatabase(e,t);return r&&Mc.read(r,n)}function getOpenClawStateDatabaseIfOpenAtPath(e){let t=getCachedOpenClawStateDatabase(e);return observeOpenClawDatabaseMaintenanceResource(t?.db.isOpen?t.db:void 0),t?.db.isOpen?t:void 0}function closeStaleCachedOpenClawStateDatabase(e){if(Z.get(e.path)!==e)return;$.invalidate(e.path);let t=closeOpenClawStateDatabaseHandle(e);notifyOpenClawStateDatabaseClosed(e),be(t,`Stale OpenClaw state database cleanup failed for ${e.path}.`)}function recordOpenClawStateDatabaseOpenFailure(e,t){Tc.record(y({path:e}),t)}function clearOpenClawStateDatabaseOpenFailure(e){let t=y({path:e});Tc.clear(t),$.invalidate(t),notifyOpenClawStateDatabaseLifecycle({kind:`failure-cleared`,path:t,identity:$.knownIdentity(t)})}async function getOpenClawStateDatabaseTerminalFailureAsync(e,t){return e.admission.assertCurrent(),t?.throwIfAborted(),Tc.get(e.admission.databasePath)}function assertOpenClawStateDatabaseOpenAllowed(e,t,n){let r=y({path:e});t===`cached-read`&&n?n.assertReadAllowed():(t===`cached-read`?assertStateDatabaseReadAllowed:assertStateDatabaseAccessAllowed)(e);let{identity:i}=$.capture(r),a=Tc.get(r);if(a)throw a;for(let t of bc.values())if(Q.get(t.db)?.retiring&&(t.path===r||Cc.get(t.db)?.key===i.key))throw Error(`OpenClaw state database native borrower cleanup is pending: ${e}`)}function recordOpenClawStateDatabaseLifecycleOpenError(e,t){notifyOpenClawStateDatabaseLifecycle({kind:`open-error`,path:y({path:e}),error:t})}function assertOpenClawStateDatabaseFreshOpenAllowedAtPath(e,t,n,r){assertOpenClawStateDatabaseOpenAllowed(e);let i;try{i=readOpenClawDatabaseQuarantineFailure(`state`,e,{env:t,refreshIdentity:r})}catch(e){if(!(e instanceof Yr))throw e;n?.(e)}if(i?.cause instanceof Yr&&n?.(i.cause),i)throw Mc.closeTerminalFailure(e,i),i}function retireOpenClawStateDatabaseHandle(e,t=!0,n){assertStateDatabaseBorrowersReleased(Q.get(e.db),e.path);let r=Q.get(e.db);try{let r=Z.get(e.path)?.db===e.db;t&&$.invalidate(e.path);let i=closeOpenClawStateDatabaseHandle(e,n);if(r&&t)try{notifyOpenClawStateDatabaseClosed(e)}catch(e){i.push(e)}be(i,`OpenClaw state database cleanup failed for ${e.path}.`)}catch(t){throw r&&retainStateDatabaseClose(e),t}r&&(r.cleanupComplete=!0,Q.delete(e.db))}function stateDatabaseHandlesAt(e,t){return[.../* @__PURE__ */ new Set([...bc.values(),...Z.values()])].filter(n=>e===void 0||n.path===e||t!==void 0&&Cc.get(n.db)?.key===t.key)}function retireOpenClawStateDatabaseHandles(e,t,n){let r=stateDatabaseHandlesAt(e,n),i=[];for(let e of r)try{retireOpenClawStateDatabaseHandle(e,!0,t)}catch(e){i.push(e)}return be(i,`OpenClaw state database cleanup failed.`),r.length>0}function closeOpenClawStateDatabaseByPath(e,t){return retireOpenClawStateDatabaseHandles(y({path:e}),t,$.identity(e))}function sealOpenClawStateDatabaseByPath(e){let t=y({path:e}),n=$.identity(e);return!stateDatabaseHandlesAt(t,n).some(e=>Q.get(e.db)?.references.size)&&retireOpenClawStateDatabaseHandles(t,void 0,n)}function closeOpenClawStateDatabase(e){retireOpenClawStateDatabaseHandles(void 0,e)}const Ic=$.register;function registerOpenClawStatePathAsyncResource(e,t){return Ic({close(n){return!n||n.key===e.identity.key||n.canonicalPath===e.identity.canonicalPath?t():Promise.resolve()}})}const Lc=$.capture,Rc=$.integrity;function publishOpenClawStateDatabaseWorkerAdmission(e,t){t&&e.assertCurrent(),$.publish(e.databasePath,t),e.assertCurrent(),pt(e.databasePath,e.identity)}function closeOpenClawStateDatabaseByPathAsync(e,t){let n=y({path:e});return $.close(n,async e=>(await jc(n,e),retireOpenClawStateDatabaseHandles(n,t,e)))}function closeOpenClawStateDatabaseWorkersByPathAsync(e){return $.close(y({path:e}),()=>!1)}async function closeOpenClawStateDatabaseAsync(e){await $.close(void 0,async()=>(await jc(),retireOpenClawStateDatabaseHandles(void 0,e)))}async function joinOpenClawStateDatabaseBorrowers(){await Promise.all(stateDatabaseHandlesAt().map(e=>joinStateDatabaseBorrowersReleased(Q.get(e.db),e.path)))}async function releaseOpenClawStateDatabaseCustody(){await closeOpenClawStateDatabaseAsync(),Ge()}function isOpenClawStateDatabaseOpen(e){return e===void 0?Array.from(Z.values()).some(e=>e.db.isOpen):Z.get(y({path:e}))?.db.isOpen===!0}function closeOpenClawStateDatabaseForTest(){closeOpenClawStateDatabase(),Tc.clearAll()}function assertPublishedOpenClawStateDatabaseLifecycle(){if(ee(Qr)!==X)throw Error(`OpenClaw state database lifecycle is retired; its owners cannot serve the published lifecycle`)}const zc={assertOpenClawStateDatabaseFreshOpenAllowedAtPath,assertOpenClawStateDatabaseOpenAllowed,clearOpenClawStateDatabaseOpenFailure,closeOpenClawStateDatabase,closeOpenClawStateDatabaseByPath,sealOpenClawStateDatabaseByPath,closeOpenClawStateDatabaseForTest,closeOpenClawStateDatabaseHandle,closeUnpublishedOpenClawStateDatabaseHandle,closeStaleCachedOpenClawStateDatabase,evictCachedOpenClawStateDatabase,evictOpenClawStateDatabaseAfterCorruption,getCachedOpenClawStateDatabase,peekOpenClawStateDatabaseConnection:e=>Z.get(y({path:e}))?.db,withCachedOpenClawStateDatabase,getOpenClawStateDatabaseRecordedFailure:Tc.peek,getOpenClawStateDatabaseIfOpenAtPath,getKnownOpenClawStateDatabaseIdentity:$.knownIdentity,isOpenClawStateDatabaseOpen,isOpenClawStateDatabaseSchemaReady:e=>Z.get(e.path)===e&&e.db.isOpen,publishOpenClawStateDatabase,recordOpenClawStateDatabaseOpenFailure,recordOpenClawStateDatabaseLifecycleOpenError,async reconcileFailedWorkerAdmission(e){await $.retireChangedAdmission(e),e.assertCurrent()},touchStateDatabase:Ec};async function prepareOpenClawStateDatabaseRemoval(e,t){let n=y({path:e}),r=getOpenClawDatabaseMaintenanceScope();if(!r?.ownsSchemaMaintenance)throw Error(`State removal requires the installation's maintenance owner`);r.assertAdmission();let i=$.holdExclusion(n);try{await closeOpenClawStateDatabaseByPathAsync(n),r.assertOwnerCurrent(),retainSqliteDatabaseRemovalExclusion(n,r),r.assertOwnerCurrent()}catch(e){throw i(),e}let a=!0;return{assertCurrent(){if(!a)throw Error(`State removal admission has been released`);t()},release(){a&&(a=!1,i())}}}export{StateDatabaseReadAdmissionInvalidatedError as C,getOpenClawDatabaseMaintenanceScope as E,createSqliteWorkerTransferReceiver as S,createStateWorkerMemoryPressureSubscription as T,hydrateOpenClawStateWorkerError as _,publishOpenClawStateDatabaseWorkerAdmission as a,findOpenClawStateDatabaseFailure as b,registerOpenClawStateDatabaseLifecycleListener as c,getExistingOpenClawStateSchemaPath as d,isExistingOpenClawStateSchema as f,captureStateDatabaseAccess as g,acquireStateDatabaseSchemaLease as h,yc as i,captureSqliteWorkerStateContext as l,retainSqliteWriteAdmissionService as m,getOpenClawStateDatabaseTerminalFailureAsync as n,recordOpenClawStateDatabaseOpenFailure as o,sc as p,zc as r,Ic as s,assertPublishedOpenClawStateDatabaseLifecycle as t,sqliteWorkerRequestBytes as u,retainOpenClawStateWorkerErrorPayload as v,Br as w,createSqliteWorkerTransferOwner as x,ti as y};