openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
287 lines • 467 kB
JavaScript
import{$ as e,C as t,G as n,H as r,I as i,K as a,L as s,N as c,P as l,Q as u,S as d,U as f,V as p,W as m,c as h,it as g,j as v,nt as ee,ot as te,q as ne,t as re,tt as y,u as ie,z as ae}from"./openclaw-state-lease-heartbeat.worker-subsystem-DoPLR_ni.mjs";import{$ as oe,$t as se,A as ce,An as le,At as ue,B as de,Bn as fe,Cn as pe,D as me,Dn as he,En as ge,Fn as _e,G as ve,Gt as ye,Hn as be,Ht as xe,J as Se,Jn as Ce,K as we,Kn as Te,Kt as Ee,Ln as De,M as Oe,Mn as ke,Mt as Ae,N as je,Nn as Me,On as Ne,Pn as Pe,Q as Fe,Rn as Ie,S as Le,St as Re,T as ze,Tn as Be,U as Ve,Ut as He,V as Ue,Vn as We,Vt as Ge,W as Ke,Wt as qe,X as Je,Xn as Ye,Y as Xe,Yn as Ze,Yt as Qe,Zn as $e,Zt as et,_ as tt,_t as nt,a as rt,at as it,b as at,bn as b,cn as ot,dt as st,fn as ct,ft as lt,gn as ut,h as dt,it as ft,j as pt,jt as mt,k as ht,kn as gt,kt as _t,m as vt,mt as yt,nn as bt,ot as xt,q as St,qn as Ct,qt as wt,rt as Tt,tt as Et,u as Dt,v as Ot,vn as kt,wn as At,wt as jt,xn as Mt,xt as Nt,yn as Pt,zn as Ft,zt as It}from"./openclaw-state-lease-heartbeat.worker-sqlite-worker-database-admission-relay-D7p41P-I.mjs";import{i as Lt,n as Rt}from"./openclaw-state-lease-heartbeat.worker-error-graph-internal-BdBY63_R.mjs";import{n as zt,r as Bt}from"./openclaw-state-lease-heartbeat.worker-path-existence-CuWhT9zy.mjs";import{a as Vt,i as Ht,o as Ut}from"./openclaw-state-lease-heartbeat.worker-cli-invocation-9KSnD_FV.mjs";import{o as Wt}from"./openclaw-state-lease-heartbeat.worker-runtime-process-manifest-BzzQjyny.mjs";import{n as Gt,r as Kt,t as qt}from"./openclaw-state-lease-heartbeat.worker-runtime-binary-2I4NLA2I.mjs";import{n as Jt}from"./openclaw-state-lease-heartbeat.worker-runtime-worker-url-D-Ef6nrK.mjs";import"./openclaw-state-lease-heartbeat.worker-errors-u9cPpOZi.mjs";import{createRequire as Yt}from"node:module";import{MessageChannel as Xt,isMainThread as Zt,parentPort as Qt,threadId as $t,workerData as en}from"node:worker_threads";import{AsyncLocalStorage as tn}from"node:async_hooks";import{createHash as nn,hash as rn,randomUUID as an}from"node:crypto";import x from"node:path";import S,{chmodSync as on,statSync as sn,unlinkSync as cn,writeFileSync as ln,default as un}from"node:fs";import dn from"node:os";import pn from"node:fs/promises";import"@openclaw/fs-safe/path";import mn,{spawnSync as hn}from"node:child_process";import{ProcSafeError as gn}from"@openclaw/proc-safe/errors";import{readProcessIdentity as _n}from"@openclaw/proc-safe/identity";import"@openclaw/fs-safe/durability";import{isUtf8 as vn}from"node:buffer";import{fileURLToPath as yn,pathToFileURL as bn}from"node:url";import{GCProfiler as xn,getHeapSpaceStatistics as Sn,getHeapStatistics as Cn}from"node:v8";import{channel as wn}from"node:diagnostics_channel";import{isDeepStrictEqual as Tn}from"node:util";import{readFileDescriptorBoundedSync as En,readFileWindowFullySync as Dn}from"@openclaw/fs-safe/advanced";import{acquireFileLockSync as On}from"@openclaw/fs-safe/file-lock";import"node:timers/promises";const kn=new ne(64);function resolveDatabasePath(e={}){return e.path===void 0?resolveOpenClawStateSqlitePath(e.env??process.env):_e(x.resolve(e.path))}function resolveOpenClawStateSqliteDir(e=process.env){return x.dirname(resolveOpenClawStateSqlitePath(e))}function resolveOpenClawStateSqlitePath(e=process.env){let t=a(e),n=kn.peek(t);if(n!==void 0)return n;let r=_e(x.join(t,`state`,`openclaw.sqlite`));return kn.set(t,r),r}function resolveOpenClawStateDirForDatabasePath(e){let t=x.dirname(x.resolve(e));return x.basename(t)===`state`?x.dirname(t):t}function resolveQuarantineStorePath(e){return x.join(resolveOpenClawStateSqliteDir(e),`openclaw-quarantine.sqlite`)}const An=y(Symbol.for(`openclaw.maintenanceLiveAuthorityReads`),()=>/* @__PURE__ */ new WeakMap);function allowsMaintenanceLiveAuthorityReads(e,t){return hasAdmittedMaintenanceLiveAuthorityReads(e,Bt(t))}function hasAdmittedMaintenanceLiveAuthorityReads(e,t){for(let n=e;n;n=jn.parents.get(n))if(An.get(n)?.has(t))return!0;return!1}function maintenanceOwnerHasSourceCustody(e,t){return e?.ownsSchemaMaintenance?(e.assertReadAdmission(),!allowsMaintenanceLiveAuthorityReads(e,t)):!1}function readCustodiedDrainedSqliteSource(e){if(!maintenanceOwnerHasSourceCustody(getOpenClawDatabaseMaintenanceScope(),e))return;let t=Bt(e);if(!(S.existsSync(`${t}-journal`)||(S.statSync(`${t}-wal`,{throwIfNoEntry:!1})?.size??0)>0))return S.statSync(t,{bigint:!0})}const jn=y(Symbol.for(`openclaw.databaseMaintenanceResources`),()=>({current:new tn,claims:/* @__PURE__ */ new WeakMap,parents:/* @__PURE__ */ new WeakMap}));function getOpenClawDatabaseMaintenanceScope(){return jn.current.getStore()?.scope}function isOpenClawDatabaseMaintenanceResourceOwned(e,t){return jn.claims.get(e)?.scope===t}function getOpenClawDatabaseMaintenanceResourceScope(e){return jn.claims.get(e)?.scope}function observeOpenClawDatabaseMaintenanceResource(e){if(!e)return;let t=jn.claims.get(e),n=getOpenClawDatabaseMaintenanceScope();if(!t)return;let r=commonMaintenanceAncestor(t.scope,n);r!==t.scope&&(t.scope.assertAdmission(),t.release(),jn.claims.delete(e),r&&r.own(e,t.phase,t.close))}function commonMaintenanceAncestor(e,t){let n=/* @__PURE__ */ new Set;for(let t=e;t;t=jn.parents.get(t))n.add(t);for(let e=t;e;e=jn.parents.get(e))if(n.has(e))return e}const Mn=`STATE_DATABASE_READ_ADMISSION_INVALIDATED`;var StateDatabaseReadAdmissionInvalidatedError=class extends Error{constructor(...e){super(...e),this.code=Mn}};function isStateDatabaseReadAdmissionInvalidatedError(e){return g(e)===Mn}function createOpenClawStateDatabaseAsyncLifecycle(){let e=/* @__PURE__ */ new Set,t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Map,a=Promise.resolve(),proofFor=()=>{let e=new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT);return new BigInt64Array(e)[0]=-1n,e},generationFor=e=>{let t=new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT);return{integrity:{identity:e,lifetime:{revision:new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT),epoch:0n},revision:t,epoch:0n,proof:proofFor()}}},publishCreatedIdentity=(e,n)=>{Atomics.add(new BigInt64Array(e.generation.integrity.revision),0,1n),Atomics.add(new BigInt64Array(e.generation.integrity.lifetime.revision),0,1n),t.delete(e.identity.key),e.identity=n,e.generation.integrity.identity=n,t.set(n.key,e)},known=e=>n.get(e)??n.get(resolveDatabasePath({path:e})),bindPath=(e,t)=>{e.paths.add(t),n.has(t)||n.set(t,e)},overlaps=(e,t)=>{if(e.identity.key===t.identity.key)return!0;for(let n of e.paths)if(t.paths.has(n))return!0;return!1},isSealed=e=>{if(r.size===0)return!1;for(let t of r)if(t.record===void 0||overlaps(t.record,e))return!0;return!1},hasCloseCustody=e=>isSealed(e)||i.has(e),assertOpen=e=>{if(isSealed(e))throw new StateDatabaseReadAdmissionInvalidatedError(`OpenClaw state database read admission is closed`)},findPhysicalRecord=e=>{let r=t.get(e.key);if(!r||!e.key.startsWith(`file:`)||hasCloseCustody(r))return r;for(let t of Me(r.paths,e))r.admissions.delete(t),r.paths.delete(t),n.get(t)===r&&n.delete(t);if(r.paths.size>0)return r.paths.has(r.identity.canonicalPath)||(r.identity=e,r.generation.integrity.identity=e),r;invalidate(r),forget(r)},resolve=(e,r)=>{let i=n.get(e);if(i&&(!r||i.identity.key===r.key))return!r&&i.identity.key.startsWith(`path:`)?resolve(e,Ie(e)):i;let a=r??Ie(e),s=findPhysicalRecord(a);return!s&&a.key.startsWith(`file:`)&&(s=[...t.values()].find(e=>{if(!e.identity.key.startsWith(`path:`))return!1;try{return Ie(e.identity.canonicalPath).key===a.key}catch{return!1}}),s&&publishCreatedIdentity(s,a)),s||(s={coordinationKey:a.key,identity:a,paths:/* @__PURE__ */ new Set,generation:generationFor(a),admissions:/* @__PURE__ */ new Map},t.set(a.key,s)),bindPath(s,e),bindPath(s,a.canonicalPath),s},resolveForNative=e=>{let t=resolveDatabasePath({path:e}),r=n.get(t);if(r)return r;let i=Pe(t);return i?resolve(t,i):void 0},invalidate=e=>{for(let n of e?[e]:t.values())Atomics.store(new BigInt64Array(n.generation.integrity.revision),0,-1n),Atomics.store(new BigInt64Array(n.generation.integrity.lifetime.revision),0,-1n),n.generation=generationFor(n.identity),n.admissions.clear()},seal=e=>{invalidate(e);let t={record:e};return r.add(t),t},release=e=>{e.seal&&=(r.delete(e.seal),void 0)},forget=e=>{if(!hasCloseCustody(e)&&t.get(e.identity.key)===e){t.delete(e.identity.key);for(let r of e.paths)if(n.get(r)===e){n.delete(r);for(let e of t.values())if(e.paths.has(r)){n.set(r,e);break}}}},retireReplacedRecord=e=>{let t=i.get(e);t?(t.superseded=!0,t.seal??=seal(e)):invalidate(e),forget(e)},captureRecord=(e,n)=>{let r=e.admissions.get(n);if(r)return r;let i=e.generation,a=Object.freeze({databasePath:n,coordinationKey:e.coordinationKey,get identity(){return e.identity},captureIntegrity(){a.assertCurrent();let t=i.integrity,n=Atomics.load(new BigInt64Array(t.revision),0),r=Atomics.load(new BigInt64Array(t.lifetime.revision),0);return(n!==t.epoch||r!==t.lifetime.epoch)&&(i.integrity={...t,identity:e.identity,lifetime:{revision:t.lifetime.revision,epoch:r},epoch:n,proof:proofFor()}),i.integrity},assertCurrent(){if(assertOpen(e),t.get(e.identity.key)!==e||e.generation!==i||e.admissions.get(n)!==a)throw new StateDatabaseReadAdmissionInvalidatedError(`OpenClaw state database read admission changed`)}});return e.admissions.set(n,a),a};return{identity(e){return known(e)?.identity??Pe(e)},knownIdentity(e){return known(e)?.identity},integrity(e){let t=resolveForNative(e);return t&&!isSealed(t)?captureRecord(t,resolveDatabasePath({path:e})).captureIntegrity?.():void 0},publish(e,r){let i=resolveDatabasePath({path:e}),a=r??Ie(i),s=n.get(i),c=r&&s?.identity.key===a.key?t.get(a.key):findPhysicalRecord(a);return s&&s.identity.key!==a.key&&(s.identity.key.startsWith(`path:`)&&!c?(publishCreatedIdentity(s,a),c=s):retireReplacedRecord(s)),c||=resolve(i,a),bindPath(c,i),bindPath(c,r?c.identity.canonicalPath:a.canonicalPath),{identity:a,admission:captureRecord(c,i)}},async retireChangedAdmission(e){e.assertCurrent();let n=t.get(e.identity.key),r=await De(e.databasePath);e.assertCurrent(),n&&n.identity.key!==r.key&&retireReplacedRecord(n)},invalidate(e){if(e===void 0)invalidate();else{let t=known(e);t&&invalidate(t)}},register(t){e.add(t);for(let e of i.values())e.queue?.add(t);return()=>{e.delete(t)}},capture(e,t){let r=n.get(e),i=r?.admissions.get(e);if(r&&i&&r.identity.key.startsWith(`file:`))return i.assertCurrent(),i;let a=resolveDatabasePath({path:e}),s=resolve(a,t);return assertOpen(s),captureRecord(s,a)},holdExclusion(e){let n=resolve(resolveDatabasePath({path:e})),i=seal(n);return()=>{r.delete(i);for(let e of t.values())overlaps(n,e)&&forget(e)}},close(n,r){let s=n===void 0?void 0:resolveForNative(n);if(n!==void 0&&!s)return Promise.resolve(r());let c=i.get(s);if(c?.pending)return c.pending;c||(c={retained:/* @__PURE__ */ new Set},i.set(s,c)),c.seal??=seal(s);let l=c,u=a.then(async()=>{let n=/* @__PURE__ */ new Set([...e,...l.retained]);for(let e of i.values())for(let t of e.retained)n.add(t);l.queue=n;let a=[];for(;l.queue.size;){let e=[...l.queue].filter(e=>e.phase!==`after-resources`);if(!e.length&&a.length){for(let e of l.queue)l.retained.add(e);break}let t=e.length?e:[...l.queue];for(let e of t)l.queue.delete(e);await Promise.all(t.map(async e=>{try{let t=s?.identity;t&&e.admission&&t.key!==e.admission.identity.key||await e.close(t),l.retained.delete(e)}catch(t){l.retained.add(e),a.push(t)}}))}a.length&&!l.superseded&&release(l),Ct(a,`OpenClaw state resource drainage failed`);let c=await r(s?.identity);if(i.delete(s),release(l),s===void 0){for(let[e,t]of i)t.pending||(i.delete(e),release(t));for(let e of t.values())forget(e)}else forget(s);return c}).finally(()=>{l.queue=void 0});return l.pending=u,a=u.then(()=>void 0,()=>void 0),u.catch(()=>{l.pending=void 0}),u}}}const Nn=Symbol.for(`openclaw.stateDatabaseLifecycle`),Pn=/* @__PURE__ */ `durable_background_processes.sandbox_persistent_execs.user_profile_identities.user_background_images.local_workspace_projections.local_workspace_manifest_nodes.local_workspace_tree_packs.local_workspace_source_path_sets.update_runs.session_repository_workspaces.github_repository_publication_requests.github_publication_session_lifecycles.skill_library_entries.skill_library_revisions.skill_library_events.skill_library_uploads.github_personal_publication_requests.cron_job_runtime_authorities.cron_run_trigger_state_retirements.execution_identity_contexts.mcp_oauth_pending_authorizations.node_worker_launch_containers.node_worker_launch_boots.node_worker_launch_cleanup.node_worker_launch_process_scopes.node_worker_launches.node_worker_prepared_workspaces.node_worker_turns.operator_approval_execution_identities.operator_approval_standing_grants.operator_approval_standing_grant_generations.web_push_approval_deliveries.execution_decision_facts.execution_owner_lifecycle_bindings.outbound_message_execution_bindings.outbound_message_progress`.split(`.`),Fn=[`idx_sandbox_persistent_execs_container`,`idx_sandbox_persistent_execs_container_name`,`idx_sandbox_persistent_execs_source`,`idx_user_profile_identities_profile_id`,`idx_user_profile_identities_authorization`,`idx_update_runs_created`,`idx_update_runs_active`,`idx_github_repository_publication_shared_request`,`idx_github_repository_publication_personal_request`,`idx_github_personal_publication_owner_session`,`idx_github_personal_publication_pending`,`idx_node_worker_launches_terminal_completed`,`idx_node_worker_turns_terminal_completed`,`idx_node_worker_turns_active_owner`,`idx_operator_approval_standing_grants_binding`,`idx_web_push_approval_deliveries_subscription`,`execution_identity_contexts_run_created_idx`,`execution_decision_facts_cursor_id_idx`,`execution_decision_facts_context_occurred_idx`,`execution_decision_facts_run_occurred_idx`,`outbound_message_execution_bindings_execution_event_idx`,`outbound_message_progress_occurred_idx`,`outbound_message_progress_run_occurred_idx`];[...Pn],[...Fn];const In=5e3,Ln=`https://docs.openclaw.ai/reference/database-schemas`;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 Rn=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject$1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const zn=/* @__PURE__*/ cached(()=>{if(C.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 Bn=/* @__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 Vn={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Hn={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,s={};return mirrorShape(s,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:s,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,s=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`,c={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(c[t]=e[t]);return c.path??=[],c.message=s,t?.reportInput&&(c.input=e.input),c}const Un=/[\uD800-\uDBFF]/;function codePointLength(e){let t=e.length;if(!Un.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 Wn,Gn=!1;const Kn={configurable:!0,get(){Gn=!0}};function defineLazyInternal(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Wn!==e._zod?Wn=void 0:(Wn=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Kn);let e=Gn;Gn=!1;try{let r=n(this);return Gn?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Gn||=e,r}catch(n){throw delete this[t],Gn||=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 qn;const Jn={value:void 0,enumerable:!1};let Yn=`captureStackTrace`in Error?Error:null;function newError(e){let t=Yn;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Yn=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,s=a&&/* @__PURE__ */ new WeakSet;function init(n,r){if(!n._zod){Jn.value=new Internals(r);try{Object.defineProperty(n,"_zod",Jn)}finally{Jn.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.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 c=r?.Parent??Object;class Definition extends c{}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`}};(qn=globalThis).__zod_globalConfig??(qn.__zod_globalConfig={});const C=globalThis.__zod_globalConfig;function config(e){return e&&Object.assign(C,e),C}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 Xn={get:_getMessage,set:_setMessage,enumerable:!0,configurable:!0},Zn={value:void 0,enumerable:!1},Qn=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),$n=/* @__PURE__ */ $constructor(`$ZodError`,(e,t)=>{e.name=`$ZodError`,Zn.value=t,Object.defineProperty(e,"issues",Zn),Zn.value=void 0,Object.defineProperty(e,"message",Xn);let n=Object.getPrototypeOf(e);Qn.has(n)||(Qn.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],s=a===e.length-1;if(n===`_errors`){s&&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 c=r[n];s&&c._errors.push(t(i)),r=c,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},s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise)throw new $ZodAsyncError;if(s.issues.length){let t=new((i?.Err)??e)(s.issues.map(e=>finalizeIssue(e,a,config())));throw Rn(t,i?.callee??fn),t}return s.value};return fn},_parseAsync=e=>{let fn=async(t,n,r,i)=>{let a=r?{...r,async:!0}:{async:!0},s=t._zod.run({value:n,issues:[]},a);if(s instanceof Promise&&(s=await s),s.issues.length){let t=new((i?.Err)??e)(s.issues.map(e=>finalizeIssue(e,a,config())));throw Rn(t,i?.callee??fn),t}return s.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}},er=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),tr=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),validate=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==er)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[tr]=!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),nr=/^[cC][0-9a-z]{6,}$/,rr=/^[0-9a-z]+$/,ir=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,ar=/^[0-9a-vA-V]{20}$/,or=/^[A-Za-z0-9]{27}$/,sr=/^[a-zA-Z0-9_-]{21}$/;function nanoidOfLength(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const cr=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,lr=/^([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)$/,ur=/^(?:[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 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])$/,fr=/^(([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}|:))$/,pr=/^((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])$/,mr=/^(([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])$/,hr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,gr=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,_r=/^https?$/,vr=/^\+[1-9]\d{6,14}$/,yr=`(?:(?:\\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 br=/*@__PURE__*/ anchor(yr);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(`^${yr}T(?:${r})$`)}const xr=/^[\s\S]{0,}$/,Sr=/^-?\d+(?:\.\d+)?$/,Cr=/^[^A-Z]*$/,wr=/^[^a-z]*$/,w=/*@__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},Tr={number:`number`,bigint:`bigint`,object:`date`},Er=/*@__PURE__*/ $constructor(`$ZodCheckLessThan`,(e,t)=>{w.init(e,t);let n=Tr[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Tr[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})}}),Dr=/*@__PURE__*/ $constructor(`$ZodCheckGreaterThan`,(e,t)=>{w.init(e,t);let n=Tr[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Tr[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})}}),Or=/*@__PURE__*/ $constructor(`$ZodCheckMultipleOf`,(e,t)=>{w.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})}}),kr=/*@__PURE__*/ $constructor(`$ZodCheckNumberFormat`,(e,t)=>{w.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Vn[t.format];e._zod.check=s=>{let c=s.value;if(n){if(!Number.isInteger(c)){s.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?s.issues.push({input:c,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}):s.issues.push({input:c,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}}c<i&&s.issues.push({origin:`number`,input:c,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),c>a&&s.issues.push({origin:`number`,input:c,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Ar=/*@__PURE__*/ $constructor(`$ZodCheckMaxLength`,(e,t)=>{var n;w.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})}}),jr=/*@__PURE__*/ $constructor(`$ZodCheckMinLength`,(e,t)=>{var n;w.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})}}),Mr=/*@__PURE__*/ $constructor(`$ZodCheckLengthEquals`,(e,t)=>{var n;w.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 s=getLengthableOrigin(r),c=a>t.length;n.issues.push({origin:s,...c?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Nr=/*@__PURE__*/ $constructor(`$ZodCheckStringFormat`,(e,t)=>{var n,r;w.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=()=>{})}),Pr=/*@__PURE__*/ $constructor(`$ZodCheckRegex`,(e,t)=>{Nr.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})}}),Fr=/*@__PURE__*/ $constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Cr,Nr.init(e,t)}),Ir=/*@__PURE__*/ $constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=wr,Nr.init(e,t)}),Lr=/*@__PURE__*/ $constructor(`$ZodCheckIncludes`,(e,t)=>{w.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})}}),Rr=/*@__PURE__*/ $constructor(`$ZodCheckStartsWith`,(e,t)=>{w.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})}}),zr=/*@__PURE__*/ $constructor(`$ZodCheckEndsWith`,(e,t)=>{w.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})}}),Br=/*@__PURE__*/ $constructor(`$ZodCheckOverwrite`,(e,t)=>{w.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 Vr={major:4,minor:6,patch:7},T=/*@__PURE__*/ $constructor(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Vr;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 s of n){if(s._zod.def.when){if(explicitlyAborted(t)||!s._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,c=s._zod.check(t);if(c instanceof Promise&&r?.async===!1)throw new $ZodAsyncError;if(a||c instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await c,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 Hr=/*@__PURE__*/ $constructor(`$ZodString`,(e,t)=>{T.init(e,t),e._zod.pattern=t.pattern??xr,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}}),E=/*@__PURE__*/ $constructor(`$ZodStringFormat`,(e,t)=>{Nr.init(e,t),Hr.init(e,t)}),Ur=/*@__PURE__*/ $constructor(`$ZodGUID`,(e,t)=>{t.pattern??=lr,E.init(e,t)}),Wr=/*@__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();E.init(e,t)}),Gr=/*@__PURE__*/ $constructor(`$ZodEmail`,(e,t)=>{t.pattern??=ur,E.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===_r.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 Kr=/[\t\n\r]/g;function stripTabAndNewline(e){return e.replace(Kr,``)}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 qr=/*@__PURE__*/ $constructor(`$ZodURL`,(e,t)=>{E.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})}}}),Jr=/*@__PURE__*/ $constructor(`$ZodEmoji`,(e,t)=>{t.pattern??=emoji(),E.init(e,t)}),Yr=/*@__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?sr:nanoidOfLength(t.length),E.init(e,t)}),Xr=/*@__PURE__*/ $constructor(`$ZodCUID`,(e,t)=>{t.pattern??=nr,E.init(e,t)}),Zr=/*@__PURE__*/ $constructor(`$ZodCUID2`,(e,t)=>{t.pattern??=rr,E.init(e,t)}),Qr=/*@__PURE__*/ $constructor(`$ZodULID`,(e,t)=>{t.pattern??=ir,E.init(e,t)}),$r=/*@__PURE__*/ $constructor(`$ZodXID`,(e,t)=>{t.pattern??=ar,E.init(e,t)}),ei=/*@__PURE__*/ $constructor(`$ZodKSUID`,(e,t)=>{t.pattern??=or,E.init(e,t)}),ti=/*@__PURE__*/ $constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??=datetime(t),E.init(e,t)}),ni=/*@__PURE__*/ $constructor(`$ZodISODate`,(e,t)=>{t.pattern??=br,E.init(e,t)}),ri=/*@__PURE__*/ $constructor(`$ZodISOTime`,(e,t)=>{t.pattern??=time(t),E.init(e,t)}),ii=/*@__PURE__*/ $constructor(`$ZodISODuration`,(e,t)=>{t.pattern??=cr,E.init(e,t)}),ai=/*@__PURE__*/ $constructor(`$ZodIPv4`,(e,t)=>{t.pattern??=dr,E.init(e,t)}),oi=/^[0-9a-fA-F:.]+$/;function isValidIPv6(e){return oi.test(e)?canParseURL(`http://[${e}]`):!1}const si=/*@__PURE__*/ $constructor(`$ZodIPv6`,(e,t)=>{t.pattern??=fr,E.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})}}),ci=/*@__PURE__*/ $constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??=pr,E.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 li=/*@__PURE__*/ $constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??=mr,E.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 ui=/^[0-9a-zA-Z+/]*={0,2}$/,di=/*@__PURE__*/ $constructor(`$ZodBase64`,(e,t)=>{t.pattern??=ui,E.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})}}),fi=/^[A-Za-z0-9_-]*$/;function isValidBase64URL(e){if(!fi.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const pi=/*@__PURE__*/ $constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??=fi,E.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})}}),mi=/*@__PURE__*/ $constructor(`$ZodE164`,(e,t)=>{t.pattern??=vr,E.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 hi=/*@__PURE__*/ $constructor(`$ZodJWT`,(e,t)=>{E.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})}}),gi=/*@__PURE__*/ $constructor(`$ZodNumber`,(e,t)=>{T.init(e,t),e._zod.pattern=Sr,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}}),_i=/*@__PURE__*/ $constructor(`$ZodNumberFormat`,(e,t)=>{kr.init(e,t),gi.init(e,t)}),vi=/*@__PURE__*/ $constructor(`$ZodUnknown`,(e,t)=>{T.init(e,t),e._zod.parse=e=>e}),yi=/*@__PURE__*/ $constructor(`$ZodNever`,(e,t)=>{T.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 s=t(n.value);if(s>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of sizeCaps(e._zod.def.checks))if(s>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 bi=/*@__PURE__*/ $constructor(`$ZodArray`,(e,t)=>{T.init(e,t);let n=C.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 s=[],c=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],l=t.element._zod.run({value:n,issues:[]},i);if(l instanceof Promise)s.push(l.then(t=>handleArrayResult(t,r,e)));else if(handleArrayResult(l,r,e),c&&l.issues.length!==0&&aborted(l))break}return s.length?Promise.all(s).then(()=>r):r},capSize(e,arraySize)});function handlePropertyResult(e,t,n,r,i,a){let s=n in r,c=a===`optional`;if(s||!c||i!==`optional`){if(e.issues.length){if(i!==void 0&&c&&!s)return;t.issues.push(...prefixIssues(n,e.issues))}!s&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(s||i===`defaulted`&&!c)&&(t.value[n]=void 0):t.value[n]=e.value}}const xi=[];function normalizeDef(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:xi,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,s){let c=[],l=i.keySet,u=i.catchall._zod,d=u.def.type,f=u.optin,p=u.optout,m=0;for(let i in t){if(s&&n.issues.length!==m){if(aborted(n,m))break;m=n.issues.length}if(l.has(i))continue;if(i===`__proto__`){d===`never`&&c.push(i);continue}if(d===`never`){c.push(i);continue}let a=u.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>handlePropertyResult(e,n,i,t,f,p))):handlePropertyResult(a,n,i,t,f,p)}return c.length&&n.issues.push({code:`unrecognized_keys`,keys:c,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const Si=/*@__PURE__*/ $constructor(`$ZodObject`,(e,t)=>{T.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,s=t.catchall,c,l=C.memoizer;l?.attach(e),e._zod.parse=(t,n)=>{c??=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=l?l.alloc(e,t,{},n):{};let u=[],d=c.shape,f=n?.abortEarly,p=t.issues.length;for(let e of c.allKeys){if(f&&t.issues.length!==p){if(aborted(t,p))break;p=t.issues.length}if(e===`__proto__`)continue;let i=d[e],a=i._zod.optin,s=i._zod.optout,c=i._zod.run({value:r[e],issues:[]},n);c instanceof Promise?u.push(c.then(n=>handlePropertyResult(n,t,e,r,a,s))):handlePropertyResult(c,t,e,r,a,s)}return s?handleCatchall(u,r,t,n,i.value,e,f===!0):u.length?Promise.all(u).then(()=>t):t}}),Ci=/*@__PURE__*/ $constructor(`$ZodObjectJIT`,(e,t)=>{Si.init(e,t);let n=e._zod.parse,r=cached(()=>normalizeDef(t)),i=C.memoizer,generateFastpass=t=>{let n=r.value,a=n.symbolKeys,s=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;
}`;s.write(`const input = payload.value;`);let c=Object.create(null),l=0;for(let e of n.allKeys)c[e]=`key_${l++}`;s.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=c[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:esc(e),i=`${r} in input`,l=t[e],u=l?._zod?.optin,d=u!==void 0,f=l?._zod?.optout===`optional`;if(s.write(`const ${n} = ${parseStr(r)};`),d&&f){let e=u===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;s.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 d?(s.write(`
if (${n}.issues.length) {${prefixStr(n,r)}
}
`),u===`defaulted`?s.write(`newResult[${r}] = ${n}.value;`):s.write(`
if (${n}.value !== undefined || ${i}) {
newResult[${r}] = ${n}.value;
}
`)):s.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 s.write(`payload.value = newResult;`),s.write(`return payload;`),s.compile()},a,s=isObject$1,c=!C.jitless,l=c&&zn.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(a||=generateFastpass(t.shape),i=a(i,f),u?handleCatchall([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,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 wi=/*@__PURE__*/ $constructor(`$ZodUnion`,(e,t)=>{T.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,s=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)s.push(t),a=!0;else{if(t.issues.length===0)return t;s.push(t)}}return a?Promise.all(s).then(t=>handleUnionResults(t,r,e,i)):handleUnionResults(s,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 Ti=/*@__PURE__*/ $constructor(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,wi.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 s=i.value;if(!isObject$1(s))return i.issues.push({code:`invalid_type`,expected:`object`,input:s,inst:e}),i;let c=s?.[t.discriminator],l=r.value.get(c);return l&&(c!==void 0||a.direction!==`backward`)?l._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:s,path:[t.discriminator],inst:e}),i)}}),Ei=/*@__PURE__*/ $constructor(`$ZodIntersection`,(e,t)=>{T.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],s=mergeValues(i,a);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.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 s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=mergeValues(t.value,n.value);if(!c.valid){if(aborted(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const Di=/*@__PURE__*/ $constructor(`$ZodEnum`,(e,t)=>{T.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=>Bn.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}}),Oi=/*@__PURE__*/ $constructor(`$ZodLiteral`,(e,t)=>{T.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}}),ki=/*@__PURE__*/ $constructor(`$ZodTransform`,(e,t)=>{T.init(e,t),e._zod.optin=`optional`,C.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 Ai=/*@__PURE__*/ $constructor(`$ZodOptional`,(e,t)=>{T.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)}}),ji=/*@__PURE__*/ $constructor(`$ZodExactOptional`,(e,t)=>{Ai.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)}),Mi=/*@__PURE__*/ $constructor(`$ZodNullable`,(e,t)=>{T.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)}),Ni=/*@__PURE__*/ $constructor(`$ZodDefault`,(e,t)=>{T.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 Pi=/*@__PURE__*/ $constructor(`$ZodPrefault`,(e,t)=>{T.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))}),Fi=/*@__PURE__*/ $constructor(`$ZodNonOptional`,(e,t)=>{T.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 Ii=/*@__PURE__*/ $constructor(`$ZodCatch`,(e,t)=>{T.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)}}),Li=/*@__PURE__*/ $constructor(`$ZodPipe`,(e,t)=>{T.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 Ri=/*@__PURE__*/ $constructor(`$ZodReadonly`,(e,t)=>{T.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 zi=/*@__PURE__*/ $constructor(`$ZodCustom`,(e,t)=>{w.init(e,t),T.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 Bi=`~memo`,Vi=[];function isRef(e){return typeof e==`object`&&!!e}function cloneIssues(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const Hi=/*@__PURE__*/ new WeakMap;function isRecursive(e,t,n){let r=Hi.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 s=Object.getOwnPropertyDescriptor(e,a);if(r&&!s.enumerable)continue;let c=s.get?1:s.value?._zod?isRecursive(s.value,t,n):0;c>i&&(i=c)}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&&Hi.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 Ui;const Wi=[],Gi={alloc(e,t,n){let r=Ui;if(!r)return n;Ui=void 0;let i={value:n,issues:null};return r.set(t.value,i),Wi.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=(s,c)=>{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(s,c);i===2||r?n=!0:r=!0}let l=s.value;if(!isRef(l))return t(s,c);let u=c[Bi];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[Bi]=u);let d;i===c?d=a:(d=bucketFor(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...cloneIssues(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;Ui=d;let p=Wi.length,m=t(s,c);Ui=void 0;let h=Wi.length>p?Wi.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?cloneIssues(e.issues):Vi),e)):(h&&(h.issues=m.issues.length?cloneIssues(m.issues):Vi),m)};e._zod.parse=wrapped,e._zod.run===t&&(e._zod.run=wrapped)})}};function memoizer(){return Gi}function isBackEdge(e,t){let n=e[Bi]?.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 Ki,$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}(Ki=globalThis).__zod_globalRegistry??(Ki.__zod_globalRegistry=registry());const qi=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 _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 Er({check:`less_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _lte(e,t){return new Er({check:`less_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _gt(e,t){return new Dr({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
function _gte(e,t){return new Dr({check:`greater_than`,...normalizeParams(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
function _multipleOf(e,t){return new Or({check:`multiple_of`,...normalizeParams(t),value:e})}// @__NO_SIDE_EFFECTS__
function _maxLength(e,t){return new Ar({check:`max_length`,...normalizeParams(t),maximum:e})}// @__NO_SIDE_EFFECTS__
function _minLength(e,t){return new jr({check:`min_length`,...normalizeParams(t),minimum:e})}// @__NO_SIDE_EFFECTS__
function _length(e,t){return new Mr({check:`length_equals`,...normalizeParams(t),length:e})}// @__NO_SIDE_EFFECTS__
function _regex(e,t){return new Pr({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}// @__NO_SIDE_EFFECTS__
function _lowercase(e){return new Fr({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _uppercase(e){return new Ir({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _includes(e,t){return new Lr({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}// @__NO_SIDE_EFFECTS__
function _startsWith(e,t){return new Rr({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}// @__NO_SIDE_EFFECTS__
function _endsWith(e,t){return new zr({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}// @__NO_SIDE_EFFECTS__
function _overwrite(e){return new Br({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 _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 w({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??qi,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 s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let c=e._zod.toJSONSchema?.();if(c)s.schema=c;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,r);else{let n=s.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&&(s.ref||=a,processSchema(a,t,r),t.seen.get(a).isParent=!0)}let l=t.metadataRegistry.get(e);return l&&assignProps(s.schema,l),t.io===`input`&&isTransforming(e)&&(delete s.schema.examples,delete s.schema.default),t.io===`input`&&`_prefault`in s.schema&&((r=s.schema).default??(r.default=s.schema._prefault)),delete s.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 Ji=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),Yi=[`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(!Ji.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 Ji)if(t in e)return;let n=t.filter(e=>Yi.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=foldObjects(t);else{let e=n[0],i=Yi.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),s=e[i].map(e=>foldObjects([...a,e]));if(s.some(e=>!e))return;r={[i]:s}}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),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(r.allOf=r.allOf??[],r.allOf.push(s)):assignProps(r,s),assignProps(r,i),t._zod.parent===a)for(let e in r)e!==`$ref`&&e!==`allOf`&&(e in i||delete r[e]);if(s.$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 s=t._zod.parent;if(s&&s!==a){flattenRef(s);let t=e.seen.get(s);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??{},s=initializeContext({...i??{},target:a,io:t,processors:n});return processSchema(e,s),extractDefs(s,e),finalize(s,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)},Xi={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(Vn),bigint_format:formatContributor(Hn),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)Xi[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 Zi={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Qi=/* @__PURE__ */ new Map([[ui,hr],[fi,gr]]),exactPattern=e=>Qi.get(e)??e,stringProcessor=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:s,format:c,patterns:l,contentEncoding:u,laxFormat:d}=aggregateChecks(e);if(typeof a==`number`&&(i.minLength=a),typeof s==`number`&&(i.maxLength=s),c&&(i.format=Zi[c]??c,i.format===``&&delete i.format,(c===`time`||d)&&delete i.format),u&&(i.contentEncoding=u),l&&l.size>0){let e=[...l].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:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u,isInt:d}=aggregateChecks(e);i.type=d?`integer`:`number`;let f=typeof u==`number`&&u>=(a??-1/0),p=typeof l==`number`&&l<=(s??1/0),m=t.target===`draft-04`||t.target===`openapi-3.0`;if(f?m?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),p?m?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof s==`number`&&(i.maximum=s),c){let n=/* @__PURE__ */ new Set;for(let a of c)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,...s]=n;a!==void 0&&(i.multipleOf=a),s.length&&(i.allOf=[...i.allOf??[],...s.map(e=>({multipleOf:e}))])}},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 s of i.values)if(s===void 0){if(handleUnrepresentable(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s==`bigint`){if(handleUnrepresentable(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(s))}else a.push(s);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:s,maximum:c}=aggregateChecks(e);typeof s==`number`&&(i.minItems=s),typeof c==`number`&&(i.maxItems=c),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,s=a.shape;if(Object.getOwnPropertySymbols(s).length&&handleUnrepresentable(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in s)assignProp(i.properties,e,processSchema(s[e],t,{...r,path:[...r.path,`properties`,e]}));let c=[];for(let e of Object.keys(s)){let n=a.shape[e];(t.io===`input`?inputOptin(n)===void 0:n._zod.optout===void 0)&&c.push(e)}c.length>0&&(i.required=c),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,s=i.options.map((e,n)=>processSchema(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=s:n.anyOf=s},intersectionProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.left,t,{...r,path:[...r.path,`allOf`,0]}),s=processSchema(i.right,t,{...r,path:[...r.path,`allOf`,1]}),isSimpleIntersection=e=>`allOf`in e&&Object.keys(e).length===1,c=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(s)?s.allOf:[s]];n.allOf=c,t.intersections.push(c)},nullableProcessor=(e,t,n,r)=>{let i=e._zod.def,a=processSchema(i.innerType,t,r),s=t.seen.get(e);t.target===`openapi-3.0`?(s.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},$i=Symbol();function serializeDefaultValue(e,t,n,r,i){let a=!1,s=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`),$i):JSON.parse(s)}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 s=serializeDefaultValue(i.defaultValue,e,t,n,r);s!==$i&&(n.default=s)},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 s=serializeDefaultValue(i.defaultValue,e,t,n,r);s!==$i&&(n._prefault=s)},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 s;try{s=i.catchValue(void 0)}catch{handleUnrepresentable(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=s},pipeProcessor=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),s=t.io===`input`?a?i.out:i.in:i.out;processSchema(s,t,r);let c=t.seen.get(e);c.ref=s},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},ea=/* @__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 D=/*@__PURE__*/ $constructor(`ZodError`,(e,t)=>{$n.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);ea.has(n)||(ea.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}),ta=/* @__PURE__ */ _parse(D),na=/* @__PURE__ */ _parseAsync(D),ra=/* @__PURE__ */ _safeParse(D),ia=/* @__PURE__ */ _safeParseAsync(D),aa=/* @__PURE__ */ _encode(D),oa=/* @__PURE__ */ _decode(D),sa=/* @__PURE__ */ _encodeAsync(D),ca=/* @__PURE__ */ _decodeAsync(D),la=/* @__PURE__ */ _safeEncode(D),ua=/* @__PURE__ */ _safeDecode(D),da=/* @__PURE__ */ _safeEncodeAsync(D),fa=/* @__PURE__ */ _safeDecodeAsync(D);function _ensureDefaultLocale(){C.localeError||config(en_default())}function _ensureDefaultMemoizer(){C.memoizer||config({memoizer:memoizer()})}const O=/*@__PURE__*/ $constructor(`ZodType`,(e,t)=>(_ensureDefaultLocale(),T.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 qi.add(t,{description:e}),t},meta(...e){if(e.length===0)return qi.get(this);let t=this.clone();return qi.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 ta(this,e,t,{callee:_parse})},parseAsync:async function _parseAsync(e,t){return await na(this,e,t,{callee:_parseAsync})},safeParse(e,t){return ra(this,e,t)},async safeParseAsync(e,t){return ia(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 aa(this,e,t,{callee:_encode})},decode:function _decode(e,t){return oa(this,e,t,{callee:_decode})},encodeAsync:async function _encodeAsync(e,t){return await sa(this,e,t,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(e,t){return await ca(this,e,t,{callee:_decodeAsync})},safeEncode(e,t){return la(this,e,t)},safeDecode(e,t){return ua(this,e,t)},async safeEncodeAsync(e,t){return da(this,e,t)},async safeDecodeAsync(e,t){return fa(this,e,t)},toJSONSchema(e){return createToJSONSchemaMethod(this,{})(e)},get description(){return qi.get(this)?.description},get _def(){return this._zod.def}}),pa=/*@__PURE__*/ $constructor(`_ZodString`,(e,t)=>{Hr.init(e,t),O.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())}})),ma=/*@__PURE__*/ $constructor(`ZodString`,(e,t)=>{Hr.init(e,t),pa.init(e,t)},{email(e){return this.check(/* @__PURE__ */ _email(ya,e))},url(e){return this.check(/* @__PURE__ */ _url(Sa,e))},jwt(e){return this.check(/* @__PURE__ */ _jwt(La,e))},emoji(e){return this.check(/* @__PURE__ */ _emoji(Ca,e))},guid(e){return this.check(/* @__PURE__ */ _guid(ba,e))},uuid(e){return this.check(/* @__PURE__ */ _uuid(xa,e))},uuidv4(e){return this.check(/* @__PURE__ */ _uuidv4(xa,e))},uuidv6(e){return this.check(/* @__PURE__ */ _uuidv6(xa,e))},uuidv7(e){return this.check(/* @__PURE__ */ _uuidv7(xa,e))},nanoid(e){return this.check(/* @__PURE__ */ _nanoid(wa,e))},cuid(e){return this.check(/* @__PURE__ */ _cuid(Ta,e))},cuid2(e){return this.check(/* @__PURE__ */ _cuid2(Ea,e))},ulid(e){return this.check(/* @__PURE__ */ _ulid(Da,e))},base64(e){return this.check(/* @__PURE__ */ _base64(Pa,e))},base64url(e){return this.check(/* @__PURE__ */ _base64url(Fa,e))},xid(e){return this.check(/* @__PURE__ */ _xid(Oa,e))},ksuid(e){return this.check(/* @__PURE__ */ _ksuid(ka,e))},ipv4(e){return this.check(/* @__PURE__ */ _ipv4(Aa,e))},ipv6(e){return this.check(/* @__PURE__ */ _ipv6(ja,e))},cidrv4(e){return this.check(/* @__PURE__ */ _cidrv4(Ma,e))},cidrv6(e){return this.check(/* @__PURE__ */ _cidrv6(Na,e))},e164(e){return this.check(/* @__PURE__ */ _e164(Ia,e))},datetime(e){return this.check(/* @__PURE__ */ _isoDateTime(ha,e))},date(e){return this.check(/* @__PURE__ */ _isoDate(ga,e))},time(e){return this.check(/* @__PURE__ */ _isoTime(_a,e))},duration(e){return this.check(/* @__PURE__ */ _isoDuration(va,e))}});function string(e){return/* @__PURE__ */ _string(ma,e)}const k=/*@__PURE__*/ $constructor(`ZodStringFormat`,(e,t)=>{E.init(e,t),pa.init(e,t)}),ha=/*@__PURE__*/ $constructor(`ZodISODateTime`,(e,t)=>{ti.init(e,t),k.init(e,t)}),ga=/*@__PURE__*/ $constructor(`ZodISODate`,(e,t)=>{ni.init(e,t),k.init(e,t)}),_a=/*@__PURE__*/ $constructor(`ZodISOTime`,(e,t)=>{ri.init(e,t),k.init(e,t)}),va=/*@__PURE__*/ $constructor(`ZodISODuration`,(e,t)=>{ii.init(e,t),k.init(e,t)}),ya=/*@__PURE__*/ $constructor(`ZodEmail`,(e,t)=>{Gr.init(e,t),k.init(e,t)}),ba=/*@__PURE__*/ $constructor(`ZodGUID`,(e,t)=>{Ur.init(e,t),k.init(e,t)}),xa=/*@__PURE__*/ $constructor(`ZodUUID`,(e,t)=>{Wr.init(e,t),k.init(e,t)}),Sa=/*@__PURE__*/ $constructor(`ZodURL`,(e,t)=>{qr.init(e,t),k.init(e,t)}),Ca=/*@__PURE__*/ $constructor(`ZodEmoji`,(e,t)=>{Jr.init(e,t),k.init(e,t)}),wa=/*@__PURE__*/ $constructor(`ZodNanoID`,(e,t)=>{Yr.init(e,t),k.init(e,t)}),Ta=/*@__PURE__*/ $constructor(`ZodCUID`,(e,t)=>{Xr.init(e,t),k.init(e,t)}),Ea=/*@__PURE__*/ $constructor(`ZodCUID2`,(e,t)=>{Zr.init(e,t),k.init(e,t)}),Da=/*@__PURE__*/ $constructor(`ZodULID`,(e,t)=>{Qr.init(e,t),k.init(e,t)}),Oa=/*@__PURE__*/ $constructor(`ZodXID`,(e,t)=>{$r.init(e,t),k.init(e,t)}),ka=/*@__PURE__*/ $constructor(`ZodKSUID`,(e,t)=>{ei.init(e,t),k.init(e,t)}),Aa=/*@__PURE__*/ $constructor(`ZodIPv4`,(e,t)=>{ai.init(e,t),k.init(e,t)}),ja=/*@__PURE__*/ $constructor(`ZodIPv6`,(e,t)=>{si.init(e,t),k.init(e,t)}),Ma=/*@__PURE__*/ $constructor(`ZodCIDRv4`,(e,t)=>{ci.init(e,t),k.init(e,t)}),Na=/*@__PURE__*/ $constructor(`ZodCIDRv6`,(e,t)=>{li.init(e,t),k.init(e,t)}),Pa=/*@__PURE__*/ $constructor(`ZodBase64`,(e,t)=>{di.init(e,t),k.init(e,t)}),Fa=/*@__PURE__*/ $constructor(`ZodBase64URL`,(e,t)=>{pi.init(e,t),k.init(e,t)}),Ia=/*@__PURE__*/ $constructor(`ZodE164`,(e,t)=>{mi.init(e,t),k.init(e,t)}),La=/*@__PURE__*/ $constructor(`ZodJWT`,(e,t)=>{hi.init(e,t),k.init(e,t)}),Ra=/*@__PURE__*/ $constructor(`ZodNumber`,(e,t)=>{gi.init(e,t),O.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(Ra,e)}const za=/*@__PURE__*/ $constructor(`ZodNumberFormat`,(e,t)=>{_i.init(e,t),Ra.init(e,t)});function int(e){return/* @__PURE__ */ _int(za,e)}const Ba=/*@__PURE__*/ $constructor(`ZodUnknown`,(e,t)=>{vi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function unknown(){return/* @__PURE__ */ _unknown(Ba)}const Va=/*@__PURE__*/ $constructor(`ZodNever`,(e,t)=>{yi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)});function never(e){return/* @__PURE__ */ _never(Va,e)}const Ha=/*@__PURE__*/ $constructor(`ZodArray`,(e,t)=>{_ensureDefaultMemoizer(),bi.init(e,t),O.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(Ha,e,t)}const Ua=/*@__PURE__*/ $constructor(`ZodObject`,(e,t)=>{_ensureDefaultMemoizer(),Ci.init(e,t),O.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(Xa,this,e[0])},exactPartial(...e){return partial(Za,this,e[0],`exactPartial`)},required(...e){return required(to,this,e[0])}});function object(e,t){let n={type:`object`,shape:e??{},...normalizeParams(t)};return new Ua(n)}function strictObject(e,t){return new Ua({type:`object`,shape:e,catchall:never(),...normalizeParams(t)})}const Wa=/*@__PURE__*/ $constructor(`ZodUnion`,(e,t)=>{wi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r),e.options=t.options});function union(e,t){return new Wa({type:`union`,options:e,...normalizeParams(t)})}const Ga=/*@__PURE__*/ $constructor(`ZodDiscriminatedUnion`,(e,t)=>{Wa.init(e,t),Ti.init(e,t)});function discriminatedUnion(e,t,n){return new Ga({type:`union`,options:t,discriminator:e,...normalizeParams(n)})}const Ka=/*@__PURE__*/ $constructor(`ZodIntersection`,(e,t)=>{Ei.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)});function intersection(e,t){return new Ka({type:`intersection`,left:e,right:t})}const qa=/*@__PURE__*/ $constructor(`ZodEnum`,(e,t)=>{Di.init(e,t),O.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 qa({...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 qa({...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 qa({type:`enum`,entries:n,...normalizeParams(t)})}const Ja=/*@__PURE__*/ $constructor(`ZodLiteral`,(e,t)=>{Oi.init(e,t),O.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 Ja({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const Ya=/*@__PURE__*/ $constructor(`ZodTransform`,(e,t)=>{_ensureDefaultMemoizer(),ki.init(e,t),O.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 Ya({type:`transform`,transform:e})}const Xa=/*@__PURE__*/ $constructor(`ZodOptional`,(e,t)=>{Ai.init(e,t),O.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 Xa({type:`optional`,innerType:e})}const Za=/*@__PURE__*/ $constructor(`ZodExactOptional`,(e,t)=>{ji.init(e,t),O.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 Za({type:`optional`,innerType:e})}const Qa=/*@__PURE__*/ $constructor(`ZodNullable`,(e,t)=>{Mi.init(e,t),O.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 Qa({type:`nullable`,innerType:e})}const $a=/*@__PURE__*/ $constructor(`ZodDefault`,(e,t)=>{Ni.init(e,t),O.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 $a({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const eo=/*@__PURE__*/ $constructor(`ZodPrefault`,(e,t)=>{Pi.init(e,t),O.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 eo({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():shallowClone(t)}})}const to=/*@__PURE__*/ $constructor(`ZodNonOptional`,(e,t)=>{Fi.init(e,t),O.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 to({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const no=/*@__PURE__*/ $constructor(`ZodCatch`,(e,t)=>{Ii.init(e,t),O.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 no({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:constantCatch(t)})}const ro=/*@__PURE__*/ $constructor(`ZodPipe`,(e,t)=>{Li.init(e,t),O.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 ro({type:`pipe`,in:e,out:t})}const io=/*@__PURE__*/ $constructor(`ZodReadonly`,(e,t)=>{Ri.init(e,t),O.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 io({type:`readonly`,innerType:e})}const ao=/*@__PURE__*/ $constructor(`ZodCustom`,(e,t)=>{zi.init(e,t),O.init(e,t),e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)});function refine(e,t={}){return/* @__PURE__ */ _refine(ao,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}}let oo;function isContainerEnvironment(){return oo??=detectContainerEnvironment()}function detectContainerEnvironment(){if(process.env.FLY_MACHINE_ID?.trim()&&process.env.FLY_APP_NAME?.trim())return!0;for(let e of[`/.dockerenv`,`/run/.containerenv`,`/var/run/.containerenv`])try{return S.accessSync(e,S.constants.F_OK),!0}catch{}try{let e=S.readFileSync(`/proc/1/cgroup`,`utf8`);if(/\/docker\/|cri-containerd-[0-9a-f]|containerd\/[0-9a-f]{64}|\/kubepods[/.]|\blxc\b/.test(e))return!0}catch{}return!1}function resolveEnvironmentValue(e,t,n=process.platform){if(!e)return;if(n!==`win32`)return e[t]??(t===`PATH`?e.Path:void 0);let r=t.toUpperCase(),i=Object.keys(e).toSorted().find(e=>e.toUpperCase()===r);return i===void 0?void 0:e[i]}function mergeProcessEnv(e,t=process.platform){let n=Object.create(null),r=/* @__PURE__ */ new Map;for(let i of e){if(!i)continue;let e=Object.keys(i),a=/* @__PURE__ */ new Set;for(let s of t===`win32`?e.toSorted():e){let e=t===`win32`?s.toUpperCase():void 0;if(e!==void 0){if(a.has(e))continue;a.add(e);let t=r.get(e);t!==void 0&&delete n[t],r.delete(e)}let c=i[s];c===void 0?delete n[s]:(n[s]=c,e!==void 0&&Object.hasOwn(n,s)&&r.set(e,s))}}return n}const so=/* @__PURE__ */ new Set(/* @__PURE__ */ `PATH.Path.HOME.USER.LOGNAME.TMPDIR.TMP.TEMP.LANG.LANGUAGE.TZ.LC_ALL.LC_COLLATE.LC_CTYPE.LC_MESSAGES.LC_MONETARY.LC_NUMERIC.LC_TIME.LC_ADDRESS.LC_IDENTIFICATION.LC_MEASUREMENT.LC_NAME.LC_PAPER.LC_TELEPHONE.SYSTEMROOT.WINDIR.COMSPEC.PATHEXT.SYSTEMDRIVE.USERPROFILE.HOMEDRIVE.HOMEPATH.USERNAME.USERDOMAIN.APPDATA.LOCALAPPDATA.PROGRAMDATA.ALLUSERSPROFILE.PROGRAMFILES.PROGRAMFILES(X86).PROGRAMW6432.COMMONPROGRAMFILES.COMMONPROGRAMFILES(X86).COMMONPROGRAMW6432.PSMODULEANALYSISCACHEPATH`.split(`.`));function resolveDiagnosticProcessEnv(e=process.env,t=process.platform){return Object.fromEntries(Object.entries(mergeProcessEnv([e],t)).filter(([e])=>so.has(t===`win32`?e.toUpperCase():e)))}const co=`C:\\Windows`;function readNativeProcessStartTime(e){if(!(process.platform!==`win32`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=_n(e);return t&&!t.exited?Math.floor(t.startTimeMicros/1e3):null}catch{return}}function windowsSystemRoot(e){let t=resolveEnvironmentValue(e,`SystemRoot`,`win32`)??resolveEnvironmentValue(e,`WINDIR`,`win32`);if(!t)return co;let n=x.win32.normalize(t);return/^[A-Za-z]:\\/.test(n)&&!n.startsWith(`\\\\`)?n:co}function windowsPowerShellPath(e){return x.win32.join(windowsSystemRoot(e),`System32`,`WindowsPowerShell`,`v1.0`,`powershell.exe`)}function windowsWmicPath(e){return x.win32.join(windowsSystemRoot(e),`System32`,`wbem`,`wmic.exe`)}function decodeWindowsProcessOutput(e){return Buffer.isBuffer(e)?e.length>=2&&e[0]===255&&e[1]===254?e.toString(`utf16le`):e.toString(`utf8`):e}function parseWindowsProcessStartTime(e){let t=decodeWindowsProcessOutput(e).split(/\r?\n/).map(e=>e.trim()).filter(Boolean),n=t.find(e=>e.toLowerCase().startsWith(`creationdate=`))?.slice(13).trim()??t.find(e=>e.toLowerCase()!==`creationdate`)??``,r=Date.parse(n);if(Number.isFinite(r))return r;let i=n.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.(\d{6})([+-])(\d{3})$/);if(!i)return null;let[,a,s,c,l,u,d,f,p,m]=i;return Date.UTC(Number(a),Number(s)-1,Number(c),Number(l),Number(u),Number(d),Math.floor(Number(f)/1e3))-Number(m)*6e4*(p===`+`?1:-1)}function readWindowsProcessStartTimeSync(e,t=1e4,n=process.env){if(!Number.isInteger(e)||e<=0||e>4294967295)return null;let r=performance.now()+t,i=readNativeProcessStartTime(e);if(i!==void 0)return i;let a=Math.ceil(r-performance.now());if(a<=0)return null;let s=hn(windowsPowerShellPath(n),[`-NoProfile`,`-NonInteractive`,`-Command`,`$process = [System.Diagnostics.Process]::GetProcessById(${e}); try { [Console]::Out.Write($process.StartTime.ToUniversalTime().ToString("o")) } finally { $process.Dispose() }`],{encoding:`utf8`,env:resolveDiagnosticProcessEnv(n,`win32`),timeout:Math.min(a,5e3),windowsHide:!0});if(!s.error&&s.status===0){let e=parseWindowsProcessStartTime(s.stdout);if(e!==null)return e}let c=Math.ceil(r-performance.now());if(c<=0)return null;let l=hn(windowsWmicPath(n),[`process`,`where`,`ProcessId=${e}`,`get`,`CreationDate`,`/value`],{env:resolveDiagnosticProcessEnv(n,`win32`),timeout:c,windowsHide:!0,stdio:[`ignore`,`pipe`,`ignore`]});return!l.error&&l.status===0?parseWindowsProcessStartTime(l.stdout):null}let lo;function loadFreeBsdProcessIdentityNative(){if(typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD)throw Error(`FreeBSD process identity is unavailable in this sealed runtime`);return lo||=Yt(import.meta.url)(`@openclaw/proc-safe/identity`),lo}function readFreeBsdProcessStartTime(e){if(process.platform!==`freebsd`||!Number.isInteger(e)||e<=0||e>2147483647)return null;try{return loadFreeBsdProcessIdentityNative().readProcessIdentity(e)?.startTimeSinceBootMicros??null}catch{return null}}function readDarwinNativeIdentity(e){if(!(process.platform!==`darwin`||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=_n(e);return t&&!t.exited?{startedAt:Math.floor(t.startTimeMicros/1e6),startTimeMicros:t.startTimeMicros}:null}catch{return}}function readNativeLiveness(e){if(!(![`darwin`,`win32`,`freebsd`].includes(process.platform)||typeof SEALED_RUNTIME_BUILD==`boolean`&&SEALED_RUNTIME_BUILD))try{let t=_n(e);return t!==null&&!t.exited}catch(e){return e instanceof gn&&(e.code===`helper-unavailable`||e.code===`unsupported-platform`)?void 0:!0}}let uo=null;function isValidPid(e){return Number.isInteger(e)&&e>0}function hasLinuxProcfs(){return process.platform===`linux`||process.platform===`android`}function exitedLinuxStatus(e,t){let n=t.match(/^State:\s+(\S)/m)?.[1],r=t.match(/^Threads:[ \t]+(\d+)[ \t]*$/m)?.[1];if(r===`0`)return;let i=t.match(/^Tgid:[ \t]+(\d+)[ \t]*$/m)?.[1];return i!==void 0&&Number(i)!==e||(n===`Z`||n===`X`)&&r===`1`}function isMissingPid(e){try{process.kill(e,0)}catch(e){return p(e,`ESRCH`)}return!1}function isExitedLinuxProcess(e){if(!hasLinuxProcfs())return!1;try{let t=exitedLinuxStatus(e,S.readFileSync(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}async function isPidDefinitelyDeadAsync(e){if(!hasLinuxProcfs())return isPidDefinitelyDead(e);if(!isValidPid(e))return!0;try{process.kill(e,0)}catch(e){return p(e,`ESRCH`)}try{let t=exitedLinuxStatus(e,await S.promises.readFile(`/proc/${e}/status`,`utf8`));if(t!==void 0)return t}catch{}return isMissingPid(e)}function isPidAlive(e){if(!isValidPid(e))return!1;try{process.kill(e,0)}catch(t){let n=r(t)?t.code:void 0;if(n!==`EPERM`)return n===`ESRCH`?readNativeLiveness(e)??!1:!1}return readNativeLiveness(e)??!isExitedLinuxProcess(e)}function isPidDefinitelyDead(e){if(!isValidPid(e))return!0;let t=!1;try{process.kill(e,0)}catch(e){let n=r(e)?e.code:void 0;if(n!==`ESRCH`&&(process.platform!==`win32`||n!==`EPERM`))return!1;t=n===`ESRCH`}let n=readNativeLiveness(e);return n===void 0?t&&process.platform!==`freebsd`||isExitedLinuxProcess(e):!n}function getDarwinProcessStartTime(e,t,n){let r=performance.now(),i=readDarwinNativeIdentity(e);if(i!==void 0)return i?.startedAt??null;let a=n===void 0?1e3:Math.ceil(n-(performance.now()-r));if(a<=0)return null;try{let n=mn.execFileSync(`/bin/ps`,[`-o`,`lstart=`,`-p`,String(e)],{encoding:`utf8`,env:{...resolveDiagnosticProcessEnv(t),LC_ALL:`C`,TZ:`UTC`},stdio:[`ignore`,`pipe`,`ignore`],timeout:a,killSignal:`SIGKILL`}).trim(),r=Date.parse(`${n} UTC`);return Number.isFinite(r)?Math.floor(r/1e3):null}catch{return null}}function parseLinuxProcessStat(e,t){let n=t.lastIndexOf(`)`);if(n<0||!t.startsWith(`${e} (`))return null;let r=t.slice(n+1).trimStart().split(/\s+/),i=Number(r[19]),a=Number(r[1]);return Number.isSafeInteger(i)&&i>=0&&Number.isSafeInteger(a)&&a>=0?{parentPid:a,startedAt:i}:null}function readLinuxProcessStat(e){if(!isValidPid(e)||!hasLinuxProcfs())return null;try{return parseLinuxProcessStat(e,S.readFileSync(`/proc/${e}/stat`,`utf8`))}catch{return null}}function getProcessStartTime(e){return readLinuxProcessStat(e)?.startedAt??null}function getProcessInstanceStartTime(e){if(!isValidPid(e))return null;if(hasLinuxProcfs()){let t=getProcessStartTime(e);return Number.isSafeInteger(t)?t:null}let t=readDarwinNativeIdentity(e);if(!t)return null;let n=t.startTimeMicros;return Number.isSafeInteger(n)?n:null}function getFileLockProcessStartTime(e,t=process.env,n){if(!isValidPid(e))return null;let r=e===process.pid;if(r&&uo!==null)return uo;let i=process.platform===`darwin`?getDarwinProcessStartTime(e,t,n):process.platform===`win32`?readWindowsProcessStartTimeSync(e,n,t):process.platform===`freebsd`?readFreeBsdProcessStartTime(e):getProcessStartTime(e);return r&&i!==null&&(uo=i),i}function readLockFileOwnerPayload(e){return e?{pid:typeof e.pid==`number`&&Number.isInteger(e.pid)&&e.pid>0?e.pid:void 0,createdAt:typeof e.createdAt==`string`?e.createdAt:void 0,starttime:typeof e.starttime==`number`&&Number.isInteger(e.starttime)&&e.starttime>=0?e.starttime:void 0}:null}function inspectStaleLockOwner(e){let t=readLockFileOwnerPayload(e.payload);if(!t?.pid)return null;if((e.isPidDefinitelyDead??isPidDefinitelyDead)(t.pid))return{reason:`owner-process-exited`,pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:null};let n=t.starttime===void 0?null:(e.getProcessStartTime??getFileLockProcessStartTime)(t.pid),r={pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:n},i=process.platform===`darwin`&&t.starttime!==void 0&&t.starttime>1e10?Math.floor(t.starttime/1e6):t.starttime;return n!==null&&n!==i?{reason:`owner-starttime-changed`,...r}:null}function isLockOwnerDefinitelyStale(e){return inspectStaleLockOwner(e)!==null}const A=string().min(1).max(4096),fo={pid:number().int().positive(),startIdentity:A.max(128)},po=strictObject({...fo,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:`)),mo=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}$/)})]),ho=strictObject({kind:literal(`native`),unit:A,scope:A,placement:discriminatedUnion(`kind`,[strictObject({kind:literal(`pending`)}),strictObject({kind:literal(`attached`),invocation:string().regex(/^[a-f0-9]{32}$/i)})])}),go=literal(`original-cancellation-v1`),_o=strictObject({kind:literal(`update`),mutationProtocol:go}).extend({mutationProtocol:go.optional(),custody:_enum([`reserved`,`bound`]).optional()}),vo=discriminatedUnion(`kind`,[_o,strictObject({kind:literal(`triage`),phase:_enum([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:discriminatedUnion(`kind`,[strictObject({kind:literal(`foreground`),boot:mo}),ho])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]),yo=A.refine(x.isAbsolute,`Native source path must be absolute`),bo=string().regex(/^[a-f0-9]{64}$/),xo=strictObject({runId:A,transactionId:A,claimId:A,revision:number().int().nonnegative(),recordSha256:bo,serviceKey:yo,configPaths:array(yo).min(1).max(512),lifetimeId:A}),So=strictObject({id:string().uuid(),phase:_enum([`reserved`,`admitted`]),source:xo}),Co={executor:po,helper:po,action:vo},wo=strictObject({version:literal(2),executor:po,helper:po,action:_o}),To=strictObject({key:A,owner:A,payload:string().min(1),updatedAt:number().int().nonnegative()});discriminatedUnion(`version`,[strictObject({version:literal(4),executor:po,helper:po,action:_o,cancellation:To}).refine(e=>{let t=safeParseJsonWithSchema(wo,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),...Co,mutationOriginal:To.optional()}).refine(e=>{if(!e.mutationOriginal)return!0;let t=safeParseJsonWithSchema(wo,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`}),strictObject({version:literal(3),...Co,action:strictObject({kind:literal(`update`)}),nativeBorrower:So})]),strictObject({version:literal(1),...fo});const Eo=[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`];function createManagedHandoffBootIdentityReader(e){return function(){let t,n=process.platform===`android`?`linux`:process.platform;if(n===`linux`)t=S.readFileSync(`/proc/sys/kernel/random/boot_id`,`utf8`).trim();else if([`freebsd`,`darwin`,`win32`].includes(process.platform)){let n=process.platform===`freebsd`,r=process.platform===`win32`,i=hn(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?Eo: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=mo.safeParse(r);if(!i.success)throw Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}}const[Do,Oo,ko]=mo.options,Ao=string().min(1),jo=string().regex(/^[a-f0-9]{64}$/u),Mo=discriminatedUnion(`platform`,[Do.extend({host:Ao,platform:literal(`linux`),pidNsInode:string().min(1)}),Do.extend({host:Ao,platform:literal(`darwin`)}),Oo.extend({host:Ao,identity:Oo.shape.identity.optional()}),ko.extend({host:Ao})]);let No;function readGatewayLockProcessNamespace(){if(No?.platform===process.platform&&(No.value!==null||process.platform!==`linux`&&process.platform!==`android`))return No.value;try{let e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)(),t=Mo.parse({host:dn.hostname(),...e,...e.platform===`linux`?{pidNsInode:S.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});return No={platform:process.platform,value:t},t}catch{return No={platform:process.platform,value:null},null}}function isLegacyGatewayLeaseLock(e){return process.platform===`linux`&&e.processNamespace===void 0&&e.role===`gateway`&&typeof e.ownerId==`string`&&e.ownerId.length>0&&typeof e.createdAt==`string`}function readLockHeartbeat(e){try{return S.statSync(e).mtimeMs}catch{return}}function isForeignLinuxNamespace(e,t){return e?.platform===`linux`&&t?.platform===`linux`&&(e.host!==t.host||e.pidNsInode!==t.pidNsInode)}function describeGatewayLockHolder(e,t,n){let r=Mo.safeParse(e.processNamespace).data,i=(t?readLockHeartbeat(t):void 0)??e.heartbeatAt,a=i===void 0?void 0:Date.now()-i,s=`${r?.host??e.host??`unknown host`}${r?.platform===`linux`?`/pid-ns ${r.pidNsInode}`:``}`,c=n===`live`?`The holder ${e.pid} is alive on this host, stop it first`:n===`unknown`?`Stop the holder before retrying`:`Run this command inside the Gateway container or with a shared PID namespace`;return`holder ${e.pid??`unknown`} at ${s}, last renewed ${a===void 0?`at an unknown time`:`${Math.max(0,Math.floor(a/1e3))} s ago`}. ${c}.`}var GatewayLockNamespaceError=class extends Error{constructor(e,t){let n=process.platform===`linux`&&e.processNamespace===void 0;super(`cannot verify Gateway ownership from this process${t?` at ${t}`:``}. ${n?`Legacy holder ${e.pid??`unknown`} has no PID namespace evidence. It may already have stopped. Independently verify that no Gateway using this state is running on this host or in any sharing container. With a current OpenClaw CLI using the same state and profile, run \`openclaw gateway recover-lock --json\`, then \`openclaw gateway recover-lock --confirm <confirmation> --json\` with the returned confirmation. Retry Doctor afterward.`:describeGatewayLockHolder(e,t)}`),this.name=`GatewayLockNamespaceError`,this.legacyLock=n,this.legacyLease=isLegacyGatewayLeaseLock(e)||n&&typeof e.expiresAt==`number`;let r=Mo.safeParse(e.processNamespace).data;if(isForeignLinuxNamespace(r,readGatewayLockProcessNamespace())){let n=t?readLockHeartbeat(t):e.heartbeatAt;n!==void 0&&(this.heartbeatAgeMs=Math.max(0,Date.now()-n))}}};function classifyGatewayOwnerProcessNamespace(e,t={}){let n=Mo.safeParse(e).data;if(!n||t.ownerHost!==void 0&&t.ownerHost!==n.host)return`unknown`;let r=readGatewayLockProcessNamespace();if(!r||n.platform!==r.platform)return`unknown`;if(t.readGatewayHeartbeat&&isForeignLinuxNamespace(n,r)){if(n.host===r.host&&/^[a-f0-9]{12}$/u.test(r.host)&&isContainerEnvironment())return`dead`;let e=t.readGatewayHeartbeat();if(e!==void 0&&Date.now()-e>9e4)return`dead`}if(n.platform===`darwin`&&t.machineIdentity!==void 0){let e=jo.safeParse(t.machineIdentity).data,i=le();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 Po=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:Mo.nullable().optional(),machineIdentity:jo.nullable().optional()});function parseGatewayLockPayload(e){return safeParseJsonWithSchema(Po,e)}const{kyselyByDatabase:Fo,queryErrorHandlerByDatabase:Io}=y(Symbol.for(`openclaw.sqliteKyselyCacheState`),()=>({kyselyByDatabase:/* @__PURE__ */ new WeakMap,queryErrorHandlerByDatabase:/* @__PURE__ */ new WeakMap})),Lo=Symbol.for(`openclaw.kyselySyncStatementCache`),Ro=Symbol.for(`openclaw.kyselySyncStatementInvalidation`),zo=Symbol.for(`openclaw.kyselySyncStatementCacheEnabled`),Bo=Symbol.for(`openclaw.kyselySyncAuthorizerActive`),Vo=Symbol.for(`openclaw.sqliteDisposeCallbacks`),Ho=Symbol.for(`openclaw.sqliteDisposeGuards`),Uo=65536;function disposeSqliteStatement(e){e[Symbol.dispose]?.()}function clearStatementCache(e){let t=e[Lo];if(delete e[Lo],t)for(let e of t.statements.values())t.active.has(e)||disposeSqliteStatement(e)}function registerNodeSqliteDisposeCallback(e,t){let n=e;return installStatementInvalidation(n),pe(n[Vo]??=/* @__PURE__ */ new Set,t)}function assertNodeSqliteDisposalAllowed(e){for(let t of e[Ho]??[])t()}function disposeNodeSqliteDependents(e,t=`close`){assertNodeSqliteDisposalAllowed(e);for(let n of e[Vo]??[])n(t)}function registerNodeSqliteKyselyQueryErrorHandler(e,t){Io.set(e,t)}function clearNodeSqliteKyselyCacheForDatabase(e){clearStatementCache(e),Fo.delete(e),Io.delete(e)}function installStatementInvalidation(e){if(!e[Ro]){if(typeof e.setAuthorizer==`function`){let t=e.setAuthorizer.bind(e);Object.defineProperty(e,"setAuthorizer",{configurable:!0,writable:!0,value(e){t(e),this[Bo]=e!==null,clearStatementCache(this)}})}if(typeof e.deserialize==`function`){let t=e.deserialize.bind(e);Object.defineProperty(e,"deserialize",{configurable:!0,writable:!0,value(...e){disposeNodeSqliteDependents(this,`replace`);try{t(...e)}finally{clearStatementCache(this)}}})}for(let t of[`close`,Symbol.dispose])if(typeof e[t]==`function`){let n=e[t].bind(e);Object.defineProperty(e,t,{configurable:!0,writable:!0,value(){return disposeNodeSqliteDependents(this),clearNodeSqliteKyselyCacheForDatabase(this),n()}})}Object.defineProperty(e,Ro,{configurable:!0,value:!0})}}function queryFitsStatementCache(e,t){let n=Buffer.byteLength(e);if(n>Uo)return!1;for(let e of t){if(typeof e==`string`){if(e.length>Uo-n)return!1;n+=Buffer.byteLength(e)}else ArrayBuffer.isView(e)&&(n+=e.byteLength);if(n>Uo)return!1}return!0}function executeWithCachedStatement(e,t,n,r,i){if(b(e))return r(e.prepare(t));let a=e,executeLeased=(e,t)=>{if(i){try{i(t)}catch(e){throw t(),e}return r(e)}try{return r(e)}finally{t()}};if(!a[zo]||a[Bo]||!queryFitsStatementCache(t,n)){let n=e.prepare(t);return executeLeased(n,()=>disposeSqliteStatement(n))}let s=a[Lo];s||(s={statements:/* @__PURE__ */ new Map,candidates:/* @__PURE__ */ new Set,active:/* @__PURE__ */ new WeakSet},Object.defineProperty(a,Lo,{configurable:!0,value:s}));let c=s.statements.get(t),l;if(c&&!s.active.has(c))s.statements.delete(t),s.statements.set(t,c),l=c;else if(l=e.prepare(t),!c&&s.candidates.delete(t)){if(s.statements.set(t,l),s.statements.size>64){let e=s.statements.entries().next().value;s.statements.delete(e[0]),s.active.has(e[1])||disposeSqliteStatement(e[1])}}else if(!c&&(s.candidates.add(t),s.candidates.size>64)){let e=s.candidates.values().next().value;e!==void 0&&s.candidates.delete(e)}return s.active.add(l),executeLeased(l,()=>{s.active.delete(l),(a[Lo]!==s||s.statements.get(t)!==l)&&disposeSqliteStatement(l)})}const Wo=/* @__PURE__ */ new WeakMap,{busyTimeoutByDatabase:Go,trackedDatabases:Ko}=y(Symbol.for(`openclaw.sqliteBusyTimeout`),()=>({busyTimeoutByDatabase:/* @__PURE__ */ new WeakMap,trackedDatabases:/* @__PURE__ */ new WeakSet}));function rememberSqliteBusyTimeout(e,t){Ko.has(e)||(Ko.add(e),registerNodeSqliteDisposeCallback(e,()=>Go.delete(e))),Go.set(e,t)}function normalizeSqliteNonNegativeInteger(e,t){if(!Number.isInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return e}function readSqliteBusyTimeout(e){let t=Go.get(e);if(t!==void 0)return t;let n=e.prepare(`PRAGMA busy_timeout`).get(),r=n?.busy_timeout??n?.timeout,i=Number(typeof r==`bigint`?r:r??0);return rememberSqliteBusyTimeout(e,i),i}function setSqliteBusyTimeout(e,t){let n=normalizeSqliteNonNegativeInteger(t,`busyTimeoutMs`);Go.get(e)!==n&&(e.exec(`PRAGMA busy_timeout = ${n}`),rememberSqliteBusyTimeout(e,n))}function shouldReportSqliteLockFailure(e){return Wo.get(e)!==`suppress`}function runWithSqliteBusyTimeout(e,t,n,r={}){let i=normalizeSqliteNonNegativeInteger(t,`busyTimeoutMs`),a=readSqliteBusyTimeout(e),s=Wo.get(e);r.lockFailureReporting&&Wo.set(e,r.lockFailureReporting),setSqliteBusyTimeout(e,i);let c=!1,restore=()=>{c||=(e.isOpen&&a!==i&&setSqliteBusyTimeout(e,a),s?Wo.set(e,s):Wo.delete(e),!0)};try{return n(restore)}finally{restore()}}function sha256Hex(e){return rn(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}const qo=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);function hasRestrictivePermissions(e){try{return!(sn(e).mode&63)}catch{return!1}}function filesystemRejectsChmod(e){let t;try{let n=sn(e).isDirectory()?e:x.dirname(e);t=x.join(n,`.openclaw-chmod-probe-${an()}`),ln(t,``,{flag:`wx`,mode:384})}catch{return!1}try{return on(t,384),!1}catch(e){return r(e)&&e.code===`EPERM`}finally{try{cn(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){return t&&qo.has(t)?!0:t!==`EROFS`&&t!==`EPERM`?!1:n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if((sn(e).mode&4095)===t)return{applied:!0};try{return on(e,t),{applied:!0}}catch(t){if(!canIgnorePrivateChmodError(e,r(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:!1,error:t}}}const Jo=`Run OpenClaw as the user that owns its state directory, and keep that directory on a local filesystem that supports file ownership and permissions`;function ensureOwnerDirectory(e,t){let n=S.mkdirSync(e,{recursive:!0,mode:448});if(n&&t){let r=x.toNamespacedPath(n),i=[];for(let t=e;;){let{dev:e,ino:n}=S.lstatSync(t,{bigint:!0});if(i.push({path:t,dev:e,ino:n}),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=S.lstatSync(e),i=process.getuid?.();if(!r.isDirectory())throw Error(`State ownership directory must be a user-owned real directory`);if(i!==void 0&&r.uid!==i)throw Error(`State ownership directory ${e} is owned by uid ${r.uid}, not this user (uid ${i}). ${Jo}`);if(process.platform!==`win32`&&(r.mode&4095)!=448&&(applyPrivateModeSync(e,448),S.lstatSync(e).mode&63))throw Error(`State ownership directory ${e} permissions could not be set to 0700. ${Jo}`)}function removeCreatedProjectionDirectories(e){let t=e[0];for(;t;){try{let e=S.lstatSync(t.path,{bigint:!0});e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino&&S.rmdirSync(t.path)}catch(e){let t=g(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift(),t=e[0]}}function resolveStateOwnerIdentity(e){let t=Bt(e);return stateOwnerIdentity(t,Bt(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){let t=await zt(e);return stateOwnerIdentity(t,await zt(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:x.join(t,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?ae(e):e}}function stateOwnerDirectory(e){let t=process.getuid?.();return process.platform===`win32`?x.join(dn.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):n(resolveOpenClawStateDirForDatabasePath(e))}async function settlesWithin(e,t){return await Wt(e.then(()=>!0),t,()=>!1,{ref:!1})}function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}const Yo=Date.now.bind(Date);function captureLock(e){let t=S.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,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 i=S.statSync(r,{bigint:!0}),{moduleUrl:a,runtimeGeneration:s}=ut(kt(`gatewayStateOwnerHeartbeat`));return c(()=>{let c=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(c,0,BigInt(Yo()));let{port1:l,port2:u}=new Xt,d=et(a,{workerData:{clock:`epoch`,locks:n,intervalMs:15e3,failureMs:6e4,lastBeat:c.buffer,events:u},transferList:[u],execArgv:Jt(a)}),f=Lt();d.on(`message`,e=>{e===`closed`&&f.resolve()}),d.unref();let m=0,h=/* @__PURE__ */ new Map,rejectPending=e=>{for(let t of h.values())t.reject(e);h.clear(),l.unref()};l.on(`message`,e=>{if(ot(`lifecycle`,`from_worker`),e===`parent-lost`)Vt();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&&l.unref(),e.error?t?.reject(Error(e.error)):t?.resolve(e.current)}}),l.unref(),d.on(`error`,e=>{let n=/* @__PURE__ */ Error(`${ee(e)}; restart Gateway.`);rejectPending(n),t(n)}),d.once(`exit`,()=>{f.resolve(),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership verification worker stopped`))});let g,remainingUntilInspection=()=>{let e=Atomics.load(c,0),t=Yo()-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=Yo(),a=new Date(t);for(let t of e)try{let s=n[t.lockPath];if(s===void 0)throw Error(`owner acquisition bytes were not registered`);let c=await S.promises.open(t.lockPath,`r+`);try{let n=await c.stat({bigint:!0}),l=await S.promises.lstat(t.lockPath,{bigint:!0}),u=Buffer.alloc(Buffer.byteLength(s)+1),{bytesRead:d}=await c.read(u,0,u.length,0),f=await S.promises.lstat(t.lockPath,{bigint:!0});if(g||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(n,l,s,u.subarray(0,d).toString(`utf8`))||!f.isFile()||f.dev!==n.dev||f.ino!==n.ino||t.lockPath===r&&(n.dev!==i.dev||n.ino!==i.ino)){if(t.lockPath!==r)continue;throw Error(`owner lock was removed or replaced`)}await c.utimes(a,a)}finally{await c.close()}}catch(e){if(t.lockPath!==r&&p(e,`ENOENT`))continue;throw e}!g&&e.size>0&&Atomics.store(c,0,BigInt(t))},v,ne,watch=()=>{let e=remainingUntilInspection();e>0?(v=setTimeout(watch,e),v.unref()):ne??=renewAsync().then(()=>{ne=void 0,g||watch()},e=>{ne=void 0,g||t(/* @__PURE__ */ Error(`Gateway state ownership is no longer current at ${r}: ${ee(e)}; restart the Gateway.`))})};watch();let stop=()=>(g||=(clearTimeout(v),rejectPending(/* @__PURE__ */ Error(`Gateway state ownership is no longer current`)),l.close(),d.ref(),d.postMessage(`stop`,[]),(async()=>(await settlesWithin(f.promise,1e3)||process.emitWarning(`Gateway state-owner heartbeat did not close within ${Ut}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`}),d.terminate()))()),Promise.all([g,ne]).then(()=>void 0));s?.retain(d,async()=>async()=>{await stop()});let assertActive=()=>{if(g||d.threadId===-1)throw Error(`Gateway state ownership verification worker stopped`)},re=new Set(Object.keys(n));return{worker:d,paths:re,register(e){let t=captureLock(e);n[e.lockPath]=t,d.postMessage([e.lockPath,t],[]),re.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();let t=++m;return new Promise((n,r)=>{h.set(t,{resolve:n,reject:r}),l.ref();try{d.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){h.delete(t),h.size===0&&l.unref(),r(te(e,`Gateway state ownership verification failed`))}})},stop}})}function safeParseJson(e){try{return JSON.parse(e)}catch{return}}function safeParseJsonRecord(e){return/^[\t\n\r ]*\{/.test(e)?i(safeParseJson(e)):void 0}function _usingCtx(){var e=typeof SuppressedError==`function`?SuppressedError:function(e,t){var n=Error();return n.name=`SuppressedError`,n.error=e,n.suppressed=t,n},t={},n=[];function using(e,t){if(t!=null){if(Object(t)!==t)throw TypeError(`using declarations can only be used with objects, functions, null, or undefined.`);if(e)var o=t[Symbol.asyncDispose||Symbol.for(`Symbol.asyncDispose`)];if(o===void 0&&(o=t[Symbol.dispose||Symbol.for(`Symbol.dispose`)],e))var r=o;if(typeof o!=`function`)throw TypeError(`Object is not disposable.`);r&&(o=function(){try{r.call(t)}catch(e){return Promise.reject(e)}}),n.push({v:t,d:o,a:e})}else e&&n.push({d:t,a:e});return t}return{e:t,u:using.bind(null,!1),a:using.bind(null,!0),d:function(){var r,i=this.e,a=0;function next(){for(;r=n.pop();)try{if(!r.a&&a===1)return a=0,n.push(r),Promise.resolve().then(next);if(r.d){var e=r.d.call(r.v);if(r.a)return a|=2,Promise.resolve(e).then(next,err)}else a|=1}catch(e){return err(e)}if(a===1)return i===t?Promise.resolve():Promise.reject(i);if(i!==t)throw i}function err(n){return i=i===t?n:new e(n,i),next()}return next()}}}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 Xo=re(`gateway/state`);function loseOwner(e,t){e.lost.signal.aborted||(e.accepting=!1,Zo.clear(),e.heartbeat?.stop(),Xo.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 Zo=y(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map),j=y(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map),Qo=/* @__PURE__ */ new Set([`--dev`,`--no-color`]),$o=/* @__PURE__ */ new Set([`--profile`,`--log-level`,`--container`]);function isValueToken(e){return!e||e===`--`?!1:!e.startsWith(`-`)||/^-\d+(?:\.\d+)?$/.test(e)}function consumeRootOptionToken(e,t){let n=e[t];return n?Qo.has(n)||n.startsWith(`--profile=`)||n.startsWith(`--log-level=`)||n.startsWith(`--container=`)?1:$o.has(n)?isValueToken(e[t+1])?2:1:0:0}function consumeRootCommandOptionToken(e,t){return consumeKnownOptionToken(e,t,Qo,$o,`command-path`)}function getRootOptionAwareCommandPath(e,t){let n=e.slice(2),r=[],i=!1;for(let e=0;e<n.length;e+=1){let a=n[e];if(!a)break;if(!i&&a===`--`){if(r.length>0)break;i=!0;continue}let s=i?0:consumeRootCommandOptionToken(n,e);if(s>0)e+=s-1;else if((i||!a.startsWith(`-`))&&(r.push(a),r.length>=t))break}return r}function rewriteUpdateFlagArgv(e){let t=e.indexOf(`--update`);if(t===-1)return e;for(let n=2;n<e.length;n++){let r=e[n];if(!r||r===`--`)return e;if(n===t)return[...e.slice(0,t),`update`,...e.slice(t+1)];let i=consumeRootOptionToken(e,n);if(i>0)n+=i-1;else if(!r.startsWith(`-`))return e}return e}function isUpdateCommandArgv(e){return getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(e),1)[0]===`update`}function consumeKnownOptionToken(e,t,n,r,i){let a=e[t];if(!a||a===`--`||!a.startsWith(`-`))return 0;let s=a.indexOf(`=`),c=s===-1?a:a.slice(0,s);return n.has(c)?+(s===-1):r.has(c)?s===-1?i===`command-path`?e[t+1]===void 0?0:2:isValueToken(e[t+1])?2:0:i===`command-path`||a.slice(s+1).trim()?1:0:0}function getCommandPositionalsWithRootOptions(e,t){return parseCommandArgsWithRootOptions(e,t,!1)}function parseCommandArgsWithRootOptions(e,t,n,r=!1){let i=e.slice(2),a=new Set(t.booleanFlags??[]),s=new Set(t.valueFlags??[]),c=[],l=[],u=[],d=0,f=!1;for(let e=0;e<i.length;e+=1){let p=i[e];if(p===void 0)break;if(!f&&p===`--`){if(t.mode!==`command-path`)break;f=!0;continue}let m=f?0:t.mode===`command-path`?consumeRootCommandOptionToken(i,e):consumeRootOptionToken(i,e);if(m>0)(d>0&&a.has(p)?u:l).push(...i.slice(e,e+m)),e+=m-1;else if(!f&&p.startsWith(`-`)){let n=consumeKnownOptionToken(i,e,a,s,t.mode);if(n===0||d===0)return null;u.push(p),e+=n-1}else if(d<t.commandPath.length){if(p!==t.commandPath[d])return null;if(d+=1,n&&d===t.commandPath.length){let t=i.slice(e+1);return f?[`--`,...t]:t}}else if(c.push(p),!r&&c.length===t.maxPositionals)return c}return d<t.commandPath.length?null:r?{rootOptions:l,commandOptions:u}:c}const es=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]),ts=/* @__PURE__ */ new Set([`--tailscale-reset-on-exit`,`--allow-unconfigured`,`--dev`,`--ambient-channels`,`--dev-ambient-channels`,`--reset`,`--update-canary`,`--force`,`--verbose`,`--cli-backend-logs`,`--claude-cli-logs`,`--compact`,`--raw-stream`]);function isForegroundGatewayRunArgv(e){let t=getCommandPositionalsWithRootOptions(e,{commandPath:[`gateway`],booleanFlags:[...ts,`--task-supervisor`],valueFlags:[...es,`--task-supervisor-child`],mode:`command-path`});return t?t.length===0||t.length===1&&t[0]===`run`:!1}function isUndefined(e){return e===void 0||e===void 0}function isString(e){return typeof e==`string`}function isNumber(e){return typeof e==`number`}function isBoolean(e){return typeof e==`boolean`}function isNull(e){return e===null}function isDate(e){return e instanceof Date}function isBigInt(e){return typeof e==`bigint`}function isFunction(e){return typeof e==`function`}function isObject(e){return typeof e==`object`&&!!e}function freeze(e){return Object.freeze(e)}function asArray(e){return isReadonlyArray(e)?e:[e]}function isReadonlyArray(e){return Array.isArray(e)}function noop(e){return e}function getMessage(e){return e instanceof Error?e.message:String(e)}const 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})}}),ns=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]})}}),rs=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})}}),is=[`preserve rows`,`delete rows`,`drop`],P=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})}}),as=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)})}}),os=freeze({is(e){return e.kind===`DropIndexNode`},create(e,t){return freeze({kind:`DropIndexNode`,name:as.create(e),...t})},cloneWith(e,t){return freeze({...e,...t})}}),ss=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})}}),cs=freeze({is(e){return e.kind===`DropTableNode`},create(e,t){return freeze({kind:`DropTableNode`,table:e,...t})},cloneWith(e,t){return freeze({...e,...t})}}),ls=freeze({is(e){return e.kind===`AliasNode`},create(e,t){return freeze({kind:`AliasNode`,node:e,alias:t})}}),F=freeze({is(e){return e.kind===`TableNode`},create(e){return freeze({kind:`TableNode`,table:as.create(e)})},createWithSchema(e,t){return freeze({kind:`TableNode`,table:as.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 us=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})}}),ds=freeze({is(e){return e.kind===`AndNode`},create(e,t){return freeze({kind:`AndNode`,left:e,right:t})}}),fs=freeze({is(e){return e.kind===`OrNode`},create(e,t){return freeze({kind:`OrNode`,left:e,right:t})}}),ps=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`?ds.create(e.on,n):fs.create(e.on,n)})}}),ms=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:ps.create(n)})},cloneWithOn(e,t){return freeze({...e,on:e.on?ps.cloneWithOperation(e.on,`And`,t):ps.create(t)})}}),hs=freeze({is(e){return e.kind===`BinaryOperationNode`},create(e,t,n){return freeze({kind:`BinaryOperationNode`,leftOperand:e,operator:t,rightOperand:n})}}),gs=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(gs);const _s=freeze({"+":!0,"-":!0,"*":!0,"/":!0,"%":!0,"^":!0,"&":!0,"|":!0,"#":!0,"<<":!0,">>":!0});Object.keys(_s);const vs=freeze({"->":!0,"->>":!0}),ys=Object.keys(vs),bs=freeze({...gs,..._s,"||":!0}),xs=Object.keys(bs),Ss=freeze({exists:!0,"not exists":!0});Object.keys(Ss);const Cs=freeze({...Ss,"-":!0,not:!0}),ws=Object.keys(Cs);[...xs,...ys,...ws];const Ts=freeze({is(e){return e.kind===`OperatorNode`},create(e){return freeze({kind:`OperatorNode`,operator:e})}});function isBinaryOperator(e){return isString(e)&&bs[e]}function isJSONOperator(e){return isString(e)&&vs[e]}function isUnaryOperator(e){return isString(e)&&Cs[e]}const I=freeze({is(e){return e.kind===`ColumnNode`},create(e){return freeze({kind:`ColumnNode`,column:N.create(e)})}}),Es=freeze({is(e){return e.kind===`SelectAllNode`},create(){return freeze({kind:`SelectAllNode`})}}),Ds=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:Es.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 Os=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})}}),L=freeze({is(e){return e.kind===`RawNode`},create(e,t){return freeze({kind:`RawNode`,sqlFragments:freeze(e),parameters:freeze(t)})},createWithSql(e){return L.create([e],[])},createWithChild(e){return L.create([``,``],[e])},createWithChildren(e){return L.create(Array(e.length+1).fill(``),e)}}),ks=freeze({is(e){return e.kind===`CollateNode`},create(e){return freeze({kind:`CollateNode`,collation:N.create(e)})}});var As=class OrderByItemBuilder{#e;constructor(e){this.#e=freeze(e)}desc(){return new OrderByItemBuilder({node:Os.cloneWith(this.#e.node,{direction:L.createWithSql(`desc`)})})}asc(){return new OrderByItemBuilder({node:Os.cloneWith(this.#e.node,{direction:L.createWithSql(`asc`)})})}nullsLast(){return new OrderByItemBuilder({node:Os.cloneWith(this.#e.node,{nulls:`last`})})}nullsFirst(){return new OrderByItemBuilder({node:Os.cloneWith(this.#e.node,{nulls:`first`})})}collate(e){return new OrderByItemBuilder({node:Os.cloneWith(this.#e.node,{collation:ks.create(e)})})}toOperationNode(){return this.#e.node}};const js=/* @__PURE__ */ new Set;function logOnce(e){js.has(e)||(js.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(Os.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 Os.create(e,L.createWithSql(t))}if(isExpression(t))return logOnce("`orderBy(..., expr)` is deprecated. Use `orderBy(..., 'asc')` or `orderBy(..., (ob) => ...)` instead."),Os.create(e,t.toOperationNode());let n=Os.create(e);return t?t(new As({node:n})).toOperationNode():n}const Ms=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})}}),Ns=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])})}}),Ps=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 Ms.create(parseStringReference(e),Ns.create(Ts.create(t)));if(t===`->$`||t===`->>$`)return Ms.create(parseStringReference(e),Ps.create(Ts.create(t.slice(0,-1))));throw Error(`Invalid JSON operator: ${t}`)}function parseStringReference(e){if(!e.includes(`.`))return Ds.create(I.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 ls.create(parseStringReference(n),N.create(r))}return parseStringReference(e)}function parseColumnName(e){return I.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 Ds.create(I.create(r),F.createWithSchema(t,n))}function parseStringReferenceWithTable(e){let[t,n]=e;return Ds.create(I.create(n),F.create(t))}function trim$2(e){return e.trim()}const Fs=freeze({is(e){return e.kind===`PrimitiveValueListNode`},create(e){return freeze({kind:`PrimitiveValueListNode`,values:freeze([...e])})}}),Is=freeze({is(e){return e.kind===`ValueListNode`},create(e){return freeze({kind:`ValueListNode`,values:freeze(e)})}}),R=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):R.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 R.createImmediate(e)}function parseValueExpressionList(e){return e.some(isExpressionOrFactory)?Is.create(e.map(e=>parseValueExpression(e))):Fs.create(e)}const Ls=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)?hs.create(parseReferenceExpression(e),parseBinaryOperator(t),R.createImmediate(n)):hs.create(parseReferenceExpression(e),parseBinaryOperator(t),parseValueExpressionOrList(n))}function parseReferentialBinaryOperation(e,t,n){return hs.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`?ds.create:fs.create;if(e.length===0)return hs.create(R.createImmediate(1),Ts.create(`=`),R.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?Ls.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 Ts.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 Rs=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])})}}),zs=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])})}}),Bs=freeze({is(e){return e.kind===`OverNode`},create(){return freeze({kind:`OverNode`})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Rs.cloneWithItems(e.orderBy,t):Rs.create(t)})},cloneWithPartitionByItems(e,t){return freeze({...e,partitionBy:e.partitionBy?zs.cloneWithItems(e.partitionBy,t):zs.create(t)})}}),Vs=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])})}}),Hs=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])})}}),Us=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`?ds.create(e.having,n):fs.create(e.having,n)})}}),z=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})}}),Ws=freeze({is(e){return e.kind===`ListNode`},create(e){return freeze({kind:`ListNode`,items:freeze(e)})}}),Gs=freeze({is(e){return e.kind===`UpdateQueryNode`},create(e,t){return freeze({kind:`UpdateQueryNode`,table:e.length===1?e[0]:Ws.create(e),...t&&{with:t}})},createWithoutTable(){return freeze({kind:`UpdateQueryNode`})},cloneWithFromItems(e,t){return freeze({...e,from:e.from?Vs.cloneWithFroms(e.from,t):Vs.create(t)})},cloneWithUpdates(e,t){return freeze({...e,updates:e.updates?freeze([...e.updates,...t]):t})},cloneWithLimit(e,t){return freeze({...e,limit:t})}}),Ks=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])})}}),qs=freeze({is(e){return e.kind===`DeleteQueryNode`},create(e,t){return freeze({kind:`DeleteQueryNode`,from:Vs.create(e),...t&&{with:t}})},cloneWithOrderByItems:(e,t)=>H.cloneWithOrderByItems(e,t),cloneWithoutOrderBy:e=>H.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?Ks.create(t):Ks.cloneWithTables(e.using,t)})}}),B=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`?ds.create(e.where,n):fs.create(e.where,n)})}}),Js=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)})}}),Ys=freeze({is(e){return e.kind===`ExplainNode`},create(e,t){return freeze({kind:`ExplainNode`,format:e,options:t})}}),Xs=freeze({is(e){return e.kind===`WhenNode`},create(e){return freeze({kind:`WhenNode`,condition:e})},cloneWithResult(e,t){return freeze({...e,result:t})}}),V=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),Xs.cloneWithResult(e.whens[e.whens.length-1],t)]):void 0})}}),Zs=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)})}}),H=freeze({is(e){return U.is(e)||z.is(e)||Gs.is(e)||qs.is(e)||V.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?B.cloneWithOperation(e.where,`And`,t):B.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?Js.cloneWithSelections(e.returning,t):Js.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:Ys.create(t,n?.toOperationNode())})},cloneWithTop(e,t){return freeze({...e,top:t})},cloneWithOutput(e,t){return freeze({...e,output:e.output?Zs.cloneWithSelections(e.output,t):Zs.create(t)})},cloneWithOrderByItems(e,t){return freeze({...e,orderBy:e.orderBy?Rs.cloneWithItems(e.orderBy,t):Rs.create(t)})},cloneWithoutOrderBy(e){return freeze({...e,orderBy:void 0})}}),U=freeze({is(e){return e.kind===`SelectQueryNode`},create(e){return freeze({kind:`SelectQueryNode`,...e&&{with:e}})},createFrom(e,t){return freeze({kind:`SelectQueryNode`,from:Vs.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)=>H.cloneWithOrderByItems(e,t),cloneWithGroupByItems(e,t){return freeze({...e,groupBy:e.groupBy?Hs.cloneWithItems(e.groupBy,t):Hs.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?Us.cloneWithOperation(e.having,`And`,t):Us.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=>H.cloneWithoutOrderBy(e),cloneWithoutGroupBy(e){return freeze({...e,groupBy:void 0})}});var Qs=class JoinBuilder{#e;constructor(e){this.#e=freeze(e)}on(...e){return new JoinBuilder({...this.#e,joinNode:ms.cloneWithOn(this.#e.joinNode,parseValueBinaryOperationOrExpression(e))})}onRef(e,t,n){return new JoinBuilder({...this.#e,joinNode:ms.cloneWithOn(this.#e.joinNode,parseReferentialBinaryOperation(e,t,n))})}onTrue(){return new JoinBuilder({...this.#e,joinNode:ms.cloneWithOn(this.#e.joinNode,L.createWithSql(`true`))})}$call(e){return e(this)}toOperationNode(){return this.#e.joinNode}};const $s=freeze({is(e){return e.kind===`PartitionByItemNode`},create(e){return freeze({kind:`PartitionByItemNode`,partitionBy:e})}});function parsePartitionBy(e){return parseReferenceExpressionOrList(e).map($s.create)}var ec=class OverBuilder{#e;constructor(e){this.#e=freeze(e)}orderBy(...e){return new OverBuilder({overNode:Bs.cloneWithOrderByItems(this.#e.overNode,parseOrderBy(e))})}clearOrderBy(){return new OverBuilder({overNode:H.cloneWithoutOrderBy(this.#e.overNode)})}partitionBy(e){return new OverBuilder({overNode:Bs.cloneWithPartitionByItems(this.#e.overNode,parsePartitionBy(e))})}$call(e){return e(this)}toOperationNode(){return this.#e.overNode}};const tc=freeze({is(e){return e.kind===`SelectionNode`},create(e){return freeze({kind:`SelectionNode`,selection:e})},createSelectAll(){return freeze({kind:`SelectionNode`,selection:Es.create()})},createSelectAllFromTable(e){return freeze({kind:`SelectionNode`,selection:Ds.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)?tc.create(parseAliasedStringReference(e)):isDynamicReferenceBuilder(e)?tc.create(e.toOperationNode()):tc.create(parseAliasedExpression(e))}function parseSelectAll(e){return e?Array.isArray(e)?e.map(parseSelectAllArg):[parseSelectAllArg(e)]:[tc.createSelectAll()]}function parseSelectAllArg(e){if(isString(e))return tc.createSelectAllFromTable(parseTable(e));throw Error(`invalid value selectAll expression: ${JSON.stringify(e)}`)}const nc=freeze({is(e){return e.kind===`ValuesNode`},create(e){return freeze({kind:`ValuesNode`,values:freeze(e)})}}),rc=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(I.create)),nc.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 s of n){let n=t.get(s);if(isUndefined(n)){a--;continue}let c=e[s];(isUndefined(c)||isExpressionOrFactory(c))&&(i=!0),r[n]=c}if(a<t.size||i){let e=rc.create();return Is.create(r.map(t=>isUndefined(t)?e:parseValueExpression(t)))}return Fs.create(r)}const ic=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?[ic.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])=>ic.create(I.create(e),parseValueExpression(t)))}const ac=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 W=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?B.cloneWithOperation(e.indexWhere,`And`,t):B.create(t)})},cloneWithIndexOrWhere(e,t){return freeze({...e,indexWhere:e.indexWhere?B.cloneWithOperation(e.indexWhere,`Or`,t):B.create(t)})},cloneWithUpdateWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?B.cloneWithOperation(e.updateWhere,`And`,t):B.create(t)})},cloneWithUpdateOrWhere(e,t){return freeze({...e,updateWhere:e.updateWhere?B.cloneWithOperation(e.updateWhere,`Or`,t):B.create(t)})},cloneWithoutIndexWhere(e){return freeze({...e,indexWhere:void 0})},cloneWithoutUpdateWhere(e){return freeze({...e,updateWhere:void 0})}});var oc=class OnConflictBuilder{#e;constructor(e){this.#e=freeze(e)}column(e){let t=I.create(e);return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWith(this.#e.onConflictNode,{columns:this.#e.onConflictNode.columns?freeze([...this.#e.onConflictNode.columns,t]):freeze([t])})})}columns(e){let t=e.map(I.create);return new OnConflictBuilder({...this.#e,onConflictNode:W.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:W.cloneWith(this.#e.onConflictNode,{constraint:N.create(e)})})}expression(e){return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWith(this.#e.onConflictNode,{indexExpression:e.toOperationNode()})})}where(...e){return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWithIndexWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWithIndexWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictBuilder({...this.#e,onConflictNode:W.cloneWithoutIndexWhere(this.#e.onConflictNode)})}doNothing(){return new OnConflictDoNothingBuilder({...this.#e,onConflictNode:W.cloneWith(this.#e.onConflictNode,{doNothing:!0})})}doUpdateSet(e){return new sc({...this.#e,onConflictNode:W.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}},sc=class OnConflictUpdateBuilder{#e;constructor(e){this.#e=freeze(e)}where(...e){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:W.cloneWithUpdateWhere(this.#e.onConflictNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:W.cloneWithUpdateWhere(this.#e.onConflictNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new OnConflictUpdateBuilder({...this.#e,onConflictNode:W.cloneWithoutUpdateWhere(this.#e.onConflictNode)})}$call(e){return e(this)}toOperationNode(){return this.#e.onConflictNode}};const cc=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 cc.create(e,t)}function isTopModifiers(e){return e===`percent`||e===`with ties`||e===`percent with ties`}const lc=freeze({is(e){return e.kind===`OrActionNode`},create(e){return freeze({kind:`OrActionNode`,action:e})}});var uc=class InsertQueryBuilder{#e;constructor(e){this.#e=freeze(e)}values(e){let[t,n]=parseInsertExpression(e);return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{columns:t,values:n})})}columns(e){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{columns:freeze(e.map(I.create))})})}expression(e){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{values:parseExpression(e)})})}defaultValues(){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{defaultValues:!0})})}modifyEnd(e){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}ignore(){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{orAction:lc.create(`ignore`)})})}orIgnore(){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{orAction:lc.create(`ignore`)})})}orAbort(){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{orAction:lc.create(`abort`)})})}orFail(){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{orAction:lc.create(`fail`)})})}orReplace(){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{orAction:lc.create(`replace`)})})}orRollback(){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{orAction:lc.create(`rollback`)})})}top(e,t){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}onConflict(e){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{onConflict:e(new oc({onConflictNode:W.create()})).toOperationNode()})})}onDuplicateKeyUpdate(e){return new InsertQueryBuilder({...this.#e,queryNode:z.cloneWith(this.#e.queryNode,{onDuplicateKey:ac.create(parseUpdateObjectExpression(e))})})}returning(e){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll())})}output(e){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new InsertQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new InsertQueryBuilder({...this.#e,queryNode:H.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:H.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}},DeleteResult=class{numDeletedRows;constructor(e){this.numDeletedRows=e}};const dc=freeze({is(e){return e.kind===`LimitNode`},create(e){return freeze({kind:`LimitNode`,limit:e})}});var G,DeleteQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new G({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new G({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new G({...this.#e,queryNode:H.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new G({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(e){return new G({...this.#e,queryNode:qs.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 G({...this.#e,queryNode:H.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}returning(e){return new G({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new G({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new G({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new G({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}clearReturning(){return new G({...this.#e,queryNode:H.cloneWithoutReturning(this.#e.queryNode)})}clearLimit(){return new G({...this.#e,queryNode:qs.cloneWithoutLimit(this.#e.queryNode)})}orderBy(...e){return new G({...this.#e,queryNode:H.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new G({...this.#e,queryNode:H.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new G({...this.#e,queryNode:qs.cloneWithLimit(this.#e.queryNode,dc.create(parseValueExpression(e)))})}modifyEnd(e){return new G({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}$call(e){return e(this)}$if(e,t){return e?t(this):new G({...this.#e})}$castTo(){return new G(this.#e)}$narrowType(){return new G(this.#e)}$assertType(){return new G(this.#e)}withPlugin(e){return new G({...this.#e,executor:this.#e.executor.withPlugin(e)})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.queryNode,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(e){let t=this.compile(),n=await this.#e.executor.executeQuery(t,e),{adapter:r}=this.#e.executor,i=t.query;return i.returning&&r.supportsReturning||i.output&&r.supportsOutput?n.rows:[new 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 G({...this.#e,queryNode:H.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};G=DeleteQueryBuilder;var UpdateResult=class{numUpdatedRows;numChangedRows;constructor(e,t){this.numUpdatedRows=e,this.numChangedRows=t}},K,UpdateQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}where(...e){return new K({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new K({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}clearWhere(){return new K({...this.#e,queryNode:H.cloneWithoutWhere(this.#e.queryNode)})}top(e,t){return new K({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}from(e){return new K({...this.#e,queryNode:Gs.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 K({...this.#e,queryNode:H.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new K({...this.#e,queryNode:H.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}clearOrderBy(){return new K({...this.#e,queryNode:H.cloneWithoutOrderBy(this.#e.queryNode)})}limit(e){return new K({...this.#e,queryNode:Gs.cloneWithLimit(this.#e.queryNode,dc.create(parseValueExpression(e)))})}set(...e){return new K({...this.#e,queryNode:Gs.cloneWithUpdates(this.#e.queryNode,parseUpdate(...e))})}returning(e){return new K({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new K({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new K({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new K({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}modifyEnd(e){return new K({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}clearReturning(){return new K({...this.#e,queryNode:H.cloneWithoutReturning(this.#e.queryNode)})}$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 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 K({...this.#e,queryNode:H.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};K=UpdateQueryBuilder;const fc=freeze({is(e){return e.kind===`CommonTableExpressionNameNode`},create(e,t){return freeze({kind:`CommonTableExpressionNameNode`,table:F.create(e),columns:t?freeze(t.map(I.create)):void 0})}}),pc=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 mc=class CTEBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new CTEBuilder({...this.#e,node:pc.cloneWith(this.#e.node,{materialized:!0})})}notMaterialized(){return new CTEBuilder({...this.#e,node:pc.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():pc.create(parseCommonTableExpressionName(e),n)}function cteBuilderFactory(e){return t=>new mc({node:pc.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 fc.create(n,r)}return fc.create(e)}const hc=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])})}}),gc=/* @__PURE__ */ `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`.split(``);function randomString(e){let t=``;for(let n=0;n<e;++n)t+=randomChar();return t}function randomChar(){return gc[~~(Math.random()*gc.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 _c={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)&&_c[e.kind]===!0}const vc=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:F.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=>F.is(e)&&!e.table.schema?{...e,table:this.transformIdentifier(e.table.identifier,t)}:this.transformNode(e,t))}}#r(e,t,n){return vc[e.func]?e[n].map(e=>!F.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&&as.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&&(ms.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(F.is(e))return this.#s(e.table,t);if(ls.is(e)&&F.is(e.node))return this.#s(e.node.table,t);if(Ws.is(e))for(let n of e.items)this.#o(n,t);else if(Ks.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 yc=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 Xs.create(parseFilterList([yc.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)?L.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 q={};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(q);t.addEventListener(`abort`,abortListener);try{assertNotAborted(t,`before ${n}`,r);let a=await Promise.race([e,i]);if(a!==q)return a;r?.(),throwReasonWithTiming(t.reason,`during ${n}`)}finally{t.removeEventListener(`abort`,abortListener),a(q)}}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 bc=freeze([]);var QueryExecutorBase=class{#e;constructor(e=bc){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),s=this.provideConnection.bind(this),{promise:c,resolve:l}=new Deferred,abortListener=()=>l(q);r.addEventListener(`abort`,abortListener,{once:!0});try{assertNotAborted(r,`before query execution`,a);let l=getInflightQueryAbortHandler(n,i,a);if(l&&i.collectSessionInfo){assertNotAborted(r,`before query execution`,a);let e=i.collectSessionInfo();await Promise.race([c,e]).catch(e=>{throw a(),e})===q&&(e.catch(printBackgroundFail(`collectSessionInfo`)).finally(a),throwReasonWithTiming(r.reason,`before query execution`))}let u=i.executeQuery(e,t),d=await Promise.race([c,u]).catch(e=>{throw a(),e});d===q?(Promise.allSettled([u.catch(printBackgroundFail(`query`)),l?.(s).catch(printBackgroundFail(`inflightQueryAbortHandler`))]).finally(a),throwReasonWithTiming(r.reason,`during query execution`)):a();let f=this.#t(d,e.queryId,t),p=await Promise.race([c,f]);return p===q&&(f.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),p}finally{l(q),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:s,resolve:c}=new Deferred,abortListener=()=>c(q);r.addEventListener(`abort`,abortListener,{once:!0});let l,u;assertNotAborted(r,`before query streaming`,a);let{queryId:d}=e;try{for(l=i.streamQuery(e,t,n);;){assertNotAborted(r,`during query streaming`);let e=l.next(),t=await Promise.race([s,e]);if(t===q&&(u=e.catch(printBackgroundFail(`iterator.next`)),throwReasonWithTiming(r.reason,`during query streaming`)),t.done)break;let i=this.#t(t.value,d,n),a=await Promise.race([s,i]);a===q&&(u=i.catch(printBackgroundFail(`plugins.transformResult`)),throwReasonWithTiming(r.reason,`during result transformation`)),yield a}}finally{c(q),r.removeEventListener(`abort`,abortListener);let e=(l?.return?.()||Promise.resolve()).finally(()=>u).finally(a);u||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 xc=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}},Sc=class MergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}using(...e){return new Cc({...this.#e,queryNode:V.cloneWithUsing(this.#e.queryNode,parseJoin(`Using`,e))})}returning(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new MergeQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}},Cc=class WheneableMergeQueryBuilder{#e;constructor(e){this.#e=freeze(e)}modifyEnd(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,e.toOperationNode())})}top(e,t){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.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:V.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:H.cloneWithReturning(this.#e.queryNode,parseSelectArg(e))})}returningAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.cloneWithReturning(this.#e.queryNode,parseSelectAll(e))})}output(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectArg(e))})}outputAll(e){return new WheneableMergeQueryBuilder({...this.#e,queryNode:H.cloneWithOutput(this.#e.queryNode,parseSelectAll(e))})}#n(e,t=!1,n=!1){let r={...this.#e,queryNode:V.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 Cc({...this.#e,queryNode:V.cloneWithThen(this.#e.queryNode,parseMergeThen(`delete`))})}thenDoNothing(){return new Cc({...this.#e,queryNode:V.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenUpdate(e){return new Cc({...this.#e,queryNode:V.cloneWithThen(this.#e.queryNode,parseMergeThen(e(new UpdateQueryBuilder({queryId:this.#e.queryId,executor:xc,queryNode:Gs.createWithoutTable()}))))})}thenUpdateSet(...e){return this.thenUpdate(t=>t.set(...e))}},NotMatchedThenableMergeQueryBuilder=class{#e;constructor(e){this.#e=freeze(e)}thenDoNothing(){return new Cc({...this.#e,queryNode:V.cloneWithThen(this.#e.queryNode,parseMergeThen(`do nothing`))})}thenInsertValues(e){let[t,n]=parseInsertExpression(e);return new Cc({...this.#e,queryNode:V.cloneWithThen(this.#e.queryNode,parseMergeThen(z.cloneWith(z.createWithoutInto(),{columns:t,values:n})))})}},wc=class QueryCreator{#e;constructor(e){this.#e=freeze(e)}selectFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:U.createFrom(parseTableExpressionOrList(e),this.#e.withNode)})}selectNoFrom(e){return createSelectQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:U.cloneWithSelections(U.create(this.#e.withNode),parseSelectArg(e))})}insertInto(e){return new uc({queryId:createQueryId(),executor:this.#e.executor,queryNode:z.create(parseTable(e),this.#e.withNode)})}replaceInto(e){return new uc({queryId:createQueryId(),executor:this.#e.executor,queryNode:z.create(parseTable(e),this.#e.withNode,!0)})}deleteFrom(e){return new DeleteQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:qs.create(parseTableExpressionOrList(e),this.#e.withNode)})}updateTable(e){return new UpdateQueryBuilder({queryId:createQueryId(),executor:this.#e.executor,queryNode:Gs.create(parseTableExpressionOrList(e),this.#e.withNode)})}mergeInto(e){return new Sc({queryId:createQueryId(),executor:this.#e.executor,queryNode:V.create(parseAliasedTable(e),this.#e.withNode)})}with(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?hc.cloneWithExpression(this.#e.withNode,n):hc.create(n)})}withRecursive(e,t){let n=parseCommonTableExpression(e,t);return new QueryCreator({...this.#e,withNode:this.#e.withNode?hc.cloneWithExpression(this.#e.withNode,n):hc.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 wc({executor:xc})}function createJoinBuilder(e,t){return new Qs({joinNode:ms.create(e,parseTableExpression(t))})}function createOverBuilder(){return new ec({overNode:Bs.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 ms.createWithOn(e,parseTableExpression(t),parseReferentialBinaryOperation(n,`=`,r))}function parseOnlessJoin(e,t){return ms.create(e,parseTableExpression(t))}const Tc=freeze({is(e){return e.kind===`OffsetNode`},create(e){return freeze({kind:`OffsetNode`,offset:e})}}),Ec=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(Ec.create)}const Dc=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=>Dc.create(e,parseExpression(t),n))}var J=class ExpressionWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new Oc(fs.create(this.#e,parseValueBinaryOperationOrExpression(e)))}and(...e){return new kc(ds.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 ls.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():N.create(this.#t))}},Oc=class OrWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}or(...e){return new OrWrapper(fs.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new OrWrapper(this.#e)}toOperationNode(){return Ls.create(this.#e)}},kc=class AndWrapper{#e;constructor(e){this.#e=e}get expressionType(){}as(e){return new AliasedExpressionWrapper(this,e)}and(...e){return new AndWrapper(ds.create(this.#e,parseValueBinaryOperationOrExpression(e)))}$castTo(){return new AndWrapper(this.#e)}toOperationNode(){return Ls.create(this.#e)}};const Ac=freeze({is(e){return e.kind===`FetchNode`},create(e,t){return{kind:`FetchNode`,rowCount:R.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 Ac.create(e,t)}function isFetchModifier(e){return e===`only`||e===`with ties`}var Y,SelectQueryBuilderImpl=class{#e;constructor(e){this.#e=freeze(e)}get expressionType(){}get isSelectQueryBuilder(){return!0}where(...e){return new Y({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}whereRef(e,t,n){return new Y({...this.#e,queryNode:H.cloneWithWhere(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}having(...e){return new Y({...this.#e,queryNode:U.cloneWithHaving(this.#e.queryNode,parseValueBinaryOperationOrExpression(e))})}havingRef(e,t,n){return new Y({...this.#e,queryNode:U.cloneWithHaving(this.#e.queryNode,parseReferentialBinaryOperation(e,t,n))})}select(e){return new Y({...this.#e,queryNode:U.cloneWithSelections(this.#e.queryNode,parseSelectArg(e))})}distinctOn(e){return new Y({...this.#e,queryNode:U.cloneWithDistinctOn(this.#e.queryNode,parseReferenceExpressionOrList(e))})}modifyFront(e){return new Y({...this.#e,queryNode:U.cloneWithFrontModifier(this.#e.queryNode,us.createWithExpression(e.toOperationNode()))})}modifyEnd(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,us.createWithExpression(e.toOperationNode()))})}distinct(){return new Y({...this.#e,queryNode:U.cloneWithFrontModifier(this.#e.queryNode,us.create(`Distinct`))})}forUpdate(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,us.create(`ForUpdate`,e?asArray(e).map(parseTable):void 0))})}forShare(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,us.create(`ForShare`,e?asArray(e).map(parseTable):void 0))})}forKeyShare(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,us.create(`ForKeyShare`,e?asArray(e).map(parseTable):void 0))})}forNoKeyUpdate(e){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,us.create(`ForNoKeyUpdate`,e?asArray(e).map(parseTable):void 0))})}skipLocked(){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,us.create(`SkipLocked`))})}noWait(){return new Y({...this.#e,queryNode:H.cloneWithEndModifier(this.#e.queryNode,us.create(`NoWait`))})}selectAll(e){return new Y({...this.#e,queryNode:U.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 Y({...this.#e,queryNode:H.cloneWithJoin(this.#e.queryNode,parseJoin(e,t))})}orderBy(...e){return new Y({...this.#e,queryNode:H.cloneWithOrderByItems(this.#e.queryNode,parseOrderBy(e))})}groupBy(e){return new Y({...this.#e,queryNode:U.cloneWithGroupByItems(this.#e.queryNode,parseGroupBy(e))})}limit(e){return new Y({...this.#e,queryNode:U.cloneWithLimit(this.#e.queryNode,dc.create(parseValueExpression(e)))})}offset(e){return new Y({...this.#e,queryNode:U.cloneWithOffset(this.#e.queryNode,Tc.create(parseValueExpression(e)))})}fetch(e,t=`only`){return new Y({...this.#e,queryNode:U.cloneWithFetch(this.#e.queryNode,parseFetch(e,t))})}top(e,t){return new Y({...this.#e,queryNode:H.cloneWithTop(this.#e.queryNode,parseTop(e,t))})}union(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!1))})}unionAll(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`union`,e,!0))})}intersect(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!1))})}intersectAll(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`intersect`,e,!0))})}except(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!1))})}exceptAll(e){return new Y({...this.#e,queryNode:U.cloneWithSetOperations(this.#e.queryNode,parseSetOperations(`except`,e,!0))})}as(e){return new AliasedSelectQueryBuilderImpl(this,e)}clearSelect(){return new Y({...this.#e,queryNode:U.cloneWithoutSelections(this.#e.queryNode)})}clearWhere(){return new Y({...this.#e,queryNode:H.cloneWithoutWhere(this.#e.queryNode)})}clearLimit(){return new Y({...this.#e,queryNode:U.cloneWithoutLimit(this.#e.queryNode)})}clearOffset(){return new Y({...this.#e,queryNode:U.cloneWithoutOffset(this.#e.queryNode)})}clearOrderBy(){return new Y({...this.#e,queryNode:H.cloneWithoutOrderBy(this.#e.queryNode)})}clearGroupBy(){return new Y({...this.#e,queryNode:U.cloneWithoutGroupBy(this.#e.queryNode)})}$call(e){return e(this)}$if(e,t){return e?t(this):new Y({...this.#e})}$castTo(){return new Y(this.#e)}$narrowType(){return new Y(this.#e)}$assertType(){return new Y(this.#e)}$asTuple(){return new J(this.toOperationNode())}$asScalar(){return new J(this.toOperationNode())}withPlugin(e){return new Y({...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 Y({...this.#e,queryNode:H.cloneWithExplain(this.#e.queryNode,e,t)}).execute()}};Y=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 ls.create(this.#e.toOperationNode(),N.create(this.#t))}};const jc=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]?Rs.cloneWithItems(e[r],t):Rs.create(t)})},cloneWithFilter(e,t){return freeze({...e,filter:e.filter?B.cloneWithOperation(e.filter,`And`,t):B.create(t)})},cloneWithOrFilter(e,t){return freeze({...e,filter:e.filter?B.cloneWithOperation(e.filter,`Or`,t):B.create(t)})},cloneWithOver(e,t){return freeze({...e,over:t})}}),Mc=freeze({is(e){return e.kind===`FunctionNode`},create(e,t){return freeze({kind:`FunctionNode`,func:e,arguments:t})}});var Nc=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:jc.cloneWithDistinct(this.#e.aggregateFunctionNode)})}orderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:H.cloneWithOrderByItems(this.#e.aggregateFunctionNode,parseOrderBy(e))})}clearOrderBy(){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:H.cloneWithoutOrderBy(this.#e.aggregateFunctionNode)})}withinGroupOrderBy(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:jc.cloneWithOrderBy(this.#e.aggregateFunctionNode,parseOrderBy(e),!0)})}filterWhere(...e){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:jc.cloneWithFilter(this.#e.aggregateFunctionNode,parseValueBinaryOperationOrExpression(e))})}filterWhereRef(e,t,n){return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:jc.cloneWithFilter(this.#e.aggregateFunctionNode,parseReferentialBinaryOperation(e,t,n))})}over(e){let t=createOverBuilder();return new AggregateFunctionBuilder({...this.#e,aggregateFunctionNode:jc.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 ls.create(this.#e.toOperationNode(),N.create(this.#t))}};function createFunctionModule(){let fn=(e,t)=>new J(Mc.create(e,parseReferenceExpressionOrList(t??[]))),agg=(e,t)=>new Nc({aggregateFunctionNode:jc.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 Nc({aggregateFunctionNode:jc.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 Nc({aggregateFunctionNode:jc.create(`json_agg`,[isString(e)?parseTable(e):e.toOperationNode()])})},toJson(e){return new J(Mc.create(`to_json`,[isString(e)?parseTable(e):e.toOperationNode()]))}})}const Pc=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 Pc.create(Ts.create(e),parseReferenceExpression(t));throw Error(`invalid unary operator ${JSON.stringify(e)}`)}const X=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),Xs.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:X.cloneWithWhen(this.#e.node,Xs.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,Xs.create(parseReferentialBinaryOperation(e,t,n)))})}},CaseThenBuilder=class{#e;constructor(e){this.#e=freeze(e)}then(e){return new CaseWhenBuilder({...this.#e,node:X.cloneWithThen(this.#e.node,isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e))})}thenRef(e){return new CaseWhenBuilder({...this.#e,node:X.cloneWithThen(this.#e.node,parseReferenceExpression(e))})}},CaseWhenBuilder=class{#e;constructor(e){this.#e=freeze(e)}when(...e){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,Xs.create(parseValueBinaryOperationOrExpression(e)))})}whenRef(e,t,n){return new CaseThenBuilder({...this.#e,node:X.cloneWithWhen(this.#e.node,Xs.create(parseReferentialBinaryOperation(e,t,n)))})}else(e){return new CaseEndBuilder({...this.#e,node:X.cloneWith(this.#e.node,{else:isSafeImmediateValue(e)?parseSafeImmediateValue(e):parseValueExpression(e)})})}elseRef(e){return new CaseEndBuilder({...this.#e,node:X.cloneWith(this.#e.node,{else:parseReferenceExpression(e)})})}end(){return new J(X.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new J(X.cloneWith(this.#e.node,{isStatement:!0}))}},CaseEndBuilder=class{#e;constructor(e){this.#e=freeze(e)}end(){return new J(X.cloneWith(this.#e.node,{isStatement:!1}))}endCase(){return new J(X.cloneWith(this.#e.node,{isStatement:!0}))}};const Fc=freeze({is(e){return e.kind===`JSONPathLegNode`},create(e,t){return freeze({kind:`JSONPathLegNode`,type:e,value:t})}}),Ic=/^#-\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`&&!Ic.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 Ms.is(this.#e)?new Lc(Ms.cloneWithTraversal(this.#e,Ps.is(this.#e.traversal)?Ps.cloneWithLeg(this.#e.traversal,Fc.create(e,t)):Ns.cloneWithValue(this.#e.traversal,R.createImmediate(t)))):new Lc(Ps.cloneWithLeg(this.#e,Fc.create(e,t)))}},Lc=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 ls.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():N.create(this.#t))}};const Rc=freeze({is(e){return e.kind===`TupleNode`},create(e){return freeze({kind:`TupleNode`,values:freeze(e)})}}),zc=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}),Bc=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+\)$/]),Vc=freeze({is(e){return e.kind===`DataTypeNode`},create(e){return freeze({kind:`DataTypeNode`,dataType:e})}});function isColumnDataType(e){return zc[e]||Bc.some(t=>t.test(e))}function parseDataTypeExpression(e){if(isOperationNodeSource(e))return e.toOperationNode();if(isColumnDataType(e))return Vc.create(e);throw Error(`invalid column data type ${JSON.stringify(e)}`)}const Hc=freeze({is(e){return e.kind===`CastNode`},create(e,t){return freeze({kind:`CastNode`,expression:e,dataType:t})}});function createExpressionBuilder(e=xc){function binary(e,t,n){return new J(parseValueBinaryOperation(e,t,n))}function unary(e,t){return new J(parseUnaryOperation(e,t))}let t=Object.assign(binary,{fn:void 0,eb:void 0,selectFrom(t){return createSelectQueryBuilder({queryId:createQueryId(),executor:e,queryNode:U.createFrom(parseTableExpressionOrList(t))})},case(e){return new CaseBuilder({node:X.create(isUndefined(e)?void 0:parseReferenceExpression(e))})},ref(e,t){return isUndefined(t)?new J(parseStringReference(e)):new JSONPathBuilder(parseJSONReference(e,t))},jsonPath(){return new JSONPathBuilder(Ps.create())},table(e){return new J(parseTable(e))},val(e){return new J(parseValueExpression(e))},refTuple(...e){return new J(Rc.create(e.map(parseReferenceExpression)))},tuple(...e){return new J(Rc.create(e.map(parseValueExpression)))},lit(e){return new J(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 J(hs.create(parseReferenceExpression(e),Ts.create(`between`),ds.create(parseValueExpression(t),parseValueExpression(n))))},betweenSymmetric(e,t,n){return new J(hs.create(parseReferenceExpression(e),Ts.create(`between symmetric`),ds.create(parseValueExpression(t),parseValueExpression(n))))},and(e){return isReadonlyArray(e)?new J(parseFilterList(e,`and`)):new J(parseFilterObject(e,`and`))},or(e){return isReadonlyArray(e)?new J(parseFilterList(e,`or`)):new J(parseFilterObject(e,`or`))},parens(...e){let t=parseValueBinaryOperationOrExpression(e);return Ls.is(t)?new J(t):new J(Ls.create(t))},cast(e,t){return new J(Hc.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 ls.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 ls.create(parseTable(n),N.create(r))}return parseTable(e)}function parseTable(e){if(e.includes(`.`)){let[t,n]=e.split(`.`).map(trim$1);return F.createWithSchema(t,n)}return F.create(e)}function trim$1(e){return e.trim()}const Uc=freeze({is(e){return e.kind===`AddColumnNode`},create(e){return freeze({kind:`AddColumnNode`,column:e})}}),Z=freeze({is(e){return e.kind===`ColumnDefinitionNode`},create(e,t){return freeze({kind:`ColumnDefinitionNode`,column:I.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})}}),Wc=freeze({is(e){return e.kind===`DropColumnNode`},create(e){return freeze({kind:`DropColumnNode`,column:I.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),Gc=freeze({is(e){return e.kind===`RenameColumnNode`},create(e,t){return freeze({kind:`RenameColumnNode`,column:I.create(e),renameTo:I.create(t)})}}),Kc=freeze({is(e){return e.kind===`CheckConstraintNode`},create(e,t){return freeze({kind:`CheckConstraintNode`,expression:e,name:t?N.create(t):void 0})}}),qc=freeze({cascade:!0,"no action":!0,restrict:!0,"set default":!0,"set null":!0});Object.keys(qc);const Jc=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)&&qc[e]}function parseDefaultValueExpression(e){return isOperationNodeSource(e)?e.toOperationNode():R.createImmediate(e)}const Yc=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})}}),Xc=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 Zc=class ColumnDefinitionBuilder{#e;constructor(e){this.#e=e}autoIncrement(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=parseStringReference(e);if(!t.table||Es.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{references:Jc.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(Z.cloneWith(this.#e,{references:Jc.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(Z.cloneWith(this.#e,{references:Jc.cloneWithOnUpdate(this.#e.references,parseOnModifyForeignAction(e))}))}unique(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{unique:!0}))}notNull(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{defaultTo:Xc.create(parseDefaultValueExpression(e))}))}check(e){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{check:Kc.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{generated:Yc.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{generated:Yc.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{generated:Yc.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error(`stored() can only be called after generatedAlwaysAs`);return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{generated:Yc.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new ColumnDefinitionBuilder(Z.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new ColumnDefinitionBuilder(Z.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new ColumnDefinitionBuilder(Z.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}};const Qc=freeze({is(e){return e.kind===`ModifyColumnNode`},create(e){return freeze({kind:`ModifyColumnNode`,column:e})}}),$c=freeze({is(e){return e.kind===`ForeignKeyConstraintNode`},create(e,t,n,r){return freeze({kind:`ForeignKeyConstraintNode`,columns:e,references:Jc.create(t,n),name:r?N.create(r):void 0})},cloneWith(e,t){return freeze({...e,...t})}});var el=class ForeignKeyConstraintBuilder{#e;constructor(e){this.#e=e}onDelete(e){return new ForeignKeyConstraintBuilder($c.cloneWith(this.#e,{onDelete:parseOnModifyForeignAction(e)}))}onUpdate(e){return new ForeignKeyConstraintBuilder($c.cloneWith(this.#e,{onUpdate:parseOnModifyForeignAction(e)}))}deferrable(){return new ForeignKeyConstraintBuilder($c.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new ForeignKeyConstraintBuilder($c.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new ForeignKeyConstraintBuilder($c.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new ForeignKeyConstraintBuilder($c.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}};const tl=freeze({is(e){return e.kind===`AddConstraintNode`},create(e){return freeze({kind:`AddConstraintNode`,constraint:e})}}),nl=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(I.create)),freeze({kind:`UniqueConstraintNode`,columns:freeze(e),name:t?N.create(t):void 0,nullsNotDistinct:n})},cloneWith(e,t){return freeze({...e,...t})}}),rl=freeze({is(e){return e.kind===`DropConstraintNode`},create(e){return freeze({kind:`DropConstraintNode`,constraintName:N.create(e)})},cloneWith(e,t){return freeze({...e,...t})}}),il=freeze({is(e){return e.kind===`AlterColumnNode`},create(e,t,n){return freeze({kind:`AlterColumnNode`,column:I.create(e),[t]:n})}});var AlterColumnBuilder=class{#e;constructor(e){this.#e=e}setDataType(e){return new AlteredColumnBuilder(il.create(this.#e,`dataType`,parseDataTypeExpression(e)))}setDefault(e){return new AlteredColumnBuilder(il.create(this.#e,`setDefault`,parseDefaultValueExpression(e)))}dropDefault(){return new AlteredColumnBuilder(il.create(this.#e,`dropDefault`,!0))}setNotNull(){return new AlteredColumnBuilder(il.create(this.#e,`setNotNull`,!0))}dropNotNull(){return new AlteredColumnBuilder(il.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)}},al=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:tl.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)}},ol=class AlterTableDropConstraintBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new AlterTableDropConstraintBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropConstraint:rl.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new AlterTableDropConstraintBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropConstraint:rl.cloneWith(this.#e.node.dropConstraint,{modifier:`cascade`})})})}restrict(){return new AlterTableDropConstraintBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropConstraint:rl.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 sl=freeze({is(e){return e.kind===`PrimaryKeyConstraintNode`},create(e,t){return freeze({kind:`PrimaryKeyConstraintNode`,columns:freeze(e.map(I.create)),name:t?N.create(t):void 0})},cloneWith(e,t){return freeze({...e,...t})}}),cl=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 ll=class AlterTableAddIndexBuilder{#e;constructor(e){this.#e=freeze(e)}unique(){return new AlterTableAddIndexBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:cl.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new AlterTableAddIndexBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:cl.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:cl.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:cl.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new AlterTableAddIndexBuilder({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:cl.cloneWith(this.#e.node.addIndex,{using:L.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)}},ul=class UniqueConstraintNodeBuilder{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new UniqueConstraintNodeBuilder(nl.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new UniqueConstraintNodeBuilder(nl.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new UniqueConstraintNodeBuilder(nl.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new UniqueConstraintNodeBuilder(nl.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new UniqueConstraintNodeBuilder(nl.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}},dl=class PrimaryKeyConstraintBuilder{#e;constructor(e){this.#e=e}deferrable(){return new PrimaryKeyConstraintBuilder(sl.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new PrimaryKeyConstraintBuilder(sl.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new PrimaryKeyConstraintBuilder(sl.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new PrimaryKeyConstraintBuilder(sl.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 fl=freeze({is(e){return e.kind===`RenameConstraintNode`},create(e,t){return freeze({kind:`RenameConstraintNode`,oldName:N.create(e),newName:N.create(t)})}});var pl=class DropColumnBuilder{#e;constructor(e){this.#e=freeze({...e})}ifExists(){return new DropColumnBuilder({...this.#e,node:Wc.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 ml({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}dropColumn(e,t=noop){let n=t(new pl({node:Wc.create(e)}));return new ml({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,n.toOperationNode())})}renameColumn(e,t){return new ml({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,Gc.create(e,t))})}addColumn(e,t,n=noop){let r=n(new Zc(Z.create(e,parseDataTypeExpression(t))));return new ml({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,Uc.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new Zc(Z.create(e,parseDataTypeExpression(t))));return new ml({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,Qc.create(r.toOperationNode()))})}addUniqueConstraint(e,t,n=noop){let r=n(new ul(nl.create(t.map(e=>isString(e)?I.create(e):parseExpression(e)),e)));return new AlterTableExecutor({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addConstraint:tl.create(r.toOperationNode())})})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Kc.create(t.toOperationNode(),e)));return new AlterTableExecutor({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addConstraint:tl.create(r.toOperationNode())})})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new el($c.create(t.map(I.create),parseTable(n),r.map(I.create),e)));return new al({...this.#e,constraintBuilder:a})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new dl(sl.create(t,e)));return new AlterTableExecutor({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addConstraint:tl.create(r.toOperationNode())})})}dropConstraint(e){return new ol({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropConstraint:rl.create(e)})})}renameConstraint(e,t){return new ol({...this.#e,node:M.cloneWithTableProps(this.#e.node,{renameConstraint:fl.create(e,t)})})}addIndex(e){return new ll({...this.#e,node:M.cloneWithTableProps(this.#e.node,{addIndex:cl.create(e)})})}dropIndex(e){return new AlterTableExecutor({...this.#e,node:M.cloneWithTableProps(this.#e.node,{dropIndex:os.create(e)})})}$call(e){return e(this)}},ml=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 pl({node:Wc.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,Gc.create(e,t))})}addColumn(e,t,n=noop){let r=n(new Zc(Z.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,Uc.create(r.toOperationNode()))})}modifyColumn(e,t,n=noop){let r=n(new Zc(Z.create(e,parseDataTypeExpression(t))));return new AlterTableColumnAlteringBuilder({...this.#e,node:M.cloneWithColumnAlteration(this.#e.node,Qc.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 Is.create(e.values.map(R.createImmediate))}transformValue(e){return R.createImmediate(e.value)}},hl=class CreateIndexBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateIndexBuilder({...this.#e,node:ns.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new CreateIndexBuilder({...this.#e,node:ns.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new CreateIndexBuilder({...this.#e,node:ns.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new CreateIndexBuilder({...this.#e,node:ns.cloneWith(this.#e.node,{table:parseTable(e)})})}column(e){return new CreateIndexBuilder({...this.#e,node:ns.cloneWithColumns(this.#e.node,[isString(e)?parseOrderedColumnName(e):e.toOperationNode()])})}columns(e){return new CreateIndexBuilder({...this.#e,node:ns.cloneWithColumns(this.#e.node,e.map(e=>isString(e)?parseOrderedColumnName(e):e.toOperationNode()))})}expression(e){return new CreateIndexBuilder({...this.#e,node:ns.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new CreateIndexBuilder({...this.#e,node:ns.cloneWith(this.#e.node,{using:L.createWithSql(e)})})}where(...e){let t=new ImmediateValueTransformer;return new CreateIndexBuilder({...this.#e,node:H.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)}},gl=class CreateSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifNotExists(){return new CreateSchemaBuilder({...this.#e,node:rs.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(is.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}var _l=class CreateTableAddIndexBuilder{#e;constructor(e){this.#e=e}using(e){return new CreateTableAddIndexBuilder(cl.cloneWith(this.#e,{using:L.createWithSql(e)}))}$call(e){return e(this)}toOperationNode(){return this.#e}},vl=class CreateTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateTableBuilder({...this.#e,node:P.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new CreateTableBuilder({...this.#e,node:P.cloneWith(this.#e.node,{onCommit:parseOnCommitAction(e)})})}ifNotExists(){return new CreateTableBuilder({...this.#e,node:P.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,n=noop){let r=n(new Zc(Z.create(e,parseDataTypeExpression(t))));return new CreateTableBuilder({...this.#e,node:P.cloneWithColumn(this.#e.node,r.toOperationNode())})}addPrimaryKeyConstraint(e,t,n=noop){let r=n(new dl(sl.create(t,e)));return new CreateTableBuilder({...this.#e,node:P.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addUniqueConstraint(e,t,n=noop){let r=n(new ul(nl.create(t.map(e=>isString(e)?I.create(e):parseExpression(e)),e)));return new CreateTableBuilder({...this.#e,node:P.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addIndex(e,t,n=noop){let r=n(new _l(cl.cloneWithColumns(cl.create(e),t.map(e=>isString(e)?I.create(e):parseExpression(e)))));return new CreateTableBuilder({...this.#e,node:P.cloneWithIndex(this.#e.node,r.toOperationNode())})}addCheckConstraint(e,t,n=noop){let r=n(new CheckConstraintBuilder(Kc.create(t.toOperationNode(),e)));return new CreateTableBuilder({...this.#e,node:P.cloneWithConstraint(this.#e.node,r.toOperationNode())})}addForeignKeyConstraint(e,t,n,r,i=noop){let a=i(new el($c.create(t.map(I.create),parseTable(n),r.map(I.create),e)));return new CreateTableBuilder({...this.#e,node:P.cloneWithConstraint(this.#e.node,a.toOperationNode())})}modifyFront(e){return new CreateTableBuilder({...this.#e,node:P.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new CreateTableBuilder({...this.#e,node:P.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new CreateTableBuilder({...this.#e,node:P.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)}},yl=class DropIndexBuilder{#e;constructor(e){this.#e=freeze(e)}on(e){return new DropIndexBuilder({...this.#e,node:os.cloneWith(this.#e.node,{table:parseTable(e)})})}ifExists(){return new DropIndexBuilder({...this.#e,node:os.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropIndexBuilder({...this.#e,node:os.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)}},bl=class DropSchemaBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropSchemaBuilder({...this.#e,node:ss.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropSchemaBuilder({...this.#e,node:ss.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)}},xl=class DropTableBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new DropTableBuilder({...this.#e,node:cs.cloneWith(this.#e.node,{temporary:!0})})}ifExists(){return new DropTableBuilder({...this.#e,node:cs.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTableBuilder({...this.#e,node:cs.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 Sl=freeze({is(e){return e.kind===`CreateViewNode`},create(e){return freeze({kind:`CreateViewNode`,name:as.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)}},Cl=class CreateViewBuilder{#e;constructor(e){this.#e=freeze(e)}temporary(){return new CreateViewBuilder({...this.#e,node:Sl.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new CreateViewBuilder({...this.#e,node:Sl.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new CreateViewBuilder({...this.#e,node:Sl.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new CreateViewBuilder({...this.#e,node:Sl.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new CreateViewBuilder({...this.#e,node:Sl.cloneWith(this.#e.node,{columns:e.map(parseColumnName)})})}as(e){let t=e.withPlugin(new ImmediateValuePlugin).toOperationNode();return new CreateViewBuilder({...this.#e,node:Sl.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 wl=freeze({is(e){return e.kind===`DropViewNode`},create(e){return freeze({kind:`DropViewNode`,name:as.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var Tl=class DropViewBuilder{#e;constructor(e){this.#e=freeze(e)}materialized(){return new DropViewBuilder({...this.#e,node:wl.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new DropViewBuilder({...this.#e,node:wl.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropViewBuilder({...this.#e,node:wl.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 El=freeze({is(e){return e.kind===`CreateTypeNode`},create(e){return freeze({kind:`CreateTypeNode`,name:e})},cloneWithEnum(e,t){return freeze({...e,enum:Is.create(t.map(R.createImmediate))})}});var Dl=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:El.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 Ol=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 kl=class DropTypeBuilder{#e;constructor(e){this.#e=freeze(e)}ifExists(){return new DropTypeBuilder({...this.#e,node:Ol.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new DropTypeBuilder({...this.#e,node:Ol.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 as.createWithSchema(t[0],t[1]);throw Error(`invalid schemable identifier ${e}`)}return as.create(e)}function parseSchemableIdentifierArray(e){return Array.isArray(e)||(e=[e]),e.map(parseSchemableIdentifier)}function trim(e){return e.trim()}const Al=freeze({is(e){return e.kind===`RefreshMaterializedViewNode`},create(e){return freeze({kind:`RefreshMaterializedViewNode`,name:as.create(e)})},cloneWith(e,t){return freeze({...e,...t})}});var jl=class RefreshMaterializedViewBuilder{#e;constructor(e){this.#e=freeze(e)}concurrently(){return new RefreshMaterializedViewBuilder({...this.#e,node:Al.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Al.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new RefreshMaterializedViewBuilder({...this.#e,node:Al.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 Ml=freeze({is(e){return e.kind===`AlterTypeNode`},create(e){return freeze({kind:`AlterTypeNode`,name:e})},cloneWith(e,t){return freeze({...e,...t})}}),Nl=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)}},Pl,AlterTypeAddValueBuilder=class extends QueryFinalizer{#e;constructor(e){super(e),this.#e=e}ifNotExists(){return new Pl({...this.#e,node:Ml.cloneWith(this.#e.node,{addValue:Nl.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 Pl({...this.#e,node:Ml.cloneWith(this.#e.node,{addValue:Nl.cloneWith(this.#e.node.addValue,{isBefore:t,neighborValue:R.createImmediate(e)})})})}};Pl=AlterTypeAddValueBuilder;const Fl=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:Ml.cloneWith(this.#e.node,{addValue:Nl.create(R.createImmediate(e))})})}renameTo(e){return new QueryFinalizer({...this.#e,node:Ml.cloneWith(this.#e.node,{renameTo:N.create(e)})})}renameValue(e,t){return new QueryFinalizer({...this.#e,node:Ml.cloneWith(this.#e.node,{renameValue:Fl.create(R.createImmediate(e),R.createImmediate(t))})})}setSchema(e){return new QueryFinalizer({...this.#e,node:Ml.cloneWith(this.#e.node,{setSchema:N.create(e)})})}},Il=class SchemaModule{#e;constructor(e){this.#e=e}createTable(e){return new vl({queryId:createQueryId(),executor:this.#e,node:P.create(parseTable(e))})}dropTable(e){return new xl({queryId:createQueryId(),executor:this.#e,node:cs.create(parseTable(e))})}createIndex(e){return new hl({queryId:createQueryId(),executor:this.#e,node:ns.create(e)})}dropIndex(e){return new yl({queryId:createQueryId(),executor:this.#e,node:os.create(e)})}createSchema(e){return new gl({queryId:createQueryId(),executor:this.#e,node:rs.create(e)})}dropSchema(e){return new bl({queryId:createQueryId(),executor:this.#e,node:ss.create(e)})}alterTable(e){return new AlterTableBuilder({queryId:createQueryId(),executor:this.#e,node:M.create(parseTable(e))})}createView(e){return new Cl({queryId:createQueryId(),executor:this.#e,node:Sl.create(e)})}refreshMaterializedView(e){return new jl({queryId:createQueryId(),executor:this.#e,node:Al.create(e)})}dropView(e){return new Tl({queryId:createQueryId(),executor:this.#e,node:wl.create(e)})}createType(e){return new Dl({queryId:createQueryId(),executor:this.#e,node:El.create(parseSchemableIdentifier(e))})}alterType(e){return new AlterTypeBuilder({executor:this.#e,node:Ml.create(parseSchemableIdentifier(e)),queryId:createQueryId()})}dropType(e){return new kl({queryId:createQueryId(),executor:this.#e,node:Ol.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)}}},Ll=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,s=performanceNow();try{return await t.call(e,n,i)}catch(e){throw a=e,await r.#l(e,n,s),e}finally{a||await r.#u(n,s)}},e.streamQuery=async function*(t,i,a){let s,c=performanceNow();try{for await(let r of n.call(e,t,i,a))yield r}catch(e){throw s=e,await r.#l(e,t,c),e}finally{s||await r.#u(t,c,!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 Rl=[`read only`,`read write`],zl=[`read uncommitted`,`read committed`,`repeatable read`,`serializable`,`snapshot`];function validateTransactionSettings(e){if(e.accessMode&&!Rl.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!zl.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 Bl=class Kysely extends wc{#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(),s=r.createAdapter(),c=new RuntimeDriver(i,s,new Log(e.log??[])),l=new Ll(a,s,new DefaultConnectionProvider(c),e.plugins??[]);t={executor:l},n={config:e,executor:l,dialect:r,driver:c}}super(t),this.#e=freeze(n)}get schema(){return new Il(this.#e.executor)}get dynamic(){return new DynamicModule}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new CaseBuilder({node:X.create(isUndefined(e)?void 0:parseExpression(e))})}get fn(){return createFunctionModule()}transaction(){return new Hl({...this.#e})}startTransaction(){return new Ul({...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()}},Vl=class Transaction extends Bl{#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 Bl({...this.#e,executor:n}))},freeze({signal:t?.signal}))}},Hl=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 Gl(this.#e.executor.withConnectionProvider(new SingleConnectionProvider(t)),n),s=new Vl({...r,executor:a}),c=!1;try{await this.#e.driver.beginTransaction(t,i),c=!0;let r=await e(s);return await this.#e.driver.commitTransaction(t),n.isCommitted=!0,r}catch(e){throw c&&(await this.#e.driver.rollbackTransaction(t),n.isRolledBack=!0),e}})}},Ul=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 Wl({...n,connection:i,state:{isCommitted:!1,isRolledBack:!1},executor:this.#e.executor.withConnectionProvider(new SingleConnectionProvider(i.connection))})}},Wl=class ControlledTransaction extends Vl{#e;#t;constructor(e){e={...e,executor:new Gl(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 Gl=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)}},Kl=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?xc: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 Kl(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 ls.create(this.#e.toOperationNode(),isOperationNodeSource(this.#t)?this.#t.toOperationNode():N.create(this.#t))}};const Q=Object.assign((e,...t)=>createRawBuilder({queryId:createQueryId(),rawNode:L.create(e,t?.map(parseParameter)??[])}),{ref(e){return createRawBuilder({queryId:createQueryId(),rawNode:L.createWithChild(parseStringReference(e))})},val(e){return createRawBuilder({queryId:createQueryId(),rawNode:L.createWithChild(parseValueExpression(e))})},table(e){return createRawBuilder({queryId:createQueryId(),rawNode:L.createWithChild(parseTable(e))})},id(...e){let t=Array(e.length+1).fill(`.`);return t[0]=``,t[t.length-1]=``,createRawBuilder({queryId:createQueryId(),rawNode:L.create(t,e.map(N.create))})},lit(e){return createRawBuilder({queryId:createQueryId(),rawNode:L.createWithChild(R.createImmediate(e))})},raw(e){return createRawBuilder({queryId:createQueryId(),rawNode:L.createWithSql(e)})},join(e,t=Q`, `){let n=Array(Math.max(2*e.length-1,0)),r=t.toOperationNode();for(let t=0;t<e.length;++t)n[2*t]=parseParameter(e[t]),t!==e.length-1&&(n[2*t+1]=r);return createRawBuilder({queryId:createQueryId(),rawNode:L.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 ql=/'/g,Jl=/['"]/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&&!Ls.is(this.parentNode)&&!z.is(this.parentNode)&&!P.is(this.parentNode)&&!Sl.is(this.parentNode)&&!Dc.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&&!Ls.is(this.parentNode)&&!L.is(this.parentNode)&&!Xs.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&&!Ls.is(this.parentNode)&&!L.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(Zl[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&&!Ls.is(this.parentNode)&&!L.is(this.parentNode)&&!Xs.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(Yl[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 Ts.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&&P.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(ql,`''`)}sanitizeJSONPathMemberValue(e){return e.replace(Jl,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?Xl[e.modifier]-Xl[t.modifier]:1))}compileColumnAlterations(e){this.compileList(e)}announcesNewColumnDataType(){return!0}};const Yl=freeze({ForKeyShare:`for key share`,ForNoKeyUpdate:`for no key update`,ForUpdate:`for update`,ForShare:`for share`,NoWait:`nowait`,SkipLocked:`skip locked`,Distinct:`distinct`}),Xl=freeze({ForKeyShare:1,ForNoKeyUpdate:1,ForUpdate:1,ForShare:1,NoWait:2,SkipLocked:2,Distinct:0}),Zl=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`}),Ql=freeze({raw(e,t=[]){return freeze({sql:e,query:L.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 L.createWithChildren([L.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(Ql.raw(`begin`))}async commitTransaction(e){await e.executeQuery(Ql.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Ql.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(!U.is(i))throw Error(`Sqlite driver only supports streaming of select queries`);let s=a.iterate(r);for(let e of s)yield{rows:[e]}}};const $l=/"/g,eu=/[\\'"]/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($l,`""`)}sanitizeJSONPathMemberValue(e){return e.replace(eu,e=>e===`\\`?`\\\\`:e===`'`?`''`:`\\"`)}visitDefaultInsertValue(e){this.append(`null`)}};const tu=`kysely_migration`,nu=`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`,`!=`,tu).where(`name`,`!=`,nu)),n}async#n(e){let t=await this.#t(this.#e,e).execute(),n=await this.#e.with(`table_list`,t=>this.#t(t,e)).selectFrom([`table_list as tl`,Q`pragma_table_info(tl.name)`.as(`p`)]).select([`tl.name as table`,`p.cid`,`p.name`,`p.type`,`p.notnull`,`p.dflt_value`,`p.pk`]).orderBy(`tl.name`).orderBy(`p.cid`).execute(),r={};for(let e of n)r[e.table]??=[],r[e.table].push(e);return t.map(({name:e,sql:t,type:n})=>{let i=t?.split(/[\(\),]/)?.find(e=>e.toLowerCase().includes(`autoincrement`))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,``),a=r[e]??[];if(!i){let e=a.filter(e=>e.pk>0);e.length===1&&e[0].type.toLowerCase()===`integer`&&(i=e[0].name)}return{name:e,isView:n===`view`,isForeign:!1,columns:a.map(e=>({name:e.name,dataType:e.type,isNullable:!e.notnull,isAutoIncrementing:e.name===i,hasDefaultValue:e.dflt_value!=null,comment:void 0}))}})}},SqliteAdapter=class extends DialectAdapterBase{get supportsMultipleConnections(){return!1}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(e,t){}async releaseMigrationLock(e,t){}},SqliteDialect=class{#e;constructor(e){this.#e=freeze({...e})}createDriver(){return new SqliteDriver(this.#e)}createQueryCompiler(){return new SqliteQueryCompiler}createAdapter(){return new SqliteAdapter}createIntrospector(e){return new SqliteIntrospector(e)}};function extendStackTrace(e,t){if(isStackHolder(e)&&t.stack){let n=t.stack.split(`
`).slice(1).join(`
`);return e.stack+=`\n${n}`,e}return e}function isStackHolder(e){return isObject(e)&&isString(e.stack)}const ru=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(Ql.raw(n))}async commitTransaction(e){await e.executeQuery(Ql.raw(`commit`))}async rollbackTransaction(e){await e.executeQuery(Ql.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[ru]()}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}}[ru](){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(Ql.raw(e,[]))});let a=new n({...r,password:`password`in r?r.password:void 0});try{if(await a.connect(),i.queryId!==this.#n.queryId)return;await a.query(e,[])}finally{a.end()}}},PostgresIntrospector=class{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom(`pg_catalog.pg_namespace`).select(`nspname`).$castTo().execute()).map(e=>({name:e.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom(`pg_catalog.pg_attribute as a`).innerJoin(`pg_catalog.pg_class as c`,`a.attrelid`,`c.oid`).innerJoin(`pg_catalog.pg_namespace as ns`,`c.relnamespace`,`ns.oid`).innerJoin(`pg_catalog.pg_type as typ`,`a.atttypid`,`typ.oid`).innerJoin(`pg_catalog.pg_namespace as dtns`,`typ.typnamespace`,`dtns.oid`).select([`a.attname as column`,`a.attnotnull as not_null`,`a.atthasdef as has_default`,`c.relname as table`,`c.relkind as table_type`,`ns.nspname as schema`,`typ.typname as type`,`dtns.nspname as type_schema`,Q`col_description(a.attrelid, a.attnum)`.as(`column_description`),Q`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as(`auto_incrementing`)]).where(`c.relkind`,`in`,[`r`,`v`,`p`,`f`]).where(`ns.nspname`,`!~`,`^pg_`).where(`ns.nspname`,`!=`,`information_schema`).where(`ns.nspname`,`!=`,`crdb_internal`).where(Q`has_schema_privilege(ns.nspname, 'USAGE')`).where(`a.attnum`,`>=`,0).where(`a.attisdropped`,`!=`,!0).orderBy(`ns.nspname`).orderBy(`c.relname`).orderBy(`a.attnum`).$castTo();e.withInternalKyselyTables||(t=t.where(`c.relname`,`!=`,tu).where(`c.relname`,`!=`,nu));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 iu=/"/g;var PostgresQueryCompiler=class extends DefaultQueryCompiler{sanitizeIdentifier(e){return e.replace(iu,`""`)}};const au=BigInt(`3853314791062309107`);var PostgresAdapter=class extends DialectAdapterBase{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await Q`
with set_timeout as (
select set_config('lock_timeout', '${Q.lit(36e5)}', true) as config_val
)
select pg_advisory_lock(${Q.lit(au)})
from set_timeout`.execute(e)}async releaseMigrationLock(e,t){await Q`select pg_advisory_unlock(${Q.lit(au)})`.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 ou=/^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,su=[{major:24,minor:16,patch:0},{major:26,minor:1,patch:0}],cu=su[su.length-1];`${su.map(({major:e,minor:t,patch:n},r)=>`>=${e}.${t}.${n}${r<su.length-1?` <${e+1}`:``}`).join(` || `).replaceAll(` || `,`, `).replace(/, ([^,]+)$/,`, or $1`)}`;function parseNodeReleaseVersion(e){if(typeof e!=`string`)return null;let t=ou.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>cu.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(ou.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(su)};
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,lu=templateFragments`(SELECT value FROM json_each(${0}))`,uu=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!L.is(e)||e.sqlFragments!==lu||e.parameters.length!==1)return;let t=e.parameters[0];for(;L.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``);)t=t.parameters[0];if(!R.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(Ts.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===lu;!t&&e.sqlFragments!==uu?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 du=parseNodeReleaseVersion(process.versions.node),fu=!process.versions.bun&&(du?.major===24&&isNodeVersionAtLeast(du,{major:24,minor:20,patch:0})||isNodeVersionAtLeast(du,{major:26,minor:6,patch:0})),pu=new SqliteDialect({database:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}}),mu=/* @__PURE__ */ new WeakMap,hu=new OpenClawPostgresDialect({pool:async()=>{throw Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});function getNodeSqliteKysely(e){if(b(e)){let t=mu.get(e);return t||(t=new Bl({dialect:hu}),mu.set(e,t)),t}let t=Fo.get(e);if(t)return t;let n=new Bl({dialect:pu});return Fo.set(e,n),n}function reportNodeSqliteKyselyQueryError(e,t){try{Io.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 te(i,r)}function executeCompiledSqliteQuerySync(e,t,n=!1,r=t.parameters){if(b(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 installStatementInvalidation(e),executeWithCachedStatement(e,i,r,i=>{if(n&&U.is(t.query)){let e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(U.is(t.query)||i.columns().length>0){if(fu)return{rows:i.all(...r)};let t=i.iterate(...r),n=ye(e,`kysely eager query`),a=!1,s,c=[];try{for(let e of t)n.progress(),c.push(e)}catch(e){a=!0,s=e}if(releaseSqliteIterator(t,n,a,`SQLite query cleanup failed`),a)throw te(s,`SQLite query failed`);return{rows:c}}i.setReadBigInts(!0);let a;try{a=i.run(...r)}finally{i.setReadBigInts(!1)}let{changes:s,lastInsertRowid:c}=a,l={numAffectedRows:BigInt(s),rows:[]};return z.is(t.query)&&s>0?{...l,insertId:BigInt(c)}: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),Q`${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 executeSqliteQueryTakeFirstSync(e,t){return executeCompiledSqliteQuerySync(e,t.compile(),!0).rows[0]}const gu={name:`database.engine.schema`,schemaDependent:!0};function hasPostgresCatalogColumn(e,t,n){return e.some(e=>e.table===t&&e.kind===`column`&&e.value!==null&&typeof e.value==`object`&&`name`in e.value&&e.value.name===n)}function canonical(e){return JSON.stringify(e,(e,t)=>typeof t==`object`&&t&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).toSorted(([e],[t])=>e.localeCompare(t,`en`))):t)}function assertPostgresCatalog(e,t){if(!Tn(e.map(canonical).toSorted(),t.map(canonical).toSorted()))throw Error(`PostgreSQL catalog differs from its generated contract; use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`)}function readPostgresCatalog(e){if(!Array.isArray(e)||!e.every(e=>typeof e==`object`&&!!e&&typeof e.table==`string`&&typeof e.kind==`string`&&`value`in e))throw Error(`PostgreSQL did not return catalog facts`);return e}function postgresCatalogQuery(e,t=!1){let n=`'${e.replaceAll(`'`,`''`)}'`,columns=(e,t)=>`(SELECT jsonb_agg(a.attname ORDER BY k.ordinality) FROM unnest(${t}) WITH ORDINALITY k(num, ordinality) JOIN pg_catalog.pg_attribute a ON a.attrelid = ${e} AND a.attnum = k.num)`,action=e=>`CASE ${e} WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END`;return`WITH relations AS (
SELECT c.oid, c.relname FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = ${n} AND c.relkind IN ('r', 'p')
), attributes AS (
SELECT r.relname, a.attname, a.atttypid, a.atttypmod, a.attnotnull,
a.attidentity, a.attnum, a.attgenerated, a.attcollation,
pg_catalog.pg_get_expr(d.adbin, d.adrelid) AS default_expression
FROM relations r JOIN pg_catalog.pg_attribute a ON a.attrelid = r.oid
LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = r.oid AND d.adnum = a.attnum
WHERE a.attnum > 0 AND NOT a.attisdropped
), facts AS (
SELECT r.relname AS "table", 'table' AS kind, 'null'::jsonb AS value FROM relations r
UNION ALL SELECT a.relname, 'column', jsonb_build_object(
'name', a.attname, 'type', pg_catalog.format_type(a.atttypid, a.atttypmod),
'nullable', NOT a.attnotnull, 'identity', a.attidentity = 'd', 'position', a.attnum,
'default', regexp_replace(a.default_expression, '::(text|bigint|double precision)$', ''))
FROM attributes a
UNION ALL SELECT r.relname, CASE c.contype WHEN 'p' THEN 'primaryKey' ELSE 'unique' END,
${columns(`r.oid`,`c.conkey`)} FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid WHERE c.contype IN ('p', 'u')
UNION ALL SELECT r.relname, 'foreignKey', jsonb_build_object(
'columns', ${columns(`r.oid`,`c.conkey`)}, 'target', target.relname,
'targetColumns', ${columns(`c.confrelid`,`c.confkey`)},
'onUpdate', ${action(`c.confupdtype`)}, 'onDelete', ${action(`c.confdeltype`)},
'deferrable', c.condeferrable, 'deferred', c.condeferred)
FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid
JOIN pg_catalog.pg_class target ON target.oid = c.confrelid WHERE c.contype = 'f'
UNION ALL SELECT r.relname, 'indexes', to_jsonb((SELECT count(*) FROM pg_catalog.pg_index i WHERE i.indrelid = r.oid)) FROM relations r
UNION ALL SELECT r.relname, 'checks', to_jsonb((SELECT count(*) FROM pg_catalog.pg_constraint c WHERE c.conrelid = r.oid AND c.contype = 'c')) FROM relations r
${t?`UNION ALL SELECT r.relname, 'constraintDefinition', jsonb_build_object('name', c.conname, 'definition', pg_catalog.pg_get_constraintdef(c.oid)) FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid
UNION ALL SELECT r.relname, 'indexDefinition', jsonb_build_object('name', c.relname, 'definition', pg_catalog.pg_get_indexdef(i.indexrelid), 'valid', i.indisvalid) FROM relations r JOIN pg_catalog.pg_index i ON i.indrelid = r.oid JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid
UNION ALL SELECT a.relname, 'columnDefinition', jsonb_build_object('name', a.attname, 'default', a.default_expression, 'generated', a.attgenerated, 'identity', a.attidentity, 'collation', a.attcollation::regcollation::text) FROM attributes a
UNION ALL SELECT r.relname, 'triggerDefinition', jsonb_build_object('name', t.tgname, 'definition', pg_catalog.pg_get_triggerdef(t.oid), 'enabled', t.tgenabled, 'function', pg_catalog.pg_get_functiondef(t.tgfoid)) FROM relations r JOIN pg_catalog.pg_trigger t ON t.tgrelid = r.oid WHERE NOT t.tgisinternal
UNION ALL SELECT c.relname, 'viewDefinition', to_jsonb(pg_catalog.pg_get_viewdef(c.oid)) FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${n} AND c.relkind IN ('v', 'm')
UNION ALL SELECT c.cfgname, 'textSearchDefinition', jsonb_build_object('token', m.maptokentype, 'order', m.mapseqno, 'dictionary', d.dictname, 'namespace', dn.nspname)
FROM pg_catalog.pg_ts_config c JOIN pg_catalog.pg_namespace n ON n.oid = c.cfgnamespace
JOIN pg_catalog.pg_ts_config_map m ON m.mapcfg = c.oid JOIN pg_catalog.pg_ts_dict d ON d.oid = m.mapdict
JOIN pg_catalog.pg_namespace dn ON dn.oid = d.dictnamespace WHERE n.nspname = ${n} AND c.cfgname = 'openclaw_simple_unaccent'
UNION ALL SELECT p.proname, 'functionDefinition', to_jsonb(pg_catalog.pg_get_functiondef(p.oid)) FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = ${n} AND p.proname = 'openclaw_vector' AND p.prokind = 'f'`:``}
) SELECT coalesce(jsonb_agg(facts), '[]'::jsonb) AS catalog FROM facts`}var DatabaseSearchCapabilityUnavailableError=class extends Error{constructor(e,t){super(t??`Database ${e} search capability is unavailable.`),this.capability=e,this.code=`DATABASE_SEARCH_CAPABILITY_UNAVAILABLE`,this.name=`DatabaseSearchCapabilityUnavailableError`}};const pgSearchName=e=>`"${e.replaceAll(`"`,`""`)}"`,_u=`openclaw_simple_unaccent`;function postgresSearchVectorSql(e,t,n=1){let r=`coalesce(${t}, '')`;return`to_tsvector(${e}::regconfig, ${n===2?`regexp_replace(${r}, '[[:punct:]]+', ' ', 'g')`:r})`}function postgresSearchTextTriggerSql(e){let{table:t,field:n,sync:r}=e;return`CREATE FUNCTION ${r}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
NEW.openclaw_search := ${postgresSearchVectorSql(`format('%I.%I', TG_TABLE_SCHEMA, '${_u}')`,`NEW.${n}`,2)};
RETURN NEW;
END $$;
CREATE TRIGGER ${r} BEFORE INSERT OR UPDATE OF ${n} ON ${t} FOR EACH ROW EXECUTE FUNCTION ${r}();`}function postgresVectorDimensions(e){if(typeof e!=`number`||!Number.isInteger(e)||e<1||e>16e3)throw Error(`PostgreSQL vector capability unavailable: dimensions must be 1–16000; choose a supported embedding dimension and rebuild the derived index.`);return e}const vu={name:`database.postgres.search`,schemaDependent:!0};function admitPostgresSearch(e,t,n,r=1){let i=JSON.stringify(t);if(at(e,vu)?.some(e=>e.signature===i&&e.vectorSearchVersion>=r))return;let a=/* @__PURE__ */ new Set;Object.keys(t.text??{}).length&&a.add(`unaccent`),Object.values(t.text??{}).some(e=>e.postgres?.mode===`trigram`)&&a.add(`pg_trgm`),t.mode!==`keyword-only`&&Object.keys(t.vector??{}).length&&a.add(`vector`);for(let e of t.mode===`keyword-only`?[]:Object.values(t.vector??{}))postgresVectorDimensions(e.postgres?.dimensions);let s=t.extensionSchema??`public`,c=e.prepare(`SELECT a.name, e.extname, e.extversion, n.nspname FROM pg_catalog.pg_available_extensions a
LEFT JOIN pg_catalog.pg_extension e ON e.extname = a.name
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
WHERE a.name IN ('unaccent', 'pg_trgm', 'vector')`).all();for(let e of a){let t=c.find(t=>t.name===e);if(!t?.extname||t.nspname!==s){let n=t?t.extname?`Configure the store's extensionSchema as ${String(t.nspname)}, or have a database administrator relocate the extension; installation SQL is`:`Have a database administrator run`:`Install the server extension package for ${e}, then have a database administrator run`;throw new DatabaseSearchCapabilityUnavailableError(e===`vector`?`vector`:`fullText`,`PostgreSQL ${e} capability unavailable. ${n}: CREATE EXTENSION IF NOT EXISTS ${pgSearchName(e)} WITH SCHEMA ${pgSearchName(s)};${e===`vector`?` For keyword-only memory explicitly set memory.search.provider to "none".`:``}`)}if(e===`vector`&&r===2){let e=/^(\d+)\.(\d+)/.exec(String(t.extversion));if(!e||Number(e[1])===0&&Number(e[2])<7)throw new DatabaseSearchCapabilityUnavailableError(`vector`,`PostgreSQL binary vector search requires pgvector 0.7 or newer. Upgrade the server extension package, then have a database administrator run ALTER EXTENSION vector UPDATE before reopening the store.`)}}if(e.prepare(`SELECT coalesce(has_schema_privilege(to_regnamespace(?), 'CREATE'), has_database_privilege(current_database(), 'CREATE'))::int AS allowed`).get(n)?.allowed!==1)throw Error(`PostgreSQL search capability unavailable: insufficient CREATE privilege. Have the database owner grant CREATE on schema ${pgSearchName(n)} (or on the database before initial admission).`);return()=>publishPostgresSearch(e,t,r)}function publishPostgresSearch(e,t,n=1){let r=JSON.stringify(t),i=at(e,vu)??[],a=i.find(e=>e.signature===r);ce(e,vu,[...i.filter(e=>e.signature!==r),{signature:r,vectorSearchVersion:a?.vectorSearchVersion===2?2:n}])}function postgresVectorDecoderSql(e,t=1,n=!1){let r=pgSearchName(e);return t===1?`CREATE ${n?`OR REPLACE `:``}FUNCTION openclaw_vector(bytes bytea, dimensions integer) RETURNS ${r}.vector
LANGUAGE plpgsql IMMUTABLE STRICT AS $$
DECLARE vals real[] := '{}'; bits bigint; exponent integer; fraction double precision; value double precision;
BEGIN
IF octet_length(bytes) <> dimensions * 8 THEN RAISE EXCEPTION 'embedding dimension mismatch; rebuild the derived vector index'; END IF;
FOR i IN 0..dimensions-1 LOOP
bits := 0;
FOR j IN 0..7 LOOP bits := bits | (get_byte(bytes, i*8+j)::bigint << (j*8)); END LOOP;
exponent := ((bits >> 52) & 2047)::integer;
IF exponent = 2047 THEN RAISE EXCEPTION 'embedding must be finite'; END IF;
fraction := (bits & 4503599627370495)::double precision / 4503599627370496;
IF exponent < 873 OR (exponent = 873 AND fraction = 0) THEN value := 0;
ELSE value := (1 + fraction) * power(2::double precision, exponent - 1023); END IF;
IF bits < 0 THEN value := -value; END IF;
vals := array_append(vals, value::real);
END LOOP;
RETURN vals::${r}.vector;
END $$;`:`CREATE ${n?`OR REPLACE `:``}FUNCTION openclaw_vector(bytes bytea, dimensions integer) RETURNS ${r}.vector
LANGUAGE plpgsql IMMUTABLE STRICT AS $$
DECLARE vals double precision[]; first_nonfinite integer;
BEGIN
IF octet_length(bytes) <> dimensions * 8 THEN RAISE EXCEPTION 'embedding dimension mismatch; rebuild the derived vector index'; END IF;
-- Flatten TOAST once: repeated get_byte calls otherwise detoast the entire embedding.
bytes := bytes || '\\x'::bytea;
WITH bits AS MATERIALIZED (
SELECT i,
get_byte(bytes, i*8)::bigint |
(get_byte(bytes, i*8+1)::bigint << 8) |
(get_byte(bytes, i*8+2)::bigint << 16) |
(get_byte(bytes, i*8+3)::bigint << 24) |
(get_byte(bytes, i*8+4)::bigint << 32) |
(get_byte(bytes, i*8+5)::bigint << 40) |
(get_byte(bytes, i*8+6)::bigint << 48) |
(get_byte(bytes, i*8+7)::bigint << 56) AS b
FROM generate_series(0, dimensions-1) AS i
), parts AS (
SELECT i, b, ((b >> 52) & 2047)::integer AS exponent,
(b & 4503599627370495)::double precision / 4503599627370496 AS fraction
FROM bits
)
SELECT coalesce(array_agg(
CASE WHEN b < 0 THEN -1::double precision ELSE 1::double precision END *
CASE WHEN exponent = 2047 OR exponent < 873 OR (exponent = 873 AND fraction = 0)
THEN 0::double precision
ELSE (1 + fraction) * power(2::double precision, exponent - 1023)
END ORDER BY i
), ARRAY[]::double precision[]), min(i) FILTER (WHERE exponent = 2047)
INTO vals, first_nonfinite FROM parts;
IF first_nonfinite IS NOT NULL THEN
-- Preserve the old left-to-right overflow versus nonfinite error precedence.
PERFORM vals[1:first_nonfinite]::real[];
RAISE EXCEPTION 'embedding must be finite';
END IF;
RETURN vals::real[]::${r}.vector;
END $$;`}function postgresSearchSql(e,t,n={},r=1,i=1,a=1){let s=pgSearchName(e.extensionSchema??`public`),c=`${pgSearchName(t)}.${pgSearchName(_u)}`,l=`'${c.replaceAll(`'`,`''`)}'`,u=[];Object.keys(e.text??{}).length&&!n.text&&u.push(`CREATE TEXT SEARCH CONFIGURATION ${c} (COPY = pg_catalog.simple);
ALTER TEXT SEARCH CONFIGURATION ${c} ALTER MAPPING FOR hword, hword_part, word, numword, numhword, hword_numpart WITH ${s}.unaccent, pg_catalog.simple;`);for(let t of Object.values(e.text??{})){if(!t.postgres||t.fields.length!==1)throw Error(`PostgreSQL text index requires one field and a declared source identity`);let e=pgSearchName(t.table),n=pgSearchName(t.fields[0]);u.push(a===2?`ALTER TABLE ${e} ADD COLUMN openclaw_search tsvector;
${postgresSearchTextTriggerSql({table:e,field:n,sync:pgSearchName(`${t.table}_search_sync`)})}
UPDATE ${e} SET openclaw_search = ${postgresSearchVectorSql(l,n,2)};`:`ALTER TABLE ${e} ADD COLUMN openclaw_search tsvector GENERATED ALWAYS AS (${postgresSearchVectorSql(l,n)}) STORED;`),u.push(`CREATE INDEX ${pgSearchName(`${t.table}_search_gin`)} ON ${e} USING gin(openclaw_search);`),t.postgres.mode===`trigram`&&u.push(`CREATE INDEX ${pgSearchName(`${t.table}_trgm_gin`)} ON ${e} USING gin(${n} ${s}.gin_trgm_ops);`)}if(e.mode===`keyword-only`)return u.join(`
`);Object.keys(e.vector??{}).length&&!n.vector&&u.push(postgresVectorDecoderSql(e.extensionSchema??`public`,r));for(let t of Object.values(e.vector??{})){let e=t.postgres;if(!e)throw Error(`PostgreSQL vector index requires a canonical embedding source`);let n=pgSearchName(t.table),r=pgSearchName(e.source),a=pgSearchName(e.key),c=pgSearchName(e.embedding),l=postgresVectorDimensions(e.dimensions),d=`INSERT INTO ${n}(id, embedding) SELECT ${a}, openclaw_vector(${c}, ${l}) FROM ${r} WHERE octet_length(${c}) > 0`,f=i===2?`, embedding_bits bit(${l}) GENERATED ALWAYS AS (CASE WHEN ${s}.vector_norm(embedding) > 0 THEN ${s}.binary_quantize(embedding)::bit(${l}) ELSE NULL END) STORED`:``;u.push(`CREATE TABLE ${n} (id TEXT PRIMARY KEY REFERENCES ${r}(${a}) ON UPDATE CASCADE ON DELETE CASCADE, embedding ${s}.vector(${l}) NOT NULL${f});
CREATE FUNCTION ${pgSearchName(`${t.table}_sync`)}() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'UPDATE' AND OLD.${c} IS NOT DISTINCT FROM NEW.${c} THEN RETURN NEW; END IF;
IF octet_length(NEW.${c}) > 0 THEN
INSERT INTO ${n}(id, embedding) VALUES (NEW.${a}, openclaw_vector(NEW.${c}, ${l}))
ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding;
ELSE
DELETE FROM ${n} WHERE id = NEW.${a};
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER ${pgSearchName(`${t.table}_sync`)} AFTER INSERT OR UPDATE OF ${c} ON ${r} FOR EACH ROW EXECUTE FUNCTION ${pgSearchName(`${t.table}_sync`)}();
${d};`)}return u.join(`
`)}function postgresStoreNamespace(e,t,n){return`${e}_${t}_${n.replaceAll(`-`,``).slice(0,16)}`}const yu=`CREATE TABLE openclaw_schema_meta (
store TEXT PRIMARY KEY, version BIGINT NOT NULL, store_id TEXT NOT NULL,
fingerprint TEXT, ddl_hash TEXT, server_major BIGINT)`,bu=`Use a compatible OpenClaw binary or restore the matching PostgreSQL schema and anchor; do not edit schema metadata.`,quote=e=>`"${e.replaceAll(`"`,`""`)}"`,hash$1=e=>nn(`sha256`).update(e).digest(`hex`),xu=/* @__PURE__ */ new WeakMap,Su={name:`database.postgres.schema`,schemaDependent:!0},getAdmittedPostgresSchema=e=>at(e,Su),retainPostgresSchema=(e,t)=>{let{postgresMigrations:n,...r}=t;ce(e,Su,r)};function admitPostgresCapabilities(e){let t=xu.get(e);if(t)return t;let n=e.prepare(`SELECT current_setting('server_version_num')::int AS version, current_setting('server_encoding') AS server_encoding, current_setting('client_encoding') AS client_encoding`).get();if(!n||typeof n.version!=`number`||n.version<16e4||n.server_encoding!==`UTF8`||n.client_encoding!==`UTF8`)throw Error(`PostgreSQL requires version 16 or newer and UTF8 server/client encoding; upgrade the server or port to a UTF8 database and set client_encoding=UTF8.`);let r={serverMajor:Math.floor(n.version/1e4),serverEncoding:`UTF8`,clientEncoding:`UTF8`};return xu.set(e,r),r}function readPostgresSchema(e,t,n){let r=e.query(`WITH captured AS (${postgresCatalogQuery(t,!0)})
SELECT catalog::text, to_jsonb(meta)::text AS metadata FROM captured
CROSS JOIN ${quote(t)}.openclaw_schema_meta meta WHERE meta.store = ?`,[n]).rows[0];if(!r||typeof r.catalog!=`string`||typeof r.metadata!=`string`)throw Error(`Missing PostgreSQL catalog or metadata. ${bu}`);let i=JSON.parse(r.metadata);return{catalog:readPostgresCatalog(JSON.parse(r.catalog)),metadata:i}}function withPostgresSearchExtensions(e,t){return{...e,searchExtensions:JSON.parse(t.metadata.search_extensions??`{}`)}}function postgresSchemaFingerprint(e,t){let n=e.filter(e=>e.table!==`openclaw_schema_meta`).map(e=>JSON.stringify(e)).toSorted().join(`
`);if(!t)return hash$1(n);let r=JSON.stringify(t.from).slice(1,-1),i=JSON.stringify(quote(t.from)).slice(1,-1),a=JSON.stringify(t.to).slice(1,-1);return hash$1(n.replaceAll(`${i}.`,`${r}.`).replaceAll(r,a))}function postgresSchemaSql(e,t,n){let r=new Set(n?.filter(e=>e.kind===`table`).map(e=>e.table)),i=e.postgresFragments?.filter(e=>n?e.tables.some(e=>r.has(e)):e.activation===`version-additive`)??[],a=/* @__PURE__ */ new Map,add=t=>{if(!a.has(t.id)){for(let n of t.dependencies){let t=e.postgresFragments?.find(e=>e.id===n);if(!t)throw Error(`Missing PostgreSQL fragment dependency ${n}`);add(t)}a.set(t.id,t.sql)}};i.forEach(add);let s=[e.search,...Object.values(e.searchExtensions??{})].filter(e=>e!==void 0),c={text:!1,vector:!1},l=s.map(n=>{let r=postgresSearchSql(n,t,c,e.postgresVectorDecoderVersion,e.postgresVectorSearchVersion,e.postgresTextSearchVersion);return c.text||=Object.keys(n.text??{}).length>0,c.vector||=n.mode!==`keyword-only`&&Object.keys(n.vector??{}).length>0,`;\n${r}`}),u=e.postgresWithoutOptionalColumn;return[(u&&n&&!hasPostgresCatalogColumn(n,u.table,u.column)?u.sql:e.postgres)??``,...a.values(),...l].join(`
`)}function postgresSchemaHash(e,t){return hash$1(postgresSchemaSql(e,`openclaw_schema`,t))}function recordPostgresSchema(e,t,n,r){if(!e.isTransaction)throw Error(`PostgreSQL schema publication requires the owner's writer transaction`);let i=r??readPostgresSchema(e,t,n.id),a=postgresSchemaHash(n,i.catalog);return e.prepare(`UPDATE openclaw_schema_meta SET fingerprint = ?, ddl_hash = ?, server_major = ? WHERE store = ?`).run(postgresSchemaFingerprint(i.catalog),a,admitPostgresCapabilities(e).serverMajor,n.id),a}function verifyPostgresSchema(e,t,n,r,i=!1,a=!1){let s=postgresSchemaFingerprint(r.catalog),c=postgresSchemaHash(n,r.catalog),{metadata:l}=r,u=admitPostgresCapabilities(e).serverMajor;if(l.server_major===u&&l.fingerprint&&l.fingerprint!==s)throw Error(`PostgreSQL schema drift detected. ${bu}`);if(l.server_major===u&&l.fingerprint&&l.ddl_hash===c)return c;if(a)throw Error(`Read-only PostgreSQL admission requires a matching schema seal. ${bu}`);if(i)e.runTransaction(()=>verifyPostgresSchemaDefinition(e,t,n,r));else return verifyAndRecordPostgresSchema(e,t,n,r),c}function verifyPostgresSchemaDefinition(e,t,n,r){let i=postgresSchemaFingerprint(r.catalog,{from:t,to:t}),a=`openclaw_check_${an().replaceAll(`-`,``)}`;e.exec(`CREATE SCHEMA ${quote(a)}`);try{e.exec(`SET LOCAL search_path TO ${quote(a)}`),e.exec(postgresSchemaSql(n,a,r.catalog));let s=e.query(`SELECT catalog::text FROM (${postgresCatalogQuery(a,!0)}) captured`).rows[0];if(postgresSchemaFingerprint(readPostgresCatalog(JSON.parse(String(s?.catalog))),{from:a,to:t})!==i)throw Error(`PostgreSQL schema drift detected against generated DDL. ${bu}`)}finally{e.exec(`SET LOCAL search_path TO ${quote(t)}`),e.exec(`DROP SCHEMA ${quote(a)} CASCADE`)}}function verifyAndRecordPostgresSchema(e,t,n,r=readPostgresSchema(e,t,n.id)){return e.runTransaction(()=>{verifyPostgresSchemaDefinition(e,t,n,r),r.metadata.ddl_hash||e.exec(`ALTER TABLE openclaw_schema_meta ADD COLUMN IF NOT EXISTS fingerprint TEXT, ADD COLUMN IF NOT EXISTS ddl_hash TEXT, ADD COLUMN IF NOT EXISTS server_major BIGINT`),recordPostgresSchema(e,t,n,r)}),r}const Cu=`Use the matching OpenClaw version or restore the matching PostgreSQL schema and anchor.`;function getPostgresPhysicalFacts(e,t){if(b(e)&&e.isTransaction&&!t?.refresh){let t=we.get(e);if(t?.schema.store===`agent`)return e.isOpen&&e.anchor.isOpen?t.schema:void 0}return at(e,gu,t)}function admitPostgresPhysicalFacts(e){let t=getPostgresPhysicalFacts(e.db);if(t){if(t.version!==e.version||t.storeId!==e.storeId||t.namespace!==e.namespace||t.store!==e.store)throw Error(`PostgreSQL metadata identity or version mismatch. ${Cu}`);if(e.requireSealedSchema){let n=e.schema,r=getAdmittedPostgresSchema(e.db);if(!n||!t.schemaHash||t.schemaHash!==postgresSchemaHash({...n,searchExtensions:r?.searchExtensions},t.catalog))throw Error(`Read-only PostgreSQL admission requires a matching schema seal. ${Cu}`)}return t}let n=admitPostgresCapabilities(e.db),r;try{r=readPostgresSchema(e.db,e.namespace,e.store)}catch(e){throw Error(`Cannot read PostgreSQL catalog or metadata. ${Cu}`,{cause:e})}let{metadata:i,catalog:a}=r;if(i.version!==e.version||i.store_id!==e.storeId)throw Error(`PostgreSQL metadata identity or version mismatch. ${Cu}`);let s;if(e.schema){let t=withPostgresSearchExtensions(e.schema,r);s=e.recordSchema?recordPostgresSchema(e.db,e.namespace,t,r):verifyPostgresSchema(e.db,e.namespace,t,r,e.preserveSchemaSeal,e.requireSealedSchema),retainPostgresSchema(e.db,t)}let c={engine:`postgres`,admissionId:an(),store:e.store,namespace:e.namespace,storeId:i.store_id,version:i.version,schemaHash:s,capabilities:n,catalog:a};return ce(e.db,gu,c),c}const wu=y(Symbol.for(`openclaw.sqlitePinnedReadSnapshots`),()=>/* @__PURE__ */ new WeakMap);function getSqlitePinnedReadSnapshot(e){return wu.get(e)}function runSqliteSchemaReadSnapshotSync(e,t){let n=wu.get(e);for(let r=0;;r+=1){wu.set(e,n??{});try{let n=executeWithCachedStatement(e,`PRAGMA schema_version`,[],e=>{let n;try{let i;try{n=e.iterate(),i=n.next()}catch(e){if(!Zt&&r<4&&(ft(e)===261||Tt(e)===`SQLITE_BUSY_RECOVERY`))return{retry:!0};throw e}if(i.done)throw Error(`SQLite schema_version query returned no row`);return{retry:!1,value:t(Number(i.value.schema_version))}}finally{n?.return?.()}});if(!n.retry)return n.value}finally{n||wu.delete(e)}}}const Tu={name:`sqlite-schema`,writer:`connection`,lifetime:`process`,schemaDependent:!0,read:e=>s(e)?e:void 0},Eu={name:`sqlite-text-encoding`,writer:`connection`,lifetime:`process`,read:e=>typeof e==`string`?e:void 0};function readSqliteTextEncoding(e){let t=at(e,Eu);if(t!==void 0)return t;let n=executeWithCachedStatement(e,`PRAGMA encoding`,[],e=>e.get());if(typeof n?.encoding!=`string`)throw Error(`SQLite did not report its text encoding`);return n.encoding}function readSqliteSchemaObjects(e){return executeWithCachedStatement(e,`SELECT type, name, tbl_name, sql FROM main.sqlite_schema WHERE type IN ('table', 'view', 'index', 'trigger')`,[],e=>e.all())}function captureSqliteSchemaFacts(e,t=0,n){let r=at(e,Eu),i=runSqliteSchemaReadSnapshotSync(e,i=>{let a=executeWithCachedStatement(e,`PRAGMA user_version`,[],e=>e.get()),s=Number(a?.user_version??0);n?.(s);let c=r??readSqliteTextEncoding(e),l=readSqliteSchemaObjects(e),u={admissionId:an(),revision:t,userVersion:s,textEncoding:c,schemaVersion:i,tables:/* @__PURE__ */ new Set,views:/* @__PURE__ */ new Set,tableSql:/* @__PURE__ */ new Map,indexes:/* @__PURE__ */ new Set,indexDefinitions:/* @__PURE__ */ new Map,triggers:/* @__PURE__ */ new Map};for(let e of l){if(typeof e.name!=`string`)continue;let t=typeof e.sql==`string`?e.sql:null;switch(e.type){case`table`:u.tables.add(e.name),u.tableSql.set(e.name,t);break;case`view`:u.views.add(e.name);break;case`index`:u.indexes.add(e.name),typeof e.tbl_name==`string`&&u.indexDefinitions.set(e.name,{table:e.tbl_name,sql:t});break;case`trigger`:typeof e.tbl_name==`string`&&u.triggers.set(e.name,{table:e.tbl_name,sql:t})}}return u});return r===void 0&&(i.tables.size>0||i.views.size>0)&&ce(e,Eu,i.textEncoding),i}function captureTrackedSqliteSchemaFacts(e,t,n){t.capturing=!0;try{return captureSqliteSchemaFacts(e,t.revision,n)}finally{t.capturing=!1}}function invalidateTrackedSqliteSchemaFacts(e){e.revision+=1,e.facts=void 0}function observeSchemaLifetime(e,t,n){t.snapshot&&t.snapshot!==n&&(e.isTransaction&&t.transactionCatalogBound||invalidateTrackedSqliteSchemaFacts(t),t.snapshot=void 0,t.qualifiedSnapshot=void 0);let r=Le(e),i=t.processRevision!==void 0&&t.processRevision!==r;return i&&!t.transactionalSchema&&(e.isTransaction&&t.transactionCatalogBound||t.facts&&n&&t.qualifiedSnapshot===n)?(t.transactionalFacts||=e.isTransaction,t.snapshot=n,!1):(t.processRevision=r,i&&invalidateTrackedSqliteSchemaFacts(t),(t.transactionalSchema||t.transactionalTempSchema||t.transactionalFacts)&&!e.isTransaction&&(t.transactionalSchema&&pt(e),invalidateTrackedSqliteSchemaFacts(t),t.transactionalSchema=!1,t.transactionalTempSchema=!1,t.transactionalFacts=!1),i)}function prepareSqliteTempTrackingSchema(e,t){let{createSql:n,objects:r}=prepareTranscriptIndexSchema(t),i=new Map(r.map(e=>[e.name.toLowerCase(),e])),a=r.map(e=>e.name),s=r.filter(e=>e.type===`table`).map(e=>e.name),c=[...a,...s],l=executeWithCachedStatement(e,`SELECT type, name, tbl_name, sql FROM temp.sqlite_schema
WHERE name COLLATE NOCASE IN (${a.map(()=>`?`).join(`,`)})
OR (type = 'trigger' AND tbl_name COLLATE NOCASE IN (${s.map(()=>`?`).join(`,`)}))`,c,e=>e.all(...c)),u=l.some(e=>{let t=typeof e.name==`string`?i.get(e.name.toLowerCase()):void 0;return!t||e.type!==t.type||e.tbl_name!==t.table||typeof e.sql!=`string`||Nt(e.sql)!==Nt(t.sql)});return{sql:n(new Set(l.flatMap(e=>e.type===`trigger`&&typeof e.name==`string`?[e.name.toLowerCase()]:[]))),unexpected:u}}function prepareTranscriptIndexSchema(e){let t=Re(e.statusTable),n=Re(e.pendingTable),r=Re(e.pendingIndex),i=`${t} (
id INTEGER PRIMARY KEY CHECK (id = 1), sibling_write_revision INTEGER NOT NULL,
schema_version INTEGER NOT NULL, complete INTEGER NOT NULL, after_session TEXT,
completed_traversals INTEGER NOT NULL
) STRICT`,a=`${n} (session_id TEXT PRIMARY KEY, state INTEGER NOT NULL) STRICT`,s=`${r} ON ${n}(state, session_id)`,c=e.observedTables.flatMap(e=>[`INSERT`,`UPDATE`,`DELETE`].map(t=>{let r=`openclaw_${e}_projection_${t.toLowerCase()}`,i=t===`UPDATE`?[`OLD`,`NEW`]:[t===`DELETE`?`OLD`:`NEW`];return{name:r,table:e,definition:`TRIGGER ${Re(r)} AFTER ${t} ON main.${Re(e)}
WHEN ${i.map(e=>`NOT EXISTS (
SELECT 1 FROM ${n}
WHERE session_id = ${e}.session_id AND state = 0
)`).join(` OR `)} BEGIN
${i.map(e=>`
UPDATE ${n} SET state = 0 WHERE session_id = ${e}.session_id;
INSERT INTO ${n}
SELECT ${e}.session_id, 0 WHERE NOT EXISTS (
SELECT 1 FROM ${n} WHERE session_id = ${e}.session_id
);`).join(`
`)}
END`}}));return{createSql:e=>`
CREATE TEMP TABLE IF NOT EXISTS ${i};
INSERT INTO temp.${t} VALUES (1, -1, -1, 0, NULL, 0)
ON CONFLICT(id) DO UPDATE SET sibling_write_revision = -1;
CREATE TEMP TABLE IF NOT EXISTS ${a};
CREATE INDEX IF NOT EXISTS temp.${s};
${c.map(({name:t,definition:n})=>`${e.has(t.toLowerCase())?`DROP TRIGGER IF EXISTS temp.${Re(t)};`:``}CREATE TEMP ${n};`).join(`
`)}
`,objects:[{name:e.statusTable,type:`table`,table:e.statusTable,sql:`CREATE TABLE ${i}`},{name:e.pendingTable,type:`table`,table:e.pendingTable,sql:`CREATE TABLE ${a}`},{name:e.pendingIndex,type:`index`,table:e.pendingTable,sql:`CREATE INDEX ${s}`},...c.map(e=>({name:e.name,type:`trigger`,table:e.table,sql:`CREATE ${e.definition}`}))]}}function beginPostgresReadSnapshotScope(e){let t=getPostgresPhysicalFacts(e),n=Oe(e);return t&&n!==void 0&&we.set(e,{schema:t,writeRevision:n,mutationRevision:e.mutationRevision,snapshot:{}}),()=>we.delete(e)}function invalidateSqliteSchemaFacts(e){Le(e),invalidateSchemaFacts(e,!0)}function invalidateSchemaFacts(e,t,n=`main`,r=n!==`temp`){let i=St.get(e);if(i){let a=n===`main`;if(i.isolatedTempTables.clear(),e.isTransaction&&(i.transactionMutationRevision=void 0),a&&ze(e),a&&e.isTransaction&&!i.transactionalSchema&&(i.transactionBaseFacts=i.facts),r)for(let e of i.mutationListeners??[])e(void 0);invalidateTrackedSqliteSchemaFacts(i),i.transactionalSchema||=a&&e.isTransaction,i.transactionalTempSchema||=n===`temp`&&e.isTransaction,i.pendingSchema||=a&&i.nativeDepth>0,t&&a&&!e.isTransaction&&i.nativeDepth===0&&pt(e)}}function trackSchemaChanges(e,t,n,r){let settle=(n=!1,r=!1)=>{if(r){let n=getSqlitePinnedReadSnapshot(e),r=n&&(t.transactionalSchema?t.transactionBaseFacts:t.facts);tt(e),invalidateTrackedSqliteSchemaFacts(t),t.transactionalSchema=!1,t.transactionalTempSchema=!1,t.transactionalFacts=!1,n&&t.admitted&&!t.authorizerActive&&(t.facts=r?{...r,revision:t.revision}:captureTrackedSqliteSchemaFacts(e,t),t.snapshot=n,t.qualifiedSnapshot=n),t.transactionBaseFacts=void 0}else(n||!e.isTransaction)&&(t.transactionalSchema||t.transactionalTempSchema||t.transactionalFacts)&&(t.transactionalSchema&&pt(e),invalidateTrackedSqliteSchemaFacts(t),t.transactionalSchema&&=e.isTransaction,t.transactionalTempSchema&&=e.isTransaction,t.transactionalFacts=!1)},i=Xe(e,n,(n,i)=>{if(t.settling)return{finish:()=>{}};let{control:a,dataChange:s}=n,c=a?.outerRollback!==!0&&n.schemaChange,l=n.mainSchemaChange&&a?.outerRollback!==!0;ve(e,t);let u=i===`bind`?void 0:getSqlitePinnedReadSnapshot(e),d=i!==`bind`&&!u&&!t.capturing?{}:void 0;if(u&&u!==t.snapshot&&!t.capturing){if(e.isTransaction&&(t.transactionRead||t.transactionCatalogBound)&&t.processRevision!==Le(e))t.transactionCatalogBound||invalidateTrackedSqliteSchemaFacts(t),t.transactionalFacts=!0;else if(observeSchemaLifetime(e,t,void 0),!t.facts&&!t.transactionalSchema){let n=at(e,Tu);n&&(t.facts={...n,revision:t.revision})}t.snapshot=u,t.qualifiedSnapshot=u}t.nativeDepth===0&&settle();let f=e.isTransaction;if((r||t.processRevision===void 0)&&!f&&(a?.kind===`BEGIN`||a?.kind===`SAVEPOINT`)){let n=Le(e);t.processRevision??=n}let p=!f&&a?.kind===`BEGIN`&&a.single?t.mutationRevision:void 0;!f&&a?.kind===`BEGIN`&&t.admitted&&getAdmittedSqliteSchemaFacts(e);let m=!!a&&!Je(a,f),h=a?.kind===`ROLLBACK`,g=h&&t.transactionalSchema&&!a.outerRollback,v=c&&!n.temporaryTableSchemaChange||h&&t.transactionalSchema,ee=l||g?`main`:h?t.transactionalTempSchema&&!t.transactionalSchema?`temp`:`rollback`:n.temporaryTableSchemaChange?`temp`:`local`;h&&tt(e),(c||h)&&invalidateSchemaFacts(e,!1,ee,v),(s||n.temporaryTableSchemaChange||a?.kind===`ROLLBACK`)&&(t.mutationRevision+=1),i!==`bind`&&f&&!a&&!t.transactionCatalogBound&&(t.transactionRead=!0);let te=c||s||a!==void 0,ne=n.temporaryWriteTables?.every(e=>t.isolatedTempTables.has(e));(s&&!ne||l)&&vt(e,l||t.nativeDepth>0),te&&(t.mutationDepth+=1),t.nativeDepth+=1;let re=jt(e),y=t.schemaMutationRevision;return l&&(t.schemaMutationRevision+=1),t.pendingSchema||=l,d&&t.unmanagedSnapshots.add(d),{stepped:()=>{u&&t.facts&&e.isTransaction&&(t.transactionCatalogBound=!0)},finish:(n,r,i)=>{if(d&&t.unmanagedSnapshots.delete(d)&&t.iteratorFacts&&(invalidateTrackedSqliteSchemaFacts(t),t.iteratorFacts=!1),re(),--t.nativeDepth,te&&--t.mutationDepth,!e.isOpen)return;(c||h)&&(h&&tt(e),invalidateSchemaFacts(e,!1,ee,v));let s=n&&f&&a?.outerRollback===!0&&!e.isTransaction&&!l&&t.schemaMutationRevision===y;if(s&&(settle(!1,!0),t.pendingSchema=!1),t.nativeDepth===0){t.settling=!0;try{let i=t.pendingSchema||t.transactionalSchema;!s&&t.pendingSchema&&!e.isTransaction&&!t.transactionalSchema&&pt(e),s||settle(m),i&&!e.isTransaction&&!s&&(invalidateTrackedSqliteSchemaFacts(t),n||tt(e),t.admitted&&!t.authorizerActive&&!r&&(getAdmittedSqliteSchemaFacts(e),t.transactionBaseFacts=void 0)),t.pendingSchema=!1}finally{t.settling=!1}}Ke(e,t,f,m,n,p),t.mutationDepth===0&&!e.isTransaction&&Ot(e,i),t.transactionRead||=e.isTransaction&&!(!a||a.single)}}});Se(e,()=>{Ot(e),je(e)}),t.installTempTrackingSchema=r=>{let{sql:a,unexpected:s}=prepareSqliteTempTrackingSchema(e,r);try{if(i(()=>n.DatabaseSync.prototype.exec.call(e,a),{schemaChange:s,mainSchemaChange:s,temporaryTableSchemaChange:!1,dataChange:!0,temporaryWriteTables:[],control:void 0}),!s)for(let e of[r.statusTable,r.pendingTable])t.isolatedTempTables.add(e.toLowerCase())}catch(t){throw invalidateSqliteSchemaFacts(e),t}},typeof e.setAuthorizer==`function`&&(e.setAuthorizer=r=>{n.DatabaseSync.prototype.setAuthorizer.call(e,r),t.authorizerActive=r!==null,Ue(e,t.authorizerActive),invalidateTrackedSqliteSchemaFacts(t)}),registerNodeSqliteDisposeCallback(e,()=>{invalidateTrackedSqliteSchemaFacts(t),t.readRevision=void 0,t.transactionSnapshot=void 0})}function runSqliteReadOperationSync(e,t){if(b(e))return t();let n=St.get(e);if(!n||n.authorizerActive)return t();n.readDepth+=1;try{return n.admitted&&getAdmittedSqliteSchemaFacts(e),t()}finally{--n.readDepth}}function trackSqliteSchema(e,t,n=!0){if(!St.has(e)){let r={admitted:!1,publicationReady:!1,revision:0,readDepth:0,mutationRevision:0,mutationDepth:0,transactionOpen:e.isOpen&&e.isTransaction,transactionRead:!1,transactionCatalogBound:!1,nativeDepth:0,pendingSchema:!1,schemaMutationRevision:0,settling:!1,capturing:!1,transactionalSchema:!1,transactionalTempSchema:!1,transactionalFacts:!1,authorizerActive:!1,unmanagedSnapshots:/* @__PURE__ */ new Set,isolatedTempTables:/* @__PURE__ */ new Set,iteratorFacts:!1};St.set(e,r),trackSchemaChanges(e,r,t,n);let i=Le(e,{existingOnly:!0}),a=at(e,Tu,{existingOnly:!0});a&&(r.admitted=!0,r.facts={...a,revision:r.revision},r.processRevision=i)}}function isSqliteSchemaAdmissionCold(e){let t=St.get(e);return!(!t||t.admitted||t.authorizerActive)}function admitSqliteSchema(e,t){let n=St.get(e);if(!n)throw Error(`SQLite schema admission requires a connection tracked from native open`);n.admitted=!0;let r=getAdmittedSqliteSchemaFacts(e,t);!n.publicationReady&&r&&n.unmanagedSnapshots.size===0&&!getSqlitePinnedReadSnapshot(e)&&(n.publicationReady=de(e))}function getAdmittedSqliteSchemaFacts(e,t){if(b(e))return;let n=St.get(e);if(!n?.admitted||n.authorizerActive)return;let r=getSqlitePinnedReadSnapshot(e),i=e.isTransaction&&(n.transactionRead||n.transactionCatalogBound)&&n.processRevision!==Le(e)||n.unmanagedSnapshots.size>0,a=observeSchemaLifetime(e,n,r);if(n.facts)t?.(n.facts.userVersion);else{n.snapshot=r,n.transactionalFacts||=e.isTransaction&&(n.readDepth===0||a);let s=i||!!r||n.transactionalSchema,c=n.transactionalSchema||s?void 0:at(e,Tu);if(c)return t?.(c.userVersion),n.facts={...c,revision:n.revision},n.facts;let l=Le(e);n.facts=captureTrackedSqliteSchemaFacts(e,n,t),n.iteratorFacts||=n.unmanagedSnapshots.size>0,n.qualifiedSnapshot=r,n.transactionCatalogBound||=e.isTransaction,s||ce(e,Tu,n.facts,{schemaRevision:l})}return n.facts}function resolveSqliteFilesystemPath(e){return process.platform===`win32`?x.toNamespacedPath(x.resolve(e)):e}function resolveNodeSqliteLocation(e){return e===``||e===`:memory:`||e.startsWith(`file:`)?e:resolveSqliteFilesystemPath(e)}function resolveSqliteFileUriPath(e,t){if(t===`win32`){let t=x.win32.toNamespacedPath(x.win32.resolve(e));return`file:${encodeURIComponent(t)}`}return bn(x.resolve(e)).href}function resolveReadOnlyShmSqliteFileUri(e,t=process.platform){return`${resolveSqliteFileUriPath(e,t)}?mode=ro&readonly_shm=1`}function resolveExistingSqliteFileUri(e,t=process.platform){return`${resolveSqliteFileUriPath(e,t)}?mode=rw`}function resolveImmutableSqliteFileUri(e,t=process.platform){return`${resolveSqliteFileUriPath(e,t)}?mode=ro&immutable=1`}function openNodeSqliteDatabase(e,t,n){let r=nt(),i=resolveNodeSqliteLocation(e),a=t?.open===!1?void 0:me(i,{create:t?.readOnly!==!0});if(t?.open!==!1&&n!==void 0&&a!==n)throw Error(`SQLite staging database changed before native open`);let s=new r.DatabaseSync(i,t??{});if(s.isOpen)try{dt(s,a)}catch(e){throw s.close(),e}return s.open=()=>{let e=me(i,{create:t?.readOnly!==!0});if(n!==void 0&&e!==n)throw Error(`SQLite staging database changed before native open`);r.DatabaseSync.prototype.open.call(s);try{dt(s,e)}catch(e){throw s.close(),e}},trackSqliteSchema(s,{DatabaseSync:r.DatabaseSync,StatementSync:r.StatementSync},t?.readOnly!==!0),s.isOpen&&t?.timeout!==void 0&&rememberSqliteBusyTimeout(s,Math.max(0,t.timeout)),It().explicitSqliteCloseReleasesNativeResources||registerNodeSqliteDisposeCallback(s,()=>{}),qe(s),s}function classifyGatewayLockProcessNamespace(e,t,n){if(e&&n&&isLegacyGatewayLeaseLock(e)){let t=Date.now(),r=Date.parse(e.createdAt);if(!Number.isFinite(r)||t-r<=3e5)return`unknown`;try{let r=openNodeSqliteDatabase(resolveReadOnlyShmSqliteFileUri(n),{readOnly:!0});try{let n=getNodeSqliteKysely(r),{rows:i}=executeSqliteQuerySync(r,{compile:()=>Q`SELECT expires_at AS expiresAt
FROM ${Q`state_leases NOT INDEXED`}
WHERE scope = ${`gateway-owner`} AND owner = ${e.ownerId}`.compile(n)});return i.every(e=>typeof e.expiresAt==`number`&&e.expiresAt<=t)?`dead`:`unknown`}finally{r.close()}}catch{return`unknown`}}if((process.platform===`win32`||process.platform===`darwin`)&&e&&e.processNamespace===void 0&&t){try{if(Date.now()-S.statSync(t).mtimeMs>9e4&&isLockOwnerDefinitelyStale({payload:{pid:e.pid,starttime:e.startTime}}))return`dead`}catch{}return`unknown`}return classifyGatewayOwnerProcessNamespace(e?.processNamespace,{machineIdentity:e?.machineIdentity,readGatewayHeartbeat:t?()=>readLockHeartbeat(t):void 0})}function isLegacyPluginSourceCaptureName(e){return e.startsWith(`openclaw-plugin-build-`)||e.startsWith(`openclaw-model-catalog-`)}function normalizeProcArg(e){return u(e.replaceAll(`\\`,`/`))}const Du=[`openclaw.mjs`,`dist/index.js`,`dist/entry.js`,`scripts/run-node.mjs`,`src/entry.ts`,`src/index.ts`];function referencesRetainedArtifact(e){return e.split(/[\\/=]/u).some(e=>isLegacyPluginSourceCaptureName(e)||/^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(e))}function readProcessPackageIdentity(e,t=!1){for(let n=e;;){let e;try{e=JSON.parse(S.readFileSync(x.join(n,`package.json`),`utf8`))}catch(e){let r=x.dirname(n);if(t&&g(e)===`ENOENT`){if(r===n)return{kind:`absent`};if(x.basename(n)===`node_modules`)return{kind:`unknown`,reason:`could not read package identity`};n=r;continue}return{kind:`unknown`,reason:`could not read package identity`}}return!s(e)||typeof e.name!=`string`||!e.name.trim()||e.name!==e.name.trim()?{kind:`unknown`,reason:`package identity has no valid name`}:{kind:`package`,name:e.name,scripts:s(e.scripts)?e.scripts:{}}}}function readProcessWorkingDirectories(e){let t=new Set(e.filter(e=>Number.isSafeInteger(e)&&e>0)),n=/* @__PURE__ */ new Map;if(t.size===0)return n;if(process.platform===`linux`){for(let e of t)try{n.set(e,S.readlinkSync(`/proc/${e}/cwd`))}catch{}return n}try{if(process.platform===`darwin`){let e=hn(`/usr/sbin/lsof`,[`-a`,`-p`,[...t].join(`,`),`-d`,`cwd`,`-F0pn`],{encoding:`utf8`,timeout:5e3,maxBuffer:4194304,env:resolveDiagnosticProcessEnv()});if(e.error||e.status!==0&&e.status!==1)return n;let r=e.stdout.split(`\0`);r.pop();let i=/* @__PURE__ */ new Set,a;for(let e of r){let r=e.replace(/^\n/,``);if(r.startsWith(`p`)){let e=/^p(\d+)$/.exec(r);a=e&&t.has(Number(e[1]))?Number(e[1]):void 0}else a!==void 0&&r.startsWith(`n`)&&x.isAbsolute(r.slice(1))&&(n.delete(a)?i.add(a):i.has(a)||n.set(a,r.slice(1)))}}}catch{}return n}function classifyEntrypoint(e,t={}){let n=normalizeProcArg(e[0]??``).replace(/\.(bat|cmd|exe)$/i,``);if(!t.requirePackageIdentity&&(n.endsWith(`/openclaw`)||n===`openclaw`))return{kind:`openclaw`,entryIndex:0};let r=/(?:^|\/)openclaw\.mjs$/.test(n)?0:Kt(e).position;if(typeof r!=`number`)return r.kind===`unclassified`?{kind:`unclassified`,cause:`runtime-syntax`,reason:r.reason}:{kind:`other`};let i=e[r];if(t.inspectPackage&&!t.requirePackageIdentity&&t.cwd&&x.isAbsolute(t.cwd)&&qt(e[0]??``)&&!/[\\/]/u.test(i)&&!x.extname(i)){let e=readProcessPackageIdentity(t.cwd,!0);if(e.kind===`unknown`)return{kind:`unclassified`,cause:`package-identity`,reason:e.reason};let n=e.kind===`package`?e.scripts[i]:void 0;if(typeof n==`string`&&n.trim())return e.kind===`package`&&e.name===`openclaw`?{kind:`openclaw`}:{kind:`other`}}let a=classifyOpenClawEntrypointPath(i,t);return a.kind===`openclaw`?{...a,entryIndex:r}:a}function classifyOpenClawEntrypointPath(e,t={}){let n=normalizeProcArg(e);if(!t.requirePackageIdentity&&!t.inspectPackage&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};let r=[...Du,...t.additionalEntrypoints??[]],i=e;if(!x.isAbsolute(e)){let n=t.cwd??(t.pid===void 0?void 0:readProcessWorkingDirectories([t.pid]).get(t.pid));if(!n||!x.isAbsolute(n))return{kind:`unclassified`,cause:`cwd`,reason:`working directory is unavailable`};i=x.resolve(n,e)}let a,s;try{if(a=S.realpathSync(i),t.inspectPackage&&!t.requirePackageIdentity&&referencesRetainedArtifact(a))return{kind:`openclaw`,artifactPath:a};let n=t.requirePackageIdentity||t.inspectPackage?S.statSync(a):void 0;if(t.requirePackageIdentity&&!n?.isFile())return{kind:`unclassified`,cause:`script`,reason:`entrypoint is not a regular file: ${e}`};s=n?.isDirectory()??!1}catch{return{kind:`unclassified`,cause:`script`,reason:`could not resolve script`}}let c=normalizeProcArg(a);if(!t.requirePackageIdentity&&/(?:^|\/)openclaw\.mjs$/.test(n))return{kind:`openclaw`};let l=s?void 0:r.find(e=>c.endsWith(`/${e}`));if(!l&&(!t.inspectPackage||t.requirePackageIdentity))return{kind:`other`};let u=l?a.slice(0,-l.length):s?a:x.dirname(a),d=readProcessPackageIdentity(u,t.inspectPackage&&!t.requirePackageIdentity||!l&&!s);return d.kind===`unknown`?{kind:`unclassified`,cause:`package-identity`,reason:d.reason}:d.kind===`package`&&d.name===`openclaw`?{kind:`openclaw`,...t.requirePackageIdentity?{packageIdentity:{root:x.resolve(u),entrypoint:a}}:{}}:{kind:`other`}}function classifyOpenClawArgv(e,t={}){let{command:n,owner:r,pid:i,port:a}=t;if(!t.requirePackageIdentity&&n===`gateway`&&r?.pid===i&&r?.state===`live`&&(a===void 0||r.port===a))return{kind:`openclaw`};let s=normalizeProcArg(e[0]??``).split(`/`).at(-1)?.replace(/\.(exe|cmd|bat)$/,``)??``;if(!t.requirePackageIdentity&&/^openclaw-[a-z0-9-]+$/.test(s))return!n||s===`openclaw-${n}`?{kind:`openclaw`}:{kind:`other`};let c=classifyEntrypoint(e,t);if(n)return c.kind===`openclaw`&&normalizeProcArg(getRootOptionAwareCommandPath([`node`,...e.slice(c.entryIndex)],1)[0]??``)!==n?{kind:`other`}:c;if(c.kind===`openclaw`||!t.requirePackageIdentity&&e.some(e=>e.replaceAll(`\\`,`/`).split(`/`).some(isLegacyPluginSourceCaptureName)))return c.kind===`openclaw`?c:{kind:`openclaw`};if(t.serviceMarkerUnavailable&&!t.requirePackageIdentity)return{kind:`unclassified`,cause:`service-marker`,reason:`process environment is unreadable`};let l=t.serviceMarker;if(i!==void 0&&process.platform===`linux`&&(Gt(s)||qt(s)||s===`tsx`))try{l=S.readFileSync(`/proc/${i}/environ`,`utf8`).split(`\0`).find(e=>e.startsWith(`OPENCLAW_SERVICE_MARKER=`))?.slice(24)}catch(e){return{kind:`unclassified`,cause:`service-marker`,reason:`process identity inspection failed (${g(e)??`unavailable`})`}}return!t.requirePackageIdentity&&l===`openclaw`?{kind:`openclaw`}:c}const Ou=new tn;function comparableStateOwnerStaleReason(e,t){return t===`dead`?`owner-process-exited`:t===`same`?inspectStaleLockOwner({payload:{pid:e.pid,starttime:e.startTime}})?.reason:void 0}function isGatewayStateOwnerDefinitelyStale(e,t,n){let r=s(e)?e:null;if(!r)return!1;let i=classifyGatewayLockProcessNamespace(r,t,n);if(i===`unknown`)throw new GatewayLockNamespaceError(r,t);return comparableStateOwnerStaleReason(r,i)!==void 0}function assertPersistedStateDatabaseAccessAllowed(e){let{databasePath:t,ownerPath:n,assertMaintenance:r}=e,i=`OpenClaw state ownership at ${t} could not be verified from ${n}; restart the Gateway.`,a;try{a=S.readFileSync(n,`utf8`)}catch(e){if(g(e)===`ENOENT`)return;throw new Be(i,{cause:e})}let s=Ou.getStore();if(s?.deadOwner?.path===n&&s.deadOwner.raw===a)return;let c=parseGatewayLockPayload(a);if(!c)throw new ge(t,i);if(!Number.isSafeInteger(c.pid)||c.pid<=0)throw new Be(i);let l=classifyGatewayLockProcessNamespace(c,n,t),u=comparableStateOwnerStaleReason(c,l);if(u){s&&u===`owner-process-exited`&&(s.deadOwner={path:n,raw:a});return}if(l===`same`&&c.pid===process.pid&&!Zt)return;if(l===`same`&&!isPidAlive(c.pid))throw new ge(t,i);let d=c.role??`gateway`;if(d===`gateway`||d===`agent-embedded`)return;if(l===`same`&&c.pid===process.pid){r();return}let f=`OpenClaw state at ${t} is undergoing offline maintenance by ${d} process ${c.pid}, started ${c.createdAt}; retry when it finishes. For update progress, run \`openclaw update status --json\`. ${describeGatewayLockHolder(c,n,l===`same`?`live`:`unknown`)}`;throw c.stateOwnerKind===`schema`&&c.role===`sqlite-maintenance`?new ge(t,f):new Ne(t,f)}function defaultPayload(e){let t=resolveOpenClawStateDirForDatabasePath(e),n=getFileLockProcessStartTime(process.pid),r=Ht(),i=r===void 0?null:getFileLockProcessStartTime(r);return{pid:process.pid,ownerId:an(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:x.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?le():void 0,...r===void 0?{}:{parentPid:r},...i===null?{}:{parentStartTime:i},...n===null?{}:{startTime:n}}}function assertGatewayRestorationPriority(e,t,n){if(n.role===`gateway`)return;let r;try{r=S.readFileSync(t,`utf8`)}catch(e){if(g(e)===`ENOENT`)return;throw e}let i=parseGatewayLockPayload(r);if(!(isGatewayStateOwnerDefinitelyStale(i)||i?.pid===n.pid)&&!(n.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&classifyOpenClawArgv(process.argv,{command:`gateway`}).kind===`openclaw`))throw new ge(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,s=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,s,n),ensureOwnerDirectory(x.dirname(t),i);let c={holder:null},stale=({payload:n})=>(c.holder=Po.safeParse(n).data??null,isGatewayStateOwnerDefinitelyStale(c.holder,t,e));if(r>0)try{let n=c.holder=parseGatewayLockPayload(S.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t,e)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&isPidAlive(n.pid)))throw new At(e)}catch(e){if(g(e)!==`ENOENT`)throw e}for(let l=!1;;)try{return On(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,s,n),n),shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(n){let r=g(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&&isPidAlive(r.pid)?`live`:`unknown`);throw new At(e,n,i,r?{pid:r.pid,role:r.role}:void 0)}throw n}}const ku=y(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new tn);function getStateDatabaseSchemaLease(e){let t=ku.getStore()?.get(resolveStateOwnerIdentity(e).key);if(t&&!t.active)throw Error(`State schema maintenance scope is no longer current`);return t?.lease.assertCurrent(),t?.lease}function leaseForFile(e,t,n,r){let i=!1,holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent(),Zo.clear();let t=new Map(ku.getStore()),r={lease:a,active:!0};t.set(n.key,r);let leave=()=>{r.active=!1,Zo.clear()};try{let n=ku.run(t,e);return Ce(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(){Zo.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.onReleased?.())),n.locks.size===0&&removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){Zo.clear();let n=resolveStateOwnerIdentity(e),r=j.get(n.key),i=r?.path??n.ownerPath;if(r&&(!r.accepting||!hasPhysicalOwnership(r)))throw new At(e,r.lost.signal.reason);r&&assertStateDatabaseAccessAllowed(e);let a=r?.payload??{...defaultPayload(e),stateOwnerKind:`schema`},s,c=[];try{s=acquireGatewayStateOwnerFile(e,i,a,r?0:t.busyTimeoutMs??5e3,c)}catch(t){if(t instanceof At)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof ge)throw e}throw t}let l=r?.projectionPath??x.join(m(resolveOpenClawStateDirForDatabasePath(Bt(e))),`gateway.state.lock`),u;try{u=r?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,l,{...a,role:a.role===`gateway`?`gateway`:`agent-embedded`},0,c)}catch(e){return Te({release(){s.release(),removeCreatedProjectionDirectories(c)}},`state schema projection admission`,()=>{throw e})}r?(r.locks.add(s),r.locks.add(u),r.projectionDirectories.push(...c)):(r={key:n.key,path:i,kind:`schema`,payload:a,projectionPath:l,locks:/* @__PURE__ */ new Set([s,u]),projectionDirectories:c,lost:new AbortController,accepting:!0},j.set(r.key,r));let d=leaseForFile(i,s,r,u);try{let e=r.heartbeat??=startGatewayStateOwnerHeartbeat(r.locks,(e,t)=>observeOwnerLoss(r,e,t));return d.assertCurrent(),e.register(u),d}catch(e){return Te(d,`state schema ownership verification`,()=>{throw e})}}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(Zo.get(r)?.accepting)return;let i=n??resolveStateOwnerIdentity(e),a=j.get(i.key),s=a?.payload.role??`gateway`;if(!a||a.kind!==`process`||!a.accepting||s!==`gateway`&&s!==`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.`);Zo.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 gt()}}: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 gt();assertStateDatabaseReadAtOwnerPath(n,t,e)};let s=i.heartbeat,c=i.locks.values().next().value,l=i.getProjection?.();if(!s||!c)throw gt();let assertCurrent=(t=r)=>{if(i.lost.signal.throwIfAborted(),s.assertActive(),j.get(e.key)!==i||i.heartbeat!==s)throw gt();if(!i.accepting)assertStateDatabaseAccessAtOwnerPath(n,e,t);else if(!i.locks.has(c)||i.getProjection?.()!==l)throw gt()};assertCurrent();let u=[c.lockPath];l&&u.push(l.lockPath);let d=await s.verify(u).catch(e=>{throw i.lost.signal.throwIfAborted(),e});if(assertCurrent(),!d){let e=/* @__PURE__ */ Error(`${c.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`);throw loseOwner(i,e),e}return Zo.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:getOpenClawDatabaseMaintenanceScope();if(!r)throw new he(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 Au={Scavenge:`scavenge`,MinorMarkSweep:`scavenge`,MarkSweepCompact:`mark_sweep_compact`,IncrementalMarking:`incremental`,ProcessWeakCallbacks:`weak_processing`},ju=/* @__PURE__ */ new Set;let Mu,Nu,Pu;function getOldGenerationAfterGcBytes(){return Pu}function drain(e){let t=Mu?.stop();e&&Mu?.start();let n=[];for(let e of t?.statistics??[]){let t=Au[e.gcType];if(!t)continue;let r=e.beforeGC.heapStatistics.usedHeapSize,i={kind:t,reason:`other`,durationMs:e.cost/1e3,heapUsedBeforeBytes:r,reclaimedBytes:Math.max(0,r-e.afterGC.heapStatistics.usedHeapSize)};if(t===`mark_sweep_compact`){i.heapUsedAfterMajorGcBytes=e.afterGC.heapStatistics.usedHeapSize,i.heapUsedAfterMajorGcTimestampSeconds=Date.now()/1e3,Pu=0;for(let t of e.afterGC.heapSpaceStatistics)(t.spaceName===`old_space`||t.spaceName===`large_object_space`)&&(Pu+=t.spaceUsedSize)}n.push(i)}if(n.length)for(let e of ju)e(n)}function flushGcSamples(){Mu&&drain(!0)}function observeGcSamples(e){if(!process.versions.bun)return Mu?drain(!0):(Mu=new xn,Mu.start(),Nu=setInterval(()=>drain(!0),1e3).unref()),ju.add(e),()=>{if(!ju.has(e))return;let t=ju.size===1;drain(!t),ju.delete(e),t&&(clearInterval(Nu),Nu=void 0,Mu=void 0,Pu=void 0)}}const Fu={statement:wn(`openclaw.database.statement`),request:wn(`openclaw.database.request`)},Iu=/* @__PURE__ */ new WeakSet;let statementTiming;function attributesSqliteStatements(e){return e.startsWith(`session.transcript.`)||e.startsWith(`sessions.transcript-`)||e.startsWith(`session.metadata.`)||e.startsWith(`trajectory.`)||e.startsWith(`audit.writer.`)||e.startsWith(`knowledge.`)||e===`session.lifecycle.delete`||e===`session context snapshot read`}function startSqliteStatementTiming(e=!1){let t=statementTiming,n,r;if(e)try{r=observeGcSamples(e=>{for(let t of e)n=(n??0)+t.durationMs}),n=r?0:void 0}catch{}let i=/* @__PURE__ */ new Map,a=0,s=0,c=0,l;return statementTiming=(e,t,n)=>{a++,s+=t,(l===void 0||t>c)&&(l=e);let r=i.has(e)||i.size<32?e:``,u=i.get(r)??{count:0,totalMs:0,maxMs:0};i.set(r,u),c=Math.max(c,t),n!==void 0&&(u.rows=(u.rows??0)+n),u.count++,u.totalMs+=t,u.maxMs=Math.max(u.maxMs,t)},()=>{statementTiming=t;try{r?.()}catch{n=void 0}return{totalMs:s,callbackGcMs:n,summarize(){let identity=e=>{let t=normalizeSql(`sqlite`,e);return{id:e?nn(`sha256`).update(t).digest(`hex`).slice(0,16):`other`,operation:/^(SELECT|INSERT|UPDATE|DELETE|WITH|SAVEPOINT|RELEASE|ROLLBACK)\b/i.exec(t)?.[1]?.toUpperCase()??`OTHER`}};return{count:a,maxMs:c,slowest:l===void 0?void 0:{...identity(l),maxMs:c},statements:[...i].toSorted((e,t)=>t[1].totalMs-e[1].totalMs).slice(0,5).map(([e,t])=>Object.assign(identity(e),t,{totalMs:Math.round(t.totalMs*100)/100,maxMs:Math.round(t.maxMs*100)/100})),omittedGroups:Math.max(0,i.size-5)}}}}}function normalizeSql(e,t){let n=``;for(let r=0;r<t.length;){let i=t.slice(r);if(i.startsWith(`/*`)){let e=1;for(r+=2;r<t.length&&e;)t.startsWith(`/*`,r)?(e++,r+=2):t.startsWith(`*/`,r)?(e--,r+=2):r++;n+=` `;continue}let a=/^--[^\r\n]*/.exec(i)?.[0],s=(e===`postgres`?/^[eE]'(?:\\[\s\S]|''|[^'\\])*(?:'|$)/.exec(i)?.[0]:void 0)??/^(?:[uU]&)?'(?:''|[^'])*(?:'|$)/.exec(i)?.[0],c=/^\$(?:[A-Za-z_][\w]*)?\$/.exec(i)?.[0],l=/^(?:"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\])/.exec(i)?.[0],u=/[\w$]/.test(t[r-1]??``)?void 0:/^(?:0x[\da-f]+|\d+(?:\.\d*)?(?:e[+-]?\d+)?)(?!\w)/i.exec(i)?.[0];if(c){let e=t.indexOf(c,r+c.length);r=e<0?t.length:e+c.length,n+=`?`}else if(a||s||l||u){let e=a??s??l??u??``;r+=e.length,n+=a?` `:l?e:`?`}else n+=t[r++]}return n.replace(/\s+/g,` `).trim()}function observeDatabaseOperation(e,t,n,r,i){let a=Fu[t],s=e===`sqlite`&&t===`statement`?statementTiming:void 0;if(!a.hasSubscribers&&!s)return r();let c=performance.now(),l=`error`,u;try{let e=r();return l=`ok`,u=i===`all`&&Array.isArray(e)?e.length:i===`get`?Number(e!==void 0):void 0,e}finally{let t=performance.now()-c;n!==void 0&&s?.(n,t,u),a.hasSubscribers&&a.publish({engine:e,sql:n===void 0?void 0:normalizeSql(e,n),threadId:$t,outcome:l,durationMs:t})}}function observeConnection(e){if(Iu.has(e))return e;Iu.add(e);let t=e.exec.bind(e),n=e.prepare.bind(e);return e.exec=e=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>t(e)),e.prepare=e=>{let t=n(e);for(let n of[`get`,`all`,`run`]){let r=t[n].bind(t);Object.defineProperty(t,n,{configurable:!0,writable:!0,value:(...t)=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>r(...t),n===`run`?void 0:n)})}let r=t.iterate.bind(t);return t.iterate=(...t)=>{let n=r(...t),i=statementTiming;if(!Fu.statement.hasSubscribers&&!i)return n;let a=0,s=0,c=!1,l=!1,finish=t=>{l||(l=!0,c&&(i?.(e,a,s),Fu.statement.hasSubscribers&&Fu.statement.publish({engine:`sqlite`,sql:normalizeSql(`sqlite`,e),threadId:$t,outcome:t,durationMs:a})))},step=e=>{if(l)return e();let t=performance.now();try{let n=e();return a+=performance.now()-t,n.done?finish(`ok`):s++,n}catch(e){throw a+=performance.now()-t,finish(`error`),e}},u={next:(...e)=>(c=!0,step(()=>n.next(...e))),return:e=>step(()=>n.return?.(e)??{done:!0,value:e}),[Symbol.iterator](){return this}};return Object.setPrototypeOf(u,Object.getPrototypeOf(n)),u},t},e}const Lu=1e3,Ru=1e3,zu=Symbol.for(`openclaw.sqliteAbortedTransaction`);function assertTransactionUsable(e){if(b(e))return;let t=e[zu];if(t)throw t.error}const Bu=re(`sqlite/transaction`),Vu=y(Symbol.for(`openclaw.sqliteWriteAdmissionServices`),()=>/* @__PURE__ */ new Map),Hu=/* @__PURE__ */ new WeakMap;function writeAdmissionLocation(e){let t=Hu.get(e);if(t!==void 0)return t;let n=e.location(),r=n===null?null:_e(n);return Hu.set(e,r),r}function retainSqliteWriteAdmissionService(e,t){let n=[...new Set(e.map(_e))].map(e=>{let n=Vu.get(e)??/* @__PURE__ */ new Set,retained=()=>t();return n.add(retained),Vu.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&&Vu.get(e)===t&&Vu.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=Vu.size>0?writeAdmissionLocation(e):null,r=n===null?void 0:Vu.get(n);if(!r){execNativeBegin(e,t);return}let i=performance.now()+readSqliteBusyTimeout(e);for(;;)try{runWithSqliteBusyTimeout(e,Math.min(25,Math.max(0,Math.ceil(i-performance.now()))),()=>execNativeBegin(e,t));return}catch(e){if(!Fe(e)||performance.now()>=i)throw e;for(let e of r){let n=Date.now();t.serviceCalls+=1;try{e()}finally{t.serviceMs+=Date.now()-n}}if(performance.now()>=i)throw e}}function slowBusyWaitThresholdMs(e){return e?.busyTimeoutMs===void 0||e.busyTimeoutMs<=0?Lu:Math.min(Lu,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||Ge()?.operation||`unlabeled`,...t?.diagnosticContext?{context:{...t.diagnosticContext}}:{}}}function logTransactionStep(e,t){try{if(!t&&e.elapsedMs<slowBusyWaitThresholdMs(e.options))return;let n=t?ft(t.error):void 0,r=t?it(t.error):void 0;(e.options?.logger??Bu).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:Tt(t.error)}:{},elapsedMs:e.elapsedMs,...e.holderAtWaitStart?{holderAtWaitStart:e.holderAtWaitStart}:{},...t?{failureKind:`lock-contention`}:{},isMainThread:Zt,pid:process.pid,...n===void 0?{}:{sqliteErrcode:n},...r===void 0?{}:{sqlitePrimaryCode:r},step:e.step,threadId:$t,...e.beginAdmission?{beginAdmission:{...e.beginAdmission}}:{}})}catch{}}function execTimedTransactionStep(e){let t=Date.now(),n=e.sql===`BEGIN IMMEDIATE`?{nativeAttempts:0,nativeMs:0,serviceCalls:0,serviceMs:0}:void 0,r=n?_t(e.db,t):void 0;try{n?beginImmediateTransaction(e.db,n):e.db.exec(e.sql);let i=Date.now()-t;return logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:i,holderAtWaitStart:r,options:e.options,step:e.step}),i}catch(i){let a=Date.now()-t;throw Fe(i)&&shouldReportSqliteLockFailure(e.db)&&(e.step!==`begin`||e.options?.beginLockFailureReporting!==`suppress`)&&logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:a,holderAtWaitStart:r,options:e.options,step:e.step},{error:i}),i}}function discardUnsafeConnection(e,t){let n={error:t};e[zu]??=n;try{Ee(e,t)}catch(t){throw e[zu]===n&&(n.error=t),t}finally{clearNodeSqliteKyselyCacheForDatabase(e);try{e.close()}catch{}}}function abortImmediateTransaction(e,t,n){if(!e[zu]){if(!n&&e.isOpen&&!e.isTransaction)Ee(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=runSqliteReadOperationSync(e,t);return Pt(n),assertTransactionUsable(e),e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`),n}catch(t){let n=e[zu];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=xe(),a=i?Date.now()-i.preparedAtMs:void 0,s=execTimedTransactionStep({db:e,options:r,sql:n===`immediate`?`BEGIN IMMEDIATE`:`BEGIN`,step:`begin`});return i&&(i.transactions.count+=1),settleSqliteTransactionSync(e,t,n,s,a,r)}function settleSqliteTransactionSync(e,t,n,r,i,a,s=!1){let c=xe(),l=Date.now(),u=n===`immediate`?mt(e):void 0;u&&ue(u,a?.operationLabel||Ge()?.operation||`unlabeled`,l);let d=c?.hostAdmissionWaitMs??0,f=c?.databaseAdmissionWaitMs??0,p=0,commit=()=>{let t=Date.now(),n=c?.databaseAdmissionWaitMs??0;try{wt(e),execTimedTransactionStep({db:e,options:a,sql:`COMMIT`,step:`commit`})}finally{p+=Date.now()-t-((c?.databaseAdmissionWaitMs??0)-n)}},m=!1,h=a?.operationLabel||Ge()?.operation,g=h?.startsWith(`sessions.transcript-hydration.`)===!0,v;try{let n=h&&attributesSqliteStatements(h)?startSqliteStatementTiming(g):void 0,r;try{r=s?t():runSqliteReadOperationSync(e,t)}finally{v=n?.()}return Pt(r),assertTransactionUsable(e),m=!0,a?.withCommit?Pt(a.withCommit(commit)):commit(),r}catch(t){throw abortImmediateTransaction(e,t,m),assertTransactionUsable(e),t}finally{u&&Atomics.compareExchange(u,1,$t+1,0);try{c?.diskRead&&(c.diskRead.context=a?.diagnosticContext);let t=Date.now()-l,s=(c?.hostAdmissionWaitMs??0)-d,u=(c?.databaseAdmissionWaitMs??0)-f,m=Math.max(0,t-s-u-p);t<(a?.slowTransactionHoldMs??Ru)||(a?.logger??Bu).warn(`slow SQLite transaction hold`,{async:!1,callbackKind:`application-transaction`,isMainThread:Zt,mode:n,pid:process.pid,threadId:$t,...transactionDiagnosticLabels(e,a),...c?.holdContext||g&&c?.hydrationActiveEvents!==void 0?{context:He(a?.diagnosticContext,g)}:{},elapsedMs:t,phases:{prepareMs:i,beginMs:r,sqlMs:m,...v?{statementExecutionMs:Math.round(v.totalMs*100)/100,callbackOtherMs:Math.round(Math.max(0,m-v.totalMs)*100)/100,callbackGcMs:v.callbackGcMs===void 0?void 0:Math.round(v.callbackGcMs*100)/100}:{},hostAdmissionWaitMs:s,databaseAdmissionWaitMs:u,commitMs:p},...v?{statementTiming:v.summarize()}:{},thresholdMs:a?.slowTransactionHoldMs??Ru})}catch{}finally{c&&(c.preparedAtMs=Date.now(),c.hydrationActiveEvents!==void 0&&(c.hydrationActiveEvents=void 0))}}}function runSqliteImmediateTransactionSync(e,t,n){return b(e)?e.runTransaction(t,n):(assertTransactionUsable(e),Qe(e,()=>runSqliteTransactionSync(e,t,`immediate`,n)))}function runSqliteSingleStatementSync(e,t){return b(e)?e.runTransaction(t):(assertTransactionUsable(e),Qe(e,()=>{let n=Vu.size>0?writeAdmissionLocation(e):null;if(e.isTransaction||n!==null&&Vu.has(n))return runSqliteTransactionSync(e,t,`immediate`);let r=runSqliteReadOperationSync(e,t);return Pt(r),r}))}function serveWorkerMemorySamples(e,t){let{port1:n,port2:r}=new Xt,i=ct(e=>{n.postMessage({sqliteReaderCounter:e})}),a=bt(()=>{n.postMessage({postgresBridgeCounters:se()})}),s=process.versions.bun?void 0:Cn().heap_size_limit,c,l=!1,flushGc=()=>{c&&=(n.postMessage({gc:c}),void 0)},sample=()=>{let{heapUsed:e,heapTotal:r,external:i,arrayBuffers:a}=process.memoryUsage(),l=process.versions.bun?void 0:Sn().map(({space_name:e,space_used_size:t})=>({space_name:e,space_used_size:t}));n.postMessage({heapUsed:e,heapTotal:r,external:i,arrayBuffers:a,heapSizeLimitBytes:s,oldGenerationAfterGcBytes:getOldGenerationAfterGcBytes(),heapSpaces:l,retainedData:t?.(),gc:c}),c=void 0},u,setGcEnabled=e=>{e?u??=observeGcSamples(e=>{(c??=[]).push(...e),(l||c.length>=256)&&flushGc()}):(u?.(),u=void 0,c=void 0)};return n.on(`message`,e=>{if(e&&`flush`in e)flushGcSamples(),flushGc(),n.postMessage({flushed:!0,heapUsed:Cn().used_heap_size});else if(e&&`captureGcProfile`in e){let t=e.captureGcProfile;import(`./openclaw-state-lease-heartbeat.worker-diagnostic-worker-gc-profile-BofYzIjq.mjs`).then(({captureWorkerGcProfiles:e})=>e()).then(e=>{n.postMessage({gcStorm:e.status===`complete`?{...t,captureStatus:`complete`,profiles:e.result}:{...t,captureStatus:`unavailable`,captureReason:e.reason}})}).catch(()=>{n.postMessage({gcStorm:{...t,captureStatus:`unavailable`,captureReason:`capture-failed`}})})}else e?setGcEnabled(e.gc):sample()}),n.once(`close`,()=>{a(),i(),u?.(),c=void 0}),n.on(`messageerror`,()=>n.close()),n.unref(),sample(),e.postMessage({status:`memory`,port:r,postgresBridgeCounters:se()},[r]),{setTaskMetrics(e){l=e,setGcEnabled(e)},collectTask(){return l?!0:void 0},close(){a(),i(),u?.(),u=void 0,flushGc(),n.close()}}}function stateEngineInput(){if(Ye())return Ze(`state`)}const Uu=y(Symbol.for(`openclaw.sqliteWalWriteAdmissions`),()=>/* @__PURE__ */ new WeakMap);function registerSqliteWalWorkerMaintenance(e,t,n){e.exec(`PRAGMA wal_autocheckpoint = 0;`);let r=Uu.get(e)?.stopCheckpointTick;Uu.set(e,{execute:t,cancel:n}),r?.()}function isSqliteWalWorkerMaintained(e){return Uu.get(e)?.execute!==void 0}const Wu=y(Symbol.for(`openclaw.stateNativeIdentities`),()=>/* @__PURE__ */ new WeakMap);function readTrackedStateDatabaseIdentity(e){return Wu.get(Mt(e))}function openTrackedStateDatabase(e,t){let n=openTrackedStateDatabaseResult(e,t);if(n.status===`unavailable`)throw n.error;return n.database}function openTrackedStateDatabaseResult(e,t){assertStateDatabaseAccessAllowed(e);try{t?.expectedIdentity!==void 0&&ke(e,t.expectedIdentity);let n=t?.existingOnly||t?.expectedIdentity!==void 0?resolveExistingSqliteFileUri(e):e,r=t?.readOnly?{readOnly:!0,timeout:t.timeout}:{enableForeignKeyConstraints:t?.enableForeignKeyConstraints},i=Ie(e),a=xt(()=>openNodeSqliteDatabase(n,r));try{assertStateDatabaseAccessAllowed(e),i.key.startsWith(`file:`)&&ke(e,i.key,i.birthtime);let t=i.key.startsWith(`file:`)?i:Ie(e);if(t.key.startsWith(`file:`)){Wu.set(a,t);let e=registerNodeSqliteDisposeCallback(a,()=>{Wu.delete(a),e()})}}catch(e){throw a.close(),e}return{status:`available`,database:a}}catch(e){return{status:`unavailable`,error:e}}}function closeTrackedStateDatabase(e){e.isOpen&&e.close()}function closeStateDatabaseHandle(e,t){try{var n=_usingCtx();let r=[];if(b(e.db)){for(let t of[e.db,e.db.anchor]){if(t===e.db.anchor&&e.db.isOpen)break;try{t.isOpen&&t.close()}catch(e){r.push(e)}}let t=e.db.isOpen||e.db.anchor.isOpen;if(!t)try{e.afterClose?.()}catch(e){r.push(e),t=!0}return{errors:r,cleanupPending:t}}let i=n.u(ht(e.db)),a=isSqliteWalWorkerMaintained(e.db),s=e.walMaintenance?.health?.state===`error`,c=!1;try{e.db.isOpen&&!a&&setSqliteBusyTimeout(e.db,0),c=e.walMaintenance?.close(t)===!0&&t?.checkpointMode!==`PASSIVE`}catch(e){r.push(e)}try{clearNodeSqliteKyselyCacheForDatabase(e.db)}catch(e){r.push(e)}try{closeTrackedStateDatabase(e.db)}catch(e){r.push(e)}let l=!1;if(!e.db.isOpen)try{e.afterClose?.()}catch(e){r.push(e),l=!0}return r.length===0&&!l&&t?.checkpointMode!==`PASSIVE`&&(c||a&&!s)&&i.publish(),{errors:r,cleanupPending:l}}catch(e){n.e=e}finally{n.d()}}function formatStateLeaseLoss(e){return e.reason===`expired`?`lease loss: expired; expiredByMs=${e.expiredByMs}; expiresAt=${e.expiresAt}; heartbeatAgeMs=${e.heartbeatAgeMs}${e.renewalTimerLateByMs===void 0?``:`; renewal timer late ${e.renewalTimerLateByMs} ms`}`:e.reason===`replaced`?`lease loss: replaced; owner=[redacted]`:`lease loss: ${e.reason}`}var OpenClawStateLeaseError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`OpenClawStateLeaseError`,this.code=t.code,this.loss=t.loss}};function createOpenClawStateLeaseLostError(e,t,n){let r=e.renewalTimer,i=r?Math.max(r.lateByMs,r.dueAt===void 0?0:Date.now()-r.dueAt):0,a=n?.reason===`expired`&&i>0?{...n,renewalTimerLateByMs:i}:n;return new OpenClawStateLeaseError(`${e.leaseLabel??`state lease`} ${e.scope}/${e.key} was lost${a?` (${formatStateLeaseLoss(a)})`:``}; retry the operation`,{code:`OPENCLAW_STATE_LEASE_LOST`,cause:t,loss:a})}const $={status:0,expiresAt:3,lastRenewedAt:4,startupPhase:5,ownerFence:6,starting:0n,ready:1n,closed:2n,lost:3n},Gu={"entry-not-observed":0n,"body-entry":1n,"open-complete":2n,"initial-renew-start":3n,"initial-renew-returned":4n};function parseStateLeaseProcessOwner(e){let t=safeParseJsonRecord(e??``)?.owner;if(!s(t))return null;let{pid:n,host:r,startedAt:i}=t;return typeof n!=`number`||!Number.isSafeInteger(n)||n<=0||typeof r!=`string`||!r||i!==null&&(typeof i!=`number`||!Number.isSafeInteger(i)||i<0)?null:{pid:n,host:r,startedAt:i,...t.machineIdentity===void 0?{}:{machineIdentity:jo.safeParse(t.machineIdentity).data??null},...t.processNamespace===void 0?{}:{processNamespace:Mo.safeParse(t.processNamespace).data??null}}}const Ku=number().int().min(0).max(2**53-1),qu=discriminatedUnion(`reason`,[object({reason:literal(`expired`),expiresAt:Ku,expiredByMs:Ku,heartbeatAgeMs:Ku,renewalTimerLateByMs:Ku.optional()}),object({reason:literal(`replaced`),owner:literal(`[redacted]`)}),object({reason:literal(`missing`)}),object({reason:literal(`storage-failed`)}),object({reason:literal(`admission-failed`)})]);function stateLeaseWriteScope(e){return JSON.stringify([`state-lease`,e.scope,e.key])}function readOpenClawStateLease(e,t){return executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`state_leases`).select([`owner`,`created_at as createdAt`,`expires_at as expiresAt`,`heartbeat_at as heartbeatAt`,`payload_json as payloadJson`]).where(`scope`,`=`,t.scope).where(`lease_key`,`=`,t.key))}function readOpenClawStateLeaseLoss(e,t){try{let n=readOpenClawStateLease(e,t),r=Date.now(),i=n?n.owner===t.owner?n.expiresAt!==null&&n.heartbeatAt!==null&&n.expiresAt<=r?{reason:`expired`,expiresAt:n.expiresAt,expiredByMs:r-n.expiresAt,heartbeatAgeMs:Math.max(0,r-n.heartbeatAt)}:void 0:{reason:`replaced`,owner:`[redacted]`}:{reason:`missing`};return qu.safeParse(i).data}catch{return}}function readOpenClawStateLeaseExpiry(e,t,n){return executeSqliteQueryTakeFirstSync(e,getNodeSqliteKysely(e).selectFrom(`state_leases`).select(`expires_at`).where(`scope`,`=`,t.scope).where(`lease_key`,`=`,t.key).where(`owner`,`=`,t.owner).where(`expires_at`,`>`,n??Date.now()).$narrowType())?.expires_at}function repairMissingProcessStartTime(e,t,n){if(n?.startedAt==null)return;let r=readOpenClawStateLease(e,t),i=parseStateLeaseProcessOwner(r?.payloadJson??null);if(r?.owner!==t.owner||i?.startedAt!==null||i.pid!==n.pid||i.host!==n.host||!r.payloadJson)return;let a=JSON.parse(r.payloadJson);if(s(a)&&s(a.owner))return JSON.stringify({...a,owner:{...a.owner,startedAt:n.startedAt}})}function renewOpenClawStateLeaseInTransaction(e,t,n,r,i){return Ve(e,[stateLeaseWriteScope(t)],()=>{let a=i??Date.now(),s=a+n,c=repairMissingProcessStartTime(e,t,r);return executeSqliteQuerySync(e,getNodeSqliteKysely(e).updateTable(`state_leases`).set({expires_at:s,heartbeat_at:a,updated_at:a,...c===void 0?{}:{payload_json:c}}).where(`scope`,`=`,t.scope).where(`lease_key`,`=`,t.key).where(`owner`,`=`,t.owner).where(`expires_at`,`>`,a)).numAffectedRows===1n?s:void 0})}function identityKey(e){return JSON.stringify([e.scope,e.key,e.owner])}function createStateLeaseRenewalScheduler(e){let t=/* @__PURE__ */ new Map,n,r=!1,arm=()=>{r||(clearTimeout(n),n=void 0,t.size>0&&(n=setTimeout(run,Math.max(1,Math.min(...t.values())-Date.now())),n.unref()))};function run(){n=void 0;let i=Date.now(),a=[...t].filter(([,e])=>e<=i).map(([e])=>e);for(let e of a)t.delete(e);let s=a[0];if(!s)arm();else{r=!0;try{let t=s.execute(()=>{let t=e(),n=Date.now(),r=getNodeSqliteKysely(t).updateTable(`state_leases`).set(e=>{let predicate=t=>e.and([e(`scope`,`=`,t.identity.scope),e(`lease_key`,`=`,t.identity.key),e(`owner`,`=`,t.identity.owner)]),t=e.case().when(predicate(s)).then(e.val(n+s.leaseMs));for(let r of a.slice(1))t=t.when(predicate(r)).then(e.val(n+r.leaseMs));return{expires_at:t.else(e.ref(`expires_at`)).end(),heartbeat_at:n,updated_at:n}}).where(`expires_at`,`>`,n).where(e=>e.or(a.map(t=>e.and([e(`scope`,`=`,t.identity.scope),e(`lease_key`,`=`,t.identity.key),e(`owner`,`=`,t.identity.owner)])))).returning([`scope`,`lease_key`,`owner`,`expires_at`]),renew=()=>Ve(t,a.map(e=>stateLeaseWriteScope(e.identity)),()=>runSqliteSingleStatementSync(t,()=>executeSqliteQuerySync(t,r).rows)),i=b(t)?renew():runWithSqliteBusyTimeout(t,0,renew,{lockFailureReporting:`suppress`});return new Map(i.map(e=>[identityKey({scope:e.scope,key:e.lease_key,owner:e.owner}),e.expires_at??void 0]))});for(let e of a)e.complete({expiresAt:t.get(identityKey(e.identity))})}catch(e){for(let t of a)t.complete({error:e})}finally{r=!1,arm()}}}return{schedule(e,n){let r=Math.min(n,n-e.leaseMs+e.intervalMs);for(let[n,i]of t)n.intervalMs===e.intervalMs&&(r=Math.min(r,i));t.set(e,r),arm()},cancel(e){t.delete(e),arm()}}}const Ju=y(Symbol.for(`openclaw.quarantineReadCleanupError`),()=>class extends AggregateError{constructor(e,t){super(e,`OpenClaw quarantine reader cleanup failed.`,{cause:e[0]}),this.quarantine=t,this.name=`OpenClawQuarantineReadCleanupError`}}),Yu=y(Symbol.for(`openclaw.stateDatabaseFailurePaths`),()=>/* @__PURE__ */ new WeakMap);function markOpenClawStateDatabaseFailure(e,t){Yu.set(e,t)}function readOpenClawStateDatabaseFailurePath(e){return Yu.get(e)}function findOpenClawStateDatabaseFailure(e,t){let n=[e],r=/* @__PURE__ */ new Set;for(let e of n)if(e instanceof Error&&!r.has(e)){if(r.add(e),Yu.get(e)===t)return e;n.push(e.cause),e instanceof AggregateError&&n.push(...e.errors)}}var DuplicateAgentError=class extends Error{};const Xu=`openclaw doctor --fix`;var AuthProfileStoreUnreadableError=class extends Error{constructor(e){super(`Auth profile store ${h(e)} is unreadable; run ${Xu}.`),this.databasePath=e,this.code=`AUTH_PROFILE_STORE_UNREADABLE`,this.action=Xu,this.name=`AuthProfileStoreUnreadableError`}},McpOAuthStoreCorruptionError=class extends Error{constructor(e,t,n){super(`MCP OAuth store ${e} is invalid: ${t}`,n),this.name=`McpOAuthStoreCorruptionError`}},SandboxStateOwnerRequiredError=class extends Error{constructor(e){super(`Sandbox workspace preparation cannot run alongside a foreign live owner of the selected state root, or when that ownership cannot be verified. Run this SDK call inside the owning Gateway plugin/runtime, or stop the Gateway through its service owner and wait for any embedded run to finish, then retry offline. Inspect openclaw gateway status; this call does not acquire ownership or route remotely.`,{cause:e}),this.code=`GATEWAY_STATE_OWNER_REQUIRED`,this.name=`SandboxStateOwnerRequiredError`}},WorkspaceAliasRepointedError=class extends Error{constructor(e){super(`workspace path alias points to a different current target: ${e.aliasPath} now resolves to ${e.currentWorkspacePath}, but its stored workspace state belongs to ${e.storedWorkspacePath}. Run \`openclaw doctor --fix\` and confirm the move, or use \`openclaw doctor --fix --force\`.`),this.code=`WORKSPACE_ALIAS_REPOINTED`,this.name=`WorkspaceAliasRepointedError`,this.aliasPath=e.aliasPath,this.storedWorkspacePath=e.storedWorkspacePath,this.currentWorkspacePath=e.currentWorkspacePath}},WorktreeRemovalContentionError=class extends Error{constructor(e,t,n){super(t),this.kind=e,this.blockedByRun=n,this.name=`WorktreeRemovalContentionError`}},WorktreeRemovalLockError=class extends Error{constructor(e,t){super(t),this.kind=e,this.name=`WorktreeRemovalLockError`}},SessionWorktreeSourceChangedError=class extends Error{},SessionWorktreeLifecycleError=class extends Error{constructor(e,t){super(e),this.reason=t}},SessionGoalOperationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SessionGoalOperationError`}},SessionCanonicalKeyMigrationRequiredError=class extends Error{constructor(e){super(`${e}; stop the Gateway and run openclaw doctor --fix`),this.code=`SESSION_CANONICAL_KEY_MIGRATION_REQUIRED`,this.name=`SessionCanonicalKeyMigrationRequiredError`}},SqliteSessionMutationConflictError=class extends Error{constructor(e){super(`SQLite session state changed while preparing ${e}`),this.operationLabel=e,this.name=`SqliteSessionMutationConflictError`}},SqliteTranscriptMutationConflictError=class extends Error{constructor(e){super(`SQLite transcript changed while preparing rewrite for ${e}`),this.sessionId=e,this.name=`SqliteTranscriptMutationConflictError`}},SessionEntryLifecycleUpsertConflictError=class extends Error{constructor(e){super(`SQLite session entry changed before lifecycle upsert for ${e}`),this.sessionKey=e,this.name=`SessionEntryLifecycleUpsertConflictError`}},SessionPendingInputCustodyError=class extends Error{},SessionTranscriptReadFenceError=class extends Error{constructor(e){super(e),this.name=`SessionTranscriptReadFenceError`}};function isRedactedIdentifier(e){return typeof e==`string`&&/^(?:-|sha256:[0-9a-f]{12})$/.test(e)}function parseTranscriptAppendRefusal(e){if(!s(e)||!isRedactedIdentifier(e.agentIdHash)||!isRedactedIdentifier(e.expectedSessionIdHash)||!isRedactedIdentifier(e.sessionKeyHash))return;let t={agentIdHash:e.agentIdHash,expectedSessionIdHash:e.expectedSessionIdHash,sessionKeyHash:e.sessionKeyHash};if(e.code===`session-entry-missing`)return{...t,code:e.code};if(e.code===`session-rebound`&&isRedactedIdentifier(e.actualSessionIdHash))return{...t,code:e.code,actualSessionIdHash:e.actualSessionIdHash}}var SessionTranscriptWriterClaimReboundError=class extends Error{constructor(e){super(`session writer claim changed before transcript persistence`,{cause:e}),this.name=`SessionTranscriptWriterClaimReboundError`}},ModelAccountConnectAuthorityError=class extends Error{constructor(){super(`This account action requires a current authorized connection; reconnect and try again.`)}},WorkerSessionAlreadyAttachedError=class extends Error{constructor(e,t){super(`Session ${e} is already attached to worker environment ${t}`),this.sessionId=e,this.environmentId=t}},SqliteJsonlReadBudgetExceededError=class extends Error{};const Zu=/^(?<year>\d{4})\.(?<month>[1-9]\d?)\.(?<patch>[1-9]\d*)(?:-(?:(?<channel>alpha|beta)\.(?<prerelease>[1-9]\d*)|(?<correction>[1-9]\d*)))?$/;function parseReleaseVersion(e){let t=e.trim(),n=Zu.exec(t)?.groups;if(!n)return null;let r=Number(n.year),i=Number(n.month),a=Number(n.patch),s=n.prerelease===void 0?void 0:Number(n.prerelease),c=n.correction===void 0?void 0:Number(n.correction);if(!Number.isSafeInteger(r)||!Number.isSafeInteger(i)||!Number.isSafeInteger(a)||i<1||i>12||a<1||s!==void 0&&!Number.isSafeInteger(s)||c!==void 0&&!Number.isSafeInteger(c))return null;let l=n.channel===`alpha`?`alpha`:n.channel===`beta`?`beta`:`stable`;return{version:t,baseVersion:`${r}.${i}.${a}`,channel:l,year:r,month:i,patch:a,alphaNumber:l===`alpha`?s:void 0,betaNumber:l===`beta`?s:void 0,...c===void 0?{}:{correctionNumber:c}}}function compareReleaseVersions(e,t){let n=parseReleaseVersion(e),r=parseReleaseVersion(t);if(n===null||r===null)return null;if(n.year!==r.year)return Math.sign(n.year-r.year);if(n.month!==r.month)return Math.sign(n.month-r.month);if(n.patch!==r.patch)return Math.sign(n.patch-r.patch);if(n.channel!==r.channel){let e={alpha:0,beta:1,stable:2};return Math.sign(e[n.channel]-e[r.channel])}return n.channel===`alpha`&&r.channel===`alpha`?Math.sign((n.alphaNumber??0)-(r.alphaNumber??0)):n.channel===`beta`&&r.channel===`beta`?Math.sign((n.betaNumber??0)-(r.betaNumber??0)):Math.sign((n.correctionNumber??0)-(r.correctionNumber??0))}function walkUpFrom(e,t,n){let r=x.resolve(e);for(let e=0;t.maxDepth===void 0||e<t.maxDepth;e+=1){let e=n(r);if(e!=null)return e;let t=x.dirname(r);if(t===r)break;r=t}return null}function readGitMetadataFile(e,t=1048576){let n=S.openSync(e,S.constants.O_RDONLY|(S.constants.O_NONBLOCK??0));try{let e=S.fstatSync(n);if(!e.isFile()||e.size>t)throw Error(`Git metadata is not a bounded regular file`);let r=En(n,Math.min(e.size,t));if(r.length!==e.size)throw Error(`Git metadata changed during its read`);return r}finally{S.closeSync(n)}}function readGitDirectoryPointerTarget(e,t=``){let n=readGitMetadataFile(e),r=n.toString(`utf8`).replace(/[\r\n]+$/u,``);if(!vn(n)||!r.startsWith(t)||r.length===t.length||r.includes(`\0`))throw Error(`Git directory pointer is incomplete or malformed`);let i=r.slice(t.length);return x.isAbsolute(i)?i:`${x.dirname(e)}${x.sep}${i}`}function readGitDirectoryPointer(e,t=``){return S.realpathSync.native(readGitDirectoryPointerTarget(e,t))}function resolveGitDirFromMarker(e){let t=x.join(e,`.git`);try{let e=S.statSync(t);return e.isDirectory()?t:e.isFile()?readGitDirectoryPointer(t,`gitdir: `):null}catch{return null}}function resolveGitHeadPath(e,t={}){return walkUpFrom(e,t,e=>{let t=resolveGitDirFromMarker(e);return t?x.join(t,`HEAD`):null})}function readGitMetadataPrefix(e,t=256){let n=S.openSync(e,S.constants.O_RDONLY|(S.constants.O_NONBLOCK??0));try{if(!S.fstatSync(n).isFile())throw Error(`Git metadata is not a regular file`);let e=Buffer.alloc(t),r=Dn(n,e,0);return e.subarray(0,r).toString(`utf-8`)}finally{S.closeSync(n)}}function readGitHead(e,t={}){let n=resolveGitHeadPath(e,t);if(!n)return;let r=readGitMetadataFile(n).toString(`utf8`).trim();if(!r.startsWith(`ref:`))return{headPath:n,ref:null,value:r||null};let i=r.replace(/^ref:\s*/i,``).trim(),a=resolveGitRefsBase(n);return{headPath:n,ref:i,value:readGitRefs(a,[i]).get(i)??null,refsBase:a}}function resolveGitRefsBase(e){let t=x.dirname(e),n=x.join(t,`commondir`);try{return readGitDirectoryPointer(n)}catch(e){if(!f(e)||S.lstatSync(n,{throwIfNoEntry:!1}))throw e}return t}function readGitRefs(e,t){let n=new Map(t.map(e=>[e,null])),r=/* @__PURE__ */ new Set;for(let i of t){let t=resolveRefPath(e,i);if(t)try{n.set(i,readGitMetadataPrefix(t).trim())}catch(e){if(!f(e))throw e;r.add(i)}}if(r.size===0)return n;try{let t=readGitMetadataFile(x.join(e,`packed-refs`),2**53-1).toString(`utf8`),i=RegExp(`^(?![#^])[^\\S\\r\\n]*(\\S+)[^\\S\\r\\n]+(${[...r].map(ie).join(`|`)})(?=\\s|$)`,`gm`);for(let[,e,a]of t.matchAll(i))r.delete(a)&&n.set(a,e)}catch(e){if(!f(e))throw e}return n}function resolveRefPath(e,t){if(!t.startsWith(`refs/`)||t.split(/[/]/).includes(`..`))return null;let n=x.resolve(e,t),r=x.relative(e,n);return!r||r.startsWith(`..`)||x.isAbsolute(r)?null:n}const Qu=y(Symbol.for(`openclaw.asyncWorkScope`),()=>new tn),$u=y(Symbol.for(`openclaw.asyncWorkScopeAncestry`),()=>new tn),ed=y(Symbol.for(`openclaw.asyncWorkScopeClosedError`),()=>class extends Error{constructor(){super(`Async work scope is closed`),this.name=`AsyncWorkScopeClosedError`}});var td=class AsyncWorkScope{constructor(e){this.failures=e,this.pending=/* @__PURE__ */ new Set,this.controller=new AbortController,this.phase=`open`}get signal(){return this.controller.signal}get hasPendingWork(){return this.pending.size>0}get isClosing(){return this.phase!==`open`}enter(e){let t=Qu.getStore();if(t===this)return e();let n=$u.getStore(),r=t?n?.scope===t?n:{scope:t}:void 0;return v(Qu,this,()=>($u.enterWith({scope:this,parent:r}),e()))}run(e){if(this.phase===`closed`)throw new ed;if(this.pending.size>0)return this.enter(e);let t=Lt();this.pending.add(t.promise);try{return this.enter(e)}finally{t.resolve(),this.pending.delete(t.promise)}}track(e){if(this.phase===`closed`)return Promise.reject(new ed);let t=Lt();this.pending.add(t.promise),t.promise.then(()=>this.pending.delete(t.promise),e=>{this.pending.delete(t.promise),this.failures&&(Rt(e),this.failures.add(e))});try{t.resolve(this.enter(e))}catch(e){t.reject(e)}return t.promise}beginClose(e){this.phase===`open`&&(this.phase=`closing`,this.controller.abort(e),Rt(this.controller.signal.reason))}runWhenIdle(e){return AsyncWorkScope.runWhenAllIdle(()=>[this],()=>this.track(e))}static async runWhenAllIdle(e,t){let n=e();for(;n.some(e=>e.pending.size>0);)await Promise.allSettled(n.flatMap(e=>Array.from(e.pending))),n=e();return t()}async drain(){for(this.beginClose();this.pending.size>0;)await Promise.allSettled(this.pending);this.phase=`closed`}};y(Symbol.for(`openclaw.gatewayRetainedWorkTimeoutError`),()=>class extends Error{constructor(){super(`Retained Gateway work did not settle after abort; resources remain retained`)}});function runOutsideAsyncWorkScope(e){return Qu.getStore()===void 0?$u.getStore()===void 0?e():$u.exit(e):v(Qu,void 0,()=>($u.enterWith(void 0),e()))}function appendPluginInstanceCleanupFailures(e,t,n){for(let r of n.errors)e.some(e=>e.pluginId===t&&e.error===r)||e.push({pluginId:t,hookId:`instance`,error:r})}function createPluginCacheSdk(){return{hosts:/* @__PURE__ */ new Map,contexts:/* @__PURE__ */ new Map,roots:/* @__PURE__ */ new Set,packageNames:/* @__PURE__ */ new Map,packageSearches:/* @__PURE__ */ new Map,argvDirectories:/* @__PURE__ */ new Map,devSourceRoots:/* @__PURE__ */ new Map,runtimeModules:/* @__PURE__ */ new Map,normalizedJitiAliases:/* @__PURE__ */ new Map,aliasFacts:/* @__PURE__ */ new WeakMap,native:{sdkProviders:/* @__PURE__ */ new Map,nextSdkProviderOrder:0,parents:/* @__PURE__ */ new Map,aliases:/* @__PURE__ */ new Map,registeredHosts:/* @__PURE__ */ new Set,hostRoots:/* @__PURE__ */ new Map,nearestPackageRoots:/* @__PURE__ */ new Map,loaderPackageRoots:/* @__PURE__ */ new Map,allowedParentRoots:/* @__PURE__ */ new Map}}}const nd=y(Symbol.for(`openclaw.pluginCache`),()=>({snapshotOwners:/* @__PURE__ */ new WeakMap,retirements:[]})),rd=y(Symbol.for(`openclaw.pluginCacheRetainers`),()=>/* @__PURE__ */ new WeakMap),id=y(Symbol.for(`openclaw.pluginInstanceCacheOwners`),()=>/* @__PURE__ */ new WeakMap);function releasePluginCacheInstance(e,t){let n=id.get(e);if(t)t.instances.delete(e),n?.delete(t);else{for(let t of n??[])t.instances.delete(e);n?.clear()}n?.size===0&&id.delete(e)}function getPluginCacheRetainers(e){let t=rd.get(e);return t||(t={references:/* @__PURE__ */ new Set,controller:new AbortController,settled:Lt()},rd.set(e,t)),t}function createPluginMetadataCache(){return{current:{snapshot:void 0,owner:`operation`,configFingerprint:void 0,agentWorkspaceFingerprint:void 0,envFingerprint:void 0,defaultDiscoveryCompatible:!1,compatibleConfigFingerprints:void 0,configIdentities:/* @__PURE__ */ new WeakSet},autoEnable:/* @__PURE__ */ new WeakMap,snapshots:/* @__PURE__ */ new Map,derivedIndexes:/* @__PURE__ */ new WeakMap,preparedManifests:/* @__PURE__ */ new WeakMap,snapshotManifestFacts:/* @__PURE__ */ new WeakMap,discovery:/* @__PURE__ */ new Map,sharedDiscovery:/* @__PURE__ */ new Map,projections:/* @__PURE__ */ new WeakMap,projectionSources:/* @__PURE__ */ new WeakMap,completions:/* @__PURE__ */ new WeakMap,indexFacts:/* @__PURE__ */ new WeakMap,providerPolicyOwners:/* @__PURE__ */ new WeakMap,channelAdapters:/* @__PURE__ */ new WeakMap,bundledChannelCatalogs:/* @__PURE__ */ new Map,bundledProviderPolicySurfaces:/* @__PURE__ */ new WeakMap,staticCatalogStates:/* @__PURE__ */ new WeakMap,modelSuppressionResolvers:/* @__PURE__ */ new WeakMap,mcpAuthDeclarations:/* @__PURE__ */ new WeakMap}}function createPluginCache(e={}){return{async[Symbol.asyncDispose](){await retirePluginCache(this)},kind:e.kind??`operation`,roots:/* @__PURE__ */ new Map,rootAliases:/* @__PURE__ */ new Map,sdk:createPluginCacheSdk(),setupModules:/* @__PURE__ */ new Map,instances:/* @__PURE__ */ new Set,metadata:createPluginMetadataCache(),installRecords:/* @__PURE__ */ new Map,persistedInstalledIndex:/* @__PURE__ */ new Map,preparedBundledDiscoveryModes:/* @__PURE__ */ new Map,dependencyStatus:/* @__PURE__ */ new WeakMap,moduleLoaders:/* @__PURE__ */ new Map,sources:/* @__PURE__ */ new Map,sourceAliases:/* @__PURE__ */ new Map,runtimeRecordRoots:/* @__PURE__ */ new WeakMap}}function getProcessPluginCache(){return nd.current??=createPluginCache({kind:`process`})}function getScopedPluginCache(){return d()?.cacheScope?.cache}function getPluginCache(){return getScopedPluginCache()??getProcessPluginCache()}function retirePluginCache(e,t,n){let r=getPluginCacheRetainers(e);if(r.retirement)return r.retirement;let i=Lt();return r.retirement=i.promise,r.controller.abort(),Rt(r.controller.signal.reason),runOutsideAsyncWorkScope(async()=>{r.references.size&&await r.settled.promise;let i=new td;try{return await i.track(()=>beginPluginCacheRetirement(e,t,n))}finally{await i.drain()}}).then(i.resolve,i.reject),i.promise}function beginPluginCacheRetirement(e,n,r){if(e.retirement)return e.retirement;let i=Lt();return e.retirement=i.promise,(async()=>{n?.();let i=e.retireRegistryLoads?.(),a=/* @__PURE__ */ new Set([...e.setupModules.values(),...e.instances]);for(let e of a)e.quiesce();let[s]=await Promise.allSettled([i]),c=await Promise.allSettled([...a].map(async e=>({resource:e,result:await e.dispose(void 0,r)}))),l=e.sourceAdmissions;if(l){let e=c.flatMap(e=>e.status===`fulfilled`?e.value.result.errors.flatMap(e=>e instanceof t?[e.settled]:[]):[]);e.length>0?Promise.allSettled(e).then(()=>l.dispose()).catch(e=>process.emitWarning(`Plugin native capture cleanup failed: ${String(e)}`)):await l.dispose()}e.setupModules.clear();for(let t of e.instances)releasePluginCacheInstance(t,e);let u=[...s.status===`rejected`?[s.reason]:[],...c.flatMap(e=>e.status===`rejected`?[e.reason]:[])];if(u.length)throw AggregateError(u,`Plugin cache resources failed to retire`);let d=s.status===`fulfilled`?s.value:void 0,f=[...d?.failures??[]];for(let e of c){if(e.status!==`fulfilled`)continue;let{resource:t,result:n}=e.value;appendPluginInstanceCleanupFailures(f,t.pluginId,n)}return{cleanupCount:d?.cleanupCount??0,failures:f}})().then(i.resolve,i.reject),i.promise}function parsePackageName(e){let t=JSON.parse(e);return typeof t.name==`string`?t.name:null}async function readPackageName(e,t){t?.throwIfAborted();let n=getPluginCache().sdk.packageNames,r=x.join(x.resolve(e),`package.json`);if(n.has(r))return n.get(r)??null;try{let e=parsePackageName(await pn.readFile(r,{encoding:`utf-8`,signal:t}));return t?.throwIfAborted(),n.set(r,e),e}catch{return t?.throwIfAborted(),n.set(r,null),null}}function readPackageNameSync(e){let t=getPluginCache().sdk.packageNames,n=x.join(x.resolve(e),`package.json`);if(t.has(n))return t.get(n)??null;try{let e=parsePackageName(un.readFileSync(n,`utf-8`));return t.set(n,e),e}catch{return t.set(n,null),null}}async function findPackageRoot(e,t){for(let n of iterAncestorDirs(e))if(await readPackageName(n,t)===`openclaw`)return n;return null}function findPackageRootSync(e){for(let t of iterAncestorDirs(e))if(readPackageNameSync(t)===`openclaw`)return t;return null}function*iterAncestorDirs(e){let t=x.resolve(e);for(let e=0;e<12&&(yield t,x.basename(t)!==`node_modules`);e+=1){let e=x.dirname(t);if(e===t)break;t=e}}function candidateDirsFromArgv1(e){let t=getPluginCache().sdk.argvDirectories,n=x.resolve(e),r=t.get(n);if(r)return[...r];let i=n,a=[];try{let e=un.realpathSync(i);e!==i&&a.push(x.dirname(e))}catch{}a.push(x.dirname(i));let s=i.split(x.sep),c=s.lastIndexOf(`.bin`);if(c>0&&s[c-1]===`node_modules`){let e=x.basename(i),t=s.slice(0,c).join(x.sep);a.push(x.join(t,e))}let l=dedupeCandidates(a);return t.set(n,l),[...l]}function preparePackageRootSearch(e,t){let n=buildCandidates(e),r=n.join(`\0`),i=getPluginCache().sdk.packageSearches,a=i.get(r);return{candidates:n,first:a?.all?a.all[0]??null:a?.first,complete(e){return i.set(r,t?{...i.get(r),first:e}:{first:e}),e}}}async function resolveOpenClawPackageRoot(e){e.signal?.throwIfAborted();let t=preparePackageRootSearch(e,!0);if(t.first!==void 0)return t.first;for(let n of t.candidates){let r=await findPackageRoot(n,e.signal);if(r)return t.complete(r)}return t.complete(null)}function resolveOpenClawPackageRootSync(e){let t=preparePackageRootSearch(e,!1);if(t.first!==void 0)return t.first;for(let e of t.candidates){let n=findPackageRootSync(e);if(n)return t.complete(n)}return t.complete(null)}function buildCandidates(e){let t=[];if(e.moduleUrl)try{t.push(x.dirname(yn(e.moduleUrl)))}catch{}return e.argv1&&t.push(...candidateDirsFromArgv1(e.argv1)),e.cwd&&t.push(e.cwd),dedupeCandidates(t)}function dedupeCandidates(e){return[...new Set(e.map(e=>x.resolve(e)))]}const formatCommit=e=>{let t=e?.match(/[0-9a-fA-F]{7,40}/);return t?u(t[0].slice(0,7)):null},ad=new ne(256),resolveCommitSearchDir=e=>{if(e.cwd)return x.resolve(e.cwd);if(e.moduleUrl)try{return x.dirname(yn(e.moduleUrl))}catch{}return process.cwd()},cacheGitCommit=(e,t)=>(ad.set(e,t),t),resolveGitLookupDepth=(e,t)=>{if(!t)return;let n=x.relative(t,e);if(!(n.startsWith(`..`)||x.isAbsolute(n)))return(n?n.split(x.sep).filter(Boolean).length:0)+1},readCommitFromGit=(e,t)=>{let n=readGitHead(e,{maxDepth:resolveGitLookupDepth(e,t)});return n===void 0?void 0:formatCommit(n.value)},readCommitFromPackageJson=()=>{try{let e=Yt(import.meta.url)(`../../package.json`);return formatCommit(e.gitHead??e.githead??null)}catch{return null}},readCommitProbe=(e,t,n)=>{try{for(let r of t){let t=yn(new URL(r,e)),i;try{i=readGitMetadataPrefix(t,1024)}catch(e){if(f(e))continue;return null}try{let e=l(JSON.parse(i))?.[n];return typeof e==`string`?formatCommit(e):null}catch{return null}}}catch{}},readCommitFromBuildInfo=(e=import.meta.url)=>readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)??null,readLoadedCommit=e=>{let t=readCommitProbe(e,[`../.buildstamp`,`./.buildstamp`],`head`),n=readCommitProbe(e,[`../.runtime-postbuildstamp`,`./.runtime-postbuildstamp`],`head`);return t!==void 0||n!==void 0?t||n?t&&t===n?t:null:readCommitFromBuildInfo(e):readCommitProbe(e,[`../build-info.json`,`./build-info.json`],`commit`)},resolveCommitHash=(e={})=>{let t=e.env??process.env,n=t.GIT_COMMIT?.trim()||t.GIT_SHA?.trim(),r=formatCommit(n);if(r)return r;let i=resolveCommitSearchDir(e),a=ad.get(i);if(a!==void 0)return a;let s=resolveOpenClawPackageRootSync({cwd:e.cwd,moduleUrl:e.moduleUrl});try{let e=readCommitFromGit(i,s);if(e!==void 0)return cacheGitCommit(i,e)}catch{}let c=readCommitFromBuildInfo();if(c)return cacheGitCommit(i,c);let l=readCommitFromPackageJson();return l?cacheGitCommit(i,l):cacheGitCommit(i,null)};function resolveLoadedCommitHash(e={}){let t=e.moduleUrl??import.meta.url,n=readLoadedCommit(t);return n===void 0?resolveCommitHash({moduleUrl:t,...e.env?{env:e.env}:{}}):n}const od=[`../package.json`,`../../package.json`,`../../../package.json`,`./package.json`],sd=[`../build-info.json`,`../../build-info.json`,`./build-info.json`];function readStringFromJsonCandidates(t,n,r,i=!1){try{let a=Yt(t);for(let t of n)try{let n=a(t),s=e(n[r]);if(!s||i&&n.name!==`openclaw`)continue;return s}catch{}return null}catch{return null}}function firstNonEmpty(...t){for(let n of t){let t=e(n);if(t&&t.toLowerCase()!==`undefined`&&t.toLowerCase()!==`null`)return t}}function readVersionFromPackageJsonForModuleUrl(e){return readStringFromJsonCandidates(e,od,`version`,!0)}function readVersionFromBuildInfoForModuleUrl(e){return readStringFromJsonCandidates(e,sd,`version`)}function readBuildProvenanceForModuleUrl(t){try{let n=Yt(t);for(let t of sd)try{let r=n(t),i=e(r.buildId);if(i&&i.length<=96){let a={buildId:i};for(let t of[`version`,`commit`,`builtAt`]){let n=e(r[t]);n&&(a[t]=n)}try{a.buildInfoPath=n.resolve(t)}catch{}return a}}catch{}}catch{}return null}function resolveVersionFromModuleUrl(e){return readVersionFromBuildInfoForModuleUrl(e)||readVersionFromPackageJsonForModuleUrl(e)}function resolveBinaryVersion(e){return resolveVersionFromModuleUrl(e.moduleUrl)||firstNonEmpty(e.bundledVersion)||`0.0.0`}readBuildProvenanceForModuleUrl(import.meta.url);const cd=resolveLoadedCommitHash({moduleUrl:import.meta.url});function resolveRuntimeServiceCommit(){return cd}const ld=resolveBinaryVersion({moduleUrl:import.meta.url,bundledVersion:process.env.OPENCLAW_BUNDLED_VERSION}),ud={"state-migrations":`state migration`,"newer-schema":`a newer OpenClaw build`,"agent-media":`offline media migration`,"audit-events-v2":`state database schema migration`,"legacy-workshop-review-index":`state database schema migration`,"legacy-cron-run-logs":`cron run history migration`,"legacy-workspace":`workspace setup state migration`,"legacy-session-store":`session store migration`};var StartupMaintenanceRequiredError=class extends Error{constructor(e,t,n){super(t,n),this.kind=e,this.code=`gateway.maintenance_required`,this.name=`StartupMaintenanceRequiredError`}get reason(){return ud[this.kind]}},SqliteSchemaVersionError=class extends StartupMaintenanceRequiredError{constructor(e){super(`newer-schema`,e),this.name=`SqliteSchemaVersionError`}};function readSqliteUserVersion(e){let t=executeWithCachedStatement(e,`PRAGMA user_version`,[],e=>e.get());return Number(t?.user_version??0)}function readSqliteWriterAppVersion(e){try{let t=executeWithCachedStatement(e,`SELECT app_version FROM schema_meta WHERE meta_key = 'primary' LIMIT 1`,[],e=>e.get());return typeof t?.app_version==`string`&&t.app_version.length>0?t.app_version:void 0}catch{return}}function describeRunningOpenClawBuild(){let e=resolveRuntimeServiceCommit(),t=resolveOpenClawPackageRootSync({moduleUrl:import.meta.url}),n=e?`OpenClaw ${ld} (${e})`:`OpenClaw ${ld}`;return t?`${n} installed at ${t}`:n}function isNewerSqliteWriterVersion(e){return(compareReleaseVersions(e??``,ld)??0)>0}function createNewerSqliteSchemaVersionError(e,t,n,r,i,a=`runtime`){let s=isNewerSqliteWriterVersion(i),c=s?`; it is newer than this Gateway (${ld}).`:a===`runtime`?`; run openclaw doctor --fix to inspect this database.`:`.`;return new SqliteSchemaVersionError(`This OpenClaw build cannot open your existing data.
${e} ${t} uses newer schema version ${n}; this build supports ${r}.\n`+(i&&(a===`runtime`||i!==ld)?`It was written by OpenClaw ${i}${c}\n`:``)+`Refused by ${describeRunningOpenClawBuild()}.\n`+(s?`Use the newer install that supports schema ${n} or newer, or run openclaw update to update this Gateway service before restarting. To use an older build, restore your pre-update backup created with openclaw backup create.\n`:`Use a build that supports schema ${n} or newer with this state directory. To use an older build, restore your pre-update backup created with openclaw backup create.\n`)+`See ${Ln}.`)}var PluginBlobStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`PluginBlobStoreError`,this.code=t.code,this.operation=t.operation,t.path&&(this.path=t.path)}};function capturePluginStateErrorCause(e,t,n=/* @__PURE__ */ new Set){if(e===void 0)return;let r=t?.(e);if(r)return{canonical:r};if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`)return{name:`Error`,message:String(e)};if(typeof e!=`object`)return{name:`Error`,message:`Unknown SQLite error cause`};if(n.has(e)||n.size>=8)return{name:`Error`,message:`Additional SQLite error cause omitted`};n.add(e);let i=`name`in e&&typeof e.name==`string`?e.name:`Error`,a=`message`in e&&typeof e.message==`string`?e.message:i,s=`code`in e?e.code:void 0,c=`errcode`in e?e.errcode:void 0,l=`errno`in e?e.errno:void 0;return{name:i,message:a,...typeof s==`string`||typeof s==`number`?{errorCode:s}:{},...typeof c==`number`?{errcode:c}:{},...typeof l==`number`?{errno:l}:{},...`cause`in e?{cause:capturePluginStateErrorCause(e.cause,t,n)}:{},...e instanceof AggregateError?{errors:e.errors.slice(0,8).map(e=>capturePluginStateErrorCause(e,t,n))}:{}}}var PluginStateStoreError=class extends Error{constructor(e,t){super(e,{cause:t.cause}),this.name=`PluginStateStoreError`,this.code=t.code,this.operation=t.operation,this.owner=t.owner??{pid:process.pid,threadId:$t,version:ld},t.path&&(this.path=t.path)}toJSON(){return{name:this.name,message:this.message,code:this.code,operation:this.operation,path:this.path,owner:this.owner,cause:capturePluginStateErrorCause(this.cause)}}},SecretStoreValidationError=class extends Error{constructor(e,t){super(t),this.code=e,this.name=`SecretStoreValidationError`}},ModelSelectionLockedError=class extends Error{constructor(e=`Model selection is locked for this session.`){super(e),this.name=`ModelSelectionLockedError`}},SkillUploadRequestError=class extends Error{constructor(...e){super(...e),this.name=`SkillUploadRequestError`}},SkillLibraryError=class extends Error{constructor(e,t,n,r){super(t,r),this.code=e,this.currentRevision=n,this.name=`SkillLibraryError`}},OpenClawAgentDatabaseMediaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(`agent-media`,`OpenClaw agent database ${e} uses schema version ${t}; run openclaw doctor --fix to migrate persisted media before using it.`),this.pathname=e,this.schemaVersion=t,this.name=`OpenClawAgentDatabaseMediaMigrationRequiredError`}},OpenClawStateDatabaseSchemaMigrationRequiredError=class extends StartupMaintenanceRequiredError{constructor(e,t){super(e,`OpenClaw state database schema migration required (${e}) at ${t}; run openclaw doctor --fix to migrate it.`),this.kind=e,this.pathname=t,this.name=`OpenClawStateDatabaseSchemaMigrationRequiredError`}};function normalizeOpenClawStateSchemaReadError(e,t){if(e instanceof Error&&e.message.startsWith(`malformed database schema (idx_skill_workshop_collection_reviews_workspace_time)`)){let n=new OpenClawStateDatabaseSchemaMigrationRequiredError(`legacy-workshop-review-index`,t);return n.cause=e,n}return e}var SessionMetadataUnavailableError=class extends Error{constructor(e,t,n=[]){super(`Session metadata unavailable (${[e,...n].join(`: `)}); retry after the agent store is ready.`,t),this.reason=e,this.missingTables=n,this.name=`SessionMetadataUnavailableError`}};const dd={"worktree-source-changed":SessionWorktreeSourceChangedError,"model-account-authority":ModelAccountConnectAuthorityError,"duplicate-agent":DuplicateAgentError,"model-selection-locked":ModelSelectionLockedError,"session-canonical-key-migration":SessionCanonicalKeyMigrationRequiredError,"session-pending-input-custody":SessionPendingInputCustodyError,"session-transcript-read-fence":SessionTranscriptReadFenceError,"skill-upload-request":SkillUploadRequestError,"state-database-access":Be,coordinator:be,ownership:fe,"newer-schema":SqliteSchemaVersionError,"jsonl-read-budget":SqliteJsonlReadBudgetExceededError,"range-error":RangeError,"syntax-error":SyntaxError,"type-error":TypeError};function isMessageOnlyErrorIdentity(e){return typeof e.type==`string`&&Object.hasOwn(dd,e.type)}function identifyError(e){if(e instanceof SandboxStateOwnerRequiredError)return{type:`sandbox-state-owner-required`};if(e instanceof AuthProfileStoreUnreadableError)return{type:`auth-profile-store-unreadable`,databasePath:e.databasePath};if(e instanceof SessionWorktreeLifecycleError&&e.reason===`owner-mismatch`)return{type:`session-worktree-owner-mismatch`};if(e instanceof WorktreeRemovalContentionError)return{type:`worktree-removal-contention`,kind:e.kind,...e.blockedByRun?{blockedByRun:{worktreeId:e.blockedByRun.worktreeId,pid:e.blockedByRun.pid}}:{}};if(e instanceof WorktreeRemovalLockError)return{type:`worktree-removal-lock`,kind:e.kind};if(e instanceof PluginStateStoreError)return{type:`plugin-state`,stateCode:e.code,operation:e.operation,path:e.path,owner:{pid:e.owner.pid,threadId:e.owner.threadId,version:e.owner.version}};if(e instanceof SkillLibraryError)return{type:`skill-library`,libraryCode:e.code,...e.currentRevision===void 0?{}:{currentRevision:e.currentRevision}};if(e instanceof SecretStoreValidationError)return{type:`secret-store-validation`,secretCode:e.code};if(e instanceof WorkerSessionAlreadyAttachedError)return{type:`worker-session-already-attached`,sessionId:e.sessionId,environmentId:e.environmentId};if(e instanceof PluginBlobStoreError)return{type:`plugin-blob`,blobCode:e.code,operation:e.operation,...e.path===void 0?{}:{path:e.path}};if(e instanceof WorkspaceAliasRepointedError)return{type:`workspace-alias-repointed`,aliasPath:e.aliasPath,storedWorkspacePath:e.storedWorkspacePath,currentWorkspacePath:e.currentWorkspacePath};if(e instanceof McpOAuthStoreCorruptionError)return{type:`mcp-oauth-corruption`};if(e instanceof SessionGoalOperationError)return{type:`session-goal-operation`,goalCode:e.code};if(e instanceof SessionEntryLifecycleUpsertConflictError)return{type:`session-lifecycle-upsert-conflict`,sessionKey:e.sessionKey};if(e instanceof SessionTranscriptWriterClaimReboundError){let t=parseTranscriptAppendRefusal(e.cause);return{type:`session-transcript-writer-claim-rebound`,...t?{refusal:t}:{}}}if(e instanceof SqliteSessionMutationConflictError)return{type:`session-mutation-conflict`,operationLabel:e.operationLabel};if(e instanceof SqliteTranscriptMutationConflictError)return{type:`session-transcript-mutation-conflict`,sessionId:e.sessionId};if(e instanceof SessionMetadataUnavailableError)return{type:`session-metadata`,reason:e.reason,missingTables:[...e.missingTables]};if(e instanceof At)return{type:`state-owner-contention`,databasePath:e.databasePath};if(e instanceof ge)return{type:`state-admission-pending`,databasePath:e.databasePath};if(e instanceof Ne)return{type:`state-offline-maintenance`,databasePath:e.databasePath};if(e instanceof he)return{type:`state-maintenance-scope`};if(e instanceof OpenClawStateLeaseError)return{type:`state-lease`,leaseCode:e.code,leaseLoss:e.loss};if(e instanceof We)return{type:`ownership-metadata`,databasePath:e.databasePath};if(e instanceof Ft)return{type:`external-ownership`,databasePath:e.databasePath,managerId:e.managerId};if(e instanceof OpenClawStateDatabaseSchemaMigrationRequiredError)return{type:`state-migration`,kind:e.kind,pathname:e.pathname};if(e instanceof OpenClawAgentDatabaseMediaMigrationRequiredError)return{type:`agent-media-migration`,pathname:e.pathname,schemaVersion:e.schemaVersion};for(let[t,n]of Object.entries(dd))if(e instanceof n)return{type:t};return e instanceof StartupMaintenanceRequiredError?{type:`maintenance`,kind:e.kind}:{type:e instanceof AggregateError?`aggregate`:`error`}}function createError(e){if(isMessageOnlyErrorIdentity(e)){let t=dd[e.type];return new t(e.message)}switch(e.type){case`sandbox-state-owner-required`:return new SandboxStateOwnerRequiredError;case`session-worktree-owner-mismatch`:return new SessionWorktreeLifecycleError(e.message,`owner-mismatch`);case`worktree-removal-contention`:return new WorktreeRemovalContentionError(e.kind,e.message,e.blockedByRun);case`worktree-removal-lock`:return new WorktreeRemovalLockError(e.kind,e.message);case`plugin-state`:return new PluginStateStoreError(e.message,{code:e.stateCode,operation:e.operation,path:e.path,owner:e.owner});case`skill-library`:return new SkillLibraryError(e.libraryCode,e.message,e.currentRevision);case`secret-store-validation`:return new SecretStoreValidationError(e.secretCode,e.message);case`worker-session-already-attached`:return new WorkerSessionAlreadyAttachedError(e.sessionId,e.environmentId);case`workspace-alias-repointed`:return new WorkspaceAliasRepointedError(e);case`session-goal-operation`:return new SessionGoalOperationError(e.goalCode,e.message);case`session-lifecycle-upsert-conflict`:return new SessionEntryLifecycleUpsertConflictError(e.sessionKey);case`session-mutation-conflict`:return new SqliteSessionMutationConflictError(e.operationLabel);case`session-transcript-mutation-conflict`:return new SqliteTranscriptMutationConflictError(e.sessionId);case`session-transcript-writer-claim-rebound`:return new SessionTranscriptWriterClaimReboundError(e.refusal);case`session-metadata`:return new SessionMetadataUnavailableError(e.reason,void 0,e.missingTables);case`error`:return Error(e.message);case`mcp-oauth-corruption`:return new McpOAuthStoreCorruptionError(``,``);case`aggregate`:return AggregateError([],e.message);case`auth-profile-store-unreadable`:return new AuthProfileStoreUnreadableError(e.databasePath);case`state-owner-contention`:return new At(e.databasePath);case`state-admission-pending`:return new ge(e.databasePath,e.message);case`state-offline-maintenance`:return new Ne(e.databasePath,e.message);case`state-maintenance-scope`:return new he(``);case`ownership-metadata`:return new We(e.databasePath,``);case`external-ownership`:return new Ft(e.databasePath,e.managerId);case`plugin-blob`:return new PluginBlobStoreError(e.message,{code:e.blobCode,operation:e.operation,...e.path===void 0?{}:{path:e.path}});case`state-lease`:return new OpenClawStateLeaseError(e.message,{code:e.leaseCode,loss:e.leaseLoss});case`maintenance`:return new StartupMaintenanceRequiredError(e.kind,e.message);case`state-migration`:return new OpenClawStateDatabaseSchemaMigrationRequiredError(e.kind,e.pathname)}return new OpenClawAgentDatabaseMediaMigrationRequiredError(e.pathname,e.schemaVersion)}function isScalar(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e)}function isNativeErrorCode(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0&&e<=2147483647}function isWorkerOutcomeCode(e){return e===`outcome-unknown`||e===`unavailable`}function encodeOpenClawStateWorkerError(e,t={}){if(!(e instanceof Error))return;let n=[],r=[],i=/* @__PURE__ */ new Map,a=!1,encodeValue=e=>{if(!(e instanceof Error))return isScalar(e)?{value:e}:{undefined:!0};let t=i.get(e);if(t!==void 0)return{ref:t};let n=r.length;return i.set(e,n),r.push(e),{ref:n}};try{encodeValue(e);for(let e of r){let{name:t,message:r}=e;if(typeof t!=`string`||typeof r!=`string`)return;let i=identifyError(e);if(Object.entries(i).some(([e,t])=>(e===`owner`||e===`blockedByRun`||e===`refusal`||e===`leaseLoss`&&t!==void 0?Object.values(t):e===`missingTables`&&Array.isArray(t)?t:[t]).some(e=>e!==void 0&&!isScalar(e))))return;let s=oe(e),c=lt(e,`outcome-unknown`)||lt(e,`unavailable`),l=readOpenClawStateDatabaseFailurePath(e),u=`errcode`in e?e.errcode:void 0;a||=c||l!==void 0||s||isNativeErrorCode(u)||Fe(e)||e instanceof Ju||i.type!==`error`&&i.type!==`aggregate`;let d=`code`in e?e.code:void 0,f=`errno`in e?e.errno:void 0;n.push({...i,name:c?`SqliteWorkerError`:t===`SqliteWorkerError`&&isWorkerOutcomeCode(d)?`Error`:t,message:r,...typeof d==`string`||typeof d==`number`&&Number.isFinite(d)?{code:d}:{},...isNativeErrorCode(u)?{errcode:u}:{},...typeof f==`number`&&Number.isInteger(f)?{errno:f}:{},...s?{nativeOpen:!0}:{},...l===void 0?{}:{stateDatabasePath:l},...`cause`in e&&!(i.type===`session-transcript-writer-claim-rebound`&&i.refusal)?{cause:encodeValue(e.cause)}:{},...e instanceof AggregateError?{errors:e.errors.map(encodeValue)}:{}})}return a||t.includeOrdinary===!0?{version:1,root:0,nodes:n}:void 0}catch{return}}function decodeErrorGraph(e,t){try{if(e.version!==1)return;let n=e.nodes;if(t.includeOrdinary!==!0&&!n.some(e=>e.stateDatabasePath!==void 0||e.nativeOpen===!0||e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)||isNativeErrorCode(e.errcode)||Fe(e)||e.type===`aggregate`&&e.name===`OpenClawQuarantineReadCleanupError`||e.type!==`error`&&e.type!==`aggregate`))return;let r=n.map(e=>{if(e.name===`SqliteWorkerError`&&isWorkerOutcomeCode(e.code)){let t=new st(e.message,e.code);return e.type===`error`?t:yt(createError(e),t)}return createError(e)}),decodeValue=e=>`ref`in e?r[e.ref]:`value`in e?e.value:void 0;for(let[e,t]of n.entries()){let n=r[e];n.name=t.name,n.message=t.message,t.nativeOpen&&Et(n),t.stateDatabasePath!==void 0&&markOpenClawStateDatabaseFailure(n,t.stateDatabasePath);for(let[e,r]of Object.entries({...t.code===void 0?{}:{code:t.code},...t.errcode===void 0?{}:{errcode:t.errcode},...t.errno===void 0?{}:{errno:t.errno},...t.cause?{cause:decodeValue(t.cause)}:{}}))Object.defineProperty(n,e,{value:r,configurable:!0,writable:!0});n instanceof AggregateError&&(n.errors=(t.errors??[]).map(decodeValue))}return{errors:r,root:e.root}}catch{return}}const fd=y(Symbol.for(`openclaw.sharedStateWorkerErrorPayloads`),()=>/* @__PURE__ */ new WeakMap);function retainOpenClawStateWorkerErrorPayload(e,t){t&&fd.set(e,t)}function hydrateOpenClawStateWorkerError(e,t={}){if(!(e instanceof Error))return e;let n=/* @__PURE__ */ new Map,r=[{error:e,finish:!1}],replace=e=>e instanceof Error?n.get(e)??e:e;for(;r.length>0;){let e=r.pop(),{error:i}=e;if(!e.finish){if(n.has(i))continue;n.set(i,i);let e=fd.get(i),a=e===void 0?void 0:decodeErrorGraph(e,t);if(a){n.set(i,a.errors[a.root]);continue}if(r.push({error:i,finish:!0}),i.cause instanceof Error&&r.push({error:i.cause,finish:!1}),i instanceof AggregateError)for(let e of i.errors)e instanceof Error&&r.push({error:e,finish:!1});continue}let a=replace(i.cause),s=i instanceof AggregateError?i.errors:void 0,c=s?.map(replace);if(a===i.cause&&(!c||c.every((e,t)=>e===s?.[t])))continue;let l=i instanceof AggregateError?AggregateError([],i.message):Error(i.message);Object.setPrototypeOf(l,Object.getPrototypeOf(i));let u=Object.getOwnPropertyDescriptors(i);`cause`in i&&(u.cause={configurable:!0,writable:!0,...u.cause,value:a}),c&&(u.errors={configurable:!0,writable:!0,...u.errors,value:c}),Object.defineProperties(l,u),n.set(i,l)}return n.get(e)}const pd=/* @__PURE__ */ new Map;let md;async function startHeartbeat(e,t,n=!1){let r=Date.now()+6e4,i,a=JSON.stringify([e.path,e.expectedIdentity]),admissionFailure=e=>new OpenClawStateLeaseError(`state lease heartbeat database admission failed`,{code:`OPENCLAW_STATE_LEASE_STORAGE_FAILED`,loss:{reason:`admission-failed`},cause:e}),operationLoss=e=>e instanceof OpenClawStateLeaseError&&e.loss?e.loss:{reason:`storage-failed`};function withDatabaseAdmission(t){return Ae((t,n,r,i)=>{try{return rt(e.databaseAdmissionPort,t,n,r,i)}catch(e){throw admissionFailure(e)}},t)}let s=new BigInt64Array(e.shared),c=new BigInt64Array(e.renewalProgress);Atomics.store(s,$.startupPhase,Gu[`body-entry`]);function observeDurableExpiry(e){return Atomics.store(s,$.expiresAt,BigInt(e??0)),e}function openHeartbeatDatabaseOnce(){let t=md?.(e.path,e.expectedIdentity);if(t)return{database:t.database.db,close:()=>{t.close()}};let n=openTrackedStateDatabase(e.path,{existingOnly:!0,expectedIdentity:e.expectedIdentity});return{database:n,close:()=>closeTrackedStateDatabase(n)}}function openHeartbeatDatabase(){let remaining=()=>Math.min(r,Number(Atomics.load(s,$.expiresAt)))-Date.now();for(;remaining()>0&&Atomics.load(s,$.status)===$.starting;){try{return openHeartbeatDatabaseOnce()}catch(e){if(!Fe(e))throw e}Atomics.wait(s,$.status,$.starting,Math.max(1,Math.min(25,remaining())))}throw Error(`state lease heartbeat startup deadline expired or owner stopped`)}let l;function assertDatabaseAccess(){try{assertStateDatabaseAccessAllowed(e.path);let t=readTrackedStateDatabaseIdentity(l);if(!t)throw Error(`State lease heartbeat database has no admitted physical identity`);ke(e.path,e.expectedIdentity,t.birthtime)}catch(e){throw admissionFailure(e)}}function withHeartbeatDatabase(e){let t=i;if(!t)throw Error(`State lease heartbeat database is closed`);l=t.database,assertDatabaseAccess();try{return e()}catch(n){if(!b(l)||l.isOpen)throw n;return t.close(),Object.assign(t,openHeartbeatDatabaseOnce()),l=t.database,assertDatabaseAccess(),e()}}let u=e.processOwner,d,f=!1,p=!1,m={identity:e.identity,leaseMs:e.leaseMs,intervalMs:e.heartbeatMs,execute:e=>withRenewalProgress(()=>withHeartbeatDatabase(e)),complete:e=>runAutomatic(()=>renewInWorker(!1,`automatic-renewal`,e),`automatic-renewal`)},close=()=>{if(!f){clearTimeout(d),i?.renewals.cancel(m);try{i&&=(i.references===1?(i.close(),pd.delete(a)):i.references--,void 0)}catch(e){t.postMessage({startupError:ee(e)},[]);return}f=!0,e.databaseAdmissionPort.close(),e.lossPort.close(),t.off(`message`,receiveMessage),n?t.postMessage({closed:!0},[]):t.close()}},h=0,g,observeLoss=()=>{try{return withDatabaseAdmission(()=>readOpenClawStateLeaseLoss(i?.database??l,e.identity))}catch(e){return operationLoss(e)}},recordLoss=t=>{g||Atomics.load(s,$.status)===$.closed||(g=t,e.lossPort.postMessage(t,[]))},lose=e=>{recordLoss(e),Atomics.compareExchange(s,$.status,$.starting,$.lost),Atomics.compareExchange(s,$.status,$.ready,$.lost),close()},renewInWorker=(n,r,a)=>{if(Atomics.load(s,$.status)>=$.closed)return;let c,f;h+=1;try{if(a&&`error`in a)throw a.error;u?.identity.startedAt===null&&Atomics.load(s,$.status)===$.ready&&(u.identity.startedAt=getFileLockProcessStartTime(u.identity.pid,u.env));let renew=()=>runSqliteImmediateTransactionSync(l,()=>{if(assertDatabaseAccess(),!(Atomics.load(s,$.status)>=$.closed))return renewOpenClawStateLeaseInTransaction(l,e.identity,e.leaseMs,u?.identity)},{operationLabel:`state.lease.renew`,logger:{warn(){}}});c=a?a.expiresAt:withHeartbeatDatabase(()=>b(l)?renew():runWithSqliteBusyTimeout(l,0,renew,{lockFailureReporting:`suppress`})),c!==void 0&&Atomics.store(s,$.lastRenewedAt,BigInt(c-e.leaseMs)),c!==void 0&&u?.identity.startedAt!=null&&(u=void 0)}catch(a){if(!Fe(a)){if(t.postMessage({name:a instanceof Error?a.name:`Error`,message:ee(a),code:Tt(a),errcode:ft(a),attempt:h,elapsedMs:Date.now()-e.acquiredAt},[]),n)throw a;lose({path:r,outcome:`operation-error`,leaseLoss:operationLoss(a)});return}if(f=a,!b(l)&&Atomics.load(s,$.ownerFence)===1n){if(clearTimeout(d),i?.renewals.cancel(m),p||(p=!0,Promise.resolve(Atomics.waitAsync(s,$.ownerFence,1n).value).then(()=>{p=!1,runAutomatic(renew,`automatic-renewal`)})),n)throw a;return Number(Atomics.load(s,$.expiresAt))}assertDatabaseAccess(),c=readOpenClawStateLeaseExpiry(l,e.identity)}if(observeDurableExpiry(c),c===void 0)n||lose({path:r,outcome:`no-current-owned-unexpired-row`,leaseLoss:observeLoss()});else{if(clearTimeout(d),i?.renewals.cancel(m),f===void 0&&u===void 0&&(!e.deferActivation||Atomics.load(s,$.status)===$.ready))return i?.renewals.schedule(m,c),c;if(d=setTimeout(()=>{e.deferActivation&&Atomics.load(s,$.status)===$.starting?runAutomatic(activateHeartbeat,`activation`):runAutomatic(renew,`automatic-renewal`)},Math.max(1,Math.min(f===void 0?e.heartbeatMs:25,c-Date.now()))),d.unref(),n&&f!==void 0)throw te(f,`state lease heartbeat renewal was delayed`);return c}};function withRenewalProgress(e){Atomics.add(c,0,1n);try{return withDatabaseAdmission(e)}finally{Atomics.add(c,0,1n),Atomics.notify(c,0)}}let renew=(e=!1,t=`automatic-renewal`)=>withRenewalProgress(()=>renewInWorker(e,t));function activateHeartbeat(){let n;try{Atomics.store(s,$.startupPhase,Gu[`initial-renew-start`]),n=renew(e.deferActivation===!0,`activation`),Atomics.store(s,$.startupPhase,Gu[`initial-renew-returned`])}catch(t){if(e.deferActivation&&Fe(t)){clearTimeout(d),d=setTimeout(()=>runAutomatic(activateHeartbeat,`activation`),Math.max(1,Math.min(25,Number(Atomics.load(s,$.expiresAt))-Date.now())));return}lose({path:`activation`,outcome:`operation-error`,leaseLoss:operationLoss(t)});return}n===void 0?lose({path:`activation`,outcome:`no-current-owned-unexpired-row`,leaseLoss:observeLoss()}):Atomics.compareExchange(s,$.status,$.starting,$.ready)===$.starting&&t.postMessage(null,[])}let receive=n=>{if(`registration`in n)return;if(`close`in n){Atomics.store(s,$.status,$.closed),close();return}if(`startup`in n){e.deferActivation&&Atomics.load(s,$.status)===$.starting&&activateHeartbeat();return}if(Atomics.load(s,$.status)!==$.ready)return;let r,i=!1,a=`operation-error`,c,u=n.operation===`renew`?`explicit-renew`:`explicit-verify`;try{let t=n.operation===`renew`?renew(!0,u):withDatabaseAdmission(()=>withHeartbeatDatabase(()=>observeDurableExpiry(readOpenClawStateLeaseExpiry(l,e.identity))));if(t===void 0)throw a=`no-current-owned-unexpired-row`,createOpenClawStateLeaseLostError(e.identity,void 0,observeLoss());r={id:n.id,ok:!0,expiresAt:t}}catch(e){i=!Fe(e);let t=e instanceof OpenClawStateLeaseError?e:new OpenClawStateLeaseError(`failed to ${n.operation} state lease heartbeat`,{code:`OPENCLAW_STATE_LEASE_STORAGE_FAILED`,loss:operationLoss(e),cause:e});c=operationLoss(t),r={id:n.id,ok:!1,message:t.message,payload:encodeOpenClawStateWorkerError(t)}}i&&recordLoss({path:u,outcome:a,leaseLoss:c}),t.postMessage(r,[]),i&&lose({path:u,outcome:a,leaseLoss:c})};function runAutomatic(e,t){try{e()}catch(e){lose({path:t,outcome:`operation-error`,leaseLoss:operationLoss(e)})}}function receiveMessage(e){runAutomatic(()=>receive(e),`automatic-renewal`)}try{if(e.postgresPool&&Dt(e.postgresPool),e.databaseEngineSelection&&$e(e.databaseEngineSelection),stateEngineInput()&&!md&&(md=(await import(`./openclaw-state-lease-heartbeat.worker-openclaw-state-db-engine-Dm1_z5Gw.mjs`)).openExistingStatePostgresConnection,Atomics.load(s,$.status)!==$.starting||Math.min(r,Number(Atomics.load(s,$.expiresAt)))<=Date.now()))throw Error(`state lease heartbeat startup deadline expired or owner stopped`);let n=pd.get(a);if(n)i=n,i.references++;else{let e={...withDatabaseAdmission(openHeartbeatDatabase),renewals:createStateLeaseRenewalScheduler(()=>e.database),references:1};i=e,pd.set(a,e)}l=i.database,Atomics.store(s,$.startupPhase,Gu[`open-complete`]),t.on(`message`,receiveMessage),e.deferActivation?t.postMessage({startup:`prepared`},[]):runAutomatic(activateHeartbeat,`activation`)}catch(e){t.postMessage({startupError:ee(e)},[]),close()}}if(!Qt)throw Error(`State lease heartbeat requires its parent port`);serveWorkerMemorySamples(Qt);let hd=Promise.resolve();Qt.on(`message`,e=>{`registration`in e&&(hd=hd.then(()=>startHeartbeat(e.registration,e.port)))}),hd=startHeartbeat(en,Qt,!0);export{createSqliteQueryCache as $,openNodeSqliteDatabase as A,observeOpenClawDatabaseMaintenanceResource as At,admitPostgresPhysicalFacts as B,assertStateDatabaseReadAllowed as C,Nn as Ct,readProcessPackageIdentity as D,getOpenClawDatabaseMaintenanceResourceScope as Dt,classifyOpenClawEntrypointPath as E,isStateDatabaseReadAdmissionInvalidatedError as Et,getAdmittedSqliteSchemaFacts as F,postgresSchemaSql as G,admitPostgresCapabilities as H,isSqliteSchemaAdmissionCold as I,verifyAndRecordPostgresSchema as J,postgresStoreNamespace as K,runSqliteReadOperationSync as L,resolveImmutableSqliteFileUri as M,resolveDatabasePath as Mt,admitSqliteSchema as N,resolveOpenClawStateSqlitePath as Nt,readProcessWorkingDirectories as O,getOpenClawDatabaseMaintenanceScope as Ot,beginPostgresReadSnapshotScope as P,resolveQuarantineStorePath as Pt,assertPostgresCatalog as Q,captureSqliteSchemaFacts as R,assertStateDatabaseAccessAllowed as S,In as St,classifyOpenClawArgv as T,createOpenClawStateDatabaseAsyncLifecycle as Tt,getAdmittedPostgresSchema as U,getPostgresPhysicalFacts as V,yu as W,withPostgresSearchExtensions as X,verifyPostgresSchema as Y,admitPostgresSearch as Z,retainSqliteWriteAdmissionService as _,readLinuxProcessStat as _t,readSqliteUserVersion as a,getRootOptionAwareCommandPath as at,observeDatabaseOperation as b,isContainerEnvironment as bt,resolveOpenClawPackageRoot as c,_usingCtx as ct,Ju as d,registerNodeSqliteKyselyQueryErrorHandler as dt,executeSqliteQuerySync as et,closeStateDatabaseHandle as f,getFileLockProcessStartTime as ft,stateEngineInput as g,parseLinuxProcessStat as gt,registerSqliteWalWorkerMaintenance as h,isPidDefinitelyDeadAsync as ht,createNewerSqliteSchemaVersionError as i,SqliteQueryCompiler as it,resolveExistingSqliteFileUri as j,readCustodiedDrainedSqliteSource as jt,referencesRetainedArtifact as k,isOpenClawDatabaseMaintenanceResourceOwned as kt,findOpenClawStateDatabaseFailure as l,sha256Hex as lt,readTrackedStateDatabaseIdentity as m,isPidDefinitelyDead as mt,retainOpenClawStateWorkerErrorPayload as n,prepareSqliteQuerySync as nt,readSqliteWriterAppVersion as o,isUpdateCommandArgv as ot,openTrackedStateDatabase as p,getProcessInstanceStartTime as pt,readPostgresSchema as q,normalizeOpenClawStateSchemaReadError as r,parseNodeReleaseVersion as rt,ld as s,rewriteUpdateFlagArgv as st,hydrateOpenClawStateWorkerError as t,getNodeSqliteKysely as tt,markOpenClawStateDatabaseFailure as u,executeWithCachedStatement as ut,runSqliteImmediateTransactionSync as v,mergeProcessEnv as vt,captureStateDatabaseAccess as w,StateDatabaseReadAdmissionInvalidatedError as wt,acquireStateDatabaseSchemaLease as x,Ln as xt,observeConnection as y,resolveDiagnosticProcessEnv as yt,Tu as z};