openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
258 lines • 216 kB
JavaScript
import{B as coerceErrorMessage,K as toErrorObject,T as normalizeWindowsPathForComparison,U as extractErrorCode,at as hasErrnoCode,c as FsSafeError$1,f as resolveStateDir,it as resolveGlobalSingleton,l as root,n as resolveGatewayLockDir,r as resolveGatewayLockDirForCanonicalStateDir,st as isErrno,v as resolveRequiredOsHomeDir,yt as isRecord,z as runInDetachedAsyncContext}from"./paths--OfTlHNJ.js";import{_ as groupPluginRecords,a as resolvePreferredOpenClawTmpDir,t as createSubsystemLogger}from"./subsystem-ClzPkrHG.js";import{n as resolveIdentityPathViaExistingAncestor,r as resolveIdentityPathViaExistingAncestorSync}from"./path-existence-CCBbp2xL.js";import{t as createDeferredCore}from"./deferred-Btxs3f7l.js";import{i as settlesWithin}from"./async-work-scope-BmlBpc8q.js";import{a as requestCliParentTermination,i as getCliParentPid,o as RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS}from"./cli-invocation-BQt-q4O8.js";import{n as resolveRuntimeWorkerThreadExecArgv}from"./runtime-worker-url-C_8irENp.js";import{$t as createSqliteTableContract,Dn as normalizeDatabasePath,Dt as markSqliteInspectionOperation,Gn as resolveRuntimeProcessEntrypointUrl,In as isPromiseLike,Mt as sqliteExtendedResultCode,Nn as assertSyncTransactionResult,Nt as sqlitePrimaryResultCode,Pn as isPostgresSqlConnection,Pt as withSqliteInspectionOperation,Qt as createSqliteIndexContract,Sn as assertDatabaseFileIdentity,Wn as readProcessMachineIdentity,Yt as requireNodeSqlite,_ as currentSqliteOperationTiming,_n as recordSqliteTransactionWriter,_t as prepareSqliteTransactionCommit,dn as runWithSqliteCleanup,g as captureSqliteReaderOwner,gn as readSqliteTransactionWriter,ht as discardSqliteTransactionState,jt as sqliteErrorCode,kt as readSqliteInspectionOperation,r as captureRuntimeWorkerSource,sn as SqliteSnapshotCleanupError,v as readSqliteOperationHoldContext,vn as sqliteTransactionWriterSlot,wt as isSqliteLockError,x as retainSqliteReader,xt as withSqlitePostCommitPublications}from"./sqlite-worker-request-class-l9sdQxsj.js";import{B as isPrivateDirectoryCreationRefused,C as publishPreparedCopy,Ct as normalizeSqliteNonNegativeInteger,D as removeTempDirectoryAsync,Dt as shouldReportSqliteLockFailure,E as removeTempDirectory,Ft as kyselyByDatabase,G as resolveReadOnlyShmSqliteFileUri,H as openNodeSqliteDatabase,It as queryErrorHandlerByDatabase,K as resolveSqliteFilesystemPath,N as SQLITE_SNAPSHOT_PREFIX,Nt as executeWithCachedStatement,P as acquireSqliteSnapshotToken,Pt as installStatementInvalidation,R as SqliteSnapshotCapacityError,S as preparationCleanupError,T as registerSnapshotTempDirectory,Tt as runWithSqliteBusyTimeout,Ut as getOpenClawDatabaseMaintenanceScope,V as markPrivateDirectoryCreationRefused,et as runSqliteReadOperationSync,jt as disposeSqliteStatement,k as retainSnapshotWork,kt as clearNodeSqliteKyselyCacheForDatabase,l as resolveOpenClawStateDirForDatabasePath,wt as readSqliteBusyTimeout,x as discardPreparedCopyPayload,y as cleanupFailedSnapshotPreparation,z as hasSqliteSnapshotCapacityCode}from"./openclaw-state-db-async-lifecycle-DFpGMybR.js";import{a as normalizeSchemaSql,c as quoteSqliteIdentifier}from"./sqlite-schema-sql-D2HdV_QG.js";import{C as GatewayStateOwnerContentionError,D as StateDatabaseOfflineMaintenanceError,E as StateDatabaseMaintenanceScopeError,O as createGatewayStateProcessOwnerRetiredError,T as StateDatabaseAdmissionPendingError,p as createCpuTrackedWorker,w as StateDatabaseAccessError,x as recordWorkerMessage}from"./sqlite-worker-operation-settlement-DUfe98Na.js";import{s as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS}from"./openclaw-state-db-contract-lz-66XzZ.js";import{i as isPidDefinitelyDead,r as isPidAlive,t as getFileLockProcessStartTime}from"./pid-alive-b9rOSUDi.js";import{o as getCommandPositionalsWithRootOptions,t as classifyOpenClawArgv,u as isContainerEnvironment}from"./gateway-process-argv-DG4ixJQ7.js";import path from"node:path";import fsPromises from"node:fs/promises";import fs,{chmodSync,fstatSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{toUSVString}from"node:util";import{copyRootFileSync,createDirectorySync,createFileSync,readFileWindowFullySync,sameFileContentsSync,sameFileIdentity}from"@openclaw/fs-safe/advanced";import{FsSafeError}from"@openclaw/fs-safe/errors";import{createHash,hash,randomUUID}from"node:crypto";import os from"node:os";import{AsyncLocalStorage}from"node:async_hooks";import{MessageChannel,isMainThread,threadId}from"node:worker_threads";import{execFile,spawnSync}from"node:child_process";import{channel}from"node:diagnostics_channel";import{GCProfiler}from"node:v8";import{Buffer as Buffer$1}from"node:buffer";import{setTimeout as setTimeout$1}from"node:timers/promises";import{acquireFileLockSync}from"@openclaw/fs-safe/file-lock";import{InsertQueryNode,Kysely,OperatorNode,PostgresDialect,PostgresQueryCompiler,RawNode,SelectQueryNode,SqliteDialect,ValueNode,sql}from"kysely";
//!src/infra/sqlite-backup.ts
async function backupNodeSqliteDatabase(e,t,n){const r=setInterval(()=>{},100);try{const r=await requireNodeSqlite().backup(e,resolveSqliteFilesystemPath(t),{progress:n});n?.({totalPages:r,remainingPages:0});return r}finally{clearInterval(r)}}
//!src/infra/sqlite-file-copy.ts
async function copySqliteFile(e,t,n,r={}){const{beforeByteCopy:i,clone:a=`auto`}=r;const o=await root(path.dirname(e));const s=await root(path.dirname(t));let c;const copy=r=>s.copyIn(path.basename(t),{relativePath:path.basename(e),root:{stat:e=>o.stat(e),open:async(t,r)=>{const i=await o.open(t,r);try{if(!sameFileIdentity(n,await i.handle.stat({bigint:true})))throw new Error(`SQLite copy source changed: ${e}`);return i}catch(e){await i.handle.close();throw e}}}},{clone:r,...i?{maxBytes:Number(n.size)}:{},sourceHardlinks:`allow`,overwrite:false,mode:384,durable:true,onDestinationPublished:e=>{c=e}});if(i&&a===`auto`)try{await copy(`always`)}catch(e){if(c||!(e instanceof FsSafeError$1)||!(e.code===`unsupported-platform`||e.code===`helper-unavailable`&&e.message===`native file cloning is unavailable`))throw e;await i(Number(n.size));await copy(`never`)}else{await i?.(Number(n.size));await copy(a)}if(!c)throw new Error(`SQLite copy was not published: ${t}`);return c}
//!src/infra/windows-private-directory.ts
function createPrivateWindowsDirectory(e){let t=false;try{createDirectorySync(path.resolve(e),{private:true,assertBeforeMutation(){t=true}})}catch(e){if(!t||e instanceof FsSafeError&&e.code===`already-exists`)throw markPrivateDirectoryCreationRefused(e);throw e}}
//!src/infra/sqlite-private-directory.ts
const SQLITE_DIRECTORY_MODE=448;function resolvePrivateSqliteSnapshotStagingRoot(e=process.env){try{return resolveSnapshotStagingRoot(e)}catch(e){if(e instanceof Error&&hasSqliteSnapshotCapacityCode(e))throw new SqliteSnapshotCapacityError(`SQLite snapshot staging root is unavailable: ${e.message}; free disk space/quota`,{cause:e});throw e}}function resolveSnapshotStagingRoot(e){const t=e.OPENCLAW_UPDATE_IN_PROGRESS===`1`?e.TMPDIR?.trim():void 0;if(t&&path.isAbsolute(t))return resolvePreferredOpenClawTmpDir({preferredDir:path.join(t,`openclaw`),tmpdir:()=>t});const n=process.platform===`win32`?e.LOCALAPPDATA?.trim():void 0;const r=process.platform===`win32`?`AppData/Local`:`.cache`;const i=process.platform===`darwin`?`Library/Caches`:r;const a=[e.XDG_CACHE_HOME?.trim(),n].find(e=>e&&path.isAbsolute(e))??path.join(resolveRequiredOsHomeDir(e),i);const o=resolveStateDir(e);const s=createHash(`sha256`).update(o).digest(`hex`).slice(0,24);fs.mkdirSync(a,{recursive:true,mode:SQLITE_DIRECTORY_MODE});const c=resolvePreferredOpenClawTmpDir({preferredDir:path.join(a,`openclaw`),tmpdir:()=>a});const[l=``,...u]=path.relative(c,o).split(path.sep);const d=u.length>0&&/^sqlite-[a-f0-9]{24}$/u.test(l)?l:`sqlite-${s}`;const f=path.join(c,d);fs.mkdirSync(f,{recursive:true,mode:SQLITE_DIRECTORY_MODE});const p=fs.lstatSync(f);if(!p.isDirectory()||process.getuid&&p.uid!==process.getuid()||process.platform!==`win32`&&(p.mode&63)!==0)throw new Error(`SQLite snapshot namespace must be a private user-owned directory`);return f}function createPrivateSqliteTempDirectorySync(e,t){if(process.platform!==`win32`)try{return fs.mkdtempSync(path.join(e,t))}catch(e){throw markPrivateDirectoryCreationRefused(e)}const n=path.join(e,`${t}${randomUUID()}`);createPrivateWindowsDirectory(n);return n}
//!src/infra/disk-space.ts
function finiteNonNegativeNumber(e){const t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function findExistingDiskSpacePath(e){let t=path.resolve(e);while(true)try{return fs.statSync(t).isDirectory()?t:path.dirname(t)}catch{const e=path.dirname(t);if(e===t)return null;t=e}}function tryReadDiskSpace(e){const t=findExistingDiskSpacePath(e);if(!t)return null;try{const n=fs.statfsSync(t);const r=finiteNonNegativeNumber(n.bsize);const i=finiteNonNegativeNumber(n.bavail);if(r===null||i===null)return null;const a=finiteNonNegativeNumber(n.blocks);return{targetPath:e,checkedPath:t,availableBytes:r*i,totalBytes:a===null?null:r*a}}catch{return null}}function formatDiskSpaceBytes(e){const t=e/1048576;const n=Math.max(0,Math.round(t));if(n<1024)return`${n} MiB`;const r=t/1024;return`${r.toFixed(r<10?1:0)} GiB`}
//!src/infra/sqlite-schema-catalog.ts
function readSqliteImageSizeBytes(e){return Number(e.prepare(`PRAGMA page_count;`).get()?.page_count)*Number(e.prepare(`PRAGMA page_size;`).get()?.page_size)}function createSqliteTableContractReader(e,t=[],n=[]){let r;let i;const a=/* @__PURE__ */ new Set;const readCatalog=(o=[])=>{if(!r){const i=[...n,...o];r=readSqliteSchemaCatalog(e,{viewNames:t,virtualTableNames:i});for(const e of r.tables)if(e.sql&&/^CREATE VIRTUAL TABLE /iu.test(e.sql)&&!i.includes(e.name))a.add(e.name)}else for(const t of o){if(!a.has(t))continue;const n=readSqliteColumnCatalog(e,t);r={...r,tables:r.tables.map(e=>e.name===t?{...e,columns:n}:e)};a.delete(t);i=void 0}return r};return Object.assign(e=>{const t=readCatalog([e]);return(i??=sqliteSchemaContractFromCatalog(t)).get(e)},{readCatalog:(n,r)=>n.every(e=>t.includes(e))?readCatalog(r):readSqliteSchemaCatalog(e,{viewNames:n,virtualTableNames:r}),readView:n=>{return(t.includes(n)?readCatalog().views:readSqliteSchemaCatalog(e,{viewNames:[n],virtualTableNames:[]}).views).find(e=>e.name===n)}})}function sqliteSchemaContractFromCatalog(e){return new Map(e.tables.map(e=>[e.name,createSqliteTableContract(e.name,e,{schema:`main`,name:e.name,strict:e.strict,wr:e.withoutRowid},e.indexes.map(e=>createSqliteIndexContract(e,e.sql,e.terms)).toSorted(compareJson),e.triggers,e.columns,e.foreignKeys)]))}function readSqliteSchemaCatalog(e,t={}){const n=e.prepare(`SELECT type, name, tbl_name, sql FROM main.sqlite_schema ORDER BY name`).all();const r=n.filter(e=>e.type===`table`&&!e.name.startsWith(`sqlite_`));const i=n.filter(e=>e.type===`view`&&(!t.viewNames||t.viewNames.includes(e.name)));if(r.length===0&&i.length===0)return{tables:[],views:[]};const a=e.prepare(`PRAGMA table_list`).all();const o=a.filter(e=>e.schema===`main`&&e.type===`virtual`&&t.virtualTableNames&&!t.virtualTableNames.includes(e.name)).map(e=>e.name);const s=a.some(e=>[`pragma_index_list`,`pragma_index_xinfo`,`pragma_table_xinfo`,`pragma_foreign_key_list`].includes(e.name.toLowerCase()));let c;let l;if(!s){c=/* @__PURE__ */ new Map;l=/* @__PURE__ */ new Map;const t=e.prepare(`
SELECT t.name AS table_name, i.seq AS index_seq,
i.name AS index_name, i.origin, i.partial, i."unique",
x.seqno, x.cid, x.name, x."desc", x.coll, x."key"
FROM main.sqlite_schema AS t
CROSS JOIN pragma_index_list(t.name, 'main') AS i
LEFT JOIN pragma_index_xinfo(i.name, 'main') AS x ON 1 = 1
WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_'
ORDER BY t.name, i.seq, x.seqno
`).all();for(const e of t){const t=c.get(e.table_name)??[];if(t.at(-1)?.index_seq!==e.index_seq){t.push({table_name:e.table_name,index_seq:e.index_seq,name:e.index_name,origin:e.origin,partial:e.partial,unique:e.unique});c.set(e.table_name,t)}if(e.seqno!==null){const t=l.get(e.table_name)??[];t.push({table_name:e.table_name,index_seq:e.index_seq,seqno:e.seqno,cid:e.cid,name:e.name,desc:e.desc,coll:e.coll,key:e.key});l.set(e.table_name,t)}}}const u=!t.viewNames?`t.type IN ('table', 'view')`:t.viewNames.length>0?`t.type = 'table' OR (t.type = 'view' AND t.name IN (${t.viewNames.map(()=>`?`).join(`, `)}))`:`t.type = 'table'`;const d=o.length?`AND t.name NOT IN (${o.map(()=>`?`).join(`, `)})`:``;const f=s?void 0:groupPluginRecords(e.prepare(`
SELECT t.name AS table_name, x.cid, x.name, x.type, x."notnull", x.dflt_value, x.pk, x.hidden
FROM main.sqlite_schema AS t
CROSS JOIN pragma_table_xinfo(t.name, 'main') AS x
WHERE (${u}) AND substr(t.name, 1, 7) <> 'sqlite_'
${d}
ORDER BY t.name, x.cid
`).all(...t.viewNames??[],...o),e=>e.table_name);const p=s?void 0:groupPluginRecords(e.prepare(`
SELECT t.name AS table_name, f.id, f.seq, f."table", f."from", f."to",
f.on_update, f.on_delete, f."match"
FROM main.sqlite_schema AS t
CROSS JOIN pragma_foreign_key_list(t.name, 'main') AS f
WHERE t.type = 'table' AND substr(t.name, 1, 7) <> 'sqlite_'
ORDER BY t.name, f.id, f.seq
`).all(),e=>e.table_name);const m=groupPluginRecords(n.filter(e=>e.type===`trigger`),e=>e.tbl_name);const h=new Map(n.filter(e=>e.type===`index`).map(e=>[e.name,e.sql]));const normalizedRow=e=>({name:e.name,sql:normalizeSchemaSql(e.sql)});const readColumns=t=>o.includes(t)?[]:f?(f.get(t)??[]).map(({table_name:e,...t})=>t):readSqliteColumnCatalog(e,t);const readTriggers=e=>(m.get(e)??[]).map(normalizedRow);return{tables:r.map(t=>{const n=a.find(e=>e.schema===`main`&&e.name===t.name);if(!n)throw new Error(`Could not inspect SQLite table options for ${t.name}.`);const r=c?c.get(t.name)??[]:e.prepare(`PRAGMA main.index_list(${quoteSqliteIdentifier(t.name)})`).all().map(({name:e,origin:t,partial:n,unique:r,seq:i})=>({name:e,origin:t,partial:n,unique:r,index_seq:i}));const i=groupPluginRecords(l?.get(t.name)??[],e=>e.index_seq);return{name:t.name,sql:normalizeSchemaSql(t.sql),strict:n.strict,withoutRowid:n.wr,columns:readColumns(t.name),foreignKeys:p?(p.get(t.name)??[]).map(({table_name:e,...t})=>t):e.prepare(`PRAGMA main.foreign_key_list(${quoteSqliteIdentifier(t.name)})`).all(),indexes:r.map(t=>({name:t.name,origin:t.origin,partial:t.partial,unique:t.unique,sql:normalizeSchemaSql(h.get(t.name)??null),terms:l?(i.get(t.index_seq)??[]).map(({table_name:e,index_seq:t,...n})=>n):e.prepare(`PRAGMA main.index_xinfo(${quoteSqliteIdentifier(t.name)})`).all()})).toSorted((e,t)=>e.name.localeCompare(t.name)),triggers:readTriggers(t.name)}}),views:i.map(e=>({name:e.name,sql:normalizeSchemaSql(e.sql),columns:readColumns(e.name),triggers:readTriggers(e.name)}))}}function readSqliteColumnCatalog(e,t){return e.prepare(`PRAGMA main.table_xinfo(${quoteSqliteIdentifier(t)})`).all()}function compareJson(e,t){return JSON.stringify(e).localeCompare(JSON.stringify(t))}
//!src/infra/sqlite-snapshot-policy.ts
const MAX_SNAPSHOT_ATTEMPTS=10;const SQLITE_SOURCE_READ_BUSY_TIMEOUT_MS=3e4;const SNAPSHOT_RETRY_BASE_MS=10;const SNAPSHOT_RETRY_MAX_MS=80;function sqliteSnapshotSourceFileSize(e){try{const t=fs.statSync(e);return t.isFile()?t.size:0}catch(e){if(hasErrnoCode(e,`ENOENT`))return 0;throw e}}function assertSqliteSnapshotSpace(e,t){const n=typeof e===`string`?[``,`-wal`,`-journal`].reduce((t,n)=>t+sqliteSnapshotSourceFileSize(e+n),0):readSqliteImageSizeBytes(e);const r=tryReadDiskSpace(t);if(r&&r.availableBytes<n)throw Object.assign(/* @__PURE__ */ new Error(`SQLite read-only snapshot needs ${formatDiskSpaceBytes(n)} (${n} bytes) near ${t}, but only ${formatDiskSpaceBytes(r.availableBytes)} (${r.availableBytes} bytes) is available. Free disk space before retrying.`),{code:`ENOSPC`})}function waitForSnapshotRetrySync(e){if(e+1>=10)return;const t=Math.min(SNAPSHOT_RETRY_MAX_MS,SNAPSHOT_RETRY_BASE_MS*2**e);if(t>0)Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}
//!src/infra/sqlite-snapshot-staging.ts
function acquireSqliteSnapshotReadToken(e){return acquireSqliteSnapshotToken(e,`read`)}function sqliteSnapshotStagingError(e,t,n=false,r){markSqliteInspectionOperation(t,`snapshot`);let i=n;let a=false;let o=false;let s;for(let n=0,r=t;n<8&&r instanceof Error;n+=1){o||=r instanceof AggregateError||r instanceof SqliteSnapshotCleanupError;const{errcode:t,path:n}=r;a||=hasSqliteSnapshotCapacityCode(r);if(a||typeof t===`number`&&[13,778,1034,1290].includes(t)||`${n??``}${path.sep}`.startsWith(`${e}${path.sep}`)){i=true;if(typeof t===`number`)s=t}r=r.cause}if(!i)return t;const c=a?`free disk space/quota`:`check filesystem health and write permissions`;let l=``;if(a&&r)try{const t=sqliteSnapshotSourceFileSize(r)+sqliteSnapshotSourceFileSize(`${r}-wal`)+sqliteSnapshotSourceFileSize(`${r}-journal`);const n=tryReadDiskSpace(e)?.availableBytes;const i=fs.existsSync(`${r}-wal`)&&fs.existsSync(`${r}-shm`);l=`; estimated ${t} bytes needed; ${n===void 0?`available bytes unknown`:`${n} bytes available`}; source ${i?`has live WAL sidecars`:`has no live WAL sidecars`}`}catch{}const u=process.env.OPENCLAW_UPDATE_IN_PROGRESS===`1`?`TMPDIR`:`XDG_CACHE_HOME`;const d=`${t instanceof Error?t.message:String(t)}${s!==void 0?` (SQLite errcode=${s})`:``}; snapshot staging root ${n?e:path.dirname(e)}${l}: ${c} or set ${u} to a writable filesystem`;const f=a&&!o&&readSqliteInspectionOperation(t)!==`source`?new SqliteSnapshotCapacityError(d,{cause:t}):new Error(d,{cause:t});return isPrivateDirectoryCreationRefused(t)?markPrivateDirectoryCreationRefused(f):f}async function createSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=false,n,r=false){n?.throwIfAborted();try{return await allocateSqliteSnapshotStagingDirectory(e,t,n,r)}catch(e){if(e instanceof SqliteSnapshotCleanupError||r&&e instanceof AggregateError)throw e;n?.throwIfAborted();markSqliteInspectionOperation(e,`snapshot`);throw e}}async function allocateSqliteSnapshotStagingDirectory(e=resolvePrivateSqliteSnapshotStagingRoot(),t=false,n,r=false){n?.throwIfAborted();if(r){const r=new AbortController;return retainSnapshotWork((async()=>{const{allocateWorkerOwnedSqliteSnapshotDirectory:i}=await import(`./sqlite-snapshot-staging-allocation-D53_RWvV.js`);n?.throwIfAborted();r.signal.throwIfAborted();const a=await i(e,t,n?AbortSignal.any([n,r.signal]):r.signal);registerSnapshotTempDirectory(a.directory);if(n?.aborted||r.signal.aborted){if(!await removeTempDirectoryAsync(a.directory))throw new SqliteSnapshotCleanupError(`SQLite snapshot cleanup failed: ${a.directory}`);n?.throwIfAborted();r.signal.throwIfAborted()}return a.directory})(),()=>r.abort(/* @__PURE__ */ new Error(`SQLite snapshot allocation stopped`)))}return createSqliteSnapshotStagingDirectorySync(e,t)}function createSqliteSnapshotStagingDirectorySync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=false){const n=createSqliteSnapshotStagingTokenSync(e,t);registerSnapshotTempDirectory(n.directory,n.release);return n.directory}function createSqliteSnapshotStagingTokenSync(e=resolvePrivateSqliteSnapshotStagingRoot(),t=false){let n;try{try{n=createPrivateSqliteTempDirectorySync(e,t?`openclaw-sqlite-readonly-${process.pid}-`:SQLITE_SNAPSHOT_PREFIX)}catch(t){throw sqliteSnapshotStagingError(e,t,true)}return{directory:n,release:acquireSqliteSnapshotToken(n,`create`)}}catch(e){if(n)removeTempDirectory(n);throw e}}
//!src/infra/sqlite-wal-checksum.ts
const SQLITE_WAL_MAGIC_LE=931071618;const SQLITE_WAL_MAGIC_BE=931071619;function readUint32(e,t,n){return n===`LE`?e.readUInt32LE(t):e.readUInt32BE(t)}function sqliteWalChecksum(e,t,n=[0,0]){let[r,i]=n;for(let n=0;n<e.length;n+=8){r=r+readUint32(e,n,t)+i>>>0;i=i+readUint32(e,n+4,t)+r>>>0}return[r,i]}
//!src/infra/sqlite-snapshot-wal-prefix.ts
const WAL_HEADER_BYTES=32;const WAL_FRAME_HEADER_BYTES=24;const COPY_BUFFER_BYTES=1048576;function readWalGeneration(e){const t=Buffer.alloc(WAL_HEADER_BYTES);if(readFileWindowFullySync(e,t,0)!==t.length)return;const n=t.readUInt32BE(0);if(n!==931071618&&n!==931071619)return;const r=n===931071618?`LE`:`BE`;const i=t.readUInt32BE(8);const[a,o]=sqliteWalChecksum(t.subarray(0,24),r);if(i<512||i>65536||(i&i-1)!==0||t.readUInt32BE(24)!==a||t.readUInt32BE(28)!==o)return;return{header:t,byteOrder:r,frameBytes:WAL_FRAME_HEADER_BYTES+i}}function copyCommittedWalFrames(e,t,n,r){const{header:i,byteOrder:a,frameBytes:o}=n;if(readWalGeneration(e)?.header.equals(i)!==true)return false;const s=i.subarray(16,24);let c=[i.readUInt32BE(24),i.readUInt32BE(28)];writeFully(t,i,0);let l=WAL_HEADER_BYTES;const u=Math.max(1,Math.floor(COPY_BUFFER_BYTES/o));const d=Buffer.allocUnsafe(u*o);for(let n=WAL_HEADER_BYTES;n<r;){const i=d.subarray(0,Math.min(d.length,r-n));const u=readFileWindowFullySync(e,i,n);let f=0;let p=true;for(let e=0;e+o<=u;e+=o){const t=i.subarray(e,e+o);if(t.readUInt32BE(0)===0||!t.subarray(8,16).equals(s)){p=false;break}const r=sqliteWalChecksum(t.subarray(WAL_FRAME_HEADER_BYTES),a,sqliteWalChecksum(t.subarray(0,8),a,c));if(t.readUInt32BE(16)!==r[0]||t.readUInt32BE(20)!==r[1]){p=false;break}c=r;f=e+o;if(t.readUInt32BE(4)!==0)l=n+f}if(f>0)writeFully(t,i.subarray(0,f),n);if(!p||f<i.length)break;n+=f}fs.ftruncateSync(t,l);fs.fsyncSync(t);return l}function writeFully(e,t,n){for(let r=0;r<t.length;){const i=fs.writeSync(e,t,r,t.length-r,n+r);if(i<=0)throw new Error(`SQLite WAL snapshot write made no progress`);r+=i}}function matchesCapturedWalPrefix(e,t,n){const r=fs.openSync(t,`r`);try{const t=fs.fstatSync(r);if(!t.isFile()||t.size!==n)return false;const i=Buffer.allocUnsafe(Math.min(COPY_BUFFER_BYTES,n));const a=Buffer.allocUnsafe(i.length);for(let t=0;t<n;t+=i.length){const o=Math.min(i.length,n-t);const s=i.subarray(0,o);const c=a.subarray(0,o);if(readFileWindowFullySync(e,s,t)!==o||readFileWindowFullySync(r,c,t)!==o||!s.equals(c))return false}return true}finally{fs.closeSync(r)}}function prepareSqliteWalPrefixCopy(e,t,n){const r=readWalGeneration(e);if(!r)return;return()=>{const i=fs.fstatSync(e).size;if(!Number.isSafeInteger(i)||i<WAL_HEADER_BYTES)return false;const a=fs.openSync(t,`wx`,384);let o;try{o=copyCommittedWalFrames(e,a,r,i)}finally{fs.closeSync(a)}return o!==false&&n()&&matchesCapturedWalPrefix(e,t,o)&&readWalGeneration(e)?.header.equals(r.header)===true}}
//!src/infra/sqlite-readonly-location.ts
const SQLITE_HEADER_BYTES=20;const SQLITE_READONLY_RESULT_CODE=8;const SQLITE_RESULT_CODE_MASK=255;const SQLITE_JOURNAL_MAGIC=Buffer.from([217,213,5,249,32,161,99,215]);var SqliteSourceChangedError=class extends Error{constructor(e,t){super(t?.attempts?`SQLite source did not stabilize (reason=${e}, attempts=${t.attempts}) after ${t.attempts} read-only inspection attempts. Wait a moment for write activity to settle, then retry the inspection`:`SQLite source changed during read-only inspection (reason=${e})`,t);this.reason=e}};function statIfPresent(e){try{return fs.statSync(e,{bigint:true})}catch(e){if(e.code===`ENOENT`)return;throw e}}function readSourceSidecars(e){return{journal:Boolean(statIfPresent(`${e}-journal`)),shm:Boolean(statIfPresent(`${e}-shm`)),wal:Boolean(statIfPresent(`${e}-wal`))}}function openPinnedFile(e,t){let n;try{n=fs.openSync(e,`r`)}catch(e){if(e.code===`ENOENT`)throw new SqliteSourceChangedError(`source-disappeared`);throw e}try{const r=fs.fstatSync(n,{bigint:true});if(t)assertDatabaseFileIdentity(r,t);const i=statIfPresent(e);if(!r.isFile()||!i?.isFile()||!sameFileIdentity(r,i))throw new SqliteSourceChangedError(`source-identity-changed`);return{descriptor:n,identity:r,pathname:e}}catch(e){fs.closeSync(n);throw e}}function readSourceJournalMode(e,t){const n=openPinnedFile(e,t);try{const e=Buffer.alloc(SQLITE_HEADER_BYTES);const t=fs.readSync(n.descriptor,e,0,e.length,0);assertPinnedIdentityUnchanged(n);if(t===0)return`empty`;if(t!==e.length||e.subarray(0,16).toString(`utf8`)!==`SQLite format 3\0`)return`unknown`;return e[18]===2||e[19]===2?`wal`:`rollback`}finally{fs.closeSync(n.descriptor)}}function assertPinnedIdentityUnchanged(e){const t=fs.fstatSync(e.descriptor,{bigint:true});const n=statIfPresent(e.pathname);if(!t.isFile()||!n?.isFile()||!sameFileIdentity(e.identity,t)||!sameFileIdentity(e.identity,n))throw new SqliteSourceChangedError(`source-identity-changed`)}function sourceMatchesCopy(e,t,n){const r=openPinnedFile(e,n);try{const e=fs.openSync(t,`r`);try{if(!fs.fstatSync(e).isFile())return false;const t=sameFileContentsSync(r.descriptor,e);assertPinnedIdentityUnchanged(r);return t}finally{fs.closeSync(e)}}finally{fs.closeSync(r.descriptor)}}function assertExpectedSidecars(e,t){const n=readSourceSidecars(e);if(n.journal!==t.journal||n.wal!==t.wal)throw new SqliteSourceChangedError(`journal-state-changed`)}function isSqliteReadOnlyError(e){let t=e;for(let e=0;e<8&&t&&typeof t===`object`;e+=1){const e=t;if(typeof e.errcode===`number`&&(e.errcode&SQLITE_RESULT_CODE_MASK)===SQLITE_READONLY_RESULT_CODE)return true;t=e.cause}return false}function rollbackJournalReferencesSuperJournal(e){const t=fs.openSync(e,`r`);try{const e=fs.fstatSync(t).size;if(e<16)return false;const n=Buffer.allocUnsafe(16);if(fs.readSync(t,n,0,n.length,e-n.length)!==n.length)return false;const r=n.readUInt32BE(0);return r>0&&r<=e-20&&n.subarray(8).equals(SQLITE_JOURNAL_MAGIC)}finally{fs.closeSync(t)}}function syncPrivateSnapshot(e){const t=fs.openSync(e,`r+`);try{fs.fsyncSync(t)}finally{fs.closeSync(t)}}function recoverPrivateJournalCopy(e){if(rollbackJournalReferencesSuperJournal(`${e}-journal`))throw new Error(`SQLite hot rollback journal references a super-journal and cannot be recovered privately: ${e}`);const t=openNodeSqliteDatabase(e);try{t.exec(`PRAGMA busy_timeout = 30000; PRAGMA trusted_schema = OFF;`);t.prepare(`PRAGMA schema_version;`).get()}finally{t.close()}fs.rmSync(`${e}-journal`,{force:true});syncPrivateSnapshot(e)}function*createStableReadOnlyCopyInTempDirectory(e,t,n,r=n?path.dirname(n):resolvePrivateSqliteSnapshotStagingRoot(),i,a){let o=n;try{o??=createSqliteSnapshotStagingDirectorySync(r);assertSqliteSnapshotSpace(e,o);const n=path.join(o,`database.sqlite.partial`);if(process.platform!==`win32`)fs.chmodSync(o,448);if(readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);const s=readSourceSidecars(e);let c=false;if(t===`wal`&&s.wal&&!s.journal){const t=openPinnedFile(`${e}-wal`);try{const r=prepareSqliteWalPrefixCopy(t.descriptor,`${n}-wal`,()=>sourceMatchesCopy(e,n,i));if(r)yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i};const a=r?.();assertPinnedIdentityUnchanged(t);if(a===false)throw new SqliteSourceChangedError(`wal-copy-unstable`);c=a===true}finally{fs.closeSync(t.descriptor)}}const l=[...s.journal?[`-journal`]:[],...s.wal?[`-wal`]:[]];if(c)assertExpectedSidecars(e,s);else if(l.length>0){for(const t of l)yield{sourcePath:`${e}${t}`,targetPath:`${n}${t}`};yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i};if(!sourceMatchesCopy(e,n,i))throw new SqliteSourceChangedError(`main-changed-during-copy`);for(const t of l)if(!sourceMatchesCopy(`${e}${t}`,`${n}${t}`))throw new SqliteSourceChangedError(t===`-wal`?`wal-changed-during-copy`:`rollback-journal-changed-during-copy`);assertExpectedSidecars(e,s)}else{yield{sourcePath:e,targetPath:n,expectedSourceIdentity:i};assertExpectedSidecars(e,s);const t=a!==void 0||sourceMatchesCopy(e,n,i);assertExpectedSidecars(e,s);if(!t)throw new SqliteSourceChangedError(`main-changed-during-copy`)}if(readSourceJournalMode(e,i)!==t)throw new SqliteSourceChangedError(`journal-mode-changed`);if(a&&(s.journal||s.wal&&fs.statSync(`${n}-wal`).size!==0))throw new SqliteSourceChangedError(`recovery-data-appeared`);if(s.journal)recoverPrivateJournalCopy(n);return publishPreparedCopy(o,a)}catch(t){const r=o?sqliteSnapshotStagingError(o,t,false,e):t;if(o&&n===void 0){const e=[r];if(!removeTempDirectory(o,t=>e.push(t)))throw preparationCleanupError(e,`SQLite snapshot preparation`)}throw r}}async function copyPreparedLocation(e){let t=e.next();while(!t.done){try{const{sourcePath:e,targetPath:n,expectedSourceIdentity:r}=t.value;const i=openPinnedFile(e,r);try{await copySqliteFile(e,n,i.identity,{clone:`never`})}finally{try{assertPinnedIdentityUnchanged(i)}finally{fs.closeSync(i.descriptor)}}}catch(n){t=e.throw(n);continue}t=e.next()}return t.value}async function createOnlineReadOnlyBackup(e,t,n,r){const i=typeof t===`object`?t.directory:await createSqliteSnapshotStagingDirectory(t,false,n);const a=path.join(i,`database.sqlite.partial`);try{if(process.platform!==`win32`)fs.chmodSync(i,448);const t=withSqliteInspectionOperation(`source`,()=>openNodeSqliteDatabase(e,{readOnly:true}));try{t.exec(`PRAGMA busy_timeout = ${SQLITE_SOURCE_READ_BUSY_TIMEOUT_MS}; PRAGMA trusted_schema = OFF; BEGIN;`);t.prepare(`PRAGMA schema_version;`).get();assertSqliteSnapshotSpace(t,i);await retainSnapshotWork(backupNodeSqliteDatabase(t,a,r));t.exec(`ROLLBACK;`)}finally{if(t.isOpen)t.close()}syncPrivateSnapshot(a);return publishPreparedCopy(i)}catch(n){const r=sqliteSnapshotStagingError(i,n,false,e);return cleanupFailedSnapshotPreparation(i,r,`SQLite online backup`,typeof t===`object`)}}function*prepareArtifactPreservingCopy(e,t,n,r){const i=fs.realpathSync.native(e);for(let e=0;;e+=1)try{return yield*createStableReadOnlyCopyInTempDirectory(i,readSourceJournalMode(i,n),typeof t===`object`?t.directory:void 0,typeof t===`string`?t:void 0,n,r)}catch(n){if(typeof t===`object`)discardPreparedCopyPayload(t.directory,n);if(!(n instanceof SqliteSourceChangedError))throw n;if(e+1>=10)throw new SqliteSourceChangedError(n.reason,{cause:n,attempts:10});waitForSnapshotRetrySync(e)}}const LIVE_WRITER_CHANGES=/* @__PURE__ */ new Set([`wal-copy-unstable`,`main-changed-during-copy`,`wal-changed-during-copy`]);async function prepareSqliteReadOnlyCopyInProcess(e,t,n){try{return await copyPreparedLocation(prepareArtifactPreservingCopy(e,t,n))}catch(r){if(!(r instanceof SqliteSourceChangedError)||!LIVE_WRITER_CHANGES.has(r.reason))throw r;const i=fs.realpathSync.native(e);const a=openPinnedFile(i,n);try{const e=readSourceSidecars(i);if(readSourceJournalMode(i,n)!==`wal`||!e.wal||!e.shm||e.journal)throw r;const o=await createOnlineReadOnlyBackup(i,t);try{assertPinnedIdentityUnchanged(a)}catch(e){o.cleanup();throw e}return o}finally{fs.closeSync(a.descriptor)}}}async function prepareSqliteReadOnlyLocationFromOwnedDatabase(e,t,n,r){const assertReady=()=>{n?.throwIfAborted();t();if(!e.isOpen||e.isTransaction)throw new Error(`SQLite inspection requires an open owner outside a transaction`)};assertReady();const i=await createSqliteSnapshotStagingDirectory(void 0,false,n,r===`async`);try{assertReady();assertSqliteSnapshotSpace(e,i);const r=path.join(i,`database.sqlite.partial`);await retainSnapshotWork(backupNodeSqliteDatabase(e,r));n?.throwIfAborted();t();return publishPreparedCopy(i)}catch(e){const t=[e];if(!await removeTempDirectoryAsync(i,e=>t.push(e))&&r===`async`)throw preparationCleanupError(t,`Owned SQLite snapshot preparation`);throw e}}
//!packages/normalization-core/src/node-crypto.ts
function sha256Hex(e){return hash(`sha256`,e,`hex`)}function sha256HexPrefixCore(e,t){return sha256Hex(e).slice(0,t)}
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
function getEnumValues(e){const 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){if(typeof t===`bigint`)return t.toString();return t}var Cached=class{constructor(e){this._getter=e;this._value=void 0}get value(){const e=this._getter;if(e!==void 0){this._value=e();this._getter=void 0}return this._value}};function cached(e){return new Cached(e)}function nullish(e){return e===null||e===void 0}function cleanRegex(e){const t=e.startsWith(`^`)?1:0;const n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function floatSafeRemainder(e,t){const n=e/t;const r=Math.round(n);const i=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<i)return 0;return n-r}function assignProp(e,t,n){Object.defineProperty(e,t,{value:n,writable:true,enumerable:true,configurable:true})}function rawShape(e){const 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(){const e=n();assignProp(this,t,e);return e},enumerable:true,configurable:true})}function putProp(e,t,n){if(t in e)assignProp(e,t,n);else e[t]=n}function mirrorShape(e,t,n,r){const i=sourceShape(t);for(const a of n){const n=Object.getOwnPropertyDescriptor(i,a);if(!n.enumerable)continue;if(n.get)deferProp(e,a,()=>{const e=t._zod.def.shape[a];return r?r(e,a):e});else putProp(e,a,r?r(n.value,a):n.value)}}function mirrorProps(e,t){for(const n of Reflect.ownKeys(t)){const r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)deferProp(e,n,()=>t[n]);else putProp(e,n,r.value)}}function mergeDefs(...e){const t={};for(const n of e){const 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 captureStackTrace=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function isObject(e){return typeof e===`object`&&e!==null&&!Array.isArray(e)}const allowsEval=/* @__PURE__*/ cached(()=>{if(globalConfig.jitless)return false;if(typeof navigator!==`undefined`&&navigator?.userAgent?.includes(`Cloudflare`))return false;try{new Function(``);return true}catch(e){return false}});function isPlainObject(e){if(isObject(e)===false)return false;const t=e.constructor;if(t===void 0)return true;if(typeof t!==`function`)return true;const n=t.prototype;if(isObject(n)===false)return false;if(Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)===false)return false;return true}function shallowClone(e){if(isPlainObject(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}const propertyKeyTypes=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function escapeRegex(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function clone(e,t,n){const r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function normalizeParams(e){const t=e;if(!t)return{};if(typeof t===`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}delete t.message;if(typeof t.error===`string`)return{...t,error:()=>t.error};return t}function stringifyPrimitive(e){if(typeof e===`bigint`)return e.toString()+`n`;if(typeof e===`string`)return`"${e}"`;return`${e}`}function optionalKeys(e){return Object.keys(e).filter(t=>{return e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`})}const NUMBER_FORMAT_RANGES=/*@__PURE__*/ (()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))();const BIGINT_FORMAT_RANGES={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function pick(e,t){const n=e._zod.def;const r=n.checks;if(r&&r.length>0)throw new Error(`.pick() cannot be used on object schemas containing refinements`);const i={};mirrorShape(i,e,maskedKeys(e,t));return clone(e,mergeDefs(n,{shape:i,checks:[]}))}function maskedKeys(e,t){const n=sourceShape(e);const r=[];for(const e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw new Error(`Unrecognized key: "${String(e)}"`);if(t[e])r.push(e)}return r}function omit(e,t){const n=e._zod.def;const r=n.checks;if(r&&r.length>0)throw new Error(`.omit() cannot be used on object schemas containing refinements`);const i=new Set(maskedKeys(e,t));const a={};mirrorShape(a,e,Reflect.ownKeys(sourceShape(e)).filter(e=>!i.has(e)));return clone(e,mergeDefs(n,{shape:a,checks:[]}))}function extend(e,t){if(!isPlainObject(t))throw new Error(`Invalid input to extend: expected a plain object`);const n=e._zod.def.checks;if(n&&n.length>0){const n=sourceShape(e);for(const e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw new 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){const n={};mirrorShape(n,e,Reflect.ownKeys(sourceShape(e)));mirrorProps(n,t);return n}function safeExtend(e,t){if(!isPlainObject(t))throw new 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 new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);const n={};mirrorShape(n,e,Reflect.ownKeys(sourceShape(e)));mirrorShape(n,t,Reflect.ownKeys(sourceShape(t)));return 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`){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${r}() cannot be used on object schemas containing refinements`);const a=n?new Set(maskedKeys(t,n)):void 0;const o={};mirrorShape(o,t,Reflect.ownKeys(sourceShape(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t})));return clone(t,mergeDefs(t._zod.def,{shape:o,checks:[]}))}function required(e,t,n){const r=n?new Set(maskedKeys(t,n)):void 0;const i={};mirrorShape(i,t,Reflect.ownKeys(sourceShape(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t}));return clone(t,mergeDefs(t._zod.def,{shape:i}))}function aborted(e,t=0){if(e.aborted===true)return true;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==true)return true;return false}function explicitlyAborted(e,t=0){if(e.aborted===true)return true;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===false)return true;return false}function prefixIssues(e,t){return t.map(t=>{var n;(n=t).path??(n.path=[]);t.path.unshift(e);return t})}function unwrapMessage(e){return typeof e===`string`?e:e?.message}function sizeCaps(e){const t=[];for(const n of e??[]){const e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;const r=e.maximum??e.length??e.size;if(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;const i=e.inst?._zod?.traits;if(i?.has(`$ZodType`)){if(i.has(`$ZodCheck`))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst}const a=e.schema!==e.inst?e.schema?._zod.def?.error:void 0;const o=e.message?e.message:unwrapMessage(e.inst?._zod.def?.error?.(e))??unwrapMessage(a?.(e))??unwrapMessage(t?.error?.(e))??unwrapMessage(n.customError?.(e))??unwrapMessage(n.localeError?.(e))??`Invalid input`;const s={};for(const t of Object.keys(e)){if(t===`inst`||t===`schema`||t===`continue`||t===`input`||t===`__proto__`)continue;s[t]=e[t]}s.path??(s.path=[]);s.message=o;if(t?.reportInput)s.input=e.input;return s}const highSurrogate=/[\uD800-\uDBFF]/;function codePointLength(e){const t=e.length;if(!highSurrogate.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320){n--;r++}return n}function getLengthableOrigin(e){if(Array.isArray(e))return`array`;if(typeof e===`string`)return`string`;return`unknown`}function parsedType(e){const 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`;const t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function issue(...e){const[t,n,r]=e;if(typeof t===`string`)return{message:t,code:`custom`,input:n,inst:r};return{...t}}function members(e,t){for(const n in t){const r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:false});else defineBound(e,n,r.value)}}function own(e,t,n,r=true){Object.defineProperty(e,t,{configurable:true,writable:true,enumerable:r,value:n});return n}function hide(e,t,n){return own(e,t,n,false)}/* @__NO_SIDE_EFFECTS__ */
function derived(e,t){for(const n in e){const r=e[n];Object.defineProperty(t,n,{configurable:true,enumerable:true,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:true,get(){return this==null?n:own(this,t,n.bind(this))},set(e){own(this,t,e)}})}function claim(e,t){const n=Object.getPrototypeOf(e);return t in n?void 0:n}let installing;let broke=false;const breaker={configurable:true,get(){broke=true}};function defineLazyInternal(e,t,n){const r=Object.getPrototypeOf(e._zod);if(t in r&&installing!==e._zod){installing=void 0;return}installing=e._zod;Object.defineProperty(r,t,{configurable:true,get(){Object.defineProperty(this,t,breaker);const e=broke;broke=false;try{const r=n(this);if(broke)delete this[t];else Object.defineProperty(this,t,{configurable:true,writable:true,value:r});broke=broke||e;return r}catch(n){delete this[t];broke=broke||e;throw n}},set(e){Object.defineProperty(this,t,{configurable:true,writable:true,value:e})}})}function installLazyProp(e,t,n,r){const i=claim(e,t);if(!i)return;Object.defineProperty(i,t,{configurable:true,get(){const e={configurable:true,writable:true,enumerable:r,value:void 0};Object.defineProperty(this,t,e);e.value=n(this);Object.defineProperty(this,t,e);return e.value},set(e){Object.defineProperty(this,t,{configurable:true,writable:true,enumerable:r,value:e})}})}const CONSTANT_CATCH=`~constantCatch`;function constantCatch(e){const fn=()=>e;fn[CONSTANT_CATCH]=true;return fn}
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/core.js
var _a$1;const _zodDesc={value:void 0,enumerable:false};let _E=`captureStackTrace`in Error?Error:null;function newError(e){const t=_E;if(t){const n=t.stackTraceLimit;if(typeof n===`number`){try{t.stackTraceLimit=0}catch{_E=null;return new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}/* @__NO_SIDE_EFFECTS__ */
function $constructor(e,t,n,r){const i={};function Internals(e){this.def=e;this.constr=_;this.traits=/* @__PURE__ */ new Set}Internals.prototype=i;const a=n;const o=a&&/* @__PURE__ */ new WeakSet;function init(n,r){if(!n._zod){_zodDesc.value=new Internals(r);try{Object.defineProperty(n,"_zod",_zodDesc)}finally{_zodDesc.value=void 0}}else if(n._zod.traits.has(e))return;n._zod.traits.add(e);t(n,r);if(o){const e=Object.getPrototypeOf(n);const t=n._zod.constr.prototype;let r=e;while(r&&r!==t)r=Object.getPrototypeOf(r);const i=r??e;if(!o.has(i)){o.add(i);members(i,a)}}const i=_.prototype;for(const e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;if(!(e in n))n[e]=i[e].bind(n)}}const s=r?.Parent??Object;class Definition extends s{}Object.defineProperty(Definition,"name",{value:e});function _(e){const t=r?.Parent?newError(Definition):this;init(t,e);const n=t._zod.deferred;if(n){for(const e of n)e();t._zod.deferred=void 0}const i=globalThis.__zod_globalConfig?.postProcessor;if(i)i(t);return t}Object.defineProperty(_,"init",{value:init});Object.defineProperty(_,Symbol.hasInstance,{value:t=>{if(r?.Parent&&t instanceof r.Parent)return true;return t?._zod?.traits?.has(e)}});Object.defineProperty(_,"name",{value:e});return _}var $ZodAsyncError=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}};var $ZodEncodeError=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name=`ZodEncodeError`}};(_a$1=globalThis).__zod_globalConfig??(_a$1.__zod_globalConfig={});const globalConfig=globalThis.__zod_globalConfig;function config(e){if(e)Object.assign(globalConfig,e);return globalConfig}
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/errors.js
function _getMessage(){const e=this._zod;e.message??(e.message=JSON.stringify(e.def,jsonStringifyReplacer,2));return e.message}function _setMessage(e){this._zod.message=e}const _messageDesc={get:_getMessage,set:_setMessage,enumerable:true,configurable:true};const _issuesDesc={value:void 0,enumerable:false};const _installedToString=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);const initializer$1=(e,t)=>{e.name=`$ZodError`;_issuesDesc.value=t;Object.defineProperty(e,"issues",_issuesDesc);_issuesDesc.value=void 0;Object.defineProperty(e,"message",_messageDesc);const n=Object.getPrototypeOf(e);if(!_installedToString.has(n)){_installedToString.add(n);Object.defineProperty(n,"toString",{configurable:true,enumerable:false,get(){const value=()=>this.message;Object.defineProperty(this,"toString",{value,configurable:true,writable:true});return value},set(e){Object.defineProperty(this,"toString",{value:e,configurable:true,writable:true})}})}};const $ZodError=/* @__PURE__ */ $constructor(`$ZodError`,initializer$1);function node(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t)){if(t===`__proto__`)Object.defineProperty(e,t,{value:n(),writable:true,enumerable:true,configurable:true});else e[t]=n()}return e[t]}function flattenError(e,t=e=>e.message){const n={};const r=[];for(const i of e.issues)if(i.path.length>0)node(n,i.path[0],()=>[]).push(t(i));else r.push(t(i));return{formErrors:r,fieldErrors:n}}function formatError(e,t=e=>e.message){const n={_errors:[]};const processError=(e,r=[])=>{for(const 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{const e=[...r,...i.path];if(e.length===0)n._errors.push(t(i));else{let r=n;let a=0;while(a<e.length){const n=e[a];const o=a===e.length-1;if(n===`_errors`){if(o)r._errors.push(t(i));a++;continue}if(!Object.prototype.hasOwnProperty.call(r,n))Object.defineProperty(r,n,{value:{_errors:[]},enumerable:true,writable:true,configurable:true});const s=r[n];if(o)s._errors.push(t(i));r=s;a++}}}};processError(e);return n}
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/parse.js
function finalizeParams(e,t){return{callee:t?.callee??e,Err:t?.Err}}const _parse=e=>{const fn=(t,n,r,i)=>{const a=r?{...r,async:false}:{async:false};const o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new $ZodAsyncError;if(o.issues.length){const t=new((i?.Err)??e)(o.issues.map(e=>finalizeIssue(e,a,config())));captureStackTrace(t,i?.callee??fn);throw t}return o.value};return fn};const _parseAsync=e=>{const fn=async(t,n,r,i)=>{const a=r?{...r,async:true}:{async:true};let o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)o=await o;if(o.issues.length){const t=new((i?.Err)??e)(o.issues.map(e=>finalizeIssue(e,a,config())));captureStackTrace(t,i?.callee??fn);throw t}return o.value};return fn};const _safeParse=e=>(t,n,r)=>{const i=r?{...r,async:false}:{async:false};const 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:true,data:a.value}};function failure(e,t,n){let r;return{success:false,get error(){if(!r){r=new e(t.map(e=>finalizeIssue(e,n,config())));t=void 0;n=void 0}return r},set error(e){r=e;t=void 0;n=void 0}}}const _safeParseAsync=e=>async(t,n,r)=>{const i=r?{...r,async:true}:{async:true};let a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)a=await a;return a.issues.length?failure(e,a.issues,i):{success:true,data:a.value}};const COMPILE_INVALID=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`);const COMPILE_FALLBACK=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`);const validate=((e,t,n)=>{const r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==COMPILE_INVALID)return true;if(r.definite===true&&n===void 0)return false}return validateFallback(e,t,n)});function validateFallback(e,t,n){const r=n?{...n,async:false,abortEarly:true}:{async:false,abortEarly:true};const i=e._zod.bag.fallbackRun;let a;if(i){r[COMPILE_FALLBACK]=true;a=i({value:t,issues:[]},r)}else a=e._zod.run({value:t,issues:[]},r);if(a instanceof Promise)throw new $ZodAsyncError;return a.issues.length===0}const validateAsync$1=async(e,t,n)=>{const r=n?{...n,async:true,abortEarly:true}:{async:true,abortEarly:true};let i=e._zod.run({value:t,issues:[]},r);if(i instanceof Promise)i=await i;return i.issues.length===0};const _encode=e=>{const t=_parse(e);const fn=(e,n,r,i)=>{const a=r?{...r,direction:`backward`}:{direction:`backward`};return t(e,n,a,finalizeParams(fn,i))};return fn};const _decode=e=>{const t=_parse(e);const fn=(e,n,r,i)=>{return t(e,n,r,finalizeParams(fn,i))};return fn};const _encodeAsync=e=>{const t=_parseAsync(e);const fn=async(e,n,r,i)=>{const a=r?{...r,direction:`backward`}:{direction:`backward`};return await t(e,n,a,finalizeParams(fn,i))};return fn};const _decodeAsync=e=>{const t=_parseAsync(e);const fn=async(e,n,r,i)=>{return await t(e,n,r,finalizeParams(fn,i))};return fn};const _safeEncode=e=>(t,n,r)=>{const i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParse(e)(t,n,i)};const _safeDecode=e=>(t,n,r)=>{return _safeParse(e)(t,n,r)};const _safeEncodeAsync=e=>async(t,n,r)=>{const i=r?{...r,direction:`backward`}:{direction:`backward`};return _safeParseAsync(e)(t,n,i)};const _safeDecodeAsync=e=>async(t,n,r)=>{return _safeParseAsync(e)(t,n,r)};
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/regexes.js
const cuid=/^[cC][0-9a-z]{6,}$/;const cuid2=/^[0-9a-z]+$/;const ulid=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/;const xid=/^[0-9a-vA-V]{20}$/;const ksuid=/^[A-Za-z0-9]{27}$/;const nanoid=/^[a-zA-Z0-9_-]{21}$/;function nanoidOfLength(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;const guid=/^([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})$/;const uuid=e=>{if(!e)return/^([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)$/;return new 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})$`)};const email=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;const _emoji$1=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function emoji(){return new RegExp(_emoji$1,`u`)}const ipv4=/^(?:(?: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])$/;const ipv6=/^(([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}|:))$/;const cidrv4=/^((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])$/;const cidrv6=/^(([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])$/;const base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;const base64url=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;const httpProtocol=/^https?$/;const e164=/^\+[1-9]\d{6,14}$/;const dateSource=`(?:(?:\\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 new RegExp(`^${e}$`)}const date=/*@__PURE__*/ anchor(dateSource);function timeSource(e){const 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 new RegExp(`^${timeSource(e)}$`)}function datetime(e){const t=[`Z`];if(e.offset)t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);const n=`${timeSource({precision:e.precision,seconds:true})}(?:${t.join(`|`)})`;const r=e.local?`${n}|${timeSource({precision:e.precision})}`:n;return new RegExp(`^${dateSource}T(?:${r})$`)}const anyString=/^[\s\S]{0,}$/;const integer=/^-?\d+$/;const number$1=/^-?\d+(?:\.\d+)?$/;const boolean$1=/^(?:true|false)$/i;const lowercase=/^[^A-Z]*$/;const uppercase=/^[^a-z]*$/;
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/checks.js
const $ZodCheck=/*@__PURE__*/ $constructor(`$ZodCheck`,(e,t)=>{var n;e._zod??(e._zod={});e._zod.def=t;(n=e._zod).onattach??(n.onattach=[])});const _whenHasLength=e=>{const t=e.value;return!nullish(t)&&t.length!==void 0};const numericOriginMap={number:`number`,bigint:`bigint`,object:`date`};const $ZodCheckLessThan=/*@__PURE__*/ $constructor(`$ZodCheckLessThan`,(e,t)=>{$ZodCheck.init(e,t);const n=numericOriginMap[typeof t.value];e._zod.check=r=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:numericOriginMap[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})}});const $ZodCheckGreaterThan=/*@__PURE__*/ $constructor(`$ZodCheckGreaterThan`,(e,t)=>{$ZodCheck.init(e,t);const n=numericOriginMap[typeof t.value];e._zod.check=r=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:numericOriginMap[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})}});const $ZodCheckMultipleOf=/*@__PURE__*/ $constructor(`$ZodCheckMultipleOf`,(e,t)=>{$ZodCheck.init(e,t);e._zod.check=n=>{if(typeof n.value!==typeof t.value)throw new Error(`Cannot mix number and bigint in multiple_of check.`);if(typeof n.value===`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):floatSafeRemainder(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}});const $ZodCheckNumberFormat=/*@__PURE__*/ $constructor(`$ZodCheckNumberFormat`,(e,t)=>{$ZodCheck.init(e,t);t.format=t.format||`float64`;const n=t.format?.includes(`int`);const r=n?`int`:`number`;const[i,a]=NUMBER_FORMAT_RANGES[t.format];e._zod.check=o=>{const s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:false,input:s,inst:e});return}if(!Number.isSafeInteger(s)){if(s>0)o.issues.push({input:s,code:`too_big`,maximum:Number.MAX_SAFE_INTEGER,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:true,continue:!t.abort});else o.issues.push({input:s,code:`too_small`,minimum:Number.MIN_SAFE_INTEGER,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:true,continue:!t.abort});return}}if(s<i)o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:true,inst:e,continue:!t.abort});if(s>a)o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:true,inst:e,continue:!t.abort})}});const $ZodCheckMaxLength=/*@__PURE__*/ $constructor(`$ZodCheckMaxLength`,(e,t)=>{var n;$ZodCheck.init(e,t);(n=e._zod.def).when??(n.when=_whenHasLength);e._zod.check=n=>{const r=n.value;const i=r.length;if((typeof r===`string`&&i>t.maximum?codePointLength(r):i)<=t.maximum)return;const a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:true,input:r,inst:e,continue:!t.abort})}});const $ZodCheckMinLength=/*@__PURE__*/ $constructor(`$ZodCheckMinLength`,(e,t)=>{var n;$ZodCheck.init(e,t);(n=e._zod.def).when??(n.when=_whenHasLength);e._zod.check=n=>{const r=n.value;const i=r.length;if((typeof r===`string`&&i>=t.minimum&&i<t.minimum*2?codePointLength(r):i)>=t.minimum)return;const a=getLengthableOrigin(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:true,input:r,inst:e,continue:!t.abort})}});const $ZodCheckLengthEquals=/*@__PURE__*/ $constructor(`$ZodCheckLengthEquals`,(e,t)=>{var n;$ZodCheck.init(e,t);(n=e._zod.def).when??(n.when=_whenHasLength);e._zod.check=n=>{const r=n.value;const i=r.length;const a=typeof r===`string`&&i>=t.length&&i<=t.length*2?codePointLength(r):i;if(a===t.length)return;const o=getLengthableOrigin(r);const s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:true,exact:true,input:n.value,inst:e,continue:!t.abort})}});const $ZodCheckStringFormat=/*@__PURE__*/ $constructor(`$ZodCheckStringFormat`,(e,t)=>{var n,r;$ZodCheck.init(e,t);if(t.pattern)(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0;if(t.pattern.test(n.value))return;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})});else(r=e._zod).check??(r.check=()=>{})});const $ZodCheckRegex=/*@__PURE__*/ $constructor(`$ZodCheckRegex`,(e,t)=>{$ZodCheckStringFormat.init(e,t);e._zod.check=n=>{t.pattern.lastIndex=0;if(t.pattern.test(n.value))return;n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}});const $ZodCheckLowerCase=/*@__PURE__*/ $constructor(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??(t.pattern=lowercase);$ZodCheckStringFormat.init(e,t)});const $ZodCheckUpperCase=/*@__PURE__*/ $constructor(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??(t.pattern=uppercase);$ZodCheckStringFormat.init(e,t)});const $ZodCheckIncludes=/*@__PURE__*/ $constructor(`$ZodCheckIncludes`,(e,t)=>{$ZodCheck.init(e,t);const n=escapeRegex(t.includes);t.pattern=new RegExp(typeof t.position===`number`?`^.{${t.position},}${n}`:n);e._zod.check=n=>{if(n.value.includes(t.includes,t.position))return;n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}});const $ZodCheckStartsWith=/*@__PURE__*/ $constructor(`$ZodCheckStartsWith`,(e,t)=>{$ZodCheck.init(e,t);const n=new RegExp(`^${escapeRegex(t.prefix)}.*`);t.pattern??(t.pattern=n);e._zod.check=n=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}});const $ZodCheckEndsWith=/*@__PURE__*/ $constructor(`$ZodCheckEndsWith`,(e,t)=>{$ZodCheck.init(e,t);const n=new RegExp(`.*${escapeRegex(t.suffix)}$`);t.pattern??(t.pattern=n);e._zod.check=n=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});const $ZodCheckOverwrite=/*@__PURE__*/ $constructor(`$ZodCheckOverwrite`,(e,t)=>{$ZodCheck.init(e,t);e._zod.check=e=>{e.value=t.tx(e.value)}});
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/doc.js
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-=1}}write(e){if(typeof e===`function`){e(this,{execution:`sync`});e(this,{execution:`async`});return}const t=e.split(`
`).filter(e=>e);const n=Math.min(...t.map(e=>e.length-e.trimStart().length));const r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(const e of r)this.content.push(e)}compile(){const e=Function;const t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
`)}\n};`)(...Object.values(this.closed))}};
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/versions.js
const version={major:4,minor:6,patch:7};
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/schemas.js
const $ZodType=/*@__PURE__*/ $constructor(`$ZodType`,(e,t)=>{var n;e??(e={});e._zod.def=t;e._zod.bag=e._zod.bag||{};e._zod.version=version;const r=e._zod.def.checks;const i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(const t of i)for(const 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{const runChecks=(t,n,r)=>{if(t.memo)return t;let i=aborted(t);let a;for(const o of n){if(o._zod.def.when){if(explicitlyAborted(t))continue;if(!o._zod.def.when(t))continue}else if(i)continue;const n=t.issues.length;const s=o._zod.check(t);if(s instanceof Promise&&r?.async===false)throw new $ZodAsyncError;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s;if(t.issues.length===n)return;attachSchema(t.issues,n,e);if(!i)i=aborted(t,n)});else{if(t.issues.length===n)continue;attachSchema(t.issues,n,e);if(!i)i=aborted(t,n)}}if(a)return a.then(()=>{return t});return t};const handleCanaryResult=(t,n,r)=>{if(aborted(t)){t.aborted=true;return t}const a=runChecks(n,i,r);if(a instanceof Promise){if(r.async===false)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`){const r=e._zod.parse({value:t.value,issues:[]},{...n,skipChecks:true});if(r instanceof Promise)return r.then(e=>{return handleCanaryResult(e,t,n)});return handleCanaryResult(r,t,n)}const r=e._zod.parse(t,n);if(r instanceof Promise){if(n.async===false)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)}});const toStandardResult=(e,t)=>e.issues.length?{issues:e.issues.map(e=>finalizeIssue(e,t,config()))}:{value:e.value};async function validateAsync(e,t){const n={async:true};return toStandardResult(await e._zod.run({value:t,issues:[]},n),n)}function standardProps(e){return{validate:t=>{const n={async:false};try{const r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return toStandardResult(r,n)}catch(e){}return validateAsync(e,t)},vendor:`zod`,version:1}}const $ZodString=/*@__PURE__*/ $constructor(`$ZodString`,(e,t)=>{$ZodType.init(e,t);e._zod.pattern=t.pattern??anyString;e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(e){}if(typeof n.value===`string`)return n;n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e});return n}});const $ZodStringFormat=/*@__PURE__*/ $constructor(`$ZodStringFormat`,(e,t)=>{$ZodCheckStringFormat.init(e,t);$ZodString.init(e,t)});const $ZodGUID=/*@__PURE__*/ $constructor(`$ZodGUID`,(e,t)=>{t.pattern??(t.pattern=guid);$ZodStringFormat.init(e,t)});const $ZodUUID=/*@__PURE__*/ $constructor(`$ZodUUID`,(e,t)=>{if(t.version){const e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=uuid(e))}else t.pattern??(t.pattern=uuid());$ZodStringFormat.init(e,t)});const $ZodEmail=/*@__PURE__*/ $constructor(`$ZodEmail`,(e,t)=>{t.pattern??(t.pattern=email);$ZodStringFormat.init(e,t)});const URL_BAD_FORMAT=1;const URL_UNPARSEABLE=2;function canParseURL(e){try{if(typeof URL!==`undefined`&&typeof URL.canParse===`function`)return URL.canParse(e);new URL(e);return true}catch{return false}}function validateURL(e,t){if(!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t))return canParseURL(e)||2;return parseURLObject(e,t)}function parseURLObject(e,t){if(!t.normalize&&t.protocol?.source===httpProtocol.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL!==`undefined`){const t=URL;if(typeof t.parse===`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}const asciiTabOrNewline=/[\t\n\r]/g;function stripTabAndNewline(e){return e.replace(asciiTabOrNewline,``)}function urlHostnameOk(e,t){t.lastIndex=0;return t.test(e.hostname)}function urlProtocolOk(e,t){t.lastIndex=0;return t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const $ZodURL=/*@__PURE__*/ $constructor(`$ZodURL`,(e,t)=>{$ZodStringFormat.init(e,t);e._zod.check=n=>{try{const r=n.value.trim();const 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===true){n.value=stripTabAndNewline(r);return}if(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});if(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(r){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}});const $ZodEmoji=/*@__PURE__*/ $constructor(`$ZodEmoji`,(e,t)=>{t.pattern??(t.pattern=emoji());$ZodStringFormat.init(e,t)});const $ZodNanoID=/*@__PURE__*/ $constructor(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?nanoid:nanoidOfLength(t.length));$ZodStringFormat.init(e,t)});const $ZodCUID=/*@__PURE__*/ $constructor(`$ZodCUID`,(e,t)=>{t.pattern??(t.pattern=cuid);$ZodStringFormat.init(e,t)});const $ZodCUID2=/*@__PURE__*/ $constructor(`$ZodCUID2`,(e,t)=>{t.pattern??(t.pattern=cuid2);$ZodStringFormat.init(e,t)});const $ZodULID=/*@__PURE__*/ $constructor(`$ZodULID`,(e,t)=>{t.pattern??(t.pattern=ulid);$ZodStringFormat.init(e,t)});const $ZodXID=/*@__PURE__*/ $constructor(`$ZodXID`,(e,t)=>{t.pattern??(t.pattern=xid);$ZodStringFormat.init(e,t)});const $ZodKSUID=/*@__PURE__*/ $constructor(`$ZodKSUID`,(e,t)=>{t.pattern??(t.pattern=ksuid);$ZodStringFormat.init(e,t)});const $ZodISODateTime=/*@__PURE__*/ $constructor(`$ZodISODateTime`,(e,t)=>{t.pattern??(t.pattern=datetime(t));$ZodStringFormat.init(e,t)});const $ZodISODate=/*@__PURE__*/ $constructor(`$ZodISODate`,(e,t)=>{t.pattern??(t.pattern=date);$ZodStringFormat.init(e,t)});const $ZodISOTime=/*@__PURE__*/ $constructor(`$ZodISOTime`,(e,t)=>{t.pattern??(t.pattern=time(t));$ZodStringFormat.init(e,t)});const $ZodISODuration=/*@__PURE__*/ $constructor(`$ZodISODuration`,(e,t)=>{t.pattern??(t.pattern=duration);$ZodStringFormat.init(e,t)});const $ZodIPv4=/*@__PURE__*/ $constructor(`$ZodIPv4`,(e,t)=>{t.pattern??(t.pattern=ipv4);$ZodStringFormat.init(e,t)});const ipv6Alphabet=/^[0-9a-fA-F:.]+$/;function isValidIPv6(e){if(!ipv6Alphabet.test(e))return false;return canParseURL(`http://[${e}]`)}const $ZodIPv6=/*@__PURE__*/ $constructor(`$ZodIPv6`,(e,t)=>{t.pattern??(t.pattern=ipv6);$ZodStringFormat.init(e,t);e._zod.check=n=>{if(!isValidIPv6(n.value))n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}});const $ZodCIDRv4=/*@__PURE__*/ $constructor(`$ZodCIDRv4`,(e,t)=>{t.pattern??(t.pattern=cidrv4);$ZodStringFormat.init(e,t)});function isValidCIDRv6(e){const t=e.split(`/`);if(t.length!==2)return false;const[n,r]=t;if(!r)return false;const i=Number(r);if(`${i}`!==r)return false;if(i<0||i>128)return false;return isValidIPv6(n)}const $ZodCIDRv6=/*@__PURE__*/ $constructor(`$ZodCIDRv6`,(e,t)=>{t.pattern??(t.pattern=cidrv6);$ZodStringFormat.init(e,t);e._zod.check=n=>{if(!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 true;if(/\s/.test(e))return false;if(e.length%4!==0)return false;try{atob(e);return true}catch{return false}}const base64Charset=/^[0-9a-zA-Z+/]*={0,2}$/;const $ZodBase64=/*@__PURE__*/ $constructor(`$ZodBase64`,(e,t)=>{t.pattern??(t.pattern=base64Charset);$ZodStringFormat.init(e,t);e._zod.check=n=>{if(isValidBase64(n.value))return;n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});const base64urlCharset=/^[A-Za-z0-9_-]*$/;function isValidBase64URL(e){if(!base64urlCharset.test(e))return false;const t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return isValidBase64(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const $ZodBase64URL=/*@__PURE__*/ $constructor(`$ZodBase64URL`,(e,t)=>{t.pattern??(t.pattern=base64urlCharset);$ZodStringFormat.init(e,t);e._zod.check=n=>{if(isValidBase64URL(n.value))return;n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}});const $ZodE164=/*@__PURE__*/ $constructor(`$ZodE164`,(e,t)=>{t.pattern??(t.pattern=e164);$ZodStringFormat.init(e,t)});function isValidJWT(e,t=null){try{const n=e.split(`.`);if(n.length!==3)return false;const[r]=n;if(!r)return false;const i=JSON.parse(atob(r));if(`typ`in i&&i?.typ!==`JWT`)return false;if(!i.alg)return false;if(t&&(!(`alg`in i)||i.alg!==t))return false;return true}catch{return false}}const $ZodJWT=/*@__PURE__*/ $constructor(`$ZodJWT`,(e,t)=>{$ZodStringFormat.init(e,t);e._zod.check=n=>{if(isValidJWT(n.value,t.alg))return;n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}});const $ZodNumber=/*@__PURE__*/ $constructor(`$ZodNumber`,(e,t)=>{$ZodType.init(e,t);e._zod.pattern=number$1;e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(e){}const i=n.value;if(typeof i===`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;const a=typeof i===`number`?Number.isNaN(i)?`NaN`:!Number.isFinite(i)?String(i):void 0:void 0;n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}});return n}});const $ZodNumberFormat=/*@__PURE__*/ $constructor(`$ZodNumberFormat`,(e,t)=>{$ZodCheckNumberFormat.init(e,t);$ZodNumber.init(e,t)});const $ZodBoolean=/*@__PURE__*/ $constructor(`$ZodBoolean`,(e,t)=>{$ZodType.init(e,t);e._zod.pattern=boolean$1;e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(e){}const i=n.value;if(typeof i===`boolean`)return n;n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e});return n}});const $ZodUnknown=/*@__PURE__*/ $constructor(`$ZodUnknown`,(e,t)=>{$ZodType.init(e,t);e._zod.parse=e=>e});const $ZodNever=/*@__PURE__*/ $constructor(`$ZodNever`,(e,t)=>{$ZodType.init(e,t);e._zod.parse=(t,n)=>{t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e});return t}});function capSize(e,t){const n=sizeCaps(e._zod.def.checks);if(!n.length)return;const r=Math.min(...n.map(e=>e[0]));const i=e._zod.parse;e._zod.parse=(n,a)=>{const o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(const[t,r]of sizeCaps(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){const t=n.issues.length;r._zod.check(n);n.issues[t].continue=false;attachSchema(n.issues,t,e);return n}}return i(n,a)}}const arraySize=e=>Array.isArray(e)?e.length:-1;function handleArrayResult(e,t,n){if(e.issues.length)t.issues.push(...prefixIssues(n,e.issues));t.value[n]=e.value}const $ZodArray=/*@__PURE__*/ $constructor(`$ZodArray`,(e,t)=>{$ZodType.init(e,t);const n=globalConfig.memoizer;n?.attach(e);e._zod.parse=(r,i)=>{const a=r.value;if(!Array.isArray(a)){r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e});return r}r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);const o=[];const s=i?.abortEarly;for(let e=0;e<a.length;e++){const n=a[e];const c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>handleArrayResult(t,r,e)));else{handleArrayResult(c,r,e);if(s&&c.issues.length!==0&&aborted(c))break}}if(o.length)return Promise.all(o).then(()=>r);return r};capSize(e,arraySize)});function handlePropertyResult(e,t,n,r,i,a){const o=n in r;const s=a===`optional`;if(!o&&s&&i===`optional`)return;if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...prefixIssues(n,e.issues))}if(!o&&i===void 0){if(!e.issues.length)t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}if(e.value===void 0){if(o||i===`defaulted`&&!s)t.value[n]=void 0}else t.value[n]=e.value}const NO_SYMBOL_KEYS=[];function normalizeDef(e){const t=Object.keys(e.shape);const n=Object.getOwnPropertySymbols(e.shape);const r=n.length?n:NO_SYMBOL_KEYS;const i=r.length?[...t,...r]:t;for(const t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw new Error(`Invalid element at key "${String(t)}": expected a Zod schema`);const a=optionalKeys(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function handleCatchall(e,t,n,r,i,a,o){const s=[];const c=i.keySet;const l=i.catchall._zod;const u=l.def.type;const d=l.optin;const f=l.optout;let p=0;for(const i in t){if(o&&n.issues.length!==p){if(aborted(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){if(u===`never`)s.push(i);continue}if(u===`never`){s.push(i);continue}const a=l.run({value:t[i],issues:[]},r);if(a instanceof Promise)e.push(a.then(e=>handlePropertyResult(e,n,i,t,d,f)));else handlePropertyResult(a,n,i,t,d,f)}if(s.length)n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:true});if(!e.length)return n;return Promise.all(e).then(()=>{return n})}const $ZodObject=/*@__PURE__*/ $constructor(`$ZodObject`,(e,t)=>{$ZodType.init(e,t);const n=Object.getOwnPropertyDescriptor(t,`shape`);const r=n?.get?n.get.raw:t.shape??{};if(r){const get=()=>{const e={...r};Object.defineProperty(t,"shape",{value:e});get.raw=e;return e};get.raw=r;Object.defineProperty(t,"shape",{get})}const i=cached(()=>normalizeDef(t));defineLazyInternal(e,`propValues`,e=>{const t=e.def.shape;const n={};for(const e in t){const r=t[e]._zod;if(r.values){if(!Object.prototype.hasOwnProperty.call(n,e))assignProp(n,e,/* @__PURE__ */ new Set);for(const t of r.values)n[e].add(t);if(r.optin!==void 0)n[e].add(void 0)}}return n});const a=isObject;const o=t.catchall;let s;const c=globalConfig.memoizer;c?.attach(e);e._zod.parse=(t,n)=>{s??(s=i.value);const r=t.value;if(!a(r)){t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e});return t}t.value=c?c.alloc(e,t,{},n):{};const l=[];const u=s.shape;const d=n?.abortEarly;let f=t.issues.length;for(const e of s.allKeys){if(d&&t.issues.length!==f){if(aborted(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;const i=u[e];const a=i._zod.optin;const o=i._zod.optout;const s=i._zod.run({value:r[e],issues:[]},n);if(s instanceof Promise)l.push(s.then(n=>handlePropertyResult(n,t,e,r,a,o)));else handlePropertyResult(s,t,e,r,a,o)}if(!o)return l.length?Promise.all(l).then(()=>t):t;return handleCatchall(l,r,t,n,i.value,e,d===true)}});const $ZodObjectJIT=/*@__PURE__*/ $constructor(`$ZodObjectJIT`,(e,t)=>{$ZodObject.init(e,t);const n=e._zod.parse;const r=cached(()=>normalizeDef(t));const i=globalConfig.memoizer;const generateFastpass=t=>{const n=r.value;const a=n.symbolKeys;const o=new Doc([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a});const parseStr=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`;const prefixStr=(e,t)=>`
let ${e}_ab = false;
for (let i = 0; i < ${e}.issues.length; i++) {
const iss = ${e}.issues[i];
iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
payload.issues.push(iss);
if (iss.continue !== true) ${e}_ab = true;
}
if (${e}_ab && ctx && ctx.abortEarly) {
payload.value = newResult;
return payload;
}`;o.write(`const input = payload.value;`);const s=Object.create(null);let c=0;for(const e of n.allKeys)s[e]=`key_${c++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(const e of n.allKeys){if(e===`__proto__`)continue;const n=s[e];const r=typeof e===`symbol`?`syms[${a.indexOf(e)}]`:esc(e);const i=`${r} in input`;const c=t[e];const l=c?._zod?.optin;const u=l!==void 0;const d=c?._zod?.optout===`optional`;o.write(`const ${n} = ${parseStr(r)};`);if(u&&d){const e=l===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
const ${n}_present = ${i};
if (!${n}.issues.length || ${n}_present) {
if (${n}.issues.length) {${prefixStr(n,r)}
}
if (${e}) {
newResult[${r}] = ${n}.value;
}
}
`)}else if(!u)o.write(`
const ${n}_present = ${i};
if (${n}.issues.length) {${prefixStr(n,r)}
}
if (!${n}_present && !${n}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${r}]
});
if (ctx && ctx.abortEarly) {
payload.value = newResult;
return payload;
}
}
if (${n}_present) {
newResult[${r}] = ${n}.value;
}
`);else{o.write(`
if (${n}.issues.length) {${prefixStr(n,r)}
}
`);if(l===`defaulted`)o.write(`newResult[${r}] = ${n}.value;`);else o.write(`
if (${n}.value !== undefined || ${i}) {
newResult[${r}] = ${n}.value;
}
`)}}o.write(`payload.value = newResult;`);o.write(`return payload;`);return o.compile()};let a;const o=isObject;const s=!globalConfig.jitless;const c=allowsEval;const l=s&&c.value;const u=t.catchall;let d;e._zod.parse=(i,c)=>{d??(d=r.value);const f=i.value;if(!o(f)){i.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e});return i}if(s&&l&&c?.async===false&&c.jitless!==true){if(!a)a=generateFastpass(t.shape);i=a(i,c);if(!u)return i;return handleCatchall([],f,i,c,d,e,c?.abortEarly===true)}return n(i,c)}});function handleUnionResults(e,t,n,r){for(const n of e)if(n.issues.length===0){t.value=n.value;return t}const i=e.filter(e=>!aborted(e));if(i.length===1){t.value=i[0].value;return 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())))});return t}const $ZodUnion=/*@__PURE__*/ $constructor(`$ZodUnion`,(e,t)=>{$ZodType.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)){const t=e.def.options.map(e=>e._zod.pattern);return new RegExp(`^(${t.map(e=>cleanRegex(e.source)).join(`|`)})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=false;const o=[];for(const e of t.options){const t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise){o.push(t);a=true}else{if(t.issues.length===0)return t;o.push(t)}}if(!a)return handleUnionResults(o,r,e,i);return Promise.all(o).then(t=>{return handleUnionResults(t,r,e,i)})}});function discriminatorMap(e){const t=/* @__PURE__ */ new Map;for(const n of e.options){const r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(const e of r)if(t.has(e)){if(e!==void 0)throw new Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}const $ZodDiscriminatedUnion=/*@__PURE__*/ $constructor(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=false;$ZodUnion.init(e,t);const n=e._zod.parse;defineLazyInternal(e,`propValues`,e=>{const t={};let n=0;for(const r of e.def.options){const i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);if(i[e.def.discriminator]?.has(void 0))n++;for(const[e,n]of Object.entries(i)){if(!Object.prototype.hasOwnProperty.call(t,e))assignProp(t,e,/* @__PURE__ */ new Set);for(const r of n)t[e].add(r)}}if(!e.def.unionFallback&&n>1)t[e.def.discriminator]?.delete(void 0);return t});t.options.forEach((e,n)=>{const r=rawShape(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw new Error(`Invalid discriminated union option at index "${n}"`)});const r=cached(()=>discriminatorMap(t));e._zod.parse=(i,a)=>{const o=i.value;if(!isObject(o)){i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e});return i}const s=o?.[t.discriminator];const c=r.value.get(s);if(c&&(s!==void 0||a.direction!==`backward`))return c._zod.run(i,a);if(t.unionFallback||a.direction===`backward`)return n(i,a);i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e});return i}});const $ZodIntersection=/*@__PURE__*/ $constructor(`$ZodIntersection`,(e,t)=>{$ZodType.init(e,t);e._zod.parse=(e,n)=>{const r=e.value;const i=t.left._zod.run({value:r,issues:[]},n);const a=t.right._zod.run({value:r,issues:[]},n);if(i instanceof Promise||a instanceof Promise)return Promise.all([i,a]).then(([t,n])=>{return handleIntersectionResults(e,t,n)});return handleIntersectionResults(e,i,a)}});function mergeValues(e,t){if(e===t)return{valid:true,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:true,data:e};if(isPlainObject(e)&&isPlainObject(t)){const n=Object.keys(t);const r=Object.keys(e).filter(e=>n.indexOf(e)!==-1);const i={...e,...t};if(Object.prototype.hasOwnProperty.call(i,`__proto__`))delete i.__proto__;for(const n of r){if(n===`__proto__`)continue;const r=mergeValues(e[n],t[n]);if(!r.valid)return{valid:false,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:true,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:false,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=e[r];const a=t[r];const o=mergeValues(i,a);if(!o.valid)return{valid:false,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:true,data:n}}return{valid:false,mergeErrorPath:[]}}function handleIntersectionResults(e,t,n){const r=/* @__PURE__ */ new Map;let i;const a=/* @__PURE__ */ new Map;const collect=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length){i??(i=e);n=e.keys}else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){const t=String(e.path[0]);if(!a.has(t))a.set(t,e);n=[t]}else return false;for(const e of n){if(!r.has(e))r.set(e,{});r.get(e)[t]=true}return true};for(const n of t.issues)if(!collect(n,`l`))e.issues.push(n);for(const t of n.issues)if(!collect(t,`r`))e.issues.push(t);const o=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(o.length){const t=i?o.filter(e=>i.keys.includes(e)):[];if(t.length)e.issues.push({...i,keys:t});for(const n of o)if(!t.includes(n)&&a.has(n))e.issues.push(a.get(n))}const s=mergeValues(t.value,n.value);if(!s.valid){if(aborted(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`)}e.value=s.data;return e}const $ZodRecord=/*@__PURE__*/ $constructor(`$ZodRecord`,(e,t)=>{$ZodType.init(e,t);const n=globalConfig.memoizer;n?.attach(e);e._zod.parse=(r,i)=>{const a=r.value;if(!isPlainObject(a)){r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e});return r}const o=[];const s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};const c=/* @__PURE__ */ new Set;for(const n of s)if(typeof n===`string`||typeof n===`number`||typeof n===`symbol`){c.add(typeof n===`number`?n.toString():n);if(n===`__proto__`)continue;const s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>finalizeIssue(e,i,config())),input:n,path:[n],inst:e});continue}const l=s.value;if(l===`__proto__`)continue;const u=t.valueType._zod.run({value:a[n],issues:[]},i);if(u instanceof Promise)o.push(u.then(e=>{if(e.issues.length)r.issues.push(...prefixIssues(n,e.issues));r.value[l]=e.value}));else{if(u.issues.length)r.issues.push(...prefixIssues(n,u.issues));r.value[l]=u.value}}let l;for(const e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else{l=l??[];l.push(e)}}if(l&&l.length>0)r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:true})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(const n of Reflect.ownKeys(a)){if(n===`__proto__`)continue;if(!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new Error(`Async schemas not supported in object keys currently`);if(typeof n===`string`&&number$1.test(n)&&l.issues.length){const e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw new Error(`Async schemas not supported in object keys currently`);if(e.issues.length===0)l=e}if(l.issues.length){if(t.mode===`loose`)r.value[n]=a[n];else if(s){c=c??[];c.push(n)}else r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>finalizeIssue(e,i,config())),input:n,path:[n],inst:e});continue}const u=l.value;if(u===`__proto__`)continue;const d=t.valueType._zod.run({value:a[n],issues:[]},i);if(d instanceof Promise)o.push(d.then(e=>{if(e.issues.length)r.issues.push(...prefixIssues(n,e.issues));r.value[u]=e.value}));else{if(d.issues.length)r.issues.push(...prefixIssues(n,d.issues));r.value[u]=d.value}}if(c&&c.length>0)r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:true})}if(o.length)return Promise.all(o).then(()=>r);return r}});const $ZodEnum=/*@__PURE__*/ $constructor(`$ZodEnum`,(e,t)=>{$ZodType.init(e,t);const n=getEnumValues(t.entries);const r=new Set(n);e._zod.values=r;defineLazyInternal(e,`pattern`,e=>{const t=getEnumValues(e.def.entries).filter(e=>propertyKeyTypes.has(typeof e));return new RegExp(t.length?`^(${t.map(e=>escapeRegex(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)});e._zod.parse=(t,i)=>{const a=t.value;if(r.has(a))return t;t.issues.push({code:`invalid_value`,values:n,input:a,inst:e});return t}});const $ZodLiteral=/*@__PURE__*/ $constructor(`$ZodLiteral`,(e,t)=>{$ZodType.init(e,t);const n=new Set(t.values);e._zod.values=n;defineLazyInternal(e,`pattern`,e=>{const t=e.def.values;return new 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)=>{const a=r.value;if(n.has(a))return r;r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e});return r}});const $ZodTransform=/*@__PURE__*/ $constructor(`$ZodTransform`,(e,t)=>{$ZodType.init(e,t);e._zod.optin=`optional`;globalConfig.memoizer?.guard(e);e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new $ZodEncodeError(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>{n.value=e;return n});if(i instanceof Promise)throw new $ZodAsyncError;n.value=i;return n}});function handleOptionalResult(e,t){e.value=t.issues.length?void 0:t.value;return e}const $ZodOptional=/*@__PURE__*/ $constructor(`$ZodOptional`,(e,t)=>{$ZodType.init(e,t);defineLazyInternal(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`);e._zod.optout=`optional`;defineLazyInternal(e,`values`,e=>{const t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0});defineLazyInternal(e,`pattern`,e=>{const t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${cleanRegex(t.source)})?$`):void 0});e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;const r=t.innerType._zod.run({value:e.value,issues:[]},n);if(r instanceof Promise)return r.then(t=>handleOptionalResult(e,t));return handleOptionalResult(e,r)}return t.innerType._zod.run(e,n)}});const $ZodExactOptional=/*@__PURE__*/ $constructor(`$ZodExactOptional`,(e,t)=>{$ZodOptional.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)=>{return t.innerType._zod.run(e,n)}});const $ZodNullable=/*@__PURE__*/ $constructor(`$ZodNullable`,(e,t)=>{$ZodType.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=>{const t=e.def.innerType._zod.pattern;return t?new RegExp(`^(${cleanRegex(t.source)}|null)$`):void 0});defineLazyInternal(e,`values`,e=>{return e.def.innerType._zod.values?/* @__PURE__ */ new Set([...e.def.innerType._zod.values,null]):void 0});e._zod.parse=(e,n)=>{if(e.value===null)return e;return t.innerType._zod.run(e,n)}});const $ZodDefault=/*@__PURE__*/ $constructor(`$ZodDefault`,(e,t)=>{$ZodType.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){e.value=t.defaultValue;return e}const r=t.innerType._zod.run(e,n);if(r instanceof Promise)return r.then(e=>handleDefaultResult(e,t));return handleDefaultResult(r,t)}});function handleDefaultResult(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}const $ZodPrefault=/*@__PURE__*/ $constructor(`$ZodPrefault`,(e,t)=>{$ZodType.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)e.value=t.defaultValue;return t.innerType._zod.run(e,n)}});const $ZodNonOptional=/*@__PURE__*/ $constructor(`$ZodNonOptional`,(e,t)=>{$ZodType.init(e,t);defineLazyInternal(e,`values`,e=>{const t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0});e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);if(i instanceof Promise)return i.then(t=>handleNonOptionalResult(t,e));return handleNonOptionalResult(i,e)}});function handleNonOptionalResult(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t});return e}function handleCatchResult(e,t,n,r){if(!t.issues.length){e.value=t.value;if(t.memo)e.memo=true;return e}e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>finalizeIssue(e,r,config()))},input:e.value});return e}const $ZodCatch=/*@__PURE__*/ $constructor(`$ZodCatch`,(e,t)=>{$ZodType.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);const r=t.innerType._zod.run({value:e.value,issues:[]},n);if(r instanceof Promise)return r.then(r=>handleCatchResult(e,r,t,n));return handleCatchResult(e,r,t,n)}});const $ZodPipe=/*@__PURE__*/ $constructor(`$ZodPipe`,(e,t)=>{$ZodType.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`){const r=t.out._zod.run(e,n);if(r instanceof Promise)return r.then(e=>handlePipeResult(e,t.in,n));return handlePipeResult(r,t.in,n)}const r=t.in._zod.run(e,n);if(r instanceof Promise)return r.then(e=>handlePipeResult(e,t.out,n));return handlePipeResult(r,t.out,n)}});function handlePipeResult(e,t,n){if(e.issues.some(e=>e.code!==`unrecognized_keys`)){e.aborted=true;return e}return t._zod.run({value:e.value,issues:e.issues},n)}const $ZodReadonly=/*@__PURE__*/ $constructor(`$ZodReadonly`,(e,t)=>{$ZodType.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);const r=t.innerType._zod.run(e,n);if(r instanceof Promise)return r.then(handleReadonlyResult);return handleReadonlyResult(r)}});function handleReadonlyResult(e){if(!e.memo)e.value=Object.freeze(e.value);return e}const $ZodCustom=/*@__PURE__*/ $constructor(`$ZodCustom`,(e,t)=>{$ZodCheck.init(e,t);$ZodType.init(e,t);e._zod.parse=(e,t)=>{return e};e._zod.check=n=>{const r=n.value;const 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){const e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)e.params=r._zod.def.params;t.issues.push(issue(e))}}
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/memoizer.js
var $ZodCyclicError=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`);this.name=`ZodCyclicError`}};const STATE=`~memo`;const NO_ISSUES=[];function isRef(e){return e!==null&&typeof e===`object`}function cloneIssues(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const recursive=/*@__PURE__*/ new WeakMap;const NONE=0;const ASSUMED=1;const PROVEN=2;function isRecursive(e,t,n){const r=recursive.get(e);if(r!==void 0)return r?PROVEN:NONE;if(t.has(e))return PROVEN;t.add(e);let i=NONE;const check=e=>{if(i!==PROVEN&&e?._zod){const r=isRecursive(e,t,n);if(r>i)i=r}};const shape=(e,r)=>{let i=NONE;for(const a of Reflect.ownKeys(e)){const o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;const s=o.get?ASSUMED:o.value?._zod?isRecursive(o.value,t,n):NONE;if(s>i)i=s}return i};const merge=e=>{if(e>i)i=e};const a=e._zod.def;switch(a.type){case`object`:{const e=rawShape(a);merge(e?shape(e,true):ASSUMED);check(a.catchall);break}case`array`:check(a.element);break;case`tuple`:for(const 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(const 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`:{const r=a._cachedInner??(n?e._zod.innerType:void 0);merge(r?isRecursive(r,t,false):ASSUMED);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(const e in a){const t=Object.getOwnPropertyDescriptor(a,e);if(!t||t.get)continue;const n=t.value;if(!n||typeof n!==`object`)continue;if(n._zod)check(n);else if(Array.isArray(n))for(const e of n)check(e)}}t.delete(e);return settle(e,i)}function settle(e,t){if(t!==ASSUMED)recursive.set(e,t===PROVEN);return t}function bucketFor(e,t){let n=e.buckets.get(t);if(!n){n=/* @__PURE__ */ new WeakMap;e.buckets.set(t,n)}return n}let handoff;const open=[];const memo={alloc(e,t,n){const r=handoff;if(!r)return n;handoff=void 0;const i={value:n,issues:null};r.set(t.value,i);open.push(i);return n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]);e._zod.deferred.push(()=>{const t=e._zod.parse;const wrapped=(e,n)=>{if(n.direction!==`backward`&&isBackEdge(n,e.value))throw new $ZodCyclicError;return t(e,n)};e._zod.parse=wrapped;if(e._zod.run===t)e._zod.run=wrapped})},attach(e){var t;let n;let r=false;let i;let a;(t=e._zod).deferred??(t.deferred=[]);e._zod.deferred.push(()=>{const t=e._zod.parse;const wrapped=(o,s)=>{if(n===void 0){const i=isRecursive(e,/* @__PURE__ */ new Set,false);if(i===NONE){e._zod.parse=t;if(e._zod.run===wrapped)e._zod.run=t;return t(o,s)}if(i===PROVEN||r)n=true;else r=true}const c=o.value;if(!isRef(c))return t(o,s);let l=s[STATE];if(!l){l={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0};s[STATE]=l}let u;if(i===s)u=a;else{u=bucketFor(l,e);i=s;a=u}const d=u.get(c);if(d){o.value=d.value;if(d.issues){if(d.issues.length)o.issues.push(...cloneIssues(d.issues))}else{o.memo=true;l.backEdges??(l.backEdges=/* @__PURE__ */ new WeakSet);l.backEdges.add(d.value)}return o}handoff=u;const f=open.length;const p=t(o,s);handoff=void 0;const m=open.length>f?open.pop():void 0;if(p instanceof Promise)return p.then(e=>{if(m)m.issues=e.issues.length?cloneIssues(e.issues):NO_ISSUES;return e});if(m)m.issues=p.issues.length?cloneIssues(p.issues):NO_ISSUES;return p};e._zod.parse=wrapped;if(e._zod.run===t)e._zod.run=wrapped})}};function memoizer(){return memo}function isBackEdge(e,t){const n=e[STATE]?.backEdges;return n!==void 0&&isRef(t)&&n.has(t)}
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/locales/en.js
const error=()=>{const 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}const 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`};const n={nan:`NaN`};function getTypeName(e,t){if(e===`number`&&typeof t===`number`&&!Number.isFinite(t))return String(t);return 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`:if(e.values.length===1)return`Invalid input: expected ${stringifyPrimitive(e.values[0])}`;return`Invalid option: expected one of ${joinValues(e.values,`|`)}`;case`too_big`:{const t=e.exact?`exactly `:e.inclusive?`<=`:`<`;const n=getSizing(e.origin);if(n)return`Too big: expected ${e.origin??`value`} to have ${t}${e.maximum.toString()} ${n.unit??`elements`}`;return`Too big: expected ${e.origin??`value`} to be ${t}${e.maximum.toString()}`}case`too_small`:{const t=e.exact?`exactly `:e.inclusive?`>=`:`>`;const n=getSizing(e.origin);if(n)return`Too small: expected ${e.origin} to have ${t}${e.minimum.toString()} ${n.unit}`;return`Too small: expected ${e.origin} to be ${t}${e.minimum.toString()}`}case`invalid_format`:{const n=e;if(n.format===`starts_with`)return`Invalid string: must start with "${n.prefix}"`;if(n.format===`ends_with`)return`Invalid string: must end with "${n.suffix}"`;if(n.format===`includes`)return`Invalid string: must include "${n.includes}"`;if(n.format===`regex`)return`Invalid string: must match pattern ${n.pattern}`;return`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`:if(e.options&&Array.isArray(e.options)&&e.options.length>0)return`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`;if(e.inclusive===false)return`Invalid input: more than one option matched`;return`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function en_default(){return{localeError:error()}}
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/registries.js
var _a;var $ZodRegistry=class{constructor(){this._map=/* @__PURE__ */ new WeakMap;this._idmap=/* @__PURE__ */ new Map}add(e,...t){const n=t[0];this._map.set(e,n);if(n&&typeof n===`object`&&`id`in n)this._idmap.set(n.id,e);return this}clear(){this._map=/* @__PURE__ */ new WeakMap;this._idmap=/* @__PURE__ */ new Map;return this}remove(e){const t=this._map.get(e);if(t&&typeof t===`object`&&`id`in t)this._idmap.delete(t.id);this._map.delete(e);return this}get(e){const t=e._zod.parent;if(t){const n={...this.get(t)??{}};delete n.id;const 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}(_a=globalThis).__zod_globalRegistry??(_a.__zod_globalRegistry=registry());const globalRegistry=globalThis.__zod_globalRegistry;
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/api.js
function snapshotChecks(e){if(e.checks)e.checks=[...e.checks];return 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:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _guid(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuid(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv4(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:false,version:`v4`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv6(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:false,version:`v6`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _uuidv7(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:false,version:`v7`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _url(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _emoji(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _nanoid(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cuid(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cuid2(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ulid(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _xid(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ksuid(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ipv4(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _ipv6(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cidrv4(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _cidrv6(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _base64(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _base64url(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _e164(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _jwt(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:false,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _isoDateTime(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:false,local:false,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:false,format:`safeint`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _boolean(e,t){return new e({type:`boolean`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _unknown(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
function _never(e,t){return new e({type:`never`,...normalizeParams(t)})}// @__NO_SIDE_EFFECTS__
function _lt(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:false})}// @__NO_SIDE_EFFECTS__
function _lte(e,t){return new $ZodCheckLessThan({check:`less_than`,...normalizeParams(t),value:e,inclusive:true})}// @__NO_SIDE_EFFECTS__
function _gt(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:false})}// @__NO_SIDE_EFFECTS__
function _gte(e,t){return new $ZodCheckGreaterThan({check:`greater_than`,...normalizeParams(t),value:e,inclusive:true})}// @__NO_SIDE_EFFECTS__
function _multipleOf(e,t){return new $ZodCheckMultipleOf({check:`multiple_of`,...normalizeParams(t),value:e})}// @__NO_SIDE_EFFECTS__
function _maxLength(e,t){return new $ZodCheckMaxLength({check:`max_length`,...normalizeParams(t),maximum:e})}// @__NO_SIDE_EFFECTS__
function _minLength(e,t){return new $ZodCheckMinLength({check:`min_length`,...normalizeParams(t),minimum:e})}// @__NO_SIDE_EFFECTS__
function _length(e,t){return new $ZodCheckLengthEquals({check:`length_equals`,...normalizeParams(t),length:e})}// @__NO_SIDE_EFFECTS__
function _regex(e,t){return new $ZodCheckRegex({check:`string_format`,format:`regex`,...normalizeParams(t),pattern:e})}// @__NO_SIDE_EFFECTS__
function _lowercase(e){return new $ZodCheckLowerCase({check:`string_format`,format:`lowercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _uppercase(e){return new $ZodCheckUpperCase({check:`string_format`,format:`uppercase`,...normalizeParams(e)})}// @__NO_SIDE_EFFECTS__
function _includes(e,t){return new $ZodCheckIncludes({check:`string_format`,format:`includes`,...normalizeParams(t),includes:e})}// @__NO_SIDE_EFFECTS__
function _startsWith(e,t){return new $ZodCheckStartsWith({check:`string_format`,format:`starts_with`,...normalizeParams(t),prefix:e})}// @__NO_SIDE_EFFECTS__
function _endsWith(e,t){return new $ZodCheckEndsWith({check:`string_format`,format:`ends_with`,...normalizeParams(t),suffix:e})}// @__NO_SIDE_EFFECTS__
function _overwrite(e){return new $ZodCheckOverwrite({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
function _normalize(e){return/* @__PURE__ */ _overwrite(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
function _trim(){return/* @__PURE__ */ _overwrite(e=>e.trim())}// @__NO_SIDE_EFFECTS__
function _toLowerCase(){return/* @__PURE__ */ _overwrite(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
function _toUpperCase(){return/* @__PURE__ */ _overwrite(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
function _slugify(){return/* @__PURE__ */ _overwrite(e=>slugify(e))}// @__NO_SIDE_EFFECTS__
function _array(e,t,n){return new e({type:`array`,element:t,...normalizeParams(n)})}// @__NO_SIDE_EFFECTS__
function _custom(e,t,n){const r=normalizeParams(n);r.abort??(r.abort=true);return new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
function _refine(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...normalizeParams(n)})}// @__NO_SIDE_EFFECTS__
function _superRefine(e,t){const n=/* @__PURE__ */ _check(t=>{t.addIssue=e=>{if(typeof e===`string`)t.issues.push(issue(e,t.value,n._zod.def));else{const r=e;if(r.fatal)r.continue=false;r.code??(r.code=`custom`);if(!(`input`in r))r.input=t.value;r.inst??(r.inst=n);r.continue??(r.continue=!n._zod.def.abort);t.issues.push(issue(r))}};return e(t.value,t)},t);return n}// @__NO_SIDE_EFFECTS__
function _check(e,t){const n=new $ZodCheck({check:`custom`,...normalizeParams(t)});n._zod.check=e;return n}
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/to-json-schema.js
function assignProps(e,...t){for(const n of t)for(const t of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,t))assignProp(e,t,n[t]);return e}function initializeContext(e){let t=e?.target??`draft-2020-12`;if(t===`draft-4`)t=`draft-04`;if(t===`draft-7`)t=`draft-07`;return{processors:e.processors??{},metadataRegistry:e?.metadata??globalRegistry,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){const a=typeof t.unrepresentable===`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return false;if(a===void 0||a===`throw`)throw new Error(i);Object.assign(n,a);return true}function processSchema(e,t,n={path:[],schemaPath:[]}){var r;const i=e._zod.def;const a=t.seen.get(e);if(a){a.count++;if(n.schemaPath.includes(e))a.cycle=n.path;return a.schema}const o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);t.sharedDefsExtractedFor=void 0;t.sharedEmitDoneFor=void 0;const s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{const r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{const n=o.schema;const a=t.processors[i.type];if(!a)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}const a=e._zod.parent;if(a){if(!o.ref)o.ref=a;processSchema(a,t,r);t.seen.get(a).isParent=true}}const c=t.metadataRegistry.get(e);if(c)assignProps(o.schema,c);if(t.io===`input`&&isTransforming(e)){delete o.schema.examples;delete o.schema.default}if(t.io===`input`&&`_prefault`in o.schema)(r=o.schema).default??(r.default=o.schema._prefault);delete o.schema._prefault;return t.seen.get(e).schema}function encodeJSONPointerSegment(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function extractDefs(e,t){const n=e.seen.get(t);if(!n)throw new Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;const r=/* @__PURE__ */ new Map;for(const t of e.seen.entries()){const n=e.metadataRegistry.get(t[0])?.id;if(n){const e=r.get(n);if(e&&e!==t[0])throw new 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])}}const makeURI=t=>{const r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){const n=e.external.registry.get(t[0])?.id;const i=e.external.uri??(e=>e);if(n)return{ref:i(n)};const a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;t[1].defId=a;return{defId:a,ref:`${i(`__shared`)}#/${r}/${encodeJSONPointerSegment(a)}`}}const i=`#`;const a=`${i}/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:i};const o=t[1].schema.id??`__schema${e.counter++}`;return{defId:o,ref:a+encodeJSONPointerSegment(o)}};const extractToDef=e=>{if(e[1].schema.$ref)return;const t=e[1];const{ref:n,defId:r}=makeURI(e);t.def={...t.schema};if(r)t.defId=r;const i=t.schema;for(const e in i)delete i[e];i.$ref=n};if(e.cycles===`throw`)for(const t of e.seen.entries()){const e=t[1];if(e.cycle)throw new Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const n of e.seen.entries()){const r=n[1];if(t===n[0]){extractToDef(n);continue}if(e.external){const r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){extractToDef(n);continue}}if(e.metadataRegistry.get(n[0])?.id){extractToDef(n);continue}if(r.cycle){extractToDef(n);continue}if(r.count>1){if(e.reused===`ref`)extractToDef(n)}}if(e.external)e.sharedDefsExtractedFor=e.external}function compactTypeUnion(e){const t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;const n=[];for(const e of t){if(!e||typeof e!==`object`)return;compactTypeUnion(e);const t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;const r=e.type;for(const e of Array.isArray(r)?r:[r]){if(typeof e!==`string`)return;if(!n.includes(e))n.push(e)}}delete e.anyOf;e.type=n.length===1?n[0]:n}const FOLDABLE_KEYS=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]);const UNION_KEYS=[`oneOf`,`anyOf`];function undeclaredConstraint(e){const t=e.additionalProperties;if(t===void 0||t===false||typeof t!==`object`||t===null)return null;return Object.keys(t).length?t:null}function foldObjects(e){const t=[];for(const n of e){if(typeof n!==`object`||n.type!==`object`)return null;for(const e in n)if(!FOLDABLE_KEYS.has(e))return null;t.push(n)}const n={};const r=/* @__PURE__ */ new Set;for(const e of t){for(const r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;const e=[];for(const n of t){const t=n.properties?.[r]??undeclaredConstraint(n);if(t===null||t===void 0)continue;if(!e.some(e=>JSON.stringify(e)===JSON.stringify(t)))e.push(t)}const i=e.length===1?e[0]:foldObjects(e)??{allOf:e};assignProp(n,r,i)}for(const t of e.required??[])r.add(t)}const i={type:`object`,properties:n};if(r.size)i.required=[...r];if(t.every(e=>e.additionalProperties===false))i.additionalProperties=false;else{const e=[];for(const n of t){const t=undeclaredConstraint(n);if(t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t)))e.push(t)}if(e.length===1)i.additionalProperties=e[0];else if(e.length>1)i.additionalProperties={allOf:e}}return i}function foldIntersection(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const t of FOLDABLE_KEYS)if(t in e)return;const n=t.filter(e=>UNION_KEYS.some(t=>Array.isArray(e[t])));let r=null;if(!n.length)r=foldObjects(t);else{const e=n[0];const i=UNION_KEYS.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;const a=t.filter(t=>t!==e);const o=e[i].map(e=>foldObjects([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}if(!r)return;delete e.allOf;assignProps(e,r)}function finalize(e,t){const n=e.seen.get(t);if(!n)throw new Error(`Unprocessed schema. This is a bug in Zod.`);const flattenRef=t=>{const n=e.seen.get(t);if(n.ref===null)return;const r=n.def??n.schema;const i={...r};const a=n.ref;n.ref=null;if(a){flattenRef(a);const n=e.seen.get(a);const o=n.schema;if(o.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)){r.allOf=r.allOf??[];r.allOf.push(o)}else assignProps(r,o);assignProps(r,i);if(t._zod.parent===a)for(const e in r){if(e===`$ref`||e===`allOf`)continue;if(!(e in i))delete r[e]}if(o.$ref&&n.def)for(const e in r){if(e===`$ref`||e===`allOf`)continue;if(e in n.def&&JSON.stringify(r[e])===JSON.stringify(n.def[e]))delete r[e]}}const o=t._zod.parent;if(o&&o!==a){flattenRef(o);const t=e.seen.get(o);if(t?.schema.$ref){r.$ref=t.schema.$ref;if(t.def)for(const e in r){if(e===`$ref`||e===`allOf`)continue;if(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(const t of[...e.seen.entries()].reverse())flattenRef(t[0]);if(e.target!==`openapi-3.0`)for(const t of e.seen.entries())compactTypeUnion(t[1].def??t[1].schema);for(const t of e.deferred)t();if(e.intersections.length){const t=/* @__PURE__ */ new Map;for(const n of e.seen.values())for(const e of[n.schema,n.def]){const n=e?.allOf;if(!Array.isArray(n))continue;const r=t.get(n);if(r)r.push(e);else t.set(n,[e])}for(const n of e.intersections)for(const e of t.get(n)??[])foldIntersection(e)}}const r={};if(e.target===`draft-2020-12`)r.$schema=`https://json-schema.org/draft/2020-12/schema`;else if(e.target===`draft-07`)r.$schema=`http://json-schema.org/draft-07/schema#`;else if(e.target===`draft-04`)r.$schema=`http://json-schema.org/draft-04/schema#`;else if(e.target===`openapi-3.0`){}if(e.external?.uri){const n=e.external.registry.get(t)?.id;if(!n)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(n)}assignProps(r,n.defId?n.schema:n.def??n.schema);const i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&r.id===i)delete r.id;const a=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const t of e.seen.entries()){const e=t[1];if(e.def&&e.defId){if(e.def.id===e.defId)delete e.def.id;assignProp(a,e.defId,e.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external){}else if(Object.keys(a).length>0){if(e.target===`draft-2020-12`)r.$defs=a;else r.definitions=a}try{const n=JSON.parse(JSON.stringify(r));Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:createStandardJSONSchemaMethod(t,`input`,e.processors),output:createStandardJSONSchemaMethod(t,`output`,e.processors)}},enumerable:false,writable:false});return n}catch(e){throw new Error(`Error converting schema to JSON.`)}}function isTransforming(e,t){const n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return false;n.seen.add(e);const r=e._zod.def;if(r.type===`transform`)return true;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`){if(e._zod.traits.has(`$ZodCodec`))return true;return isTransforming(r.in,n)||isTransforming(r.out,n)}if(r.type===`object`){for(const e in r.shape)if(isTransforming(r.shape[e],n))return true;return false}if(r.type===`union`){for(const e of r.options)if(isTransforming(e,n))return true;return false}if(r.type===`tuple`){for(const e of r.items)if(isTransforming(e,n))return true;if(r.rest&&isTransforming(r.rest,n))return true;return false}return false}const createToJSONSchemaMethod=(e,t={})=>n=>{const r=initializeContext({...n,processors:t});processSchema(e,r);extractDefs(r,e);return finalize(r,e)};const createStandardJSONSchemaMethod=(e,t,n={})=>r=>{const{libraryOptions:i,target:a}=r??{};const o=initializeContext({...i??{},target:a,io:t,processors:n});processSchema(e,o);extractDefs(o,e);return finalize(o,e)};
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/json-schema-processors.js
const narrowMin=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n};const narrowMax=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n};const narrowBoth=(e,t)=>{narrowMin(e,`minimum`,t);narrowMax(e,`maximum`,t)};const addDivisor=(e,t)=>{e.multipleOf??(e.multipleOf=[]);if(!e.multipleOf.includes(t))e.multipleOf.push(t)};const addPattern=(e,t)=>{e.patterns??(e.patterns=/* @__PURE__ */ new Set);e.patterns.add(t)};const intersectMime=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]};const setFormat=(e,t)=>{e.format=t;if(t.includes(`int`))e.isInt=true};const minContributor=(e,t)=>narrowMin(e,`minimum`,t.minimum);const maxContributor=(e,t)=>narrowMax(e,`maximum`,t.maximum);const formatContributor=e=>(t,n)=>{setFormat(t,n.format);const[r,i]=e[n.format];narrowMin(t,`minimum`,r);narrowMax(t,`maximum`,i)};const contributors={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(NUMBER_FORMAT_RANGES),bigint_format:formatContributor(BIGINT_FORMAT_RANGES),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);if(t.pattern)addPattern(e,t.pattern);if(t.format===`base64`||t.format===`base64url`)e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=true},mime_type:(e,t)=>intersectMime(e,t.mime)};function aggregateChecks(e){const t={};const n=e._zod.def;const r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(const e of r)contributors[e._zod.def.check]?.(t,e._zod.def);const i=e._zod.bag;if(i.minimum!==void 0)narrowMin(t,`minimum`,i.minimum);if(i.exclusiveMinimum!==void 0)narrowMin(t,`exclusiveMinimum`,i.exclusiveMinimum);if(i.maximum!==void 0)narrowMax(t,`maximum`,i.maximum);if(i.exclusiveMaximum!==void 0)narrowMax(t,`exclusiveMaximum`,i.exclusiveMaximum);if(i.multipleOf!==void 0)addDivisor(t,i.multipleOf);if(i.format!==void 0){t.format??(t.format=i.format);if(i.format.includes(`int`))t.isInt=true}if(i.mime)intersectMime(t,i.mime);for(const e of i.patterns??[])addPattern(t,e);return t}const formatMap={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``};const exactPatterns=/* @__PURE__ */ new Map([[base64Charset,base64],[base64urlCharset,base64url]]);const exactPattern=e=>exactPatterns.get(e)??e;const stringProcessor=(e,t,n,r)=>{const i=n;i.type=`string`;const{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=aggregateChecks(e);if(typeof a===`number`)i.minLength=a;if(typeof o===`number`)i.maxLength=o;if(s){i.format=formatMap[s]??s;if(i.format===``)delete i.format;if(s===`time`||u)delete i.format}if(l)i.contentEncoding=l;if(c&&c.size>0){const e=[...c].map(exactPattern);if(e.length===1)i.pattern=e[0].source;else if(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}))]}};const numberProcessor=(e,t,n,r)=>{const i=n;const{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=aggregateChecks(e);i.type=u?`integer`:`number`;const d=typeof l===`number`&&l>=(a??Number.NEGATIVE_INFINITY);const f=typeof c===`number`&&c<=(o??Number.POSITIVE_INFINITY);const p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d){if(p){i.minimum=l;i.exclusiveMinimum=true}else i.exclusiveMinimum=l}else if(typeof a===`number`)i.minimum=a;if(f){if(p){i.maximum=c;i.exclusiveMaximum=true}else i.exclusiveMaximum=c}else if(typeof o===`number`)i.maximum=o;if(s){const n=/* @__PURE__ */ new Set;for(const a of s)if(Number.isFinite(a)&&a!==0)n.add(Math.abs(a));else handleUnrepresentable(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);const[a,...o]=n;if(a!==void 0)i.multipleOf=a;if(o.length)i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))]}};const booleanProcessor=(e,t,n,r)=>{n.type=`boolean`};const neverProcessor=(e,t,n,r)=>{n.not={}};const unknownProcessor=(e,t,n,r)=>{};const enumProcessor=(e,t,n,r)=>{const i=e._zod.def;const a=getEnumValues(i.entries);if(a.length===0){n.not={};return}if(a.every(e=>typeof e===`number`))n.type=`number`;if(a.every(e=>typeof e===`string`))n.type=`string`;n.enum=a};const literalProcessor=(e,t,n,r)=>{const i=e._zod.def;if(i.values.length===0){n.not={};return}const a=[];for(const o of i.values)if(o===void 0){if(handleUnrepresentable(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o===`bigint`){if(handleUnrepresentable(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length===0){}else if(a.length===1){const e=a[0];n.type=e===null?`null`:typeof e;if(t.target===`draft-04`||t.target===`openapi-3.0`)n.enum=[e];else n.const=e}else{if(a.every(e=>typeof e===`number`))n.type=`number`;if(a.every(e=>typeof e===`string`))n.type=`string`;if(a.every(e=>typeof e===`boolean`))n.type=`boolean`;if(a.every(e=>e===null))n.type=`null`;n.enum=a}};const customProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Custom types cannot be represented in JSON Schema`)};const transformProcessor=(e,t,n,r)=>{handleUnrepresentable(e,t,n,r,`Transforms cannot be represented in JSON Schema`)};const arrayProcessor=(e,t,n,r)=>{const i=n;const a=e._zod.def;const{minimum:o,maximum:s}=aggregateChecks(e);if(typeof o===`number`)i.minItems=o;if(typeof s===`number`)i.maxItems=s;i.type=`array`;i.items=processSchema(a.element,t,{...r,path:[...r.path,`items`]})};function inputOptin(e){const t=e._zod.def;if(t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`))return inputOptin(t.out);if(t.type===`catch`)return inputOptin(t.innerType);return e._zod.optin}const objectProcessor=(e,t,n,r)=>{const i=n;const a=e._zod.def;const o=a.shape;if(Object.getOwnPropertySymbols(o).length&&handleUnrepresentable(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`;i.properties={};for(const e in o)assignProp(i.properties,e,processSchema(o[e],t,{...r,path:[...r.path,`properties`,e]}));const s=[];for(const e of Object.keys(o)){const n=a.shape[e];if(t.io===`input`?inputOptin(n)===void 0:n._zod.optout===void 0)s.push(e)}if(s.length>0)i.required=s;if(a.catchall?._zod.def.type===`never`)i.additionalProperties=false;else if(!a.catchall){if(t.io===`output`)i.additionalProperties=false}else if(a.catchall)i.additionalProperties=processSchema(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})};const unionProcessor=(e,t,n,r)=>{const i=e._zod.def;const a=i.inclusive===false;const o=i.options.map((e,n)=>processSchema(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));if(a)n.oneOf=o;else n.anyOf=o};const intersectionProcessor=(e,t,n,r)=>{const i=e._zod.def;const a=processSchema(i.left,t,{...r,path:[...r.path,`allOf`,0]});const o=processSchema(i.right,t,{...r,path:[...r.path,`allOf`,1]});const isSimpleIntersection=e=>`allOf`in e&&Object.keys(e).length===1;const s=[...isSimpleIntersection(a)?a.allOf:[a],...isSimpleIntersection(o)?o.allOf:[o]];n.allOf=s;t.intersections.push(s)};function stringifyKeyNames(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);const r=e.get(t)?.def;if(!r)return t;const i=stringifyKeyNames(e,r,n);return i===r?t:i}for(const r of[`anyOf`,`oneOf`]){const i=t[r];if(!Array.isArray(i))continue;const a=i.map(t=>stringifyKeyNames(e,t,n));if(a.some((e,t)=>e!==i[t]))t={...t,[r]:a}}const r=Array.isArray(t.type)?t.type:[t.type];const i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`);const a=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!a?.some(e=>typeof e===`number`))return t;const{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;if(p.enum)p.enum=p.enum.map(e=>typeof e===`number`?String(e):e);else if(typeof p.const===`number`)p.const=String(p.const);if(!i)return p;p.type=`string`;if(!a)p.pattern=(r.includes(`number`)?number$1:integer).source;return p}const pendingRecords=/* @__PURE__ */ new WeakMap;function rewriteKeyNames(e){const t=/* @__PURE__ */ new Map;for(const n of e.seen.values())if(n.def&&!t.has(n.schema))t.set(n.schema,n);const n=/* @__PURE__ */ new Map;for(const r of pendingRecords.get(e)??[]){const i=e.seen.get(r);const a=(i?.def??i?.schema)?.propertyNames;if(!a||a===true||n.has(a))continue;const o=stringifyKeyNames(t,a,/* @__PURE__ */ new Set);if(o!==a)n.set(a,o)}if(!n.size)return;for(const t of e.seen.values())for(const e of[t.schema,t.def]){const t=e&&n.get(e.propertyNames);if(t)e.propertyNames=t}}const recordProcessor=(e,t,n,r)=>{const i=n;const a=e._zod.def;i.type=`object`;const o=a.keyType;const s=aggregateChecks(o).patterns;if(a.mode===`loose`&&s&&s.size>0){const e=processSchema(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(const t of s)assignProp(i.patternProperties,exactPattern(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=processSchema(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=pendingRecords.get(t);if(!n){n=[];pendingRecords.set(t,n);t.deferred.push(()=>rewriteKeyNames(t))}n.push(e)}i.additionalProperties=processSchema(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}const c=o._zod.values;const l=t.io===`input`&&inputOptin(a.valueType)!==void 0;if(c&&!a.partial&&!l){const e=[...c].filter(e=>typeof e===`string`||typeof e===`number`);if(e.length>0)i.required=e.map(String)}};const nullableProcessor=(e,t,n,r)=>{const i=e._zod.def;const a=processSchema(i.innerType,t,r);const o=t.seen.get(e);if(t.target===`openapi-3.0`){o.ref=i.innerType;n.nullable=true}else n.anyOf=[a,{type:`null`}]};const nonoptionalProcessor=(e,t,n,r)=>{const i=e._zod.def;processSchema(i.innerType,t,r);const a=t.seen.get(e);a.ref=i.innerType};const UNREPRESENTABLE_DEFAULT=Symbol();function serializeDefaultValue(e,t,n,r,i){let a=false;const o=JSON.stringify(e,(e,t)=>{if(typeof t!==`bigint`)return t;a=true;return null});if(!a)return JSON.parse(o);handleUnrepresentable(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`);return UNREPRESENTABLE_DEFAULT}const defaultProcessor=(e,t,n,r)=>{const i=e._zod.def;processSchema(i.innerType,t,r);const a=t.seen.get(e);a.ref=i.innerType;const o=serializeDefaultValue(i.defaultValue,e,t,n,r);if(o!==UNREPRESENTABLE_DEFAULT)n.default=o};const prefaultProcessor=(e,t,n,r)=>{const i=e._zod.def;processSchema(i.innerType,t,r);const a=t.seen.get(e);a.ref=i.innerType;if(t.io!==`input`)return;const o=serializeDefaultValue(i.defaultValue,e,t,n,r);if(o!==UNREPRESENTABLE_DEFAULT)n._prefault=o};const catchProcessor=(e,t,n,r)=>{const i=e._zod.def;processSchema(i.innerType,t,r);const a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{handleUnrepresentable(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o};const pipeProcessor=(e,t,n,r)=>{const i=e._zod.def;const a=i.in._zod.traits.has(`$ZodTransform`);const o=t.io===`input`?a?i.out:i.in:i.out;processSchema(o,t,r);const s=t.seen.get(e);s.ref=o};const readonlyProcessor=(e,t,n,r)=>{const i=e._zod.def;processSchema(i.innerType,t,r);const a=t.seen.get(e);a.ref=i.innerType;n.readOnly=true};const optionalProcessor=(e,t,n,r)=>{const i=e._zod.def;processSchema(i.innerType,t,r);const a=t.seen.get(e);a.ref=i.innerType};
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/errors.js
const _installedErrorProtos=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function _lazyMethod(e,t,n){Object.defineProperty(e,t,{configurable:true,enumerable:false,get(){const e=n(this);Object.defineProperty(this,t,{value:e,configurable:true,writable:true});return e},set(e){Object.defineProperty(this,t,{value:e,configurable:true,writable:true})}})}const initializer=(e,t)=>{$ZodError.init(e,t);e.name=`ZodError`;const n=Object.getPrototypeOf(e);if(_installedErrorProtos.has(n))return;_installedErrorProtos.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:true,enumerable:false,get(){return this.issues.length===0}})};const ZodRealError=/*@__PURE__*/ $constructor(`ZodError`,initializer,void 0,{Parent:Error});
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/parse.js
const parse=/* @__PURE__ */ _parse(ZodRealError);const parseAsync=/* @__PURE__ */ _parseAsync(ZodRealError);const safeParse=/* @__PURE__ */ _safeParse(ZodRealError);const safeParseAsync=/* @__PURE__ */ _safeParseAsync(ZodRealError);const encode=/* @__PURE__ */ _encode(ZodRealError);const decode=/* @__PURE__ */ _decode(ZodRealError);const encodeAsync=/* @__PURE__ */ _encodeAsync(ZodRealError);const decodeAsync=/* @__PURE__ */ _decodeAsync(ZodRealError);const safeEncode=/* @__PURE__ */ _safeEncode(ZodRealError);const safeDecode=/* @__PURE__ */ _safeDecode(ZodRealError);const safeEncodeAsync=/* @__PURE__ */ _safeEncodeAsync(ZodRealError);const safeDecodeAsync=/* @__PURE__ */ _safeDecodeAsync(ZodRealError);
//!node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/schemas.js
function _ensureDefaultLocale(){if(!globalConfig.localeError)config(en_default())}function _ensureDefaultMemoizer(){if(!globalConfig.memoizer)config({memoizer:memoizer()})}const ZodType=/*@__PURE__*/ $constructor(`ZodType`,(e,t)=>{_ensureDefaultLocale();$ZodType.init(e,t);e.def=t;e.type=t.type;return e},{check(...e){const 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:true})},with(...e){return this.check(...e)},clone(e,t){return clone(this,e,t)},brand(){return this},register(e,t){e.add(this,t);return this},refine(e,t){return this.check(refine(e,t))},superRefine(e,t){return this.check(superRefine(e,t))},overwrite(e){return this.check(_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){const t=this.clone();globalRegistry.add(t,{description:e});return t},meta(...e){if(e.length===0)return globalRegistry.get(this);const t=this.clone();globalRegistry.add(t,e[0]);return 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 parse(this,e,t,{callee:_parse})},parseAsync:async function _parseAsync(e,t){return await parseAsync(this,e,t,{callee:_parseAsync})},safeParse(e,t){return safeParse(this,e,t)},async safeParseAsync(e,t){return safeParseAsync(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 encode(this,e,t,{callee:_encode})},decode:function _decode(e,t){return decode(this,e,t,{callee:_decode})},encodeAsync:async function _encodeAsync(e,t){return await encodeAsync(this,e,t,{callee:_encodeAsync})},decodeAsync:async function _decodeAsync(e,t){return await decodeAsync(this,e,t,{callee:_decodeAsync})},safeEncode(e,t){return safeEncode(this,e,t)},safeDecode(e,t){return safeDecode(this,e,t)},async safeEncodeAsync(e,t){return safeEncodeAsync(this,e,t)},async safeDecodeAsync(e,t){return safeDecodeAsync(this,e,t)},toJSONSchema(e){return createToJSONSchemaMethod(this,{})(e)},get description(){return globalRegistry.get(this)?.description},get _def(){return this._zod.def}});const _ZodString=/*@__PURE__*/ $constructor(`_ZodString`,(e,t)=>{$ZodString.init(e,t);ZodType.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(_regex(...e))},includes(...e){return this.check(_includes(...e))},startsWith(...e){return this.check(_startsWith(...e))},endsWith(...e){return this.check(_endsWith(...e))},min(...e){return this.check(_minLength(...e))},max(...e){return this.check(_maxLength(...e))},length(...e){return this.check(_length(...e))},nonempty(...e){return this.check(_minLength(1,...e))},lowercase(e){return this.check(_lowercase(e))},uppercase(e){return this.check(_uppercase(e))},trim(){return this.check(_trim())},normalize(...e){return this.check(_normalize(...e))},toLowerCase(){return this.check(_toLowerCase())},toUpperCase(){return this.check(_toUpperCase())},slugify(){return this.check(_slugify())}}));const ZodString=/*@__PURE__*/ $constructor(`ZodString`,(e,t)=>{$ZodString.init(e,t);_ZodString.init(e,t)},{email(e){return this.check(_email(ZodEmail,e))},url(e){return this.check(_url(ZodURL,e))},jwt(e){return this.check(_jwt(ZodJWT,e))},emoji(e){return this.check(_emoji(ZodEmoji,e))},guid(e){return this.check(_guid(ZodGUID,e))},uuid(e){return this.check(_uuid(ZodUUID,e))},uuidv4(e){return this.check(_uuidv4(ZodUUID,e))},uuidv6(e){return this.check(_uuidv6(ZodUUID,e))},uuidv7(e){return this.check(_uuidv7(ZodUUID,e))},nanoid(e){return this.check(_nanoid(ZodNanoID,e))},cuid(e){return this.check(_cuid(ZodCUID,e))},cuid2(e){return this.check(_cuid2(ZodCUID2,e))},ulid(e){return this.check(_ulid(ZodULID,e))},base64(e){return this.check(_base64(ZodBase64,e))},base64url(e){return this.check(_base64url(ZodBase64URL,e))},xid(e){return this.check(_xid(ZodXID,e))},ksuid(e){return this.check(_ksuid(ZodKSUID,e))},ipv4(e){return this.check(_ipv4(ZodIPv4,e))},ipv6(e){return this.check(_ipv6(ZodIPv6,e))},cidrv4(e){return this.check(_cidrv4(ZodCIDRv4,e))},cidrv6(e){return this.check(_cidrv6(ZodCIDRv6,e))},e164(e){return this.check(_e164(ZodE164,e))},datetime(e){return this.check(_isoDateTime(ZodISODateTime,e))},date(e){return this.check(_isoDate(ZodISODate,e))},time(e){return this.check(_isoTime(ZodISOTime,e))},duration(e){return this.check(_isoDuration(ZodISODuration,e))}});function string(e){return _string(ZodString,e)}const ZodStringFormat=/*@__PURE__*/ $constructor(`ZodStringFormat`,(e,t)=>{$ZodStringFormat.init(e,t);_ZodString.init(e,t)});const ZodISODateTime=/*@__PURE__*/ $constructor(`ZodISODateTime`,(e,t)=>{$ZodISODateTime.init(e,t);ZodStringFormat.init(e,t)});const ZodISODate=/*@__PURE__*/ $constructor(`ZodISODate`,(e,t)=>{$ZodISODate.init(e,t);ZodStringFormat.init(e,t)});const ZodISOTime=/*@__PURE__*/ $constructor(`ZodISOTime`,(e,t)=>{$ZodISOTime.init(e,t);ZodStringFormat.init(e,t)});const ZodISODuration=/*@__PURE__*/ $constructor(`ZodISODuration`,(e,t)=>{$ZodISODuration.init(e,t);ZodStringFormat.init(e,t)});const ZodEmail=/*@__PURE__*/ $constructor(`ZodEmail`,(e,t)=>{$ZodEmail.init(e,t);ZodStringFormat.init(e,t)});const ZodGUID=/*@__PURE__*/ $constructor(`ZodGUID`,(e,t)=>{$ZodGUID.init(e,t);ZodStringFormat.init(e,t)});const ZodUUID=/*@__PURE__*/ $constructor(`ZodUUID`,(e,t)=>{$ZodUUID.init(e,t);ZodStringFormat.init(e,t)});const ZodURL=/*@__PURE__*/ $constructor(`ZodURL`,(e,t)=>{$ZodURL.init(e,t);ZodStringFormat.init(e,t)});const ZodEmoji=/*@__PURE__*/ $constructor(`ZodEmoji`,(e,t)=>{$ZodEmoji.init(e,t);ZodStringFormat.init(e,t)});const ZodNanoID=/*@__PURE__*/ $constructor(`ZodNanoID`,(e,t)=>{$ZodNanoID.init(e,t);ZodStringFormat.init(e,t)});const ZodCUID=/*@__PURE__*/ $constructor(`ZodCUID`,(e,t)=>{$ZodCUID.init(e,t);ZodStringFormat.init(e,t)});const ZodCUID2=/*@__PURE__*/ $constructor(`ZodCUID2`,(e,t)=>{$ZodCUID2.init(e,t);ZodStringFormat.init(e,t)});const ZodULID=/*@__PURE__*/ $constructor(`ZodULID`,(e,t)=>{$ZodULID.init(e,t);ZodStringFormat.init(e,t)});const ZodXID=/*@__PURE__*/ $constructor(`ZodXID`,(e,t)=>{$ZodXID.init(e,t);ZodStringFormat.init(e,t)});const ZodKSUID=/*@__PURE__*/ $constructor(`ZodKSUID`,(e,t)=>{$ZodKSUID.init(e,t);ZodStringFormat.init(e,t)});const ZodIPv4=/*@__PURE__*/ $constructor(`ZodIPv4`,(e,t)=>{$ZodIPv4.init(e,t);ZodStringFormat.init(e,t)});const ZodIPv6=/*@__PURE__*/ $constructor(`ZodIPv6`,(e,t)=>{$ZodIPv6.init(e,t);ZodStringFormat.init(e,t)});const ZodCIDRv4=/*@__PURE__*/ $constructor(`ZodCIDRv4`,(e,t)=>{$ZodCIDRv4.init(e,t);ZodStringFormat.init(e,t)});const ZodCIDRv6=/*@__PURE__*/ $constructor(`ZodCIDRv6`,(e,t)=>{$ZodCIDRv6.init(e,t);ZodStringFormat.init(e,t)});const ZodBase64=/*@__PURE__*/ $constructor(`ZodBase64`,(e,t)=>{$ZodBase64.init(e,t);ZodStringFormat.init(e,t)});const ZodBase64URL=/*@__PURE__*/ $constructor(`ZodBase64URL`,(e,t)=>{$ZodBase64URL.init(e,t);ZodStringFormat.init(e,t)});const ZodE164=/*@__PURE__*/ $constructor(`ZodE164`,(e,t)=>{$ZodE164.init(e,t);ZodStringFormat.init(e,t)});const ZodJWT=/*@__PURE__*/ $constructor(`ZodJWT`,(e,t)=>{$ZodJWT.init(e,t);ZodStringFormat.init(e,t)});const ZodNumber=/*@__PURE__*/ $constructor(`ZodNumber`,(e,t)=>{$ZodNumber.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>numberProcessor(e,t,n,r);e.isFinite=true},/*@__PURE__*/ derived({minValue:e=>{const{minimum:t,exclusiveMinimum:n}=aggregateChecks(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:e=>{const{maximum:t,exclusiveMaximum:n}=aggregateChecks(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:e=>{const{isInt:t,multipleOf:n}=aggregateChecks(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>aggregateChecks(e).format??null},{gt(e,t){return this.check(_gt(e,t))},gte(e,t){return this.check(_gte(e,t))},min(e,t){return this.check(_gte(e,t))},lt(e,t){return this.check(_lt(e,t))},lte(e,t){return this.check(_lte(e,t))},max(e,t){return this.check(_lte(e,t))},int(e){return this.check(int(e))},safe(e){return this.check(int(e))},positive(e){return this.check(_gt(0,e))},nonnegative(e){return this.check(_gte(0,e))},negative(e){return this.check(_lt(0,e))},nonpositive(e){return this.check(_lte(0,e))},multipleOf(e,t){return this.check(_multipleOf(e,t))},step(e,t){return this.check(_multipleOf(e,t))},finite(){return this}}));function number(e){return _number(ZodNumber,e)}const ZodNumberFormat=/*@__PURE__*/ $constructor(`ZodNumberFormat`,(e,t)=>{$ZodNumberFormat.init(e,t);ZodNumber.init(e,t)});function int(e){return _int(ZodNumberFormat,e)}const ZodBoolean=/*@__PURE__*/ $constructor(`ZodBoolean`,(e,t)=>{$ZodBoolean.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>booleanProcessor(e,t,n,r)});function boolean(e){return _boolean(ZodBoolean,e)}const ZodUnknown=/*@__PURE__*/ $constructor(`ZodUnknown`,(e,t)=>{$ZodUnknown.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>unknownProcessor(e,t,n,r)});function unknown(){return _unknown(ZodUnknown)}const ZodNever=/*@__PURE__*/ $constructor(`ZodNever`,(e,t)=>{$ZodNever.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>neverProcessor(e,t,n,r)});function never(e){return _never(ZodNever,e)}const ZodArray=/*@__PURE__*/ $constructor(`ZodArray`,(e,t)=>{_ensureDefaultMemoizer();$ZodArray.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>arrayProcessor(e,t,n,r);e.element=t.element},{min(e,t){return this.check(_minLength(e,t))},nonempty(e){return this.check(_minLength(1,e))},max(e,t){return this.check(_maxLength(e,t))},length(e,t){return this.check(_length(e,t))},unwrap(){return this.element}});function array(e,t){return _array(ZodArray,e,t)}const ZodObject=/*@__PURE__*/ $constructor(`ZodObject`,(e,t)=>{_ensureDefaultMemoizer();$ZodObjectJIT.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>objectProcessor(e,t,n,r);installLazyProp(e,`shape`,e=>e._zod.def.shape,false)},{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(ZodOptional,this,e[0])},exactPartial(...e){return partial(ZodExactOptional,this,e[0],`exactPartial`)},required(...e){return required(ZodNonOptional,this,e[0])}});function object(e,t){const n={type:`object`,shape:e??{},...normalizeParams(t)};return new ZodObject(n)}function strictObject(e,t){return new ZodObject({type:`object`,shape:e,catchall:never(),...normalizeParams(t)})}function looseObject(e,t){return new ZodObject({type:`object`,shape:e,catchall:unknown(),...normalizeParams(t)})}const ZodUnion=/*@__PURE__*/ $constructor(`ZodUnion`,(e,t)=>{$ZodUnion.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>unionProcessor(e,t,n,r);e.options=t.options});function union(e,t){return new ZodUnion({type:`union`,options:e,...normalizeParams(t)})}const ZodDiscriminatedUnion=/*@__PURE__*/ $constructor(`ZodDiscriminatedUnion`,(e,t)=>{ZodUnion.init(e,t);$ZodDiscriminatedUnion.init(e,t)});function discriminatedUnion(e,t,n){return new ZodDiscriminatedUnion({type:`union`,options:t,discriminator:e,...normalizeParams(n)})}const ZodIntersection=/*@__PURE__*/ $constructor(`ZodIntersection`,(e,t)=>{$ZodIntersection.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>intersectionProcessor(e,t,n,r)});function intersection(e,t){return new ZodIntersection({type:`intersection`,left:e,right:t})}const ZodRecord=/*@__PURE__*/ $constructor(`ZodRecord`,(e,t)=>{_ensureDefaultMemoizer();$ZodRecord.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>recordProcessor(e,t,n,r);e.keyType=t.keyType;e.valueType=t.valueType});function record(e,t,n){if(!t||!t._zod)return new ZodRecord({type:`record`,keyType:string(),valueType:e,...normalizeParams(t)});return new ZodRecord({type:`record`,keyType:e,valueType:t,...normalizeParams(n)})}const ZodEnum=/*@__PURE__*/ $constructor(`ZodEnum`,(e,t)=>{$ZodEnum.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>enumProcessor(e,t,n,r);e.enum=t.entries;e.options=[...e._zod.values];const n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{const i={};for(const r of e)if(n.has(r))i[r]=t.entries[r];else throw new Error(`Key ${r} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})};e.exclude=(e,r)=>{const i={...t.entries};for(const t of e)if(n.has(t))delete i[t];else throw new Error(`Key ${t} not found in enum`);return new ZodEnum({...t,checks:[],...normalizeParams(r),entries:i})}});function _enum(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new ZodEnum({type:`enum`,entries:n,...normalizeParams(t)})}const ZodLiteral=/*@__PURE__*/ $constructor(`ZodLiteral`,(e,t)=>{$ZodLiteral.init(e,t);ZodType.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 new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function literal(e,t){return new ZodLiteral({type:`literal`,values:Array.isArray(e)?e:[e],...normalizeParams(t)})}const ZodTransform=/*@__PURE__*/ $constructor(`ZodTransform`,(e,t)=>{_ensureDefaultMemoizer();$ZodTransform.init(e,t);ZodType.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{const t=r;if(t.fatal)t.continue=false;t.code??(t.code=`custom`);if(!(`input`in t))t.input=n.value;t.inst??(t.inst=e);n.issues.push(issue(t))}};const i=t.transform(n.value,n);if(i instanceof Promise)return i.then(e=>{n.value=e;return n});n.value=i;return n}});function transform(e){return new ZodTransform({type:`transform`,transform:e})}const ZodOptional=/*@__PURE__*/ $constructor(`ZodOptional`,(e,t)=>{$ZodOptional.init(e,t);ZodType.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 ZodOptional({type:`optional`,innerType:e})}const ZodExactOptional=/*@__PURE__*/ $constructor(`ZodExactOptional`,(e,t)=>{$ZodExactOptional.init(e,t);ZodType.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 ZodExactOptional({type:`optional`,innerType:e})}const ZodNullable=/*@__PURE__*/ $constructor(`ZodNullable`,(e,t)=>{$ZodNullable.init(e,t);ZodType.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 ZodNullable({type:`nullable`,innerType:e})}const ZodDefault=/*@__PURE__*/ $constructor(`ZodDefault`,(e,t)=>{$ZodDefault.init(e,t);ZodType.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 ZodDefault({type:`default`,innerType:e,get defaultValue(){return typeof t===`function`?t():shallowClone(t)}})}const ZodPrefault=/*@__PURE__*/ $constructor(`ZodPrefault`,(e,t)=>{$ZodPrefault.init(e,t);ZodType.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 ZodPrefault({type:`prefault`,innerType:e,get defaultValue(){return typeof t===`function`?t():shallowClone(t)}})}const ZodNonOptional=/*@__PURE__*/ $constructor(`ZodNonOptional`,(e,t)=>{$ZodNonOptional.init(e,t);ZodType.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 ZodNonOptional({type:`nonoptional`,innerType:e,...normalizeParams(t)})}const ZodCatch=/*@__PURE__*/ $constructor(`ZodCatch`,(e,t)=>{$ZodCatch.init(e,t);ZodType.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 ZodCatch({type:`catch`,innerType:e,catchValue:typeof t===`function`?t:constantCatch(t)})}const ZodPipe=/*@__PURE__*/ $constructor(`ZodPipe`,(e,t)=>{$ZodPipe.init(e,t);ZodType.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 ZodPipe({type:`pipe`,in:e,out:t})}const ZodReadonly=/*@__PURE__*/ $constructor(`ZodReadonly`,(e,t)=>{$ZodReadonly.init(e,t);ZodType.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 ZodReadonly({type:`readonly`,innerType:e})}const ZodCustom=/*@__PURE__*/ $constructor(`ZodCustom`,(e,t)=>{$ZodCustom.init(e,t);ZodType.init(e,t);e._zod.processJSONSchema=(t,n,r)=>customProcessor(e,t,n,r)});function custom(e,t){return _custom(ZodCustom,e??(()=>true),t)}function refine(e,t={}){return _refine(ZodCustom,e,t)}function superRefine(e,t){return _superRefine(e,t)}
//!src/utils/zod-parse.ts
function safeParseWithSchema(e,t){const n=e.safeParse(t);return n.success?n.data:null}function safeParseJsonWithSchema(e,t){try{return safeParseWithSchema(e,JSON.parse(t))}catch{return null}}
//!src/infra/stale-lock-file.ts
function readLockFileOwnerPayload(e){if(!e)return null;return{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}}function inspectStaleLockOwner(e){const 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};const n=t.starttime===void 0?null:(e.getProcessStartTime??getFileLockProcessStartTime)(t.pid);const r={pid:t.pid,recordedStarttime:t.starttime??null,observedStarttime:n};const i=process.platform===`darwin`&&t.starttime!==void 0&&t.starttime>1e10?Math.floor(t.starttime/1e6):t.starttime;if(n!==null&&n!==i)return{reason:`owner-starttime-changed`,...r};return null}function isLockOwnerDefinitelyStale(e){return inspectStaleLockOwner(e)!==null}
//!src/infra/update-managed-service-handoff-schema.ts
const text=string().min(1).max(4096);const nativeProcessIdentityShape={pid:number().int().positive(),startIdentity:text.max(128)};const processIdentitySchema=strictObject({...nativeProcessIdentityShape,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:`));const managedHandoffBootSchema=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}$/)})]);const nativeLifetimeSchema=strictObject({kind:literal(`native`),unit:text,scope:text,placement:discriminatedUnion(`kind`,[strictObject({kind:literal(`pending`)}),strictObject({kind:literal(`attached`),invocation:string().regex(/^[a-f0-9]{32}$/i)})])});const cancellationProtocol=literal(`original-cancellation-v1`);const updateAction=strictObject({kind:literal(`update`),mutationProtocol:cancellationProtocol}).extend({mutationProtocol:cancellationProtocol.optional(),custody:_enum([`reserved`,`bound`]).optional()});const actionSchema=discriminatedUnion(`kind`,[updateAction,strictObject({kind:literal(`triage`),phase:_enum([`reserved`,`running`,`closing`,`closed`,`uncertain`]),lifetime:discriminatedUnion(`kind`,[strictObject({kind:literal(`foreground`),boot:managedHandoffBootSchema}),nativeLifetimeSchema])}).refine(e=>e.phase!==`running`||e.lifetime.kind!==`native`||e.lifetime.placement.kind===`attached`)]);const sourcePath=text.refine(path.isAbsolute,`Native source path must be absolute`);const digest=string().regex(/^[a-f0-9]{64}$/);const nativeBorrowerSourceSchema=strictObject({runId:text,transactionId:text,claimId:text,revision:number().int().nonnegative(),recordSha256:digest,serviceKey:sourcePath,configPaths:array(sourcePath).min(1).max(512),lifetimeId:text});const nativeBorrowerSchema=strictObject({id:string().uuid(),phase:_enum([`reserved`,`admitted`]),source:nativeBorrowerSourceSchema});const commonPayload={executor:processIdentitySchema,helper:processIdentitySchema,action:actionSchema};const originalUpdateSchema=strictObject({version:literal(2),executor:processIdentitySchema,helper:processIdentitySchema,action:updateAction});const originalGenerationSchema=strictObject({key:text,owner:text,payload:string().min(1),updatedAt:number().int().nonnegative()});const cancellingPayloadSchema=strictObject({version:literal(4),executor:processIdentitySchema,helper:processIdentitySchema,action:updateAction,cancellation:originalGenerationSchema}).refine(e=>{const t=safeParseJsonWithSchema(originalUpdateSchema,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`)});const currentPayloadSchema=strictObject({version:literal(2),...commonPayload,mutationOriginal:originalGenerationSchema.optional()}).refine(e=>{if(!e.mutationOriginal)return true;const t=safeParseJsonWithSchema(originalUpdateSchema,e.mutationOriginal.payload);return t!==null&&!e.mutationOriginal.key.includes(`/.openclaw-update-child-`)&&t.action.mutationProtocol===`original-cancellation-v1`});const payloadSchema=discriminatedUnion(`version`,[cancellingPayloadSchema,currentPayloadSchema,strictObject({version:literal(3),...commonPayload,action:strictObject({kind:literal(`update`)}),nativeBorrower:nativeBorrowerSchema})]);const retiredPayloadSchema=strictObject({version:literal(1),...nativeProcessIdentityShape});
//!src/infra/update-managed-service-handoff-boot.ts
const windowsBootIdentityArgs=[`-NoProfile`,`-NonInteractive`,`-Command`,`(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`];const windowsBootIdentityTimeoutMs=5e3;function createManagedHandoffBootIdentityReader(e){return function bootIdentity(){let t;const n=process.platform===`android`?`linux`:process.platform;if(n===`linux`)t=fs.readFileSync(`/proc/sys/kernel/random/boot_id`,`utf8`).trim();else if([`freebsd`,`darwin`,`win32`].includes(process.platform)){const n=process.platform===`freebsd`;const r=process.platform===`win32`;const i=spawnSync(r?`powershell.exe`:n?`/sbin/sysctl`:`/usr/sbin/sysctl`,r?windowsBootIdentityArgs:n?[`-b`,`kern.boot_id`]:[`-n`,`kern.bootsessionuuid`],{env:e,...n?{maxBuffer:16}:{encoding:`utf8`,windowsHide:true},timeout:r?windowsBootIdentityTimeoutMs:1e3,killSignal:`SIGKILL`,stdio:[`ignore`,`pipe`,`ignore`]});if(!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()}const r={platform:n,identity:n===`win32`?t:t?.toLowerCase()};const i=managedHandoffBootSchema.safeParse(r);if(!i.success)throw new Error(`OS boot identity unavailable; run openclaw triage manually`);return i.data}}
//!src/infra/gateway-lock-payload.ts
const GATEWAY_OWNER_HEARTBEAT_MS=15e3;const GATEWAY_OWNER_HEARTBEAT_STALE_MS=9e4;const LEGACY_GATEWAY_OWNER_LEASE_TTL_MS=3e5;const[uuidBoot,windowsBoot,freebsdBoot]=managedHandoffBootSchema.options;const host=string().min(1);const MachineIdentitySchema=string().regex(/^[a-f0-9]{64}$/u);const GatewayProcessNamespaceSchema=discriminatedUnion(`platform`,[uuidBoot.extend({host,platform:literal(`linux`),pidNsInode:string().min(1)}),uuidBoot.extend({host,platform:literal(`darwin`)}),windowsBoot.extend({host,identity:windowsBoot.shape.identity.optional()}),freebsdBoot.extend({host})]);let processNamespace;function readGatewayLockProcessNamespace(){if(processNamespace?.platform===process.platform&&(processNamespace.value!==null||process.platform!==`linux`&&process.platform!==`android`))return processNamespace.value;try{const e=process.platform===`win32`?{platform:`win32`}:createManagedHandoffBootIdentityReader(process.env)();const t=GatewayProcessNamespaceSchema.parse({host:os.hostname(),...e,...e.platform===`linux`?{pidNsInode:fs.readlinkSync(`/proc/self/ns/pid`).match(/^pid:\[(\d+)\]$/u)?.[1]}:{}});processNamespace={platform:process.platform,value:t};return t}catch{processNamespace={platform:process.platform,value:null};return 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 fs.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){const r=GatewayProcessNamespaceSchema.safeParse(e.processNamespace).data;const i=(t?readLockHeartbeat(t):void 0)??e.heartbeatAt;const a=i===void 0?void 0:Date.now()-i;const o=`${r?.host??e.host??`unknown host`}${r?.platform===`linux`?`/pid-ns ${r.pidNsInode}`:``}`;const s=n===`live`?`The holder ${e.pid} is alive on this host, stop it first`:n===`unknown`?`Stop the holder before retrying`:`Run this command inside the Gateway container or with a shared PID namespace`;return`holder ${e.pid??`unknown`} at ${o}, last renewed ${a===void 0?`at an unknown time`:`${Math.max(0,Math.floor(a/1e3))} s ago`}. ${s}.`}var GatewayLockNamespaceError=class extends Error{constructor(e,t){const 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`;const r=GatewayProcessNamespaceSchema.safeParse(e.processNamespace).data;if(isForeignLinuxNamespace(r,readGatewayLockProcessNamespace())){const n=t?readLockHeartbeat(t):e.heartbeatAt;if(n!==void 0)this.heartbeatAgeMs=Math.max(0,Date.now()-n)}}};function classifyGatewayOwnerProcessNamespace(e,t={}){const n=GatewayProcessNamespaceSchema.safeParse(e).data;if(!n||t.ownerHost!==void 0&&t.ownerHost!==n.host)return`unknown`;const r=readGatewayLockProcessNamespace();if(!r)return`unknown`;if(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`;const e=t.readGatewayHeartbeat();if(e!==void 0&&Date.now()-e>9e4)return`dead`}if(n.platform===`darwin`&&t.machineIdentity!==void 0){const e=MachineIdentitySchema.safeParse(t.machineIdentity).data;const i=readProcessMachineIdentity();if(e&&i){if(e!==i)return`unknown`;if(n.identity!==r.identity)return`dead`}}const i=n.platform===`darwin`&&r.platform===`darwin`&&n.identity===r.identity;if(n.host!==r.host&&!i)return`unknown`;if(n.platform===`win32`)return`same`;if(n.identity!==r.identity)return`dead`;if(n.platform!==`linux`||r.platform===`linux`&&n.pidNsInode===r.pidNsInode)return`same`;return`unknown`}const LockPayloadSchema=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:GatewayProcessNamespaceSchema.nullable().optional(),machineIdentity:MachineIdentitySchema.nullable().optional()});function parseGatewayLockPayload(e){return safeParseJsonWithSchema(LockPayloadSchema,e)}
//!src/infra/gateway-state-owner-cold-admission.ts
function createColdAdmissionBudget(e){const t=normalizeSqliteNonNegativeInteger(e.busyTimeoutMs,`busyTimeoutMs`);const n=performance.now()+t;const r=resolveIdentityPathViaExistingAncestorSync(e.databasePath);const remainingBusyTimeoutMs=()=>Math.max(0,Math.ceil(n-performance.now()));const retryDelay=t=>{if(!(t instanceof StateDatabaseAdmissionPendingError)||resolveIdentityPathViaExistingAncestorSync(t.databasePath)!==r||e.canRetry?.()===false)throw t;const i=n-performance.now();if(i<=0)throw t;return Math.min(10,i)};return{remainingBusyTimeoutMs,retryDelay}}
//!src/infra/private-mode.ts
const CHMOD_UNSUPPORTED_CODES=/* @__PURE__ */ new Set([`ENOTSUP`,`EOPNOTSUPP`,`EINVAL`]);const PRIVATE_PROBE_FILE_MODE=384;function hasRestrictivePermissions(e){try{return(statSync(e).mode&63)===0}catch{return false}}function filesystemRejectsChmod(e){let t;try{const n=statSync(e).isDirectory()?e:path.dirname(e);t=path.join(n,`.openclaw-chmod-probe-${randomUUID()}`);writeFileSync(t,``,{flag:`wx`,mode:PRIVATE_PROBE_FILE_MODE})}catch{return false}try{chmodSync(t,PRIVATE_PROBE_FILE_MODE);return false}catch(e){return isErrno(e)&&e.code===`EPERM`}finally{try{unlinkSync(t)}catch{}}}function canIgnorePrivateChmodError(e,t,n){if(t&&CHMOD_UNSUPPORTED_CODES.has(t))return true;if(t!==`EROFS`&&t!==`EPERM`)return false;return n||t===`EPERM`&&filesystemRejectsChmod(e)}function applyPrivateModeSync(e,t){if((statSync(e).mode&4095)===t)return{applied:true};try{chmodSync(e,t);return{applied:true}}catch(t){if(!canIgnorePrivateChmodError(e,isErrno(t)?t.code:void 0,hasRestrictivePermissions(e)))throw t;return{applied:false,error:t}}}
//!src/infra/gateway-state-owner-directory.ts
const LOCAL_STATE_FILESYSTEM_GUIDANCE=`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){const n=fs.mkdirSync(e,{recursive:true,mode:448});if(n&&t){const r=path.toNamespacedPath(n);const i=[];for(let t=e;;){const{dev:e,ino:n}=fs.lstatSync(t,{bigint:true});i.push({path:t,dev:e,ino:n});if(path.toNamespacedPath(t)===r)break;const a=path.dirname(t);if(a===t)throw new Error(`Created state ownership directory is outside its expected ancestry`);t=a}for(const e of i){const n=t.findIndex(t=>t.path===e.path);if(n<0)t.push(e);else t[n]=e}}const r=fs.lstatSync(e);const i=process.getuid?.();if(!r.isDirectory())throw new Error(`State ownership directory must be a user-owned real directory`);if(i!==void 0&&r.uid!==i)throw new Error(`State ownership directory ${e} is owned by uid ${r.uid}, not this user (uid ${i}). ${LOCAL_STATE_FILESYSTEM_GUIDANCE}`);if(process.platform!==`win32`&&(r.mode&4095)!==448){applyPrivateModeSync(e,448);if((fs.lstatSync(e).mode&63)!==0)throw new Error(`State ownership directory ${e} permissions could not be set to 0700. ${LOCAL_STATE_FILESYSTEM_GUIDANCE}`)}}function removeCreatedProjectionDirectories(e){let t=e[0];while(t){try{const e=fs.lstatSync(t.path,{bigint:true});if(e.isDirectory()&&e.dev===t.dev&&e.ino===t.ino)fs.rmdirSync(t.path)}catch(e){const t=extractErrorCode(e);if(t!==`ENOENT`&&t!==`ENOTEMPTY`&&t!==`EEXIST`)throw e}e.shift();t=e[0]}}function resolveStateOwnerIdentity(e){const t=resolveIdentityPathViaExistingAncestorSync(e);return stateOwnerIdentity(t,resolveIdentityPathViaExistingAncestorSync(stateOwnerDirectory(t)))}async function resolveStateOwnerIdentityAsync(e){const t=await resolveIdentityPathViaExistingAncestor(e);return stateOwnerIdentity(t,await resolveIdentityPathViaExistingAncestor(stateOwnerDirectory(t)))}function stateOwnerIdentity(e,t){return{canonicalPath:e,ownerPath:path.join(t,`state.${sha256HexPrefixCore(e,16)}.lock`),key:process.platform===`win32`?normalizeWindowsPathForComparison(e):e}}function stateOwnerDirectory(e){const t=process.getuid?.();return process.platform===`win32`?path.join(os.homedir(),`AppData`,`Local`,`OpenClaw`,`locks`,t===void 0?`openclaw-state-owners`:`openclaw-state-owners-${t}`):resolveGatewayLockDirForCanonicalStateDir(resolveOpenClawStateDirForDatabasePath(e))}
//!src/infra/gateway-state-owner-heartbeat.runtime.ts
function isGatewayStateOwnerLockSnapshotCurrent(e,t,n,r){return t.isFile()&&e.nlink!==0n&&e.dev===t.dev&&e.ino===t.ino&&r===n}
//!src/infra/gateway-state-owner-heartbeat.ts
const now=Date.now.bind(Date);function captureLock(e){const t=fs.readFileSync(e.lockPath,`utf8`);if(!e.verifyStillHeld())throw new Error(`OpenClaw state ownership is no longer current`);return t}function startGatewayStateOwnerHeartbeat(e,t){const n={};for(const t of e)n[t.lockPath]=captureLock(t);const r=Object.keys(n)[0];if(!r)throw new Error(`Gateway state ownership requires a held lock`);const i=fs.statSync(r,{bigint:true});const{moduleUrl:a,runtimeGeneration:o}=captureRuntimeWorkerSource(resolveRuntimeProcessEntrypointUrl(`gatewayStateOwnerHeartbeat`));return runInDetachedAsyncContext(()=>{const s=new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));Atomics.store(s,0,BigInt(now()));const{port1:c,port2:l}=new MessageChannel;const u=createCpuTrackedWorker(a,{workerData:{clock:`epoch`,locks:n,intervalMs:GATEWAY_OWNER_HEARTBEAT_MS,failureMs:6e4,lastBeat:s.buffer,events:l},transferList:[l],execArgv:resolveRuntimeWorkerThreadExecArgv(a)});const d=createDeferredCore();u.on(`message`,e=>{if(e===`closed`)d.resolve()});u.unref();let f=0;const p=/* @__PURE__ */ new Map;const rejectPending=e=>{for(const t of p.values())t.reject(e);p.clear();c.unref()};c.on(`message`,e=>{recordWorkerMessage(`lifecycle`,`from_worker`);if(e===`parent-lost`)requestCliParentTermination();else if(e&&typeof e===`object`&&e.type===`lost`)t(/* @__PURE__ */ new Error(`${e.error}; restart the Gateway.`),e.lockPath);else if(e&&typeof e===`object`&&e.type===`verified`){const t=p.get(e.id);p.delete(e.id);if(p.size===0)c.unref();if(e.error)t?.reject(new Error(e.error));else t?.resolve(e.current)}});c.unref();u.on(`error`,e=>{const n=/* @__PURE__ */ new Error(`${coerceErrorMessage(e)}; restart Gateway.`);rejectPending(n);t(n)});u.once(`exit`,()=>{d.resolve();rejectPending(/* @__PURE__ */ new Error(`Gateway state ownership verification worker stopped`))});let m;const remainingUntilInspection=()=>{const e=Atomics.load(s,0);const t=now()-Number(e);return t<0?0:6e4-t};const inspect=()=>{const e=remainingUntilInspection();if(e<=0)throw new Error(`Gateway state ownership renewal is overdue at ${r}; retry after storage recovers.`);return e};const renewAsync=async()=>{const t=now();const a=new Date(t);for(const t of e)try{const o=n[t.lockPath];if(o===void 0)throw new Error(`owner acquisition bytes were not registered`);const s=await fs.promises.open(t.lockPath,`r+`);try{const n=await s.stat({bigint:true});const c=await fs.promises.lstat(t.lockPath,{bigint:true});const l=Buffer.alloc(Buffer.byteLength(o)+1);const{bytesRead:u}=await s.read(l,0,l.length,0);const d=await fs.promises.lstat(t.lockPath,{bigint:true});if(m||!e.has(t))continue;if(!isGatewayStateOwnerLockSnapshotCurrent(n,c,o,l.subarray(0,u).toString(`utf8`))||!d.isFile()||d.dev!==n.dev||d.ino!==n.ino||t.lockPath===r&&(n.dev!==i.dev||n.ino!==i.ino)){if(t.lockPath!==r)continue;throw new Error(`owner lock was removed or replaced`)}await s.utimes(a,a)}finally{await s.close()}}catch(e){if(t.lockPath!==r&&hasErrnoCode(e,`ENOENT`))continue;throw e}if(!m&&e.size>0)Atomics.store(s,0,BigInt(t))};let h;let g;const watch=()=>{const e=remainingUntilInspection();if(e>0){h=setTimeout(watch,e);h.unref()}else g??=renewAsync().then(()=>{g=void 0;if(!m)watch()},e=>{g=void 0;if(!m)t(/* @__PURE__ */ new Error(`Gateway state ownership is no longer current at ${r}: ${coerceErrorMessage(e)}; restart the Gateway.`))})};watch();const stop=()=>{if(!m){clearTimeout(h);rejectPending(/* @__PURE__ */ new Error(`Gateway state ownership is no longer current`));c.close();u.ref();u.postMessage(`stop`,[]);m=(async()=>{if(!await settlesWithin(d.promise,1e3))process.emitWarning(`Gateway state-owner heartbeat did not close within ${RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS}ms; forcing termination. Lock file descriptors may remain open until process exit.`,{code:`GATEWAY_STATE_HEARTBEAT_CLOSE_TIMEOUT`});return u.terminate()})()}return Promise.all([m,g]).then(()=>void 0)};o?.retain(u,async()=>async()=>{await stop()});const assertActive=()=>{if(m||u.threadId===-1)throw new Error(`Gateway state ownership verification worker stopped`)};const v=new Set(Object.keys(n));return{worker:u,paths:v,register(e){const t=captureLock(e);n[e.lockPath]=t;u.postMessage([e.lockPath,t],[]);v.add(e.lockPath)},inspect,assertActive,verify(e){assertActive();const t=++f;return new Promise((n,r)=>{p.set(t,{resolve:n,reject:r});c.ref();try{u.postMessage({type:`verify`,id:t,paths:e},[])}catch(e){p.delete(t);if(p.size===0)c.unref();r(toErrorObject(e,`Gateway state ownership verification failed`))}})},stop}})}
//!src/infra/gateway-state-owner-lifecycle.ts
function hasPhysicalOwnership(e){try{return verifyOwnerLock(e,e.locks.values().next().value)}catch(t){if(e.lost.signal.aborted)return false;throw t}}function verifyOwnerLock(e,t){e.lost.signal.throwIfAborted();e.heartbeat?.inspect();if(!t)return false;const n=e.getProjection?.();if(n&&e.heartbeat&&!e.heartbeat.paths.has(n.lockPath))e.heartbeat.register(n);const r=e.payload.role??`gateway`;if(e.kind===`process`&&e.accepting&&(r===`gateway`||r===`agent-embedded`)&&e.heartbeat){e.heartbeat.assertActive();return true}if(!t.verifyStillHeld()){loseOwner(e,/* @__PURE__ */ new Error(`${t.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`));return false}return true}const log=createSubsystemLogger(`gateway/state`);function loseOwner(e,t){if(e.lost.signal.aborted)return;e.accepting=false;readOwnerPaths.clear();e.heartbeat?.stop();log.error(t.message);e.lost.abort(t)}function observeOwnerLoss(e,t,n){const r=[...e.locks,e.getProjection?.()];if(!n||r.some(e=>e?.lockPath===n))loseOwner(e,t)}const readOwnerPaths=resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStateReadOwnerPaths`),()=>/* @__PURE__ */ new Map);const owners=resolveGlobalSingleton(Symbol.for(`openclaw.gatewayStateOwners`),()=>/* @__PURE__ */ new Map);const GATEWAY_RUN_VALUE_FLAGS=/* @__PURE__ */ new Set([`--port`,`--bind`,`--token`,`--token-file`,`--auth`,`--password`,`--password-file`,`--tailscale`,`--ws-log`,`--raw-stream-path`]);const GATEWAY_RUN_BOOLEAN_FLAGS=/* @__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){const t=getCommandPositionalsWithRootOptions(e,{commandPath:[`gateway`],booleanFlags:[...GATEWAY_RUN_BOOLEAN_FLAGS,`--task-supervisor`],valueFlags:[...GATEWAY_RUN_VALUE_FLAGS,`--task-supervisor-child`],mode:`command-path`});if(!t)return false;return t.length===0||t.length===1&&t[0]===`run`}const NODE_RELEASE_VERSION_RE=/^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;const NODE_RELEASE_FLOORS=[{major:24,minor:16,patch:0},{major:26,minor:1,patch:0}];const HIGHEST_RELEASE_FLOOR=NODE_RELEASE_FLOORS[NODE_RELEASE_FLOORS.length-1];const SUPPORTED_NODE_VERSION_RANGE=NODE_RELEASE_FLOORS.map(({major:e,minor:t,patch:n},r)=>`>=${e}.${t}.${n}${r<NODE_RELEASE_FLOORS.length-1?` <${e+1}`:``}`).join(` || `);const SUPPORTED_NODE_VERSIONS=`${SUPPORTED_NODE_VERSION_RANGE.replaceAll(` || `,`, `).replace(/, ([^,]+)$/,`, or $1`)} (Node 26 recommended)`;function parseNodeReleaseVersion(e){if(typeof e!==`string`)return null;const t=NODE_RELEASE_VERSION_RE.exec(e.trim());if(!t)return null;const n={major:Number(t[1]),minor:Number(t[2]),patch:Number(t[3])};return Object.values(n).every(Number.isSafeInteger)&&(!t[4]||n.major>HIGHEST_RELEASE_FLOOR.major)?n:null}function isNodeVersionAtLeast(e,t){if(!e)return false;if(e.major!==t.major)return e.major>t.major;if(e.minor!==t.minor)return e.minor>t.minor;return e.patch>=t.patch}function renderProcessNodeVersionCheck(){return`((value) => {
if (typeof value !== "string") return false;
const match = new RegExp(${JSON.stringify(NODE_RELEASE_VERSION_RE.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(NODE_RELEASE_FLOORS)};
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)`}const PROCESS_NODE_VERSION_CHECK=renderProcessNodeVersionCheck();
//!src/infra/sql-query-compiler.ts
const templateFragments=(e,t)=>e;const sqliteStringSetFragments=templateFragments`(SELECT value FROM json_each(${0}))`;const sqliteStringSetEntriesFragments=templateFragments`json_each(${0})`;function postgresStringArray(e){if(!RawNode.is(e)||e.sqlFragments!==sqliteStringSetFragments||e.parameters.length!==1)return;let t=e.parameters[0];while(RawNode.is(t)&&t.parameters.length===1&&t.sqlFragments.length===2&&t.sqlFragments.every(e=>e===``))t=t.parameters[0];if(!ValueNode.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;return`{${n.map(e=>`"${e.replace(/["\\]/g,`\\$&`)}"`).join(`,`)}}`}var OpenClawPostgresQueryCompiler=class extends PostgresQueryCompiler{visitBinaryOperation(e){if(OperatorNode.is(e.operator)&&e.operator.operator===`in`){const 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){const t=e.sqlFragments===sqliteStringSetFragments;if(!t&&e.sqlFragments!==sqliteStringSetEntriesFragments){super.visitRaw(e);return}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))`)}};var OpenClawPostgresDialect=class extends PostgresDialect{createQueryCompiler(){return new OpenClawPostgresQueryCompiler}};
//!src/infra/kysely-sync.ts
const nodeVersion=parseNodeReleaseVersion(process.versions.node);const supportsRepreparedAll=!process.versions.bun&&(nodeVersion?.major===24&&isNodeVersionAtLeast(nodeVersion,{major:24,minor:20,patch:0})||isNodeVersionAtLeast(nodeVersion,{major:26,minor:6,patch:0}));const compileOnlySqliteDialect=new SqliteDialect({database:async()=>{throw new Error(`getNodeSqliteKysely() returns a compile-only Kysely facade; use executeSqliteQuerySync() to execute node:sqlite queries.`)}});const postgresKyselyByDatabase=/* @__PURE__ */ new WeakMap;const compileOnlyPostgresDialect=new OpenClawPostgresDialect({pool:async()=>{throw new Error(`getNodeSqliteKysely() returns a compile-only Kysely facade.`)}});function getNodeSqliteKysely(e){if(isPostgresSqlConnection(e)){let t=postgresKyselyByDatabase.get(e);if(!t){t=new Kysely({dialect:compileOnlyPostgresDialect});postgresKyselyByDatabase.set(e,t)}return t}const t=kyselyByDatabase.get(e);if(t)return t;const n=new Kysely({dialect:compileOnlySqliteDialect});kyselyByDatabase.set(e,n);return n}function reportNodeSqliteKyselyQueryError(e,t){try{queryErrorHandlerByDatabase.get(e)?.(t)}catch{}}function releaseSqliteIterator(e,t,n,r){let i;try{e.return?.()}catch(e){i=e}t.release();if(!n&&i!==void 0)throw toErrorObject(i,r)}function executeCompiledSqliteQuerySync(e,t,n=false,r=t.parameters){if(isPostgresSqlConnection(e)){const i=e.query(t.sql,r);const a=n?i.rows.slice(0,1):i.rows;return i.columns.length>0?{rows:a}:{rows:[],numAffectedRows:BigInt(i.rowCount)}}try{const i=t.sql;installStatementInvalidation(e);return executeWithCachedStatement(e,i,r,i=>{if(n&&SelectQueryNode.is(t.query)){const e=i.get(...r);return{rows:e===void 0?[]:[e]}}if(SelectQueryNode.is(t.query)||i.columns().length>0){if(supportsRepreparedAll)return{rows:i.all(...r)};const t=i.iterate(...r);const n=retainSqliteReader(e,`kysely eager query`);let a=false;let o;const s=[];try{for(const e of t){n.progress();s.push(e)}}catch(e){a=true;o=e}releaseSqliteIterator(t,n,a,`SQLite query cleanup failed`);if(a)throw toErrorObject(o,`SQLite query failed`);return{rows:s}}i.setReadBigInts(true);let a;try{a=i.run(...r)}finally{i.setReadBigInts(false)}const{changes:o,lastInsertRowid:s}=a;const c={numAffectedRows:BigInt(o),rows:[]};if(InsertQueryNode.is(t.query)&&o>0)return{...c,insertId:BigInt(s)};return c})}catch(t){reportNodeSqliteKyselyQueryError(e,t);throw t}}function executeSqliteQuerySync(e,t){return executeCompiledSqliteQuerySync(e,t.compile())}function createSqliteQueryCache(e){const t=/* @__PURE__ */ new WeakMap;return n=>{let r=t.get(n);if(r===void 0){r=e(n);t.set(n,r)}return r}}function compileSqliteQueryBindings(e){const t=/* @__PURE__ */ new Map;const n=e(e=>{const n=Symbol(`sqlite-query-parameter`);t.set(n,e);return sql`${n}`}).compile();const r=n.parameters.map(e=>t.get(e)??(()=>e));return{compiled:n,bind:e=>r.map(t=>t(e))}}function prepareSqliteQuerySync(e,t){const{compiled:n,bind:r}=compileSqliteQueryBindings(t);return t=>executeCompiledSqliteQuerySync(e,n,false,r(t))}function iterateSqliteQuerySync(e,t){if(isPostgresSqlConnection(e))return(function*(){yield*executeCompiledSqliteQuerySync(e,t.compile()).rows})();const n=captureSqliteReaderOwner();return(function*(){const r=t.compile();let i;try{i=e.prepare(r.sql);if(!SelectQueryNode.is(r.query)&&i.columns().length===0)return;const t=r.parameters;const a=i.iterate(...t);const o=retainSqliteReader(e,`kysely iterator`,n);let s=false;try{for(const e of a){o.progress();yield e}}catch(e){s=true;throw toErrorObject(e,`SQLite iterator failed`)}finally{releaseSqliteIterator(a,o,s,`SQLite iterator cleanup failed`)}}catch(t){reportNodeSqliteKyselyQueryError(e,t);throw t}finally{if(i)disposeSqliteStatement(i)}})()}function executeSqliteQueryTakeFirstSync(e,t){return executeCompiledSqliteQuerySync(e,t.compile(),true).rows[0]}
//!src/infra/gateway-lock-recovery-namespace.ts
function classifyGatewayLockProcessNamespace(e,t,n){if(e&&n&&isLegacyGatewayLeaseLock(e)){const t=Date.now();const r=Date.parse(e.createdAt);if(!Number.isFinite(r)||t-r<=3e5)return`unknown`;try{const r=openNodeSqliteDatabase(resolveReadOnlyShmSqliteFileUri(n),{readOnly:true});try{const n=getNodeSqliteKysely(r);const{rows:i}=executeSqliteQuerySync(r,{compile:()=>sql`SELECT expires_at AS expiresAt
FROM ${sql`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()-fs.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})}
//!src/infra/gateway-state-owner-record.ts
const ownerInspections=new AsyncLocalStorage;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){const r=isRecord(e)?e:null;if(!r)return false;const i=classifyGatewayLockProcessNamespace(r,t,n);if(i===`unknown`)throw new GatewayLockNamespaceError(r,t);return comparableStateOwnerStaleReason(r,i)!==void 0}function assertPersistedStateDatabaseAccessAllowed(e){const{databasePath:t,ownerPath:n,assertMaintenance:r}=e;const i=`OpenClaw state ownership at ${t} could not be verified from ${n}; restart the Gateway.`;let a;try{a=fs.readFileSync(n,`utf8`)}catch(e){if(extractErrorCode(e)===`ENOENT`)return;throw new StateDatabaseAccessError(i,{cause:e})}const o=ownerInspections.getStore();if(o?.deadOwner?.path===n&&o.deadOwner.raw===a)return;const s=parseGatewayLockPayload(a);if(!s)throw new StateDatabaseAdmissionPendingError(t,i);if(!Number.isSafeInteger(s.pid)||s.pid<=0)throw new StateDatabaseAccessError(i);const c=classifyGatewayLockProcessNamespace(s,n,t);const l=comparableStateOwnerStaleReason(s,c);if(l){if(o&&l===`owner-process-exited`)o.deadOwner={path:n,raw:a};return}if(c===`same`&&s.pid===process.pid&&!isMainThread)return;if(c===`same`&&!isPidAlive(s.pid))throw new StateDatabaseAdmissionPendingError(t,i);const u=s.role??`gateway`;if(u===`gateway`||u===`agent-embedded`)return;if(c===`same`&&s.pid===process.pid){r();return}const d=`OpenClaw state at ${t} is undergoing offline maintenance by ${u} process ${s.pid}, started ${s.createdAt}; retry when it finishes. For update progress, run \`openclaw update status --json\`. ${describeGatewayLockHolder(s,n,c===`same`?`live`:`unknown`)}`;if(s.stateOwnerKind===`schema`&&s.role===`sqlite-maintenance`)throw new StateDatabaseAdmissionPendingError(t,d);throw new StateDatabaseOfflineMaintenanceError(t,d)}function defaultPayload(e){const t=resolveOpenClawStateDirForDatabasePath(e);const n=getFileLockProcessStartTime(process.pid);const r=getCliParentPid();const i=r===void 0?null:getFileLockProcessStartTime(r);return{pid:process.pid,ownerId:randomUUID(),createdAt:(/* @__PURE__ */ new Date()).toISOString(),stateDir:t,configPath:path.join(t,`openclaw.json`),role:`sqlite-maintenance`,processNamespace:readGatewayLockProcessNamespace(),machineIdentity:process.platform===`darwin`?readProcessMachineIdentity():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=fs.readFileSync(t,`utf8`)}catch(e){if(extractErrorCode(e)===`ENOENT`)return;throw e}const i=parseGatewayLockPayload(r);if(isGatewayStateOwnerDefinitelyStale(i)||i?.pid===n.pid)return;if(n.pid===process.pid&&isForegroundGatewayRunArgv(process.argv)&&classifyOpenClawArgv(process.argv,{command:`gateway`}).kind===`openclaw`)return;throw new StateDatabaseAdmissionPendingError(e,`Gateway restoration has priority for OpenClaw state at ${e}; retry when it finishes.`)}function acquireGatewayStateOwnerFile(e,t,n,r=0,i){const a=performance.now()+r;const o=`${resolveStateOwnerIdentity(e).ownerPath}.gateway-restoration`;assertGatewayRestorationPriority(e,o,n);ensureOwnerDirectory(path.dirname(t),i);const s={holder:null};const stale=({payload:n})=>{s.holder=LockPayloadSchema.safeParse(n).data??null;return isGatewayStateOwnerDefinitelyStale(s.holder,t,e)};if(r>0)try{const n=s.holder=parseGatewayLockPayload(fs.readFileSync(t,`utf8`));if(n&&!isGatewayStateOwnerDefinitelyStale(n,t,e)&&(n.pid===process.pid||(n.role??`gateway`)===`gateway`&&isPidAlive(n.pid)))throw new GatewayStateOwnerContentionError(e)}catch(e){if(extractErrorCode(e)!==`ENOENT`)throw e}for(let c=false;;)try{return acquireFileLockSync(t,{lockPath:t,retry:r>0?{factor:1.25,minTimeout:10,maxTimeout:25,randomize:false}:{retries:0},timeoutMs:Math.max(0,Math.ceil(a-performance.now())),staleMs:Infinity,staleRecovery:`remove-if-unchanged`,reentrantOwner:n.ownerId,payload:()=>{assertGatewayRestorationPriority(e,o,n);return n},shouldReclaim:stale,shouldRemoveStaleLock:stale})}catch(n){const r=extractErrorCode(n);if(r===`ENOENT`&&!c){c=true;ensureOwnerDirectory(path.dirname(t),i);continue}if(r===`file_lock_timeout`||r===`file_lock_stale`){const{holder:r}=s;const i=describeGatewayLockHolder(r??{},t,r&&isPidAlive(r.pid)?`live`:`unknown`);throw new GatewayStateOwnerContentionError(e,n,i,r?{pid:r.pid,role:r.role}:void 0)}throw n}}
//!src/infra/gateway-state-owner.ts
const schemaOwners=resolveGlobalSingleton(Symbol.for(`openclaw.stateDatabaseSchemaOwners`),()=>new AsyncLocalStorage);function getStateDatabaseSchemaLease(e){const t=schemaOwners.getStore()?.get(resolveStateOwnerIdentity(e).key);if(t&&!t.active)throw new Error(`State schema maintenance scope is no longer current`);t?.lease.assertCurrent();return t?.lease}function withStateDatabaseColdAdmission(e,t){const{remainingBusyTimeoutMs:n,retryDelay:r}=createColdAdmissionBudget(e);const i=new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));for(;;)try{assertStateDatabaseAccessAllowed(e.databasePath);return t(n)}catch(e){Atomics.wait(i,0,0,r(e))}}function resolveGatewayStateOwnerPath(e){return resolveStateOwnerIdentity(e).ownerPath}function leaseForFile(e,t,n,r){let i=false;const holdsPhysicalLease=()=>verifyOwnerLock(n,t)&&(!r||r.verifyStillHeld());function run(e){a.assertCurrent();readOwnerPaths.clear();const t=new Map(schemaOwners.getStore());const r={lease:a,active:true};t.set(n.key,r);const leave=()=>{r.active=false;readOwnerPaths.clear()};try{const n=schemaOwners.run(t,e);if(isPromiseLike(n))return Promise.resolve(n).finally(leave);leave();return n}catch(e){leave();throw e}}const a={path:e,assertCurrent(){if(i||!holdsPhysicalLease())throw new Error(`OpenClaw state ownership is no longer current`)},assertDatabaseAccess(e){if(i||owners.get(n.key)!==n||resolveStateOwnerIdentity(e).key!==n.key||!holdsPhysicalLease())throw new Error(`OpenClaw state maintenance does not own this database`)},run,release(){readOwnerPaths.clear();if(!i){r?.release();t.release();i=true;n.locks.delete(t);if(r)n.locks.delete(r);if(n.locks.size===0&&owners.get(n.key)===n){n.heartbeat?.stop();n.accepting=false;owners.delete(n.key);n.onReleased?.()}}if(n.locks.size===0)removeCreatedProjectionDirectories(n.projectionDirectories)}};return a}function acquireStateDatabaseSchemaLease(e,t={}){readOwnerPaths.clear();const n=resolveStateOwnerIdentity(e);let r=owners.get(n.key);const i=r?.path??n.ownerPath;if(r&&(!r.accepting||!hasPhysicalOwnership(r)))throw new GatewayStateOwnerContentionError(e,r.lost.signal.reason);if(r)assertStateDatabaseAccessAllowed(e);const a=r?.payload??{...defaultPayload(e),stateOwnerKind:`schema`};let o;const s=[];try{o=acquireGatewayStateOwnerFile(e,i,a,r?0:t.busyTimeoutMs??5e3,s)}catch(t){if(t instanceof GatewayStateOwnerContentionError)try{assertStateDatabaseAccessAllowed(e)}catch(e){if(e instanceof StateDatabaseAdmissionPendingError)throw e}throw t}const c=r?.projectionPath??path.join(resolveGatewayLockDir(resolveOpenClawStateDirForDatabasePath(resolveIdentityPathViaExistingAncestorSync(e))),`gateway.state.lock`);let l;try{l=r?.getProjection?.()?.retain()??acquireGatewayStateOwnerFile(e,c,{...a,role:a.role===`gateway`?`gateway`:`agent-embedded`},0,s)}catch(e){return runWithSqliteCleanup({release(){o.release();removeCreatedProjectionDirectories(s)}},`state schema projection admission`,()=>{throw e})}if(r){r.locks.add(o);r.locks.add(l);r.projectionDirectories.push(...s)}else{r={key:n.key,path:i,kind:`schema`,payload:a,projectionPath:c,locks:/* @__PURE__ */ new Set([o,l]),projectionDirectories:s,lost:new AbortController,accepting:true};owners.set(r.key,r)}const u=leaseForFile(i,o,r,l);try{const e=r.heartbeat??=startGatewayStateOwnerHeartbeat(r.locks,(e,t)=>observeOwnerLoss(r,e,t));u.assertCurrent();e.register(l);return u}catch(e){return runWithSqliteCleanup(u,`state schema ownership verification`,()=>{throw e})}}function prepareStateDatabaseReadAccess(e){return captureAdmittedGatewayStateOwner(e,false)}async function captureAdmittedGatewayStateOwner(e,t){e.assertCurrent();const n=e.identity.canonicalPath;const r=process.platform===`win32`?normalizeWindowsPathForComparison(n):n;const i=owners.get(r);if(!i||i.kind!==`process`)return;const a={canonicalPath:n,key:r,ownerPath:i.path};const assertRegistered=()=>{e.assertCurrent();i.lost.signal.throwIfAborted();if(owners.get(r)!==i)throw createGatewayStateProcessOwnerRetiredError()};const assertCurrent=()=>{assertRegistered();if(!i.accepting)throw createGatewayStateProcessOwnerRetiredError();assertStateDatabaseAccessAtOwnerPath(n,a,void 0)};const o=createStateDatabaseAccess(a,i);const assertReadAllowed=e=>{assertRegistered();o.assertReadAllowed(e)};const s=path.resolve(e.databasePath);const c=t?assertCurrent:assertRegistered;c();if(t||readOwnerPaths.get(s)!==i){const t=await resolveIdentityPathViaExistingAncestor(s);c();if((process.platform===`win32`?normalizeWindowsPathForComparison(t):t)!==r)throw new GatewayStateOwnerContentionError(e.databasePath)}if(!t){assertReadAllowed();if(readOwnerPaths.get(path.resolve(n))===i)readOwnerPaths.set(s,i)}return{ownerId:i.payload.ownerId,role:i.payload.role??`gateway`,signal:i.lost.signal,assertCurrent,assertReadAllowed,prepareAccess:o.prepareAccess}}function assertStateDatabaseReadAllowed(e,t){assertStateDatabaseReadAtOwnerPath(e,t)}function assertStateDatabaseReadAtOwnerPath(e,t,n){if(owners.size===0){assertStateDatabaseAccessAtOwnerPath(e,n??resolveStateOwnerIdentity(e),t);return}const r=path.resolve(e);if(readOwnerPaths.get(r)?.accepting)return;const i=n??resolveStateOwnerIdentity(e);const a=owners.get(i.key);const o=a?.payload.role??`gateway`;if(!a||a.kind!==`process`||!a.accepting||o!==`gateway`&&o!==`agent-embedded`){assertStateDatabaseAccessAtOwnerPath(e,i,t);return}if(!hasPhysicalOwnership(a)){a.lost.signal.throwIfAborted();throw new Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`)}readOwnerPaths.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){const{canonicalPath:n}=e;const r=owners.get(e.key);return{canonicalPath:n,processOwner:r?.kind===`process`?{role:r.payload.role??`gateway`,signal:r.lost.signal,assertCurrent(){r.lost.signal.throwIfAborted();if(!r.accepting||owners.get(e.key)!==r)throw createGatewayStateProcessOwnerRetiredError()}}:void 0,prepareAccess:async r=>{const i=t??owners.get(e.key);const a=i?.payload.role??`gateway`;if(!i||i.kind!==`process`||!i.accepting||a!==`gateway`&&a!==`agent-embedded`){assertStateDatabaseAccessAtOwnerPath(n,e,r);return(t=r)=>{if(i&&owners.get(e.key)!==i)throw createGatewayStateProcessOwnerRetiredError();assertStateDatabaseReadAtOwnerPath(n,t,e)}}const o=i.heartbeat;const s=i.locks.values().next().value;const c=i.getProjection?.();if(!o||!s)throw createGatewayStateProcessOwnerRetiredError();const assertCurrent=(t=r)=>{i.lost.signal.throwIfAborted();o.assertActive();if(owners.get(e.key)!==i||i.heartbeat!==o)throw createGatewayStateProcessOwnerRetiredError();if(!i.accepting){assertStateDatabaseAccessAtOwnerPath(n,e,t);return}if(!i.locks.has(s)||i.getProjection?.()!==c)throw createGatewayStateProcessOwnerRetiredError()};assertCurrent();const l=[s.lockPath];if(c)l.push(c.lockPath);const u=await o.verify(l).catch(e=>{i.lost.signal.throwIfAborted();throw e});assertCurrent();if(!u){const e=/* @__PURE__ */ new Error(`${s.lockPath}: no longer current; lock removed/replaced; restart the Gateway.`);loseOwner(i,e);throw e}readOwnerPaths.set(path.resolve(n),i);return assertCurrent},assertReadAllowed(t){assertStateDatabaseReadAtOwnerPath(n,t,e)}}}function assertStateDatabaseAccessAtOwnerPath(e,t,n){const assertMaintenance=()=>{const t=n?n.schemaLease:getStateDatabaseSchemaLease(e);if(t){t.assertDatabaseAccess(e);return}const r=n?n.maintenanceScope:getOpenClawDatabaseMaintenanceScope();if(!r)throw new StateDatabaseMaintenanceScopeError(e);r.assertDatabaseAccess(e)};const r=owners.get(t.key);if(r){if(!hasPhysicalOwnership(r)){r.lost.signal.throwIfAborted();throw new Error(`OpenClaw state ownership at ${e} was lost: owner lock was removed or replaced; restart the Gateway.`)}const t=r.payload.role??`gateway`;if(!r.accepting||t!==`gateway`&&t!==`agent-embedded`)assertMaintenance();return}assertPersistedStateDatabaseAccessAllowed({databasePath:e,ownerPath:t.ownerPath,assertMaintenance})}
//!src/infra/gc-observer.ts
const kinds={Scavenge:`scavenge`,MinorMarkSweep:`scavenge`,MarkSweepCompact:`mark_sweep_compact`,IncrementalMarking:`incremental`,ProcessWeakCallbacks:`weak_processing`};const subscribers=/* @__PURE__ */ new Set;let profiler;let timer;let oldGenerationAfterGcBytes;function drain(e){const t=profiler?.stop();if(e)profiler?.start();const n=[];for(const e of t?.statistics??[]){const t=kinds[e.gcType];if(!t)continue;const r=e.beforeGC.heapStatistics.usedHeapSize;const 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;oldGenerationAfterGcBytes=0;for(const t of e.afterGC.heapSpaceStatistics)if(t.spaceName===`old_space`||t.spaceName===`large_object_space`)oldGenerationAfterGcBytes+=t.spaceUsedSize}n.push(i)}if(n.length)for(const e of subscribers)e(n)}function observeGcSamples(e){if(process.versions.bun)return;if(profiler)drain(true);else{profiler=new GCProfiler;profiler.start();timer=setInterval(()=>drain(true),1e3).unref()}subscribers.add(e);return()=>{if(!subscribers.has(e))return;const t=subscribers.size===1;drain(!t);subscribers.delete(e);if(t){clearInterval(timer);timer=void 0;profiler=void 0;oldGenerationAfterGcBytes=void 0}}}
//!src/infra/database-engine/observation.ts
const channels={statement:channel(`openclaw.database.statement`),request:channel(`openclaw.database.request`)};const observedConnections=/* @__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=false){const t=statementTiming;let n;let r;if(e)try{r=observeGcSamples(e=>{for(const t of e)n=(n??0)+t.durationMs});n=r?0:void 0}catch{}const i=/* @__PURE__ */ new Map;let a=0;let o=0;let s=0;let c;statementTiming=(e,t,n)=>{a++;o+=t;if(c===void 0||t>s)c=e;const r=i.has(e)||i.size<32?e:``;const l=i.get(r)??{count:0,totalMs:0,maxMs:0};i.set(r,l);s=Math.max(s,t);if(n!==void 0)l.rows=(l.rows??0)+n;l.count++;l.totalMs+=t;l.maxMs=Math.max(l.maxMs,t)};return()=>{statementTiming=t;try{r?.()}catch{n=void 0}return{totalMs:o,callbackGcMs:n,summarize(){const identity=e=>{const t=normalizeSql(`sqlite`,e);return{id:e?createHash(`sha256`).update(t).digest(`hex`).slice(0,16):`other`,operation:/^(SELECT|INSERT|UPDATE|DELETE|WITH|SAVEPOINT|RELEASE|ROLLBACK)\b/i.exec(t)?.[1]?.toUpperCase()??`OTHER`}};return{count:a,maxMs:s,slowest:c===void 0?void 0:{...identity(c),maxMs:s},statements:[...i].toSorted((e,t)=>t[1].totalMs-e[1].totalMs).slice(0,5).map(([e,t])=>Object.assign(identity(e),t,{totalMs:Math.round(t.totalMs*100)/100,maxMs:Math.round(t.maxMs*100)/100})),omittedGroups:Math.max(0,i.size-5)}}}}}function normalizeSql(e,t){let n=``;for(let r=0;r<t.length;){const i=t.slice(r);if(i.startsWith(`/*`)){let e=1;r+=2;while(r<t.length&&e)if(t.startsWith(`/*`,r)){e++;r+=2}else if(t.startsWith(`*/`,r)){e--;r+=2}else r++;n+=` `;continue}const a=/^--[^\r\n]*/.exec(i)?.[0];const o=(e===`postgres`?/^[eE]'(?:\\[\s\S]|''|[^'\\])*(?:'|$)/.exec(i)?.[0]:void 0)??/^(?:[uU]&)?'(?:''|[^'])*(?:'|$)/.exec(i)?.[0];const s=/^\$(?:[A-Za-z_][\w]*)?\$/.exec(i)?.[0];const c=/^(?:"(?:""|[^"])*"|`(?:``|[^`])*`|\[[^\]]*\])/.exec(i)?.[0];const l=!/[\w$]/.test(t[r-1]??``)?/^(?:0x[\da-f]+|\d+(?:\.\d*)?(?:e[+-]?\d+)?)(?!\w)/i.exec(i)?.[0]:void 0;if(s){const e=t.indexOf(s,r+s.length);r=e<0?t.length:e+s.length;n+=`?`}else if(a||o||c||l){const e=a??o??c??l??``;r+=e.length;n+=a?` `:c?e:`?`}else n+=t[r++]}return n.replace(/\s+/g,` `).trim()}function observeDatabaseOperation(e,t,n,r,i){const a=channels[t];const o=e===`sqlite`&&t===`statement`?statementTiming:void 0;if(!a.hasSubscribers&&!o)return r();const s=performance.now();let c=`error`;let l;try{const e=r();c=`ok`;l=i===`all`&&Array.isArray(e)?e.length:i===`get`?Number(e!==void 0):void 0;return e}finally{const t=performance.now()-s;if(n!==void 0)o?.(n,t,l);if(a.hasSubscribers)a.publish({engine:e,sql:n===void 0?void 0:normalizeSql(e,n),threadId,outcome:c,durationMs:t})}}function observeConnection(e){if(observedConnections.has(e))return e;observedConnections.add(e);const t=e.exec.bind(e);const n=e.prepare.bind(e);e.exec=e=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>t(e));e.prepare=e=>{const t=n(e);for(const n of[`get`,`all`,`run`]){const r=t[n].bind(t);Object.defineProperty(t,n,{configurable:true,writable:true,value:(...t)=>observeDatabaseOperation(`sqlite`,`statement`,e,()=>r(...t),n===`run`?void 0:n)})}const r=t.iterate.bind(t);t.iterate=(...t)=>{const n=r(...t);const i=statementTiming;if(!channels.statement.hasSubscribers&&!i)return n;let a=0;let o=0;let s=false;let c=false;const finish=t=>{if(c)return;c=true;if(s){i?.(e,a,o);if(channels.statement.hasSubscribers)channels.statement.publish({engine:`sqlite`,sql:normalizeSql(`sqlite`,e),threadId,outcome:t,durationMs:a})}};const step=e=>{if(c)return e();const t=performance.now();try{const n=e();a+=performance.now()-t;if(n.done)finish(`ok`);else o++;return n}catch(e){a+=performance.now()-t;finish(`error`);throw e}};const l={next:(...e)=>{s=true;return step(()=>n.next(...e))},return:e=>step(()=>n.return?.(e)??{done:true,value:e}),[Symbol.iterator](){return this}};Object.setPrototypeOf(l,Object.getPrototypeOf(n));return l};return t};return e}
//!src/infra/sqlite-transaction.ts
const DEFAULT_SLOW_BUSY_WAIT_MS=1e3;const DEFAULT_SLOW_TRANSACTION_HOLD_MS=1e3;const abortedTransactionSymbol=Symbol.for(`openclaw.sqliteAbortedTransaction`);function assertTransactionUsable(e){if(isPostgresSqlConnection(e))return;const t=e[abortedTransactionSymbol];if(t)throw t.error}const transactionLog=createSubsystemLogger(`sqlite/transaction`);const writeAdmissionServices=resolveGlobalSingleton(Symbol.for(`openclaw.sqliteWriteAdmissionServices`),()=>/* @__PURE__ */ new Map);const writeAdmissionLocations=/* @__PURE__ */ new WeakMap;function writeAdmissionLocation(e){const t=writeAdmissionLocations.get(e);if(t!==void 0)return t;const n=e.location();const r=n===null?null:normalizeDatabasePath(n);writeAdmissionLocations.set(e,r);return r}function retainSqliteWriteAdmissionService(e,t){const n=[...new Set(e.map(normalizeDatabasePath))].map(e=>{const n=writeAdmissionServices.get(e)??/* @__PURE__ */ new Set;const retained=()=>t();n.add(retained);writeAdmissionServices.set(e,n);return{location:e,services:n,retained}});return()=>{for(const{location:e,services:t,retained:r}of n){t.delete(r);if(t.size===0&&writeAdmissionServices.get(e)===t)writeAdmissionServices.delete(e)}}}function execNativeBegin(e,t){const n=Date.now();t.nativeAttempts+=1;try{e.exec(`BEGIN IMMEDIATE`)}finally{t.nativeMs+=Date.now()-n}}function beginImmediateTransaction(e,t){const n=writeAdmissionServices.size>0?writeAdmissionLocation(e):null;const r=n===null?void 0:writeAdmissionServices.get(n);if(!r){execNativeBegin(e,t);return}const i=performance.now()+readSqliteBusyTimeout(e);while(true)try{runWithSqliteBusyTimeout(e,Math.min(25,Math.max(0,Math.ceil(i-performance.now()))),()=>execNativeBegin(e,t));return}catch(e){if(!isSqliteLockError(e)||performance.now()>=i)throw e;for(const e of r){const n=Date.now();t.serviceCalls+=1;try{e()}finally{t.serviceMs+=Date.now()-n}}if(performance.now()>=i)throw e}}function slowBusyWaitThresholdMs(e){if(e?.busyTimeoutMs===void 0||e.busyTimeoutMs<=0)return DEFAULT_SLOW_BUSY_WAIT_MS;return Math.min(DEFAULT_SLOW_BUSY_WAIT_MS,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||captureSqliteReaderOwner()?.operation||`unlabeled`,...t?.diagnosticContext?{context:{...t.diagnosticContext}}:{}}}function logTransactionStep(e,t){try{if(!t&&e.elapsedMs<slowBusyWaitThresholdMs(e.options))return;const n=t?sqliteExtendedResultCode(t.error):void 0;const r=t?sqlitePrimaryResultCode(t.error):void 0;(e.options?.logger??transactionLog).warn(t?`SQLite transaction lock wait failed`:`slow SQLite transaction step`,{async:false,...e.options?.busyTimeoutMs!==void 0?{busyTimeoutMs:e.options.busyTimeoutMs}:{},...transactionDiagnosticLabels(e.db,e.options),...t?{code:sqliteErrorCode(t.error)}:{},elapsedMs:e.elapsedMs,...e.holderAtWaitStart?{holderAtWaitStart:e.holderAtWaitStart}:{},...t?{failureKind:`lock-contention`}:{},isMainThread,pid:process.pid,...n!==void 0?{sqliteErrcode:n}:{},...r!==void 0?{sqlitePrimaryCode:r}:{},step:e.step,threadId,...e.beginAdmission?{beginAdmission:{...e.beginAdmission}}:{}})}catch{}}function execTimedTransactionStep(e){const t=Date.now();const n=e.sql===`BEGIN IMMEDIATE`?{nativeAttempts:0,nativeMs:0,serviceCalls:0,serviceMs:0}:void 0;const r=n?readSqliteTransactionWriter(e.db,t):void 0;try{if(n)beginImmediateTransaction(e.db,n);else e.db.exec(e.sql);const i=Date.now()-t;logTransactionStep({beginAdmission:n,db:e.db,elapsedMs:i,holderAtWaitStart:r,options:e.options,step:e.step});return i}catch(i){const a=Date.now()-t;if(isSqliteLockError(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});throw i}}function discardUnsafeConnection(e,t){const n={error:t};e[abortedTransactionSymbol]??=n;try{discardSqliteTransactionState(e,t)}catch(t){if(e[abortedTransactionSymbol]===n)n.error=t;throw t}finally{clearNodeSqliteKyselyCacheForDatabase(e);try{e.close()}catch{}}}function abortImmediateTransaction(e,t,n){if(e[abortedTransactionSymbol])return;if(!n&&e.isOpen&&!e.isTransaction){discardSqliteTransactionState(e,t,`rolled-back`);return}try{e.exec(`ROLLBACK`)}catch{discardUnsafeConnection(e,t)}}function runSqliteTransactionSync(e,t,n,r){if(e.isTransaction){e.exec(`SAVEPOINT openclaw_tx_nested`);try{const n=runSqliteReadOperationSync(e,t);assertSyncTransactionResult(n);assertTransactionUsable(e);e.exec(`RELEASE SAVEPOINT openclaw_tx_nested`);return n}catch(t){const n=e[abortedTransactionSymbol];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}}const i=currentSqliteOperationTiming();const a=i?Date.now()-i.preparedAtMs:void 0;const o=execTimedTransactionStep({db:e,options:r,sql:n===`immediate`?`BEGIN IMMEDIATE`:`BEGIN`,step:`begin`});if(i)i.transactions.count+=1;return settleSqliteTransactionSync(e,t,n,o,a,r)}function settleSqliteTransactionSync(e,t,n,r,i,a,o=false){const s=currentSqliteOperationTiming();const c=Date.now();const l=n===`immediate`?sqliteTransactionWriterSlot(e):void 0;if(l)recordSqliteTransactionWriter(l,a?.operationLabel||captureSqliteReaderOwner()?.operation||`unlabeled`,c);const u=s?.hostAdmissionWaitMs??0;const d=s?.databaseAdmissionWaitMs??0;let f=0;const commit=()=>{const t=Date.now();const n=s?.databaseAdmissionWaitMs??0;try{prepareSqliteTransactionCommit(e);execTimedTransactionStep({db:e,options:a,sql:`COMMIT`,step:`commit`})}finally{f+=Date.now()-t-((s?.databaseAdmissionWaitMs??0)-n)}};let p=false;const m=a?.operationLabel||captureSqliteReaderOwner()?.operation;const h=m?.startsWith(`sessions.transcript-hydration.`)===true;let g;try{const n=m&&attributesSqliteStatements(m)?startSqliteStatementTiming(h):void 0;let r;try{r=o?t():runSqliteReadOperationSync(e,t)}finally{g=n?.()}assertSyncTransactionResult(r);assertTransactionUsable(e);p=true;if(a?.withCommit)assertSyncTransactionResult(a.withCommit(commit));else commit();return r}catch(t){abortImmediateTransaction(e,t,p);assertTransactionUsable(e);throw t}finally{if(l)Atomics.compareExchange(l,1,threadId+1,0);try{if(s?.diskRead)s.diskRead.context=a?.diagnosticContext;const t=Date.now()-c;const o=(s?.hostAdmissionWaitMs??0)-u;const l=(s?.databaseAdmissionWaitMs??0)-d;const p=Math.max(0,t-o-l-f);if(!(t<(a?.slowTransactionHoldMs??DEFAULT_SLOW_TRANSACTION_HOLD_MS)))(a?.logger??transactionLog).warn(`slow SQLite transaction hold`,{async:false,callbackKind:`application-transaction`,isMainThread,mode:n,pid:process.pid,threadId,...transactionDiagnosticLabels(e,a),...s?.holdContext||h&&s?.hydrationActiveEvents!==void 0?{context:readSqliteOperationHoldContext(a?.diagnosticContext,h)}:{},elapsedMs:t,phases:{prepareMs:i,beginMs:r,sqlMs:p,...g?{statementExecutionMs:Math.round(g.totalMs*100)/100,callbackOtherMs:Math.round(Math.max(0,p-g.totalMs)*100)/100,callbackGcMs:g.callbackGcMs===void 0?void 0:Math.round(g.callbackGcMs*100)/100}:{},hostAdmissionWaitMs:o,databaseAdmissionWaitMs:l,commitMs:f},...g?{statementTiming:g.summarize()}:{},thresholdMs:a?.slowTransactionHoldMs??DEFAULT_SLOW_TRANSACTION_HOLD_MS})}catch{}finally{if(s){s.preparedAtMs=Date.now();if(s.hydrationActiveEvents!==void 0)s.hydrationActiveEvents=void 0}}}}function runSqliteDeferredTransactionSync(e,t,n){if(isPostgresSqlConnection(e))return e.runTransaction(t,n);assertTransactionUsable(e);return withSqlitePostCommitPublications(e,()=>runSqliteTransactionSync(e,t,`deferred`,n))}function runSqliteReadSnapshotSync(e,t,n){if(isPostgresSqlConnection(e)){if(e.isTransaction){const e=t();assertSyncTransactionResult(e);return e}return e.runTransaction(t,n,true)}assertTransactionUsable(e);if(!e.isTransaction)return runSqliteDeferredTransactionSync(e,t,n);const r=runSqliteReadOperationSync(e,t);assertSyncTransactionResult(r);assertTransactionUsable(e);return r}function runSqliteImmediateTransactionSync(e,t,n){if(isPostgresSqlConnection(e))return e.runTransaction(t,n);assertTransactionUsable(e);return withSqlitePostCommitPublications(e,()=>runSqliteTransactionSync(e,t,`immediate`,n))}function runSqliteSingleStatementSync(e,t){if(isPostgresSqlConnection(e))return e.runTransaction(t);assertTransactionUsable(e);return withSqlitePostCommitPublications(e,()=>{const n=writeAdmissionServices.size>0?writeAdmissionLocation(e):null;if(e.isTransaction||n!==null&&writeAdmissionServices.has(n))return runSqliteTransactionSync(e,t,`immediate`);const r=runSqliteReadOperationSync(e,t);assertSyncTransactionResult(r);return r})}
//!src/infra/database-engine/admission-scope.ts
const processRole=resolveGlobalSingleton(Symbol.for(`openclaw.databaseProcessRole`),()=>({}));function getDatabaseProcessRole(){return processRole.role}let admissionDepth=0;function withEngineStoreAdmission(e){admissionDepth+=1;try{const t=e();if(isPromiseLike(t))throw new Error(`Database engine admission must remain synchronous`);return t}finally{admissionDepth-=1}}function assertEngineStoreExecutionAllowed(){if(threadId===0&&admissionDepth===0&&processRole.role!==`cli-oneshot`)throw new Error(`PostgreSQL connections must run in a worker; only synchronous admission, migrations, and CLI one-shots may run on the main thread`)}
//!src/infra/sqlite-handle-lifecycle.ts
const SQLITE_IDLE_HANDLE_TTL_MS=18e5;const SQLITE_CLI_AGENT_IDLE_HANDLE_TTL_MS=3e4;function resolveAgentDatabaseIdleHandleTtlMs(){return getDatabaseProcessRole()===`cli-oneshot`?SQLITE_CLI_AGENT_IDLE_HANDLE_TTL_MS:SQLITE_IDLE_HANDLE_TTL_MS}
//!src/infra/sqlite-schema-issues.ts
var SqliteSchemaMismatchError=class extends Error{constructor(...e){super(...e);this.name=`SqliteSchemaMismatchError`}};function isSqliteSchemaMismatchError(e){return e instanceof Error&&e.name===`SqliteSchemaMismatchError`}const ISSUE_DESCRIPTIONS={"missing-table":`missing table`,"missing-column":`column definitions differ for`,"unexpected-column":`column definitions differ for`,"column-definition-drift":`column definitions differ for`,"table-constraint-drift":`table constraints differ for`,"table-definition-drift":`table definition differs for`,"missing-or-drifted-index":`missing or drifted index`,"unexpected-unique-index":`unexpected unique index`,"missing-or-drifted-trigger":`missing or drifted trigger`,"missing-or-drifted-view":`missing or drifted view`,"unexpected-trigger":`unexpected trigger`,"virtual-table-definition-drift":`virtual table definition differs for`,"table-options-drift":`table options differ for`};function isColumnIssue(e){return e===`column-definition-drift`||e===`missing-column`||e===`unexpected-column`}function defaultIssueMessage(e,t){const n=isColumnIssue(e)?t.split(`.`,1)[0]:t;return`${ISSUE_DESCRIPTIONS[e]} ${n}`}function createSqliteSchemaIssue(e,t,n){return{code:e,objectName:t,message:n??defaultIssueMessage(e,t)}}function legacySqliteSchemaIssueMessages(e){const t=new Set(e.filter(e=>isColumnIssue(e.code)).map(e=>e.objectName.split(`.`,1)[0]));return[...new Set(e.filter(e=>e.code!==`table-constraint-drift`||!t.has(e.objectName)).map(e=>e.message))]}function throwSqliteSchemaMismatches(e,t){const n=t.slice(0,8);if(t.length>n.length)n.push(`${t.length-n.length} additional mismatch(es)`);throw new SqliteSchemaMismatchError(`SQLite schema is incomplete or noncanonical for ${e}: ${n.join(`; `)}; run openclaw doctor --fix to repair it.`)}export{record as $,executeSqliteQueryTakeFirstSync as A,classifyGatewayOwnerProcessNamespace as B,getStateDatabaseSchemaLease as C,classifyGatewayLockProcessNamespace as D,withStateDatabaseColdAdmission as E,readOwnerPaths as F,boolean as G,createManagedHandoffBootIdentityReader as H,applyPrivateModeSync as I,literal as J,custom as K,GatewayLockNamespaceError as L,iterateSqliteQuerySync as M,prepareSqliteQuerySync as N,createSqliteQueryCache as O,parseNodeReleaseVersion as P,object as Q,GatewayProcessNamespaceSchema as R,captureStateDatabaseAccess as S,resolveGatewayStateOwnerPath as T,_enum as U,parseGatewayLockPayload as V,array as W,never as X,looseObject as Y,number as Z,observeConnection as _,throwSqliteSchemaMismatches as a,isSqliteReadOnlyError as at,assertStateDatabaseAccessAllowed as b,assertEngineStoreExecutionAllowed as c,readSourceJournalMode as ct,assertTransactionUsable as d,createSqliteSnapshotStagingDirectory as dt,string as et,retainSqliteWriteAdmissionService as f,createSqliteSnapshotStagingDirectorySync as ft,runSqliteSingleStatementSync as g,resolvePrivateSqliteSnapshotStagingRoot as gt,runSqliteReadSnapshotSync as h,createPrivateSqliteTempDirectorySync as ht,legacySqliteSchemaIssueMessages as i,SqliteSourceChangedError as it,getNodeSqliteKysely as j,executeSqliteQuerySync as k,getDatabaseProcessRole as l,readSourceSidecars as lt,runSqliteImmediateTransactionSync as m,sqliteSchemaContractFromCatalog as mt,createSqliteSchemaIssue as n,unknown as nt,SQLITE_IDLE_HANDLE_TTL_MS as o,prepareSqliteReadOnlyCopyInProcess as ot,runSqliteDeferredTransactionSync as p,createSqliteTableContractReader as pt,discriminatedUnion as q,isSqliteSchemaMismatchError as r,sha256Hex as rt,resolveAgentDatabaseIdleHandleTtlMs as s,prepareSqliteReadOnlyLocationFromOwnedDatabase as st,SqliteSchemaMismatchError as t,union as tt,withEngineStoreAdmission as u,acquireSqliteSnapshotReadToken as ut,observeDatabaseOperation as v,prepareStateDatabaseReadAccess as w,assertStateDatabaseReadAllowed as x,acquireStateDatabaseSchemaLease as y,MachineIdentitySchema as z};