UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

138 lines • 392 kB
import{Bt as e,Ct as t,Dt as n,H as r,Ht as i,J as a,Kt as o,Mt as s,Pt as c,Tt as l,U as u,at as d,ft as f,i as p,kt as m,lt as ee,pt as h,t as g,vt as v}from"./disk-budget.worker-subsystem-9qP7ka6r.mjs";import{$ as te,$r as ne,Ai as re,Di as ie,Dn as ae,Et as oe,G as se,Gn as ce,Hn as le,In as ue,J as de,Lt as fe,Nn as pe,Oi as me,Pt as he,Q as ge,Ri as _e,St as ve,Tt as ye,U as be,Ui as xe,Un as Se,Ur as Ce,V as we,Vn as Te,Vt as Ee,Wn as De,Xn as Oe,Y as ke,Z as Ae,_t as je,ar as Me,at as Ne,ct as Pe,dn as Fe,dr as Ie,fi as Le,fn as Re,ft as ze,gn as Be,gr as Ve,gt as He,hr as Ue,ht as We,ir as Ge,ji as Ke,ki as qe,kn as Je,kr as Ye,kt as Xe,li as Ze,lr as Qe,lt as $e,mr as et,on as tt,or as nt,ot as rt,pr as it,q as at,rr as ot,si as st,sr as ct,tr as lt,tt as ut,ui as dt,vr as ft,vt as pt,xr as y,yn as mt,zn as ht}from"./disk-budget.worker-sqlite-readonly-worker-Bob4L7Jx.mjs";import{r as gt,t as _t}from"./disk-budget.worker-deferred-BKs9Ozs0.mjs";import{B as vt,E as yt,F as bt,G as xt,H as St,U as Ct,V as wt,W as Tt}from"./disk-budget.worker-sqlite-worker-operation-settlement-B656vNKC.mjs";import{a as Et,i as Dt,o as Ot}from"./disk-budget.worker-cli-invocation-OtTkpH1g.mjs";import{d as kt,i as At,l as jt,n as Mt,o as Nt,r as Pt,u as Ft}from"./disk-budget.worker-sqlite-schema-sql-BnVx4b5A.mjs";import{t as It}from"./disk-budget.worker-errors-DTPr0dgo.mjs";import{o as Lt,t as Rt}from"./disk-budget.worker-gateway-process-argv-lGmvE77y.mjs";import{a as zt,o as Bt,r as Vt}from"./disk-budget.worker-openclaw-root-DFzofuF0.mjs";import{i as Ht,o as Ut,s as Wt}from"./disk-budget.worker-service-child-group-ownership-DO90jxGH.mjs";import{n as Gt}from"./disk-budget.worker-runtime-worker-url-MsqcyVdt.mjs";import{MessageChannel as Kt,isMainThread as qt,threadId as Jt}from"node:worker_threads";import{AsyncLocalStorage as Yt}from"node:async_hooks";import{hash as Xt,randomUUID as Zt}from"node:crypto";import b,{chmodSync as Qt,statSync as $t,unlinkSync as en,writeFileSync as tn}from"node:fs";import"node:fs/promises";import nn from"node:os";import x from"node:path";import"@openclaw/fs-safe/path";import{promisify as rn}from"node:util";import{performance as an}from"node:perf_hooks";import{copyRootFileSync as on,createDirectorySync as sn,readFileWindowFullySync as cn,sameFileContentsSync as ln,sameFileIdentity as un}from"@openclaw/fs-safe/advanced";import{spawnSync as dn}from"node:child_process";import{FsSafeError as pn,FsSafeError as mn}from"@openclaw/fs-safe/errors";import"@openclaw/fs-safe/output";import{root as hn}from"@openclaw/fs-safe/root";import"@openclaw/fs-safe/secure-file";import"@openclaw/fs-safe/walk";import{setImmediate as gn}from"node:timers/promises";import"node:buffer";import{probeTreeClone as _n}from"@openclaw/fs-safe/copy";import{acquireFileLockSync as vn}from"@openclaw/fs-safe/file-lock";async function backupNodeSqliteDatabase(e,t,n){let r=setInterval(()=>{},100);try{let r=await Oe().backup(e,oe(t),{progress:n});return n?.({totalPages:r,remainingPages:0}),r}finally{clearInterval(r)}}async function root$1(e,t){return await hn(e,t)}async function copySqliteFile(e,t,n,r){let i=await root$1(x.dirname(e)),a=await root$1(x.dirname(t)),o,copy=s=>a.copyIn(x.basename(t),{relativePath:x.basename(e),root:{stat:e=>i.stat(e),open:async(t,r)=>{let a=await i.open(t,r);try{if(!un(n,await a.handle.stat({bigint:!0})))throw Error(`SQLite copy source changed: ${e}`);return a}catch(e){throw await a.handle.close(),e}}}},{clone:s,...r?{maxBytes:Number(n.size)}:{},sourceHardlinks:`allow`,overwrite:!1,mode:384,durable:!0,onDestinationPublished:e=>{o=e}});if(r)try{await copy(`always`)}catch(e){if(o||!(e instanceof mn)||!(e.code===`unsupported-platform`||e.code===`helper-unavailable`&&e.message===`native file cloning is unavailable`))throw e;await r(Number(n.size)),await copy(`never`)}else await copy(`auto`);if(!o)throw Error(`SQLite copy was not published: ${t}`);return o}function createPrivateWindowsDirectory(e){let t=!1;try{sn(x.resolve(e),{private:!0,assertBeforeMutation(){t=!0}})}catch(e){throw!t||e instanceof pn&&e.code===`already-exists`?pt(e):e}}function resolvePrivateSqliteSnapshotStagingRoot(e=process.env){try{return resolveSnapshotStagingRoot(e)}catch(e){throw e instanceof Error&&He(e)?new We(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`,{cause:e}):e}}function resolveSnapshotStagingRoot(e){let t=e.OPENCLAW_UPDATE_IN_PROGRESS===`1`?e.TMPDIR?.trim():void 0;if(t&&x.isAbsolute(t))return p({preferredDir:x.join(t,`openclaw`),tmpdir:()=>t});let n=process.platform===`win32`?e.LOCALAPPDATA?.trim():void 0,r=process.platform===`win32`?`AppData/Local`:`.cache`,i=process.platform===`darwin`?`Library/Caches`:r,a=[e.XDG_CACHE_HOME?.trim(),n].find(e=>e&&x.isAbsolute(e))??x.join(d(e),i);return p({preferredDir:x.join(a,`openclaw`),tmpdir:()=>a})}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return b.mkdtempSync(x.join(e,t))}catch(e){throw pt(e)}let n=x.join(e,`${t}${Zt()}`);return createPrivateWindowsDirectory(n),n}var SqliteSchemaMismatchError=class extends Error{constructor(...e){super(...e),this.name=`SqliteSchemaMismatchError`}};const yn={"missing-table":`missing table`,"missing-column":`column definitions differ for`,"unexpected-column":`column definitions differ for`,"column-definition-drift":`column definitions differ for`,"table-constraint-drift":`table constraints differ for`,"table-definition-drift":`table definition differs for`,"missing-or-drifted-index":`missing or drifted index`,"unexpected-unique-index":`unexpected unique index`,"missing-or-drifted-trigger":`missing or drifted trigger`,"missing-or-drifted-view":`missing or drifted view`,"unexpected-trigger":`unexpected trigger`,"virtual-table-definition-drift":`virtual table definition differs for`,"table-options-drift":`table options differ for`};function isColumnIssue(e){return e===`column-definition-drift`||e===`missing-column`||e===`unexpected-column`}function defaultIssueMessage(e,t){let n=isColumnIssue(e)?t.split(`.`,1)[0]:t;return`${yn[e]} ${n}`}function createSqliteSchemaIssue(e,t,n){return{code:e,objectName:t,message:n??defaultIssueMessage(e,t)}}function legacySqliteSchemaIssueMessages(e){let t=new Set(e.filter(e=>isColumnIssue(e.code)).map(e=>e.objectName.split(`.`,1)[0]));return[...new Set(e.filter(e=>e.code!==`table-constraint-drift`||!t.has(e.objectName)).map(e=>e.message))]}function throwSqliteSchemaMismatches(e,t){let n=t.slice(0,8);throw t.length>n.length&&n.push(`${t.length-n.length} additional mismatch(es)`),new SqliteSchemaMismatchError(`SQLite schema is incomplete or noncanonical for ${e}: ${n.join(`; `)}; run openclaw doctor --fix to repair it.`)}const bn=/* @__PURE__ */ new WeakMap;function readCanonicalTableDefinition(e,t){if(!/^CREATE TABLE\b/iu.test(e)||At(e,/\bAS\b/giu))return;let n=lt(e,t);return[...n.columns.values()].every(e=>{let t=jt(e,0);return t?.keyword!==`CONSTRAINT`&&/^[a-z_][a-z0-9_]*$/u.test(t?.raw??``)})?n:void 0}function tableHasColumn(e,t,n){return readTableColumns(e,t).has(n)}function readTableColumns(e,t){if(y(e))return new Set(Ee(e)?.catalog.flatMap(e=>e.table===t&&e.kind===`column`&&e.value&&typeof e.value==`object`&&`name`in e.value&&typeof e.value.name==`string`?[e.value.name]:[])??[]);let n=Xe(e),r=n?.tableSql.get(t);if(n&&!r&&![...n.tables,...n.views].some(e=>e.toLowerCase()===t.toLowerCase()))return/* @__PURE__ */ new Set;if(n&&r){let e=bn.get(n),i=e?.get(t);if(i)return i;let a=readCanonicalTableDefinition(r,t);if(a){let r=new Set(a.columns.keys());return e||(e=/* @__PURE__ */ new Map,bn.set(n,e)),e.set(t,r),r}}let i=e.prepare(`PRAGMA table_info(${t})`).all();return new Set(i.flatMap(e=>typeof e.name==`string`?[e.name]:[]))}function classifySqliteTableReadError(e,t,n,r){if(y(e)||De(r)!==1)return r;try{let i=readTableColumns(e,t);if(i.size>0&&n.some(e=>!i.has(e)))return new SqliteSchemaMismatchError(`SQLite table ${t} is missing required columns; run openclaw doctor --fix to repair it.`,{cause:r})}catch{}return r}function tablePrimaryKeyColumns(e,t){if(y(e)){let n=Ee(e)?.catalog.find(e=>e.table===t&&e.kind===`primaryKey`)?.value;return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}let n=Xe(e)?.tableSql.get(t),r=n&&readCanonicalTableDefinition(n,t);if(r){let e=r.constraints.find(e=>{let t=jt(e,0);return t&&Ft(e,t)===`PRIMARY`});if(!e)return[...r.columns].flatMap(([e,t])=>At(t,/\bPRIMARY\s+KEY\b/giu)?[e]:[]);let t=Mt(e,`(`),n=kt(e.slice(t+1,Pt(e,t))).map(e=>Nt(jt(e,0)?.raw??``));if(n.every(e=>r.columns.has(e)))return[...new Set(n)]}return e.prepare(`PRAGMA table_info(${t})`).all().filter(e=>Number(e.pk??0)>0&&typeof e.name==`string`).toSorted((e,t)=>Number(e.pk??0)-Number(t.pk??0)).map(e=>e.name)}function tableExists(e,t){if(y(e))return Ee(e)?.catalog.some(e=>e.table===t&&e.kind===`table`)??!1;let n=Xe(e);return n?n.tables.has(t):it(e,`SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?`,[t],e=>e.get(t))?.ok===1}function ensureColumn(e,t,n){let r=n.trim().split(/\s+/,1)[0];return!r||!tableExists(e,t)||tableHasColumn(e,t,r)?!1:(e.exec(`ALTER TABLE ${t} ADD COLUMN ${n};`),!0)}const xn={name:`agent.schema-metadata`,lifetime:`process`,schemaDependent:!0,read(e){if(!(typeof e!=`object`||!e||!(`agentId`in e)||e.agentId!==null&&typeof e.agentId!=`string`||!(`role`in e)||e.role!==null&&typeof e.role!=`string`||!(`schemaVersion`in e)||e.schemaVersion!==null&&typeof e.schemaVersion!=`number`))return{agentId:e.agentId,role:e.role,schemaVersion:e.schemaVersion}}};function schemaMetadataKey(e){return{name:`agent.schema-metadata:${e}`,read:xn.read}}function publishAgentSchemaMetadata(e,t){Be(e,xn,t);let n=Xe(e);n&&Be(e,schemaMetadataKey(n.admissionId),t)}function readExistingAgentSchemaMeta(e){let t=Xe(e),n=t&&tt(e,schemaMetadataKey(t.admissionId));if(n)return n;let r=!t||tt(e,fe)?.admissionId===t.admissionId?tt(e,xn):void 0;if(r)return t&&Be(e,schemaMetadataKey(t.admissionId),r),r;if(!tableExists(e,`schema_meta`))return null;let i;try{i=e.prepare(`SELECT role, schema_version, agent_id FROM schema_meta WHERE meta_key = 'primary'`).get()}catch(t){throw classifySqliteTableReadError(e,`schema_meta`,[`meta_key`,`role`,`schema_version`,`agent_id`],t)}if(!i)return null;let a={agentId:ee(i.agent_id),role:typeof i.role==`string`?i.role:null,schemaVersion:typeof i.schema_version==`number`?i.schema_version:null},o=t&&Xe(e)===t;return y(e)||o&&tt(e,fe)?.admissionId===t.admissionId?publishAgentSchemaMetadata(e,a):o&&Be(e,schemaMetadataKey(t.admissionId),a),a}const Sn=1e3,Cn=1e3,wn=Symbol.for(`openclaw.sqliteAbortedTransaction`);function assertTransactionUsable(e){if(y(e))return;let t=e[wn];if(t)throw t.error}const Tn=g(`sqlite/transaction`),En=o(Symbol.for(`openclaw.sqliteWriteAdmissionServices`),()=>/* @__PURE__ */ new Map),Dn=/* @__PURE__ */ new WeakMap;function writeAdmissionLocation(e){let t=Dn.get(e);if(t!==void 0)return t;let n=e.location(),r=n===null?null:xe(n);return Dn.set(e,r),r}function retainSqliteWriteAdmissionService(e,t){let n=[...new Set(e.map(xe))].map(e=>{let n=En.get(e)??/* @__PURE__ */ new Set,retained=()=>t();return n.add(retained),En.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&&En.get(e)===t&&En.delete(e)}}function execNativeBegin(e,t){let n=Date.now();t.nativeAttempts+=1;try{e.exec(`BEGIN IMMEDIATE`)}finally{t.nativeMs+=Date.now()-n}}function beginImmediateTransaction(e,t){let n=En.size>0?writeAdmissionLocation(e):null,r=n===null?void 0:En.get(n);if(!r){execNativeBegin(e,t);return}let i=performance.now()+Ge(e);for(;;)try{Me(e,Math.min(25,Math.max(0,Math.ceil(i-performance.now()))),()=>execNativeBegin(e,t));return}catch(e){if(!ue(e)||performance.now()>=i)throw e;for(let e of r){let n=Date.now();t.serviceCalls+=1;try{e()}finally{t.serviceMs+=Date.now()-n}}if(performance.now()>=i)throw e}}function assertSyncTransactionResult(e){if(Le(e))throw Error(`SQLite write transactions must be synchronous; Promise returns are not supported.`)}function slowBusyWaitThresholdMs(e){return e?.busyTimeoutMs===void 0||e.busyTimeoutMs<=0?Sn:Math.min(Sn,e.busyTimeoutMs)}function transactionDiagnosticLabels(e,t){let n=t?.databaseLabel;if(!n)try{n=e?e.location()??`:memory:`:`unavailable`}catch{n=`unavailable`}return{database:n,operation:t?.operationLabel||ie()?.operation||`unlabeled`,...t?.diagnosticContext?{context:{...t.diagnosticContext}}:{}}}function logTransactionStep(e,t){try{if(!t&&e.elapsedMs<slowBusyWaitThresholdMs(e.options))return;let n=t?Se(t.error):void 0,r=t?De(t.error):void 0;(e.options?.logger??Tn).warn(t?`SQLite transaction lock wait failed`:`slow SQLite transaction step`,{async:!1,...e.options?.busyTimeoutMs===void 0?{}:{busyTimeoutMs:e.options.busyTimeoutMs},...transactionDiagnosticLabels(e.db,e.options),...t?{code:le(t.error)}:{},elapsedMs:e.elapsedMs,...t?{failureKind:`lock-contention`}:{},isMainThread:qt,pid:process.pid,...n===void 0?{}:{sqliteErrcode:n},...r===void 0?{}:{sqlitePrimaryCode:r},step:e.step,threadId:Jt,...e.beginAdmission?{beginAdmission:{...e.beginAdmission}}:{}})}catch{}}function execTimedTransactionStep(e){let t=Date.now(),n=e.sql===`BEGIN IMMEDIATE`?{nativeAttempts:0,nativeMs:0,serviceCalls:0,serviceMs:0}:void 0;try{n?beginImmediateTransaction(e.db,n):e.db.exec(e.sql);let r=Date.now()-t;return logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:r,options:e.options,step:e.step}),r}catch(r){let i=Date.now()-t;throw ue(r)&&ct(e.db)&&(e.step!==`begin`||e.options?.beginLockFailureReporting!==`suppress`)&&logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:i,options:e.options,step:e.step},{error:r}),r}}function discardUnsafeConnection(e,t){let n={error:t};e[wn]??=n;try{ae(e,t)}catch(t){throw e[wn]===n&&(n.error=t),t}finally{Qe(e);try{e.close()}catch{}}}function abortImmediateTransaction(e,t,n){if(!e[wn]){if(!n&&e.isOpen&&!e.isTransaction)ae(e,t,`rolled-back`);else try{e.exec(`ROLLBACK`)}catch{discardUnsafeConnection(e,t)}}}function runSqliteTransactionSync(e,t,n,r){if(e.isTransaction){e.exec(`SAVEPOINT openclaw_tx_nested`);try{let n=he(e,t);return assertSyncTransactionResult(n),assertTransactionUsable(e),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`),n}catch(t){let n=e[wn];if(n)throw n.error;try{e.exec(`ROLLBACK TO SAVEPOINT openclaw_tx_nested`),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`)}catch{discardUnsafeConnection(e,t)}throw t}}let i=me(),a=i?Date.now()-i.preparedAtMs:void 0,o=execTimedTransactionStep({db:e,options:r,sql:n===`immediate`?`BEGIN IMMEDIATE`:`BEGIN`,step:`begin`});return i&&(i.transactions.count+=1),settleSqliteTransactionSync(e,t,n,o,a,r)}function settleSqliteTransactionSync(e,t,n,r,i,a,o=!1){let s=me(),c=Date.now(),l=s?.hostAdmissionWaitMs??0,u=s?.databaseAdmissionWaitMs??0,d=0,commit=()=>{let t=Date.now(),n=s?.databaseAdmissionWaitMs??0;try{Je(e),execTimedTransactionStep({db:e,options:a,sql:`COMMIT`,step:`commit`})}finally{d+=Date.now()-t-((s?.databaseAdmissionWaitMs??0)-n)}},f=!1;try{let n=o?t():he(e,t);return assertSyncTransactionResult(n),assertTransactionUsable(e),f=!0,a?.withCommit?assertSyncTransactionResult(a.withCommit(commit)):commit(),n}catch(t){throw abortImmediateTransaction(e,t,f),assertTransactionUsable(e),t}finally{try{let t=Date.now()-c,o=(s?.hostAdmissionWaitMs??0)-l,f=(s?.databaseAdmissionWaitMs??0)-u;t<(a?.slowTransactionHoldMs??Cn)||(a?.logger??Tn).warn(`slow SQLite transaction hold`,{async:!1,callbackKind:`application-transaction`,...transactionDiagnosticLabels(e,a),elapsedMs:t,phases:{prepareMs:i,beginMs:r,sqlMs:Math.max(0,t-o-f-d),hostAdmissionWaitMs:o,databaseAdmissionWaitMs:f,commitMs:d},isMainThread:qt,mode:n,pid:process.pid,threadId:Jt,thresholdMs:a?.slowTransactionHoldMs??Cn})}catch{}finally{s&&(s.preparedAtMs=Date.now())}}}function runSqliteDeferredTransactionSync(e,t,n){return y(e)?e.runTransaction(t,n):(assertTransactionUsable(e),pe(e,()=>runSqliteTransactionSync(e,t,`deferred`,n)))}function runSqliteReadSnapshotSync(e,t,n){if(y(e)){if(e.isTransaction){let e=t();return assertSyncTransactionResult(e),e}return e.runTransaction(t,n,!0)}if(assertTransactionUsable(e),!e.isTransaction)return runSqliteDeferredTransactionSync(e,t,n);let r=he(e,t);return assertSyncTransactionResult(r),assertTransactionUsable(e),r}function runSqliteImmediateTransactionSync(e,t,n){return y(e)?e.runTransaction(t,n):(assertTransactionUsable(e),pe(e,()=>runSqliteTransactionSync(e,t,`immediate`,n)))}function runSqliteSingleStatementSync(e,t){return y(e)?e.runTransaction(t):(assertTransactionUsable(e),pe(e,()=>{let n=En.size>0?writeAdmissionLocation(e):null;if(e.isTransaction||n!==null&&En.has(n))return runSqliteTransactionSync(e,t,`immediate`);let r=he(e,t);return assertSyncTransactionResult(r),r}))}const On=o(Symbol.for(`openclaw.sessionControllerCleanupContext`),()=>({}));function runWithSessionControllerCleanup(e){return On.exit?On.exit(e):e()}const kn=g(`gateway/scheduler`),An={now:()=>Date.now(),monotonicNow:()=>performance.now(),arm:(e,t)=>{let n=setTimeout(()=>{v(`scheduler:wake`,()=>{e()})},t);return n.unref(),()=>clearTimeout(n)}};function nextMaintenanceSlot(e,t,n){return e+(Math.floor(Math.max(0,t-e)/n)+1)*n}var GatewayScheduler=class{constructor(e={}){this.jobs=/* @__PURE__ */ new Map,this.pending=/* @__PURE__ */ new Set,this.dispatching=!1,this.fenced=!1,this.controller=new AbortController,this.clock=e.clock??An}get signal(){return this.controller.signal}now(){return this.clock.now()}get nextWakeAtMs(){let e=this.now(),t=this.clock.monotonicNow(),n=null;for(let r of this.jobs.values()){if(r.running)continue;let i=e+this.remaining(r,e,t);n=n===null?i:Math.min(n,i)}return n}scope(){let e=new AbortController,t={signal:AbortSignal.any([this.signal,e.signal]),jobs:/* @__PURE__ */ new Set},beginClose=()=>{e.abort(),gt(e.signal.reason),gt(t.signal.reason);for(let e of t.jobs)this.cancel(e)},close=()=>{beginClose();let e=[...t.jobs].flatMap(e=>e.running??[]);return e.length>0?Promise.all(e).then(()=>void 0):void 0};return{signal:t.signal,now:()=>this.now(),schedule:e=>this.scheduleOwned(e,t),beginClose,close,stop:async()=>{await close()}}}schedule(e){return this.scheduleOwned(e)}scheduleOwned(e,t){let n=`delayMs`in e,r=this.now(),i=n?r+e.delayMs:e.atMs,a=e.phase===`maintenance`?Math.max(r,Math.floor(i/1e4)*1e4):i;if(!Number.isFinite(a)||e.everyMs!==void 0&&(!Number.isFinite(e.everyMs)||e.everyMs<=0))throw Error(`Invalid Gateway schedule: ${e.id}`);let o=this.fenced||t?.signal.aborted===!0,s=o?void 0:this.jobs.get(e.id),c={id:e.id,diagnosticName:`scheduler:${e.id.startsWith(`maintenance:`)?e.id.split(`:`).slice(0,3).join(`:`):e.id.split(/[:/]/u,1)[0]}`,run:e.run,everyMs:e.everyMs,phase:e.phase,atMs:a,elapsedAtMs:e.phase!==`maintenance`&&(n||e.everyMs!==void 0)?this.clock.monotonicNow()+Math.max(0,a-r):void 0,context:zt(()=>runWithSessionControllerCleanup(()=>Yt.snapshot())),cancelled:o,owner:t};e.mode===`earliest`&&s&&!s.running&&(c.atMs=Math.min(c.atMs,s.atMs),e.phase!==`maintenance`&&s.elapsedAtMs!==void 0&&(c.elapsedAtMs=c.elapsedAtMs===void 0?s.elapsedAtMs:Math.min(c.elapsedAtMs,s.elapsedAtMs)));let cancel=()=>this.cancel(c);return o||(t?.jobs.add(c),this.jobs.set(c.id,c),s&&this.cancel(s),this.arm()),{get atMs(){return c.atMs},cancel,stop:async()=>{cancel(),await c.running}}}cancel(e){e.cancelled=!0,e.running||e.owner?.jobs.delete(e),this.jobs.get(e.id)===e&&(this.jobs.delete(e.id),this.arm())}fence(){this.fenced=!0,this.cancelTimer?.(),this.cancelTimer=void 0;for(let e of this.jobs.values())this.cancel(e);this.jobs.clear()}beginClose(){this.fence(),this.controller.abort(),gt(this.controller.signal.reason)}async stop(){this.beginClose(),await Promise.all(this.pending)}remaining(e,t,n){let r=e.atMs-t;return e.elapsedAtMs===void 0?r:Math.min(r,e.elapsedAtMs-n)}arm(){if(this.fenced||this.dispatching)return;this.cancelTimer?.(),this.cancelTimer=void 0;let e=this.nextWakeAtMs;if(e!==null){let t=this.now(),n=Math.min(2147483647,Math.max(0,Math.ceil(e-t)));this.cancelTimer=i(()=>this.clock.arm(()=>this.wake(t+n),n))}}wake(e){if(this.cancelTimer=void 0,this.fenced)return;let t=this.now(),n=this.clock.monotonicNow(),r=[...this.jobs.values()].filter(e=>!e.running&&this.remaining(e,t,n)<=0).toSorted((e,r)=>this.remaining(e,t,n)-this.remaining(r,t,n)),i;t-e>6e4&&kn.debug(`late wake by ${t-e}ms; coalescing ${r.length} due jobs`),this.dispatching=!0;try{for(let e of r){if(this.fenced||e.cancelled||e.owner?.signal.aborted||this.jobs.get(e.id)!==e)continue;e.everyMs===void 0&&this.jobs.delete(e.id);let t=this.run(e);t&&(i??=[]).push(t)}}finally{this.dispatching=!1,this.arm()}return i?Promise.all(i).then(()=>void 0):void 0}run(e){kn[e.everyMs===void 0?`debug`:`trace`](`running ${e.id}`);let t=_t(),n=new Vt;e.running=t.promise,this.pending.add(t.promise);let finish=()=>{e.running=void 0,this.pending.delete(t.promise),e.everyMs!==void 0&&!e.cancelled&&!this.fenced?e.phase===`maintenance`?(e.atMs=Math.floor(e.atMs/1e4)*1e4,e.atMs=nextMaintenanceSlot(e.atMs,this.now(),e.everyMs)):(e.atMs=this.now()+e.everyMs,e.elapsedAtMs=this.clock.monotonicNow()+e.everyMs):e.owner?.jobs.delete(e),t.resolve(),this.arm()},r;try{r=e.context(()=>v(e.diagnosticName,()=>n.run(e.run)))}catch(t){kn.error(`${e.id} failed: ${String(t)}`)}if(!r&&!n.hasPendingWork)finish();else return Promise.resolve(r).catch(t=>kn.error(`${e.id} failed: ${String(t)}`)).then(()=>Vt.runWhenAllIdle(()=>[n],()=>n.drain())).finally(finish),t.promise}};const jn=BigInt(2**53-1);function readFiniteSqliteNumber(e){let t=typeof e==`bigint`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function coerceRequiredSqliteNumber(e){return typeof e==`bigint`?Number(e):e}function normalizeSqliteNumber(e){return typeof e==`bigint`?e>jn||e<-jn?void 0:Number(e):typeof e==`number`?e:void 0}const Mn=o(Symbol.for(`openclaw.sqliteWalCheckpointListeners`),()=>/* @__PURE__ */ new Set);function observeSqliteWalCheckpointHealth(e,t){let{activeReaders:n,readerDiagnostics:r,...i}=t;if(t.state===`complete`)return i;let{activeReaders:a,...o}=qe(e);return{...i,activeReaders:[...(n??[]).filter(e=>e.threadId!==o.threadId),...a].toSorted((e,t)=>t.ageMs-e.ageMs).slice(0,8),readerDiagnostics:[...(r??[]).filter(e=>e.threadId!==o.threadId),o].slice(-8)}}function notifyCheckpoint(e,t){for(let n of Mn)try{n({databasePath:Ke(e),health:structuredClone(t.health),observedAtNs:t.observedAtNs,lastCompletedAtNs:t.lastCompletedAtNs})}catch{}}function sqliteFileBytes(e){try{return b.statSync(e).size}catch(e){if(l(e,`ENOENT`))return 0;throw e}}function readCheckpointResult(e){let[t,n,r]=Object.values(e??{}).map(e=>normalizeSqliteNumber(typeof e==`number`||typeof e==`bigint`?e:null));if(t===void 0||n===void 0||r===void 0)throw Error(`SQLite returned an invalid WAL checkpoint result`);return{busy:t,logFrames:n,checkpointedFrames:r}}function checkpoint(e,t){return e.prepare(`PRAGMA wal_checkpoint(${t});`).get()}var SqliteWalCheckpointBusyError=class extends Error{};function truncateSqliteWal(e,t){let n=checkpoint(e,`TRUNCATE`),r=readFiniteSqliteNumber(n?.busy??(n?Object.values(n)[0]:void 0));if(r===void 0)throw Error(`SQLite checkpoint returned an invalid result for ${t}.`);if(r!==0)throw new SqliteWalCheckpointBusyError(`SQLite checkpoint remained busy for ${t}. Stop OpenClaw and retry.`)}function createSqliteWalCheckpoint(e,t,n){let r,checkpointObservation=()=>({state:`error`,observedAtMs:Date.now(),walBytes:null,databaseBytes:null,logFrames:null,checkpointedFrames:null,lastCompletedAtMs:r?.health.lastCompletedAtMs??null,consecutiveBlocked:0,warning:!0}),recordCheckpointError=(e,n=checkpointObservation())=>{let i={...n,observedAtMs:Date.now(),state:`error`,consecutiveBlocked:0,warning:!0,error:It(e)};r={observedAtNs:process.hrtime.bigint(),lastCompletedAtNs:r?.lastCompletedAtNs,health:t.databasePath?observeSqliteWalCheckpointHealth(t.databasePath,i):i},t.databasePath&&notifyCheckpoint(t.databasePath,r),t.onCheckpointError?.(e)},recordCheckpoint=(e,i,a)=>{let o=process.hrtime.bigint(),s=checkpointObservation(),c,l;try{let{busy:e,logFrames:a,checkpointedFrames:u}=readCheckpointResult(i);if(c=e!==0,s.logFrames=a,s.checkpointedFrames=u,s.state=c||u<a?`blocked`:`complete`,s.state===`complete`?s.lastCompletedAtMs=s.observedAtMs:s.consecutiveBlocked=(r?.health.consecutiveBlocked??0)+1,t.databasePath)try{s.databaseBytes=sqliteFileBytes(t.databasePath),s.walBytes=sqliteFileBytes(`${t.databasePath}-wal`)}catch(e){l=e,s.error=It(e)}s.warning=s.state===`blocked`&&(s.consecutiveBlocked>=2||s.walBytes!==null&&s.databaseBytes!==null&&s.walBytes>Math.max(2*s.databaseBytes,n)),r={observedAtNs:o,lastCompletedAtNs:s.state===`complete`?o:r?.lastCompletedAtNs,health:t.databasePath?observeSqliteWalCheckpointHealth(t.databasePath,s):s},t.databasePath&&notifyCheckpoint(t.databasePath,r)}catch(e){return recordCheckpointError(e,s),!1}if(s.error!==void 0&&t.onCheckpointError?.(l),s.warning&&!a){let n=t.databaseLabel??`sqlite database`;t.onCheckpointError?.(/* @__PURE__ */ Error(`${n} WAL checkpoint ${e} ${c?`remained busy`:`blocked by a reader`}`))}return s.state===`complete`};return{adopt(e){if(r&&r.observedAtNs>=e.observedAtNs&&(r.lastCompletedAtNs??0n)>=(e.lastCompletedAtNs??0n))return;let n=(r?.lastCompletedAtNs??0n)>(e.lastCompletedAtNs??0n)?r:e;(!r||e.observedAtNs>r.observedAtNs)&&(r=structuredClone(e)),r.lastCompletedAtNs=n?.lastCompletedAtNs,r.health.lastCompletedAtMs=n?.health.lastCompletedAtMs??null,t.databasePath&&(r.health=observeSqliteWalCheckpointHealth(t.databasePath,r.health),notifyCheckpoint(t.databasePath,r))},checkpoint(t,n={}){try{return recordCheckpoint(t,checkpoint(e,t),n.quiet===!0)}catch(e){return recordCheckpointError(e),!1}},recordError:recordCheckpointError,inspectIdle(){let{busy:t,logFrames:n,checkpointedFrames:r}=readCheckpointResult(checkpoint(e,`PASSIVE`));return t===0&&n>=0&&r>=0&&r<=n},get health(){return r?structuredClone(r.health):void 0},get snapshot(){return r?structuredClone(r):void 0}}}const Nn=/\\([0-7]{3})/g;function decodeMountInfoPath(e){return e.replace(Nn,(e,t)=>String.fromCharCode(Number.parseInt(t,8)))}const Pn=/* @__PURE__ */ new Set([.../* @__PURE__ */ new Set([26985,20859,4283649346,4266872130]),16914839]),Fn=1e3,In=/* @__PURE__ */ new Set([`cifs`,`smbfs`,`smb2`,`smb3`]),Ln=/* @__PURE__ */ new Set([`virtiofs`,`fuse.virtiofs`,`9p`,`9p2000.l`]),Rn=g(`infra/sqlite-wal`);let zn=!1;function findExistingVolumePaths(e){let t=x.resolve(e);for(;;){let e;try{e=b.statSync(t)}catch{let e=x.dirname(t);if(e===t)return null;t=e;continue}let n=b.realpathSync(t);return{canonicalPath:e.isDirectory()?n:x.dirname(n),originalPath:e.isDirectory()?t:x.dirname(t)}}}function parseProcMountInfoEntries(e){let t=[];for(let n of e.split(`
`)){let e=n.indexOf(` - `);if(e===-1)continue;let r=n.slice(0,e).split(` `),i=n.slice(e+3).split(` `),a=r[4],o=i[0];a&&o&&t.push({mountPoint:decodeMountInfoPath(a),fsType:o,...i[1]?{source:decodeMountInfoPath(i[1])}:{}})}return t}function parseMountCommandEntries(e){let t=[];for(let n of e.split(`
`)){let e=/^(.+) on (.+) type ([^,\s)]+) \(/.exec(n)??/^(.+) on (.+) \(([^,\s)]+)/.exec(n);if(e){let[,n,r,i]=e;n&&r&&i&&t.push({source:n,mountPoint:r,fsType:i})}}return t}function readMountEntries(){try{return{ok:!0,value:parseProcMountInfoEntries(b.readFileSync(`/proc/self/mountinfo`,`utf8`))}}catch{}try{return{ok:!0,value:parseMountCommandEntries(String(process.getBuiltinModule(`node:child_process`).execFileSync(`mount`,[],{killSignal:`SIGKILL`,timeout:Fn})))}}catch(e){return l(e,`ETIMEDOUT`)?{ok:!1,error:`timeout`}:{ok:!0,value:[]}}}function isPathWithinMount(e,t){let n=x.resolve(e),r=x.resolve(t);return n===r||r===x.parse(r).root||n.startsWith(`${r}${x.sep}`)}function isSshfsMountSource(e){if(!e)return!1;let t=e.toLowerCase();return t===`sshfs`||t.startsWith(`sshfs#`)||t.startsWith(`sshfs@`)||/^(?:[^/\s:]+@)?[^/\s:]+:.*/u.test(e)}function resolveNetworkMountJournalPolicy(e){let t=e.fsType.toLowerCase();if(t.startsWith(`nfs`)||In.has(t))return`rollback`;if(t===`fuse.sshfs`||(t===`macfuse`||t===`osxfuse`)&&isSshfsMountSource(e.source))return`unsupported`}function resolveMountTypeJournalPolicy(e){let t=e.fsType.toLowerCase();return resolveNetworkMountJournalPolicy(e)??(Ln.has(t)||t.startsWith(`9p`)?`rollback`:`wal`)}function findMountEntry(e,t){return t.filter(t=>isPathWithinMount(e,t.mountPoint)).toSorted((e,t)=>t.mountPoint.length-e.mountPoint.length)[0]}function resolveMountEntryJournalPolicy(e,t){let n=findMountEntry(e,t);return n?resolveMountTypeJournalPolicy(n):`wal`}function isSqlitePathOnBtrfs(e){if(process.platform!==`linux`)return!1;let t=findExistingVolumePaths(e);if(!t)return!1;try{return b.statfsSync(t.canonicalPath).type===2435016766}catch{let e=readMountEntries();return e.ok&&findMountEntry(t.canonicalPath,e.value)?.fsType.toLowerCase()===`btrfs`}}function setSqliteDirectoryNoCow(e){if(!b.statSync(e).isDirectory())throw Error(`SQLite NOCOW target is not a directory: ${e}`);let t=process.getBuiltinModule(`node:child_process`).spawnSync(`chattr`,[`+C`,e],{encoding:`utf8`,killSignal:`SIGKILL`,timeout:Fn,maxBuffer:4096});if(t.error||t.status!==0)throw t.error??/* @__PURE__ */ Error(`chattr +C failed: ${t.stderr.trim()||t.signal||t.status}`)}function prepareSqliteDatabaseDirectory(e){if(!(process.platform!==`linux`||b.existsSync(e)))try{isSqlitePathOnBtrfs(e)&&setSqliteDirectoryNoCow(x.dirname(e))}catch(t){zn||(zn=!0,Rn.warn(`Could not enable SQLite directory NOCOW; continuing with filesystem defaults`,{databasePath:e,error:t instanceof Error?t.message:String(t)}))}}function combineMountEntryJournalPolicies(e){let t=readMountEntries();if(!t.ok){let[t,n]=e;if(process.platform===`darwin`&&t===n)try{if(_n(n)===`apfs`)return`wal`}catch{}return`rollback`}let n=new Set(e.map(e=>resolveMountEntryJournalPolicy(e,t.value)));return n.has(`unsupported`)?`unsupported`:n.has(`rollback`)?`rollback`:`wal`}function isWindowsUncPath(e){return/^\\\\\?\\UNC\\[^\\]+\\[^\\]+/i.test(e)||/^\\\\(?![?.]\\)[^\\]+\\[^\\]+/.test(e)}function isWindowsDrivePath(e){return/^[A-Za-z]:[\\/]/.test(e)||/^\\\\\?\\[A-Za-z]:[\\/]/i.test(e)}function resolvePathJournalPolicy(e){if(process.platform===`win32`){let t=x.win32.normalize(e);if(isWindowsUncPath(t))return`rollback`;if(isWindowsDrivePath(t))try{return isWindowsUncPath(x.win32.normalize(b.realpathSync.native(e)))?`rollback`:`wal`}catch{return`rollback`}}let t=findExistingVolumePaths(e);if(!t)return`wal`;let n=[t.originalPath,t.canonicalPath];try{if(Pn.has(b.statfsSync(t.canonicalPath).type))return`rollback`}catch{}return combineMountEntryJournalPolicies(n)}const Bn=/* @__PURE__ */ new WeakMap;function createSqliteWalReclamationResult(){return{checkpointCompleted:!1,freePagesBefore:null,remainingFreePages:null,checkpointCalls:0,checkpointIncomplete:0,checkpointMs:0,checkpointMaxMs:0,queryMs:0,vacuumMs:0,vacuumPasses:0,vacuumPagesRequested:0}}function readSqliteFreePageCount(e,t){let n=t?an.now():0;try{return Number(e.prepare(`PRAGMA freelist_count`).get()?.freelist_count??0)}finally{t&&(t.queryMs+=an.now()-n)}}function reclaimSqliteWalFreePages(e,t,n){let r=createSqliteWalReclamationResult(),checkpoint=()=>{n.beforeMutation?.();let e=an.now();try{let e=n.checkpointMode??`TRUNCATE`,i=t(e);return r.checkpointCalls++,!i&&e===`TRUNCATE`&&(n.beforeMutation?.(),i=t(`PASSIVE`),r.checkpointCalls++),r.checkpointCompleted=i,r.checkpointIncomplete+=Number(!i),i}finally{let t=an.now()-e;r.checkpointMs+=t,r.checkpointMaxMs=Math.max(r.checkpointMaxMs,t)}};return n.maxPages===0&&n.checkpointMode===`PASSIVE`?(checkpoint(),r):Me(e,0,()=>{if(!checkpoint()||n.maxPages===0)return r;let t=readSqliteFreePageCount(e,r);if(r.freePagesBefore=t,r.remainingFreePages=t,!Number.isSafeInteger(t)||t<=0)return r;let i=Math.min(Bn.get(e)??8,t,n.maxPages??512);if(!Number.isSafeInteger(i)||i<=0)throw Error(`SQLite page reclamation requires a positive integer page limit`);let a=an.now(),o=!1,s=!1;try{runSqliteImmediateTransactionSync(e,()=>{o=!0,n.beforeMutation?.(),r.vacuumPasses++,r.vacuumPagesRequested+=i,e.exec(`PRAGMA incremental_vacuum(${i});`),n.onCommit?.()},{beginLockFailureReporting:`suppress`,busyTimeoutMs:0,operationLabel:`incremental-vacuum`}),s=!0}catch(e){if(o||!ue(e))throw e;return r}finally{let t=an.now()-a;r.vacuumMs+=t,s&&Bn.set(e,Math.max(1,Math.min(512,i*2,Math.floor(i*25/Math.max(t,.001)))))}return n.afterCommit?.(),checkpoint()&&(r.remainingFreePages=readSqliteFreePageCount(e,r)),r})}const Vn=`/proc/self/fd`;async function readUnlessMissing(e,t=!1){try{return await e()}catch(e){if(t&&l(e,`EBADF`)||l(e,`ENOENT`))return;throw e}}function isSqliteWalSidecarSplitBrain(e,t){return e.nlink===0n||!t||e.dev!==t.dev||e.ino!==t.ino}async function detectSqliteWalSplitBrain(e){let t=await readUnlessMissing(()=>b.promises.readdir(Vn)),n=[`${e}-wal`,`${e}-shm`];for(let r of t??[]){let t=x.join(Vn,r),i=await readUnlessMissing(()=>b.promises.readlink(t));if(i===void 0)continue;let a=n.find(e=>i===e||i===`${e} (deleted)`);if(!a)continue;let o=await readUnlessMissing(()=>rn(b.fstat)(Number(r),{bigint:!0}),!0);if(o===void 0||await readUnlessMissing(()=>b.promises.readlink(t))!==i)continue;let s=await readUnlessMissing(()=>b.promises.stat(a,{bigint:!0}));if(!isSqliteWalSidecarSplitBrain(o,s))continue;let c=await readUnlessMissing(()=>rn(b.fstat)(Number(r),{bigint:!0}),!0);if(c&&c.dev===o.dev&&c.ino===o.ino&&await readUnlessMissing(()=>b.promises.readlink(t))===i)return{event:`sqlite_wal_sidecar_identity_mismatch`,databasePath:e,descriptorDevice:o.dev.toString(),descriptorInode:o.ino.toString(),sidecarPath:a,...s?{targetDevice:s.dev.toString(),targetInode:s.ino.toString()}:{}}}}function terminateForSqliteWalSplitBrain(e,t){try{b.writeSync(2,`${JSON.stringify({level:`fatal`,subsystem:`infra/sqlite-wal`,message:`SQLite WAL sidecar identity mismatch; terminating without SQLite cleanup`,...e,databaseLabel:t,pid:process.pid})}\n`)}catch{}try{process.kill(process.pid,`SIGKILL`)}finally{process.abort()}}const Hn=o(Symbol.for(`openclaw.sqliteWalWriteAdmissions`),()=>/* @__PURE__ */ new WeakMap);function registerSqliteWalWorkerMaintenance(e,t,n){e.exec(`PRAGMA wal_autocheckpoint = 0;`);let r=Hn.get(e)?.stopCheckpointTick;Hn.set(e,{execute:t,cancel:n}),r?.()}function isSqliteWalWorkerMaintained(e){return Hn.get(e)?.execute!==void 0}function cancelSqliteWalWriteAdmission(e){return Hn.get(e)?.cancel?.()}function createSqliteWalMaintenanceScheduler(e,t,n,r,i,a,o){let s=Hn.get(e);Hn.set(e,{...s,stopCheckpointTick:o});let c;return()=>(c||=(async()=>{let i=a(),o=!1;for(;;){let a=n(i);if(!a||i===0&&Hn.get(e)?.execute)return;a.continuation=o;let s,admitted=()=>{n(i)&&(s=t(a))},c=Hn.get(e);c?.execute?(s=await c.execute(a),s?.checkpoint&&r(s.checkpoint)):c?.admit?await c.admit(admitted):admitted();let l=s?.reclaimedPages??0;if(i-=l,l<=0||i<=0)return;o=!0,await gn()}})().catch(i).finally(()=>{c=void 0}),c)}const Un=1e4,Wn=67108864,Gn=new Int32Array(new SharedArrayBuffer(4)),Kn=g(`infra/sqlite-wal`),qn=new GatewayScheduler;let Jn=0;const Yn={name:`sqlite-wal-completed-write-revision`,read:e=>e instanceof SharedArrayBuffer&&e.byteLength===Int32Array.BYTES_PER_ELEMENT?e:void 0};function sharedCompletedCheckpoint(e,t){let n=tt(e,Yn);return n||=(n=new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT),Atomics.store(new Int32Array(n),0,t-1|0),Be(e,Yn,n),tt(e,Yn)),n?new Int32Array(n):void 0}function enableIncrementalAutoVacuumForFreshDatabase(e){let t=e.location(),n=t?Re(t,fe):void 0;n&&(n.userVersion>0||n.tables.size>0||n.views.size>0)||e.prepare(`PRAGMA page_count`).get()?.page_count===0&&e.exec(`PRAGMA auto_vacuum = INCREMENTAL;`)}function configureSqlitePreSchemaPragmas(e,t={}){t.busyTimeoutMs!==void 0&&nt(e,t.busyTimeoutMs),enableIncrementalAutoVacuumForFreshDatabase(e)}function readJournalModeResult(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.journal_mode??Object.values(t)[0];return typeof n==`string`?n.toLowerCase():null}function hasInMemoryMainDatabase(e){return e.prepare(`PRAGMA database_list;`).all().find(e=>e.name===`main`)?.file===``}function requireRollbackJournalMode(e,t){let n=readJournalModeResult(e.prepare(`PRAGMA journal_mode = DELETE;`).get());if(n!==`delete`){let e=t.databaseLabel??`sqlite database`,r=t.databasePath?` at ${t.databasePath}`:``;throw Error(`${e}${r} is on a network-backed volume but SQLite kept journal_mode=${n??`unknown`}; refusing to continue with WAL on network storage.`)}}function enableWalJournalMode(e,t,n){let r=an.now()+t,i=!1;try{for(;;)try{let t=readJournalModeResult(e.prepare(`PRAGMA journal_mode = WAL;`).get());if(t===`wal`)return!0;if(t===`memory`&&hasInMemoryMainDatabase(e))return!1;let r=n.databaseLabel??`sqlite database`,i=n.databasePath?` at ${n.databasePath}`:``;throw Error(`${r}${i} could not enable WAL; SQLite kept journal_mode=${t??`unknown`}.`)}catch(t){let n=Math.max(0,r-an.now());if(!ue(t)||n<=0)throw t;i||=(nt(e,0),!0),Atomics.wait(Gn,0,0,Math.min(10,n))}}finally{i&&nt(e,t)}}function enableMacosCheckpointFullfsync(e){if(process.platform===`darwin`)try{e.exec(`PRAGMA checkpoint_fullfsync = 1;`)}catch{}}function refuseUnsupportedFilesystem(e){let t=e.databaseLabel??`sqlite database`,n=e.databasePath?` at ${e.databasePath}`:``;throw Error(`${t}${n} is on SSHFS, which cannot safely coordinate SQLite writes across mounts; refusing to open the database.`)}function configureSqliteWalMaintenance(e,t={}){let n=t.busyTimeoutMs??0;t.busyTimeoutMs!==void 0&&nt(e,t.busyTimeoutMs);let r=ot(t.autoCheckpointPages??16384,`autoCheckpointPages`),o=ot(t.checkpointIntervalMs??18e5,`checkpointIntervalMs`),s=Math.min(o,a),c=o>Un?Un:0,l=t.checkpointMode??`TRUNCATE`,u=t.checkpointMode??`PASSIVE`,d=t.databasePath?resolvePathJournalPolicy(t.databasePath):`wal`;if(d===`unsupported`&&refuseUnsupportedFilesystem(t),d===`rollback`&&requireRollbackJournalMode(e,t),d===`rollback`||!enableWalJournalMode(e,n,t))return{checkpoint:()=>!0,reclaimFreePages:(t={})=>reclaimSqliteWalFreePages(e,()=>!0,t),stop:async()=>{},close:()=>!0};enableMacosCheckpointFullfsync(e),e.exec(`PRAGMA wal_autocheckpoint = ${isSqliteWalWorkerMaintained(e)?0:r};`),e.exec(`PRAGMA journal_size_limit = ${Wn};`);let f=process.platform===`linux`&&t.databasePath&&b.existsSync(t.databasePath)?b.realpathSync.native(t.databasePath):void 0,p=!1,m=!1,ee=!!f,h=createSqliteWalCheckpoint(e,t,Wn),g=h.checkpoint,runMaintenance=e=>{if(p||m)return!1;try{return t.runMaintenance?t.runMaintenance(e):e()}catch(e){return h.recordError(e),!1}},checkpoint=()=>runMaintenance(()=>g(l)),reclaimFreePages=(t={})=>{let n,r;if(runMaintenance(()=>{try{return n=reclaimSqliteWalFreePages(e,g,t),n.checkpointCompleted}catch(e){throw r={error:e},e}}),r)throw r.error;if(!n)throw Error(`SQLite page reclamation owner is unavailable`);return{...n,checkpoint:h.snapshot}},v=qn.scope(),te=`sqlite-wal:${++Jn}`,ne=0,re,maintainPeriodic=(t,n,r)=>{if(p)return{reclaimedPages:0};t.checkpoint&&h.adopt(t.checkpoint);let i=0,a=t.maxPages===0,o=a&&t.checkpointMode===`PASSIVE`,s=o?mt(e):void 0,c=s===void 0?void 0:sharedCompletedCheckpoint(e,s),l=c!==void 0&&Atomics.load(c,0)===s;if(s!==void 0&&(l||s===re&&h.health?.state===`complete`))return{reclaimedPages:0,checkpoint:h.health?.state===`complete`?h.snapshot:void 0};let runTickCheckpoint=e=>h.checkpoint(e,{quiet:a});return re=runMaintenance(()=>{let a;if(o)n?.(`transaction`),a=runTickCheckpoint(`PASSIVE`);else{let r=reclaimSqliteWalFreePages(e,runTickCheckpoint,{checkpointMode:t.checkpointMode,maxPages:t.maxPages,beforeMutation:()=>n?.(`transaction`),onCommit:()=>n?.(`commit`)});a=r.checkpointCompleted,a&&r.freePagesBefore!==null&&r.remainingFreePages!==null&&(i=Math.min(r.vacuumPagesRequested,r.freePagesBefore-r.remainingFreePages))}if(a&&t.checkpointMode===`PASSIVE`&&(h.health?.walBytes??0)>Wn&&(n?.(`transaction`),Me(e,0,()=>runTickCheckpoint(`TRUNCATE`))),a&&t.maxPages>0&&!t.continuation)try{r?.()}catch(e){if(!ue(e))throw e}return a})&&h.health?.state===`complete`?s:void 0,c&&re!==void 0&&Atomics.store(c,0,re),{reclaimedPages:i,checkpoint:h.snapshot}},stopCheckpointTick,ie=createSqliteWalMaintenanceScheduler(e,maintainPeriodic,e=>s>0&&!v.signal.aborted&&!p&&!m&&!t.isScheduledMaintenanceSuspended?.()?{maxPages:e,checkpointMode:u,checkpoint:h.snapshot}:void 0,h.adopt,e=>h.recordError(e),()=>{let e=ne;return ne=0,e},()=>stopCheckpointTick?.()),schedule=(e,t,n)=>i(()=>v.schedule({id:`${te}:${e}`,delayMs:t,everyMs:t,run:n}));if(s>0&&schedule(`periodic`,s,async()=>{if(f&&ee){m=!0;let n=ft(e,()=>{throw Error(`SQLite WAL inspection is pending; await maintenance.stop() before close`)});try{let e;try{e=await detectSqliteWalSplitBrain(f)}catch(e){ee=!1,Kn.warn(`SQLite WAL split-brain detection disabled`,{databaseLabel:t.databaseLabel,databasePath:f,error:e instanceof Error?e.message:String(e)})}e&&(p=!0,v.beginClose(),terminateForSqliteWalSplitBrain(e,t.databaseLabel))}finally{n(),m=!1}if(v.signal.aborted)return}return ne=512,ie()}),c>0&&!isSqliteWalWorkerMaintained(e)){let t=!1,n,cancelTick=()=>{n?.cancel(),n=void 0},armTick=()=>{!t&&!n&&!v.signal.aborted&&!p&&(n=i(()=>v.schedule({id:`${te}:tick`,delayMs:c,run:runTick})))},runTick=async()=>{if(n=void 0,await ie(),t)return;let r=mt(e),i=r===void 0?void 0:sharedCompletedCheckpoint(e,r);i&&Atomics.load(i,0)===r?cancelTick():armTick()},r=u===`PASSIVE`?Fe(e,armTick):void 0;r?(stopCheckpointTick=()=>{t=!0,r(),cancelTick()},armTick()):stopCheckpointTick=schedule(`tick`,c,ie).cancel}let beginClose=()=>(stopCheckpointTick?.(),i(()=>v.beginClose()),cancelSqliteWalWriteAdmission(e));return{get health(){return h.health},checkpoint,maintainPeriodic,reclaimFreePages,inspectIdle:()=>runMaintenance(h.inspectIdle)?`healthy`:`retire`,stop:async()=>{try{await beginClose()}finally{await i(()=>v.stop())}},close:t=>(beginClose(),p||isSqliteWalWorkerMaintained(e)?!1:runMaintenance(()=>g(t?.checkpointMode??l)))}}let Xn;function detachEmptySqliteExitGroup(e){e.pending.size>0||(Xn===e&&(Xn=void 0),process.removeListener(`exit`,e.dispatch))}function registerSqliteCacheExitClose(e){let t={close:e},n=Xn;if(!n||process.listeners(`exit`).at(-1)!==n.dispatch){let e=/* @__PURE__ */ new Set([t]),r={pending:e,dispatch:()=>{let t=[...e];e.clear(),detachEmptySqliteExitGroup(r);for(let e of t)try{e.close()}catch{}}};process.on(`exit`,r.dispatch),Xn=n=r}else n.pending.add(t);let r=n;return()=>{r.pending.delete(t),detachEmptySqliteExitGroup(r)}}function configureSqliteConnectionPragmas(e,t={}){let{foreignKeys:n,synchronous:r,...i}=t,a=configureSqliteWalMaintenance(e,i);try{return r&&e.exec(`PRAGMA synchronous = ${r};`),n&&e.exec(`PRAGMA foreign_keys = ON;`),a}catch(e){try{a.close()}catch(t){throw Ze([e,t],`SQLite connection pragma configuration and WAL maintenance cleanup both failed.`,e)}throw e}}function sqliteSnapshotSourceFileSize(e){try{let t=b.statSync(e);return t.isFile()?t.size:0}catch(e){if(l(e,`ENOENT`))return 0;throw e}}function waitForSnapshotRetrySync(e){if(e+1>=10)return;let t=Math.min(80,10*2**e);t>0&&Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function finiteNonNegativeNumber(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=x.resolve(e);for(;;)try{return b.statSync(t).isDirectory()?t:x.dirname(t)}catch{let e=x.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){let t=findExistingDiskSpacePath(e);if(!t)return null;try{let n=b.statfsSync(t),r=finiteNonNegativeNumber(n.bsize),i=finiteNonNegativeNumber(n.bavail);if(r===null||i===null)return null;let a=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:r*i,totalBytes:a===null?null:r*a}}catch{return null}}function acquireSqliteSnapshotReadToken(e){return rt(e,`read`)}function sqliteSnapshotStagingError(e,t,n=!1,r){ht(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 st;let{errcode:t,path:n}=r;a||=He(r),(a||typeof t==`number`&&[13,778,1034,1290].includes(t)||`${n??``}${x.sep}`.startsWith(`${e}${x.sep}`))&&(i=!0,typeof t==`number`&&(s=t)),r=r.cause}if(!i)return t;let c=a?`free disk space/quota`:`check filesystem health and write permissions`,l=``;if(a&&r)try{let t=sqliteSnapshotSourceFileSize(r)+sqliteSnapshotSourceFileSize(`${r}-wal`)+sqliteSnapshotSourceFileSize(`${r}-journal`),n=tryReadDiskSpace(e)?.availableBytes,i=b.existsSync(`${r}-wal`)&&b.existsSync(`${r}-shm`);l=`; estimated ${t} bytes needed; ${n===void 0?`available bytes unknown`:`${n} bytes available`}; source ${i?`has live WAL sidecars`:`has no live WAL sidecars`}`}catch{}let u=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`,d=`${t instanceof Error?t.message:String(t)}${s===void 0?``:` (SQLite errcode=${s})`}; snapshot staging root ${n?e:x.dirname(e)}${l}: ${c} or set ${u} to a writable filesystem`,f=a&&!o&&Te(t)!==`source`?new We(d,{cause:t}):Error(d,{cause:t});return je(t)?pt(f):f}async function createSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){n?.throwIfAborted();try{return await allocateSqliteSnapshotStagingDirectory(e,t,n,r)}catch(e){throw e instanceof st||r&&e instanceof AggregateError||(n?.throwIfAborted(),ht(e,`snapshot`)),e}}async function allocateSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1,n,r=!1){if(n?.throwIfAborted(),r){let r=new AbortController;return ut((async()=>{let{allocateWorkerOwnedSqliteSnapshotDirectory:i}=await import(`./disk-budget.worker-sqlite-snapshot-staging-allocation-ChSGWKAi.mjs`);n?.throwIfAborted(),r.signal.throwIfAborted();let a=await i(e,t,n?AbortSignal.any([n,r.signal]):r.signal);if(Ae(a.directory),n?.aborted||r.signal.aborted){if(!await te(a.directory))throw new st(`SQLite snapshot cleanup failed: ${a.directory}`);n?.throwIfAborted(),r.signal.throwIfAborted()}return a.directory})(),()=>r.abort(/* @__PURE__ */ Error(`SQLite snapshot allocation stopped`)))}return createSqliteSnapshotStagingDirectorySync(e,t)}function createSqliteSnapshotStagingDirectorySync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n=createSqliteSnapshotStagingTokenSync(e,t);return Ae(n.directory,n.release),n.directory}function createSqliteSnapshotStagingTokenSync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=!1){let n;try{try{n=createPrivateSqliteTempDirectorySync(e,t?`openclaw-sqlite-readonly-${process.pid}-`:Ne)}catch(t){throw sqliteSnapshotStagingError(e,t,!0)}return{directory:n,release:rt(n,`create`)}}catch(e){throw n&&ge(n),e}}function readUint32(e,t,n){return n===`LE`?e.readUInt32LE(t):e.readUInt32BE(t)}function sqliteWalChecksum(e,t,n=[0,0]){let[r,i]=n;for(let n=0;n<e.length;n+=8)r=r+readUint32(e,n,t)+i>>>0,i=i+readUint32(e,n+4,t)+r>>>0;return[r,i]}const Zn=1048576;function readWalGeneration(e){let t=Buffer.alloc(32);if(cn(e,t,0)!==t.length)return;let n=t.readUInt32BE(0);if(n!==931071618&&n!==931071619)return;let r=n===931071618?`LE`:`BE`,i=t.readUInt32BE(8),[a,o]=sqliteWalChecksum(t.subarray(0,24),r);if(!(i<512||i>65536||i&i-1||t.readUInt32BE(24)!==a||t.readUInt32BE(28)!==o))return{header:t,byteOrder:r,frameBytes:24+i}}function copyCommittedWalFrames(e,t,n,r){let{header:i,byteOrder:a,frameBytes:o}=n;if(readWalGeneration(e)?.header.equals(i)!==!0)return!1;let s=i.subarray(16,24),c=[i.readUInt32BE(24),i.readUInt32BE(28)];writeFully(t,i,0);let l=32,u=Math.max(1,Math.floor(Zn/o)),d=Buffer.allocUnsafe(u*o);for(let n=32;n<r;){let i=d.subarray(0,Math.min(d.length,r-n)),u=cn(e,i,n),f=0,p=!0;for(let e=0;e+o<=u;e+=o){let t=i.subarray(e,e+o);if(t.readUInt32BE(0)===0||!t.subarray(8,16).equals(s)){p=!1;break}let r=sqliteWalChecksum(t.subarray(24),a,sqliteWalChecksum(t.subarray(0,8),a,c));if(t.readUInt32BE(16)!==r[0]||t.readUInt32BE(20)!==r[1]){p=!1;break}c=r,f=e+o,t.readUInt32BE(4)!==0&&(l=n+f)}if(f>0&&writeFully(t,i.subarray(0,f),n),!p||f<i.length)break;n+=f}return b.ftruncateSync(t,l),b.fsyncSync(t),l}function writeFully(e,t,n){for(let r=0;r<t.length;){let i=b.writeSync(e,t,r,t.length-r,n+r);if(i<=0)throw Error(`SQLite WAL snapshot write made no progress`);r+=i}}function matchesCapturedWalPrefix(e,t,n){let r=b.openSync(t,`r`);try{let t=b.fstatSync(r);if(!t.isFile()||t.size!==n)return!1;let i=Buffer.allocUnsafe(Math.min(Zn,n)),a=Buffer.allocUnsafe(i.length);for(let t=0;t<n;t+=i.length){let o=Math.min(i.length,n-t),s=i.subarray(0,o),c=a.subarray(0,o);if(cn(e,s,t)!==o||cn(r,c,t)!==o||!s.equals(c))return!1}return!0}finally{b.closeSync(r)}}function prepareSqliteWalPrefixCopy(e,t,n){let r=readWalGeneration(e);if(r)return()=>{let i=b.fstatSync(e).size;if(!Number.isSafeInteger(i)||i<32)return!1;let a=b.openSync(t,`wx`,384),o;try{o=copyCommittedWalFrames(e,a,r,i)}finally{b.closeSync(a)}return o!==!1&&n()&&matchesCapturedWalPrefix(e,t,o)&&readWalGeneration(e)?.header.equals(r.header)===!0}}function getEnumValues(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function joinValues(e,t=`|`){return e.map(e=>stringifyPrimitive(e)).join(t)}function jsonStringifyReplacer(e,t){return typeof t==`bigint`?t.toString():t}var Cached=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function cached(e){return new Cached(e)}function nullish(e){return e==null}function cleanRegex(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function floatSafeRemainder(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function assignProp(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function rawShape(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function sourceShape(e){return rawShape(e._zod.def)??e._zod.def.shape}function deferProp(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return assignProp(this,t,e),e},enumerable:!0,configurable:!0})}function putProp(e,t,n){t in e?assignProp(e,t,n):e[t]=n}function mirrorShape(e,t,n,r){let i=sourceShape(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?deferProp(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):putProp(e,a,r?r(n.value,a):n.value))}}function mirrorProps(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?deferProp(e,n,()=>t[n]):putProp(e,n,r.value))}}function mergeDefs(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function esc(e){return JSON.stringify(e)}function slugify(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Qn=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const $n=/* @__PURE__*/ cached(()=>{if(S.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function isPlainObject(e){if(isObject$1(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return isObject$1(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function shallowClone(e){return isPlainObject(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const er=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function normalizeParams(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function stringifyPrimitive(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function optionalKeys(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const tr={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},nr={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function pick(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return mirrorShape(i,e,maskedKeys(e,t)),clone(e,mergeDefs(n,{shape:i,checks:[]}))}function maskedKeys(e,t){let n=sourceShape(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function omit(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(maskedKeys(e,t)),a={};return mirrorShape(a,e,Reflect.ownKeys(sourceShape(e)).filter(e=>!i.has(e))),clone(e,mergeDefs(n,{shape:a,checks:[]}))}function extend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=sourceShape(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return clone(e,mergeDefs(e._zod.def,{shape:extended(e,t)}))}function extended(e,t){let n={};return mirrorShape(n,e,Reflect.ownKeys(sourceShape(e))),mirrorProps(n,t),n}function safeExtend(e,t){if(!isPlainObject(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return clone(e,mergeDefs(e._zod.def,{shape:extended(e,t)}))}function merge(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return mirrorShape(n,e,Reflect.ownKeys(sourceShape(e))),mirrorShape(n,t,Reflect.ownKeys(sourceShape(t))),clone(e,mergeDefs(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function partial(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(maskedKeys(t,n)):void 0,o={};return mirrorShape(o,t,Reflect.ownKeys(sourceShape(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),clone(t,mergeDefs(t._zod.def,{shape:o,checks:[]}))}function required(e,t,n){let r=n?new Set(maskedKeys(t,n)):void 0,i={};return mirrorShape(i,t,Reflect.ownKeys(sourceShape(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),clone(t,mergeDefs(t._zod.def,{shape:i}))}function aborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function explicitlyAborted(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function prefixIssues(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function unwrapMessage(e){return typeof e==`string`?e:e?.message}function sizeCaps(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function attachSchema(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function finalizeIssue(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(a?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(n.customError?.(e))??unwrapMessage(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}const rr=/[\uD800-\uDBFF]/;function codePointLength(e){let t=e.length;if(!rr.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function getLengthableOrigin(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function parsedType(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function issue(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function members(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):defineBound(e,n,r.value)}}function own(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function hide(e,t,n){return own(e,t,n,!1)}/* @__NO_SIDE_EFFECTS__ */
function derived(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return own(this,n,r(this))},set(e){own(this,n,e)}})}return t}function defineBound(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:own(this,t,n.bind(this))},set(e){own(this,t,e)}})}function claim(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let ir,ar=!1;const or={configurable:!0,get(){ar=!0}};function defineLazyInternal(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&ir!==e._zod?ir=void 0:(ir=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,or);let e=ar;ar=!1;try{let r=n(this);return ar?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),ar||=e,r}catch(n){throw delete this[t],ar||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function installLazyProp(e,t,n,r){let i=claim(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function constantCatch(e){let fn=()=>e;return fn[`~constantCatch`]=!0,fn}var sr;const cr={value:void 0,enumerable:!1};let lr=`captureStackTrace`in Error?Error:null;function newError(e){let t=lr;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return lr=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}/* @__NO_SIDE_EFFECTS__ */
function $constructor(e,t,n,r){let i={};function Internals(e){this.def=e,this.constr=_,this.traits=/* @__PURE__ */ new Set}Internals.prototype=i;let a=n,o=a&&/* @__PURE__ */ new WeakSet;function init(n,r){if(!n._zod){cr.value=new Internals(r);try{Object.defineProperty(n,"_zod",cr)}finally{cr.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),o){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;o.has(i)||(o.add(i),members(i,a))}let i=_.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let s=r?.Parent??Object;class Definition extends s{}Object.defineProperty(Definition,"name",{value:e});function _(e){let t=r?.Parent?newError(Definition):this;init(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(_,"name",{value:e}),_}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$ZodEncodeError=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(sr=globalThis).__zod_globalConfig??(sr.__zod_globalConfig={});const S=globalThis.__zod_globalConfig;function config(e){return e&&Object.assign(S,e),S}function _getMessage(){let e=this._zod;return e.message??=JSON.stringify(e.def,jsonStringifyReplacer,2),e.message}function _setMessage(e){this._zod.message=e}const ur={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},dr={value:void 0,enumerable:!1},fr=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),pr=/* @__PURE__ */ $constructor(`$ZodError`,(e,t)=>{e.name=`$ZodError`,dr.value=t,Object.defineProperty(e,"issues",dr),dr.value=void 0,Object.defineProperty(e,"message",ur);let n=Object.getPrototypeOf(e);fr.has(n)||(fr.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let value=()=>this.message;return Object.defineProperty(this,"toString",{value,configurable:!0,writable:!0}),value},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))});function node(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function flattenError(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?node(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function formatError(e,t=e=>e.message){let n={_errors:[]},processError=(e,r=[])=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>processError({issues:e},[...r,...i.path]));else if(i.code===`invalid_key`)processError({issues:i.issues},[...r,...i.path]);else if(i.code===`invalid_element`)processError({issues:i.issues},[...r,...i.path]);else{let e=[...r,...i.path];if(e.length===0)n._errors.push(t(i));else{let r=n,a=0;for(;a<e.length;){let n=e[a],o=a===e.length-1;if(n===`_errors`){o&&r._errors.push(t(i)),a++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(i)),r=s,a++}}}};return processError(e),n}function finalizeParams(e,t){return{callee:t?.callee??e,Err:t?.Err}}const _parse=e=>{let fn=(t,n,r,i)=>{let a=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new $ZodAsyncError;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>finalizeIssue(e,a,config())));throw Qn(t,i?.callee??fn),t}return o.value};return fn},_parseAsync=e=>{let fn=async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>finalizeIssue(e,a,config())));throw Qn(t,i?.callee??fn),t}return o.value};return fn},_safeParse=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new $ZodAsyncError;return a.issues.length?failure(e,a.issues,i):{success:!0,data:a.value}};function failure(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>finalizeIssue(e,n,config()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const _safeParseAsync=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?failure(e,a.issues,i):{success:!0,data:a.value}},mr=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),hr=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),validate=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==mr)return!0;if(r.definite===!0&&n===void 0)return!1}return validateFallback(e,t,n)});function validateFallback(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[hr]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new $ZodAsyncError;return a.issues.length===0}const validateAsync$1=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},_encode=e=>{let t=_parse(e),fn=(e,n,r,i)=>{let a=r?{...r,direction:`backward`}:{direction:`backward`};return t(e,n,a,finalizeParams(fn,i))};return fn},_decode=e=>{let t=_parse(e),fn=(e,n,r,i)=>t(e,n,r,finalizeParams(fn,i));return fn},_encodeAsync=e=>{let t=_parseAsync(e),fn=async(e,n,r,i)=>{let a=r?{...r,direction:`backward`}:{direction:`backward`};return await t(e,n,a,finalizeParams(fn,i))};return fn},_decodeAsync=e=>{let t=_parseAsync(e),fn=async(e,n,r,i)=>await t(e,n,r,finalizeParams(fn,i));return fn},_safeEncode=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParse(e)(t,n,i)},_safeDecode=e=>(t,n,r)=>_safeParse(e)(t,n,r),_safeEncodeAsync=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParseAsync(e)(t,n,i)},_safeDecodeAsync=e=>async(t,n,r)=>_safeParseAsync(e)(t,n,r),gr=/^[cC][0-9a-z]{6,}$/,_r=/^[0-9a-z]+$/,vr=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,yr=/^[0-9a-vA-V]{20}$/,br=/^[A-Za-z0-9]{27}$/,xr=/^[a-zA-Z0-9_-]{21}$/;function nanoidOfLength(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Sr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cr=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,wr=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function emoji(){return/* @__PURE__ */ RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const Tr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Er=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Dr=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Or=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,kr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ar=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,jr=/^https?$/,Mr=/^\+[1-9]\d{6,14}$/,Nr=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function anchor(e){return RegExp(`^${e}$`)}const Pr=/*@__PURE__*/ anchor(Nr);function timeSource(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function time(e){return RegExp(`^${timeSource(e)}$`)}function datetime(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${timeSource({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${timeSource({precision:e.precision})}`:n;return RegExp(`^${Nr}T(?:${r})$`)}const Fr=/^[\s\S]{0,}$/,Ir=/^-?\d+$/,Lr=/^-?\d+(?:\.\d+)?$/,Rr=/^(?:true|false)$/i,zr=/^[^A-Z]*$/,Br=/^[^a-z]*$/,C=/*@__PURE__*/ $constructor(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),_whenHasLength=e=>{let t=e.value;return!nullish(t)&&t.length!==void 0},Vr={number:`number`,bigint:`bigint`,object:`date`},Hr=/*@__PURE__*/ $constructor(`$ZodCheckLessThan`,(e,t)=>{C.init(e,t);let n=Vr[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Vr[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ur=/*@__PURE__*/ $constructor(`$ZodCheckGreaterThan`,(e,t)=>{C.init(e,t);let n=Vr[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Vr[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Wr=/*@__PURE__*/ $constructor(`$ZodCheckMultipleOf`,(e,t)=>{C.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):floatSafeRemainder(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Gr=/*@__PURE__*/ $constructor(`$ZodCheckNumberFormat`,(e,t)=>{C.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=tr[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Kr=/*@__PURE__*/ $constructor(`$ZodCheckMaxLength`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?codePointLength(r):i)<=t.maximum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),qr=/*@__PURE__*/ $constructor(`$ZodCheckMinLength`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?codePointLength(r):i)>=t.minimum)return;let a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Jr=/*@__PURE__*/ $constructor(`$ZodCheckLengthEquals`,(e,t)=>{var n;C.init(e,t),(n=e._zod.def).when??(n.when=_whenHasLength),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?codePointLength(r):i;if(a===t.length)return;let o=getLengthableOrigin(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Yr=/*@__PURE__*/ $constructor(`$ZodCheckStringFormat`,(e,t)=>{var n,r;C.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Xr=/*@__PURE__*/ $constructor(`$ZodCheckRegex`,(e,t)=>{Yr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Zr=/*@__PURE__*/ $constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=zr,Yr.init(e,t)}),Qr=/*@__PURE__*/ $constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Br,Yr.init(e,t)}),$r=/*@__PURE__*/ $constructor(`$ZodCheckIncludes`,(e,t)=>{C.init(e,t);let n=escapeRegex(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),ei=/*@__PURE__*/ $constructor(`$ZodCheckStartsWith`,(e,t)=>{C.init(e,t);let n=RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),ti=/*@__PURE__*/ $constructor(`$ZodCheckEndsWith`,(e,t)=>{C.init(e,t);let n=RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),ni=/*@__PURE__*/ $constructor(`$ZodCheckOverwrite`,(e,t)=>{C.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var Doc=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
`)}\n};`)(...Object.values(this.closed))}};const ri={major:4,minor:6,patch:7},w=/*@__PURE__*/ $constructor(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ri;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let runChecks=(t,n,r)=>{if(t.memo)return t;let i=aborted(t),a;for(let o of n){if(o._zod.def.when){if(explicitlyAborted(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new $ZodAsyncError;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(attachSchema(t.issues,n,e),i||=aborted(t,n))});else{if(t.issues.length===n)continue;attachSchema(t.issues,n,e),i||=aborted(t,n)}}return a?a.then(()=>t):t},handleCanaryResult=(t,n,r)=>{if(aborted(t))return t.aborted=!0,t;let a=runChecks(n,i,r);if(a instanceof Promise){if(r.async===!1)throw new $ZodAsyncError;return a.then(t=>e._zod.parse(t,r))}return e._zod.parse(a,r)};e._zod.run=(t,n)=>{if(n.skipChecks)return e._zod.parse(t,n);if(n.direction===`backward`){let r=e._zod.parse({value:t.value,issues:[]},{...n,skipChecks:!0});return r instanceof Promise?r.then(e=>handleCanaryResult(e,t,n)):handleCanaryResult(r,t,n)}let r=e._zod.parse(t,n);if(r instanceof Promise){if(n.async===!1)throw new $ZodAsyncError;return r.then(e=>runChecks(e,i,n))}return runChecks(r,i,n)}}},{get"~standard"(){return hide(this,`~standard`,standardProps(this))},set"~standard"(e){own(this,`~standard`,e)}}),toStandardResult=(e,t)=>e.issues.length?{issues:e.issues.map(e=>finalizeIssue(e,t,config()))}:{value:e.value};async function validateAsync(e,t){let n={async:!0};return toStandardResult(await e._zod.run({value:t,issues:[]},n),n)}function standardProps(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return toStandardResult(r,n)}catch{}return validateAsync(e,t)},vendor:`zod`,version:1}}const ii=/*@__PURE__*/ $constructor(`$ZodString`,(e,t)=>{w.init(e,t),e._zod.pattern=t.pattern??Fr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),T=/*@__PURE__*/ $constructor(`$ZodStringFormat`,(e,t)=>{Yr.init(e,t),ii.init(e,t)}),ai=/*@__PURE__*/ $constructor(`$ZodGUID`,(e,t)=>{t.pattern??=Cr,T.init(e,t)}),oi=/*@__PURE__*/ $constructor(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=uuid(e)}else t.pattern??=uuid();T.init(e,t)}),si=/*@__PURE__*/ $constructor(`$ZodEmail`,(e,t)=>{t.pattern??=wr,T.init(e,t)});function canParseURL(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function validateURL(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?canParseURL(e)||2:parseURLObject(e,t)}function parseURLObject(e,t){if(!t.normalize&&t.protocol?.source===jr.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}const ci=/[\t\n\r]/g;function stripTabAndNewline(e){return e.replace(ci,``)}function urlHostnameOk(e,t){return t.lastIndex=0,t.test(e.hostname)}function urlProtocolOk(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const li=/*@__PURE__*/ $constructor(`$ZodURL`,(e,t)=>{T.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=validateURL(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=stripTabAndNewline(r);return}t.hostname&&!urlHostnameOk(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!urlProtocolOk(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:stripTabAndNewline(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),ui=/*@__PURE__*/ $constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),T.init(e,t)}),di=/*@__PURE__*/ $constructor(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?xr:nanoidOfLength(t.length),T.init(e,t)}),fi=/*@__PURE__*/ $constructor(`$ZodCUID`,(e,t)=>{t.pattern??=gr,T.init(e,t)}),pi=/*@__PURE__*/ $constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=_r,T.init(e,t)}),mi=/*@__PURE__*/ $constructor(`$ZodULID`,(e,t)=>{t.pattern??=vr,T.init(e,t)}),hi=/*@__PURE__*/ $constructor(`$ZodXID`,(e,t)=>{t.pattern??=yr,T.init(e,t)}),gi=/*@__PURE__*/ $constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=br,T.init(e,t)}),_i=/*@__PURE__*/ $constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime(t),T.init(e,t)}),vi=/*@__PURE__*/ $constructor(`$ZodISODate`,(e,t)=>{t.pattern??=Pr,T.init(e,t)}),yi=/*@__PURE__*/ $constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time(t),T.init(e,t)}),bi=/*@__PURE__*/ $constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=Sr,T.init(e,t)}),xi=/*@__PURE__*/ $constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=Tr,T.init(e,t)}),Si=/^[0-9a-fA-F:.]+$/;function isValidIPv6(e){return Si.test(e)?canParseURL(`http://[${e}]`):!1}const Ci=/*@__PURE__*/ $constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=Er,T.init(e,t),e._zod.check=n=>{isValidIPv6(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),wi=/*@__PURE__*/ $constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Dr,T.init(e,t)});function isValidCIDRv6(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:isValidIPv6(n)}const Ti=/*@__PURE__*/ $constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Or,T.init(e,t),e._zod.check=n=>{isValidCIDRv6(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function isValidBase64(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Ei=/^[0-9a-zA-Z+/]*={0,2}$/,Di=/*@__PURE__*/ $constructor(`$ZodBase64`,(e,t)=>{t.pattern??=Ei,T.init(e,t),e._zod.check=n=>{isValidBase64(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Oi=/^[A-Za-z0-9_-]*$/;function isValidBase64URL(e){if(!Oi.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const ki=/*@__PURE__*/ $constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=Oi,T.init(e,t),e._zod.check=n=>{isValidBase64URL(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Ai=/*@__PURE__*/ $constructor(`$ZodE164`,(e,t)=>{t.pattern??=Mr,T.init(e,t)});function isValidJWT(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const ji=/*@__PURE__*/ $constructor(`$ZodJWT`,(e,t)=>{T.init(e,t),e._zod.check=n=>{isValidJWT(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Mi=/*@__PURE__*/ $constructor(`$ZodNumber`,(e,t)=>{w.init(e,t),e._zod.pattern=Lr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Ni=/*@__PURE__*/ $constructor(`$ZodNumberFormat`,(e,t)=>{Gr.init(e,t),Mi.init(e,t)}),Pi=/*@__PURE__*/ $constructor(`$ZodBoolean`,(e,t)=>{w.init(e,t),e._zod.pattern=Rr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Fi=/*@__PURE__*/ $constructor(`$ZodUnknown`,(e,t)=>{w.init(e,t),e._zod.parse=e=>e}),Ii=/*@__PURE__*/ $constructor(`$ZodNever`,(e,t)=>{w.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function capSize(e,t){let n=sizeCaps(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of sizeCaps(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,attachSchema(n.issues,t,e),n}}return i(n,a)}}const arraySize=e=>Array.isArray(e)?e.length:-1;function handleArrayResult(e,t,n){e.issues.length&&t.issues.push(...prefixIssues(n,e.issues)),t.value[n]=e.value}const Li=/*@__PURE__*/ $constructor(`$ZodArray`,(e,t)=>{w.init(e,t);let n=S.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>handleArrayResult(t,r,e)));else if(handleArrayResult(c,r,e),s&&c.issues.length!==0&&aborted(c))break}return o.length?Promise.all(o).then(()=>r):r},capSize(e,arraySize)});function handlePropertyResult(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...prefixIssues(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}const Ri=[];function normalizeDef(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Ri,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=optionalKeys(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function handleCatchall(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(aborted(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>handlePropertyResult(e,n,i,t,d,f))):handlePropertyResult(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const zi=/*@__PURE__*/ $constructor(`$ZodObject`,(e,t)=>{w.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let get=()=>{let e={...r};return Object.defineProperty(t,"shape",{value:e}),get.raw=e,e};get.raw=r,Object.defineProperty(t,"shape",{get})}let i=cached(()=>normalizeDef(t));defineLazyInternal(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||assignProp(n,e,/* @__PURE__ */ new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=isObject$1,o=t.catchall,s,c=S.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(aborted(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>handlePropertyResult(n,t,e,r,a,o))):handlePropertyResult(s,t,e,r,a,o)}return o?handleCatchall(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),Bi=/*@__PURE__*/ $constructor(`$ZodObjectJIT`,(e,t)=>{zi.init(e,t);let n=e._zod.parse,r=cached(()=>normalizeDef(t)),i=S.memoizer,generateFastpass=t=>{let n=r.value,a=n.symbolKeys,o=new Doc([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),parseStr=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,prefixStr=(e,t)=>`
          let ${e}_ab = false;
          for (let i = 0; i < ${e}.issues.length; i++) {
            const iss = ${e}.issues[i];
            iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
            payload.issues.push(iss);
            if (iss.continue !== true) ${e}_ab = true;
          }
          if (${e}_ab && ctx && ctx.abortEarly) {
            payload.value = newResult;
            return payload;
          }`;o.write(`const input = payload.value;`);let s=Object.create(null),c=0;for(let e of n.allKeys)s[e]=`key_${c++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=s[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:esc(e),i=`${r} in input`,c=t[e],l=c?._zod?.optin,u=l!==void 0,d=c?._zod?.optout===`optional`;if(o.write(`const ${n} = ${parseStr(r)};`),u&&d){let e=l===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
        const ${n}_present = ${i};
        if (!${n}.issues.length || ${n}_present) {
          if (${n}.issues.length) {${prefixStr(n,r)}
          }

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

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

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

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

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])extractToDef(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){extractToDef(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&extractToDef(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function compactTypeUnion(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;compactTypeUnion(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const fa=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),pa=[`oneOf`,`anyOf`];function undeclaredConstraint(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function foldObjects(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!fa.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??undeclaredConstraint(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}assignProp(n,r,e.length===1?e[0]:foldObjects(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=undeclaredConstraint(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function foldIntersection(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of fa)if(t in e)return;let n=t.filter(e=>pa.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=foldObjects(t);else{let e=n[0],i=pa.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>foldObjects([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,assignProps(e,r))}function finalize(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let flattenRef=t=>{let n=e.seen.get(t);if(n.ref===null)return;let r=n.def??n.schema,i={...r},a=n.ref;if(n.ref=null,a){flattenRef(a);let n=e.seen.get(a),o=n.schema;if(o.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(r.allOf=r.allOf??[],r.allOf.push(o)):assignProps(r,o),assignProps(r,i),t._zod.parent===a)for(let e in r)e!==`$ref`&&e!==`allOf`&&(e in i||delete r[e]);if(o.$ref&&n.def)for(let e in r)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(r[e])===JSON.stringify(n.def[e])&&delete r[e]}let o=t._zod.parent;if(o&&o!==a){flattenRef(o);let t=e.seen.get(o);if(t?.schema.$ref&&(r.$ref=t.schema.$ref,t.def))for(let e in r)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(r[e])===JSON.stringify(t.def[e])&&delete r[e]}e.override({zodSchema:t,jsonSchema:r,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())flattenRef(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())compactTypeUnion(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])foldIntersection(e)}}let r={};if(e.target===`draft-2020-12`?r.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?r.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?r.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");r.$id=e.external.uri(n)}assignProps(r,n.defId?n.schema:n.def??n.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&r.id===i&&delete r.id;let a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,assignProp(a,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(a).length>0&&(e.target===`draft-2020-12`?r.$defs=a:r.definitions=a);try{let n=JSON.parse(JSON.stringify(r));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return isTransforming(r.element,n);if(r.type===`set`)return isTransforming(r.valueType,n);if(r.type===`lazy`)return isTransforming(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return isTransforming(r.innerType,n);if(r.type===`intersection`)return isTransforming(r.left,n)||isTransforming(r.right,n);if(r.type===`record`||r.type===`map`)return isTransforming(r.keyType,n)||isTransforming(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:isTransforming(r.in,n)||isTransforming(r.out,n);if(r.type===`object`){for(let e in r.shape)if(isTransforming(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(isTransforming(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(isTransforming(e,n))return!0;return!!(r.rest&&isTransforming(r.rest,n))}return!1}const createToJSONSchemaMethod=(e,t={})=>n=>{let r=initializeContext({...n,processors:t});return processSchema(e,r),extractDefs(r,e),finalize(r,e)},createStandardJSONSchemaMethod=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=initializeContext({...i??{},target:a,io:t,processors:n});return processSchema(e,o),extractDefs(o,e),finalize(o,e)},narrowMin=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},narrowMax=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},narrowBoth=(e,t)=>{narrowMin(e,`minimum`,t),narrowMax(e,`maximum`,t)},addDivisor=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},addPattern=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},intersectMime=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},setFormat=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},minContributor=(e,t)=>narrowMin(e,`minimum`,t.minimum),maxContributor=(e,t)=>narrowMax(e,`maximum`,t.maximum),formatContributor=e=>(t,n)=>{setFormat(t,n.format);let[r,i]=e[n.format];narrowMin(t,`minimum`,r),narrowMax(t,`maximum`,i)},ma={greater_than:(e,t)=>narrowMin(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>narrowMax(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>addDivisor(e,t.value),number_format:formatContributor(tr),bigint_format:formatContributor(nr),min_length:minContributor,max_length:maxContributor,length_equals:(e,t)=>narrowBoth(e,t.length),min_size:minContributor,max_size:maxContributor,size_equals:(e,t)=>narrowBoth(e,t.size),string_format:(e,t)=>{setFormat(e,t.format),t.pattern&&addPattern(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>intersectMime(e,t.mime)};function aggregateChecks(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)ma[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&narrowMin(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&narrowMin(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&narrowMax(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&narrowMax(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&addDivisor(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&intersectMime(t,i.mime);for(let e of i.patterns??[])addPattern(t,e);return t}const ha={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},ga=/* @__PURE__ */ new Map([[Ei,kr],[Oi,Ar]]),exactPattern=e=>ga.get(e)??e,stringProcessor=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=aggregateChecks(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=ha[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(exactPattern);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},numberProcessor=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=aggregateChecks(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):handleUnrepresentable(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},booleanProcessor=(e,t,n,r)=>{n.type=`boolean`},neverProcessor=(e,t,n,r)=>{n.not={}},enumProcessor=(e,t,n,r)=>{let i=e._zod.def,a=getEnumValues(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},literalProcessor=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(handleUnrepresentable(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(handleUnrepresentable(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},customProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},transformProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},arrayProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=aggregateChecks(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=processSchema(a.element,t,{...r,path:[...r.path,`items`]})};function inputOptin(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?inputOptin(t.out):t.type===`catch`?inputOptin(t.innerType):e._zod.optin}const objectProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&handleUnrepresentable(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)assignProp(i.properties,e,processSchema(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?inputOptin(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=processSchema(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},unionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>processSchema(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},intersectionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=processSchema(i.right,t,{...r,path:[...r.path,`allOf`,1]}),isSimpleIntersection=e=>`allOf`in e&&Object.keys(e).length===1,s=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(o)?o.allOf:[o]];n.allOf=s,t.intersections.push(s)};function stringifyKeyNames(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=stringifyKeyNames(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>stringifyKeyNames(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Lr:Ir).source)),p}const _a=/* @__PURE__ */ new WeakMap;function rewriteKeyNames(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of _a.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=stringifyKeyNames(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}const recordProcessor=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=aggregateChecks(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=processSchema(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)assignProp(i.patternProperties,exactPattern(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=processSchema(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=_a.get(t);n||(n=[],_a.set(t,n),t.deferred.push(()=>rewriteKeyNames(t))),n.push(e)}i.additionalProperties=processSchema(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&inputOptin(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},nullableProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},nonoptionalProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},va=Symbol();function serializeDefaultValue(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(handleUnrepresentable(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),va):JSON.parse(o)}const defaultProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=serializeDefaultValue(i.defaultValue,e,t,n,r);o!==va&&(n.default=o)},prefaultProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=serializeDefaultValue(i.defaultValue,e,t,n,r);o!==va&&(n._prefault=o)},catchProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{handleUnrepresentable(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},pipeProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;processSchema(o,t,r);let s=t.seen.get(e);s.ref=o},readonlyProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},optionalProcessor=(e,t,n,r)=>{let i=e._zod.def;processSchema(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},ya=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const E=/*@__PURE__*/ $constructor(`ZodError`,(e,t)=>{pr.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);ya.has(n)||(ya.add(n),_lazyMethod(n,`format`,e=>t=>formatError(e,t)),_lazyMethod(n,`flatten`,e=>t=>flattenError(e,t)),_lazyMethod(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),_lazyMethod(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,jsonStringifyReplacer,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),ba=/* @__PURE__ */ _parse(E),xa=/* @__PURE__ */ _parseAsync(E),Sa=/* @__PURE__ */ _safeParse(E),Ca=/* @__PURE__ */ _safeParseAsync(E),wa=/* @__PURE__ */ _encode(E),Ta=/* @__PURE__ */ _decode(E),Ea=/* @__PURE__ */ _encodeAsync(E),Da=/* @__PURE__ */ _decodeAsync(E),Oa=/* @__PURE__ */ _safeEncode(E),ka=/* @__PURE__ */ _safeDecode(E),Aa=/* @__PURE__ */ _safeEncodeAsync(E),ja=/* @__PURE__ */ _safeDecodeAsync(E);function _ensureDefaultLocale(){S.localeError||config(en_default())}function _ensureDefaultMemoizer(){S.memoizer||config({memoizer:memoizer()})}const D=/*@__PURE__*/ $constructor(`ZodType`,(e,t)=>(_ensureDefaultLocale(),w.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(mergeDefs(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return clone(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(refine(e,t))},superRefine(e,t){return this.check(superRefine(e,t))},overwrite(e){return this.check(/* @__PURE__ */ _overwrite(e))},optional(){return optional(this)},exactOptional(){return exactOptional(this)},nullable(){return nullable(this)},nullish(){return optional(nullable(this))},nonoptional(e){return nonoptional(this,e)},array(){return array(this)},or(e){return union([this,e])},and(e){return intersection(this,e)},transform(e){return pipe(this,transform(e))},default(e){return _default(this,e)},prefault(e){return prefault(this,e)},catch(e){return _catch(this,e)},pipe(e){return pipe(this,e)},readonly(){return readonly(this)},describe(e){let t=this.clone();return da.add(t,{description:e}),t},meta(...e){if(e.length===0)return da.get(this);let t=this.clone();return da.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return hide(this,`~standard`,{...standardProps(this),jsonSchema:{input:createStandardJSONSchemaMethod(this,`input`),output:createStandardJSONSchemaMethod(this,`output`)}})},set"~standard"(e){own(this,`~standard`,e)},parse:function _parse(e,t){return ba(this,e,t,{callee:_parse})},parseAsync:async function _parseAsync(e,t){return await xa(this,e,t,{callee:_parseAsync})},safeParse(e,t){return Sa(this,e,t)},async safeParseAsync(e,t){return Ca(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){own(this,`spa`,e)},validate(e,t){return validate(this,e,t)},validateAsync(e,t){return validateAsync$1(this,e,t)},encode:function _encode(e,t){return wa(this,e,t,{callee:_encode})},decode:function _decode(e,t){return Ta(this,e,t,{callee:_decode})},encodeAsync:async function _encodeAsync(e,t){return await Ea(this,e,t,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(e,t){return await Da(this,e,t,{callee:_decodeAsync})},safeEncode(e,t){return Oa(this,e,t)},safeDecode(e,t){return ka(this,e,t)},async safeEncodeAsync(e,t){return Aa(this,e,t)},async safeDecodeAsync(e,t){return ja(this,e,t)},toJSONSchema(e){return createToJSONSchemaMethod(this,{})(e)},get description(){return da.get(this)?.description},get _def(){return this._zod.def}}),Ma=/*@__PURE__*/ $constructor(`_ZodString`,(e,t)=>{ii.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>stringProcessor(e,t,n,r)},/*@__PURE__*/ derived({format:e=>aggregateChecks(e).format??null,minLength:e=>aggregateChecks(e).minimum??null,maxLength:e=>aggregateChecks(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ _regex(...e))},includes(...e){return this.check(/* @__PURE__ */ _includes(...e))},startsWith(...e){return this.check(/* @__PURE__ */ _startsWith(...e))},endsWith(...e){return this.check(/* @__PURE__ */ _endsWith(...e))},min(...e){return this.check(/* @__PURE__ */ _minLength(...e))},max(...e){return this.check(/* @__PURE__ */ _maxLength(...e))},length(...e){return this.check(/* @__PURE__ */ _length(...e))},nonempty(...e){return this.check(/* @__PURE__ */ _minLength(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ _lowercase(e))},uppercase(e){return this.check(/* @__PURE__ */ _uppercase(e))},trim(){return this.check(/* @__PURE__ */ _trim())},normalize(...e){return this.check(/* @__PURE__ */ _normalize(...e))},toLowerCase(){return this.check(/* @__PURE__ */ _toLowerCase())},toUpperCase(){return this.check(/* @__PURE__ */ _toUpperCase())},slugify(){return this.check(/* @__PURE__ */ _slugify())}})),Na=/*@__PURE__*/ $constructor(`ZodString`,(e,t)=>{ii.init(e,t),Ma.init(e,t)},{email(e){return this.check(/* @__PURE__ */ _email(Ra,e))},url(e){return this.check(/* @__PURE__ */ _url(Va,e))},jwt(e){return this.check(/* @__PURE__ */ _jwt(no,e))},emoji(e){return this.check(/* @__PURE__ */ _emoji(Ha,e))},guid(e){return this.check(/* @__PURE__ */ _guid(za,e))},uuid(e){return this.check(/* @__PURE__ */ _uuid(Ba,e))},uuidv4(e){return this.check(/* @__PURE__ */ _uuidv4(Ba,e))},uuidv6(e){return this.check(/* @__PURE__ */ _uuidv6(Ba,e))},uuidv7(e){return this.check(/* @__PURE__ */ _uuidv7(Ba,e))},nanoid(e){return this.check(/* @__PURE__ */ _nanoid(Ua,e))},cuid(e){return this.check(/* @__PURE__ */ _cuid(Wa,e))},cuid2(e){return this.check(/* @__PURE__ */ _cuid2(Ga,e))},ulid(e){return this.check(/* @__PURE__ */ _ulid(Ka,e))},base64(e){return this.check(/* @__PURE__ */ _base64($a,e))},base64url(e){return this.check(/* @__PURE__ */ _base64url(eo,e))},xid(e){return this.check(/* @__PURE__ */ _xid(qa,e))},ksuid(e){return this.check(/* @__PURE__ */ _ksuid(Ja,e))},ipv4(e){return this.check(/* @__PURE__ */ _ipv4(Ya,e))},ipv6(e){return this.check(/* @__PURE__ */ _ipv6(Xa,e))},cidrv4(e){return this.check(/* @__PURE__ */ _cidrv4(Za,e))},cidrv6(e){return this.check(/* @__PURE__ */ _cidrv6(Qa,e))},e164(e){return this.check(/* @__PURE__ */ _e164(to,e))},datetime(e){return this.check(/* @__PURE__ */ _isoDateTime(Pa,e))},date(e){return this.check(/* @__PURE__ */ _isoDate(Fa,e))},time(e){return this.check(/* @__PURE__ */ _isoTime(Ia,e))},duration(e){return this.check(/* @__PURE__ */ _isoDuration(La,e))}});function string(e){return/* @__PURE__ */ _string(Na,e)}const O=/*@__PURE__*/ $constructor(`ZodStringFormat`,(e,t)=>{T.init(e,t),Ma.init(e,t)}),Pa=/*@__PURE__*/ $constructor(`ZodISODateTime`,(e,t)=>{_i.init(e,t),O.init(e,t)}),Fa=/*@__PURE__*/ $constructor(`ZodISODate`,(e,t)=>{vi.init(e,t),O.init(e,t)}),Ia=/*@__PURE__*/ $constructor(`ZodISOTime`,(e,t)=>{yi.init(e,t),O.init(e,t)}),La=/*@__PURE__*/ $constructor(`ZodISODuration`,(e,t)=>{bi.init(e,t),O.init(e,t)}),Ra=/*@__PURE__*/ $constructor(`ZodEmail`,(e,t)=>{si.init(e,t),O.init(e,t)}),za=/*@__PURE__*/ $constructor(`ZodGUID`,(e,t)=>{ai.init(e,t),O.init(e,t)}),Ba=/*@__PURE__*/ $constructor(`ZodUUID`,(e,t)=>{oi.init(e,t),O.init(e,t)}),Va=/*@__PURE__*/ $constructor(`ZodURL`,(e,t)=>{li.init(e,t),O.init(e,t)}),Ha=/*@__PURE__*/ $constructor(`ZodEmoji`,(e,t)=>{ui.init(e,t),O.init(e,t)}),Ua=/*@__PURE__*/ $constructor(`ZodNanoID`,(e,t)=>{di.init(e,t),O.init(e,t)}),Wa=/*@__PURE__*/ $constructor(`ZodCUID`,(e,t)=>{fi.init(e,t),O.init(e,t)}),Ga=/*@__PURE__*/ $constructor(`ZodCUID2`,(e,t)=>{pi.init(e,t),O.init(e,t)}),Ka=/*@__PURE__*/ $constructor(`ZodULID`,(e,t)=>{mi.init(e,t),O.init(e,t)}),qa=/*@__PURE__*/ $constructor(`ZodXID`,(e,t)=>{hi.init(e,t),O.init(e,t)}),Ja=/*@__PURE__*/ $constructor(`ZodKSUID`,(e,t)=>{gi.init(e,t),O.init(e,t)}),Ya=/*@__PURE__*/ $constructor(`ZodIPv4`,(e,t)=>{xi.init(e,t),O.init(e,t)}),Xa=/*@__PURE__*/ $constructor(`ZodIPv6`,(e,t)=>{Ci.init(e,t),O.init(e,t)}),Za=/*@__PURE__*/ $constructor(`ZodCIDRv4`,(e,t)=>{wi.init(e,t),O.init(e,t)}),Qa=/*@__PURE__*/ $constructor(`ZodCIDRv6`,(e,t)=>{Ti.init(e,t),O.init(e,t)}),$a=/*@__PURE__*/ $constructor(`ZodBase64`,(e,t)=>{Di.init(e,t),O.init(e,t)}),eo=/*@__PURE__*/ $constructor(`ZodBase64URL`,(e,t)=>{ki.init(e,t),O.init(e,t)}),to=/*@__PURE__*/ $constructor(`ZodE164`,(e,t)=>{Ai.init(e,t),O.init(e,t)}),no=/*@__PURE__*/ $constructor(`ZodJWT`,(e,t)=>{ji.init(e,t),O.init(e,t)}),ro=/*@__PURE__*/ $constructor(`ZodNumber`,(e,t)=>{Mi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>numberProcessor(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ derived({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=aggregateChecks(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=aggregateChecks(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=aggregateChecks(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>aggregateChecks(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ _gt(e,t))},gte(e,t){return this.check(/* @__PURE__ */ _gte(e,t))},min(e,t){return this.check(/* @__PURE__ */ _gte(e,t))},lt(e,t){return this.check(/* @__PURE__ */ _lt(e,t))},lte(e,t){return this.check(/* @__PURE__ */ _lte(e,t))},max(e,t){return this.check(/* @__PURE__ */ _lte(e,t))},int(e){return this.check(int(e))},safe(e){return this.check(int(e))},positive(e){return this.check(/* @__PURE__ */ _gt(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ _gte(0,e))},negative(e){return this.check(/* @__PURE__ */ _lt(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ _lte(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ _multipleOf(e,t))},step(e,t){return this.check(/* @__PURE__ */ _multipleOf(e,t))},finite(){return this}}));function number(e){return/* @__PURE__ */ _number(ro,e)}const io=/*@__PURE__*/ $constructor(`ZodNumberFormat`,(e,t)=>{Ni.init(e,t),ro.init(e,t)});function int(e){return/* @__PURE__ */ _int(io,e)}const ao=/*@__PURE__*/ $constructor(`ZodBoolean`,(e,t)=>{Pi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n,r)});function boolean(e){return/* @__PURE__ */ _boolean(ao,e)}const oo=/*@__PURE__*/ $constructor(`ZodUnknown`,(e,t)=>{Fi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function unknown(){return/* @__PURE__ */ _unknown(oo)}const so=/*@__PURE__*/ $constructor(`ZodNever`,(e,t)=>{Ii.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)});function never(e){return/* @__PURE__ */ _never(so,e)}const co=/*@__PURE__*/ $constructor(`ZodArray`,(e,t)=>{_ensureDefaultMemoizer(),Li.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>arrayProcessor(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ _minLength(e,t))},nonempty(e){return this.check(/* @__PURE__ */ _minLength(1,e))},max(e,t){return this.check(/* @__PURE__ */ _maxLength(e,t))},length(e,t){return this.check(/* @__PURE__ */ _length(e,t))},unwrap(){return this.element}});function array(e,t){return/* @__PURE__ */ _array(co,e,t)}const lo=/*@__PURE__*/ $constructor(`ZodObject`,(e,t)=>{_ensureDefaultMemoizer(),Bi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>objectProcessor(e,t,n,r),installLazyProp(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return _enum(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},loose(){return this.clone(mergeDefs(this._zod.def,{catchall:unknown()}))},strict(){return this.clone(mergeDefs(this._zod.def,{catchall:never()}))},strip(){return this.clone(mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return extend(this,e)},safeExtend(e){return safeExtend(this,e)},merge(e){return merge(this,e)},pick(e){return pick(this,e)},omit(e){return omit(this,e)},partial(...e){return partial(vo,this,e[0])},exactPartial(...e){return partial(yo,this,e[0],`exactPartial`)},required(...e){return required(Co,this,e[0])}});function object(e,t){let n={type:`object`,shape:e??{},...normalizeParams(t)};return new lo(n)}function strictObject(e,t){return new lo({type:`object`,shape:e,catchall:never(),...normalizeParams(t)})}function looseObject(e,t){return new lo({type:`object`,shape:e,catchall:unknown(),...normalizeParams(t)})}const uo=/*@__PURE__*/ $constructor(`ZodUnion`,(e,t)=>{Vi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r),e.options=t.options});function union(e,t){return new uo({type:`union`,options:e,...normalizeParams(t)})}const fo=/*@__PURE__*/ $constructor(`ZodDiscriminatedUnion`,(e,t)=>{uo.init(e,t),Hi.init(e,t)});function discriminatedUnion(e,t,n){return new fo({type:`union`,options:t,discriminator:e,...normalizeParams(n)})}const po=/*@__PURE__*/ $constructor(`ZodIntersection`,(e,t)=>{Ui.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)});function intersection(e,t){return new po({type:`intersection`,left:e,right:t})}const mo=/*@__PURE__*/ $constructor(`ZodRecord`,(e,t)=>{_ensureDefaultMemoizer(),Wi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>recordProcessor(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function record(e,t,n){return!t||!t._zod?new mo({type:`record`,keyType:string(),valueType:e,...normalizeParams(t)}):new mo({type:`record`,keyType:e,valueType:t,...normalizeParams(n)})}const ho=/*@__PURE__*/ $constructor(`ZodEnum`,(e,t)=>{Gi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>enumProcessor(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new ho({...t,checks:[],...normalizeParams(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new ho({...t,checks:[],...normalizeParams(r),entries:i})}});function _enum(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ho({type:`enum`,entries:n,...normalizeParams(t)})}const go=/*@__PURE__*/ $constructor(`ZodLiteral`,(e,t)=>{Ki.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>literalProcessor(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new go({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const _o=/*@__PURE__*/ $constructor(`ZodTransform`,(e,t)=>{_ensureDefaultMemoizer(),qi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>transformProcessor(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(issue(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(issue(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function transform(e){return new _o({type:`transform`,transform:e})}const vo=/*@__PURE__*/ $constructor(`ZodOptional`,(e,t)=>{Ji.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function optional(e){return new vo({type:`optional`,innerType:e})}const yo=/*@__PURE__*/ $constructor(`ZodExactOptional`,(e,t)=>{Yi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>optionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function exactOptional(e){return new yo({type:`optional`,innerType:e})}const bo=/*@__PURE__*/ $constructor(`ZodNullable`,(e,t)=>{Xi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nullableProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nullable(e){return new bo({type:`nullable`,innerType:e})}const xo=/*@__PURE__*/ $constructor(`ZodDefault`,(e,t)=>{Zi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>defaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function _default(e,t){return new xo({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const So=/*@__PURE__*/ $constructor(`ZodPrefault`,(e,t)=>{Qi.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>prefaultProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function prefault(e,t){return new So({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const Co=/*@__PURE__*/ $constructor(`ZodNonOptional`,(e,t)=>{$i.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nonoptionalProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function nonoptional(e,t){return new Co({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const wo=/*@__PURE__*/ $constructor(`ZodCatch`,(e,t)=>{ea.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>catchProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function _catch(e,t){return new wo({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:constantCatch(t)})}const To=/*@__PURE__*/ $constructor(`ZodPipe`,(e,t)=>{ta.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pipeProcessor(e,t,n,r),e.in=t.in,e.out=t.out});function pipe(e,t){return new To({type:`pipe`,in:e,out:t})}const Eo=/*@__PURE__*/ $constructor(`ZodReadonly`,(e,t)=>{na.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>readonlyProcessor(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function readonly(e){return new Eo({type:`readonly`,innerType:e})}const Do=/*@__PURE__*/ $constructor(`ZodCustom`,(e,t)=>{ra.init(e,t),D.init(e,t),e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)});function custom(e,t){return/* @__PURE__ */ _custom(Do,e??(()=>!0),t)}function refine(e,t={}){return/* @__PURE__ */ _refine(Do,e,t)}function superRefine(e,t){return/* @__PURE__ */ _superRefine(e,t)}function safeParseWithSchema(e,t){let n=e.safeParse(t);return n.success?n.data:null}function safeParseJsonWithSchema(e,t){try{return safeParseWithSchema(e,JSON.parse(t))}catch{return null}}function readLockFileOwnerPayload(e){return e?{pid:typeof e.pid==`number`&&Number.isInteger(e.pid)&&e.pid>0?e.pid:void 0,createdAt:typeof e.createdAt==`string`?e.createdAt:void 0,starttime:typeof e.starttime==`number`&&Number.isInteger(e.starttime)&&e.starttime>=0?e.starttime:void 0}:null}function inspectStaleLockOwner(e){let t=readLockFileOwnerPayload(e.payload);if(!t?.pid)return null;if((e.isPidDefinitelyDead??Wt)(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??Ht)(t.pid),r={pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:n},i=process.platform===`darwin`&&t.starttime!==void 0&&t.starttime>1e10?Math.floor(t.starttime/1e6):t.starttime;return n!==null&&n!==i?{reason:`owner-starttime-changed`,...r}:null}function isLockOwnerDefinitelyStale(e){return inspectStaleLockOwner(e)!==null}const k=string().min(1).max(4096),Oo={pid:number().int().positive(),startIdentity:k.max(128)},ko=strictObject({...Oo,startIdentitySource:literal(`argv-sha256`).nullable().optional()}).refine(({startIdentity:e,startIdentitySource:t})=>t===`argv-sha256`?/^win32-argv-sha256:[a-f0-9]{64}$/.test(e):!e.startsWith(`win32-argv-sha256:`)),Ao=union([strictObject({platform:_enum([`linux`,`darwin`]),identity:string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i)}),strictObject({platform:literal(`win32`),identity:string().regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z$/)}),strictObject({platform:literal(`freebsd`),identity:string().regex(/^[a-f0-9]{32}$/)})]),jo=strictObject({kind:literal(`native`),unit:k,scope:k,placement:discriminatedUnion(`kind`,[strictObject({kind:literal(`pending`)}),strictObject({kind:literal(`attached`),invocation:string().regex(/^[a-f0-9]{32}$/i)})])}),Mo=literal(`original-cancellation-v1`),No=strictObject({kind:literal(`update`),mutationProtocol:Mo}).extend({mutationProtocol:Mo.optional(),custody:_enum([`reserved`,`bound`]).optional()}),Po=discriminatedUnion(`kind`,[No,strictObject({kind:literal(`triage`),phase:_enum([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:discriminatedUnion(`kind`,[strictObject({kind:literal(`foreground`),boot:Ao}),jo])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]),Fo=k.refine(x.isAbsolute,`Native source path must be absolute`),Io=string().regex(/^[a-f0-9]{64}$/),Lo=strictObject({runId:k,transactionId:k,claimId:k,revision:number().int().nonnegative(),recordSha256:Io,serviceKey:Fo,configPaths:array(Fo).min(1).max(512),lifetimeId:k}),Ro=strictObject({id:string().uuid(),phase:_enum([`reserved`,`admitted`]),source:Lo}),zo={executor:ko,helper:ko,action:Po},Bo=strictObject({version:literal(2),executor:ko,helper:ko,action:No}),Vo=strictObject({key:k,owner:k,payload:string().min(1),updatedAt:number().int().nonnegative()});discriminatedUnion(`version`,[strictObject({version:literal(4),executor:ko,helper:ko,action:No,cancellation:Vo}).refine(e=>{let t=safeParseJsonWithSchema(Bo,e.cancellation.payload);return t!==null&&JSON.stringify(t.helper)===JSON.stringify(e.helper)&&JSON.stringify(t.executor)===JSON.stringify(e.executor)&&JSON.stringify(t.action)===JSON.stringify(e.action)&&(JSON.stringify(e.helper)===JSON.stringify(e.executor)||t.action.mutationProtocol===`original-cancellation-v1`)}),strictObject({version:literal(2),...zo,mutationOriginal:Vo.optional()}).refine(e=>{if(!e.mutationOriginal)return!0;let t=safeParseJsonWithSchema(Bo,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`}),strictObject({version:literal(3),...zo,action:strictObject({kind:literal(`update`)}),nativeBorrower:Ro})]),strictObject({version:literal(1),...Oo});function createManagedHandoffBootIdentityReader(e){return function(){let t,n=process.platform===`android`?`linux`:process.platform;if(n===`linux`)t=b.readFileSync(`/proc/sys/kernel/random/boot_id`,`utf8`).trim();else if([`freebsd`,`darwin`,`win32`].includes(process.platform)){let n=process.platform===`freebsd`,r=process.platform===`win32`,i=dn(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`]: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=Ao.safeParse(r);if(!i.success)throw Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}}const[Ho,Uo,Wo]=Ao.options,Go=string().min(1),Ko=string().regex(/^[a-f0-9]{64}$/u),qo=discriminatedUnion(`platform`,[Ho.extend({host:Go,platform:literal(`linux`),pidNsInode:string().min(1)}),Ho.extend({host:Go,platform:literal(`darwin`)}),Uo.extend({host:Go,identity:Uo.shape.identity.optional()}),Wo.extend({host:Go})]);let Jo;function readGatewayLockProcessNamespace(){if(Jo?.platform===process.platform&&(Jo.value!==null||process.platform!==`linux`&&process.platform!==`android`))return Jo.value;try{let e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)(),t=qo.parse({host:nn.hostname(),...e,...e.platform===`linux`?{pidNsInode:b.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});return Jo={platform:process.platform,value:t},t}catch{return Jo={platform:process.platform,value:null},null}}function describeGatewayLockHolder(e,t,n){let r=qo.safeParse(e.processNamespace).data,i=e.heartbeatAt;if(t)try{i=b.statSync(t).mtimeMs}catch{}let 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; if it has already stopped, run `openclaw gateway recover-lock` to inspect and explicitly recover the unchanged owner":"Run this command inside the Gateway container or with a shared PID namespace; if the holder has stopped, run `openclaw gateway recover-lock` to inspect and explicitly recover the unchanged owner";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){super(`cannot verify Gateway ownership from this process; heartbeat age does not prove that the holder stopped. ${describeGatewayLockHolder(e,t)}`),this.name=`GatewayLockNamespaceError`}};function classifyGatewayLockProcessNamespace(e,t){if(process.platform===`win32`&&e&&e.processNamespace===void 0&&t){try{if(Date.now()-b.statSync(t).mtimeMs>9e4&&isLockOwnerDefinitelyStale({payload:{pid:e.pid,starttime:e.startTime}}))return`dead`}catch{}return`unknown`}return classifyGatewayOwnerProcessNamespace(e?.processNamespace,{machineIdentity:e?.machineIdentity})}function classifyGatewayOwnerProcessNamespace(e,t={}){let n=qo.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(n.platform===`darwin`&&t.machineIdentity!==void 0){let e=Ko.safeParse(t.machineIdentity).data,i=Ye();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 Yo=object({pid:number(),ownerId:string().min(1).optional(),stateOwnerKind:literal(`schema`).optional(),cronOwnerProjection:literal(`dynamic-default-v1`).optional(),createdAt:string(),startupPhase:literal(`starting`).optional(),configPath:string(),port:number().int().min(1).max(65535).optional(),role:_enum([`gateway`,`agent-embedded`,`skill-workshop-apply`,`sqlite-maintenance`]).optional(),stateDir:string().optional(),startTime:number().optional(),parentPid:number().int().positive().optional(),parentStartTime:number().optional(),processNamespace:qo.nullable().optional(),machineIdentity:Ko.nullable().optional()});function parseGatewayLockPayload(e){return safeParseJsonWithSchema(Yo,e)}function sha256Hex(e){return Xt(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}const Xo=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);function hasRestrictivePermissions(e){try{return!($t(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(e){let t;try{let n=$t(e).isDirectory()?e:x.dirname(e);t=x.join(n,`.openclaw-chmod-probe-${Zt()}`),tn(t,``,{flag:`wx`,mode:384})}catch{return!1}try{return Qt(t,384),!1}catch(e){return n(e)&&e.code===`EPERM`}finally{try{en(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&Xo.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if(($t(e).mode&4095)===t)return{applied:!0};try{return Qt(e,t),{applied:!0}}catch(t){if(!canIgnorePrivateChmodError(e,n(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:!1,error:t}}}function ensureOwnerDirectory(e,t){let n=b.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let r=x.toNamespacedPath(n),i=[];for(let t=e;;){let{dev:e,ino:n}=b.lstatSync(t,{bigint:!0});if(i.push({path:t,dev:e,ino:n}),x.toNamespacedPath(t)===r)break;let a=x.dirname(t);if(a===t)throw Error(`Created state ownership directory is outside its expected ancestry`);t=a}for(let e of i){let n=t.findIndex(t=>t.path===e.path);n<0?t.push(e):t[n]=e}}let r=b.lstatSync(e),i=process.getuid?.();if(!r.isDirectory()||i!==void 0&&r.uid!==i)throw Error(`State ownership directory must be a user-owned real directory`);if(process.platform!==`win32`&&(r.mode&4095)!=448&&(applyPrivateModeSync(e,448),b.lstatSync(e).mode&63))throw Error(`State ownership directory permissions are not private`)}function removeCreatedProjectionDirectories(e){let t=e[0];for(;t;){try{let e=b.lstatSync(t.path,{bigint:!0});e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino&&b.rmdirSync(t.path)}catch(e){let t=s(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift(),t=e[0]}}function resolveStateOwnerIdentity(e){let t=h(e);return stateOwnerIdentity(t,h(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await f(e);return stateOwnerIdentity(t,await f(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,n){return{canonicalPath:e,ownerPath:x.join(n,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?t(e):e}}function stateOwnerDirectory(e){let t=process.getuid?.();return process.platform===`win32`?x.join(nn.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):u(ne(e))}function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}const Zo=Date.now.bind(Date);function captureLock(e){let t=b.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,t){let n={};for(let t of e)n[t.lockPath]=captureLock(t);let r=Object.keys(n)[0];if(!r)throw Error(`Gateway state ownership requires a held lock`);let a=b.statSync(r,{bigint:!0}),{moduleUrl:o,runtimeGeneration:s}=we(be(`gatewayStateOwnerHeartbeat`));return i(()=>{let i=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(i,0,BigInt(Zo()));let{port1:u,port2:d}=new Kt,f=yt(o,{workerData:{clock:`epoch`,locks:n,intervalMs:15e3,failureMs:6e4,lastBeat:i.buffer,events:d},transferList:[d],execArgv:Gt(o)}),p=_t();f.on(`message`,e=>{e===`closed`&&p.resolve()}),f.unref();let ee=0,h=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of h.values())t.reject(e);h.clear(),u.unref()};u.on(`message`,e=>{if(bt(`lifecycle`,`from_worker`),e===`parent-lost`)Et();else if(e&&typeof e==`object`&&e.type===`lost`)t(/* @__PURE__ */ Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e==`object`&&e.type===`verified`){let t=h.get(e.id);h.delete(e.id),h.size===0&&u.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),u.unref(),f.on(`error`,e=>{let n=/* @__PURE__ */ Error(`${m(e)}; restart Gateway.`);rejectPending(n),t(n)}),f.once(`exit`,()=>{p.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let g,remainingUntilInspection=()=>{let e=Atomics.load(i,0),t=Zo()-Number(e);return t<0?0:6e4-t},inspect=()=>{let e=remainingUntilInspection();if(e<=0)throw Error(`Gateway state ownership renewal is overdue at ${r}; retry after storage recovers.`);return e},renewAsync=async()=>{let t=Zo(),o=new Date(t);for(let t of e)try{let i=n[t.lockPath];if(i===void 0)throw Error(`owner acquisition bytes were not registered`);let s=await b.promises.open(t.lockPath,`r+`);try{let n=await s.stat({bigint:!0}),c=await b.promises.lstat(t.lockPath,{bigint:!0}),l=Buffer.alloc(Buffer.byteLength(i)+1),{bytesRead:u}=await s.read(l,0,l.length,0),d=await b.promises.lstat(t.lockPath,{bigint:!0});if(g||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(n,c,i,l.subarray(0,u).toString(`utf8`))||!d.isFile()||d.dev!==n.dev||d.ino!==n.ino||t.lockPath===r&&(n.dev!==a.dev||n.ino!==a.ino)){if(t.lockPath!==r)continue;throw Error(`owner lock was removed or replaced`)}await s.utimes(o,o)}finally{await s.close()}}catch(e){if(t.lockPath!==r&&l(e,`ENOENT`))continue;throw e}!g&&e.size>0&&Atomics.store(i,0,BigInt(t))},v,te,watch=()=>{let e=remainingUntilInspection();e>0?(v=setTimeout(watch,e),v.unref()):te??=renewAsync().then(()=>{te=void 0,g||watch()},e=>{te=void 0,g||t(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${r}: ${m(e)}; restart the Gateway.`))})};watch();let stop=()=>(g||=(clearTimeout(v),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),u.close(),f.ref(),f.postMessage(`stop`,[]),(async()=>(await Bt(p.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${Ot}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),f.terminate()))()),Promise.all([g,te]).then(()=>void 0));s?.retain(f,async()=>async()=>{await stop()});let assertActive=()=>{if(g||f.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},ne=new Set(Object.keys(n));return{worker:f,paths:ne,register(e){let t=captureLock(e);n[e.lockPath]=t,f.postMessage([e.lockPath,t],[]),ne.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let t=++ee;return new Promise((n,r)=>{h.set(t,{resolve:n,reject:r}),u.ref();try{f.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){h.delete(t),h.size===0&&u.unref(),r(c(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 Qo=g(`gateway/state`);function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,A.clear(),e.heartbeat?.stop(),Qo.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 A=o(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),j=o(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map),$o=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),es=/* @__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=Lt(e,{commandPath:[`gateway`],booleanFlags:[...es,`--task-supervisor`],valueFlags:[...$o,`--task-supervisor-child`],mode:`command-path`});return t?t.length===0||t.length===1&&t[0]===`run`:!1}const ts=new Yt;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(t,n){let r=e(t)?t:null;if(!r)return!1;let i=classifyGatewayLockProcessNamespace(r,n);if(i===`unknown`)throw new GatewayLockNamespaceError(r,n);return comparableStateOwnerStaleReason(r,i)!==void 0}function assertPersistedStateDatabaseAccessAllowed(e){let{databasePath:t,ownerPath:n,assertMaintenance:r}=e,i=`OpenClaw state ownership at ${t} could not be verified from ${n}; restart the Gateway.`,a;try{a=b.readFileSync(n,`utf8`)}catch(e){if(s(e)===`ENOENT`)return;throw new wt(i,{cause:e})}let o=ts.getStore();if(o?.deadOwner?.path===n&&o.deadOwner.raw===a)return;let c=parseGatewayLockPayload(a);if(!c)throw new St(t,i);if(!Number.isSafeInteger(c.pid)||c.pid<=0)throw new wt(i);let l=classifyGatewayLockProcessNamespace(c,n),u=comparableStateOwnerStaleReason(c,l);if(u){o&&u===`owner-process-exited`&&(o.deadOwner={path:n,raw:a});return}if(l===`same`&&c.pid===process.pid&&!qt)return;if(l===`same`&&!Ut(c.pid))throw new St(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} (ownerKind=${c.stateOwnerKind??`process`}); retry when it finishes. For update progress, run \`openclaw update status --json\`.`;throw c.stateOwnerKind===`schema`&&c.role===`sqlite-maintenance`?new St(t,f):new Tt(t,f)}function defaultPayload(e){let t=ne(e),n=Ht(process.pid),r=Dt(),i=r===void 0?null:Ht(r);return{pid:process.pid,ownerId:Zt(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:x.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?Ye():void 0,...r===void 0?{}:{parentPid:r},...i===null?{}:{parentStartTime:i},...n===null?{}:{startTime:n}}}function assertGatewayRestorationPriority(e,t,n){if(n.role===`gateway`)return;let r;try{r=b.readFileSync(t,`utf8`)}catch(e){if(s(e)===`ENOENT`)return;throw e}let i=parseGatewayLockPayload(r);if(!(isGatewayStateOwnerDefinitelyStale(i,t)||i?.pid===n.pid)&&!(n.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&Rt(process.argv,{command:`gateway`}).kind===`openclaw`))throw new St(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,t,n,r=0,i){let a=performance.now()+r,o=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,o,n),ensureOwnerDirectory(x.dirname(t),i);let c={holder:null},stale=({payload:e})=>(c.holder=Yo.safeParse(e).data??null,isGatewayStateOwnerDefinitelyStale(c.holder,t));if(r>0)try{let n=c.holder=parseGatewayLockPayload(b.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&Ut(n.pid)))throw new vt(e)}catch(e){if(s(e)!==`ENOENT`)throw e}for(let l=!1;;)try{return vn(t,{lockPath:t,retry:r>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:!1}:{retries:0},timeoutMs:Math.max(0,Math.ceil(a-performance.now())),staleMs:1/0,staleRecovery:`remove-if-unchanged`,reentrantOwner:n.ownerId,payload:()=>(assertGatewayRestorationPriority(e,o,n),n),shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(n){let r=s(n);if(r===`ENOENT`&&!l){l=!0,ensureOwnerDirectory(x.dirname(t),i);continue}if(r===`file_lock_timeout`||r===`file_lock_stale`){let{holder:r}=c,i=describeGatewayLockHolder(r??{},t,r&&Ut(r.pid)?`live`:`unknown`);throw new vt(e,n,i,r?{pid:r.pid,role:r.role}:void 0)}throw n}}const ns=o(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new Yt);function getStateDatabaseSchemaLease(e){let t=ns.getStore()?.get(resolveStateOwnerIdentity(e).key);if(t&&!t.active)throw Error(`State schema maintenance scope is no longer current`);return t?.lease.assertCurrent(),t?.lease}function withStateDatabaseColdAdmission(e,t){let n=ot(e.busyTimeoutMs,`busyTimeoutMs`),r=performance.now()+n,i=h(e.databasePath),remainingBusyTimeoutMs=()=>Math.max(0,Math.ceil(r-performance.now())),a=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));for(;;)try{return assertStateDatabaseAccessAllowed(e.databasePath),t(remainingBusyTimeoutMs)}catch(t){if(!(t instanceof St)||h(t.databasePath)!==i||e.canRetry?.()===!1)throw t;let n=r-performance.now();if(n<=0)throw t;Atomics.wait(a,0,0,Math.min(10,n))}}function resolveGatewayStateOwnerPath(e){return resolveStateOwnerIdentity(e).ownerPath}function leaseForFile(e,t,n,r){let i=!1,holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent(),A.clear();let t=new Map(ns.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,A.clear()};try{let n=ns.run(t,e);return Le(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||j.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw Error(`OpenClaw state maintenance does not own this database`)},run,release(){A.clear(),i||(r?.release(),t.release(),i=!0,n.locks.delete(t),r&&n.locks.delete(r),n.locks.size===0&&j.get(n.key)===n&&(n.heartbeat?.stop(),n.accepting=!1,j.delete(n.key))),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){A.clear();let n=resolveStateOwnerIdentity(e),i=j.get(n.key),a=i?.path??n.ownerPath;if(i&&(!i.accepting||!hasPhysicalOwnership(i)))throw new vt(e,i.lost.signal.reason);i&&assertStateDatabaseAccessAllowed(e);let o=i?.payload??{...defaultPayload(e),stateOwnerKind:`schema`},s,c=[];try{s=acquireGatewayStateOwnerFile(e,a,o,i?0:t.busyTimeoutMs??5e3,c)}catch(t){if(t instanceof vt)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof St)throw e}throw t}let l=i?.projectionPath??x.join(r(ne(h(e))),`gateway.state.lock`),u;try{u=i?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,l,{...o,role:o.role===`gateway`?`gateway`:`agent-embedded`},0,c)}catch(e){return dt({release(){s.release(),removeCreatedProjectionDirectories(c)}},`state schema projection admission`,()=>{throw e})}i?(i.locks.add(s),i.locks.add(u),i.projectionDirectories.push(...c)):(i={key:n.key,path:a,kind:`schema`,payload:o,projectionPath:l,locks:/* @__PURE__ */ new Set([s,u]),projectionDirectories:c,lost:new AbortController,accepting:!0},j.set(i.key,i));let d=leaseForFile(a,s,i,u);try{let e=i.heartbeat??=startGatewayStateOwnerHeartbeat(i.locks,(e,t)=>observeOwnerLoss(i,e,t));return d.assertCurrent(),e.register(u),d}catch(e){return dt(d,`state schema ownership verification`,()=>{throw e})}}function prepareStateDatabaseReadAccess(e){return captureAdmittedGatewayStateOwner(e,!1)}async function captureAdmittedGatewayStateOwner(e,n){e.assertCurrent();let r=e.identity.canonicalPath,i=process.platform===`win32`?t(r):r,a=j.get(i);if(!a||a.kind!==`process`)return;let o={canonicalPath:r,key:i,ownerPath:a.path},assertRegistered=()=>{if(e.assertCurrent(),a.lost.signal.throwIfAborted(),j.get(i)!==a)throw xt()},assertCurrent=()=>{if(assertRegistered(),!a.accepting)throw xt();assertStateDatabaseAccessAtOwnerPath(r,o,void 0)},s=createStateDatabaseAccess(o,a),assertReadAllowed=e=>{assertRegistered(),s.assertReadAllowed(e)},c=x.resolve(e.databasePath),l=n?assertCurrent:assertRegistered;if(l(),n||A.get(c)!==a){let n=await f(c);if(l(),(process.platform===`win32`?t(n):n)!==i)throw new vt(e.databasePath)}return n||(assertReadAllowed(),A.get(x.resolve(r))===a&&A.set(c,a)),{ownerId:a.payload.ownerId,role:a.payload.role??`gateway`,signal:a.lost.signal,assertCurrent,assertReadAllowed,prepareAccess:s.prepareAccess}}function assertStateDatabaseReadAllowed(e,t){assertStateDatabaseReadAtOwnerPath(e,t)}function assertStateDatabaseReadAtOwnerPath(e,t,n){if(j.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}let r=x.resolve(e);if(A.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=j.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.`);A.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=j.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||j.get(e.key)!==r)throw xt()}}:void 0,prepareAccess:async r=>{let i=t??j.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&&j.get(e.key)!==i)throw xt();assertStateDatabaseReadAtOwnerPath(n,t,e)};let o=i.heartbeat,s=i.locks.values().next().value,c=i.getProjection?.();if(!o||!s)throw xt();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),o.assertActive(),j.get(e.key)!==i||i.heartbeat!==o)throw xt();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(s)||i.getProjection?.()!==c)throw xt()};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 A.set(x.resolve(n),i),assertCurrent},assertReadAllowed(t){assertStateDatabaseReadAtOwnerPath(n,t,e)}}}function assertStateDatabaseAccessAtOwnerPath(e,t,n){let assertMaintenance=()=>{let t=n?n.schemaLease:getStateDatabaseSchemaLease(e);if(t){t.assertDatabaseAccess(e);return}let r=n?n.maintenanceScope:Ce();if(!r)throw new Ct(e);r.assertDatabaseAccess(e)},r=j.get(t.key);if(r){if(!hasPhysicalOwnership(r))throw r.lost.signal.throwIfAborted(),Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`);let t=r.payload.role??`gateway`;(!r.accepting||t!==`gateway`&&t!==`agent-embedded`)&&assertMaintenance()}else assertPersistedStateDatabaseAccessAllowed({databasePath:e,ownerPath:t.ownerPath,assertMaintenance})}const rs=/* @__PURE__ */ new Set;function withSqliteSourceReadDatabase(e,t,n,r={}){assertStateDatabaseAccessAllowed(e);let i=ce(t,()=>ve(r.readOnlyShm?ye(e):e,{readOnly:!0,timeout:r.timeout}));try{return assertStateDatabaseAccessAllowed(e),n(i)}finally{try{i.close()}finally{i.isOpen&&rs.add(i)}}}const is=Buffer.from([217,213,5,249,32,161,99,215]);var SqliteSourceChangedError=class extends Error{constructor(e,t){super(t?.attempts?`SQLite source did not stabilize (reason=${e}, attempts=${t.attempts}) after ${t.attempts} read-only inspection attempts. Wait a moment for write activity to settle, then retry the inspection`:`SQLite source changed during read-only inspection (reason=${e})`,t),this.reason=e}};function statIfPresent(e){try{return b.statSync(e,{bigint:!0})}catch(e){if(e.code===`ENOENT`)return;throw e}}function readSourceSidecars(e){return{journal:!!statIfPresent(`${e}-journal`),shm:!!statIfPresent(`${e}-shm`),wal:!!statIfPresent(`${e}-wal`)}}function openPinnedFile(e,t){let n;try{n=b.openSync(e,`r`)}catch(e){throw e.code===`ENOENT`?new SqliteSourceChangedError(`source-disappeared`):e}try{let r=b.fstatSync(n,{bigint:!0});t&&_e(r,t);let i=statIfPresent(e);if(!r.isFile()||!i?.isFile()||!un(r,i))throw new SqliteSourceChangedError(`source-identity-changed`);return{descriptor:n,identity:r,pathname:e}}catch(e){throw b.closeSync(n),e}}function readSourceJournalMode(e,t){let n=openPinnedFile(e,t);try{let e=Buffer.alloc(20),t=b.readSync(n.descriptor,e,0,e.length,0);return assertPinnedIdentityUnchanged(n),t===0?`empty`:t!==e.length||e.subarray(0,16).toString(`utf8`)!==`SQLite format 3\0`?`unknown`:e[18]===2||e[19]===2?`wal`:`rollback`}finally{b.closeSync(n.descriptor)}}function assertPinnedIdentityUnchanged(e){let t=b.fstatSync(e.descriptor,{bigint:!0}),n=statIfPresent(e.pathname);if(!t.isFile()||!n?.isFile()||!un(e.identity,t)||!un(e.identity,n))throw new SqliteSourceChangedError(`source-identity-changed`)}function copySourceFile(e,t,n){let r=openPinnedFile(e,n);try{let n;try{n=b.realpathSync.native(e)}catch(e){throw s(e)===`ENOENT`?new SqliteSourceChangedError(`source-disappeared`,{cause:e}):e}let i=on({source:{rootPath:x.dirname(n),absolutePath:n},destination:{rootPath:x.dirname(t),absolutePath:t},expectedSourceIdentity:r.identity,sourceHardlinks:`allow`,clone:`auto`,mode:384});try{b.fsyncSync(i.fd),assertPinnedIdentityUnchanged(r)}finally{i.close()}}finally{b.closeSync(r.descriptor)}}function sourceMatchesCopy(e,t,n){let r=openPinnedFile(e,n);try{let e=b.openSync(t,`r`);try{if(!b.fstatSync(e).isFile())return!1;let t=ln(r.descriptor,e);return assertPinnedIdentityUnchanged(r),t}finally{b.closeSync(e)}}finally{b.closeSync(r.descriptor)}}function assertExpectedSidecars(e,t){let n=readSourceSidecars(e);if(n.journal!==t.journal||n.wal!==t.wal)throw new SqliteSourceChangedError(`journal-state-changed`)}function isSqliteReadOnlyError(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e+=1){let e=t;if(typeof e.errcode==`number`&&(e.errcode&255)==8)return!0;t=e.cause}return!1}function rollbackJournalReferencesSuperJournal(e){let t=b.openSync(e,`r`);try{let e=b.fstatSync(t).size;if(e<16)return!1;let n=Buffer.allocUnsafe(16);if(b.readSync(t,n,0,n.length,e-n.length)!==n.length)return!1;let r=n.readUInt32BE(0);return r>0&&r<=e-20&&n.subarray(8).equals(is)}finally{b.closeSync(t)}}function syncPrivateSnapshot(e){let t=b.openSync(e,`r+`);try{b.fsyncSync(t)}finally{b.closeSync(t)}}function recoverPrivateJournalCopy(e){if(rollbackJournalReferencesSuperJournal(`${e}-journal`))throw Error(`SQLite hot rollback journal references a super-journal and cannot be recovered privately: ${e}`);let t=ve(e);try{t.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF;`),t.prepare(`PRAGMA schema_version;`).get()}finally{t.close()}b.rmSync(`${e}-journal`,{force:!0}),syncPrivateSnapshot(e)}function*createStableReadOnlyCopyInTempDirectory(e,t,n,r=n?x.dirname(n):resolvePrivateSqliteSnapshotStagingRoot(),i,a){let o=n;try{o??=createSqliteSnapshotStagingDirectorySync(r);let n=x.join(o,`database.sqlite.partial`),s=x.join(o,`first`);if(process.platform!==`win32`&&b.chmodSync(o,448),readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);let c=readSourceSidecars(e),l=!1;if(t===`wal`&&c.wal&&!c.journal){let t=openPinnedFile(`${e}-wal`);try{let r=prepareSqliteWalPrefixCopy(t.descriptor,`${n}-wal`,()=>sourceMatchesCopy(e,n,i));r&&(yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i});let a=r?.();if(assertPinnedIdentityUnchanged(t),a===!1)throw new SqliteSourceChangedError(`wal-copy-unstable`);l=a===!0}finally{b.closeSync(t.descriptor)}}let u=[...c.journal?[`-journal`]:[],...c.wal?[`-wal`]:[]];if(l)assertExpectedSidecars(e,c);else if(u.length>0){for(let t of u)yield{sourcePath:`${e}${t}`,targetPath:`${n}${t}`};if(yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i},!sourceMatchesCopy(e,n,i))throw new SqliteSourceChangedError(`main-changed-during-copy`);for(let t of u)if(!sourceMatchesCopy(`${e}${t}`,`${n}${t}`))throw new SqliteSourceChangedError(t===`-wal`?`wal-changed-during-copy`:`rollback-journal-changed-during-copy`);assertExpectedSidecars(e,c)}else{yield{sourcePath:e,targetPath:s,expectedSourceIdentity:i},assertExpectedSidecars(e,c);let t=a!==void 0||sourceMatchesCopy(e,s,i);if(assertExpectedSidecars(e,c),!t)throw new SqliteSourceChangedError(`main-changed-during-copy`);b.rmSync(n,{force:!0}),b.renameSync(s,n)}if(readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);if(a&&(c.journal||c.wal&&b.statSync(`${n}-wal`).size!==0))throw new SqliteSourceChangedError(`recovery-data-appeared`);return c.journal&&recoverPrivateJournalCopy(n),ke(o,a)}catch(t){let r=o?sqliteSnapshotStagingError(o,t,!1,e):t;if(o&&n===void 0){let e=[r];if(!ge(o,t=>e.push(t)))throw de(e,`SQLite snapshot preparation`)}throw r}}function copyPreparedLocationSync(e){let t=e.next();for(;!t.done;){try{let{sourcePath:e,targetPath:n,expectedSourceIdentity:r}=t.value;copySourceFile(e,n,r)}catch(n){t=e.throw(n);continue}t=e.next()}return t.value}async function copyPreparedLocation(e){let t=e.next();for(;!t.done;){try{let{sourcePath:e,targetPath:n,expectedSourceIdentity:r}=t.value,i=openPinnedFile(e,r);try{await copySqliteFile(e,n,i.identity)}finally{try{assertPinnedIdentityUnchanged(i)}finally{b.closeSync(i.descriptor)}}}catch(n){t=e.throw(n);continue}t=e.next()}return t.value}async function createOnlineReadOnlyBackup(e,t,n,r){let i=typeof t==`object`?t.directory:await createSqliteSnapshotStagingDirectory(t,!1,n),a=x.join(i,`database.sqlite.partial`);try{process.platform!==`win32`&&b.chmodSync(i,448);let t=ce(`source`,()=>ve(e,{readOnly:!0}));try{t.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF; BEGIN;`),t.prepare(`PRAGMA schema_version;`).get(),await ut(backupNodeSqliteDatabase(t,a,r)),t.exec(`ROLLBACK;`)}finally{t.isOpen&&t.close()}let n=ve(a);try{n.exec(`PRAGMA journal_mode = DELETE;`)}finally{n.close()}return syncPrivateSnapshot(a),ke(i)}catch(n){let r=sqliteSnapshotStagingError(i,n,!1,e);return se(i,r,`SQLite online backup`,typeof t==`object`)}}function*prepareArtifactPreservingCopy(e,t,n,r){let i=b.realpathSync.native(e);for(let e=0;;e+=1)try{return yield*createStableReadOnlyCopyInTempDirectory(i,readSourceJournalMode(i,n),typeof t==`object`?t.directory:void 0,typeof t==`string`?t:void 0,n,r)}catch(n){if(typeof t==`object`&&at(t.directory,n),!(n instanceof SqliteSourceChangedError))throw n;if(e+1>=10)throw new SqliteSourceChangedError(n.reason,{cause:n,attempts:10});waitForSnapshotRetrySync(e)}}function prepareSqliteReadOnlyLocationSyncInProcess(e,t,n,r){return copyPreparedLocationSync(prepareArtifactPreservingCopy(e,t,n,r))}const as=/* @__PURE__ */ new Set([`wal-copy-unstable`,`main-changed-during-copy`,`wal-changed-during-copy`]);async function prepareSqliteReadOnlyCopyInProcess(e,t,n){try{return await copyPreparedLocation(prepareArtifactPreservingCopy(e,t,n))}catch(r){if(!(r instanceof SqliteSourceChangedError)||!as.has(r.reason))throw r;let i=b.realpathSync.native(e),a=openPinnedFile(i,n);try{let e=readSourceSidecars(i);if(readSourceJournalMode(i,n)!==`wal`||!e.wal||!e.shm||e.journal)throw r;let o=await createOnlineReadOnlyBackup(i,t);try{assertPinnedIdentityUnchanged(a)}catch(e){throw o.cleanup(),e}return o}finally{b.closeSync(a.descriptor)}}}async function prepareSqliteReadOnlyLocationFromOwnedDatabase(e,t,n,r){let assertReady=()=>{if(n?.throwIfAborted(),t(),!e.isOpen||e.isTransaction)throw Error(`SQLite inspection requires an open owner outside a transaction`)};assertReady();let i=await createSqliteSnapshotStagingDirectory(void 0,!1,n,r===`async`);try{assertReady();let r=x.join(i,`database.sqlite.partial`);return await ut(backupNodeSqliteDatabase(e,r)),n?.throwIfAborted(),t(),ke(i)}catch(e){let t=[e];throw!await te(i,e=>t.push(e))&&r===`async`?de(t,`Owned SQLite snapshot preparation`):e}}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(e){let t=b.lstatSync(e,{bigint:!0,throwIfNoEntry:!1});if(t){if(!t.isFile()||t.nlink!==1n)throw Error(`Private SQLite snapshot must be an independent regular file: ${e}`);return t}}function captureSqlitePrivateSnapshotFamily(e,t){if(b.lstatSync(`${e}-journal`,{throwIfNoEntry:!1}))return;let n=readFile(e),r=readFile(`${e}-wal`);return n?{root:t,main:fingerprint(n),wal:r&&r.size>32n?walFingerprint(r):null}:void 0}function readSqliteIntegrityFileIdentity(e,t){let n=b.statSync(e,{bigint:!0});if(!n.isFile()||t&&!un(t,n))throw Error(`SQLite source changed during integrity admission: ${e}`);return{dev:n.dev,ino:n.ino,size:n.size}}function canRetainDigest(e,t){let n=t-2000000000n;return typeof e.dev==`bigint`&&typeof e.ino==`bigint`&&typeof e.size==`bigint`&&e.dev!==0n&&e.ino!==0n&&typeof e.birthtimeNs==`bigint`&&typeof e.mtimeNs==`bigint`&&typeof e.ctimeNs==`bigint`&&e.mtimeNs>0n&&e.ctimeNs>0n&&e.mtimeNs<n&&e.ctimeNs<n}function timestampNs(e,t){return e??(typeof t==`bigint`?t*1000000n:BigInt(Math.trunc(t*1e6)))}function fingerprintFile(e,t){let n=BigInt(Date.now())*1000000n,r=b.openSync(e,`r`);try{let i=b.fstatSync(r,{bigint:!0});if(!i.isFile())throw Error(`SQLite generation target must be a regular file`);let a=t.get(e);if(a&&canRetainDigest(i,n)&&ze(a,i)){let t=b.fstatSync(r,{bigint:!0}),n=b.statSync(e,{bigint:!0});if(n.isFile()&&ze(i,t)&&ze(t,n))return a}let{sha256:o}=Pe(b.realpathSync.native(e),i),s=b.fstatSync(r,{bigint:!0}),c=b.statSync(e,{bigint:!0});if(!$e(i,s)||!$e(s,c))throw Error(`SQLite generation target changed while hashing: ${e}`);let l={birthtimeNs:timestampNs(s.birthtimeNs,s.birthtimeMs),ctimeNs:timestampNs(s.ctimeNs,s.ctimeMs),dev:s.dev,ino:s.ino,mtimeNs:timestampNs(s.mtimeNs,s.mtimeMs),sha256:o,size:s.size};return canRetainDigest(i,n)&&ze(i,s)&&ze(s,c)?t.set(e,l):t.delete(e),l}finally{b.closeSync(r)}}function readOptionalFile(e,t){try{return fingerprintFile(e,t)}catch(n){if(n.code===`ENOENT`){t.delete(e);return}throw n}}function createSqliteFileGenerationReader(){let e=/* @__PURE__ */ new Map;return t=>{let n=fingerprintFile(t,e),r=readOptionalFile(`${t}-journal`,e),i=readOptionalFile(`${t}-wal`,e);return{database:n,...r?{journal:r}:{},...i?{wal:i}:{}}}}function readStableSqliteFileGeneration(e,t=createSqliteFileGenerationReader()){let n=t(e),r=t(e);if(!sameSqliteFileGeneration(n,r))throw Error(`SQLite file generation changed while reading: ${e}`);return r}function sameFileFingerprint(e,t){return e.dev===t.dev&&e.ino===t.ino&&$e(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 serializeFileFingerprint(e){return{birthtimeNs:e.birthtimeNs.toString(),ctimeNs:e.ctimeNs.toString(),dev:e.dev.toString(),ino:e.ino.toString(),mtimeNs:e.mtimeNs.toString(),sha256:e.sha256,size:e.size.toString()}}function serializeSqliteFileGeneration(e){return JSON.stringify({database:serializeFileFingerprint(e.database),...e.journal?{journal:serializeFileFingerprint(e.journal)}:{},...e.wal?{wal:serializeFileFingerprint(e.wal)}:{}})}function parseFileFingerprint(t){if(!e(t))throw Error(`SQLite file fingerprint must be an object`);for(let e of[`birthtimeNs`,`ctimeNs`,`dev`,`ino`,`mtimeNs`,`size`])if(typeof t[e]!=`string`||!/^-?\d+$/u.test(t[e]))throw Error(`SQLite file fingerprint ${e} is invalid`);if(typeof t.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(t.sha256))throw Error(`SQLite file fingerprint sha256 is invalid`);return{birthtimeNs:BigInt(t.birthtimeNs),ctimeNs:BigInt(t.ctimeNs),dev:BigInt(t.dev),ino:BigInt(t.ino),mtimeNs:BigInt(t.mtimeNs),sha256:t.sha256,size:BigInt(t.size)}}function parseSqliteFileGeneration(t){let n=JSON.parse(t);if(!e(n))throw Error(`SQLite file generation must be an object`);return{database:parseFileFingerprint(n.database),...n.journal===void 0?{}:{journal:parseFileFingerprint(n.journal)},...n.wal===void 0?{}:{wal:parseFileFingerprint(n.wal)}}}const os=o(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));function getDatabaseProcessRole(){return os.role}let ss=0;function withEngineStoreAdmission(e){ss+=1;try{let t=e();if(Le(t))throw Error(`Database engine admission must remain synchronous`);return t}finally{--ss}}function assertEngineStoreExecutionAllowed(){if(Jt===0&&ss===0&&os.role!==`cli-oneshot`)throw Error(`PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread`)}const cs=18e5;function resolveAgentDatabaseIdleHandleTtlMs(){return getDatabaseProcessRole()===`cli-oneshot`?3e4:cs}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 M=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]})}}),N=freeze({is(e){return e.kind===`IdentifierNode`},create(e){return freeze({kind:`IdentifierNode`,name:e})}}),P=freeze({is(e){return e.kind===`CreateIndexNode`},create(e){return freeze({kind:`CreateIndexNode`,name:N.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}}),ls=freeze({is(e){return e.kind===`CreateSchemaNode`},create(e,t){return freeze({kind:`CreateSchemaNode`,schema:N.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),us=[`preserve rows`,`delete rows`,`drop`],F=freeze({is(e){return e.kind===`CreateTableNode`},create(e){return freeze({kind:`CreateTableNode`,table:e,columns:freeze([])})},cloneWithColumn(e,t){return freeze({...e,columns:freeze([...e.columns,t])})},cloneWithConstraint(e,t){return freeze({...e,constraints:e.constraints?freeze([...e.constraints,t]):freeze([t])})},cloneWithIndex(e,t){return freeze({...e,indexes:e.indexes?freeze([...e.indexes,t]):freeze([t])})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWith(e,t){return freeze({...e,...t})}}),ds=freeze({is(e){return e.kind===`SchemableIdentifierNode`},create(e){return freeze({kind:`SchemableIdentifierNode`,identifier:N.create(e)})},createWithSchema(e,t){return freeze({kind:`SchemableIdentifierNode`,schema:N.create(e),identifier:N.create(t)})}}),fs=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:ds.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),ps=freeze({is(e){return e.kind===`DropSchemaNode`},create(e,t){return freeze({kind:`DropSchemaNode`,schema:N.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),ms=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}}),hs=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),I=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:ds.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:ds.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 gs=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})}}),_s=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),vs=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),ys=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`?_s.create(e.on,n):vs.create(e.on,n)})}}),bs=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:ys.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?ys.cloneWithOperation(e.on,`And`,t):ys.create(t)})}}),xs=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),Ss=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(Ss);const Cs=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(Cs);const ws=freeze({"->":!0,"->>":!0}),Ts=Object.keys(ws),Es=freeze({...Ss,...Cs,"||":!0}),Ds=Object.keys(Es),Os=freeze({exists:!0,"not exists":!0});Object.keys(Os);const ks=freeze({...Os,"-":!0,not:!0}),As=Object.keys(ks);[...Ds,...Ts,...As];const js=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&Es[e]}function isJSONOperator(e){return isString(e)&&ws[e]}function isUnaryOperator(e){return isString(e)&&ks[e]}const L=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:N.create(e)})}}),Ms=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),Ns=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:Ms.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 Ps=freeze({is(e){return e.kind===`OrderByItemNode`},create(e,t){return freeze({kind:`OrderByItemNode`,orderBy:e,direction:t})},cloneWith(e,t){return freeze({...e,...t})}}),R=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return R.create([e],[])},createWithChild(e){return R.create([``,``],[e])},createWithChildren(e){return R.create(Array(e.length+1).fill(``),e)}}),Fs=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:N.create(e)})}});var Is=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:Ps.cloneWith(this.#e.node,{direction:R.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:Ps.cloneWith(this.#e.node,{direction:R.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:Ps.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:Ps.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:Ps.cloneWith(this.#e.node,{collation:Fs.create(e)})})}toOperationNode(){return this.#e.node}};const Ls=/* @__PURE__ */ new Set;function logOnce(e){Ls.has(e)||(Ls.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(Ps.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 Ps.create(e,R.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),Ps.create(e,t.toOperationNode());let n=Ps.create(e);return t?t(new Is({node:n})).toOperationNode():n}const Rs=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})}}),zs=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])})}}),Bs=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 Rs.create(parseStringReference(e),zs.create(js.create(t)));if(t===`->$`||t===`->>$`)return Rs.create(parseStringReference(e),Bs.create(js.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return Ns.create(L.create(e));let t=e.split(`.`).map(trim$2);if(t.length===3)return parseStringReferenceWithTableAndSchema(t);if(t.length===2)return parseStringReferenceWithTable(t);throw Error(`invalid column reference ${e}`)}function parseAliasedStringReference(e){let t=` as `;if(e.includes(t)){let[n,r]=e.split(t).map(trim$2);return hs.create(parseStringReference(n),N.create(r))}return parseStringReference(e)}function parseColumnName(e){return L.create(e)}function parseOrderedColumnName(e){if(e.includes(` `)){let[t,n]=e.split(` `).map(trim$2);if(!isOrderByDirection(n))throw Error(`invalid order direction "${n}" next to "${t}"`);return parseOrderBy([t,n])[0]}return parseColumnName(e)}function parseStringReferenceWithTableAndSchema(e){let[t,n,r]=e;return Ns.create(L.create(r),I.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return Ns.create(L.create(n),I.create(t))}function trim$2(e){return e.trim()}const Vs=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),Hs=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),z=freeze({is(e){return e.kind===`ValueNode`},create(e){return freeze({kind:`ValueNode`,value:e})},createImmediate(e){return freeze({kind:`ValueNode`,value:e,immediate:!0})}});function parseValueExpressionOrList(e){return isReadonlyArray(e)?parseValueExpressionList(e):parseValueExpression(e)}function parseValueExpression(e){return isExpressionOrFactory(e)?parseExpression(e):z.create(e)}function isSafeImmediateValue(e){return isNumber(e)||isBoolean(e)||isNull(e)}function parseSafeImmediateValue(e){if(!isSafeImmediateValue(e))throw Error(`unsafe immediate value ${JSON.stringify(e)}`);return z.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?Hs.create(e.map(e=>parseValueExpression(e))):Vs.create(e)}const Us=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)?xs.create(parseReferenceExpression(e),parseBinaryOperator(t),z.createImmediate(n)):xs.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return xs.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`?_s.create:vs.create;if(e.length===0)return xs.create(z.createImmediate(1),js.create(`=`),z.createImmediate(+(t===`and`)));let i=toOperationNode(e[0]);for(let t=1;t<e.length;++t)i=r(i,toOperationNode(e[t]));return e.length>1&&n?Us.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 js.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 Ws=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])})}}),Gs=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])})}}),Ks=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Ws.cloneWithItems(e.orderBy,t):Ws.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?Gs.cloneWithItems(e.partitionBy,t):Gs.create(t)})}}),qs=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])})}}),Js=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])})}}),Ys=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`?_s.create(e.having,n):vs.create(e.having,n)})}}),B=freeze({is(e){return e.kind===`InsertQueryNode`},create(e,t,n){return freeze({kind:`InsertQueryNode`,into:e,...t&&{with:t},replace:n})},createWithoutInto(){return freeze({kind:`InsertQueryNode`})},cloneWith(e,t){return freeze({...e,...t})}}),Xs=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),Zs=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:Xs.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?qs.cloneWithFroms(e.from,t):qs.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),Qs=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])})}}),$s=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:qs.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>U.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>U.cloneWithoutOrderBy(e),cloneWithLimit(e,t){return freeze({...e,limit:t})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithUsing(e,t){return freeze({...e,using:e.using===void 0?Qs.create(t):Qs.cloneWithTables(e.using,t)})}}),V=freeze({is(e){return e.kind===`WhereNode`},create(e){return freeze({kind:`WhereNode`,where:e})},cloneWithOperation(e,t,n){return freeze({...e,where:t===`And`?_s.create(e.where,n):vs.create(e.where,n)})}}),ec=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)})}}),tc=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),nc=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),H=freeze({is(e){return e.kind===`MergeQueryNode`},create(e,t){return freeze({kind:`MergeQueryNode`,into:e,...t&&{with:t}})},cloneWithUsing(e,t){return freeze({...e,using:t})},cloneWithWhen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens,t]):freeze([t])})},cloneWithThen(e,t){return freeze({...e,whens:e.whens?freeze([...e.whens.slice(0,-1),nc.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),rc=freeze({is(e){return e.kind===`OutputNode`},create(e){return freeze({kind:`OutputNode`,selections:freeze(e)})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})}}),U=freeze({is(e){return W.is(e)||B.is(e)||Zs.is(e)||$s.is(e)||H.is(e)},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):freeze([t])})},cloneWithWhere(e,t){return freeze({...e,where:e.where?V.cloneWithOperation(e.where,`And`,t):V.create(t)})},cloneWithJoin(e,t){return freeze({...e,joins:e.joins?freeze([...e.joins,t]):freeze([t])})},cloneWithReturning(e,t){return freeze({...e,returning:e.returning?ec.cloneWithSelections(e.returning,t):ec.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:tc.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?rc.cloneWithSelections(e.output,t):rc.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Ws.cloneWithItems(e.orderBy,t):Ws.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),W=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:qs.create(e),...t&&{with:t}})},cloneWithSelections(e,t){return freeze({...e,selections:e.selections?freeze([...e.selections,...t]):freeze(t)})},cloneWithDistinctOn(e,t){return freeze({...e,distinctOn:e.distinctOn?freeze([...e.distinctOn,...t]):freeze(t)})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):freeze([t])})},cloneWithOrderByItems:(e,t)=>U.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?Js.cloneWithItems(e.groupBy,t):Js.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?Ys.cloneWithOperation(e.having,`And`,t):Ys.create(t)})},cloneWithSetOperations(e,t){return freeze({...e,setOperations:e.setOperations?freeze([...e.setOperations,...t]):freeze([...t])})},cloneWithoutSelections(e){return freeze({...e,selections:[]})},cloneWithoutLimit(e){return freeze({...e,limit:void 0})},cloneWithoutOffset(e){return freeze({...e,offset:void 0})},cloneWithoutOrderBy:e=>U.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var ic=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:bs.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:bs.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:bs.cloneWithOn(this.#e.joinNode,R.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const ac=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map(ac.create)}var oc=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:Ks.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:U.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:Ks.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const sc=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:Ms.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:Ns.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)?sc.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?sc.create(e.toOperationNode()):sc.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[sc.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return sc.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}const cc=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}}),lc=freeze({is(e){return e.kind===`DefaultInsertValueNode`},create(){return freeze({kind:`DefaultInsertValueNode`})}});function parseInsertExpression(e){let t=isFunction(e)?e(expressionBuilder()):e;return parseInsertColumnsAndValues(isReadonlyArray(t)?t:freeze([t]))}function parseInsertColumnsAndValues(e){let t=parseColumnNamesAndIndexes(e);return[freeze([...t.keys()].map(L.create)),cc.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=lc.create();return Hs.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return Vs.create(r)}const uc=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?[uc.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])=>uc.create(L.create(e),parseValueExpression(t)))}const dc=freeze({is(e){return e.kind===`OnDuplicateKeyNode`},create(e){return freeze({kind:`OnDuplicateKeyNode`,updates:e})}});var InsertResult=class{insertId;numInsertedOrUpdatedRows;constructor(e,t){this.insertId=e,this.numInsertedOrUpdatedRows=t}},NoResultError=class extends Error{node;constructor(e){super(`no result`),this.node=e}};function isNoResultErrorConstructor(e){return Object.prototype.hasOwnProperty.call(e,`prototype`)}const G=freeze({is(e){return e.kind===`OnConflictNode`},create(){return freeze({kind:`OnConflictNode`})},cloneWith(e,t){return freeze({...e,...t})},cloneWithIndexWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?V.cloneWithOperation(e.indexWhere,`And`,t):V.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?V.cloneWithOperation(e.indexWhere,`Or`,t):V.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?V.cloneWithOperation(e.updateWhere,`And`,t):V.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?V.cloneWithOperation(e.updateWhere,`Or`,t):V.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}});var fc=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=L.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,t]):freeze([t])})})}columns(e){let t=e.map(L.create);return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,...t]):freeze(t)})})}constraint(e){return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWith(this.#e.onConflictNode,{constraint:N.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:G.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:G.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new pc({...this.#e,onConflictNode:G.cloneWith(this.#e.onConflictNode,{updates:parseUpdateObjectExpression(e)})})}$call(e){return e(this)}},OnConflictDoNothingBuilder=class{#e;constructor(e){this.#e=freeze(e)}toOperationNode(){return this.#e.onConflictNode}},pc=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:G.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:G.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:G.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}};const mc=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 mc.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const hc=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}});var gc=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{columns:freeze(e.map(L.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:hc.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:hc.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:hc.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:hc.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:hc.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{orAction:hc.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{onConflict:e(new fc({onConflictNode:G.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:B.cloneWith(this.#e.queryNode,{onDuplicateKey:dc.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new InsertQueryBuilder({...this.#e})}$castTo(){return new InsertQueryBuilder(this.#e)}$narrowType(){return new InsertQueryBuilder(this.#e)}$assertType(){return new InsertQueryBuilder(this.#e)}withPlugin(e){return new InsertQueryBuilder({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new InsertResult(n.insertId,n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new InsertQueryBuilder({...this.#e,queryNode:U.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}};const _c=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}});var K,DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new K({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new K({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new K({...this.#e,queryNode:U.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new K({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new K({...this.#e,queryNode:$s.cloneWithUsing(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new K({...this.#e,queryNode:U.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new K({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new K({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new K({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new K({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new K({...this.#e,queryNode:U.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new K({...this.#e,queryNode:$s.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new K({...this.#e,queryNode:U.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new K({...this.#e,queryNode:U.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new K({...this.#e,queryNode:$s.cloneWithLimit(this.#e.queryNode,_c.create(parseValueExpression(e)))})}modifyEnd(e){return new K({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new K({...this.#e})}$castTo(){return new K(this.#e)}$narrowType(){return new K(this.#e)}$assertType(){return new K(this.#e)}withPlugin(e){return new K({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new DeleteResult(n.numAffectedRows??BigInt(0))]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new K({...this.#e,queryNode:U.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};K=DeleteQueryBuilder;var UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},q,UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new q({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new q({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new q({...this.#e,queryNode:U.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new q({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new q({...this.#e,queryNode:Zs.cloneWithFromItems(this.#e.queryNode,parseTableExpressionOrList(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}#t(e,t){return new q({...this.#e,queryNode:U.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new q({...this.#e,queryNode:U.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new q({...this.#e,queryNode:U.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new q({...this.#e,queryNode:Zs.cloneWithLimit(this.#e.queryNode,_c.create(parseValueExpression(e)))})}set(...e){return new q({...this.#e,queryNode:Zs.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new q({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new q({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new q({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new q({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new q({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new q({...this.#e,queryNode:U.cloneWithoutReturning(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new q({...this.#e})}$castTo(){return new q(this.#e)}$narrowType(){return new q(this.#e)}$assertType(){return new q(this.#e)}withPlugin(e){return new q({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new UpdateResult(n.numAffectedRows??BigInt(0),n.numChangedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new q({...this.#e,queryNode:U.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};q=UpdateQueryBuilder;const vc=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:I.create(e),columns:t?freeze(t.map(L.create)):void 0})}}),yc=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 bc=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:yc.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:yc.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():yc.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new bc({node:yc.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 vc.create(n,r)}return vc.create(e)}const xc=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])})}}),Sc=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return Sc[~~(Math.random()*Sc.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 Cc={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)&&Cc[e.kind]===!0}const wc=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:N.create(this.#e)}}transformReferences(e,t){let n=super.transformReferences(e,t);return n.table.table.schema?n:{...n,table:I.createWithSchema(this.#e,n.table.table.identifier.name)}}transformAggregateFunction(e,t){return{...super.transformAggregateFunction({...e,aggregated:[]},t),aggregated:this.#r(e,t,`aggregated`)}}transformFunction(e,t){return{...super.transformFunction({...e,arguments:[]},t),arguments:this.#r(e,t,`arguments`)}}transformSelectModifier(e,t){return{...super.transformSelectModifier({...e,of:void 0},t),of:e.of?.map(e=>I.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return wc[e.func]?e[n].map(e=>!I.is(e)||e.table.schema?this.transformNode(e,t):{...e,table:this.transformIdentifier(e.table.identifier,t)}):this.transformNodeList(e[n],t)}#i(e){let t=/* @__PURE__ */ new Set;if(`name`in e&&e.name&&ds.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&&(bs.is(e.using)?this.#o(e.using.table,t):this.#o(e.using,t)),t}#a(e){let t=/* @__PURE__ */ new Set;return`with`in e&&e.with&&this.#c(e.with,t),t}#o(e,t){if(I.is(e))return this.#s(e.table,t);if(hs.is(e)&&I.is(e.node))return this.#s(e.node.table,t);if(Xs.is(e))for(let n of e.items)this.#o(n,t);else if(Qs.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 Tc=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 nc.create(parseFilterList([Tc.create(!e.isMatched,e.bySource),...t&&t.length>0?[t.length===3&&n?parseReferentialBinaryOperation(t[0],t[1],t[2]):parseValueBinaryOperationOrExpression(t)]:[]],`and`,!1))}function parseMergeThen(e){return isString(e)?R.create([e],[]):isOperationNodeSource(e)?e.toOperationNode():e}var Deferred=class{#e;#t;#n;constructor(){this.#e=new Promise((e,t)=>{this.#n=t,this.#t=e})}get promise(){return this.#e}resolve=e=>{this.#t?.(e),this.#t=this.#n=void 0};reject=e=>{this.#n?.(e),this.#n=this.#t=void 0}};async function provideControlledConnection(e,t){let n=new Deferred,r=new Deferred;return e.provideConnection(async e=>(n.resolve(e),await r.promise),t).catch(e=>n.reject(e)),freeze({connection:await n.promise,release:r.resolve})}function getInflightQueryAbortHandler(e=`ignore query`,t,n){if(e!==`ignore query`){if(e===`cancel query`){let r=t.cancelQuery;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.killSession?`kill session`:void 0)),r.bind(t)}if(e===`kill session`){let r=t.killSession;return r||(n(),throwUnsupportedInflightQueryAbortStrategyError(e,t.cancelQuery?`cancel query`:void 0)),r.bind(t)}throw n(),Error(`Unexpected \`inflightQueryAbortStrategy\`: "${e}"`)}}function throwUnsupportedInflightQueryAbortStrategyError(e,t){throw Error(`This dialect doesn't support \`inflightQueryAbortStrategy\` "${e}". Use "ignore query"${t?` or "${t}"`:``} instead.`)}function assertNotAborted(e,t,n){e?.aborted&&(n?.(),throwReasonWithTiming(e.reason,t))}function throwReasonWithTiming(e,t){throw decorateWithTiming(e,t),e}const J={};async function waitOrAbort(e,t,n,r){if(!t)return e;assertNotAborted(t,`before ${n}`,r);let{promise:i,resolve:a}=new Deferred,abortListener=()=>a(J);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==J)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(J)}}function printBackgroundFail(e){return t=>console.error(`\`${e}\` failed in the background after abortion: ${getMessage(t)}`)}function decorateWithTiming(e,t){typeof e==`object`&&e&&!Object.isFrozen(e)&&Object.defineProperty(e,"__kysely_timing__",{configurable:!0,enumerable:!1,value:t,writable:!1})}const Ec=freeze([]);var QueryExecutorBase=class{#e;constructor(e=Ec){this.#e=e}get plugins(){return this.#e}transformQuery(e,t){for(let n of this.#e){let r=n.transformQuery({node:e,queryId:t});if(r.kind===e.kind)e=r;else throw Error([`KyselyPlugin.transformQuery must return a node`,`of the same kind that was given to it.`,`The plugin was given a ${e.kind}`,`but it returned a ${r.kind}`].join(` `))}return e}async executeQuery(e,t){let{inflightQueryAbortStrategy:n=`ignore query`,signal:r}=t||{};if(!r){let n=await this.provideConnection(async t=>await t.executeQuery(e),t);return await this.#t(n,e.queryId)}assertNotAborted(r,`before query execution`),t=freeze({signal:r});let{connection:i,release:a}=await provideControlledConnection(this,t),o=this.provideConnection.bind(this),{promise:s,resolve:c}=new Deferred,abortListener=()=>c(J);r.addEventListener(`abort`,abortListener,{once:!0});try{assertNotAborted(r,`before query execution`,a);let c=getInflightQueryAbortHandler(n,i,a);if(c&&i.collectSessionInfo){assertNotAborted(r,`before query execution`,a);let e=i.collectSessionInfo();await Promise.race([s,e]).catch(e=>{throw a(),e})===J&&(e.catch(printBackgroundFail(`collectSessionInfo`)).finally(a),throwReasonWithTiming(r.reason,`before query execution`))}let l=i.executeQuery(e,t),u=await Promise.race([s,l]).catch(e=>{throw a(),e});u===J?(Promise.allSettled([l.catch(printBackgroundFail(`query`)),c?.(o).catch(printBackgroundFail(`inflightQueryAbortHandler`))]).finally(a),throwReasonWithTiming(r.reason,`during query execution`)):a();let d=this.#t(u,e.queryId,t),f=await Promise.race([s,d]);return f===J&&(d.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),f}finally{c(J),r.removeEventListener(`abort`,abortListener)}}async*stream(e,t,n){let{signal:r}=n||{};if(!r){let{connection:r,release:i}=await provideControlledConnection(this);try{for await(let i of r.streamQuery(e,t))yield await this.#t(i,e.queryId,n)}finally{i()}return}n=freeze({signal:r}),assertNotAborted(r,`before connection acquisition`);let{connection:i,release:a}=await provideControlledConnection(this,n),{promise:o,resolve:s}=new Deferred,abortListener=()=>s(J);r.addEventListener(`abort`,abortListener,{once:!0});let c,l;assertNotAborted(r,`before query streaming`,a);let{queryId:u}=e;try{for(c=i.streamQuery(e,t,n);;){assertNotAborted(r,`during query streaming`);let e=c.next(),t=await Promise.race([o,e]);if(t===J&&(l=e.catch(printBackgroundFail(`iterator.next`)),throwReasonWithTiming(r.reason,`during query streaming`)),t.done)break;let i=this.#t(t.value,u,n),a=await Promise.race([o,i]);a===J&&(l=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{s(J),r.removeEventListener(`abort`,abortListener);let e=(c?.return?.()||Promise.resolve()).finally(()=>l).finally(a);l||await e}}async#t(e,t,n){let{signal:r}=n||{};for(let n of this.#e)e=await n.transformResult(freeze({queryId:t,result:e,signal:r}));return e}};const Dc=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}},Oc=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new kc({...this.#e,queryNode:H.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},kc=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}whenMatched(){return this.#t([])}whenMatchedAnd(...e){return this.#t(e)}whenMatchedAndRef(e,t,n){return this.#t([e,t,n],!0)}#t(e,t){return new MatchedThenableMergeQueryBuilder({...this.#e,queryNode:H.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!0},e,t))})}whenNotMatched(){return this.#n([])}whenNotMatchedAnd(...e){return this.#n(e)}whenNotMatchedAndRef(e,t,n){return this.#n([e,t,n],!0)}whenNotMatchedBySource(){return this.#n([],!1,!0)}whenNotMatchedBySourceAnd(...e){return this.#n(e,!1,!0)}whenNotMatchedBySourceAndRef(e,t,n){return this.#n([e,t,n],!0,!0)}returning(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:U.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:H.cloneWithWhen(this.#e.queryNode,parseMergeWhen({isMatched:!1,bySource:n},e,t))};return new(n?MatchedThenableMergeQueryBuilder:NotMatchedThenableMergeQueryBuilder)(r)}$call(e){return e(this)}$if(e,t){return e?t(this):new WheneableMergeQueryBuilder({...this.#e})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new MergeResult(n.numAffectedRows)]}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}},MatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDelete(){return new kc({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new kc({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new kc({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:Dc,queryNode:Zs.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new kc({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new kc({...this.#e,queryNode:H.cloneWithThen(this.#e.queryNode,parseMergeThen(B.cloneWith(B.createWithoutInto(),{columns:t,values:n})))})}},Ac=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:W.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:W.cloneWithSelections(W.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new gc({queryId:createQueryId(),executor:this.#e.executor,queryNode:B.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new gc({queryId:createQueryId(),executor:this.#e.executor,queryNode:B.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:$s.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Zs.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new Oc({queryId:createQueryId(),executor:this.#e.executor,queryNode:H.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?xc.cloneWithExpression(this.#e.withNode,n):xc.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?xc.cloneWithExpression(this.#e.withNode,n):xc.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 Ac({executor:Dc})}function createJoinBuilder(e,t){return new ic({joinNode:bs.create(e,parseTableExpression(t))})}function createOverBuilder(){return new oc({overNode:Ks.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 bs.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return bs.create(e,parseTableExpression(t))}const jc=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),Mc=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(Mc.create)}const Nc=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=>Nc.create(e,parseExpression(t),n))}var Y=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new Pc(vs.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new Fc(_s.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 hs.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():N.create(this.#t))}},Pc=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(vs.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return Us.create(this.#e)}},Fc=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(_s.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return Us.create(this.#e)}};const Ic=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:z.create(e),modifier:t}}});function parseFetch(e,t){if(!isNumber(e)&&!isBigInt(e))throw Error(`Invalid fetch row count: ${e}`);if(!isFetchModifier(t))throw Error(`Invalid fetch modifier: ${t}`);return Ic.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var X,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new X({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new X({...this.#e,queryNode:U.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new X({...this.#e,queryNode:W.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new X({...this.#e,queryNode:W.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new X({...this.#e,queryNode:W.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new X({...this.#e,queryNode:W.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new X({...this.#e,queryNode:W.cloneWithFrontModifier(this.#e.queryNode,gs.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,gs.createWithExpression(e.toOperationNode()))})}distinct(){return new X({...this.#e,queryNode:W.cloneWithFrontModifier(this.#e.queryNode,gs.create(`Distinct`))})}forUpdate(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,gs.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,gs.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,gs.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,gs.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,gs.create(`SkipLocked`))})}noWait(){return new X({...this.#e,queryNode:U.cloneWithEndModifier(this.#e.queryNode,gs.create(`NoWait`))})}selectAll(e){return new X({...this.#e,queryNode:W.cloneWithSelections(this.#e.queryNode,parseSelectAll(e))})}innerJoin(...e){return this.#t(`InnerJoin`,e)}leftJoin(...e){return this.#t(`LeftJoin`,e)}rightJoin(...e){return this.#t(`RightJoin`,e)}fullJoin(...e){return this.#t(`FullJoin`,e)}crossJoin(...e){return this.#t(`CrossJoin`,e)}innerJoinLateral(...e){return this.#t(`LateralInnerJoin`,e)}leftJoinLateral(...e){return this.#t(`LateralLeftJoin`,e)}crossJoinLateral(...e){return this.#t(`LateralCrossJoin`,e)}crossApply(...e){return this.#t(`CrossApply`,e)}outerApply(...e){return this.#t(`OuterApply`,e)}#t(e,t){return new X({...this.#e,queryNode:U.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new X({...this.#e,queryNode:U.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new X({...this.#e,queryNode:W.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new X({...this.#e,queryNode:W.cloneWithLimit(this.#e.queryNode,_c.create(parseValueExpression(e)))})}offset(e){return new X({...this.#e,queryNode:W.cloneWithOffset(this.#e.queryNode,jc.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new X({...this.#e,queryNode:W.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new X({...this.#e,queryNode:U.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new X({...this.#e,queryNode:W.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new X({...this.#e,queryNode:W.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new X({...this.#e,queryNode:U.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new X({...this.#e,queryNode:W.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new X({...this.#e,queryNode:W.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new X({...this.#e,queryNode:U.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new X({...this.#e,queryNode:W.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new X({...this.#e})}$castTo(){return new X(this.#e)}$narrowType(){return new X(this.#e)}$assertType(){return new X(this.#e)}$asTuple(){return new Y(this.toOperationNode())}$asScalar(){return new Y(this.toOperationNode())}withPlugin(e){return new X({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile();return(await this.#e.executor.executeQuery(t,e)).rows}async executeTakeFirst(e){let[t]=await this.execute(e);return t}async executeTakeFirstOrThrow(e){typeof e==`function`&&(e={errorConstructor:e});let t=await this.executeTakeFirst(e);if(t===void 0){let t=e?.errorConstructor??NoResultError;throw isNoResultErrorConstructor(t)?new t(this.toOperationNode()):t(this.toOperationNode())}return t}async*stream(e){typeof e!=`object`&&(e={chunkSize:e});let t=this.compile(),n=this.#e.executor.stream(t,e.chunkSize??100,e);for await(let e of n)yield*e.rows}async explain(e,t){return await new X({...this.#e,queryNode:U.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};X=SelectQueryBuilderImpl;function createSelectQueryBuilder(e){return new SelectQueryBuilderImpl(e)}var AliasedSelectQueryBuilderImpl=class{#e;#t;constructor(e,t){this.#e=e,this.#t=t}get expression(){return this.#e}get alias(){return this.#t}get isAliasedSelectQueryBuilder(){return!0}toOperationNode(){return hs.create(this.#e.toOperationNode(),N.create(this.#t))}};const Lc=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]?Ws.cloneWithItems(e[r],t):Ws.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?V.cloneWithOperation(e.filter,`And`,t):V.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?V.cloneWithOperation(e.filter,`Or`,t):V.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),Rc=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var zc=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:Lc.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:U.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:U.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Lc.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Lc.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Lc.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:Lc.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 hs.create(this.#e.toOperationNode(),N.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new Y(Rc.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new zc({aggregateFunctionNode:Lc.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 zc({aggregateFunctionNode:Lc.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 zc({aggregateFunctionNode:Lc.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new Y(Rc.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const Bc=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 Bc.create(js.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const Z=freeze({is(e){return e.kind===`CaseNode`},create(e){return freeze({kind:`CaseNode`,value:e})},cloneWithWhen(e,t){return freeze({...e,when:freeze(e.when?[...e.when,t]:[t])})},cloneWithThen(e,t){return freeze({...e,when:e.when?freeze([...e.when.slice(0,-1),nc.cloneWithResult(e.when[e.when.length-1],t)]):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var CaseBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:Z.cloneWithWhen(this.#e.node,nc.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:Z.cloneWithWhen(this.#e.node,nc.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:Z.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:Z.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:Z.cloneWithWhen(this.#e.node,nc.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:Z.cloneWithWhen(this.#e.node,nc.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:Z.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:Z.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new Y(Z.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Y(Z.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new Y(Z.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new Y(Z.cloneWith(this.#e.node,{isStatement:!0}))}};const Vc=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),Hc=/^#-\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`&&!Hc.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 Rs.is(this.#e)?new Uc(Rs.cloneWithTraversal(this.#e,Bs.is(this.#e.traversal)?Bs.cloneWithLeg(this.#e.traversal,Vc.create(e,t)):zs.cloneWithValue(this.#e.traversal,z.createImmediate(t)))):new Uc(Bs.cloneWithLeg(this.#e,Vc.create(e,t)))}},Uc=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 hs.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():N.create(this.#t))}};const Wc=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),Gc=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}),Kc=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+\)$/]),qc=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return Gc[e]||Kc.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return qc.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const Jc=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=Dc){function binary(e,t,n){return new Y(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new Y(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:W.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:Z.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new Y(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(Bs.create())},table(e){return new Y(parseTable(e))},val(e){return new Y(parseValueExpression(e))},refTuple(...e){return new Y(Wc.create(e.map(parseReferenceExpression)))},tuple(...e){return new Y(Wc.create(e.map(parseValueExpression)))},lit(e){return new Y(parseSafeImmediateValue(e))},unary,not(e){return unary(`not`,e)},exists(e){return unary(`exists`,e)},neg(e){return unary(`-`,e)},between(e,t,n){return new Y(xs.create(parseReferenceExpression(e),js.create(`between`),_s.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new Y(xs.create(parseReferenceExpression(e),js.create(`between symmetric`),_s.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new Y(parseFilterList(e,`and`)):new Y(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new Y(parseFilterList(e,`or`)):new Y(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return Us.is(t)?new Y(t):new Y(Us.create(t))},cast(e,t){return new Y(Jc.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 hs.create(parseTable(this.#e),N.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 hs.create(parseTable(n),N.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return I.createWithSchema(t,n)}return I.create(e)}function trim$1(e){return e.trim()}const Yc=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}}),Q=freeze({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return freeze({kind:`ColumnDefinitionNode`,column:L.create(e),dataType:t})},cloneWithFrontModifier(e,t){return freeze({...e,frontModifiers:e.frontModifiers?freeze([...e.frontModifiers,t]):[t]})},cloneWithEndModifier(e,t){return freeze({...e,endModifiers:e.endModifiers?freeze([...e.endModifiers,t]):[t]})},cloneWith(e,t){return freeze({...e,...t})}}),Xc=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:L.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Zc=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:L.create(e),renameTo:L.create(t)})}}),Qc=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?N.create(t):void 0})}}),$c=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys($c);const el=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)&&$c[e]}function parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():z.createImmediate(e)}const tl=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})}}),nl=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 rl=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||Ms.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{references:el.create(t.table,[t.column])}))}onDelete(e){if(!this.#e.references)throw Error(`on delete constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{references:el.cloneWithOnDelete(this.#e.references,parseOnModifyForeignAction(e))}))}onUpdate(e){if(!this.#e.references)throw Error(`on update constraint can only be added for foreign keys`);return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{references:el.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{defaultTo:nl.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{check:Qc.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{generated:tl.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{generated:tl.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{generated:tl.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{generated:tl.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(Q.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(Q.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(Q.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}};const il=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}}),al=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:el.create(t,n),name:r?N.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var ol=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder(al.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder(al.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder(al.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder(al.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder(al.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder(al.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}};const sl=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}}),cl=freeze({is(e){return e.kind===`UniqueConstraintNode`},create(e,t,n){return isString(e.at(0))&&(logOnce("`UniqueConstraintNode.create(columns: string[], ...)` is deprecated - pass `ColumnNode[]` instead."),e=e.map(L.create)),freeze({kind:`UniqueConstraintNode`,columns:freeze(e),name:t?N.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return freeze({...e,...t})}}),ll=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:N.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),ul=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:L.create(e),[t]:n})}});var AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(ul.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(ul.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(ul.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(ul.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(ul.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)}},dl=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(M.cloneWithTableProps(this.#e.node,{addConstraint:sl.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)}},fl=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropConstraint:ll.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropConstraint:ll.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropConstraint:ll.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 pl=freeze({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return freeze({kind:`PrimaryKeyConstraintNode`,columns:freeze(e.map(L.create)),name:t?N.create(t):void 0})},cloneWith(e,t){return freeze({...e,...t})}}),ml=freeze({is(e){return e.kind===`AddIndexNode`},create(e){return freeze({kind:`AddIndexNode`,name:N.create(e)})},cloneWith(e,t){return freeze({...e,...t})},cloneWithColumns(e,t){return freeze({...e,columns:[...e.columns||[],...t]})}});var hl=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:ml.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:ml.cloneWithColumns(this.#e.node.addIndex,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})})}columns(e){return new AlterTableAddIndexBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:ml.cloneWithColumns(this.#e.node.addIndex,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})})}expression(e){return new AlterTableAddIndexBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:ml.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:ml.cloneWith(this.#e.node.addIndex,{using:R.createWithSql(e)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},gl=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(cl.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(cl.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(cl.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(cl.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(cl.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},_l=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(pl.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(pl.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(pl.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(pl.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 vl=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:N.create(e),newName:N.create(t)})}});var yl=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:Xc.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:M.cloneWithTableProps(this.#e.node,{renameTo:parseTable(e)})})}setSchema(e){return new AlterTableExecutor({...this.#e,node:M.cloneWithTableProps(this.#e.node,{setSchema:N.create(e)})})}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new bl({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new yl({node:Xc.create(e)}));return new bl({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new bl({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,Zc.create(e,t))})}addColumn(e,t,n=noop){let r=n(new rl(Q.create(e,parseDataTypeExpression(t))));return new bl({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,Yc.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new rl(Q.create(e,parseDataTypeExpression(t))));return new bl({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,il.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new gl(cl.create(t.map(e=>isString(e)?L.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addConstraint:sl.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Qc.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addConstraint:sl.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new ol(al.create(t.map(L.create),parseTable(n),r.map(L.create),e)));return new dl({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new _l(pl.create(t,e)));return new AlterTableExecutor({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addConstraint:sl.create(r.toOperationNode())})})}dropConstraint(e){return new fl({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropConstraint:ll.create(e)})})}renameConstraint(e,t){return new fl({...this.#e,node:M.cloneWithTableProps(this.#e.node,{renameConstraint:vl.create(e,t)})})}addIndex(e){return new hl({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:ml.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropIndex:fs.create(e)})})}$call(e){return e(this)}},bl=class AlterTableColumnAlteringBuilder{#e;constructor(e){this.#e=freeze(e)}alterColumn(e,t){let n=t(new AlterColumnBuilder(e));return new AlterTableColumnAlteringBuilder({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new yl({node:Xc.create(e)}));return new AlterTableColumnAlteringBuilder({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new AlterTableColumnAlteringBuilder({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,Zc.create(e,t))})}addColumn(e,t,n=noop){let r=n(new rl(Q.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,Yc.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new rl(Q.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,il.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 Hs.create(e.values.map(z.createImmediate))}transformValue(e){return z.createImmediate(e.value)}},xl=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:P.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:P.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:P.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:P.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:P.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:P.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:P.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:P.cloneWith(this.#e.node,{using:R.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:U.cloneWithWhere(this.#e.node,t.transformNode(parseValueBinaryOperationOrExpression(e),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Sl=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:ls.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(us.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var Cl=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder(ml.cloneWith(this.#e,{using:R.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},wl=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:F.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:F.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:F.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new rl(Q.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:F.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new _l(pl.create(t,e)));return new CreateTableBuilder({...this.#e,node:F.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new gl(cl.create(t.map(e=>isString(e)?L.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:F.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new Cl(ml.cloneWithColumns(ml.create(e),t.map(e=>isString(e)?L.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:F.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Qc.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:F.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new ol(al.create(t.map(L.create),parseTable(n),r.map(L.create),e)));return new CreateTableBuilder({...this.#e,node:F.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:F.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:F.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:F.cloneWith(this.#e.node,{selectQuery:parseExpression(e)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){await this.#e.executor.executeQuery(this.compile(),e)}},Tl=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:fs.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:fs.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:fs.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)}},El=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:ps.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:ps.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)}},Dl=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:ms.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:ms.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:ms.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 Ol=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:ds.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)}},kl=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:Ol.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:Ol.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:Ol.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:Ol.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:Ol.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:Ol.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 Al=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:ds.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var jl=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:Al.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:Al.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:Al.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 Ml=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:Hs.create(t.map(z.createImmediate))})}});var Nl=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:Ml.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 Pl=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 Fl=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:Pl.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:Pl.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 ds.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return ds.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}const Il=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:ds.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var Ll=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:Il.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Il.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Il.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 Rl=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}}),zl=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)}},Bl,AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new Bl({...this.#e,node:Rl.cloneWith(this.#e.node,{addValue:zl.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 Bl({...this.#e,node:Rl.cloneWith(this.#e.node,{addValue:zl.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:z.createImmediate(e)})})})}};Bl=AlterTypeAddValueBuilder;const Vl=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:Rl.cloneWith(this.#e.node,{addValue:zl.create(z.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:Rl.cloneWith(this.#e.node,{renameTo:N.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:Rl.cloneWith(this.#e.node,{renameValue:Vl.create(z.createImmediate(e),z.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:Rl.cloneWith(this.#e.node,{setSchema:N.create(e)})})}},Hl=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new wl({queryId:createQueryId(),executor:this.#e,node:F.create(parseTable(e))})}dropTable(e){return new Dl({queryId:createQueryId(),executor:this.#e,node:ms.create(parseTable(e))})}createIndex(e){return new xl({queryId:createQueryId(),executor:this.#e,node:P.create(e)})}dropIndex(e){return new Tl({queryId:createQueryId(),executor:this.#e,node:fs.create(e)})}createSchema(e){return new Sl({queryId:createQueryId(),executor:this.#e,node:ls.create(e)})}dropSchema(e){return new El({queryId:createQueryId(),executor:this.#e,node:ps.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:M.create(parseTable(e))})}createView(e){return new kl({queryId:createQueryId(),executor:this.#e,node:Ol.create(e)})}refreshMaterializedView(e){return new Ll({queryId:createQueryId(),executor:this.#e,node:Il.create(e)})}dropView(e){return new jl({queryId:createQueryId(),executor:this.#e,node:Al.create(e)})}createType(e){return new Nl({queryId:createQueryId(),executor:this.#e,node:Ml.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:Rl.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new Fl({queryId:createQueryId(),executor:this.#e,node:Pl.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)}}},Ul=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 Wl=[`read only`,`read write`],Gl=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function validateTransactionSettings(e){if(e.accessMode&&!Wl.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!Gl.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 Kl=class Kysely extends Ac{#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 Ul(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 Hl(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:Z.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new Jl({...this.#e})}startTransaction(){return new Yl({...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()}},ql=class Transaction extends Kl{#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 Kl({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},Jl=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 Zl(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),o=new ql({...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}})}},Yl=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 Xl({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},Xl=class ControlledTransaction extends ql{#e;#t;constructor(e){e={...e,executor:new Zl(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 Zl=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)}},Ql=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?Dc: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 Ql(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 hs.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():N.create(this.#t))}};const $=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:R.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:R.create(t,e.map(N.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChild(z.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithSql(e)})},join(e,t=$`, `){let n=Array(Math.max(2*e.length-1,0)),r=t.toOperationNode();for(let t=0;t<e.length;++t)n[2*t]=parseParameter(e[t]),t!==e.length-1&&(n[2*t+1]=r);return createRawBuilder({queryId:createQueryId(),rawNode:R.createWithChildren(n)})}});function parseParameter(e){return isOperationNodeSource(e)?e.toOperationNode():parseValueExpression(e)}var OperationNodeVisitor=class{nodeStack=[];get parentNode(){return this.nodeStack[this.nodeStack.length-2]}#e=freeze({AliasNode:this.visitAlias.bind(this),ColumnNode:this.visitColumn.bind(this),IdentifierNode:this.visitIdentifier.bind(this),SchemableIdentifierNode:this.visitSchemableIdentifier.bind(this),RawNode:this.visitRaw.bind(this),ReferenceNode:this.visitReference.bind(this),SelectQueryNode:this.visitSelectQuery.bind(this),SelectionNode:this.visitSelection.bind(this),TableNode:this.visitTable.bind(this),FromNode:this.visitFrom.bind(this),SelectAllNode:this.visitSelectAll.bind(this),AndNode:this.visitAnd.bind(this),OrNode:this.visitOr.bind(this),ValueNode:this.visitValue.bind(this),ValueListNode:this.visitValueList.bind(this),PrimitiveValueListNode:this.visitPrimitiveValueList.bind(this),ParensNode:this.visitParens.bind(this),JoinNode:this.visitJoin.bind(this),OperatorNode:this.visitOperator.bind(this),WhereNode:this.visitWhere.bind(this),InsertQueryNode:this.visitInsertQuery.bind(this),DeleteQueryNode:this.visitDeleteQuery.bind(this),ReturningNode:this.visitReturning.bind(this),CreateTableNode:this.visitCreateTable.bind(this),AddColumnNode:this.visitAddColumn.bind(this),ColumnDefinitionNode:this.visitColumnDefinition.bind(this),DropTableNode:this.visitDropTable.bind(this),DataTypeNode:this.visitDataType.bind(this),OrderByNode:this.visitOrderBy.bind(this),OrderByItemNode:this.visitOrderByItem.bind(this),GroupByNode:this.visitGroupBy.bind(this),GroupByItemNode:this.visitGroupByItem.bind(this),UpdateQueryNode:this.visitUpdateQuery.bind(this),ColumnUpdateNode:this.visitColumnUpdate.bind(this),LimitNode:this.visitLimit.bind(this),OffsetNode:this.visitOffset.bind(this),OnConflictNode:this.visitOnConflict.bind(this),OnDuplicateKeyNode:this.visitOnDuplicateKey.bind(this),CreateIndexNode:this.visitCreateIndex.bind(this),DropIndexNode:this.visitDropIndex.bind(this),ListNode:this.visitList.bind(this),PrimaryKeyConstraintNode:this.visitPrimaryKeyConstraint.bind(this),UniqueConstraintNode:this.visitUniqueConstraint.bind(this),ReferencesNode:this.visitReferences.bind(this),CheckConstraintNode:this.visitCheckConstraint.bind(this),WithNode:this.visitWith.bind(this),CommonTableExpressionNode:this.visitCommonTableExpression.bind(this),CommonTableExpressionNameNode:this.visitCommonTableExpressionName.bind(this),HavingNode:this.visitHaving.bind(this),CreateSchemaNode:this.visitCreateSchema.bind(this),DropSchemaNode:this.visitDropSchema.bind(this),AlterTableNode:this.visitAlterTable.bind(this),DropColumnNode:this.visitDropColumn.bind(this),RenameColumnNode:this.visitRenameColumn.bind(this),AlterColumnNode:this.visitAlterColumn.bind(this),ModifyColumnNode:this.visitModifyColumn.bind(this),AddConstraintNode:this.visitAddConstraint.bind(this),DropConstraintNode:this.visitDropConstraint.bind(this),RenameConstraintNode:this.visitRenameConstraint.bind(this),ForeignKeyConstraintNode:this.visitForeignKeyConstraint.bind(this),CreateViewNode:this.visitCreateView.bind(this),RefreshMaterializedViewNode:this.visitRefreshMaterializedView.bind(this),DropViewNode:this.visitDropView.bind(this),GeneratedNode:this.visitGenerated.bind(this),DefaultValueNode:this.visitDefaultValue.bind(this),OnNode:this.visitOn.bind(this),ValuesNode:this.visitValues.bind(this),SelectModifierNode:this.visitSelectModifier.bind(this),CreateTypeNode:this.visitCreateType.bind(this),DropTypeNode:this.visitDropType.bind(this),ExplainNode:this.visitExplain.bind(this),DefaultInsertValueNode:this.visitDefaultInsertValue.bind(this),AggregateFunctionNode:this.visitAggregateFunction.bind(this),OverNode:this.visitOver.bind(this),PartitionByNode:this.visitPartitionBy.bind(this),PartitionByItemNode:this.visitPartitionByItem.bind(this),SetOperationNode:this.visitSetOperation.bind(this),BinaryOperationNode:this.visitBinaryOperation.bind(this),UnaryOperationNode:this.visitUnaryOperation.bind(this),UsingNode:this.visitUsing.bind(this),FunctionNode:this.visitFunction.bind(this),CaseNode:this.visitCase.bind(this),WhenNode:this.visitWhen.bind(this),JSONReferenceNode:this.visitJSONReference.bind(this),JSONPathNode:this.visitJSONPath.bind(this),JSONPathLegNode:this.visitJSONPathLeg.bind(this),JSONOperatorChainNode:this.visitJSONOperatorChain.bind(this),TupleNode:this.visitTuple.bind(this),MergeQueryNode:this.visitMergeQuery.bind(this),MatchedNode:this.visitMatched.bind(this),AddIndexNode:this.visitAddIndex.bind(this),CastNode:this.visitCast.bind(this),FetchNode:this.visitFetch.bind(this),TopNode:this.visitTop.bind(this),OutputNode:this.visitOutput.bind(this),OrActionNode:this.visitOrAction.bind(this),CollateNode:this.visitCollate.bind(this),AlterTypeNode:this.visitAlterType.bind(this),AddValueNode:this.visitAddValue.bind(this),RenameValueNode:this.visitRenameValue.bind(this)});visitNode=e=>{this.nodeStack.push(e),this.#e[e.kind](e),this.nodeStack.pop()}};const $l=/'/g,eu=/['"]/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&&!Us.is(this.parentNode)&&!B.is(this.parentNode)&&!F.is(this.parentNode)&&!Ol.is(this.parentNode)&&!Nc.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&&!Us.is(this.parentNode)&&!R.is(this.parentNode)&&!nc.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&&!Us.is(this.parentNode)&&!R.is(this.parentNode);this.parentNode===void 0&&e.explain&&(this.visitNode(e.explain),this.append(` `)),t&&this.append(`(`),e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`delete `),e.top&&(this.visitNode(e.top),this.append(` `)),this.visitNode(e.from),e.output&&(this.append(` `),this.visitNode(e.output)),e.using&&(this.append(` `),this.visitNode(e.using)),e.joins&&(this.append(` `),this.compileList(e.joins,` `)),e.where&&(this.append(` `),this.visitNode(e.where)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.orderBy&&(this.append(` `),this.visitNode(e.orderBy)),e.limit&&(this.append(` `),this.visitNode(e.limit)),t&&this.append(`)`),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitReturning(e){this.append(`returning `),this.compileList(e.selections)}visitAlias(e){this.visitNode(e.node),this.append(` as `),this.visitNode(e.alias)}visitReference(e){e.table&&(this.visitNode(e.table),this.append(`.`)),this.visitNode(e.column)}visitSelectAll(e){this.append(`*`)}visitIdentifier(e){this.append(this.getLeftIdentifierWrapper()),this.compileUnwrappedIdentifier(e),this.append(this.getRightIdentifierWrapper())}compileUnwrappedIdentifier(e){if(!isString(e.name))throw Error(`a non-string identifier was passed to compileUnwrappedIdentifier.`);this.append(this.sanitizeIdentifier(e.name))}visitAnd(e){this.visitNode(e.left),this.append(` and `),this.visitNode(e.right)}visitOr(e){this.visitNode(e.left),this.append(` or `),this.visitNode(e.right)}visitValue(e){e.immediate?this.appendImmediateValue(e.value):this.appendValue(e.value)}visitValueList(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitTuple(e){this.append(`(`),this.compileList(e.values),this.append(`)`)}visitPrimitiveValueList(e){this.append(`(`);let{values:t}=e;for(let e=0;e<t.length;++e)this.appendValue(t[e]),e!==t.length-1&&this.append(`, `);this.append(`)`)}visitParens(e){this.append(`(`),this.visitNode(e.node),this.append(`)`)}visitJoin(e){this.append(ru[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&&!Us.is(this.parentNode)&&!R.is(this.parentNode)&&!nc.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(tu[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 js.is(e)&&e.operator===`-`}visitUsing(e){this.append(`using `),this.compileList(e.tables)}visitFunction(e){this.append(e.func),this.append(`(`),this.compileList(e.arguments),this.append(`)`)}visitCase(e){this.append(`case`),e.value&&(this.append(` `),this.visitNode(e.value)),e.when&&(this.append(` `),this.compileList(e.when,` `)),e.else&&(this.append(` else `),this.visitNode(e.else)),this.append(` end`),e.isStatement&&this.append(` case`)}visitWhen(e){this.append(`when `),this.visitNode(e.condition),e.result&&(this.append(` then `),this.visitNode(e.result))}visitJSONReference(e){this.visitNode(e.reference),this.visitNode(e.traversal)}visitJSONPath(e){e.inOperator&&this.visitNode(e.inOperator),this.append(`'$`);for(let t of e.pathLegs)this.visitNode(t);this.append(`'`)}visitJSONPathLeg(e){let t=e.type===`ArrayLocation`,n=String(e.value);t?(this.append(`[`),this.append(this.sanitizeStringLiteral(n)),this.append(`]`)):(this.append(`."`),this.append(this.sanitizeJSONPathMemberValue(n)),this.append(`"`))}visitJSONOperatorChain(e){for(let t=0,n=e.values.length;t<n;t++)t===n-1?this.visitNode(e.operator):this.append(`->`),this.visitNode(e.values[t])}visitMergeQuery(e){e.with&&(this.visitNode(e.with),this.append(` `)),this.append(`merge `),e.top&&(this.visitNode(e.top),this.append(` `)),this.append(`into `),this.visitNode(e.into),e.using&&(this.append(` `),this.visitNode(e.using)),e.whens&&(this.append(` `),this.compileList(e.whens,` `)),e.returning&&(this.append(` `),this.visitNode(e.returning)),e.output&&(this.append(` `),this.visitNode(e.output)),e.endModifiers?.length&&(this.append(` `),this.compileList(e.endModifiers,` `))}visitMatched(e){e.not&&this.append(`not `),this.append(`matched`),e.bySource&&this.append(` by source`)}visitAddIndex(e){(!this.parentNode||!F.is(this.parentNode))&&this.append(`add `),e.unique&&this.append(`unique `),this.append(`index `),this.visitNode(e.name),e.columns&&(this.append(` (`),this.compileList(e.columns),this.append(`)`)),e.using&&(this.append(` using `),this.visitNode(e.using))}visitCast(e){this.append(`cast(`),this.visitNode(e.expression),this.append(` as `),this.visitNode(e.dataType),this.append(`)`)}visitFetch(e){this.append(`fetch next `),this.visitNode(e.rowCount),this.append(` rows ${e.modifier}`)}visitOutput(e){this.append(`output `),this.compileList(e.selections)}visitTop(e){this.append(`top(${e.expression})`),e.modifiers&&this.append(` ${e.modifiers}`)}visitOrAction(e){this.append(e.action)}visitCollate(e){this.append(`collate `),this.visitNode(e.collation)}append(e){this.#e+=e}appendValue(e){this.addParameter(e),this.append(this.getCurrentParameterPlaceholder())}getLeftIdentifierWrapper(){return`"`}getRightIdentifierWrapper(){return`"`}getCurrentParameterPlaceholder(){return`$`+this.numParameters}getLeftExplainOptionsWrapper(){return`(`}getExplainOptionAssignment(){return` `}getExplainOptionsDelimiter(){return`, `}getRightExplainOptionsWrapper(){return`)`}sanitizeIdentifier(e){let t=this.getLeftIdentifierWrapper(),n=this.getRightIdentifierWrapper(),r=``;for(let i of e)r+=i,i===t?r+=t:i===n&&(r+=n);return r}sanitizeStringLiteral(e){return e.replace($l,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(eu,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?nu[e.modifier]-nu[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const tu=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),nu=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),ru=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`}),iu=freeze({raw(e,t=[]){return freeze({sql:e,query:R.createWithSql(e),parameters:freeze(t),queryId:createQueryId()})}});var DialectAdapterBase=class{get supportsCreateIfNotExists(){return!0}get supportsMultipleConnections(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}get supportsOutput(){return!1}};function parseSavepointCommand(e,t){return R.createWithChildren([R.createWithSql(`${e} `),N.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(iu.raw(`begin`))}async commitTransaction(e){await e.executeQuery(iu.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(iu.raw(`rollback`))}async savepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`savepoint`,t),createQueryId()))}async rollbackToSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`rollback to`,t),createQueryId()))}async releaseSavepoint(e,t,n){await e.executeQuery(n(parseSavepointCommand(`release`,t),createQueryId()))}async releaseConnection(){}async destroy(){this.#t?.close()}},SqliteConnection=class{#e;constructor(e){this.#e=e}async executeQuery(e){let{sql:t,parameters:n}=e,r=this.#e.prepare(t);if(r.reader)return{rows:r.all(n)};let{changes:i,lastInsertRowid:a}=r.run(n);return{insertId:a==null?void 0:BigInt(a),numAffectedRows:i==null?void 0:BigInt(i),rows:[]}}async*streamQuery(e,t){let{sql:n,parameters:r,query:i}=e,a=this.#e.prepare(n);if(!W.is(i))throw Error(`Sqlite driver only supports streaming of select queries`);let o=a.iterate(r);for(let e of o)yield{rows:[e]}}};const au=/"/g,ou=/[\\'"]/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(au,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(ou,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const su=`kysely_migration`,cu=`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`,`!=`,su).where(`name`,`!=`,cu)),n}async#n(e){let t=await this.#t(this.#e,e).execute(),n=await this.#e.with(`table_list`,t=>this.#t(t,e)).selectFrom([`table_list as tl`,$`pragma_table_info(tl.name)`.as(`p`)]).select([`tl.name as table`,`p.cid`,`p.name`,`p.type`,`p.notnull`,`p.dflt_value`,`p.pk`]).orderBy(`tl.name`).orderBy(`p.cid`).execute(),r={};for(let e of n)r[e.table]??=[],r[e.table].push(e);return t.map(({name:e,sql:t,type:n})=>{let i=t?.split(/[\(\),]/)?.find(e=>e.toLowerCase().includes(`autoincrement`))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,``),a=r[e]??[];if(!i){let e=a.filter(e=>e.pk>0);e.length===1&&e[0].type.toLowerCase()===`integer`&&(i=e[0].name)}return{name:e,isView:n===`view`,isForeign:!1,columns:a.map(e=>({name:e.name,dataType:e.type,isNullable:!e.notnull,isAutoIncrementing:e.name===i,hasDefaultValue:e.dflt_value!=null,comment:void 0}))}})}},SqliteAdapter=class extends DialectAdapterBase{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}},SqliteDialect=class{#e;constructor(e){this.#e=freeze({...e})}createDriver(){return new SqliteDriver(this.#e)}createQueryCompiler(){return new SqliteQueryCompiler}createAdapter(){return new SqliteAdapter}createIntrospector(e){return new SqliteIntrospector(e)}};function extendStackTrace(e,t){if(isStackHolder(e)&&t.stack){let n=t.stack.split(`
`).slice(1).join(`
`);return e.stack+=`\n${n}`,e}return e}function isStackHolder(e){return isObject(e)&&isString(e.stack)}const lu=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(iu.raw(n))}async commitTransaction(e){await e.executeQuery(iu.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(iu.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[lu]()}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}}[lu](){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(iu.raw(e,[]))});let a=new n({...r,password:`password`in r?r.password:void 0});try{if(await a.connect(),i.queryId!==this.#n.queryId)return;await a.query(e,[])}finally{a.end()}}},PostgresIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom(`pg_catalog.pg_namespace`).select(`nspname`).$castTo().execute()).map(e=>({name:e.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom(`pg_catalog.pg_attribute as a`).innerJoin(`pg_catalog.pg_class as c`,`a.attrelid`,`c.oid`).innerJoin(`pg_catalog.pg_namespace as ns`,`c.relnamespace`,`ns.oid`).innerJoin(`pg_catalog.pg_type as typ`,`a.atttypid`,`typ.oid`).innerJoin(`pg_catalog.pg_namespace as dtns`,`typ.typnamespace`,`dtns.oid`).select([`a.attname as column`,`a.attnotnull as not_null`,`a.atthasdef as has_default`,`c.relname as table`,`c.relkind as table_type`,`ns.nspname as schema`,`typ.typname as type`,`dtns.nspname as type_schema`,$`col_description(a.attrelid, a.attnum)`.as(`column_description`),$`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(`auto_incrementing`)]).where(`c.relkind`,`in`,[`r`,`v`,`p`,`f`]).where(`ns.nspname`,`!~`,`^pg_`).where(`ns.nspname`,`!=`,`information_schema`).where(`ns.nspname`,`!=`,`crdb_internal`).where($`has_schema_privilege(ns.nspname, 'USAGE')`).where(`a.attnum`,`>=`,0).where(`a.attisdropped`,`!=`,!0).orderBy(`ns.nspname`).orderBy(`c.relname`).orderBy(`a.attnum`).$castTo();e.withInternalKyselyTables||(t=t.where(`c.relname`,`!=`,su).where(`c.relname`,`!=`,cu));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 uu=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(uu,`""`)}};const du=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await $`
    with set_timeout as (
      select set_config('lock_timeout', '${$.lit(36e5)}', true) as config_val
    )
    select pg_advisory_lock(${$.lit(du)})
    from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await $`select pg_advisory_unlock(${$.lit(du)})`.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 fu=/^v?((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u,pu=[{major:24,minor:16,patch:0},{major:26,minor:1,patch:0}],mu=pu[pu.length-1];`${pu.map(({major:e,minor:t,patch:n},r)=>`>=${e}.${t}.${n}${r<pu.length-1?` <${e+1}`:``}`).join(` || `).replaceAll(` || `,`, `).replace(/, ([^,]+)$/,`, or $1`)}`;function parseNodeReleaseVersion(e){if(typeof e!=`string`)return null;let t=fu.exec(e.trim());if(!t)return null;let n={major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])};return Object.values(n).every(Number.isSafeInteger)&&(!t[4]||n.major>mu.major)?n:null}function isNodeVersionAtLeast(e,t){return e?e.major===t.major?e.minor===t.minor?e.patch>=t.patch:e.minor>t.minor:e.major>t.major:!1}function renderProcessNodeVersionCheck(){return`((value) => {
  if (typeof value !== "string") return false;
  const match = new RegExp(${JSON.stringify(fu.source)}, "u").exec(value.trim());
  if (!match) return false;
  const version = { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]) };
  if (!Object.values(version).every(Number.isSafeInteger)) return false;
  const floors = ${JSON.stringify(pu)};
  if (match[4] && version.major <= floors[floors.length - 1].major) return false;
  const minimum = floors.find((floor) => floor.major === version.major);
  const atLeast = (floor) =>
    version.major > floor.major ||
    (version.major === floor.major &&
      (version.minor > floor.minor ||
        (version.minor === floor.minor && version.patch >= floor.patch)));
  return minimum ? atLeast(minimum) : version.major > floors[floors.length - 1].major;
})(process.versions.node)`}renderProcessNodeVersionCheck();const templateFragments=(e,t)=>e,hu=templateFragments`(SELECT value FROM json_each(${0}))`,gu=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!R.is(e)||e.sqlFragments!==hu||e.parameters.length!==1)return;let t=e.parameters[0];for(;R.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!z.is(t)||t.immediate||typeof t.value!=`string`)return;let n;try{n=JSON.parse(t.value)}catch{return}if(Array.isArray(n)&&n.every(e=>typeof e==`string`))return`{${n.map(e=>`"${e.replace(/["\\]/g,`\\$&`)}"`).join(`,`)}}`}var OpenClawPostgresQueryCompiler=class extends PostgresQueryCompiler{visitBinaryOperation(e){if(js.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===hu;!t&&e.sqlFragments!==gu?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 _u=parseNodeReleaseVersion(process.versions.node),vu=!process.versions.bun&&(_u?.major===24&&isNodeVersionAtLeast(_u,{major:24,minor:20,patch:0})||isNodeVersionAtLeast(_u,{major:26,minor:6,patch:0})),yu=new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),bu=/* @__PURE__ */ new WeakMap,xu=new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});function getNodeSqliteKysely(e){if(y(e)){let t=bu.get(e);return t||(t=new Kl({dialect:xu}),bu.set(e,t)),t}let t=Ue.get(e);if(t)return t;let n=new Kl({dialect:yu});return Ue.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{Ve.get(e)?.(t)}catch{}}function releaseSqliteIterator(e,t,n,r){let i;try{e.return?.()}catch(e){i=e}if(t.release(),!n&&i!==void 0)throw c(i,r)}function executeCompiledSqliteQuerySync(e,t,n=!1,r=t.parameters){if(y(e)){let i=e.query(t.sql,r),a=n?i.rows.slice(0,1):i.rows;return i.columns.length>0?{rows:a}:{rows:[],numAffectedRows:BigInt(i.rowCount)}}try{let i=t.sql;return et(e),it(e,i,r,i=>{if(n&&W.is(t.query)){let e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(W.is(t.query)||i.columns().length>0){if(vu)return{rows:i.all(...r)};let t=i.iterate(...r),n=re(e,`kysely eager query`),a=!1,o,s=[];try{for(let e of t)n.progress(),s.push(e)}catch(e){a=!0,o=e}if(releaseSqliteIterator(t,n,a,`SQLite query cleanup failed`),a)throw c(o,`SQLite query failed`);return{rows:s}}i.setReadBigInts(!0);let a;try{a=i.run(...r)}finally{i.setReadBigInts(!1)}let{changes:o,lastInsertRowid:s}=a,l={numAffectedRows:BigInt(o),rows:[]};return B.is(t.query)&&o>0?{...l,insertId:BigInt(s)}:l})}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}}function executeSqliteQuerySync(e,t){return executeCompiledSqliteQuerySync(e,t.compile())}function createSqliteQueryCache(e){let t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);return r===void 0&&(r=e(n),t.set(n,r)),r}}function compileSqliteQueryBindings(e){let t=/* @__PURE__ */ new Map,n=e(e=>{let n=Symbol(`sqlite-query-parameter`);return t.set(n,e),$`${n}`}).compile(),r=n.parameters.map(e=>t.get(e)??(()=>e));return{compiled:n,bind:e=>r.map(t=>t(e))}}function prepareSqliteQuerySync(e,t){let{compiled:n,bind:r}=compileSqliteQueryBindings(t);return t=>executeCompiledSqliteQuerySync(e,n,!1,r(t))}function iterateSqliteQuerySync(e,t){if(y(e))return(function*(){yield*executeCompiledSqliteQuerySync(e,t.compile()).rows})();let n=ie();return(function*(){let r=t.compile(),i;try{if(i=e.prepare(r.sql),!W.is(r.query)&&i.columns().length===0)return;let t=r.parameters,a=i.iterate(...t),o=re(e,`kysely iterator`,n),s=!1;try{for(let e of a)o.progress(),yield e}catch(e){throw s=!0,c(e,`SQLite iterator failed`)}finally{releaseSqliteIterator(a,o,s,`SQLite iterator cleanup failed`)}}catch(t){throw reportNodeSqliteKyselyQueryError(e,t),t}finally{i&&Ie(i)}})()}function executeSqliteQueryTakeFirstSync(e,t){return executeCompiledSqliteQuerySync(e,t.compile(),!0).rows[0]}export{number as $,acquireStateDatabaseSchemaLease as A,tableExists as At,GatewayLockNamespaceError as B,isSqliteReadOnlyError as C,runSqliteSingleStatementSync as Ct,readSourceJournalMode as D,classifySqliteTableReadError as Dt,prepareSqliteReadOnlyLocationSyncInProcess as E,readExistingAgentSchemaMeta as Et,prepareStateDatabaseReadAccess as F,legacySqliteSchemaIssueMessages as Ft,_enum as G,Ko as H,resolveGatewayStateOwnerPath as I,throwSqliteSchemaMismatches as It,custom as J,array as K,withStateDatabaseColdAdmission as L,createPrivateSqliteTempDirectorySync as Lt,assertStateDatabaseReadAllowed as M,tablePrimaryKeyColumns as Mt,captureStateDatabaseAccess as N,SqliteSchemaMismatchError as Nt,readSourceSidecars as O,ensureColumn as Ot,getStateDatabaseSchemaLease as P,createSqliteSchemaIssue as Pt,never as Q,applyPrivateModeSync as R,resolvePrivateSqliteSnapshotStagingRoot as Rt,SqliteSourceChangedError as S,runSqliteReadSnapshotSync as St,prepareSqliteReadOnlyLocationFromOwnedDatabase as T,publishAgentSchemaMetadata as Tt,classifyGatewayOwnerProcessNamespace as U,qo as V,parseGatewayLockPayload as W,literal as X,discriminatedUnion as Y,looseObject as Z,readSqliteIntegrityFileIdentity as _,normalizeSqliteNumber as _t,iterateSqliteQuerySync as a,acquireSqliteSnapshotReadToken as at,serializeSqliteFileGeneration as b,runSqliteDeferredTransactionSync as bt,$ as c,configureSqliteConnectionPragmas as ct,resolveAgentDatabaseIdleHandleTtlMs as d,isSqliteWalWorkerMaintained as dt,object as et,assertEngineStoreExecutionAllowed as f,registerSqliteWalWorkerMaintenance as ft,parseSqliteFileGeneration as g,coerceRequiredSqliteNumber as gt,createSqliteFileGenerationReader as h,truncateSqliteWal as ht,getNodeSqliteKysely as i,unknown as it,assertStateDatabaseAccessAllowed as j,tableHasColumn as jt,withSqliteSourceReadDatabase as k,readTableColumns as kt,expressionBuilder as l,configureSqlitePreSchemaPragmas as lt,withEngineStoreAdmission as m,prepareSqliteDatabaseDirectory as mt,executeSqliteQuerySync as n,string as nt,prepareSqliteQuerySync as o,createSqliteSnapshotStagingDirectory as ot,getDatabaseProcessRole as p,createSqliteWalReclamationResult as pt,boolean as q,executeSqliteQueryTakeFirstSync as r,union as rt,SqliteQueryCompiler as s,createSqliteSnapshotStagingDirectorySync as st,createSqliteQueryCache as t,record as tt,cs as u,registerSqliteCacheExitClose as ut,readStableSqliteFileGeneration as v,assertTransactionUsable as vt,prepareSqliteReadOnlyCopyInProcess as w,xn as wt,captureSqlitePrivateSnapshotFamily as x,runSqliteImmediateTransactionSync as xt,sameSqliteFileGeneration as y,retainSqliteWriteAdmissionService as yt,sha256Hex as z};